@testim/testim-cli 4.151.0 → 4.152.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 +46 -46
- package/cli.js.map +4 -4
- package/meta.json +1 -1
- package/npm-shrinkwrap.json +297 -305
- package/package.json +3 -3
package/cli.js
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
1
|
#! /usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
${c.msg}`));for(let u of ew)a[u]instanceof Error&&(c[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(c).length>0&&(o&&!m&&(c.msg=o),d.text=JSON.stringify(c)),this.logger.addLog(d),r(null,!0)}setProxy(t){this.logger.setProxy(t)}async waitForFlush(){return await this.logger.waitForFlush()}}});function sw(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!$e){let{CoralogixTransport:r}=(Fd(),He(Md)),n=new r({category:"ROOT"});s.push(n),e=()=>n.waitForFlush(),t=i=>n.setProxy(i)}if(wd){let r={depth:5,colors:!0};s.push(new mt.transports.Console({format:mt.format.combine(mt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),mt.format.timestamp({format:"HH:mm:ss:SSS"}),mt.format.printf(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${wi.inspect(n.meta,r)}`))}))}return[s,e,t]}function Gd(s){fc=s}function Hd(s){Vd=s}function qd(s){$e||!s||ow(s)}function Bd(s){return{projectId:Vd,time:new Date().toISOString(),...fc&&!s&&{executionId:fc}}}function P(s){return new gc(lw.child({category:s}))}var jd,mt,wi,Ti,$d,tw,rw,Ud,Wd,nw,iw,ow,aw,cw,lw,fc,Vd,gc,W=v(()=>{"use strict";jd=I(require("node:os")),mt=I(require("winston"));de();wi=I(require("node:util")),Ti=I(require("chalk")),$d=I(require("dayjs"));U();tw=jd.hostname(),rw=tt();Ud={depth:5,colors:!0},Wd=(s,e,t)=>{let r=`[${(0,$d.default)().format("HH:mm:ss:SSS")}]`,n=wi.inspect(e,Ud),i=wi.inspect(t,Ud);return`${Ti.default.white(r)} ${Ti.default.reset()}SessionPlayer-${Ti.default.red(s)} ${n} ${i}`},[nw,iw,ow]=sw(),aw=vd?"debug":"info",cw={release:Boolean(!1),branch:"runner-v4.151.0"},lw=mt.createLogger({levels:mt.config.syslog.levels,level:aw,transports:nw,defaultMeta:{name:"runner",hostname:tw,nodeVersion:process.version,runnerVersion:rw,...cw}}),fc=null,Vd=null;gc=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,...Bd(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...Bd(n)})}catch{}}}waitForFlush(){return iw()}}});var Ii,$r,C,qt,pr,It,vi,Wr,oe,Bs,rt,zt,Rt,Si,Vr,Ei,js,Y=v(()=>{"use strict";Ii=require("p-retry"),$r=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},C=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},qt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},pr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},It=class extends Ii.AbortError{},vi=class extends Ii.AbortError{},Wr=class extends Ii.AbortError{},oe=class extends Error{},Bs=class extends Error{},rt=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},zt=class extends rt{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Rt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},Si=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Vr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Ei=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},js=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 ce(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 le(s,e,t="Timeout Error"){gi&&!zd&&(zd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new oe(t);return e=gi?Number(gi)||6e5:e,Promise.race([s,ce(e).then(()=>{throw r})])}async function se(s,e,{concurrency:t}={}){if(t){Kd||=(await import("p-limit")).default;let r=Kd(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function Kt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var Jd,zd,Kd,bc=v(()=>{"use strict";Jd=require("timers/promises");Y();de();zd=!1});var Ws,Yd,pw,$s,Xd,dw,mw,Qd,Zd=v(()=>{"use strict";Ws=I(require("lodash"));de();Yd=require("dns");W();bc();pw=P("http-request-counters"),$s=!1,Xd=async()=>{if($e)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await se(s,t=>Yd.promises.lookup(t)));return e||($s=!0),e}catch{return pw.error("network connectivity test failed"),$s=!0,!1}},dw=Ws.throttle(Xd,10*1e3),mw=60*1e3*15,Qd=()=>{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)},mw)}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),$s||dw(),a}}}async function r(){if($s||!await Xd())return!1;let n=Ws.sum([...s.fail.values()]),i=Ws.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>$s,t}});var ze={};H(ze,{deleteReq:()=>Vs,didNetworkConnectivityTestFail:()=>Rc,download:()=>Ec,get:()=>Te,getFullRes:()=>bw,getText:()=>Hs,head:()=>Tw,isNetworkHealthy:()=>Ic,post:()=>We,postForm:()=>Gs,postText:()=>vc,put:()=>Sc});function gw(){return global.caFileContent}function hw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function yw(){return!ft.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(ft.default),global.proxyUri}function dr(s,e=!1){let t=gw();t&&s.ca(t);let r=!e&&yw();r&&s.proxy(r)}async function em(s,e,t={},r=Gr,n=0){let i=ft.default.post(s).send(e).timeout(r).set(t);dr(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function wc(s,e,t={},r=Gr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=ft.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),dr(o,i),await o}var ft,Tc,st,Gr,fw,Dt,Vs,We,Gs,Hs,vc,Te,bw,Tw,Sc,Ec,Ic,Rc,Ve=v(()=>{"use strict";ft=I(require("superagent"));W();Zd();Tc=P("http-request"),st=Qd(),Gr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,fw=6e4;Dt=(s,e,t)=>{let r=e.response;e.response instanceof ft.default.Response&&typeof r.toError=="function"&&(e=e.response.toError(),e.requestHeaders=r==null?void 0:r.header,e.responseHeaders=r==null?void 0:r.headers);let n=new Error("").stack;throw Tc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};Vs=st(async(s,e={},t={},r=Gr)=>{try{let n=ft.default.delete(s).send(e).timeout(r).set(t);dr(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Dt("failed to delete request",n,{url:s})}}),We=st(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await em(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})}});Gs=st(async(s,e,t,r={},n=Gr)=>{let i=ft.default.post(s).type("form").timeout(n).set(r);i.field(e),Object.entries(t).forEach(([o,a])=>{i.attach(o,a.buffer,a.fileName)}),dr(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Dt("failed to post request",o,{url:s})}});Hs=st(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=st(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await em(s,e,t,r,n)).text}catch(i){return Dt("failed to post request",i,{url:s})}}),Te=st(async(s,e,t,r,n)=>{try{return(await wc(s,e,t,r,n)).body}catch(i){return Dt("failed to get request",i,{url:s,query:e})}}),bw=st((s,e,t,r)=>wc(s,e,t,r)),Tw=st(async s=>{let e=ft.default.head(s).timeout(Gr);dr(e);try{return await e}catch(t){return Dt("failed to head request",t,{url:s})}}),Sc=st(async(s,e,t={},r=Gr)=>{let n=ft.default.put(s).send(e).timeout(r).set(t);dr(n);try{return(await n).body}catch(i){return Dt("failed to put request",i,{url:s})}}),Ec=st(async s=>{Tc.info("start to download",{url:s});let e=ft.default.get(s).set("User-Agent","Testim.io").timeout(fw).buffer(!0).parse(hw);dr(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=st.isNetworkHealthy,Rc=st.didNetworkConnectivityTestFail});function gt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Nt.resolve(__dirname,"../../"):s=Nt.resolve(__dirname,""),s):process.cwd()}function Ri(s,e){return Oe(s)?e||Nt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Nt.basename(s)}function tt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function Cc(){try{return gd.node}catch{return""}}async function sm(s,e,t=!0){let r=await nt.promises.readdir(s,{withFileTypes:!0});await nt.promises.mkdir(e,{recursive:t});for(let n of r){let i=Nt.join(s,n.name),o=Nt.join(e,n.name);n.isDirectory()?await sm(i,o):await nt.promises.copyFile(i,o)}}async function ye(s){try{return await nt.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Nt,tm,rm,nt,ww,Mt,Ke,xi,xc,it,Ac,nm=v(()=>{"use strict";Nt=I(require("node:path"));nc();fi();tm=I(require("unzip-stream")),rm=I(require("p-retry")),nt=require("node:fs"),ww=3;Mt=async s=>{let e=await Promise.resolve().then(()=>(Ve(),ze));return(0,rm.default)(()=>e.download(s),{retries:ww,factor:1})},Ke=async(s,e)=>{let t=await Mt(s);return nt.promises.writeFile(e,t.body)};xi=async(s,e)=>{let t=Ri(s,e);return Oe(s)?Ke(s,t):nt.promises.copyFile(s,t)},xc=async s=>Oe(s)?Mt(s):nt.promises.readFile(s),it=async(s,e)=>(0,nt.createReadStream)(s).pipe(tm.Extract({path:e})),Ac=s=>(0,nt.statSync)(s).size/1e6});var Ft={};H(Ft,{APPIUM_SESSION_MESSAGE:()=>Lc,CLI_MODE:()=>q,MOBILE_APP_SOURCE:()=>Ai,MOBILE_RUN_SKIP_REASON:()=>_c,X_HEADER_RUNNER_ID:()=>Dc,gridMessages:()=>ht,gridTypes:()=>L,mobileWeb:()=>kc,runnerStatus:()=>Pc,runnerTestStatus:()=>me,socketEventTypes:()=>xt,stepResult:()=>zs,test:()=>Oc,testRunStatus:()=>qs,testStatus:()=>Je,timeoutMessages:()=>Me});var Me,qs,Pc,me,Je,ht,kc,Oc,xt,q,L,zs,Ai,_c,Lc,Dc,ie=v(()=>{"use strict";Me={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},qs={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"},Je={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},ht={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},kc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Oc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},xt={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},q={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},L={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},zs={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"},Ai={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},_c={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"},Dc="X-Testim-Runner-ID"});function Ks(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 vw(){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 Js,im,Ye,Sw,Ew,Iw,Rw,xw,Nc,Mc,om=v(()=>{"use strict";ie();Js=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},im=s=>Boolean(s.resultId&&s.source==="remote-run"),Ye=(s,e)=>s.testStatus===Je.QUARANTINE&&!im(e)&&!e.runQuarantinedTests;Sw=s=>Boolean(s.loginMode),Ew=s=>Boolean(s.tunnelOnlyMode),Iw=s=>Boolean(s.createPrefechedData),Rw=s=>Boolean(s.installLazyDepsMode),xw=s=>Boolean(s.agentMode),Nc=(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 Pi(s=0){return Ci.default.duration(s).format("HH:mm:ss.SSS")}function Fc(s=0){return Ci.default.duration(s).asSeconds()}var Ci,am,cm=v(()=>{"use strict";Ci=I(require("dayjs")),am=I(require("dayjs/plugin/duration"));Ci.default.extend(am.default)});var Ys,Hr,Jt,lm,qr,um=v(()=>{"use strict";ie();Ys=s=>!(!s||"fileName"in s),Hr=(s,e)=>{if(e===L.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},Jt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},lm=s=>s===L.TESTIM_TVC,qr=(s,e)=>lm(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 pm=v(()=>{"use strict"});var J={};H(J,{OSS:()=>zr,TESTIM_BROWSER_DIR:()=>Ut,buildBasicHeader:()=>sc,calcPercentile:()=>_i,copyDir:()=>sm,delay:()=>ce,doesPathExist:()=>ye,download:()=>Mt,downloadAndSave:()=>Ke,extractElementId:()=>Le,getArgsOnRemoteRunFailure:()=>vw,getBrowserInfo:()=>Cw,getCdpAddressForHost:()=>gr,getCliLocation:()=>gt,getDuration:()=>Pi,getDurationSec:()=>Fc,getEnginesVersion:()=>Cc,getEnvironmentGitBranch:()=>fr,getLinksFromUnescapeHTML:()=>Zs,getLocalFileSizeInMB:()=>Ac,getMemorySnapshot:()=>Uc,getPlanType:()=>Oi,getRunConfigByBrowserName:()=>Xs,getRunnerVersion:()=>tt,getSource:()=>xi,getSourceAsBuffer:()=>xc,getSourcePath:()=>Ri,getTestUrl:()=>qe,getUniqBrowsers:()=>Ks,groupTestsByRetries:()=>jc,guid:()=>re,hasTestPlanFlag:()=>Js,isAgentMode:()=>xw,isAppFromDevice:()=>Ys,isAppFromDeviceDisabled:()=>qr,isCreatePrefetchedDataMode:()=>Iw,isInstallLazyDepsMode:()=>Rw,isLoginMode:()=>Sw,isMobileProject:()=>Jt,isPromise:()=>hc,isQuarantineAndNotRemoteRun:()=>Ye,isRemoteRun:()=>im,isTestimVirtualGrid:()=>lm,isTunnelOnlyMode:()=>Ew,isURL:()=>Oe,promiseAbort:()=>yc,promiseFromCallback:()=>Kt,promiseMap:()=>se,promiseTimeout:()=>le,removePropertyFromObject:()=>ki,replaceArgsWithNoDashes:()=>Nc,sanitizeNumberValue:()=>mr,shouldBlockVirtualIosBuild:()=>Hr,spreadObjectToArgs:()=>Mc,unescapeHTML:()=>Qs,unzipFile:()=>it});function mr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function Cw(s){return s=s.toLowerCase(),Bc.find(e=>e.browserValue===s)}function Xs(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Bc.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||Bc[0],n=zr.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=zr.find(i=>i.sl.platform===e.platform):e.platformName&&(n=zr.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=zr.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=zr.find(i=>i.bs.platform===t.platform))),Kr.merge(r,n)}function fr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function ki(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&ki(s[r],e,t))}function Le(s){return s.ELEMENT||s[Gt]}function Oi(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function jc(s=[]){return Kr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,l=typeof o.retryCount=="number"?o.retryCount:1;return a===l?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=Kr.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function Qs(s){return gm.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function Zs(s){return[...gm.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function gr(s,e){let t=await Promise.resolve().then(()=>(Ve(),ze));try{return(await t.get(`http://${s}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var dm,Kr,mm,fm,Aw,Ut,zr,Bc,_i,gm,U=v(()=>{"use strict";dm=I(require("os")),Kr=I(require("lodash")),mm=I(require("path")),fm=require("linkedom");jr();nm();om();cm();nc();bc();um();pm();Aw=dm.homedir(),Ut=mm.join(Aw,".testim-browser-profile"),zr=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17"},sl:{},lt:{platform:"macOS Sonoma",safari_version:"17"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura",safari_version:"16"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey",safari_version:"15"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{platform:"macOS 10.15",safari_version:"latest"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{platform:"macOS 10.14",safari_version:"latest"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{platform:"macOS 10.13",safari_version:"latest"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{platform:"macOS 10.12",safari_version:"latest"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"latest"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"latest"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"latest"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"latest"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],Bc=[{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"}];_i=(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]};gm=new fm.DOMParser});var $c={};H($c,{$schema:()=>Pw,default:()=>Dw,definitions:()=>kw,properties:()=>Lw,required:()=>_w,type:()=>Ow});var Pw,kw,Ow,_w,Lw,Dw,hm=v(()=>{Pw="http://json-schema.org/draft-07/schema#",kw={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}}}},Ow="object",_w=["entries"],Lw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},Dw={$schema:Pw,definitions:kw,type:Ow,required:_w,properties:Lw}});async function Em(){try{return await le(Li.promises.readFile(Fi()).then(async s=>{let e=await Sm;return Fw(e,s)}),3e4)}catch{return{}}}function Fw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=Yr.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),o=i.update(r);return JSON.parse(Buffer.concat([o,i.final()]))}function Bt(s,e,t=Nw,r=void 0){return async()=>{if(!Tm)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await Uw(e);if(i)return en.debug("cache hit:",{fnName:e}),i;if(en.debug("cache miss:",{fnName:e}),!wm)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 Bw(e,o,t),o}}async function Uw(s){let t=(await Ui)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function Bw(s,e,t){if(Wc)throw en.error("calling set after waitForSave is not allowed",{key:s,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let r=await Ui;r[s]={value:e,expiry:Date.now()+t},vm=new Promise(n=>{Mi=n}),Mw(r)}catch{en.error("failed updating cache")}}async function Xr(){let s=await Ui;Object.keys(s).forEach(e=>{delete s[e]})}function Im(s){Tm=s}function jw(s=!0){wm=s}async function Rm(){try{return Wc=!0,await vm}finally{Wc=!1}}function xm(s){Ni=s,Ui=Em()}var Li,Di,Yr,ym,en,Ni,bm,Mi,Tm,wm,Wc,vm,Sm,Nw,Fi,Ui,Mw,Am,Cm,gx,Pm,Yt=v(()=>{"use strict";Li=I(require("fs")),Di=I(require("path")),Yr=I(require("crypto"));U();ym=require("lodash");W();en=P("local cache"),Ni=Di.resolve(gt(),"testim-cache"),Tm=!0,wm=!0,Wc=!1,vm=new Promise(s=>{Mi=s}),Sm=new Promise(s=>{bm=s}),Nw=1e3*60*60*3,Fi=()=>Di.resolve(Di.resolve(Ni,"testim.cache"));Ui=Em(),Mw=(0,ym.debounce)(async s=>{let e;try{let t=await Sm,r=Yr.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=Yr.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await ye(Ni)||await Li.promises.mkdir(Ni,{recursive:!0}),await Li.promises.writeFile(Fi(),a)}catch(t){en.error("failed saving cache",{err:t}),e=t}Mi(e?{success:!1,error:e}:{success:!0})},200);Am=bm,Cm=Im.bind(void 0,!1),gx=Im.bind(void 0,!0),Pm=()=>jw(!1)});function Bi(){return{cliLocation:gt(),userInfo:Qr.userInfo(),platform:Qr.platform(),release:Qr.release()}}var Qr,Vc=v(()=>{"use strict";Qr=I(require("node:os"));U()});function $w(s){try{return ji.resolve(ji.dirname(require.resolve(`${s}/package.json`)),require(`${s}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(s);throw e}}function Xt(s){let e=$w(s);return require(e)}var ji,tn=v(()=>{"use strict";ji=I(require("path"))});function Ww(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Vw(s){return/The "to" argument must be of type string./.exec(s)}function Lm(s,e,t){let r=Ww(s),n=Vw(s);return r||n?(_m.info("Failed to install package due to insufficient write access",{...Bi(),package:t,path:r}),console.error(`
|
|
2
|
+
"use strict";var VT=Object.create;var oi=Object.defineProperty;var GT=Object.getOwnPropertyDescriptor;var HT=Object.getOwnPropertyNames;var qT=Object.getPrototypeOf,zT=Object.prototype.hasOwnProperty;var v=(s,e)=>()=>(s&&(e=s(s=0)),e);var H=(s,e)=>{for(var t in e)oi(s,t,{get:e[t],enumerable:!0})},md=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of HT(e))!zT.call(s,n)&&n!==t&&oi(s,n,{get:()=>e[n],enumerable:!(r=GT(e,n))||r.enumerable});return s};var I=(s,e,t)=>(t=s!=null?VT(qT(s)):{},md(e||!s||!s.__esModule?oi(t,"default",{value:s,enumerable:!0}):t,s)),He=s=>md(oi({},"__esModule",{value:!0}),s);var Be={};H(Be,{log:()=>M,measure:()=>JT});function M(...s){if(!gd)return;let e=Date.now();console.log(`${e-KT} ${e-fd} `,...s),fd=e}function JT(s,e){if(!gd)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var gd,KT,fd,je=v(()=>{"use strict";gd=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,KT=Date.now(),fd=Date.now()});var Gt,jr=v(()=>{"use strict";Gt="element-6066-11e4-a52e-4f735466cecf"});function re(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function qe(s,e,t,r,n){let i="";return n=n?encodeURIComponent(n):"master",e&&t&&(i=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(i+=`?result-id=${r}`)),i}function ic(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function Oe(s){let e=/^(https?:\/\/)/i,t=new RegExp("^(?:(?:(?:https?|ftp):)?\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u00a1-\\uffff][a-z0-9\\u00a1-\\uffff_-]{0,62})?[a-z0-9\\u00a1-\\uffff]\\.)+(?:[a-z\\u00a1-\\uffff]{2,}\\.?))(?::\\d{2,5})?(?:[/?#]\\S*)?$","i");return e.test(s)||t.test(s)}var oc=v(()=>{"use strict"});var cc,hd,yd,fi=v(()=>{cc={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:"2.0.1"},hd={"@applitools/eyes-sdk-core":"13.11.34-legacy.1","@applitools/spec-driver-webdriverio":"1.4.29","@segment/analytics-node":"2.1.3","@types/unzip-stream":"0.3.4",ajv:"6.12.6","body-parser":"1.20.3",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",eventsource:"3.0.6",express:"4.21.1",fkill:"7.2.1","form-data":"3.0.0","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"1.1.4",jsonwebtoken:"9.0.0",linkedom:"0.18.0",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2","node-fetch":"2.7.0",npm:"10.5.0","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"6.3.1","rox-node":"5.4.12",semver:"7.6.0","serialize-error":"7.0.1","socket.io-client":"4.8.0","source-map-support":"0.5.19",superagent:"9.0.1","superagent-proxy":"3.0.0","test-exclude":"7.0.0","ua-parser-js":"0.7.39","unzip-stream":"0.3.4",uuid:"11.0.5","validate-npm-package-name":"3.0.0",webdriverio:"8.44.1",winston:"3.11.0","winston-transport":"4.6.0",ws:"8.17.1",xml2js:"0.6.2",yaml:"2.2.2"},yd={node:">= 18.0.0"}});var Ds,QT,bd,Ht,ZT,Ns,Td,wd,gi,Ms,vd,he,Sd,Ed,hi,$e,lc,Id,yi,Rd,xd,BR,jR,Ad,Cd,Us,Pd,kd,Od,_d,uc,pc,dc,mc,Ld,Fs,Dd,fc,de=v(()=>{"use strict";Ds=process.env.SERVICES_HOST||"https://services.testim.io",QT="https://testimstatic.blob.core.windows.net",bd="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:Ds,Ds=process.env.SERVICES_HOST);Ht=process.env.RUNNER_ENVIRONMENT||"production",ZT={production:"",staging:".staging",development:".dev"},Ns=process.env.EXTENSION_SP_S3_HOST||`https://playback-components${ZT[Ht]}.testim.io`,Td=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),wd=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),gi=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),Ms=process.env.EDITOR_URL,vd=process.env.WEBSOCKET_HOST||`${Ds}/ws`,he=Ds,Sd=parseInt(process.env.LOGGER_CONSOLE||"0",10),Ed=parseInt(process.env.LOGGER_DEBUG||"0",10),hi=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),$e=parseInt(process.env.IS_ON_PREM||"0",10),lc=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,Id=parseInt(process.env.DEBUG_MODE||"0",10),yi=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,Rd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",xd=process.env.CORALOGIX_PRIVATE_KEY||"d0eb01da-f966-1663-63c6-8871225d7c39",BR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),jR=process.env.APPIUM_VERSION||"1.10.1",Ad=process.env.GATEWAY_URL,Cd=process.env.EXTENSION_SERVICES_HOST||Ds,Us=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:QT,Pd=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:bd,kd=bd,Od=5*60*1e3,_d=40,uc=process.env.HEADSPIN_MOBILE_API_BASE_URL||"https://api-dev.headspin.io",pc=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",dc=process.env.HEADSPIN_TDC_DEVICES_API_PATH||"v0",mc=process.env.HEADSPIN_TDC_APPS_API_PATH||"v1",Ld=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Fs=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Dd=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||60,fc=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung"});var Nd,bi,Md=v(()=>{"use strict";Nd=I(require("superagent"));de();bi=class{constructor(e){this.logs=[];this.url=process.env.CORALOGIX_URL||"https://ingress.coralogix.com/logs/v1/bulk",this.token=xd,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=Nd.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 Fd={};H(Fd,{CoralogixTransport:()=>gc});var Ud,ew,tw,gc,Bd=v(()=>{"use strict";Ud=I(require("winston-transport"));Md();ew={debug:1,silly:2,verbose:2,silent:2,info:3,http:3,warn:4,warning:4,error:5,critical:6,crit:6},tw=["err","error","reason","e"],gc=class extends Ud.default{constructor(t){super(t);this.name="Coralogix Transport",this.category=t.category,this.logger=new bi({applicationName:"testim",subsystemName:"runner"})}log(t,r){let{category:n,level:i,message:o,meta:a={},...l}=t,c={...a,...l},d={severity:ew[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 tw)a[u]instanceof Error&&(c[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(c).length>0&&(o&&!m&&(c.msg=o),d.text=JSON.stringify(c)),this.logger.addLog(d),r(null,!0)}setProxy(t){this.logger.setProxy(t)}async waitForFlush(){return await this.logger.waitForFlush()}}});function nw(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!$e){let{CoralogixTransport:r}=(Bd(),He(Fd)),n=new r({category:"ROOT"});s.push(n),e=()=>n.waitForFlush(),t=i=>n.setProxy(i)}if(Sd){let r={depth:5,colors:!0};s.push(new mt.transports.Console({format:mt.format.combine(mt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),mt.format.timestamp({format:"HH:mm:ss:SSS"}),mt.format.printf(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${wi.inspect(n.meta,r)}`))}))}return[s,e,t]}function qd(s){hc=s}function zd(s){Hd=s}function Kd(s){$e||!s||aw(s)}function $d(s){return{projectId:Hd,time:new Date().toISOString(),...hc&&!s&&{executionId:hc}}}function P(s){return new yc(uw.child({category:s}))}var Wd,mt,wi,Ti,Vd,rw,sw,jd,Gd,iw,ow,aw,cw,lw,uw,hc,Hd,yc,W=v(()=>{"use strict";Wd=I(require("node:os")),mt=I(require("winston"));de();wi=I(require("node:util")),Ti=I(require("chalk")),Vd=I(require("dayjs"));F();rw=Wd.hostname(),sw=tt();jd={depth:5,colors:!0},Gd=(s,e,t)=>{let r=`[${(0,Vd.default)().format("HH:mm:ss:SSS")}]`,n=wi.inspect(e,jd),i=wi.inspect(t,jd);return`${Ti.default.white(r)} ${Ti.default.reset()}SessionPlayer-${Ti.default.red(s)} ${n} ${i}`},[iw,ow,aw]=nw(),cw=Ed?"debug":"info",lw={release:Boolean(!1),branch:"runner-v4.152.0"},uw=mt.createLogger({levels:mt.config.syslog.levels,level:cw,transports:iw,defaultMeta:{name:"runner",hostname:rw,nodeVersion:process.version,runnerVersion:sw,...lw}}),hc=null,Hd=null;yc=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,...$d(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...$d(n)})}catch{}}}waitForFlush(){return ow()}}});var Ii,$r,C,qt,pr,It,vi,Wr,oe,Bs,rt,zt,Rt,Si,Vr,Ei,js,Y=v(()=>{"use strict";Ii=require("p-retry"),$r=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},C=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},qt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},pr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},It=class extends Ii.AbortError{},vi=class extends Ii.AbortError{},Wr=class extends Ii.AbortError{},oe=class extends Error{},Bs=class extends Error{},rt=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},zt=class extends rt{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Rt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},Si=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Vr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Ei=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},js=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function bc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ce(s){return(0,Xd.setTimeout)(s)}function Tc(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function le(s,e,t="Timeout Error"){gi&&!Jd&&(Jd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new oe(t);return e=gi?Number(gi)||6e5:e,Promise.race([s,ce(e).then(()=>{throw r})])}async function se(s,e,{concurrency:t}={}){if(t){Yd||=(await import("p-limit")).default;let r=Yd(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function Kt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var Xd,Jd,Yd,wc=v(()=>{"use strict";Xd=require("timers/promises");Y();de();Jd=!1});var Ws,Qd,dw,$s,Zd,mw,fw,em,tm=v(()=>{"use strict";Ws=I(require("lodash"));de();Qd=require("dns");W();wc();dw=P("http-request-counters"),$s=!1,Zd=async()=>{if($e)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await se(s,t=>Qd.promises.lookup(t)));return e||($s=!0),e}catch{return dw.error("network connectivity test failed"),$s=!0,!1}},mw=Ws.throttle(Zd,10*1e3),fw=60*1e3*15,em=()=>{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)},fw)}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),$s||mw(),a}}}async function r(){if($s||!await Zd())return!1;let n=Ws.sum([...s.fail.values()]),i=Ws.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>$s,t}});var ze={};H(ze,{deleteReq:()=>Vs,didNetworkConnectivityTestFail:()=>Ac,download:()=>Rc,get:()=>Te,getFullRes:()=>Tw,getText:()=>Hs,head:()=>ww,isNetworkHealthy:()=>xc,post:()=>We,postForm:()=>Gs,postText:()=>Ec,put:()=>Ic});function hw(){return global.caFileContent}function yw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function bw(){return!ft.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(ft.default),global.proxyUri}function dr(s,e=!1){let t=hw();t&&s.ca(t);let r=!e&&bw();r&&s.proxy(r)}async function rm(s,e,t={},r=Gr,n=0){let i=ft.default.post(s).send(e).timeout(r).set(t);dr(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function Sc(s,e,t={},r=Gr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=ft.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),dr(o,i),await o}var ft,vc,st,Gr,gw,Dt,Vs,We,Gs,Hs,Ec,Te,Tw,ww,Ic,Rc,xc,Ac,Ve=v(()=>{"use strict";ft=I(require("superagent"));W();tm();vc=P("http-request"),st=em(),Gr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,gw=6e4;Dt=(s,e,t)=>{let r=e.response;e.response instanceof ft.default.Response&&typeof r.toError=="function"&&(e=e.response.toError(),e.requestHeaders=r==null?void 0:r.header,e.responseHeaders=r==null?void 0:r.headers);let n=new Error("").stack;throw vc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};Vs=st(async(s,e={},t={},r=Gr)=>{try{let n=ft.default.delete(s).send(e).timeout(r).set(t);dr(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Dt("failed to delete request",n,{url:s})}}),We=st(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await rm(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})}});Gs=st(async(s,e,t,r={},n=Gr)=>{let i=ft.default.post(s).type("form").timeout(n).set(r);i.field(e),Object.entries(t).forEach(([o,a])=>{i.attach(o,a.buffer,a.fileName)}),dr(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Dt("failed to post request",o,{url:s})}});Hs=st(async(s,e,t)=>{try{return(await Sc(s,e,t)).text}catch(r){return Dt("failed to getText request",r,{url:s,query:e})}}),Ec=st(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await rm(s,e,t,r,n)).text}catch(i){return Dt("failed to post request",i,{url:s})}}),Te=st(async(s,e,t,r,n)=>{try{return(await Sc(s,e,t,r,n)).body}catch(i){return Dt("failed to get request",i,{url:s,query:e})}}),Tw=st((s,e,t,r)=>Sc(s,e,t,r)),ww=st(async s=>{let e=ft.default.head(s).timeout(Gr);dr(e);try{return await e}catch(t){return Dt("failed to head request",t,{url:s})}}),Ic=st(async(s,e,t={},r=Gr)=>{let n=ft.default.put(s).send(e).timeout(r).set(t);dr(n);try{return(await n).body}catch(i){return Dt("failed to put request",i,{url:s})}}),Rc=st(async s=>{vc.info("start to download",{url:s});let e=ft.default.get(s).set("User-Agent","Testim.io").timeout(gw).buffer(!0).parse(yw);dr(e);try{let t=await e;return vc.info("finished to download",{url:s}),t}catch(t){return Dt("failed to download",t,{url:s})}}),xc=st.isNetworkHealthy,Ac=st.didNetworkConnectivityTestFail});function gt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Nt.resolve(__dirname,"../../"):s=Nt.resolve(__dirname,""),s):process.cwd()}function Ri(s,e){return Oe(s)?e||Nt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Nt.basename(s)}function tt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function kc(){try{return yd.node}catch{return""}}async function im(s,e,t=!0){let r=await nt.promises.readdir(s,{withFileTypes:!0});await nt.promises.mkdir(e,{recursive:t});for(let n of r){let i=Nt.join(s,n.name),o=Nt.join(e,n.name);n.isDirectory()?await im(i,o):await nt.promises.copyFile(i,o)}}async function ye(s){try{return await nt.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Nt,sm,nm,nt,vw,Mt,Ke,xi,Cc,it,Pc,om=v(()=>{"use strict";Nt=I(require("node:path"));oc();fi();sm=I(require("unzip-stream")),nm=I(require("p-retry")),nt=require("node:fs"),vw=3;Mt=async s=>{let e=await Promise.resolve().then(()=>(Ve(),ze));return(0,nm.default)(()=>e.download(s),{retries:vw,factor:1})},Ke=async(s,e)=>{let t=await Mt(s);return nt.promises.writeFile(e,t.body)};xi=async(s,e)=>{let t=Ri(s,e);return Oe(s)?Ke(s,t):nt.promises.copyFile(s,t)},Cc=async s=>Oe(s)?Mt(s):nt.promises.readFile(s),it=async(s,e)=>(0,nt.createReadStream)(s).pipe(sm.Extract({path:e})),Pc=s=>(0,nt.statSync)(s).size/1e6});var Ut={};H(Ut,{APPIUM_SESSION_MESSAGE:()=>Nc,CLI_MODE:()=>q,MOBILE_APP_SOURCE:()=>Ai,MOBILE_RUN_SKIP_REASON:()=>Dc,X_HEADER_RUNNER_ID:()=>Mc,gridMessages:()=>ht,gridTypes:()=>L,mobileWeb:()=>_c,runnerStatus:()=>Oc,runnerTestStatus:()=>me,socketEventTypes:()=>xt,stepResult:()=>zs,test:()=>Lc,testRunStatus:()=>qs,testStatus:()=>Je,timeoutMessages:()=>Me});var Me,qs,Oc,me,Je,ht,_c,Lc,xt,q,L,zs,Ai,Dc,Nc,Mc,ie=v(()=>{"use strict";Me={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},qs={COMPLETED:"completed"},Oc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},me={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Je={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},ht={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},_c={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Lc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},xt={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},q={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},L={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},zs={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"},Ai={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},Dc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Nc={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"},Mc="X-Testim-Runner-ID"});function Ks(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 Sw(){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 Js,am,Ye,Ew,Iw,Rw,xw,Aw,Uc,Fc,cm=v(()=>{"use strict";ie();Js=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},am=s=>Boolean(s.resultId&&s.source==="remote-run"),Ye=(s,e)=>s.testStatus===Je.QUARANTINE&&!am(e)&&!e.runQuarantinedTests;Ew=s=>Boolean(s.loginMode),Iw=s=>Boolean(s.tunnelOnlyMode),Rw=s=>Boolean(s.createPrefechedData),xw=s=>Boolean(s.installLazyDepsMode),Aw=s=>Boolean(s.agentMode),Uc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Fc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Pi(s=0){return Ci.default.duration(s).format("HH:mm:ss.SSS")}function Bc(s=0){return Ci.default.duration(s).asSeconds()}var Ci,lm,um=v(()=>{"use strict";Ci=I(require("dayjs")),lm=I(require("dayjs/plugin/duration"));Ci.default.extend(lm.default)});var Ys,Hr,Jt,pm,qr,dm=v(()=>{"use strict";ie();Ys=s=>!(!s||"fileName"in s),Hr=(s,e)=>{if(e===L.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},Jt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},pm=s=>s===L.TESTIM_TVC,qr=(s,e)=>pm(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function jc(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 mm=v(()=>{"use strict"});var J={};H(J,{OSS:()=>zr,TESTIM_BROWSER_DIR:()=>Ft,buildBasicHeader:()=>ic,calcPercentile:()=>_i,copyDir:()=>im,delay:()=>ce,doesPathExist:()=>ye,download:()=>Mt,downloadAndSave:()=>Ke,extractElementId:()=>Le,getArgsOnRemoteRunFailure:()=>Sw,getBrowserInfo:()=>Pw,getCdpAddressForHost:()=>gr,getCliLocation:()=>gt,getDuration:()=>Pi,getDurationSec:()=>Bc,getEnginesVersion:()=>kc,getEnvironmentGitBranch:()=>fr,getLinksFromUnescapeHTML:()=>Zs,getLocalFileSizeInMB:()=>Pc,getMemorySnapshot:()=>jc,getPlanType:()=>Oi,getRunConfigByBrowserName:()=>Xs,getRunnerVersion:()=>tt,getSource:()=>xi,getSourceAsBuffer:()=>Cc,getSourcePath:()=>Ri,getTestUrl:()=>qe,getUniqBrowsers:()=>Ks,groupTestsByRetries:()=>Wc,guid:()=>re,hasTestPlanFlag:()=>Js,isAgentMode:()=>Aw,isAppFromDevice:()=>Ys,isAppFromDeviceDisabled:()=>qr,isCreatePrefetchedDataMode:()=>Rw,isInstallLazyDepsMode:()=>xw,isLoginMode:()=>Ew,isMobileProject:()=>Jt,isPromise:()=>bc,isQuarantineAndNotRemoteRun:()=>Ye,isRemoteRun:()=>am,isTestimVirtualGrid:()=>pm,isTunnelOnlyMode:()=>Iw,isURL:()=>Oe,promiseAbort:()=>Tc,promiseFromCallback:()=>Kt,promiseMap:()=>se,promiseTimeout:()=>le,removePropertyFromObject:()=>ki,replaceArgsWithNoDashes:()=>Uc,sanitizeNumberValue:()=>mr,shouldBlockVirtualIosBuild:()=>Hr,spreadObjectToArgs:()=>Fc,unescapeHTML:()=>Qs,unzipFile:()=>it});function mr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function Pw(s){return s=s.toLowerCase(),$c.find(e=>e.browserValue===s)}function Xs(s,e,t){s=s==null?void 0:s.toLowerCase();let r=$c.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||$c[0],n=zr.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=zr.find(i=>i.sl.platform===e.platform):e.platformName&&(n=zr.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=zr.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=zr.find(i=>i.bs.platform===t.platform))),Kr.merge(r,n)}function fr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function ki(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&ki(s[r],e,t))}function Le(s){return s.ELEMENT||s[Gt]}function Oi(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Wc(s=[]){return Kr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,l=typeof o.retryCount=="number"?o.retryCount:1;return a===l?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=Kr.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function Qs(s){return ym.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function Zs(s){return[...ym.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function gr(s,e){let t=await Promise.resolve().then(()=>(Ve(),ze));try{return(await t.get(`http://${s}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var fm,Kr,gm,hm,Cw,Ft,zr,$c,_i,ym,F=v(()=>{"use strict";fm=I(require("os")),Kr=I(require("lodash")),gm=I(require("path")),hm=require("linkedom");jr();om();cm();um();oc();wc();dm();mm();Cw=fm.homedir(),Ft=gm.join(Cw,".testim-browser-profile"),zr=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17"},sl:{},lt:{platform:"macOS Sonoma",safari_version:"17"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura",safari_version:"16"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey",safari_version:"15"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{platform:"macOS 10.15",safari_version:"latest"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{platform:"macOS 10.14",safari_version:"latest"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{platform:"macOS 10.13",safari_version:"latest"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{platform:"macOS 10.12",safari_version:"latest"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"latest"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"latest"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"latest"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"latest"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],$c=[{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"}];_i=(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]};ym=new hm.DOMParser});var Vc={};H(Vc,{$schema:()=>kw,default:()=>Nw,definitions:()=>Ow,properties:()=>Dw,required:()=>Lw,type:()=>_w});var kw,Ow,_w,Lw,Dw,Nw,bm=v(()=>{kw="http://json-schema.org/draft-07/schema#",Ow={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}}}},_w="object",Lw=["entries"],Dw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},Nw={$schema:kw,definitions:Ow,type:_w,required:Lw,properties:Dw}});async function Rm(){try{return await le(Li.promises.readFile(Ui()).then(async s=>{let e=await Im;return Fw(e,s)}),3e4)}catch{return{}}}function Fw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=Yr.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),o=i.update(r);return JSON.parse(Buffer.concat([o,i.final()]))}function Bt(s,e,t=Mw,r=void 0){return async()=>{if(!vm)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await Bw(e);if(i)return en.debug("cache hit:",{fnName:e}),i;if(en.debug("cache miss:",{fnName:e}),!Sm)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 jw(e,o,t),o}}async function Bw(s){let t=(await Fi)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function jw(s,e,t){if(Gc)throw en.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 Fi;r[s]={value:e,expiry:Date.now()+t},Em=new Promise(n=>{Mi=n}),Uw(r)}catch{en.error("failed updating cache")}}async function Xr(){let s=await Fi;Object.keys(s).forEach(e=>{delete s[e]})}function xm(s){vm=s}function $w(s=!0){Sm=s}async function Am(){try{return Gc=!0,await Em}finally{Gc=!1}}function Cm(s){Ni=s,Fi=Rm()}var Li,Di,Yr,Tm,en,Ni,wm,Mi,vm,Sm,Gc,Em,Im,Mw,Ui,Fi,Uw,Pm,km,hx,Om,Yt=v(()=>{"use strict";Li=I(require("fs")),Di=I(require("path")),Yr=I(require("crypto"));F();Tm=require("lodash");W();en=P("local cache"),Ni=Di.resolve(gt(),"testim-cache"),vm=!0,Sm=!0,Gc=!1,Em=new Promise(s=>{Mi=s}),Im=new Promise(s=>{wm=s}),Mw=1e3*60*60*3,Ui=()=>Di.resolve(Di.resolve(Ni,"testim.cache"));Fi=Rm(),Uw=(0,Tm.debounce)(async s=>{let e;try{let t=await Im,r=Yr.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=Yr.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await ye(Ni)||await Li.promises.mkdir(Ni,{recursive:!0}),await Li.promises.writeFile(Ui(),a)}catch(t){en.error("failed saving cache",{err:t}),e=t}Mi(e?{success:!1,error:e}:{success:!0})},200);Pm=wm,km=xm.bind(void 0,!1),hx=xm.bind(void 0,!0),Om=()=>$w(!1)});function Bi(){return{cliLocation:gt(),userInfo:Qr.userInfo(),platform:Qr.platform(),release:Qr.release()}}var Qr,Hc=v(()=>{"use strict";Qr=I(require("node:os"));F()});function Ww(s){try{return ji.resolve(ji.dirname(require.resolve(`${s}/package.json`)),require(`${s}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(s);throw e}}function Xt(s){let e=Ww(s);return require(e)}var ji,tn=v(()=>{"use strict";ji=I(require("path"))});function Vw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Gw(s){return/The "to" argument must be of type string./.exec(s)}function Nm(s,e,t){let r=Vw(s),n=Gw(s);return r||n?(Dm.info("Failed to install package due to insufficient write access",{...Bi(),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: ${c} stderr: ${d}`}
|
|
9
|
+
`),!0):!1}function Kc(s){try{return Xt(s)}catch{return!1}}function Mm(s,e){return require(yr.join(s,`./node_modules/${e}/package.json`)).version}function Um(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=Um(s[e]);if(t)return t}}function Fm(s){let e=require(yr.join(s,"package.json"));if(!("exports"in e))return"";let t=Um(e);if(!t)throw new Ei(e.name);return t}async function Wi(s,e,t){let r=yr.join(s,"npm-shrinkwrap.json"),n=yr.join(s,"npm-shrinkwrap-dummy.json"),i=!1;try{try{await ye(r)&&(await zc.promises.rename(r,n),i=!0)}catch{}return await Lm(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(o=>{throw Nm(o.stderr,s,e)?new Vr(`${s} Failed to install package: ${e} due to insufficient write access in directory`):o})}finally{if(i)try{await zc.promises.rename(n,r)}catch{}}}function Jc(s,e,t,r,n=!0){return new Promise((i,o)=>{let a=t?["--proxy",t]:[],l=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},c="",d="",m=["--no-save","--no-package-lock","--no-prune","--no-audit","--progress=false"];n&&m.push("--prefer-offline");let u=(0,$i.spawn)("node",[qc,"i","--prefix",s,...m,...e,...a],l);u.stderr.pipe(process.stderr),u.stdout.pipe(process.stdout),u.stdout.on("data",f=>{c+=f}),u.stderr.on("data",f=>{d+=f}),u.on("close",f=>{var h,g;if(f){n&&Jc(s,e,t,r,!1).then(i).catch(o);let y;try{let T=(h=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(d))==null?void 0:h[1],w=(g=/No matching version found for (\S+)@/gm.exec(d))==null?void 0:g[1];T||w?y=`404 Not Found - GET https://registry.npmjs.org/${w??T} - Not found`:Nm(d,qc)?y=`insufficient write access in location ${qc}`:y=`Npm Installation closed with exit code ${f} with error: ${d}`}catch{y=`Npm Install closed with exit code ${f}
|
|
10
|
+
stdout: ${c} stderr: ${d}`}Dm.info(`Npm Install closed with exit code ${f}`,{message:y,stderr:d}),o(new Rt(y))}else i(c)}),setTimeout(()=>{try{u.kill()}finally{o(new oe)}},r)})}async function Bm(){try{return(await Lm("npm -v")).stdout.trim()}catch{return""}}var zc,yr,_m,$i,Lm,Dm,qc,Zr=v(()=>{"use strict";zc=I(require("fs")),yr=I(require("path"));F();_m=require("util"),$i=require("child_process");W();Hc();tn();Y();Lm=(0,_m.promisify)($i.exec),Dm=P("cli-service");qc=yr.resolve(require.resolve("npm").replace("index.js",""),"bin","npm-cli.js")});var U,$m,Wm,Vm,Hw,qw,zw,jm,Vi,Xc,_,ue=v(()=>{"use strict";U=I(require("rox-node")),$m=I(require("node-fetch")),Wm=require("eventsource");W();F();de();Vm=P("FeatureFlagsService"),Hw=!$e&&!0&&!Ad,qw=2e4,zw=60*60*24,jm=["labs","disabled","enabled"],Vi=class extends U.default.RoxString{constructor(e="disabled"){super(e,jm)}getValue(){let e=super.getValue();return jm.includes(e)?e:(Vm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},Xc=class{constructor(){this.flags={useNewWSCLI:new U.default.Flag,useSafariWebdriverVisibilityChecks:new U.default.Flag,useClickimVisibilityChecks:new U.default.Flag,runGetElementCodeInAut:new U.default.Flag,enableFrameSwitchOptimization:new U.default.Flag,maximumJsResultSize:new U.default.RoxNumber(2e3*1024),skipFileInputClicks:new U.default.Flag,errorMessageOnBadNetwork:new U.default.Flag(!0),warnOnBadNetwork:new U.default.Flag(!1),overrideAzureStorageUrl:new U.default.Flag,autoSaveDownloadFileFireFox:new U.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new U.default.Flag(!0),experimentalPreCodeCompilation:new U.default.Flag(!0),experimentalAsyncCustomCode:new U.default.Flag,useSameBrowserForMultiTests:new Vi("labs"),highSpeedMode:new Vi,usePortedHtml5DragDrop:new U.default.Flag,testNamesToBeforeSuiteHook:new U.default.Flag,addCustomCapabilities:new U.default.RoxString("{}"),addCustomLTtunnelNTLMOptions:new U.default.RoxString("{}"),LTNetworkCapabilities:new U.default.Flag,downloadToBase64:new U.default.Flag,publicGridURL:new U.default.RoxString("public-grid.testim.io"),allowAppFromDeviceRuns:new U.default.Flag(!0),unsupportedCapsFields:new U.default.RoxString("[]"),dontFocusOnInit:new U.default.Flag,retryOnSeleniumHubError:new U.default.Flag,enableLambdaTestTunnelNTLM:new U.default.Flag,enableLambdaTestTunnelSkipUpgrade:new U.default.Flag,tdcHsPreventNetworkCapture:new U.default.Flag,headSpinTdcEnableFlagCapability:new U.default.Flag,enableBatchTDC:new U.default.Flag,enableBatchHeadSpin:new U.default.Flag,clearRunnerFileCache:new U.default.Flag,forceTurboModeIfNeeded:new U.default.Flag,redisSlotManager:new U.default.Flag,tunnelBinaryNewVersion:new U.default.Flag(!1),encryptedCredentials:new U.default.Flag,computePackagePathFromPackageJsonExports:new U.default.Flag,sendExtensionOnEdgeNonLinux:new U.default.Flag,enableAppium2pCloudy:new U.default.Flag,reuseCliPkgInstallFolder:new U.default.Flag,getPublicIpFrom3rdPartyServices:new U.default.Flag,chromedriverCdnBinariesUrl:new U.default.RoxString(""),sfdcHybridCompany:new U.default.Flag,allowFixingAppIdStructure:new U.default.Flag,enableAppium2BrowserStack:new U.default.Flag,increaseTDCRequestTimeout:new U.default.Flag,accessTokenExpiryMargin:new U.default.RoxNumber(300*1e3),useMV3Extension:new U.default.Flag,testimHeadlessExtensionDownloadUrl:new U.default.RoxString("",[]),applyMobileRestrictionFromDate:new U.default.RoxNumber(17235072e5),removeMobileTrialRestrictions:new U.default.Flag,appiumConnectionRetryCount:new U.default.RoxNumber(0),appiumConnectionRequestTimeout:new U.default.RoxNumber(12e4),DFBrowserVersion:new U.default.RoxString("latest",["latest","latest-1","latest-2"]),DFAcceptInsecureOrigins:new U.default.RoxString("http://jsbin.testim.io"),enableFixForCustomExtensionForLT:new U.default.Flag(!1),enableTestPlanAggregation:new U.default.Flag,secrets:new U.default.Flag,chromeArgsDisableFeatures:new U.default.RoxString("")},U.default.register("default",this.flags)}setProjectId(e){U.default.setCustomStringProperty("projectId",e)}setProjectType(e){U.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){U.default.setCustomStringProperty("productType",e)}setCompanyId(e){U.default.setCustomStringProperty("companyId",e)}setPlanType(e){U.default.setCustomStringProperty("planType",e)}setIsPOC(e){U.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){U.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){U.default.setCustomStringProperty("runnerMode",e)}setRunnerEnvironment(e){U.default.setCustomStringProperty("runnerEnvironment",e)}async fetch({proxy:e}){let t,r,n;if(!Hw)return;if(e){t=require("https-proxy-agent").HttpsProxyAgent;let o=e?new t(e):void 0;r=(a,l)=>(0,$m.default)(a,{...l,agent:o}),n=function(a){return new Wm.EventSource(a,{fetch:r})}}let i={fetchIntervalInSec:zw,fetchFunction:r,eventSourceImpl:n};return le(U.default.setup(Rd,i),qw).catch(o=>Vm.error("failed to get feature flag status",o))}},_=new Xc});var zm={};H(zm,{install:()=>Jw,isReady:()=>Xw,start:()=>Yw});var Gm,Hm,qm,Zc,Qc,Kw,Jw,Yw,Xw,Km=v(()=>{"use strict";Gm=I(require("fkill")),Hm=I(require("p-retry"));Zr();Ve();F();tn();ue();qm="chromedriver",Zc=9515,Qc=`http://localhost:${Zc}/wd/hub`,Kw=[`--port=${Zc}`,"--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],Jw=async()=>{let s=_.flags.chromedriverCdnBinariesUrl.getValue(),e=Oe(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await Wi(gt(),`${qm} --detect_chromedriver_version ${e}`)},Yw=async()=>{process.env.NODE_OPTIONS="",await(0,Gm.default)(`:${Zc}`,{silent:!0}),await Xt(qm).start(Kw,!0)},Xw=async({chromeBinaryLocation:s})=>{await(0,Hm.default)(async()=>{var n;let e=await Te(`${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 Vs(`${Qc}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var sn={};H(sn,{getSessionPlayerFolder:()=>sl,prepareChromeDriver:()=>rn,prepareCustomExtension:()=>tl,prepareExtension:()=>rl,preparePlayer:()=>br});async function tl(s,e=!1){if(!s)return;if(Oe(s)){let n=es.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await Qw(s)>el&&!e)throw new C(Jm);return await Ke(s,n),n}let t=es.resolve(s);if(!Xm.existsSync(t))throw new C(`Failed to find custom extension in location: ${t}`);if(Pc(t)>el&&!e)throw new C(Jm);return t}async function Qw(s){let e=(Ve(),He(ze));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw Gi.warn("failed to download custom extension",{err:t}),new C(`Failed to download custom extension from location: ${s}`)}}function rl(s){Gi.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:Ri(t)}));return Bt(()=>se(e,({location:t,path:r})=>xi(t,r)),"prepareExtension",Zm,e)()}async function rn(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),i=await Promise.resolve().then(()=>(Km(),zm));try{await i.install(),await i.start(),t||await i.isReady(e),n.succeed("Chrome Driver initiated successfully")}catch(o){let a="Failed to initiate Chrome Driver";throw o instanceof Vr||(Gi.error(a,{...s,...Bi(),error:(0,Qm.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 Qw(){let s=Ht==="staging"?`${Ns}/Staging-LATEST_VERSION`:`${Fs}/extension/sessionPlayer_LATEST_RELEASE`;return(await Mt(s)).body.toString("utf8")}function Zw(){return`${Ns}/dev-sessionPlayer.zip`}async function ev(s,e){if(!Oe(s)||Oe(s)&&e||$e)return s;let t=await Qw();return`${s}-${t}${Ht==="staging"?".zip":""}`}function tl(){let s=gt();return es.resolve(s,"testim-bin")}function tv(){let s=tl();return es.resolve(s,"sessionPlayer.zip")}async function Qm(s,e,t=!1){try{return await xi(s,e),await it(e,tl())}catch(r){if(t)throw r;return await Qm(s,e,!0)}}async function br(s,e){Gi.info("prepare player",{location:s,canary:e});let t=tv();return Bt(async()=>{let r=Ht==="development"?Zw():await ev(s,e);return await Qm(r,t),{}},"preparePlayer",Xm,[s,e,t])()}var Km,Jm,es,Ym,Gi,Xm,Qc,zm,nn=v(()=>{"use strict";Km=I(require("ms")),Jm=I(require("node:fs")),es=I(require("node:path"));de();Yt();Ym=require("serialize-error");W();Vc();Y();U();Gi=P("prepare runner and testim start"),Xm=(0,Km.default)("0.5 day"),Qc=16,zm=`The size of the custom extension is more than ${Qc}MB`});function rv(){let s=on.type().toLowerCase();return s==="darwin"?on.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?on.arch()==="x64"?"win64":"win32":"linux"}async function qi(){let s=rv(),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(an,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]}/${an}/${n[s]}.zip`,a=Hi.join(rl,n[s]),l=`${a}.zip`,c=Hi.join(a,i[s]);if(await ye(c))return c;if(!await ye(l)){let m=(0,sl.default)("Downloading Chromium").start();try{await Zm.promises.mkdir(rl),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,sl.default)("Extracting Chromium").start();try{await it(l,rl)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),c}var Zm,on,Hi,sl,an,rl,nl=v(()=>{"use strict";Zm=I(require("fs")),on=I(require("os")),Hi=I(require("path")),sl=I(require("ora"));Y();U();an="1000968",rl=Hi.join(Ut,`chrome-${an}`)});async function rf(s,e){return Tr=s,cl=e,await il()}function sf(s,e){Tr=e.projectId,cl=e.token,cn=e.userAccessKey,ot=s.token,un=ll(ot),pn=s.refreshToken,ol=s.ngrokToken,al=s.isNgrokWhitelisted,ef=e.publicIp,tf=e.initializedFromCache}function nv(s=Tr,e=cl){return Bt(()=>(ln.info("request to get cli token from server"),We({url:`${he}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",sv*10,{projectId:s,token:e})()}async function iv(){ln.info("request to refresh JWT cli token from server");let s=await We({url:`${he}/auth/refreshToken`,body:{token:ot,refreshToken:pn}});return ot=s.token,un=ll(ot),s.refreshToken&&(pn=s.refreshToken),ot}async function il(){try{let s=await nv();return ln.info("successfully get cli token from server"),ot=s.token,un=ll(ot),pn=s.refreshToken,ol=s.ngrokToken,al=s.isNgrokWhitelisted,ot}catch(s){throw s.message.includes("Unauthorized")?new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(ln.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Tr}),new C(`While trying to retrieve CLI token, caught error: ${s}`))}}function ll(s){return require("jsonwebtoken").decode(s).exp*1e3}async function At(){if(!un)return il();let s=_.flags.accessTokenExpiryMargin.getValue();if(un<Date.now()+4*s)try{return await iv()}catch(e){return ln.error("failed to refresh token, executing fallback",e),il()}return ot}function zi(){return pn}function wr(){return ot?{uid:require("jsonwebtoken").decode(ot).id,ngrokToken:ol,isNgrokWhitelisted:al}:{}}async function Ki(){if(!cn||!Tr)return;if(await ul({userAccessKey:cn,projectId:Tr}))return cn;let e=`user access key "${cn}" is invalid for project "${Tr}"`;throw new C(e)}function Ji(){return ef}function Yi(){return tf}var ln,ot,un,pn,ol,al,Tr,cl,cn,ef,tf,sv,at=v(()=>{"use strict";de();Ve();Yt();Y();W();ge();ue();ln=P("testim-custom-token"),Tr=null,cl=null,sv=5*60*1e3});function ov(s){if(s.protocol)return s.protocol;if([L.TESTIM_PRIVATE,L.TESTIM,L.BROWSERSTACK,L.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([L.TESTIM_ENTERPRISE,L.TESTIM_LAMBDATEST,L.DEVICE_FARM].includes(s.type)){let e=nf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function av(s){let e=nf.exec(s);return e==null?void 0:e[3]}function Qi(s){var S,E,A,D,j,R,x,O,B,G,z;let e=s&&av(s.host),t=s.port,r=s.path,n=s&&ov(s),i=s.token,o=s.slotId,a=(S=s.hybrid)==null?void 0:S.tunnel,l=(E=s.external)==null?void 0:E.user,c=(A=s.external)==null?void 0:A.key,d=s.type,m=d===L.HYBRID?a&&((R=(j=(D=s.hybrid)==null?void 0:D.external)==null?void 0:j[s.hybrid.tunnel])==null?void 0:R.user):l,u=d===L.HYBRID?a&&((B=(O=(x=s.hybrid)==null?void 0:x.external)==null?void 0:O[s.hybrid.tunnel])==null?void 0:B.key):c,f=s.name,h=s&&(s._id||s.gridId),g=s.provider,y=(G=s.mobileTokens)==null?void 0:G.androidToken,T=(z=s.mobileTokens)==null?void 0:z.iosToken,w=s.apiUrl,b=s.isSupportGrid;return{host:e,port:t,path:r,protocol:n,accessToken:i,slotId:o,gridId:h,tunnel:a,user:l,key:c,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:w,isSupportGrid:b}}async function lv(s,e,t,r,n,i){var a;let o;try{o=await i()}catch(l){throw Xe.error("failed to get grid",{projectId:s,companyId:e,err:l}),new Error(ht.UNKNOWN)}if(Xe.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw Xe.error("invalid response - get grid",{res:o}),new Error(ht.UNKNOWN);if(o.status==="success"){if(o.grid.mode==="local")return{mode:"local"};((a=o.grid)==null?void 0:a.mode)==="custom"&&Object.assign(o.grid,lf(n));let l=Qi(o.grid);return cv(t,e,l.gridId,l.slotId,r,l.isSupportGrid),l}throw o.code==="not-found"?new rt(ht.NOT_FOUND):o.code==="no-available-slot"?new zt(`Failed to run test on ${r} - concurrency limit reached`):(Xe.error("invalid code error response - get grid",{res:o}),new rt(ht.UNKNOWN))}function af(s){return hl(s)}async function cf(s,e,t){let n=(t||await af(s)).find(i=>i._id===e);if(!n)throw new C(`Failed to find grid id: ${e}`);return Qi(n)}async function uv(s,e,t){let n=(t||await af(s)).find(i=>(i.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new C(`Failed to find grid name: ${e}`);return Qi(n)}async function pl(s,e){let t=dn[s];if(!t)return;let{slotId:r,gridId:n,browser:i,companyId:o,isSupportGrid:a}=t;if(delete dn[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 ml(o,e,r,n,i)}catch(l){Xe.error("failed to release slot",{projectId:e,err:l})}}}async function pv(s){let e=Object.values(dn).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid){Xe.info("keep alive worker slots",{projectId:s,slots:e});try{await dl(s,e)}catch(t){Xe.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function dv(s){of=global.setInterval(pv,1e4,s)}async function mv(s){let e=Object.keys(dn);if(e.length){Xe.warn("not all slots released before end runner flow",{projectId:s});try{await se(e,t=>pl(Number(t),s))}catch(t){Xe.error("failed to release all slots",{err:t,projectId:s})}}}async function fv(s){await mv(s),clearInterval(of)}function gv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function hv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function lf(s){let t=(()=>Xi.isEmpty(s.testobjectSauce)?Xi.isEmpty(s.saucelabs)?Xi.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:i,protocol:o}=s,a=gv(t,s),l=hv(t,s);return{host:r,port:n,path:i,protocol:o,type:t,user:l,key:a,gridId:re()}}async function uf(s,e){let t=s.company.companyId;return await cf(t,e.gridId,s.allGrids)}async function pf(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 lf(s);let c=t==null?void 0:t.companyId;if(a)return cf(c,a,e);if(l)return uv(c,l,e);if(Js(s)||s.tunnelOnlyMode){Xe.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new rt("Missing host or grid configuration")}async function df(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 lv(o,h,r,s,t,()=>gl({projectId:o,companyId:h,browser:s,executionId:e,isRunningLocalMode:f,gridId:l,gridName:a,host:i,testResultId:n}))}var Xi,Xe,dn,nf,of,cv,mn,mf,ts=v(()=>{"use strict";Xi=I(require("lodash"));ge();W();U();ie();Y();Xe=P("grid-service"),dn={},nf=/(^(https?):\/{2})?(.*)/,of=null;cv=(s,e,t,r,n,i)=>{dn[s]={gridId:t,companyId:e,slotId:r,browser:n,isSupportGrid:i}};mn={start:dv,end:fv};mf=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,i)),a!==L.HYBRID||!i||!l||!d||!m))return e;let u=await fl({companyId:i,gridId:o,maxRetries:d,currentRetry:m,browser:l,usingTunnel:c});Xe.info("handling hybrid grid",{response:u,companyId:i});let f=Qi({...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,i)),f}});function gn(){return Zi||"master"}function ff(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){Zi="master";return}if(s!=null&&s.isArchived)throw new C(`Branch ${s.branch} is archived, run aborted.`);if(s){Zi=s.branch||s;return}Zi=e?"master":void 0}var Zi,yl=v(()=>{"use strict";Y()});function Tf(s){$e||(s!=null&&s.userId||(s={anonymousId:bf}),yf.identify(s))}function yt(s,e){return hn("ci",s,e)}function hn(s,e,t){if($e)return;let r=s?{userId:s}:{anonymousId:bf};yf.track(Object.assign(r,{event:e,properties:t}))}var hf,yf,bf,rs=v(()=>{"use strict";de();hf=require("@segment/analytics-node"),yf=new hf.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1}),bf=require("crypto").randomBytes(20).toString("hex")});var wf={};H(wf,{isCi:()=>ss});var ss,eo=v(()=>{"use strict";ss=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});function Sf(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Ef({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=Sf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:l,source:vf(c,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);yt("test-run-ci",y)}function If({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=Sf({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,mockNetworkEnabled:n.wasMockNetworkActivated,source:vf(d,m),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){yt("test-run-ci-success",w);return}yt("test-run-ci-fail",{...w,failureReason:n.failureReason})}catch(w){f.error("failed to update test end analytics",{err:w})}}function Rf(s){yt("batch-run-ci",s)}var vf,bl=v(()=>{"use strict";rs();eo();vf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:ss&&e?"ci-with-user":ss?"ci":e?"cli-with-user":s});var bn,Tl,yv,wl,bv,to,ro,so,no,io,oo=v(()=>{"use strict";U();ie();bn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===me.FAILED},Tl=s=>{let{status:e}=s;return e===me.ABORTED},yv=s=>{let{status:e}=s;return e===me.PASSED},wl=s=>s.runnerStatus===Pc.SKIPPED,bv=s=>s.testStatus===Je.EVALUATING,to=(s,e)=>Object.values(s).filter(t=>{var r,n;return wl(t)&&(Ye(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,ro=s=>Object.values(s).filter(e=>bn(e)&&bv(e)).length,so=s=>Object.values(s).filter(bn),no=s=>Object.values(s).filter(yv),io=s=>Object.values(s).filter(Tl)});function wv(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var vl,ao,Tv,co,Af=v(()=>{"use strict";vl=I(require("lodash"));W();oo();ao=P("debug-reporter"),Tv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],co=class{constructor(e){this.options=e}onTestStarted(e,t){ao.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,i=r.host,o=r.gridId,a=r.type,l=r.failedGetBrowserAttempts;ao.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:i,failedGetBrowserAttempts:l,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...vl.default.omit(this.options,Tv),company:vl.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,i,o,a){let l=wv(process.argv);ao.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=no(e).length,a=Object.keys(e).length-o;ao.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:i,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Sl,Ct,Tn=v(()=>{"use strict";ie();Sl=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 Sl});var Il={};H(Il,{Reporter:()=>vv});var Zt,wn,vr,lo,Cf,El,vv,Rl=v(()=>{"use strict";Zt=I(require("chalk")),wn=I(require("lodash"));U();ie();Tn();oo();vr={success:Zt.default.green,warn:Zt.default.yellow,error:Zt.default.red},{CLI_MODE:lo}=Ft,Cf="device",El=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t){let r=`(${e.testId})`,n=`url: ${Zt.default.underline(qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?me.PASSED:me.FAILED,n=`(${e.testId})`,i=vr[e.success?"success":"error"];console.log(i(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${Pi(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=qe(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(vr.error("Failed runs are:")),console.log(vr.error(t.join(`
|
|
17
|
-
\r`)))}onTestPlanFinished(e,t,r,n,i){let o=so(e),a=no(e),l=io(e),c=a.length,d=l.length,m=o.length,u="",f="";if(Ct.isTestStatusEnabled){let w=ro(e);u=` FAILED-EVALUATING: ${w}`,m-=w,f=` SKIPPED: ${to(e,this.options)}`}let h=this.buildTestPlanName(i,t),g,y=vr[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${Pi(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=wn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=wn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=wn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=wn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[i,n,r,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,i,o,a){let l=u=>{u.forEach((f,h)=>{var w;let g=(w=f.testData)!=null&&w.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`,T="";f.testOptimization?T=` [${f.testOptimization.reason}]`:Ye(f,this.options)&&(T="-quarantine"),console.log(" ",h+1,":",`${f.name}${T}`,y,g)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(o,n)} test plan with ${m} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===lo.APPIUM?Cf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${Zt.default.underline(n)} slot from ${Zt.default.underline(r)}`)}onGetSession(e,t,r){let n=r===lo.APPIUM?Cf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${Zt.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,i=this.options.mode===lo.APPIUM?"device":"browser";if(n)console.log(vr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${i} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(vr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===lo.APPIUM?"Appium":"Selenium";console.log(vr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},vv=El});var Cl={};H(Cl,{Reporter:()=>Av});function Sv(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function Ev(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 Iv(s){return`${s.visitedUrlsJson||""}`}async function Rv(s,e,t,r,n,i){function o(u){let f=qe(s,t,u.testId,u.resultId,r),h={$:{name:Sv(u),classname:n,time:Fc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(bn(u)||Tl(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=bn(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return wl(u)&&Ye(u,i)&&Ct.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=Ev(u),h["visited-urls-json"]=Iv(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},w={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(Ct.isTestStatusEnabled){w.skipped=to(y,i);let b=ro(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 so(u).length+io(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Al.Builder().buildObject(m)}catch(u){return xv(u)}}function xv(s){let e=new Al.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 Al,Pf,xl,Av,Pl=v(()=>{"use strict";Al=I(require("xml2js"));U();Pf=require("fs");Tn();oo();xl=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 Rv(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Pf.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)}};Av=xl});var kf={};H(kf,{Reporter:()=>Cv});function ns(s){return s?s.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var kl,Ol,Cv,Of=v(()=>{"use strict";W();kl=P("team-city-reporter");Ol=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${r}`;return ns(n)}onTestStarted(e,t,r,n){if(r){kl.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){kl.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ns(t)}' details='${ns(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){kl.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${ns(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${ns(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ns(t)}']`)}},Cv=Ol});var _f={};H(_f,{Reporter:()=>Pv});var _l,Pv,Lf=v(()=>{"use strict";_l=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}}))}},Pv=_l});function po(s){let{platform:e}=process;e==="win32"?(0,uo.exec)(`start chrome ${s}`):e==="darwin"?(0,uo.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,uo.exec)(`google-chrome ${s}`)}var uo,Ll=v(()=>{"use strict";uo=require("child_process")});var Df={};H(Df,{Reporter:()=>kv});var Dl,kv,Nf=v(()=>{"use strict";U();Ll();Dl=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 po(t)}},kv=Dl});var Nl,Q,Pt=v(()=>{"use strict";Af();Nl=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 co(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Rl(),Il));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(Pl(),Cl));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Of(),kf)),r.includes("console")&&Promise.resolve().then(()=>(Rl(),Il)),r.includes("junit")&&Promise.resolve().then(()=>(Pl(),Cl)),r.includes("json")&&Promise.resolve().then(()=>(Lf(),_f)),r.includes("chrome")&&Promise.resolve().then(()=>(Nf(),Df))])).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 Nl});async function Ml(s,e,t){let r=is[s];if(!r)return;let{slotId:n}=r;if(delete is[s],!n){ct.warn("failed to find slot slot id",{companyId:e,workerId:s});return}ct.info("release slot id",{companyId:e,slotId:n});try{await Ul(e,t,n)}catch(i){ct.error("failed to release slot",{companyId:e,err:i})}}async function Ov(s,e){let t=Object.values(is).filter(Boolean);if(t.length!==0){ct.info("keep alive worker slots",{companyId:s,slots:t});try{await jl(s,e,t)}catch(r){ct.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function _v(s,e){Mf=global.setInterval(()=>Ov(s,e),1e4)}async function Lv(s,e){let t=Object.keys(is);if(t.length){ct.warn("not all slots released before end runner flow",{companyId:s});try{await se(t,r=>Ml(Number(r),s,e))}catch(r){ct.error("failed to release all slots",{err:r,companyId:s})}}}async function Dv(s,e){await Lv(s,e),clearInterval(Mf)}async function Uf(s,e,t){let r;try{r=await Fl(s,e)}catch(n){throw ct.error("failed to get slot",{companyId:s,err:n}),new Error(ht.UNKNOWN)}if(ct.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw ct.error("invalid response - get slot",{res:r}),new Error(ht.UNKNOWN);if(r.status==="success")return Ff(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new rt(ht.NOT_FOUND):r.code==="no-available-slot"?new zt("Failed to run test - concurrency limit reached"):(ct.error("invalid code error response - get slot",{res:r}),new rt(ht.UNKNOWN))}async function Bf(s,e,t,r){let n=is[r];if(!n)throw new Error("slot not found");Object.assign(n,t),Ff(r,n),await Bl(s,e,n),ct.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var ct,is,Mf,Ff,vn,os=v(()=>{"use strict";ge();W();U();ie();Y();ct=P("slot-service"),is={},Mf=null,Ff=(s,e)=>{is[s]=e};vn={start:_v,end:Dv}});function $f(s,e=process){async function t(r){await le(se(jf,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{En.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(En.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",()=>{En.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw En.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw En.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function as(s){jf.push(s)}var En,jf,In=v(()=>{"use strict";W();U();En=P("process-handler"),jf=[]});var Hf={};H(Hf,{installAllLazyDependencies:()=>Uv,lazyRequire:()=>lt});async function lt(s,e={}){let t=qc(s);if(t)return t;let r;e.silent||(r=(0,Wf.default)(`Installing ${s} before first usage...`).start());try{let n=await Fv(s);return r&&r.succeed(),n}catch(n){Mv.warn("failed to install dependency lazily",{dependency:s,err:n});let i=Gf(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 Fv(s){return cs.has(s)||(cs.set(s,Vf(s)),cs.get(s).catch(()=>{cs.delete(s)})),cs.get(s)}async function Vf(s){let e=qc(s);if(e)return e;let t=Gf(s),r=`${s}@${t}`;return await Wi(gt(),r),Xt(s)}async function Uv(){let s=Object.keys(oc);for(let e of s)await Vf(e)}function Gf(s){let e=Object.entries(oc).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Wf,Mv,cs,Rn=v(()=>{"use strict";Wf=I(require("ora"));Zr();W();U();fi();tn();Mv=P("lazy-require"),cs=new Map});var qf,mo,zf=v(()=>{"use strict";qf=require("istanbul-lib-report"),mo=class extends qf.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 Kf,Jf,Yf,xn,bt,Xf,fo,$l,Qf,Bv,Zf,eg,jv,$v,tg,Wv,Vv,Gv,Hv,qv,rg,sg=v(()=>{"use strict";Kf=I(require("ora")),Jf=I(require("dayjs")),Yf=I(require("test-exclude")),xn=I(require("fs")),bt=I(require("path")),Xf=I(require("istanbul-reports")),fo=I(require("istanbul-lib-report"));ge();Y();U();W();Rn();zf();$l=P("test-run-status"),Qf=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},Bv=s=>!!Qf(s).search,Zf=s=>s?Qf(s).pathname.substring(1):"",eg=(s,e)=>{let t=Zf(e);return!new Yf.default({relativePath:!1,include:s}).shouldInstrument(t)},jv=s=>s.substring(0,s.indexOf("?")),$v=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await lt("convert-source-map");if(t==="file"&&!e)throw new C("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},tg=(s,e)=>`${bt.resolve(s,Zf(e))}.js`,Wv=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await se(Object.values(t),async n=>{if(!n)return;let i=n.toObject();await se(i.sources,async(o,a)=>{if(eg(r,o))return;let l=tg(e,o);await xn.promises.mkdir(bt.parse(l).dir,{recursive:!0}),await xn.promises.writeFile(l,i.sourcesContent[a])})})},Vv={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(Bv(e)&&(e=jv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=bt.dirname(this.getPath(s));return bt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},Gv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=fo.createContext({dir:t,coverageMap:e,watermarks:fo.getDefaultWatermarks(),sourceFinder:a=>{try{let l=tg(r,a);return xn.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new mo({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:Vv}),Xf.create(a,l).execute(o)}),i},Hv=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await lt("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>eg(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},qv=async(s,e)=>{let{mergeProcessCovs:r}=await lt("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await Vl(s,"testResult",`runId=${e}`)).data.docs;return await se(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await An(l,9e4);await se(c,async d=>{if(!i.has(d.url)){let m=d.text;d.sourceUrl&&(i.set(d.url,"TEMP"),m=await Wl(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}},rg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;$l.info("start js coverage process");let n=(0,Kf.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=bt.resolve(s.codeCoverageReportPath||"./coverage"),o=bt.resolve(i,`.js/${(0,Jf.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?bt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([lt("istanbul-lib-coverage"),qv(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}$l.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await se(c.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=d.get(h),w=await $v({sourceMapType:T,source:y,sourceMapDir:a});u[h]=w;let b=await Hv(s,{source:y,sourceMap:w,functions:g});m.merge(b)}),await Wv(s,o,u);let f=await Gv(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),$l.error(c,{err:l})}}});var ng={};H(ng,{SELENIUM_PERF_MARKS:()=>xe,SeleniumPerfStats:()=>Sr});var xe,zv,Sr,ls=v(()=>{"use strict";U();xe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},zv=["ALL",...Object.values(xe)],Sr=class{constructor(){this.marks=Object.fromEntries(zv.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`,_i(r,50)],[`${t}_P95`,_i(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var cg={};H(cg,{initServer:()=>Yv,mapFilesToLocalDrive:()=>Hl});function Hl(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,go[t.id]?{screenshot:go[t.id]}:{})),Object.keys(ho).forEach(t=>{s.assets||={},s.assets[ag[t]]=ho[t]}),s.assets||={},s.assets.screenshots=Object.values(go)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function Yv({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await lt("multer"),n=typeof t=="string"?t:Kv;await Gl.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=Cn.join(n,m.testResultId);try{await Gl.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=Cn.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,og.default)();o.disable("x-powered-by"),o.post("/",i.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(go[d.stepId]=l.file.path),d.testResultId&&Jv.includes(d.subType)&&(ho[d.subType]||=[],ho[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 Gl,ig,Cn,og,Kv,go,ho,ag,Jv,ql=v(()=>{"use strict";Gl=I(require("fs")),ig=I(require("os")),Cn=I(require("path")),og=I(require("express"));Y();Rn();Kv=Cn.join(ig.tmpdir(),"testim/rca/"),go={},ho={},ag={"test-log":"consoleLogs","har-file":"networkLogs"},Jv=Object.keys(ag)});var er,zl,yo,lg=v(()=>{"use strict";er=I(require("lodash"));U();W();zl=P("override-test-data-builder"),yo=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return er.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!er.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):zl.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(er.isObject(e.overrideAllTestsData)&&!er.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):zl.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}zl.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return er.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let i=r.map(d=>this.generateTestUniqId(d)),o=i.indexOf(n),a=i.lastIndexOf(n),l=r[o],c=this.createNewTestItems(l,t);return r.splice(o,a-o+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let i=re();return{...e,resultId:i,testData:{value:r,index:n+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function bo(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Qe.warn("failed to run hook",{err:t}),new C(`failed to run hook promise ${t.message}`)}}var Er,Qe,Xv,Qv,Zv,eS,To,ug=v(()=>{"use strict";Er=I(require("lodash"));U();ie();ts();os();ge();Y();W();Pt();In();sg();ls();ql();de();ue();lg();Tn();Qe=P("test-run-status"),Xv=fr(),Qv=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,Zv=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,eS=tt();To=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=Ks(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:yi||t.parallel||1,browser:i,gitBranch:Xv,gitCommit:Qv,gitRepoUrl:Zv,runnerVersion:eS,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:w}=a,b={originalTestResultId:t,previousTestResultId:r,config:Er.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:w},Yl({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 vo(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){Qe.error("failed to upload test data artifact (runner)",{err:d})}let l=Er.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,Ir(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:i,testRetryKey:r})}async testStartReport(e,t,r){if(Ye(e,this.options))return;let n=this.exportsGlobal;try{let i=await bo(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token);return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...this.beforeSuiteParams,...i},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(i){throw Qe.error("Failed to start test",{err:i}),i}}testStartAndReport(e,t,r,n,i){let o=this.testStart(e,t,r,n);return this.testStartReport(o,t,i)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo={...t,key:void 0,user:void 0},Qe.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:i,testId:o,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Je.EVALUATING&&Ct.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Je.EVALUATING} status`);return}if(c){Q.onTestPassed(i);return}Q.onTestFailed(r,r.failureReason,qe(this.options.editorUrl,this.options.project,o,l,this.branchToUse),o,n,l)}calcResultText(e){return e.success?me.PASSED:me.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Je.QUARANTINE}`)}monitorMemoryUsage(e){let t=Uc();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&&Hl(o,Qe),o.resultUrl=qe(this.options.editorUrl,this.options.project,o.testId,o.resultId,this.branchToUse),o.status=this.calcResultText(t),t.status=o.status,t.name=o.name,t.testStatus=o.testStatus,t.testId||=o.testId,t.testCreatorName=o.testCreatorName,t.testCreatorEmail=o.testCreatorEmail,t.testOwnerName=o.testOwnerName,t.testOwnerEmail=o.testOwnerEmail,t.testData=o.config&&typeof o.config.testDataTotal=="number"?{total:o.config.testDataTotal,index:o.config.testDataIndex}:{},this.reportTestStatus(e,t,o,i),this.monitorMemoryUsage(o),Q.onTestFinished(o,e,i);let l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await bo(this.options.afterTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token)}catch(a){Qe.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(o=this.options.lightweightMode)!=null&&o.onlyTestIdsNoSuite?void 0:await Ir(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw Qe.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,i,o){let a=this.testEnd(e,t,r,n,i);return this.testEndReport(a,r,t,o)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:i,VIRTUAL_BUILD:o}=_c;return e&&(n=i),Hr(t,r)&&(n=o),n}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(o=e.gridData)==null?void 0:o.type,i=t.map(a=>{var f,h,g;let l=e.browser?Xs(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=qr(_,n)&&Ys(a.nativeApp)&&!e.appId,d=Jt(e)&&(Hr(a.nativeApp,n)||c),m=Ye(a,e)||d,u={testId:a.testId,testOptimization:a.testOptimization,status:m?me.SKIPPED:me.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Je.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(c,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((h=a.testData)==null?void 0:h.total)||null,testDataIndex:((g=a.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:l.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(i)}async endKeepAlive(e,t,r){e==="redis"&&await vn.end(r,t),e==="mongo"&&await mn.end(t)}async executionStart(e,t,r,n,i){Qe.info("execution started",{executionId:e,gridId:this.execConfig.gridId,gridHost:this.execConfig.gridHost,gridName:this.execConfig.gridName,gridType:this.execConfig.gridType,parallel:this.execConfig.parallel,runnerVersion:this.execConfig.runnerVersion,source:this.execConfig.source});let{options:o}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=o;as(()=>Promise.all([this.endKeepAlive(d,t,c),wo("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,..._.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=await bo(o.beforeSuite,m),f=new yo(u,Er.cloneDeep(this.testInfoList),t);this.testInfoList=f.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:h}=this,g=[],y=[],T=[];for(let b of h){if(b.isBeforeTestPlan){g.push(b);continue}if(b.isAfterTestPlan){T.push(b);continue}y.push(b)}let w=async()=>{let b=Er.cloneDeep(this.testRunStatus);await se(Object.keys(b),async A=>{var O;let D=b[A],j=(O=D.config)==null?void 0:O.testData,R=D.testId,x=await vo(t,R,A,j,l.defaults);x&&(delete D.config.testData,D.config.testDataUrl=x)});let S=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),E=Jl({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:S,intersections:o.intersections});return this.executionStartedPromise=E,E.catch(A=>Qe.error(A)),E};try{await w()}catch(b){Qe.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:y,afterTests:T}}concatSeleniumPerfMarks(e){Er.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var d;let t=jc(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 bo(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 rg(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await wo("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 Kl(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 Xl(s,e){var o;let t=s.canary?"-master.zip":".zip",r=`${e?Cd:Fs}/extension/testim-headless${t}`,n=_.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(o=s.company)==null?void 0:o.companyId,projectId:s.project,runnerEnvironment:Ht});return n||(tS.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 pg(s){let{chrome:e}=Xl(s,!1);return e}function So(s){let e=Ht==="staging"?`${Ns}/staging-sessionPlayer`:`${Fs}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var tS,Pn=v(()=>{"use strict";de();ue();W();tS=P("runOptionsUtils")});function mg(s,e){if(e){if(!aS.has(e)){kn.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var fg,gg,jt,hg,yg,bg,Eo,Tg,kn,rS,sS,On,nS,iS,oS,ne,aS,Io=v(()=>{"use strict";fg=I(require("ms")),gg=I(require("p-retry")),jt=I(require("node:os")),hg=I(require("portfinder")),yg=I(require("node:child_process"));U();Ve();ge();bg=I(require("node:fs")),Eo=I(require("node:fs/promises")),Tg=require("node:path");Y();W();Pn();ie();ue();U();kn=P("lambdatestService"),rS="https://downloads.lambdatest.com/tunnel/v3",sS={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"},On=`${jt.tmpdir()}/LT`,nS=`${On}/LT`,iS=(0,fg.default)("15m"),oS="2560x1440",ne=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===L.TESTIM_LAMBDATEST||e.type===L.LAMBDATEST||e.type===L.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e,t){ne.isLambdatestGrid(e)&&(ne.lambdatestConfigPromise||=Ql(t),ne.lambdatestConfig=await ne.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?iS:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ye(nS))return;let t=sS[jt.platform()+jt.arch()];if(!t)throw new Error(`tunnel on ${jt.platform()+jt.arch()} platform is not supported.`);let r=`${On}.zip`;await Ke(`${rS}/${t}`,r),await it(r,On)}static async chmodLtTunnel(e){if(!(jt.platform()==="win32"||!await ye(e))){try{await Eo.access(e,bg.constants.X_OK);return}catch{}try{await Eo.chmod(e,"777")}catch(r){throw kn.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await ce(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ne.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await hg.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,l=global.proxyUri;ne.tunnelName=re();let c=["--tunnelName",ne.tunnelName,"--infoAPIPort",String(t)];if(_.flags.enableLambdaTestTunnelNTLM.isEnabled())if(c=[...c,"--ntlm"],o&&a)c=[...c,"--ntlm-username",o,"--ntlm-password",a];else{let u=JSON.parse(_.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(c=[...c,...Mc(u)])}if(_.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(c=[...c,"--skip-upgrade"]),e.externalLambdatestUseWss&&(c=[...c,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(c=[...c,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io"]),r.tunnelUser&&r.tunnelKey)c=[...c,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&i)c=[...c,"--user",n,"--key",i];else throw new C("tunnel requires username and password");if(l)try{let u=new URL(l);c=[...c,"--proxy-host",u.hostname],u.port&&(c=[...c,"--proxy-port",u.port]),u.username&&u.password&&(c=[...c,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new C("proxy url is invalid")}e.externalLambdatestMitm&&(c=[...c,"--mitm"]),await ne.delay(3e3),await ne.chmodLtTunnel((0,Tg.join)(On,"LT")),ne.tunnel=yg.spawn("./LT",c,{cwd:On});let d="",m="";ne.tunnel.stdout.on("data",u=>{d+=u.toString()}),ne.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,gg.default)(()=>Te(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{onFailedAttempt:f=>{if(d.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});kn.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:d,stderrResult:m}),kn.error("Failed to start LT tunnel",{err:u}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!ne.tunnel))return new Promise((t,r)=>{ne.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ne.tunnel.kill()})}getCapabilities(e,t,r,n,i,o,a,l){var T,w;if(!this.isActive)return{};let c=ne.lambdatestConfig.CAPABILITIES[t]||{},d={...ne.tunnelName&&{tunnel:!0,tunnelName:ne.tunnelName}},m=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:mg(n,a==null?void 0:a.os)||mg(n,(T=o==null?void 0:o.lt)==null?void 0:T.platform)||c.platform||ne.lambdatestConfig.PLATFORM,resolution:ne.lambdatestConfig.RESOLUTION??oS,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=Xl({canary:u},!0);!h&&b[t]&&(m=[...m,b[t]]),h&&Oe(h)&&(m=[...m,h]),m.length||kn.warn("No extension was loaded in LambdaTestService",{extUrls:b,extensionPath:h})}return _.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&Oe(g)&&(m=[...m,g]),{build:r,name:`${n} - ${i}`,selenium_version:ne.lambdatestConfig.SELENIUM_VERSION,timezone:ne.lambdatestConfig.TIMEZONE,...c,...y,loadExtension:m,...d,console:!0,queueTimeout:300,network:_.flags.LTNetworkCapabilities.isEnabled(),ntlm:_.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:_.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},aS=new Set(["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey"])});function lS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Ag(s){return Eg.readFileSync(s,{encoding:"base64"})}function Cg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&Oe(s))&&s){let r=Ag(s);ps.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${tu(r)} current extension count: ${e.length}`),e.push(r)}}function Pg(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;let i=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!i){let d=typeof s.ext=="string"?s.ext:`${__dirname}/..`,m=r||d,u=`--load-extension=${m}`;ps.info(`adding extension: testim unpacked , path: ${m}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&i&&(a=Ro.basename(i));let l=Ro.join(process.cwd(),a),c=Ag(l);ps.info(`adding extension: testim zipped, path: ${l} length: ${c.length} hash: ${tu(c)} current extension count: ${e.length}`),e.push(c)}function uS(s,e,t,r,n,i,o,a){var g,y;let l=t.seleniumName||t.browserValue,c=[],d=[...xg];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Zl.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Zl.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1,"profile.password_manager_leak_detection":!1},w3c:!0};if(eu(n)){let T=_.flags.DFAcceptInsecureOrigins.getValue();typeof T=="string"&&d.push(`--unsafely-treat-insecure-origin-as-secure=${T}`),m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version=_.flags.DFBrowserVersion.getValue(),s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60}eu(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"]=Zl.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(),Cg(r,c,o),a===q.EXTENSION&&Pg(e,c,d,i,o),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[l],h={MicrosoftEdge:"ms",chrome:"goog"}[l];return ne.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=m),s}function dS(s,e,t){let r={"pdfjs.disabled":!0};return _.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":vg.join(","),"browser.helperApps.neverAsk.openFile":vg.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function us(s){return`${s.width}x${s.height}`}function bS(s){let{platform:e}=s;if(!e)return us(Sg);let t=e.split(" ")[1];return e.startsWith("Windows")&&yS.has(t)?us(fS):e==="Linux"?us(mS):e.startsWith("macOS")?us(gS):us(e==="OS X El Capitan"||e==="OS X Yosemite"?hS:Sg)}function TS(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=bS(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,Rg.cloneDeep)(t.sl);return delete i.screenResolution,t.browserValue!=="safari"&&delete i.safari_version,ut.merge(i,n,r)}return ut.merge(n,r)}return{}}function wS(s,e,t){return ut.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),{...t.bs,...s.browserstack,name:e}):{...s.browserstack,name:e}}function vS(s){return s.perfecto?s.perfecto:{}}function SS(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 ES(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=sc(i,o)),a}function ru(){return(_.flags.chromeArgsDisableFeatures.getValue()||"").split(",").filter(s=>s.trim().length)}function xo(s){var w,b,S,E;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,lambdatestService:c,mode:d}=s;if(i.mode==="local"){let A=[],D=[...xg],j={};t.headless&&D.push("--headless"),t.silentDebuggerExtensionApi&&D.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&D.push(`--remote-debugging-port=${t.remoteDebuggingPort}`);try{let R=ru();R.length&&R.forEach(x=>D.push(`--disable-features=${x}`))}catch{}return t.chromeExtraArgs&&t.chromeExtraArgs.forEach(R=>D.push(`--${R}`)),t.chromeBinaryLocation&&(j.binary=t.chromeBinaryLocation),d!==q.SELENIUM&&Pg(t,A,D,null,c),Cg(o,A,c),{logLevel:wg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:D,extensions:A,...j},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:m,driverRequestRetries:u}=t,f=ES(t,i),h={hostname:i.host,host:i.host,port:i.port||4444,path:i.path||"/wd/hub",protocol:i.protocol||"http",logLevel:wg,connectionRetryTimeout:m,connectionRetryCount:u,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!ut.isEmpty(f)&&{headers:f},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};eu(i)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,h.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(h.desiredCapabilities.nativeEvents=!1),i.user&&i.key&&(i.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=i.user,t.saucelabs.accessKey||=i.key),i.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=i.user,t.browserstack["browserstack.key"]||=i.key)),i.key&&i.type==="perfecto"&&(t.perfecto.securityToken=i.key);let g=Number(t.browserTimeout/1e3),y=t.browser||(n==null?void 0:n.browserValue);ut.merge(h.desiredCapabilities,TS(t,r,n),wS(t,r,n),vS(t),SS(t,y,g),c==null?void 0:c.getCapabilities(t,y,a,l,r,n,e,d));let T=null;switch(!t.ext&&!t.extensionPath&&((w=i.host)!=null&&w.endsWith(".testim.io"))&&!t.canary&&d===q.EXTENSION&&(y==="chrome"||y==="edge-chromium"&&_.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(T="/opt/testim-headless"),y){case"chrome":case"edge-chromium":h=pS(h,t,n,o,i,T,c,d);break;case"firefox":h=dS(h,t,c);break;case"safari":case"safari technology preview":h=lS(h,y);break;default:break}ut.merge(h.desiredCapabilities,t.seleniumCapsFileContent);try{let A={"hub.lambdatest.com":"lambdatest",[_.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},D=O=>O[i.provider]||O[h.host]||O[A[h.host]],j=O=>{var B,G;return D(O)||O[(B=h.desiredCapabilities)==null?void 0:B.browserName]||O[(G=h.desiredCapabilities)==null?void 0:G.version]||O||{}},R=JSON.parse(_.flags.addCustomCapabilities.getValue()||"{}"),x=j(j(R));Object.keys(x).length&&(ps.info(`Adding custom capabilities: ${JSON.stringify(x)}`),Object.assign(h.desiredCapabilities,x))}catch(A){ps.error("Failed to load custom capabilities",{error:A,customCapabilities:_.flags.addCustomCapabilities.getValue()})}if(h.desiredCapabilities&&!h.capabilities&&(cS(h),h.capabilities={alwaysMatch:h.desiredCapabilities,firstMatch:[{}]},delete h.desiredCapabilities),h.hostname=h.host,s.printFinalCaps){let A=(b=h.capabilities)==null?void 0:b.alwaysMatch,D=JSON.parse(JSON.stringify(h)),j=(S=D==null?void 0:D.capabilities)==null?void 0:S.alwaysMatch,R=O=>O.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(O=>{var B,G;j!=null&&j[O]&&(j[O].extensions=(G=(B=A==null?void 0:A[O])==null?void 0:B.extensions)==null?void 0:G.map(R))}),j!=null&&j.loadExtension&&(j.loadExtension=(E=A==null?void 0:A.loadExtension)==null?void 0:E.map(R));let x=require("node:util");console.log(x.inspect(D,{showHidden:!1,depth:null,colors:!0}))}return h}var Eg,Ro,Ig,ut,Rg,ps,wg,Zl,xg,tu,eu,cS,pS,vg,Sg,mS,fS,gS,hS,yS,Ao=v(()=>{"use strict";Eg=I(require("node:fs")),Ro=I(require("node:path")),Ig=I(require("node:crypto")),ut=I(require("lodash"));U();de();W();ue();ie();Io();Rg=require("lodash"),ps=P("testim-desired-capabilities-builder"),wg=hi?"debug":"silent",Zl={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},xg=["--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"],tu=(...s)=>Ig.createHash("sha256").update(s.join("")).digest("hex"),eu=s=>s.type===L.DEVICE_FARM||s.type===L.HYBRID&&s.provider==="devicefarm",cS=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=_.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{ps.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};pS=ut.memoize(uS,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(ut.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return tu(o,a,l,r,c,i)}),vg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];Sg={width:1920,height:1080},mS={width:1920,height:1200},fS={width:2560,height:1600},gS={width:2360,height:1770},hS={width:2048,height:1536},yS=new Set(["7","8","8.1","10","11"])});function Fe(s){var e,t,r,n,i,o,a,l;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||((t=s.message)==null?void 0:t.toLowerCase())==="unknown error"||((r=s.message)==null?void 0:r.match(/Unknown timeout type/))||s.name==="unknown command"||((n=s.message)==null?void 0:n.match(/did not match a known command/))||((i=s.message)==null?void 0:i.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((a=s.message)==null?void 0:a.match(/Invalid timeout type specified: ms/))||((l=s.message)==null?void 0:l.match(/\.\w* is not a function/))}function Og(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 su=v(()=>{"use strict"});function nu(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 nu(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 _g=v(()=>{"use strict"});var Lg,Dg,$t,IS,RS,Co,Ng=v(()=>{"use strict";Lg=I(require("promise-queue")),Dg=I(require("webdriverio"));de();je();U();W();jr();_g();su();ls();$t=P("WebDriverApi"),IS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},RS={implicit:0,pageLoad:1,script:2},Co=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),ac!==void 0&&(e=ac);let t=1/0;this.queue=new Lg.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(i){return this.rejectWithLog(i,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,a,l,c,d,m,u,f;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),M("right before addToQueue");let n=((o=e.capabilities.alwaysMatch)==null?void 0:o.loadExtension)||((a=e.capabilities.alwaysMatch)==null?void 0:a.loadExt)||((m=(d=(c=(l=e.capabilities.alwaysMatch)==null?void 0:l["goog:chromeOptions"])==null?void 0:c.extensions)==null?void 0:d[0])==null?void 0:m.slice(0,80)),i=(u=this.seleniumPerfStats)==null?void 0:u.markStart(xe.GET_BROWSER);try{await this.addToQueue(async()=>{$t.info("requesting browser",{testResultId:r,testName:t,extUrl:n}),M("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await Dg.remote(e),this.logGridStatus(r)}),M("after client init")}finally{(f=this.seleniumPerfStats)==null||f.markEnd(i,xe.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",i;try{i=await this.client.status();for(let a of i.nodes||[])for(let l of a.slots||[])if(((o=l==null?void 0:l.session)==null?void 0:o.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){$t.info("grid status is not supported by the grid",{testResultId:e});return}$t.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),$t.info("grid status",{gridStatusMsg:i.message,ready:i.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},i=()=>this.client.execute(e,t).catch(n),o=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return i();t=t.map(a=>{if(a===null){$t.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await o()}catch(a){if(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(xe.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,xe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(xe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Le(e)))}finally{this.seleniumPerfStats.markEnd(t,xe.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(nu,{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(Og(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[RS[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(Le(e)),await this.elementIdValue(Le(e),t)}async getViewportSize(e){let t=await this.execute(IS);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(Le(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){$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()}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return $t.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var tr={};H(tr,{getSessionPlayer:()=>Z,options:()=>ou});var Po,ou,iu,Z,we=v(()=>{"use strict";Po=require("path");W();ou={playerPath:void 0},Z=()=>{if(iu)return iu;let s=(je(),He(Be));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(nn(),He(sn)),t=e(),r=ou.playerPath?(0,Po.resolve)(ou.playerPath,"src/background/sessionPlayerInit.ts"):(0,Po.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),iu=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(Wd),n}});var Mg={};H(Mg,{doubleClick:()=>xS});var xS,Fg=v(()=>{"use strict";xS=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,i={status:"done",success:!0};window.__unloadNavigator=function(){e(i)};let o=function(u){function f(w,b,S){return S>w&&S<b}let h=u.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&f(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,T=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:T}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},c=function(u,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=o(u),h=u.event;return t.includes(h)?l(h,f.x,f.y):c(h,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(i)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var _n={};H(_n,{dispatchFocus:()=>AS});function AS(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 Ln=v(()=>{"use strict"});var Wg={};H(Wg,{WebDriver:()=>Ar});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 PS(r):void 0}catch(r){Ue.info("Error getting cdpAddress",r);return}}var ds,jg,$g,Ue,rr,CS,Ug,PS,Rr,kS,Bg,xr,Ar,Dn=v(()=>{"use strict";ds=I(require("lodash"));U();je();Ao();jg=I(require("p-retry")),$g=I(require("ua-parser-js"));jr();W();su();Ng();Y();ue();ls();Ue=P("webdriver"),[rr,CS]=[0,2],{extractElementId:Ug,getCdpAddressForHost:PS}=J,Rr=()=>(we(),He(tr)).getSessionPlayer().codeSnippets,kS=()=>(we(),He(tr)).getSessionPlayer().locatorBuilderUtils,Bg=()=>(we(),He(tr)).getSessionPlayer().utils,xr=()=>(we(),He(tr)).getSessionPlayer().positionUtils;Ar=class extends Co{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}getIgnoreVisibility(){return this.ignoreVisibility}setIgnoreVisibility(t){this.ignoreVisibility=t}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var b,S,E,A,D,j,R,x;let{overrideConfiguration:r,browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f,printFinalCaps:h,mode:g}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((E=(S=(b=n==null?void 0:n.company)==null?void 0:b.activePlan)==null?void 0:S.premiumFeatures)==null?void 0:E.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let y=xo({browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r,printFinalCaps:h,mode:g});y.desiredCapabilities&&delete y.desiredCapabilities.marionette,y.capabilities&&delete y.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let T=u?0:1500,w=u?()=>null:()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let O=await this.initClient(y,i,d);M("after initResult before getCdpAddress in init"),this.cdpUrl=await OS(O),M("after getCdpAddress in webdriver.js init"),Ue.info(`init new session testName: ${i}`,{sessionId:this.getSessionId(),testResultId:d}),await ce(T),_.flags.dontFocusOnInit.isEnabled()||await w(),M("after focus and delay in webdriver.js init")}catch(O){let B=JSON.stringify(ds.omit(y,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Ue.error("failed to init webdriver",{err:O,capabilitiesAsString:B});let G=((D=(A=n==null?void 0:n.company)==null?void 0:A.activePlan)==null?void 0:D.plan)==="free";throw(j=O.stack)!=null&&j.includes("at startWebDriverSession")&&((R=O.message)!=null&&R.startsWith("Failed to create session"))&&((x=O.message)!=null&&x.includes("Timeout awaiting 'request'"))&&G?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(O.message)?new Wr(O.message):/capabilit(y|ies)/.test(O.message)?new vi(O.message):/403 Forbidden/.test(O.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(O.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${O.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>ds.zip(i.slice(0,-1),i.slice(1)),r=this._keepAliveRequests.map(({start:i})=>i).filter(Boolean),n=t(r).map(([i,o])=>o-i);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable","not connected to DevTools"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function i(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=re();r(o);try{await this.executeJS(i),this._isAlive=!0,n("end",o),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,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=Ug(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 Si:r}}async getElement(t){var i;let r=this.seleniumPerfStats.markStart(xe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}if(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||_.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
16
|
+
4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),o}}async function Zw(){let s=Ht==="staging"?`${Ns}/Staging-LATEST_VERSION`:`${Us}/extension/sessionPlayer_LATEST_RELEASE`;return(await Mt(s)).body.toString("utf8")}function ev(){return`${Ns}/dev-sessionPlayer.zip`}async function tv(s,e){if(!Oe(s)||Oe(s)&&e||$e)return s;let t=await Zw();return`${s}-${t}${Ht==="staging"?".zip":""}`}function sl(){let s=gt();return es.resolve(s,"testim-bin")}function rv(){let s=sl();return es.resolve(s,"sessionPlayer.zip")}async function ef(s,e,t=!1){try{return await xi(s,e),await it(e,sl())}catch(r){if(t)throw r;return await ef(s,e,!0)}}async function br(s,e){Gi.info("prepare player",{location:s,canary:e});let t=rv();return Bt(async()=>{let r=Ht==="development"?ev():await tv(s,e);return await ef(r,t),{}},"preparePlayer",Zm,[s,e,t])()}var Ym,Xm,es,Qm,Gi,Zm,el,Jm,nn=v(()=>{"use strict";Ym=I(require("ms")),Xm=I(require("node:fs")),es=I(require("node:path"));de();Yt();Qm=require("serialize-error");W();Hc();Y();F();Gi=P("prepare runner and testim start"),Zm=(0,Ym.default)("0.5 day"),el=16,Jm=`The size of the custom extension is more than ${el}MB`});function sv(){let s=on.type().toLowerCase();return s==="darwin"?on.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?on.arch()==="x64"?"win64":"win32":"linux"}async function qi(){let s=sv(),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(an,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]}/${an}/${n[s]}.zip`,a=Hi.join(nl,n[s]),l=`${a}.zip`,c=Hi.join(a,i[s]);if(await ye(c))return c;if(!await ye(l)){let m=(0,il.default)("Downloading Chromium").start();try{await tf.promises.mkdir(nl),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,il.default)("Extracting Chromium").start();try{await it(l,nl)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),c}var tf,on,Hi,il,an,nl,ol=v(()=>{"use strict";tf=I(require("fs")),on=I(require("os")),Hi=I(require("path")),il=I(require("ora"));Y();F();an="1000968",nl=Hi.join(Ft,`chrome-${an}`)});async function nf(s,e){return Tr=s,ul=e,await al()}function of(s,e){Tr=e.projectId,ul=e.token,cn=e.userAccessKey,ot=s.token,un=pl(ot),pn=s.refreshToken,cl=s.ngrokToken,ll=s.isNgrokWhitelisted,rf=e.publicIp,sf=e.initializedFromCache}function iv(s=Tr,e=ul){return Bt(()=>(ln.info("request to get cli token from server"),We({url:`${he}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",nv*10,{projectId:s,token:e})()}async function ov(){ln.info("request to refresh JWT cli token from server");let s=await We({url:`${he}/auth/refreshToken`,body:{token:ot,refreshToken:pn}});return ot=s.token,un=pl(ot),s.refreshToken&&(pn=s.refreshToken),ot}async function al(){try{let s=await iv();return ln.info("successfully get cli token from server"),ot=s.token,un=pl(ot),pn=s.refreshToken,cl=s.ngrokToken,ll=s.isNgrokWhitelisted,ot}catch(s){throw s.message.includes("Unauthorized")?new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(ln.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Tr}),new C(`While trying to retrieve CLI token, caught error: ${s}`))}}function pl(s){return require("jsonwebtoken").decode(s).exp*1e3}async function At(){if(!un)return al();let s=_.flags.accessTokenExpiryMargin.getValue();if(un<Date.now()+4*s)try{return await ov()}catch(e){return ln.error("failed to refresh token, executing fallback",e),al()}return ot}function zi(){return pn}function wr(){return ot?{uid:require("jsonwebtoken").decode(ot).id,ngrokToken:cl,isNgrokWhitelisted:ll}:{}}async function Ki(){if(!cn||!Tr)return;if(await dl({userAccessKey:cn,projectId:Tr}))return cn;let e=`user access key "${cn}" is invalid for project "${Tr}"`;throw new C(e)}function Ji(){return rf}function Yi(){return sf}var ln,ot,un,pn,cl,ll,Tr,ul,cn,rf,sf,nv,at=v(()=>{"use strict";de();Ve();Yt();Y();W();ge();ue();ln=P("testim-custom-token"),Tr=null,ul=null,nv=5*60*1e3});function av(s){if(s.protocol)return s.protocol;if([L.TESTIM_PRIVATE,L.TESTIM,L.BROWSERSTACK,L.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([L.TESTIM_ENTERPRISE,L.TESTIM_LAMBDATEST,L.DEVICE_FARM].includes(s.type)){let e=af.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function cv(s){let e=af.exec(s);return e==null?void 0:e[3]}function Qi(s){var S,E,A,D,j,R,x,O,B,G,z;let e=s&&cv(s.host),t=s.port,r=s.path,n=s&&av(s),i=s.token,o=s.slotId,a=(S=s.hybrid)==null?void 0:S.tunnel,l=(E=s.external)==null?void 0:E.user,c=(A=s.external)==null?void 0:A.key,d=s.type,m=d===L.HYBRID?a&&((R=(j=(D=s.hybrid)==null?void 0:D.external)==null?void 0:j[s.hybrid.tunnel])==null?void 0:R.user):l,u=d===L.HYBRID?a&&((B=(O=(x=s.hybrid)==null?void 0:x.external)==null?void 0:O[s.hybrid.tunnel])==null?void 0:B.key):c,f=s.name,h=s&&(s._id||s.gridId),g=s.provider,y=(G=s.mobileTokens)==null?void 0:G.androidToken,T=(z=s.mobileTokens)==null?void 0:z.iosToken,w=s.apiUrl,b=s.isSupportGrid;return{host:e,port:t,path:r,protocol:n,accessToken:i,slotId:o,gridId:h,tunnel:a,user:l,key:c,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:w,isSupportGrid:b}}async function uv(s,e,t,r,n,i){var a;let o;try{o=await i()}catch(l){throw Xe.error("failed to get grid",{projectId:s,companyId:e,err:l}),new Error(ht.UNKNOWN)}if(Xe.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw Xe.error("invalid response - get grid",{res:o}),new Error(ht.UNKNOWN);if(o.status==="success"){if(o.grid.mode==="local")return{mode:"local"};((a=o.grid)==null?void 0:a.mode)==="custom"&&Object.assign(o.grid,pf(n));let l=Qi(o.grid);return lv(t,e,l.gridId,l.slotId,r,l.isSupportGrid),l}throw o.code==="not-found"?new rt(ht.NOT_FOUND):o.code==="no-available-slot"?new zt(`Failed to run test on ${r} - concurrency limit reached`):(Xe.error("invalid code error response - get grid",{res:o}),new rt(ht.UNKNOWN))}function lf(s){return bl(s)}async function uf(s,e,t){let n=(t||await lf(s)).find(i=>i._id===e);if(!n)throw new C(`Failed to find grid id: ${e}`);return Qi(n)}async function pv(s,e,t){let n=(t||await lf(s)).find(i=>(i.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new C(`Failed to find grid name: ${e}`);return Qi(n)}async function ml(s,e){let t=dn[s];if(!t)return;let{slotId:r,gridId:n,browser:i,companyId:o,isSupportGrid:a}=t;if(delete dn[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 gl(o,e,r,n,i)}catch(l){Xe.error("failed to release slot",{projectId:e,err:l})}}}async function dv(s){let e=Object.values(dn).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid){Xe.info("keep alive worker slots",{projectId:s,slots:e});try{await fl(s,e)}catch(t){Xe.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function mv(s){cf=global.setInterval(dv,1e4,s)}async function fv(s){let e=Object.keys(dn);if(e.length){Xe.warn("not all slots released before end runner flow",{projectId:s});try{await se(e,t=>ml(Number(t),s))}catch(t){Xe.error("failed to release all slots",{err:t,projectId:s})}}}async function gv(s){await fv(s),clearInterval(cf)}function hv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function yv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function pf(s){let t=(()=>Xi.isEmpty(s.testobjectSauce)?Xi.isEmpty(s.saucelabs)?Xi.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:i,protocol:o}=s,a=hv(t,s),l=yv(t,s);return{host:r,port:n,path:i,protocol:o,type:t,user:l,key:a,gridId:re()}}async function df(s,e){let t=s.company.companyId;return await uf(t,e.gridId,s.allGrids)}async function mf(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 pf(s);let c=t==null?void 0:t.companyId;if(a)return uf(c,a,e);if(l)return pv(c,l,e);if(Js(s)||s.tunnelOnlyMode){Xe.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new rt("Missing host or grid configuration")}async function ff(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 uv(o,h,r,s,t,()=>yl({projectId:o,companyId:h,browser:s,executionId:e,isRunningLocalMode:f,gridId:l,gridName:a,host:i,testResultId:n}))}var Xi,Xe,dn,af,cf,lv,mn,gf,ts=v(()=>{"use strict";Xi=I(require("lodash"));ge();W();F();ie();Y();Xe=P("grid-service"),dn={},af=/(^(https?):\/{2})?(.*)/,cf=null;lv=(s,e,t,r,n,i)=>{dn[s]={gridId:t,companyId:e,slotId:r,browser:n,isSupportGrid:i}};mn={start:mv,end:gv};gf=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,i)),a!==L.HYBRID||!i||!l||!d||!m))return e;let u=await hl({companyId:i,gridId:o,maxRetries:d,currentRetry:m,browser:l,usingTunnel:c});Xe.info("handling hybrid grid",{response:u,companyId:i});let f=Qi({...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,i)),f}});function gn(){return Zi||"master"}function hf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){Zi="master";return}if(s!=null&&s.isArchived)throw new C(`Branch ${s.branch} is archived, run aborted.`);if(s){Zi=s.branch||s;return}Zi=e?"master":void 0}var Zi,Tl=v(()=>{"use strict";Y()});function vf(s){$e||(s!=null&&s.userId||(s={anonymousId:wf}),Tf.identify(s))}function yt(s,e){return hn("ci",s,e)}function hn(s,e,t){if($e)return;let r=s?{userId:s}:{anonymousId:wf};Tf.track(Object.assign(r,{event:e,properties:t}))}var bf,Tf,wf,rs=v(()=>{"use strict";de();bf=require("@segment/analytics-node"),Tf=new bf.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1}),wf=require("crypto").randomBytes(20).toString("hex")});var Sf={};H(Sf,{isCi:()=>ss});var ss,eo=v(()=>{"use strict";ss=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});function If(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Rf({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=If({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:l,source:Ef(c,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);yt("test-run-ci",y)}function xf({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=If({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,mockNetworkEnabled:n.wasMockNetworkActivated,source:Ef(d,m),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){yt("test-run-ci-success",w);return}yt("test-run-ci-fail",{...w,failureReason:n.failureReason})}catch(w){f.error("failed to update test end analytics",{err:w})}}function Af(s){yt("batch-run-ci",s)}var Ef,wl=v(()=>{"use strict";rs();eo();Ef=(s,e)=>s!=="cli"&&s!=="cli-local"?s:ss&&e?"ci-with-user":ss?"ci":e?"cli-with-user":s});var bn,vl,bv,Sl,Tv,to,ro,so,no,io,oo=v(()=>{"use strict";F();ie();bn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===me.FAILED},vl=s=>{let{status:e}=s;return e===me.ABORTED},bv=s=>{let{status:e}=s;return e===me.PASSED},Sl=s=>s.runnerStatus===Oc.SKIPPED,Tv=s=>s.testStatus===Je.EVALUATING,to=(s,e)=>Object.values(s).filter(t=>{var r,n;return Sl(t)&&(Ye(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,ro=s=>Object.values(s).filter(e=>bn(e)&&Tv(e)).length,so=s=>Object.values(s).filter(bn),no=s=>Object.values(s).filter(bv),io=s=>Object.values(s).filter(vl)});function vv(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var El,ao,wv,co,Pf=v(()=>{"use strict";El=I(require("lodash"));W();oo();ao=P("debug-reporter"),wv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],co=class{constructor(e){this.options=e}onTestStarted(e,t){ao.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,i=r.host,o=r.gridId,a=r.type,l=r.failedGetBrowserAttempts;ao.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:i,failedGetBrowserAttempts:l,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...El.default.omit(this.options,wv),company:El.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,i,o,a){let l=vv(process.argv);ao.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=no(e).length,a=Object.keys(e).length-o;ao.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:i,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Il,Ct,Tn=v(()=>{"use strict";ie();Il=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 Il});var xl={};H(xl,{Reporter:()=>Sv});var Zt,wn,vr,lo,kf,Rl,Sv,Al=v(()=>{"use strict";Zt=I(require("chalk")),wn=I(require("lodash"));F();ie();Tn();oo();vr={success:Zt.default.green,warn:Zt.default.yellow,error:Zt.default.red},{CLI_MODE:lo}=Ut,kf="device",Rl=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t){let r=`(${e.testId})`,n=`url: ${Zt.default.underline(qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?me.PASSED:me.FAILED,n=`(${e.testId})`,i=vr[e.success?"success":"error"];console.log(i(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${Pi(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=qe(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(vr.error("Failed runs are:")),console.log(vr.error(t.join(`
|
|
17
|
+
\r`)))}onTestPlanFinished(e,t,r,n,i){let o=so(e),a=no(e),l=io(e),c=a.length,d=l.length,m=o.length,u="",f="";if(Ct.isTestStatusEnabled){let w=ro(e);u=` FAILED-EVALUATING: ${w}`,m-=w,f=` SKIPPED: ${to(e,this.options)}`}let h=this.buildTestPlanName(i,t),g,y=vr[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${Pi(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=wn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=wn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=wn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=wn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[i,n,r,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,i,o,a){let l=u=>{u.forEach((f,h)=>{var w;let g=(w=f.testData)!=null&&w.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`,T="";f.testOptimization?T=` [${f.testOptimization.reason}]`:Ye(f,this.options)&&(T="-quarantine"),console.log(" ",h+1,":",`${f.name}${T}`,y,g)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(o,n)} test plan with ${m} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===lo.APPIUM?kf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${Zt.default.underline(n)} slot from ${Zt.default.underline(r)}`)}onGetSession(e,t,r){let n=r===lo.APPIUM?kf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${Zt.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,i=this.options.mode===lo.APPIUM?"device":"browser";if(n)console.log(vr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${i} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(vr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===lo.APPIUM?"Appium":"Selenium";console.log(vr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},Sv=Rl});var kl={};H(kl,{Reporter:()=>Cv});function Ev(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function Iv(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 Rv(s){return`${s.visitedUrlsJson||""}`}async function xv(s,e,t,r,n,i){function o(u){let f=qe(s,t,u.testId,u.resultId,r),h={$:{name:Ev(u),classname:n,time:Bc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(bn(u)||vl(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=bn(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return Sl(u)&&Ye(u,i)&&Ct.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=Iv(u),h["visited-urls-json"]=Rv(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},w={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(Ct.isTestStatusEnabled){w.skipped=to(y,i);let b=ro(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 so(u).length+io(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Pl.Builder().buildObject(m)}catch(u){return Av(u)}}function Av(s){let e=new Pl.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 Pl,Of,Cl,Cv,Ol=v(()=>{"use strict";Pl=I(require("xml2js"));F();Of=require("fs");Tn();oo();Cl=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 xv(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Of.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)}};Cv=Cl});var _f={};H(_f,{Reporter:()=>Pv});function ns(s){return s?s.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var _l,Ll,Pv,Lf=v(()=>{"use strict";W();_l=P("team-city-reporter");Ll=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${r}`;return ns(n)}onTestStarted(e,t,r,n){if(r){_l.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){_l.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ns(t)}' details='${ns(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){_l.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${ns(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${ns(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ns(t)}']`)}},Pv=Ll});var Df={};H(Df,{Reporter:()=>kv});var Dl,kv,Nf=v(()=>{"use strict";Dl=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}}))}},kv=Dl});function po(s){let{platform:e}=process;e==="win32"?(0,uo.exec)(`start chrome ${s}`):e==="darwin"?(0,uo.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,uo.exec)(`google-chrome ${s}`)}var uo,Nl=v(()=>{"use strict";uo=require("child_process")});var Mf={};H(Mf,{Reporter:()=>Ov});var Ml,Ov,Uf=v(()=>{"use strict";F();Nl();Ml=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 po(t)}},Ov=Ml});var Ul,Q,Pt=v(()=>{"use strict";Pf();Ul=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 co(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Al(),xl));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(Ol(),kl));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Lf(),_f)),r.includes("console")&&Promise.resolve().then(()=>(Al(),xl)),r.includes("junit")&&Promise.resolve().then(()=>(Ol(),kl)),r.includes("json")&&Promise.resolve().then(()=>(Nf(),Df)),r.includes("chrome")&&Promise.resolve().then(()=>(Uf(),Mf))])).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 Ul});async function Fl(s,e,t){let r=is[s];if(!r)return;let{slotId:n}=r;if(delete is[s],!n){ct.warn("failed to find slot slot id",{companyId:e,workerId:s});return}ct.info("release slot id",{companyId:e,slotId:n});try{await jl(e,t,n)}catch(i){ct.error("failed to release slot",{companyId:e,err:i})}}async function _v(s,e){let t=Object.values(is).filter(Boolean);if(t.length!==0){ct.info("keep alive worker slots",{companyId:s,slots:t});try{await Wl(s,e,t)}catch(r){ct.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function Lv(s,e){Ff=global.setInterval(()=>_v(s,e),1e4)}async function Dv(s,e){let t=Object.keys(is);if(t.length){ct.warn("not all slots released before end runner flow",{companyId:s});try{await se(t,r=>Fl(Number(r),s,e))}catch(r){ct.error("failed to release all slots",{err:r,companyId:s})}}}async function Nv(s,e){await Dv(s,e),clearInterval(Ff)}async function jf(s,e,t){let r;try{r=await Bl(s,e)}catch(n){throw ct.error("failed to get slot",{companyId:s,err:n}),new Error(ht.UNKNOWN)}if(ct.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw ct.error("invalid response - get slot",{res:r}),new Error(ht.UNKNOWN);if(r.status==="success")return Bf(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new rt(ht.NOT_FOUND):r.code==="no-available-slot"?new zt("Failed to run test - concurrency limit reached"):(ct.error("invalid code error response - get slot",{res:r}),new rt(ht.UNKNOWN))}async function $f(s,e,t,r){let n=is[r];if(!n)throw new Error("slot not found");Object.assign(n,t),Bf(r,n),await $l(s,e,n),ct.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var ct,is,Ff,Bf,vn,os=v(()=>{"use strict";ge();W();F();ie();Y();ct=P("slot-service"),is={},Ff=null,Bf=(s,e)=>{is[s]=e};vn={start:Lv,end:Nv}});function Vf(s,e=process){async function t(r){await le(se(Wf,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{En.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(En.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",()=>{En.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw En.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw En.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function as(s){Wf.push(s)}var En,Wf,In=v(()=>{"use strict";W();F();En=P("process-handler"),Wf=[]});var zf={};H(zf,{installAllLazyDependencies:()=>Bv,lazyRequire:()=>lt});async function lt(s,e={}){let t=Kc(s);if(t)return t;let r;e.silent||(r=(0,Gf.default)(`Installing ${s} before first usage...`).start());try{let n=await Fv(s);return r&&r.succeed(),n}catch(n){Uv.warn("failed to install dependency lazily",{dependency:s,err:n});let i=qf(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 Fv(s){return cs.has(s)||(cs.set(s,Hf(s)),cs.get(s).catch(()=>{cs.delete(s)})),cs.get(s)}async function Hf(s){let e=Kc(s);if(e)return e;let t=qf(s),r=`${s}@${t}`;return await Wi(gt(),r),Xt(s)}async function Bv(){let s=Object.keys(cc);for(let e of s)await Hf(e)}function qf(s){let e=Object.entries(cc).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Gf,Uv,cs,Rn=v(()=>{"use strict";Gf=I(require("ora"));Zr();W();F();fi();tn();Uv=P("lazy-require"),cs=new Map});var Kf,mo,Jf=v(()=>{"use strict";Kf=require("istanbul-lib-report"),mo=class extends Kf.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 Yf,Xf,Qf,xn,bt,Zf,fo,Vl,eg,jv,tg,rg,$v,Wv,sg,Vv,Gv,Hv,qv,zv,ng,ig=v(()=>{"use strict";Yf=I(require("ora")),Xf=I(require("dayjs")),Qf=I(require("test-exclude")),xn=I(require("fs")),bt=I(require("path")),Zf=I(require("istanbul-reports")),fo=I(require("istanbul-lib-report"));ge();Y();F();W();Rn();Jf();Vl=P("test-run-status"),eg=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},jv=s=>!!eg(s).search,tg=s=>s?eg(s).pathname.substring(1):"",rg=(s,e)=>{let t=tg(e);return!new Qf.default({relativePath:!1,include:s}).shouldInstrument(t)},$v=s=>s.substring(0,s.indexOf("?")),Wv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await lt("convert-source-map");if(t==="file"&&!e)throw new C("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},sg=(s,e)=>`${bt.resolve(s,tg(e))}.js`,Vv=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await se(Object.values(t),async n=>{if(!n)return;let i=n.toObject();await se(i.sources,async(o,a)=>{if(rg(r,o))return;let l=sg(e,o);await xn.promises.mkdir(bt.parse(l).dir,{recursive:!0}),await xn.promises.writeFile(l,i.sourcesContent[a])})})},Gv={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(jv(e)&&(e=$v(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=bt.dirname(this.getPath(s));return bt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},Hv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=fo.createContext({dir:t,coverageMap:e,watermarks:fo.getDefaultWatermarks(),sourceFinder:a=>{try{let l=sg(r,a);return xn.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new mo({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:Gv}),Zf.create(a,l).execute(o)}),i},qv=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await lt("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>rg(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},zv=async(s,e)=>{let{mergeProcessCovs:r}=await lt("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await Hl(s,"testResult",`runId=${e}`)).data.docs;return await se(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await An(l,9e4);await se(c,async d=>{if(!i.has(d.url)){let m=d.text;d.sourceUrl&&(i.set(d.url,"TEMP"),m=await Gl(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}},ng=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Vl.info("start js coverage process");let n=(0,Yf.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=bt.resolve(s.codeCoverageReportPath||"./coverage"),o=bt.resolve(i,`.js/${(0,Xf.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?bt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([lt("istanbul-lib-coverage"),zv(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Vl.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await se(c.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=d.get(h),w=await Wv({sourceMapType:T,source:y,sourceMapDir:a});u[h]=w;let b=await qv(s,{source:y,sourceMap:w,functions:g});m.merge(b)}),await Vv(s,o,u);let f=await Hv(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),Vl.error(c,{err:l})}}});var og={};H(og,{SELENIUM_PERF_MARKS:()=>xe,SeleniumPerfStats:()=>Sr});var xe,Kv,Sr,ls=v(()=>{"use strict";F();xe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Kv=["ALL",...Object.values(xe)],Sr=class{constructor(){this.marks=Object.fromEntries(Kv.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`,_i(r,50)],[`${t}_P95`,_i(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var ug={};H(ug,{initServer:()=>Xv,mapFilesToLocalDrive:()=>zl});function zl(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,go[t.id]?{screenshot:go[t.id]}:{})),Object.keys(ho).forEach(t=>{s.assets||={},s.assets[lg[t]]=ho[t]}),s.assets||={},s.assets.screenshots=Object.values(go)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function Xv({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await lt("multer"),n=typeof t=="string"?t:Jv;await ql.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=Cn.join(n,m.testResultId);try{await ql.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=Cn.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,cg.default)();o.disable("x-powered-by"),o.post("/",i.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(go[d.stepId]=l.file.path),d.testResultId&&Yv.includes(d.subType)&&(ho[d.subType]||=[],ho[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 ql,ag,Cn,cg,Jv,go,ho,lg,Yv,Kl=v(()=>{"use strict";ql=I(require("fs")),ag=I(require("os")),Cn=I(require("path")),cg=I(require("express"));Y();Rn();Jv=Cn.join(ag.tmpdir(),"testim/rca/"),go={},ho={},lg={"test-log":"consoleLogs","har-file":"networkLogs"},Yv=Object.keys(lg)});var er,Jl,yo,pg=v(()=>{"use strict";er=I(require("lodash"));F();W();Jl=P("override-test-data-builder"),yo=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return er.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!er.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Jl.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(er.isObject(e.overrideAllTestsData)&&!er.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Jl.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}Jl.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return er.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let i=r.map(d=>this.generateTestUniqId(d)),o=i.indexOf(n),a=i.lastIndexOf(n),l=r[o],c=this.createNewTestItems(l,t);return r.splice(o,a-o+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let i=re();return{...e,resultId:i,testData:{value:r,index:n+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function bo(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Qe.warn("failed to run hook",{err:t}),new C(`failed to run hook promise ${t.message}`)}}var Er,Qe,Qv,Zv,eS,tS,To,dg=v(()=>{"use strict";Er=I(require("lodash"));F();ie();ts();os();ge();Y();W();Pt();In();ig();ls();Kl();de();ue();pg();Tn();Qe=P("test-run-status"),Qv=fr(),Zv=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,eS=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,tS=tt();To=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=Ks(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:yi||t.parallel||1,browser:i,gitBranch:Qv,gitCommit:Zv,gitRepoUrl:eS,runnerVersion:tS,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:w}=a,b={originalTestResultId:t,previousTestResultId:r,config:Er.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:w},Ql({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 vo(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){Qe.error("failed to upload test data artifact (runner)",{err:d})}let l=Er.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,Ir(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:i,testRetryKey:r})}async testStartReport(e,t,r){if(Ye(e,this.options))return;let n=this.exportsGlobal;try{let i=await bo(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token);return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...this.beforeSuiteParams,...i},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(i){throw Qe.error("Failed to start test",{err:i}),i}}testStartAndReport(e,t,r,n,i){let o=this.testStart(e,t,r,n);return this.testStartReport(o,t,i)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo={...t,key:void 0,user:void 0},Qe.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:i,testId:o,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Je.EVALUATING&&Ct.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Je.EVALUATING} status`);return}if(c){Q.onTestPassed(i);return}Q.onTestFailed(r,r.failureReason,qe(this.options.editorUrl,this.options.project,o,l,this.branchToUse),o,n,l)}calcResultText(e){return e.success?me.PASSED:me.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Je.QUARANTINE}`)}monitorMemoryUsage(e){let t=jc();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&&zl(o,Qe),o.resultUrl=qe(this.options.editorUrl,this.options.project,o.testId,o.resultId,this.branchToUse),o.status=this.calcResultText(t),t.status=o.status,t.name=o.name,t.testStatus=o.testStatus,t.testId||=o.testId,t.testCreatorName=o.testCreatorName,t.testCreatorEmail=o.testCreatorEmail,t.testOwnerName=o.testOwnerName,t.testOwnerEmail=o.testOwnerEmail,t.testData=o.config&&typeof o.config.testDataTotal=="number"?{total:o.config.testDataTotal,index:o.config.testDataIndex}:{},this.reportTestStatus(e,t,o,i),this.monitorMemoryUsage(o),Q.onTestFinished(o,e,i);let l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await bo(this.options.afterTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token)}catch(a){Qe.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(o=this.options.lightweightMode)!=null&&o.onlyTestIdsNoSuite?void 0:await Ir(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw Qe.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,i,o){let a=this.testEnd(e,t,r,n,i);return this.testEndReport(a,r,t,o)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:i,VIRTUAL_BUILD:o}=Dc;return e&&(n=i),Hr(t,r)&&(n=o),n}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(o=e.gridData)==null?void 0:o.type,i=t.map(a=>{var f,h,g;let l=e.browser?Xs(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=qr(_,n)&&Ys(a.nativeApp)&&!e.appId,d=Jt(e)&&(Hr(a.nativeApp,n)||c),m=Ye(a,e)||d,u={testId:a.testId,testOptimization:a.testOptimization,status:m?me.SKIPPED:me.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Je.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(c,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((h=a.testData)==null?void 0:h.total)||null,testDataIndex:((g=a.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:l.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(i)}async endKeepAlive(e,t,r){e==="redis"&&await vn.end(r,t),e==="mongo"&&await mn.end(t)}async executionStart(e,t,r,n,i){Qe.info("execution started",{executionId:e,gridId:this.execConfig.gridId,gridHost:this.execConfig.gridHost,gridName:this.execConfig.gridName,gridType:this.execConfig.gridType,parallel:this.execConfig.parallel,runnerVersion:this.execConfig.runnerVersion,source:this.execConfig.source});let{options:o}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=o;as(()=>Promise.all([this.endKeepAlive(d,t,c),wo("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,..._.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=await bo(o.beforeSuite,m),f=new yo(u,Er.cloneDeep(this.testInfoList),t);this.testInfoList=f.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:h}=this,g=[],y=[],T=[];for(let b of h){if(b.isBeforeTestPlan){g.push(b);continue}if(b.isAfterTestPlan){T.push(b);continue}y.push(b)}let w=async()=>{let b=Er.cloneDeep(this.testRunStatus);await se(Object.keys(b),async A=>{var O;let D=b[A],j=(O=D.config)==null?void 0:O.testData,R=D.testId,x=await vo(t,R,A,j,l.defaults);x&&(delete D.config.testData,D.config.testDataUrl=x)});let S=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),E=Xl({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:S,intersections:o.intersections});return this.executionStartedPromise=E,E.catch(A=>Qe.error(A)),E};try{await w()}catch(b){Qe.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:y,afterTests:T}}concatSeleniumPerfMarks(e){Er.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var d;let t=Wc(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 bo(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 ng(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await wo("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 Yl(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 Zl(s,e){var o;let t=s.canary?"-master.zip":".zip",r=`${e?kd:Us}/extension/testim-headless${t}`,n=_.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(o=s.company)==null?void 0:o.companyId,projectId:s.project,runnerEnvironment:Ht});return n||(rS.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 mg(s){let{chrome:e}=Zl(s,!1);return e}function So(s){let e=Ht==="staging"?`${Ns}/staging-sessionPlayer`:`${Us}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var rS,Pn=v(()=>{"use strict";de();ue();W();rS=P("runOptionsUtils")});function gg(s,e){if(e){if(!cS.has(e)){kn.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var hg,yg,jt,bg,Tg,wg,Eo,vg,kn,sS,nS,On,iS,oS,aS,ne,cS,Io=v(()=>{"use strict";hg=I(require("ms")),yg=I(require("p-retry")),jt=I(require("node:os")),bg=I(require("portfinder")),Tg=I(require("node:child_process"));F();Ve();ge();wg=I(require("node:fs")),Eo=I(require("node:fs/promises")),vg=require("node:path");Y();W();Pn();ie();ue();F();kn=P("lambdatestService"),sS="https://downloads.lambdatest.com/tunnel/v3",nS={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"},On=`${jt.tmpdir()}/LT`,iS=`${On}/LT`,oS=(0,hg.default)("15m"),aS="2560x1440",ne=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===L.TESTIM_LAMBDATEST||e.type===L.LAMBDATEST||e.type===L.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e,t){ne.isLambdatestGrid(e)&&(ne.lambdatestConfigPromise||=eu(t),ne.lambdatestConfig=await ne.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?oS:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ye(iS))return;let t=nS[jt.platform()+jt.arch()];if(!t)throw new Error(`tunnel on ${jt.platform()+jt.arch()} platform is not supported.`);let r=`${On}.zip`;await Ke(`${sS}/${t}`,r),await it(r,On)}static async chmodLtTunnel(e){if(!(jt.platform()==="win32"||!await ye(e))){try{await Eo.access(e,wg.constants.X_OK);return}catch{}try{await Eo.chmod(e,"777")}catch(r){throw kn.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await ce(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ne.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await bg.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,l=global.proxyUri;ne.tunnelName=re();let c=["--tunnelName",ne.tunnelName,"--infoAPIPort",String(t)];if(_.flags.enableLambdaTestTunnelNTLM.isEnabled())if(c=[...c,"--ntlm"],o&&a)c=[...c,"--ntlm-username",o,"--ntlm-password",a];else{let u=JSON.parse(_.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(c=[...c,...Fc(u)])}if(_.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(c=[...c,"--skip-upgrade"]),e.externalLambdatestUseWss&&(c=[...c,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(c=[...c,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io"]),r.tunnelUser&&r.tunnelKey)c=[...c,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&i)c=[...c,"--user",n,"--key",i];else throw new C("tunnel requires username and password");if(l)try{let u=new URL(l);c=[...c,"--proxy-host",u.hostname],u.port&&(c=[...c,"--proxy-port",u.port]),u.username&&u.password&&(c=[...c,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new C("proxy url is invalid")}e.externalLambdatestMitm&&(c=[...c,"--mitm"]),await ne.delay(3e3),await ne.chmodLtTunnel((0,vg.join)(On,"LT")),ne.tunnel=Tg.spawn("./LT",c,{cwd:On});let d="",m="";ne.tunnel.stdout.on("data",u=>{d+=u.toString()}),ne.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,yg.default)(()=>Te(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{onFailedAttempt:f=>{if(d.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});kn.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:d,stderrResult:m}),kn.error("Failed to start LT tunnel",{err:u}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!ne.tunnel))return new Promise((t,r)=>{ne.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ne.tunnel.kill()})}getCapabilities(e,t,r,n,i,o,a,l){var T,w;if(!this.isActive)return{};let c=ne.lambdatestConfig.CAPABILITIES[t]||{},d={...ne.tunnelName&&{tunnel:!0,tunnelName:ne.tunnelName}},m=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:gg(n,a==null?void 0:a.os)||gg(n,(T=o==null?void 0:o.lt)==null?void 0:T.platform)||c.platform||ne.lambdatestConfig.PLATFORM,resolution:ne.lambdatestConfig.RESOLUTION??aS,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=Zl({canary:u},!0);!h&&b[t]&&(m=[...m,b[t]]),h&&Oe(h)&&(m=[...m,h]),m.length||kn.warn("No extension was loaded in LambdaTestService",{extUrls:b,extensionPath:h})}return _.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&Oe(g)&&(m=[...m,g]),{build:r,name:`${n} - ${i}`,selenium_version:ne.lambdatestConfig.SELENIUM_VERSION,timezone:ne.lambdatestConfig.TIMEZONE,...c,...y,loadExtension:m,...d,console:!0,queueTimeout:300,network:_.flags.LTNetworkCapabilities.isEnabled(),ntlm:_.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:_.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},cS=new Set(["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey"])});function uS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Pg(s){return Rg.readFileSync(s,{encoding:"base64"})}function kg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&Oe(s))&&s){let r=Pg(s);ps.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${su(r)} current extension count: ${e.length}`),e.push(r)}}function Og(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;let i=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!i){let d=typeof s.ext=="string"?s.ext:`${__dirname}/..`,m=r||d,u=`--load-extension=${m}`;ps.info(`adding extension: testim unpacked , path: ${m}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&i&&(a=Ro.basename(i));let l=Ro.join(process.cwd(),a),c=Pg(l);ps.info(`adding extension: testim zipped, path: ${l} length: ${c.length} hash: ${su(c)} current extension count: ${e.length}`),e.push(c)}function pS(s,e,t,r,n,i,o,a){var g,y;let l=t.seleniumName||t.browserValue,c=[],d=[...Cg];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":tu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":tu.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1,"profile.password_manager_leak_detection":!1},w3c:!0};if(ru(n)){let T=_.flags.DFAcceptInsecureOrigins.getValue();typeof T=="string"&&d.push(`--unsafely-treat-insecure-origin-as-secure=${T}`),m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version=_.flags.DFBrowserVersion.getValue(),s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60}ru(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"]=tu.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+_c.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),kg(r,c,o),a===q.EXTENSION&&Og(e,c,d,i,o),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[l],h={MicrosoftEdge:"ms",chrome:"goog"}[l];return ne.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=m),s}function mS(s,e,t){let r={"pdfjs.disabled":!0};return _.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":Eg.join(","),"browser.helperApps.neverAsk.openFile":Eg.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function us(s){return`${s.width}x${s.height}`}function TS(s){let{platform:e}=s;if(!e)return us(Ig);let t=e.split(" ")[1];return e.startsWith("Windows")&&bS.has(t)?us(gS):e==="Linux"?us(fS):e.startsWith("macOS")?us(hS):us(e==="OS X El Capitan"||e==="OS X Yosemite"?yS:Ig)}function wS(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=TS(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,Ag.cloneDeep)(t.sl);return delete i.screenResolution,t.browserValue!=="safari"&&delete i.safari_version,ut.merge(i,n,r)}return ut.merge(n,r)}return{}}function vS(s,e,t){return ut.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),{...t.bs,...s.browserstack,name:e}):{...s.browserstack,name:e}}function SS(s){return s.perfecto?s.perfecto:{}}function ES(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 IS(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=ic(i,o)),a}function nu(){return(_.flags.chromeArgsDisableFeatures.getValue()||"").split(",").filter(s=>s.trim().length)}function xo(s){var w,b,S,E;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,lambdatestService:c,mode:d}=s;if(i.mode==="local"){let A=[],D=[...Cg],j={};t.headless&&D.push("--headless"),t.silentDebuggerExtensionApi&&D.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&D.push(`--remote-debugging-port=${t.remoteDebuggingPort}`);try{let R=nu();R.length&&R.forEach(x=>D.push(`--disable-features=${x}`))}catch{}return t.chromeExtraArgs&&t.chromeExtraArgs.forEach(R=>D.push(`--${R}`)),t.chromeBinaryLocation&&(j.binary=t.chromeBinaryLocation),d!==q.SELENIUM&&Og(t,A,D,null,c),kg(o,A,c),{logLevel:Sg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:D,extensions:A,...j},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:m,driverRequestRetries:u}=t,f=IS(t,i),h={hostname:i.host,host:i.host,port:i.port||4444,path:i.path||"/wd/hub",protocol:i.protocol||"http",logLevel:Sg,connectionRetryTimeout:m,connectionRetryCount:u,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!ut.isEmpty(f)&&{headers:f},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};ru(i)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,h.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(h.desiredCapabilities.nativeEvents=!1),i.user&&i.key&&(i.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=i.user,t.saucelabs.accessKey||=i.key),i.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=i.user,t.browserstack["browserstack.key"]||=i.key)),i.key&&i.type==="perfecto"&&(t.perfecto.securityToken=i.key);let g=Number(t.browserTimeout/1e3),y=t.browser||(n==null?void 0:n.browserValue);ut.merge(h.desiredCapabilities,wS(t,r,n),vS(t,r,n),SS(t),ES(t,y,g),c==null?void 0:c.getCapabilities(t,y,a,l,r,n,e,d));let T=null;switch(!t.ext&&!t.extensionPath&&((w=i.host)!=null&&w.endsWith(".testim.io"))&&!t.canary&&d===q.EXTENSION&&(y==="chrome"||y==="edge-chromium"&&_.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(T="/opt/testim-headless"),y){case"chrome":case"edge-chromium":h=dS(h,t,n,o,i,T,c,d);break;case"firefox":h=mS(h,t,c);break;case"safari":case"safari technology preview":h=uS(h,y);break;default:break}ut.merge(h.desiredCapabilities,t.seleniumCapsFileContent);try{let A={"hub.lambdatest.com":"lambdatest",[_.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},D=O=>O[i.provider]||O[h.host]||O[A[h.host]],j=O=>{var B,G;return D(O)||O[(B=h.desiredCapabilities)==null?void 0:B.browserName]||O[(G=h.desiredCapabilities)==null?void 0:G.version]||O||{}},R=JSON.parse(_.flags.addCustomCapabilities.getValue()||"{}"),x=j(j(R));Object.keys(x).length&&(ps.info(`Adding custom capabilities: ${JSON.stringify(x)}`),Object.assign(h.desiredCapabilities,x))}catch(A){ps.error("Failed to load custom capabilities",{error:A,customCapabilities:_.flags.addCustomCapabilities.getValue()})}if(h.desiredCapabilities&&!h.capabilities&&(lS(h),h.capabilities={alwaysMatch:h.desiredCapabilities,firstMatch:[{}]},delete h.desiredCapabilities),h.hostname=h.host,s.printFinalCaps){let A=(b=h.capabilities)==null?void 0:b.alwaysMatch,D=JSON.parse(JSON.stringify(h)),j=(S=D==null?void 0:D.capabilities)==null?void 0:S.alwaysMatch,R=O=>O.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(O=>{var B,G;j!=null&&j[O]&&(j[O].extensions=(G=(B=A==null?void 0:A[O])==null?void 0:B.extensions)==null?void 0:G.map(R))}),j!=null&&j.loadExtension&&(j.loadExtension=(E=A==null?void 0:A.loadExtension)==null?void 0:E.map(R));let x=require("node:util");console.log(x.inspect(D,{showHidden:!1,depth:null,colors:!0}))}return h}var Rg,Ro,xg,ut,Ag,ps,Sg,tu,Cg,su,ru,lS,dS,Eg,Ig,fS,gS,hS,yS,bS,Ao=v(()=>{"use strict";Rg=I(require("node:fs")),Ro=I(require("node:path")),xg=I(require("node:crypto")),ut=I(require("lodash"));F();de();W();ue();ie();Io();Ag=require("lodash"),ps=P("testim-desired-capabilities-builder"),Sg=hi?"debug":"silent",tu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Cg=["--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"],su=(...s)=>xg.createHash("sha256").update(s.join("")).digest("hex"),ru=s=>s.type===L.DEVICE_FARM||s.type===L.HYBRID&&s.provider==="devicefarm",lS=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=_.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{ps.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};dS=ut.memoize(pS,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(ut.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return su(o,a,l,r,c,i)}),Eg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];Ig={width:1920,height:1080},fS={width:1920,height:1200},gS={width:2560,height:1600},hS={width:2360,height:1770},yS={width:2048,height:1536},bS=new Set(["7","8","8.1","10","11"])});function Ue(s){var e,t,r,n,i,o,a,l;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||((t=s.message)==null?void 0:t.toLowerCase())==="unknown error"||((r=s.message)==null?void 0:r.match(/Unknown timeout type/))||s.name==="unknown command"||((n=s.message)==null?void 0:n.match(/did not match a known command/))||((i=s.message)==null?void 0:i.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((a=s.message)==null?void 0:a.match(/Invalid timeout type specified: ms/))||((l=s.message)==null?void 0:l.match(/\.\w* is not a function/))}function Lg(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 iu=v(()=>{"use strict"});function ou(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 ou(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 Dg=v(()=>{"use strict"});var Ng,Mg,$t,RS,xS,Co,Ug=v(()=>{"use strict";Ng=I(require("promise-queue")),Mg=I(require("webdriverio"));de();je();F();W();jr();Dg();iu();ls();$t=P("WebDriverApi"),RS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},xS={implicit:0,pageLoad:1,script:2},Co=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),lc!==void 0&&(e=lc);let t=1/0;this.queue=new Ng.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(i){return this.rejectWithLog(i,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,a,l,c,d,m,u,f;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),M("right before addToQueue");let n=((o=e.capabilities.alwaysMatch)==null?void 0:o.loadExtension)||((a=e.capabilities.alwaysMatch)==null?void 0:a.loadExt)||((m=(d=(c=(l=e.capabilities.alwaysMatch)==null?void 0:l["goog:chromeOptions"])==null?void 0:c.extensions)==null?void 0:d[0])==null?void 0:m.slice(0,80)),i=(u=this.seleniumPerfStats)==null?void 0:u.markStart(xe.GET_BROWSER);try{await this.addToQueue(async()=>{$t.info("requesting browser",{testResultId:r,testName:t,extUrl:n}),M("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await Mg.remote(e),this.logGridStatus(r)}),M("after client init")}finally{(f=this.seleniumPerfStats)==null||f.markEnd(i,xe.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",i;try{i=await this.client.status();for(let a of i.nodes||[])for(let l of a.slots||[])if(((o=l==null?void 0:l.session)==null?void 0:o.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){$t.info("grid status is not supported by the grid",{testResultId:e});return}$t.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),$t.info("grid status",{gridStatusMsg:i.message,ready:i.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},i=()=>this.client.execute(e,t).catch(n),o=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return i();t=t.map(a=>{if(a===null){$t.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await o()}catch(a){if(Ue(a))return this.unsupportedActions.add("execute"),i();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),i=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await i()}catch(o){if(Ue(o))return this.unsupportedActions.add("executeAsync"),n();throw o}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(xe.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,xe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(xe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Le(e)))}finally{this.seleniumPerfStats.markEnd(t,xe.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(ou,{ELEMENT:e,[Gt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Ue(n))return this.unsupportedActions.add("elementIdDisplayed"),r();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(Lg(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[xS[e]]=t,this.client.setTimeouts(...i)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(i){if(Ue(i))return this.unsupportedActions.add("timeouts"),n();throw i}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,i){window.scrollTo(n,i)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(Le(e)),await this.elementIdValue(Le(e),t)}async getViewportSize(e){let t=await this.execute(RS);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(Le(e))})}submitFormManually(e){return this.addToQueue(async()=>{var i;let t=await((i=this.client)==null?void 0:i.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(async()=>{if(!this.client)throw new Error("The client is not initialized");let i=await this.client.$(e);await this.client.action("pointer").move({origin:i}).perform()})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let i=Math.abs(e.width),o=Math.abs(e.height);r=async()=>await this.client.setWindowSize(i,o),n=async()=>await this.client._setWindowSize(i,o)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(i){if(Ue(i))return this.unsupportedActions.add("windowHandleSize"),r();throw i}})}}setCookie(e,t,r,n,i,o,a){return this.addToQueue(()=>{var l;return(l=this.client)==null?void 0:l.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:i,path:o,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){$t.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return $t.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var tr={};H(tr,{getSessionPlayer:()=>Z,options:()=>cu});var Po,cu,au,Z,we=v(()=>{"use strict";Po=require("path");W();cu={playerPath:void 0},Z=()=>{if(au)return au;let s=(je(),He(Be));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(nn(),He(sn)),t=e(),r=cu.playerPath?(0,Po.resolve)(cu.playerPath,"src/background/sessionPlayerInit.ts"):(0,Po.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),au=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(Gd),n}});var Fg={};H(Fg,{doubleClick:()=>AS});var AS,Bg=v(()=>{"use strict";AS=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,i={status:"done",success:!0};window.__unloadNavigator=function(){e(i)};let o=function(u){function f(w,b,S){return S>w&&S<b}let h=u.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&f(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,T=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:T}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},c=function(u,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=o(u),h=u.event;return t.includes(h)?l(h,f.x,f.y):c(h,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(i)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var _n={};H(_n,{dispatchFocus:()=>CS});function CS(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 Ln=v(()=>{"use strict"});var Gg={};H(Gg,{WebDriver:()=>Ar});async function _S(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 kS(r):void 0}catch(r){Fe.info("Error getting cdpAddress",r);return}}var ds,Wg,Vg,Fe,rr,PS,jg,kS,Rr,OS,$g,xr,Ar,Dn=v(()=>{"use strict";ds=I(require("lodash"));F();je();Ao();Wg=I(require("p-retry")),Vg=I(require("ua-parser-js"));jr();W();iu();Ug();Y();ue();ls();Fe=P("webdriver"),[rr,PS]=[0,2],{extractElementId:jg,getCdpAddressForHost:kS}=J,Rr=()=>(we(),He(tr)).getSessionPlayer().codeSnippets,OS=()=>(we(),He(tr)).getSessionPlayer().locatorBuilderUtils,$g=()=>(we(),He(tr)).getSessionPlayer().utils,xr=()=>(we(),He(tr)).getSessionPlayer().positionUtils;Ar=class extends Co{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}getIgnoreVisibility(){return this.ignoreVisibility}setIgnoreVisibility(t){this.ignoreVisibility=t}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var b,S,E,A,D,j,R,x;let{overrideConfiguration:r,browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f,printFinalCaps:h,mode:g}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((E=(S=(b=n==null?void 0:n.company)==null?void 0:b.activePlan)==null?void 0:S.premiumFeatures)==null?void 0:E.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let y=xo({browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r,printFinalCaps:h,mode:g});y.desiredCapabilities&&delete y.desiredCapabilities.marionette,y.capabilities&&delete y.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let T=u?0:1500,w=u?()=>null:()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let O=await this.initClient(y,i,d);M("after initResult before getCdpAddress in init"),this.cdpUrl=await _S(O),M("after getCdpAddress in webdriver.js init"),Fe.info(`init new session testName: ${i}`,{sessionId:this.getSessionId(),testResultId:d}),await ce(T),_.flags.dontFocusOnInit.isEnabled()||await w(),M("after focus and delay in webdriver.js init")}catch(O){let B=JSON.stringify(ds.omit(y,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Fe.error("failed to init webdriver",{err:O,capabilitiesAsString:B});let G=((D=(A=n==null?void 0:n.company)==null?void 0:A.activePlan)==null?void 0:D.plan)==="free";throw(j=O.stack)!=null&&j.includes("at startWebDriverSession")&&((R=O.message)!=null&&R.startsWith("Failed to create session"))&&((x=O.message)!=null&&x.includes("Timeout awaiting 'request'"))&&G?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(O.message)?new Wr(O.message):/capabilit(y|ies)/.test(O.message)?new vi(O.message):/403 Forbidden/.test(O.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(O.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${O.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>ds.zip(i.slice(0,-1),i.slice(1)),r=this._keepAliveRequests.map(({start:i})=>i).filter(Boolean),n=t(r).map(([i,o])=>o-i);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable","not connected to DevTools"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function i(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=re();r(o);try{await this.executeJS(i),this._isAlive=!0,n("end",o),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Fe.warn("close unexpected alert open"),await this.alertAccept().catch(l=>Fe.warn("failed to click on alert",{err:l}));return}if(Fe.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;Fe.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:l,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=l&&this.browserClosedCallbacks.forEach(c=>{try{c(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=jg(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 Si:r}}async getElement(t){var i;let r=this.seleniumPerfStats.markStart(xe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}if(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||_.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
18
18
|
var fn = ${Rr().getLocatedElementCode};
|
|
19
19
|
return fn.apply(null, arguments);
|
|
20
20
|
`,t)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}}executeJS(t,...r){return this.execute(t,...r)}async executeCodeAsync(t,r,...n){return await this.timeouts("script",r),await this.executeAsync(t,...n)}async markDynamicParent(t,r){function n({attributeName:i,attributeValue:o,locatedElement:a}){let l=getLocatedElement(a);if(!l)throw new Error("could not find dynamic parent");l.setAttribute(i,o)}await this.executeJS(`
|
|
21
21
|
var getLocatedElement = ${Rr().getLocatedElementCode};
|
|
22
22
|
var setDynamicParentAttribute = ${n.toString()};
|
|
23
23
|
return setDynamicParentAttribute.apply(null, arguments)
|
|
24
|
-
`,{attributeName:
|
|
24
|
+
`,{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(`
|
|
25
25
|
const getLocatedElement = ${Rr().getLocatedElementCode};
|
|
26
26
|
const getLocation = ${r.toString()};
|
|
27
27
|
return getLocation.apply(null, arguments)
|
|
@@ -33,22 +33,22 @@ Testim had missing write access to ${r||e}
|
|
|
33
33
|
const getLocatedElement = ${Rr().getLocatedElementCode};
|
|
34
34
|
const extractText = ${r.toString()};
|
|
35
35
|
return extractText.apply(null, arguments)
|
|
36
|
-
`,t,this.ignoreHiddenTagsText);return n}async getHTML(t){var i,o;let r=Rr().getHtmlCode(void 0,t),n=this.seleniumPerfStats.markStart(xe.GET_HTML);try{let{value:a}=await this.executeJS(r);return this.seleniumPerfStats.markEnd(n,xe.GET_HTML),a}catch(a){this.seleniumPerfStats.markEnd(n,xe.GET_HTML);let l=Object.assign(new Error(""),{success:!1,reason:a.toString(),errorType:"internal-error"});throw(o=(i=this.client)==null?void 0:i.requestHandler)!=null&&o.sessionID||Object.assign(l,{extraInfo:"Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated"}),l}}maximizeWithoutValidation(){return this.windowHandleMaximize()}setViewportSizeNEW(t,r){class i extends Error{}function o(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}}let a=()=>(0,
|
|
36
|
+
`,t,this.ignoreHiddenTagsText);return n}async getHTML(t){var i,o;let r=Rr().getHtmlCode(void 0,t),n=this.seleniumPerfStats.markStart(xe.GET_HTML);try{let{value:a}=await this.executeJS(r);return this.seleniumPerfStats.markEnd(n,xe.GET_HTML),a}catch(a){this.seleniumPerfStats.markEnd(n,xe.GET_HTML);let l=Object.assign(new Error(""),{success:!1,reason:a.toString(),errorType:"internal-error"});throw(o=(i=this.client)==null?void 0:i.requestHandler)!=null&&o.sessionID||Object.assign(l,{extraInfo:"Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated"}),l}}maximizeWithoutValidation(){return this.windowHandleMaximize()}setViewportSizeNEW(t,r){class i extends Error{}function o(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}}let a=()=>(0,Wg.default)(async()=>{let{value:c}=await this.windowHandleSize(),{value:d}=await this.execute(o),m=c.width-d.screenWidth,u=c.height-d.screenHeight;await this.windowHandleSize({width:t.width+m,height:t.height+u});let{value:f}=await this.execute(o);if(f.screenWidth!==t.width||f.screenHeight!==t.height)throw new i},{retries:5-1,factor:1,minTimeout:0}).catch(c=>{if(!(c instanceof i))throw c});if(typeof t!="object"||typeof t.width!="number"||typeof t.height!="number"||r!==void 0&&typeof r!="boolean")throw new Error("number or type of arguments don't agree with setViewportSize command");return(r===void 0?!0:r)?a():this.windowHandleSize(t)}setViewportSize(t,r){return this.setViewportSizeNEW({width:t,height:r},!0)}getBrowserMajorVersion(t){var r;try{return parseInt(((r=t.browser)==null?void 0:r.version)||"0",10)}catch(n){return Fe.error("failed to get browser version",{err:n}),0}}async getBrowserAndOS(){function t(a){let l=a.match(/(opera|chrome|safari|firefox)\/?\s*(\d+)/i)||[];if(l[1]==="Chrome"&&a.match(/\bOPR\/(\d+)/)!==null)return"opera";if(l[1]==="Chrome"&&a.match(/\bEdge|Edg\/(\d+)/)!==null)return"edge";l=l[2]?[l[1],l[2]]:[a.appName,a.appVersion,"-?"];let c=a.match(/version\/(\d+)/i);return c!==null&&l.splice(1,1,c[1]),l[0].toLowerCase()}if(this.browserAndOS)return this.browserAndOS;function r(){var a;return(a=window==null?void 0:window.navigator)!=null&&a.userAgent?window.navigator.userAgent:"unknown"}let{value:n}=await this.executeJS(r),i=(0,Vg.default)(n),o=i.os;return this.browserAndOS={os:`${o.name} ${o.version}`,browserMajor:this.getBrowserMajorVersion(i),browser:t(n),userAgent:n,browserVersion:i.browser.version},this.browserAndOS}setValue(t,r){return super.setValue(t,r)}getRelativeMoveActions(t,r){let{rect:n,clickOffset:i}=t,o=xr().calculateElementMiddlePoint(n),a=i.x,l=i.y;return!$g().isWithinBounds(n.left,n.left+n.width,o.x+a)||!$g().isWithinBounds(n.top,n.top+n.height,o.y+l)?(Fe.warn("using element center as fallback for offset"),this.getMoveActions(0,0,r)):this.getMoveActions(a,l,r)}computeAbsoluteMovement(t){let{frameOffset:r,rect:n,clickOffset:i}=t,o=n.left+i.x+r.x,a=n.top+i.y+r.y;return{x:o,y:a}}async actWithActionsAPI(t,r,n,i){let o=this.getRelativeMoveActions(t,n),a=this.getClickActions(i,r);try{return await this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:o.concat(a)}])}catch(l){Fe.error("tried to use element origin but failed because of visibility, trying absolute",l);let{x:c,y:d}=this.computeAbsoluteMovement(t),m=this.getMoveActions(c,d);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:m.concat(a)}])}}doubleClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,rr,t,["pointerDown","pointerUp","pointerDown","pointerUp"])}async doubleClickWithJS(t){let[{doubleClick:r},{dispatchFocus:n}]=await Promise.all([Promise.resolve().then(()=>(Bg(),Fg)),Promise.resolve().then(()=>(Ln(),_n))]);return this.executeCodeAsync(`
|
|
37
37
|
var getLocatedElement = ${Rr().getLocatedElementCode};
|
|
38
38
|
var dispatchFocus = ${n.toString()};
|
|
39
39
|
var doubleClick = ${r.toString()};
|
|
40
40
|
var eventData = arguments[0];
|
|
41
41
|
var done = arguments[1];
|
|
42
42
|
return doubleClick.call(null, eventData, done);
|
|
43
|
-
`,t.timeout,t)}getClickActions(t=[],r=void 0){return t.map(n=>({type:n,button:r}))}getClickActionList(t=[],r=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,r)}]}leftClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,rr,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,
|
|
44
|
-
var res = requireOrImportMethod('${
|
|
43
|
+
`,t.timeout,t)}getClickActions(t=[],r=void 0){return t.map(n=>({type:n,button:r}))}getClickActionList(t=[],r=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,r)}]}leftClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,rr,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,PS,t,["pointerDown","pointerUp"])}async rightClick(t,r){if(this.unsupportedActions.has("move"))return this.rightClickWithActionsAPI(t,r);try{return await super._rightClick(t,r)}catch(n){if(Ue(n))return this.unsupportedActions.add("move"),this.rightClickWithActionsAPI(t,r);throw n}}async leftClick(t,r){if(this.unsupportedActions.has("move"))return this.leftClickWithActionsAPI(t,r);try{return await super._leftClick(t,r)}catch(n){if(Ue(n))return this.unsupportedActions.add("move"),this.leftClickWithActionsAPI(t,r);throw n}}async dragAndDropOldAPI(t,r){return await this.moveTo(t),await this.buttonDown(),await this.moveTo(r),await this.buttonUp()}async calculateElementMiddlePoint(t,r={top:0,left:0}){let n=await this.getLocatedElementRect(t);if(!(n!=null&&n.value))throw Fe.warn(`could not find element for locatedElement ${t==null?void 0:t.testimId}`),new Error("could not calculate rect");let{x:i,y:o,width:a,height:l}=n.value;return{x:r.left+i+a/2,y:r.top+o+l/2}}async hover(t,r){if(this.unsupportedActions.has("move"))return this.moveToElementWithActionsAPI(t,r);let{x:n,y:i}=r.clickOffset;try{return await this.moveTo(t,n,i)}catch(o){if(Ue(o))return this.unsupportedActions.add("move"),this.moveToElementWithActionsAPI(t,r);throw o}}getMoveActions(t=1,r=1,n="viewport",i=0){return[{type:"pointerMove",duration:i,x:Math.floor(t)||1,y:Math.floor(r)||1,origin:n}]}moveWithActionsAPI(t){let r=this.getMoveActions(t.x,t.y);return this.actions([{type:"pointer",id:"mouse",actions:r}])}async moveToElementWithActionsAPI(t,r){try{return await this.actions([{type:"pointer",id:"mouse",actions:this.getRelativeMoveActions(r,t)}])}catch(n){Fe.error("tried to use element origin but failed because of visibility, trying location",n);let i=this.computeAbsoluteMovement(r);return await this.moveWithActionsAPI(i)}}getDragCoordinates(t){let r=t.filter(o=>o.event==="mousemove"||o.event==="pointermove"),n=r[0].pointerPosition,i=r.at(-1).pointerPosition;return{xDiff:i.screenX-n.screenX,yDiff:i.screenY-n.screenY}}async dragWithMoveTo(t,r,n,i,o){return await this.moveTo(t,i,o),await this.buttonDown(),await this.moveTo(t,r,n),await this.buttonUp()}dragWithActionsAPI(t,r,n,i,o){let a=this.getMoveActions(i,o,t,1),l=this.getClickActions(["pointerDown"],rr),c=this.getMoveActions(r,n,"pointer",1),d=this.getClickActions(["pointerUp"],rr);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(l).concat(c).concat(d)}])}async drag(t,r,n,i,o){let{width:a,height:l}=r,c=n-a/2+1,d=i-l/2,m=this.getDragCoordinates(o),{xDiff:u,yDiff:f}=m;if(this.unsupportedActions.has("move"))return this.dragWithActionsAPI(t,u,f,c,d);try{return await this.dragWithMoveTo(t,u,f,c,d)}catch(h){if(Ue(h))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,u,f,c,d);throw h}}getMoveRelativeSequence(t,r,n,i){let o=(u,f)=>Math.hypot(u.x-f.x,u.y-f.y),a={x:t,y:r},l={x:n,y:i},c=10,d=Math.round(o(a,l)/c),m=Array.from({length:d},()=>({x:Math.round((l.x-a.x)/d),y:Math.round((l.y-a.y)/d)}));return[{x:1,y:1}].concat(m)}getMoveAbsoluteSequence(t,r,n,i){return this.getMoveRelativeSequence(t,r,n,i).reduce((a,l)=>{let c=a.at(-1);return a.concat({x:Math.round(c.x+l.x),y:Math.round(c.y+l.y)})},[{x:Math.round(t),y:Math.round(r)}])}async dragAndDropWithGeneratedMoves(t,r,n){let{fromRect:i,fromX:o,fromY:a,toRect:l,toX:c,toY:d}=n,m=xr().calculateElementMiddlePoint(i),u=xr().calculateElementMiddlePoint(l),f=this.getMoveRelativeSequence(m.x+o,m.y+a,u.x+c,u.y+d);await this.moveTo(t,Math.floor(o),Math.floor(a)),await this.buttonDown();for(let h of f)await this.moveTo(null,h.x,h.y);return await this.moveTo(r,Math.round(c),Math.round(d)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:l}=t,c=xr().calculateElementMiddlePoint(r),d=xr().calculateElementMiddlePoint(o),m=Math.floor(c.x+n),u=Math.floor(c.y+i),f=Math.floor(d.x+a),h=Math.floor(d.y+l),g=this.getMoveAbsoluteSequence(m,u,f,h),y=this.getMoveActions(m,u),T=this.getClickActions(["pointerDown"],rr),w=ds.flatMap(g,A=>this.getMoveActions(A.x,A.y)),b=this.getMoveActions(f,h),S=this.getClickActions(["pointerUp"],rr),E=y.concat(T).concat(w).concat(b).concat(S);return this.actions([{type:"pointer",id:"mouse",actions:E}])}async dragAndDrop(t,r,n){if(this.isSafari()){if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPIWithGeneratedMoves(n);try{return await this.dragAndDropWithGeneratedMoves(t,r,n)}catch(i){if(Ue(i))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPIWithGeneratedMoves(n);throw i}}if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPI(n);try{return await this.dragAndDropOldAPI(t,r)}catch(i){if(Ue(i))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPI(n);throw i}}doubleClickFallback(t,r,n){return this.isSafari()?this.doubleClickWithJS(r):this.doubleClickWithActionsAPI(t,n)}async doubleClick(t,r,n){if(this.unsupportedActions.has("move")||this.isSafari())return this.doubleClickFallback(t,r,n);try{return await this.doDoubleClick(t)}catch(i){if(Ue(i))return this.unsupportedActions.add("move"),this.doubleClickFallback(t,r,n);throw i}}async dragAndDropWithActionsAPI(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:l}=t,c=xr().calculateElementMiddlePoint(r),d=xr().calculateElementMiddlePoint(o),m=Math.floor(c.x+n),u=Math.floor(c.y+i),f=Math.floor(d.x+a),h=Math.floor(d.y+l);await this.moveWithActionsAPI({x:m,y:u});let g=this.getClickActionList(["pointerDown"],rr);await this.actions(g),await this.moveWithActionsAPI({x:f,y:h});let y=this.getClickActionList(["pointerUp"],rr);return this.actions(y)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(jg(t));return r}getSource(){return this.source()}async getElementRect(t){let r={width:0,height:0,top:0,left:0},n;try{n=await this.getElementLocation(t)}catch(i){Fe.error("error getting element location",{err:i})}return n!=null&&n.value?{top:n.value.y,left:n.value.x,width:n.value.width,height:n.value.height}:r}async end(){Fe.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||Fe.warn("failed to close session because session is undefined"),this.stopKeepAliveInterval();try{return await super.end()}catch{return}}async submit(t){if(this.unsupportedActions.has("submit"))return await super.submitFormManually(t);try{return await super.submitForm(t)}catch(r){if(Ue(r))return this.unsupportedActions.add("submit"),super.submitFormManually(t);throw r}}}});var lu,uu,Nn,pu=v(()=>{"use strict";W();ue();ge();lu=P("lab-features-service"),uu=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(lu.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await du(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){lu.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=_.flags[e];this.validateAsLabFeatureFlag(t);let r=t.getValue();if(r==="disabled")return!1;if(r==="enabled")return!0;let{featuresForProject:n,labBatman:i}=this,o=n.find(l=>l.featureFlagName===e),a=o==null?void 0:o.enabled;return Boolean(i&&a)}isLabsEnabledForCompany(e){var t;return Boolean((t=e==null?void 0:e.premiumFeatures)==null?void 0:t.enableLabFeatures)}validateAsLabFeatureFlag(e){if("getValue"in e)return;let t=`Attempted querying a lab feature flag which isn't a variant. This means that a wrong configuration is being used in FeatureFlagsService (for feature flag: ${e.name}`;throw lu.error(t,{featureFlagName:e.name}),new Error(t)}},Nn=new uu});function LS(s){let e=s.startsWith("\\\\?\\"),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function DS(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 NS(s){let e=Object.getPrototypeOf(async()=>null).constructor;function t(){return e.apply(null,s)}return t.prototype=e.prototype,new t}async function MS(s,e,t,r,n={},i=void 0,o=void 0){let a=Object.keys(n).map(h=>`
|
|
44
|
+
var res = requireOrImportMethod('${LS(n[h])}');
|
|
45
45
|
if (res.sync) {
|
|
46
46
|
var ${h} = res.lib;
|
|
47
47
|
} else {
|
|
48
48
|
var ${h} = await res.lib;
|
|
49
49
|
}
|
|
50
50
|
`).join(""),l=o?`
|
|
51
|
-
${
|
|
51
|
+
${zg.default.toString()}
|
|
52
52
|
var fileBuffer = dataUriToBuffer('${o}');
|
|
53
53
|
`:"var fileBuffer = null;",c=`
|
|
54
54
|
const getMessage = arguments => {
|
|
@@ -104,7 +104,7 @@ Testim had missing write access to ${r||e}
|
|
|
104
104
|
});
|
|
105
105
|
`,d=`
|
|
106
106
|
function injectCode(params, args, incomingParams, context, code) {
|
|
107
|
-
const constructWithArguments = ${
|
|
107
|
+
const constructWithArguments = ${NS.toString()}
|
|
108
108
|
|
|
109
109
|
const resolve = result => {
|
|
110
110
|
parentPort.postMessage({
|
|
@@ -170,7 +170,7 @@ Testim had missing write access to ${r||e}
|
|
|
170
170
|
// A hack to fix an issue with stringified functions which use require. when compiling to JS, calls to require change to __require.
|
|
171
171
|
const __require = require;
|
|
172
172
|
const { parentPort } = require('worker_threads');
|
|
173
|
-
const requireOrImportMethod = ${
|
|
173
|
+
const requireOrImportMethod = ${DS.toString()}
|
|
174
174
|
|
|
175
175
|
// requireCode will set async to be true if needed.
|
|
176
176
|
${a}
|
|
@@ -179,7 +179,7 @@ Testim had missing write access to ${r||e}
|
|
|
179
179
|
|
|
180
180
|
${c}
|
|
181
181
|
|
|
182
|
-
const isPromise = ${
|
|
182
|
+
const isPromise = ${bc.toString()}
|
|
183
183
|
|
|
184
184
|
parentPort.once('message', input => {
|
|
185
185
|
const { incomingParams, context, code } = input;
|
|
@@ -208,73 +208,73 @@ Testim had missing write access to ${r||e}
|
|
|
208
208
|
injectCode(params, args, incomingParams, context, code);
|
|
209
209
|
});
|
|
210
210
|
})();
|
|
211
|
-
`,u=[],f=new
|
|
212
|
-
Action required: Please allow opening a websockets connection to ${he} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{Lo.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let r={query:{projectId:e},requestTimeout:nh,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${he}/${t}`,this._socket=gu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:nh,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${he}/${t}`,this._socket=gu.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,ih.default)(()=>le(n(),JS),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Lo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var oh={};H(oh,{remoteStepServiceSocketIO:()=>YS});var yu,YS,ah=v(()=>{"use strict";hu();yu=class extends ys{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},YS=new yu});var ch={};H(ch,{remoteStepService:()=>bs});var bu,Bn,Tu,bs,Do=v(()=>{"use strict";_o();ie();ue();({REMOTE_STEP_SAVED:bu}=xt),Tu=class{async init(e){_.flags.useNewWSCLI.isEnabled()||(Bn=(await Promise.resolve().then(()=>(ah(),oh))).remoteStepServiceSocketIO,Bn.init(e))}joinToRemoteStep(e){return _.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:remoteStep`,{resultId:e},[bu]):Bn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(_.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:remoteStep`,[bu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Bn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return _.flags.useNewWSCLI.isEnabled()?(Tt.removeFilter(`${e}:remoteStep`,[bu]),Promise.resolve()):Bn.unlistenToRemoteStep(e)}},bs=new Tu});var wu,Pr,lh=v(()=>{"use strict";hu();wu=class extends ys{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=i=>{i.resultId===t&&i.testId===r&&n(i.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Pr=new wu});var ph={};H(ph,{testResultService:()=>kt});var uh,vu,kt,No=v(()=>{"use strict";uh=require("events");_o();ie();ue();lh();vu=class extends uh.EventEmitter{init(e){if(_.flags.useNewWSCLI.isEnabled()){Tt.onConnect=()=>this.emit("socket-connected");return}Pr.init(e),Pr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return _.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[xt.TEST_RESULT_UPDATED,xt.TEST_RESULT_CREATED]):Pr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(_.flags.useNewWSCLI.isEnabled()){Tt.removeFilter(`${e}:testResult`,[xt.TEST_RESULT_UPDATED,xt.TEST_RESULT_CREATED]);return}await Pr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(_.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:testResult`,[xt.TEST_RESULT_UPDATED,xt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Pr.listenToTestResult(e,t,r)}getSocket(){if(!_.flags.useNewWSCLI.isEnabled())return Pr.getSocket()}},kt=new vu});var mh,fh,gh,Se,XS,hh,dh,QS,Mo,yh=v(()=>{"use strict";mh=I(require("lodash"));U();de();je();rs();at();ge();eh();fh=I(require("p-retry")),gh=require("node:url");W();Oo();ls();ie();Do();No();ge();Se=P("test-run-handler"),XS=3,hh=20*1e3,dh=s=>JSON.stringify(s).length<hh,QS="Test couldn't be started",Mo=class{constructor(e,t,r,n,i,o){this._executionId=e;this._executionName=t;this._options=n;this._branch=i;this._testRunStatus=o;this.seleniumPerfStats=new Sr;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var l,c;this._testStatus=r.testStatus,this._testId=r.testId,this._testOptimization=r.testOptimization,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(l=r.overrideTestConfig)==null?void 0:l.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((c=r.runConfig)!=null&&c.isMobileWeb)&&n.browser;this._runConfig=a?Xs(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 Ys(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Hr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?Ai.FROM_DEVICE:Ai.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${he}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}set nativeApp(e){this._nativeApp=e}get nativeAppMetadata(){return this._nativeApp?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async isTestRecordedWithEnhancedMode(){return(await Un({projectId:this._options.project,testId:this.testId,branch:this.branch})).domMode==="enhanced"}async getRunRequestParams(){var r,n;let t={tokenV3:await At(),refreshToken:zi(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:xd,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 Ki()};if(this._options.disableMockNetwork&&yt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=dh(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,l=this.testId;o?(Object.assign(t,{runData:i}),Se.info(`Run data sent as URL param, test id: ${l} run data length: ${a}`)):Se.warn(`Run data is too big to be sent as a URL param. Test id: ${l}, run data size: ${a} (limit: ${hh} 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 Fn(this._options);Object.assign(t,{preloadedTest:i[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return Se.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testOptimization(){return this._testOptimization}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var i;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((i=this._options.lightweightMode)!=null&&i.disableResults&&!t&&dh(e))return;let r=async()=>{try{return await Iu(this._options.project,this._testId,this._testResultId,e)}catch(o){return Se.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Eu(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===QS||this.isRerunOnTestStartTimeOutError)&&this.testInfraIssueRetryCount}setReRunOnTestStartTimeOutError(e){this.isRerunOnTestStartTimeOutError=e}decreaseInfraErrorRetry(){this.testInfraIssueRetryCount--}get retryOnInfraErrors(){return Boolean(this.testInfraIssueRetryCount)}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){M("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=new Set(["Testim Editor","Tricentis Testim Editor","Service Worker chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia/background/background.js"]),{targetId:n}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.has(o.title))||{},{targetId:i}=t.find(o=>o.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!i)throw new Error("AUT target not found");try{M("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:l}=o||{};M("before Runtime.evaluate"),await(0,fh.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},l);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),M("after wait for runTestimTest function");let{result:c}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},l);if(c.subtype==="error")throw new Error(c.description);return M("after Runtime.evaluate"),c.value}catch(o){throw Se.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new gh.URL(e)}catch{return}let{username:n,password:i}=r;if(n||i)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=i=>{if(!r){if(this.isRetryKeyMismatch(i)){Se.warn(`ignoring result update for on started due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(i.status)&&(i.resultId=this.testResultId,i.status==="completed"&&!this.isRerunOnInfraError(i.reason)&&(Se.info("setting _wasCompletedOnStartedCheck to true",{testResult:i,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=i),r=!0,t(i))}};if(this._options.disableSockets){let i=Date.now()+e,o=async()=>{if(Date.now()>i)return;let{testId:a,testResultId:l,branch:c,_options:{project:d}}=this;try{let m=await kr(a,l,d,c);n(m),r||setTimeout(o,3e3)}catch(m){Se.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else kt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await kr(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return Se.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw Se.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Me.TEST_START_TIMEOUT_MSG)}catch(i){throw Se.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Me.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await kt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Se.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||kt.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){Se.warn(`ignoring result update for on completed due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}o.status==="completed"&&(o.resultId=this._testResultId,r(o))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),i=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=mh.debounce(async()=>{try{await kt.joinToTestResult(this._testResultId,this.testId)}catch(o){Se.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await kr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(Se.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(o==null?void 0:o.status)==="completed"?(Se.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),o.resultId=this._testResultId,r(o),!0):!1}catch(o){return Se.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)kt.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await Su(this._testResultId,this._options.project,this.retryKey);a?await e()||(Se.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){Se.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&kt.off("socket-connected",e)}}listenToRemoteStep(e){bs.listenToRemoteStep(this.testResultId,t=>{Zg(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:XS;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 Fo,bh=v(()=>{"use strict";yh();Fo=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 Mo(e,t,l,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});async function wh(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await Au({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 xu(s,e){let t=s.mode===q.EXTENSION?Or:jn,r=Th.difference(Ks(s,e),t);if(r.length>0)throw yt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new C(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Th,Or,jn,Uo=v(()=>{"use strict";Th=I(require("lodash"));U();rs();ge();Y();ie();Or=["edge-chromium","chrome"],jn=[...Or,"firefox","safari","safari technology preview"]});var ZS,eE,tE,$n,Cu=v(()=>{"use strict";ts();os();W();ZS=P("worker-utils"),eE=async(s,e,t)=>{e&&await pl(s,t)},tE=async(s,e,t)=>{await Ml(s,e,t)},$n=async(s,e,t,r,n,i)=>{ZS.info("releasing player",{hasPlayer:Boolean(i)});try{await(i==null?void 0:i.onDone())}finally{n==="mongo"&&await eE(s,e,t),n==="redis"&&await tE(s,r,t)}}});function iE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var jo,Eh,$o,Ou,Ih,wt,vh,Sh,Pu,Wn,rE,ku,sE,nr,nE,Bo,oE,Ot,Vn=v(()=>{"use strict";jo=I(require("ms")),Eh=I(require("lodash")),$o=I(require("p-retry")),Ou=I(require("dayjs")),Ih=I(require("dayjs/plugin/duration"));U();je();ts();os();ge();W();Cu();Pt();Io();ue();Do();No();at();Ve();ie();Y();Ou.default.extend(Ih.default);wt=P("base-worker"),{GET_BROWSER_TIMEOUT_MSG:vh,TEST_START_TIMEOUT_MSG:Sh,TEST_COMPLETE_TIMEOUT_MSG:Pu}=Me,{SETUP_TIMEOUT:Wn,NETWORK_ERROR:rE,GRID_ERROR:ku,BROWSER_CLOSED:sE,SELENIUM_ERROR:nr,UNKNOWN_ERROR:nE,MOBILE_SESSION_ERROR:Bo}=zs;oE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Ot=class{constructor(e,t,r,n,i,o,a,l,c=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=l;this.releaseSlotOnTestFinished=c;this.lambdatestService=new ne;this.id=0;this.uniqueId="";this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let r=await df(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 js(!0)}async getBrowserOnce(e,t,r,n){throw new js(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),wt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId(),executionId:e.executionId}),await e.clearTestResult()}handleQuarantine(e){if(!Ye({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:me.SKIPPED,testStatus:e.testStatus,testOptimization:e.testOptimization};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,i;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=qr(_,(i=this.options.gridData)==null?void 0:i.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:me.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}calculateMobileTestTimeout(e){let t=_.flags.increaseTDCRequestTimeout.isEnabled(),r=e===L.TESTIM_TDC||e===L.TESTIM_HEADSPIN,n=mr(_.flags.appiumConnectionRequestTimeout.getValue(),(0,jo.default)("2m")),i=mr(_.flags.appiumConnectionRetryCount.getValue(),1),o=n*i;return e===L.BROWSERSTACK||t&&r?o+(0,jo.default)("10m"):o+(0,jo.default)("1m")}getSessionTimeout(){if(Jt(this.options)){let t=this.options.gridData.type,r=this.calculateMobileTestTimeout(t);return Math.max(r,this.options.getSessionTimeout)}return Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,$o.default)(async()=>{let n=Date.now();try{return await le(this.getSlotOnce(e),this.options.getBrowserTimeout,Me.GET_BROWSER_TIMEOUT_MSG)}catch(i){return t++,await this.handleGetSlotError(i,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,$o.default)(async()=>{var n,i;let r=Date.now();try{let o=(n=this.options.company)==null?void 0:n.companyId,a=(i=this.options.projectData)==null?void 0:i.projectId;return await le(Uf(o,a,this.id),this.options.getBrowserTimeout,Me.GET_BROWSER_TIMEOUT_MSG)}catch(o){return e++,await this.handleGetSlotError(o,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof zt?wt.info("could not get grid slot due to concurrency issue",r):wt.error("error getting grid slot",{error:e,...r}),await ce(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var i;let r=(i=this.userData)==null?void 0:i.projectId,n;try{M("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);M("before getBrowserOnce retries");let l=this.options.getBrowserRetries-o;if(!l)throw new Error("No free browser slots in desired grid");let c=0;n=await(0,$o.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await mf(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:l,currentRetry:c+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=c,M("before getBrowserOnce");let f=await le(this.getBrowserOnce(e,t,m,u),this.getSessionTimeout(),Me.GET_BROWSER_TIMEOUT_MSG);return M("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),m||f}catch(u){let f={...a,failedGetBrowserAttempts:c,id:this.options.gridData.gridId},h=this.options.mode===q.APPIUM?"device":"browser";throw wt.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Q.onGetBrowserFailure(this.id,r,++c),m.onDone(),!(u instanceof It)&&this.options.mode!==q.APPIUM&&await ce(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:l-1,minTimeout:0,factor:1}),M("after getBrowserOnce retries")}catch(o){throw await $n(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[It,Wr].some(a=>o instanceof a)?o:o instanceof rt?new pr(o,ku):new pr(o,nr)}return n}async runTest(e,t,r){var d;M("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,i=this.handleQuarantine(e);if(i)return i;let o=Jt(this.options)&&this.handleMobileTest(e);if(o)return o;M("before runTest onTestStarted");let a=e.getAppSource,l=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=l.config.baseUrl;let c=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await At(),await this.runTestOnce(e,c)}finally{await $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 O,B;if(Ye(g,this.options)||qr(_,(O=this.options.gridData)==null?void 0:O.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let w=G=>y==null?void 0:y.message.includes(G),b=y&&y instanceof pr,S=w(Sh),E=y&&(w(Pu)||S&&!e.retryOnInfraErrors),D=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||S)&&e.retryOnInfraErrors,j=E&&e.hasMoreTimeoutRetries(),R=e.hasMoreRetries()&&!b&&!E,x=!g.success&&(R||j||D);try{let G=e.retryKey;g.testRetryKey=G;let z=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,T,x,z),await this.runTestCleanup(),x){if(j&&await e.startNewTimeoutRetry(),D){wt.info(`retry test id: ${this.testId} name: ${this.testName} again due to infrastructure issues`,{testId:e.testId,retryReason:g.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId,err:y});let X=(B=this.options.projectData)==null?void 0:B.projectId,fe=e.testResultId,Ze=e.testId;await Wo(X,fe,Ze,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return R&&!D&&!j&&await e.startNewRetry(),wt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:E,testRetryKey:G,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(x)}t(this.id,...r);return}catch(G){if(G instanceof qt)return;wt.error("failed to process test result",{error:G}),t(this.id,...r);return}},i=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
213
|
-
Please make sure the CLI has stable access to the internet. ${
|
|
214
|
-
problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(g.message)||/Couldn't connect to selenium server/.test(g.message)?{errorType:nr,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(g.message)?{errorType:nr,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(g.message)?{errorType:nr,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(g.message)?{errorType:nr,reason:`Session could not be created, please check that the ${T} you requested is supported in your plan`}:{errorType:nE,reason:w}},l=async g=>{var S;let y=await Ic();!y&&_.flags.warnOnBadNetwork.isEnabled()&&console.warn(i()),wt.warn("error on run",{err:g});let T=(S=this.userData)==null?void 0:S.projectId,{errorType:w,reason:b}=this.options.mode===q.APPIUM?o(g):a(g,y);Wo(T,this.testResultId,this.testId,{status:qs.COMPLETED,success:!1,reason:b,errorType:w,testRetryKey:e.retryKey,setupStepResult:{status:qs.COMPLETED,success:!1,reason:b,errorType:w}},e.remoteRunId),await n(iE(this.testId,this.testName,this.testResultId,b),g)},c=async g=>{var S;let y=this.testId,T=this.testResultId,w=(S=this.userData)==null?void 0:S.projectId,b=this.branch;if(!y||!T||!w||!b)return wt.warn("Test failed. Not enough data to recover results via API",{err:g}),l(g);try{let E=await kr(y,T,w,b);if(wt.warn("Test failed. Got results via API",{err:g,testResult:Eh.default.omit(E,oE),resultId:T}),E&&E.status===qs.COMPLETED&&!g.message.includes(Pu))return await n(E);throw g}catch(E){return E!==g&&wt.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:w,branch:b,err:E}),l(g)}},d=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableResults)&&(this.options.useChromeLauncher||this.options.mode===q.SELENIUM),m=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),u=async g=>{try{await Promise.all([!m&&bs.joinToRemoteStep(this.testResultId),!d&&kt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==q.APPIUM&&e.validateRunConfig();let y=await this.runTest(e,this.customExtensionLocalLocation,g);await n(y),M("After onRunComplete"),t(this.id,...r)}catch(y){await c(y),t(this.id,...r)}finally{m||bs.unlistenToRemoteStep(this.testResultId)}};return this.testId=e.testId,this.testName=e.testName,this.testResultId=e.testResultId,this.overrideTestConfigId=e.overrideTestConfigId,this.testRunConfig=e.runConfig,this.branch=e.branch,u()}}});var xh,Rh,Ts,_u=v(()=>{"use strict";U();xh=I(require("p-retry"));U();W();Y();Rh=P("window-utils"),Ts=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(i,o){let a=document.elementFromPoint(i,o);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(i){let o=i.message.includes("method IWebBrowser2::Navigate2() failed");if(i.seleniumStack&&o&&n>0)return Rh.warn("selenium navigation failed. retrying to navigate",{err:i}),await ce(1500),r(n-1);throw!i.seleniumStack&&o&&Rh.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:i}),i}};return Promise.race([r(),ce(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),ce(e)])}async getZoom(){function e(){return{zoomLevel:window.outerWidth/window.innerWidth}}let{value:t}=await this.driver.executeJS(e);return t}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let r=document.body,n=document.documentElement,i=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),o=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:i,width:o}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await ce(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let r;if(typeof window<"u"&&window.location!==void 0)r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&!r.href.startsWith("res://ieframe.dll/http_404.htm")&&!r.href.startsWith("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")}if(!(await this.driver.executeJS(e)).value)throw new It("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,xh.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}}});var Lu,ws,Du=v(()=>{"use strict";W();Lu=P("cookies-utils"),ws=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(r){throw Lu.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw Lu.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw Lu.error("failed to remove cookie",{err:t}),t}}}});var Nu,Vo,Ah=v(()=>{"use strict";Nu=I(require("p-retry")),Vo=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,Nu.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,Nu.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 Ch(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 aE.warn("missing elementRect",kh.omit(s,"image")),{};let{elementRect:o}=s,a=await Go.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 Mu("height or width is equal or lower than zero");return{elementImage:await a.crop({x:l,y:c,w:d,h:m}).getBase64(Oh)}}async function cE(s,e){let t=new Go.Jimp({width:s.width,height:s.height});for(let n of e){let i=n.image.match(/^data:[^;]*;base64,(.*)$/),o=await Go.Jimp.fromBuffer(Buffer.from(i[1],"base64"));t.composite(o,n.position.left,n.position.top)}return await t.getBase64(Oh)}function lE(s,e){return cE(s,e)}async function uE(){}async function pE(s){function e(i){let o=s[i];return typeof o=="string"&&o.startsWith("data")}async function t(i){let o=await uE(s[i]);return{key:i,url:o}}let r=await se(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(i=>[i.key,i.url]));return Object.assign(s,n)}function Ph(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 kh,Go,aE,Oh,Mu,Ho,_h=v(()=>{"use strict";kh=I(require("lodash"));U();Go=require("jimp");W();aE=P("image-capture-utils"),Oh="image/png",Mu=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};Ho=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 Ch(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:Ph(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 pE({screenImage:t.image,absoluteScreenHighlight:Ph(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>ce(250),i=Boolean(e);async function o(u,f){i?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await Ch({elementRect:f},h);return{position:{left:u.x+f.left,top:u.y+f.top},size:{width:f.width,height:f.height},image:g.elementImage}}async function a(u){let f=[];for(let h of u){let g=await o(h.scrollPos,h.cropData);f.push(g)}return f}function l(u,f){let h=Math.max(u.width,f.width),g=f.width,y=Math.max(u.height,f.height),T=f.height,w=Array.from({length:Math.ceil(h/g)},(S,E)=>({scrollX:Math.min(E*g,h-g),cropX:E*g-Math.min(E*g,h-g),cropW:g-(E*g-Math.min(E*g,h-g))})),b=Array.from({length:Math.ceil(y/T)},(S,E)=>({scrollY:Math.min(E*T,y-T),cropY:E*T-Math.min(E*T,y-T),cropH:T-(E*T-Math.min(E*T,y-T))}));return w.flatMap(S=>b.map(E=>({scrollPos:{x:S.scrollX,y:E.scrollY},cropData:{top:E.cropY,left:S.cropX,width:S.cropW,height:E.cropH}})))}async function c(u,f){let h=await t.getCurrentScrollPosition(),g=l(u,f),y=await a(g);return await t.scrollToPosition(h),lE(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await c(d,m)}}});var Lh,Dh,qo,zo,Nh=v(()=>{"use strict";Lh=I(require("p-retry")),Dh=I(require("semver"));U();W();_u();Ah();_h();we();qo=P("tab-service"),zo=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),qo.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,i={}){let o=await this.getTabDetails(t,e,i),a=re();function l(c){return i.checkForMainTab?o.isMainTab:!o.isMainTab||o.isMainTab==="unknown"?!c.getMainTabInfo(e):o.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:o.url,title:o.title,favIconUrl:o.favIconUrl,order:r,from:this.getTabInfo(e,o.openerTabId),isMain:l(this),openerStepId:n},a}async addTab(e,t,r,n,i={}){let o=await this.buildTabInfo(e,t,r,n,i),a=new Ts(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new Ho(t,a,new Vo(t,this.driver,{takeScreenshots:i.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(o=>r[o]).filter(o=>!o.isMain);if(n.length===1)return this._utils[n[0].infoId];let i=Object.keys(e).map(o=>e[o]).filter(o=>this.isSameTab(e,t,o));return i.length>0?this._utils[i[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(i=>i===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:i}=Z(),o=i.urlBreaker(e.url||e.currentUrl),a=i.urlBreaker(t.url||t.currentUrl),l=n(o),c=n(a),d=r.map(m=>i.urlBreaker(m)).map(m=>n(m)).filter(m=>m===l);return l===c&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=Z();if(n){let c=this.getAllTabInfos(e),d=Object.keys(c).map(m=>c[m]);return n.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let i=this.getAllTabInfos(e),o=Object.keys(i).map(c=>i[c].url);if(this.exactUrlMatch(t,r,o))return!0;let a=c=>`${c.domain}/${c.path.join("/")}`;if(this.singleExactMatchForParts(t,r,o,a))return!0;let l=c=>`${c.domain}/${c.path.join("/")}#${c.hash}`;return!!(this.singleExactMatchForParts(t,r,o,l)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(i=>i.value));try{let[i,o,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:i,url:o,isMainTab:a}}catch(i){qo.error("failed to get url or title",{err:i})}}catch(n){qo.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await ce(500),await this.waitForTabToOpen(e))}async tryToAddTab(e){if(this.pendingTabs[e])return;let t=await this.getUnregisteredTabId(e);t&&(await this.addNewTab(e,t),await this.addFrameHandler(t),Object.assign(this.sessionTabs[e],{currentTab:null}))}async addNewPopup(e,t){let r=this.getAllTabInfos(e);if(Object.keys(r).find(o=>r[o].openerStepId===t))return;if(this.pendingTabs[e]){qo.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,Lh.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=Dh.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(i=>i.type==="locate"&&!i.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var l,c;let{tabMatcher:r,commonConstants:n}=Z();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((l=t.useCurrentTab)!=null&&l.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let i=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,i),await this.tryToAddTab(e);let o=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,o);if(!a)throw new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(u=>d.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var Fu,Ko,Uu=v(()=>{"use strict";Fu=class{select(){return console.log(`
|
|
211
|
+
`,u=[],f=new Kg.Worker(m,{eval:!0});try{return await le(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:y}=g,T={...y,tstConsoleLogs:u};pt.debug("Run code worker response",{messageWithLogs:T,transactionId:s}),h(T)}else g.action==="progress"&&u.push(g.data)}).on("error",g=>{g.message==="malformed data: URI"?pt.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:o}):pt.error("Run code worker error",{err:g,transactionId:s}),h({tstConsoleLogs:u,status:"failed",result:{resultValue:g==null?void 0:g.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{pt.debug("Run code worker has been terminated",{transactionId:s})}),f.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),i)}catch(h){if(!(h instanceof oe))throw h;return pt.warn("timeout to run code",{transactionId:s,err:h}),{tstConsoleLogs:u,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{f==null||f.terminate()}}async function US(s){try{await Hg.promises.rm(s,{recursive:!0,force:!0})}catch(e){pt.warn("failed to remove install npm packages folder",{err:e})}}function Jg(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function fs(s,e,t,r,n,i){let o=Jg(n,e,s,t),{data:a}=await FS(o,r,i);return a}async function gs(s,e,t,r,n,i,o,a,l,c){var g;let d=r.computePackagePathFromPackageJsonExports||_.flags.computePackagePathFromPackageJsonExports.isEnabled(),m=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(d){let T=Fm(y.testimPackageLocalLocation);return[y.paramName,ms.join(y.testimPackageLocalLocation,T)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=Jg(o,n,e,i);if(c){let y=await An(c);y&&(l=y)}Buffer.isBuffer(l)&&(pt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:l}),l=l.toString());let f="data:,";return l==="data:"&&(pt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:l}),l=f),{...await MS(u,t,r,s,m,a,l),nodeVersion:process.version}}async function FS(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Yg(),o=_.flags.reuseCliPkgInstallFolder.isEnabled()?n:ms.join(n,`/${s}`),a=global.proxyUri;async function l(){let c="";try{if(c=await Jc(o,r,a,t),pt.info("npm package install finished",{transactionId:s,output:c,timeout:t}),Number(c.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(m=>{let u=Mm(o,m.packageName);return{...m,packageFullName:`${m.packageName}@${u}`,packageLocalLocation:ms.resolve(o,"node_modules",m.packageName)}}),installFolder:o}}catch(d){throw pt.warn("npm package install failed",{transactionId:s,err:d}),d}}try{return await le(l(),t)}catch(c){throw c instanceof oe&&pt.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function Yg(){return ms.join(qg.tmpdir(),"/testim_local_packages")}function BS(){let s=Yg();return US(s)}var Hg,qg,ms,zg,Kg,pt,hs=v(()=>{"use strict";Hg=I(require("fs")),qg=I(require("os")),ms=I(require("path"));F();Zr();zg=I(require("data-uri-to-buffer")),Kg=require("worker_threads");Y();W();ge();Zr();ue();pt=P("cli-service");BS().catch(s=>pt.warn("failed to clean local package folder",{err:s}))});var sr={};H(sr,{run:()=>$S});function jS(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=_.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var $S,Xg=v(()=>{"use strict";hs();Y();ue();$S=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:i,context:o,testResultId:a,retryIndex:l,stepResultId:c,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let f=await gs(r,n,i,o,a,l,c,d,m,u);return f&&jS({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof oe?new Error("Timeout while running action"):f}}});var mu={};H(mu,{run:()=>WS});var WS,Qg=v(()=>{"use strict";hs();Y();WS=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:i,packageData:o,timeout:a}=e.data;try{return{data:await fs(t,r,n,o,i,a),success:!0}}catch(l){if(l instanceof Rt)return{success:!1,code:"invalid-node-package",message:l.message};if(l instanceof oe)return{success:!1,code:"timeout"};throw l}}});async function eh(s,e,t,r){try{return await fu(s,e,t,r)}catch{ko.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function GS(s,e,t,r,n){return ko.info("finished to run remote step",{stepId:t,sessionId:n}),await eh(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function Zg(s,e,t,r,n){return ko.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await eh(s,e,t,{status:"completed",success:!1,failureReason:r})}async function th(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;ko.info("start play remote step",{stepType:o,stepId:l,sessionId:a});let c=VS[o];if(!c)return await Zg(n,r,l,`Failed to find step type ${o}`,a);try{let d=await c.run(e,t,i);return await GS(n,r,l,d,a)}catch(d){return await Zg(n,r,l,d.message,a)}}var ko,VS,rh=v(()=>{"use strict";Xg();ge();Qg();W();ko=P("step-playback"),VS={"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":mu}});var nh={};H(nh,{preloadTests:()=>Un});async function Un(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await Bt(async()=>{let t=await se(s.testId,r=>Fn({...e,testId:r}),{concurrency:2});return sh.keyBy(t,"testData.id")},"loadTests",qS,[e,s.testId])()}var sh,qS,Oo=v(()=>{"use strict";sh=I(require("lodash"));Yt();ge();F();qS=1e3*60*60*10});var gu,ih,Cr,zS,hu,Tt,_o=v(()=>{"use strict";F();at();gu=I(require("ws")),ih=require("events");W();de();Cr=P("socket-service"),zS=5e3,hu=class extends ih.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),zS)}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(vd);return At().then(n=>new Promise(i=>{let o={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new gu.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===gu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Cr.info("websocket error",{event:a})}),this.ws.on("message",a=>{let l=this.parseEvent(a);l!=null&&l.type&&this.emit(l.type,l.data)})}))}sendMessage(t){if(!this.ws){Cr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Cr.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,n){let i=o=>{r(o)&&(n(o),this.removeListener(t,i))};this.on(t,i)}listenTo(t,r,n,i){function o(l){n(l)&&i(l)}(Array.isArray(r)?r:[r]).forEach(l=>{this.listeners[`${t}:${l}`]||=[];let c=o.bind(this);this.listeners[`${t}:${l}`].push(c),this.on(l,c)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,i=!1){return new Promise(o=>{let a=re(),l={query:r,id:a,type:n,fullDocument:i};this.listenOnce("add-filter:done",c=>c.id===a,o),this.sendMessage({type:"add-filter",filter:l}),this.filterMap[t]=l})}removeListeners(t,r){Object.keys(this.listeners).length!==0&&r.forEach(n=>{let i=this.listeners[`${t}:${n}`];i&&(delete this.listeners[`${t}:${n}`],i.forEach(o=>this.removeListener(n,o)))})}removeFilter(t,r){let n=this.filterMap[t];if(!n)return;let i=Array.isArray(r)?r:[r];this.removeListeners(t,i),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},Tt=new hu});var ah,yu,KS,JS,YS,oh,Lo,ys,bu=v(()=>{"use strict";ah=I(require("p-retry")),yu=I(require("socket.io-client"));de();F();W();KS=50,JS=10,YS=5e3,oh=10*1e3,Lo=P("base socket service"),ys=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Lo.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{}Lo.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===JS&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=KS)throw new Error(`Can't connect to Testim Servers.
|
|
212
|
+
Action required: Please allow opening a websockets connection to ${he} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{Lo.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:oh,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${he}/${t}`,this._socket=yu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:oh,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${he}/${t}`,this._socket=yu.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,ah.default)(()=>le(n(),YS),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Lo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var ch={};H(ch,{remoteStepServiceSocketIO:()=>XS});var Tu,XS,lh=v(()=>{"use strict";bu();Tu=class extends ys{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},XS=new Tu});var uh={};H(uh,{remoteStepService:()=>bs});var wu,Bn,vu,bs,Do=v(()=>{"use strict";_o();ie();ue();({REMOTE_STEP_SAVED:wu}=xt),vu=class{async init(e){_.flags.useNewWSCLI.isEnabled()||(Bn=(await Promise.resolve().then(()=>(lh(),ch))).remoteStepServiceSocketIO,Bn.init(e))}joinToRemoteStep(e){return _.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:remoteStep`,{resultId:e},[wu]):Bn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(_.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:remoteStep`,[wu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Bn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return _.flags.useNewWSCLI.isEnabled()?(Tt.removeFilter(`${e}:remoteStep`,[wu]),Promise.resolve()):Bn.unlistenToRemoteStep(e)}},bs=new vu});var Su,Pr,ph=v(()=>{"use strict";bu();Su=class extends ys{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=i=>{i.resultId===t&&i.testId===r&&n(i.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Pr=new Su});var mh={};H(mh,{testResultService:()=>kt});var dh,Eu,kt,No=v(()=>{"use strict";dh=require("events");_o();ie();ue();ph();Eu=class extends dh.EventEmitter{init(e){if(_.flags.useNewWSCLI.isEnabled()){Tt.onConnect=()=>this.emit("socket-connected");return}Pr.init(e),Pr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return _.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[xt.TEST_RESULT_UPDATED,xt.TEST_RESULT_CREATED]):Pr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(_.flags.useNewWSCLI.isEnabled()){Tt.removeFilter(`${e}:testResult`,[xt.TEST_RESULT_UPDATED,xt.TEST_RESULT_CREATED]);return}await Pr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(_.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:testResult`,[xt.TEST_RESULT_UPDATED,xt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Pr.listenToTestResult(e,t,r)}getSocket(){if(!_.flags.useNewWSCLI.isEnabled())return Pr.getSocket()}},kt=new Eu});var gh,hh,yh,Se,QS,bh,fh,ZS,Mo,Th=v(()=>{"use strict";gh=I(require("lodash"));F();de();je();rs();at();ge();rh();hh=I(require("p-retry")),yh=require("node:url");W();Oo();ls();ie();Do();No();ge();Se=P("test-run-handler"),QS=3,bh=20*1e3,fh=s=>JSON.stringify(s).length<bh,ZS="Test couldn't be started",Mo=class{constructor(e,t,r,n,i,o){this._executionId=e;this._executionName=t;this._options=n;this._branch=i;this._testRunStatus=o;this.seleniumPerfStats=new Sr;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var l,c;this._testStatus=r.testStatus,this._testId=r.testId,this._testOptimization=r.testOptimization,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(l=r.overrideTestConfig)==null?void 0:l.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((c=r.runConfig)!=null&&c.isMobileWeb)&&n.browser;this._runConfig=a?Xs(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 Ys(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Hr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?Ai.FROM_DEVICE:Ai.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${he}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}set nativeApp(e){this._nativeApp=e}get nativeAppMetadata(){return this._nativeApp?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async isTestRecordedWithEnhancedMode(){return(await Fn({projectId:this._options.project,testId:this.testId,branch:this.branch})).domMode==="enhanced"}async getRunRequestParams(){var r,n;let t={tokenV3:await At(),refreshToken:zi(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:Cd,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 Ki()};if(this._options.disableMockNetwork&&yt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=fh(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,l=this.testId;o?(Object.assign(t,{runData:i}),Se.info(`Run data sent as URL param, test id: ${l} run data length: ${a}`)):Se.warn(`Run data is too big to be sent as a URL param. Test id: ${l}, run data size: ${a} (limit: ${bh} 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 Un(this._options);Object.assign(t,{preloadedTest:i[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return Se.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testOptimization(){return this._testOptimization}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var i;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((i=this._options.lightweightMode)!=null&&i.disableResults&&!t&&fh(e))return;let r=async()=>{try{return await xu(this._options.project,this._testId,this._testResultId,e)}catch(o){return Se.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Ru(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===ZS||this.isRerunOnTestStartTimeOutError)&&this.testInfraIssueRetryCount}setReRunOnTestStartTimeOutError(e){this.isRerunOnTestStartTimeOutError=e}decreaseInfraErrorRetry(){this.testInfraIssueRetryCount--}get retryOnInfraErrors(){return Boolean(this.testInfraIssueRetryCount)}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){M("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=new Set(["Testim Editor","Tricentis Testim Editor","Service Worker chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia/background/background.js"]),{targetId:n}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.has(o.title))||{},{targetId:i}=t.find(o=>o.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!i)throw new Error("AUT target not found");try{M("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:l}=o||{};M("before Runtime.evaluate"),await(0,hh.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},l);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),M("after wait for runTestimTest function");let{result:c}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},l);if(c.subtype==="error")throw new Error(c.description);return M("after Runtime.evaluate"),c.value}catch(o){throw Se.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new yh.URL(e)}catch{return}let{username:n,password:i}=r;if(n||i)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=i=>{if(!r){if(this.isRetryKeyMismatch(i)){Se.warn(`ignoring result update for on started due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(i.status)&&(i.resultId=this.testResultId,i.status==="completed"&&!this.isRerunOnInfraError(i.reason)&&(Se.info("setting _wasCompletedOnStartedCheck to true",{testResult:i,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=i),r=!0,t(i))}};if(this._options.disableSockets){let i=Date.now()+e,o=async()=>{if(Date.now()>i)return;let{testId:a,testResultId:l,branch:c,_options:{project:d}}=this;try{let m=await kr(a,l,d,c);n(m),r||setTimeout(o,3e3)}catch(m){Se.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else kt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await kr(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return Se.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw Se.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Me.TEST_START_TIMEOUT_MSG)}catch(i){throw Se.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Me.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await kt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Se.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||kt.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){Se.warn(`ignoring result update for on completed due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}o.status==="completed"&&(o.resultId=this._testResultId,r(o))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),i=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=gh.debounce(async()=>{try{await kt.joinToTestResult(this._testResultId,this.testId)}catch(o){Se.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await kr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(Se.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(o==null?void 0:o.status)==="completed"?(Se.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),o.resultId=this._testResultId,r(o),!0):!1}catch(o){return Se.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)kt.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await Iu(this._testResultId,this._options.project,this.retryKey);a?await e()||(Se.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){Se.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&kt.off("socket-connected",e)}}listenToRemoteStep(e){bs.listenToRemoteStep(this.testResultId,t=>{th(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:QS;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 Uo,wh=v(()=>{"use strict";Th();Uo=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 Mo(e,t,l,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});async function Sh(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await Pu({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 Au(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 Cu(s,e){let t=s.mode===q.EXTENSION?Or:jn,r=vh.difference(Ks(s,e),t);if(r.length>0)throw yt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new C(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var vh,Or,jn,Fo=v(()=>{"use strict";vh=I(require("lodash"));F();rs();ge();Y();ie();Or=["edge-chromium","chrome"],jn=[...Or,"firefox","safari","safari technology preview"]});var eE,tE,rE,$n,ku=v(()=>{"use strict";ts();os();W();eE=P("worker-utils"),tE=async(s,e,t)=>{e&&await ml(s,t)},rE=async(s,e,t)=>{await Fl(s,e,t)},$n=async(s,e,t,r,n,i)=>{eE.info("releasing player",{hasPlayer:Boolean(i)});try{await(i==null?void 0:i.onDone())}finally{n==="mongo"&&await tE(s,e,t),n==="redis"&&await rE(s,r,t)}}});function oE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var jo,Rh,$o,Lu,xh,wt,Eh,Ih,Ou,Wn,sE,_u,nE,nr,iE,Bo,aE,Ot,Vn=v(()=>{"use strict";jo=I(require("ms")),Rh=I(require("lodash")),$o=I(require("p-retry")),Lu=I(require("dayjs")),xh=I(require("dayjs/plugin/duration"));F();je();ts();os();ge();W();ku();Pt();Io();ue();Do();No();at();Ve();ie();Y();Lu.default.extend(xh.default);wt=P("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Eh,TEST_START_TIMEOUT_MSG:Ih,TEST_COMPLETE_TIMEOUT_MSG:Ou}=Me,{SETUP_TIMEOUT:Wn,NETWORK_ERROR:sE,GRID_ERROR:_u,BROWSER_CLOSED:nE,SELENIUM_ERROR:nr,UNKNOWN_ERROR:iE,MOBILE_SESSION_ERROR:Bo}=zs;aE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Ot=class{constructor(e,t,r,n,i,o,a,l,c=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=l;this.releaseSlotOnTestFinished=c;this.lambdatestService=new ne;this.id=0;this.uniqueId="";this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let r=await ff(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 js(!0)}async getBrowserOnce(e,t,r,n){throw new js(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),wt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId(),executionId:e.executionId}),await e.clearTestResult()}handleQuarantine(e){if(!Ye({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:me.SKIPPED,testStatus:e.testStatus,testOptimization:e.testOptimization};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,i;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=qr(_,(i=this.options.gridData)==null?void 0:i.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:me.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}calculateMobileTestTimeout(e){let t=_.flags.increaseTDCRequestTimeout.isEnabled(),r=e===L.TESTIM_TDC||e===L.TESTIM_HEADSPIN,n=mr(_.flags.appiumConnectionRequestTimeout.getValue(),(0,jo.default)("2m")),i=mr(_.flags.appiumConnectionRetryCount.getValue(),1),o=n*i;return e===L.BROWSERSTACK||t&&r?o+(0,jo.default)("10m"):o+(0,jo.default)("1m")}getSessionTimeout(){if(Jt(this.options)){let t=this.options.gridData.type,r=this.calculateMobileTestTimeout(t);return Math.max(r,this.options.getSessionTimeout)}return Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,$o.default)(async()=>{let n=Date.now();try{return await le(this.getSlotOnce(e),this.options.getBrowserTimeout,Me.GET_BROWSER_TIMEOUT_MSG)}catch(i){return t++,await this.handleGetSlotError(i,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,$o.default)(async()=>{var n,i;let r=Date.now();try{let o=(n=this.options.company)==null?void 0:n.companyId,a=(i=this.options.projectData)==null?void 0:i.projectId;return await le(jf(o,a,this.id),this.options.getBrowserTimeout,Me.GET_BROWSER_TIMEOUT_MSG)}catch(o){return e++,await this.handleGetSlotError(o,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof zt?wt.info("could not get grid slot due to concurrency issue",r):wt.error("error getting grid slot",{error:e,...r}),await ce(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var i;let r=(i=this.userData)==null?void 0:i.projectId,n;try{M("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);M("before getBrowserOnce retries");let l=this.options.getBrowserRetries-o;if(!l)throw new Error("No free browser slots in desired grid");let c=0;n=await(0,$o.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await gf(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:l,currentRetry:c+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=c,M("before getBrowserOnce");let f=await le(this.getBrowserOnce(e,t,m,u),this.getSessionTimeout(),Me.GET_BROWSER_TIMEOUT_MSG);return M("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),m||f}catch(u){let f={...a,failedGetBrowserAttempts:c,id:this.options.gridData.gridId},h=this.options.mode===q.APPIUM?"device":"browser";throw wt.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Q.onGetBrowserFailure(this.id,r,++c),m.onDone(),!(u instanceof It)&&this.options.mode!==q.APPIUM&&await ce(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:l-1,minTimeout:0,factor:1}),M("after getBrowserOnce retries")}catch(o){throw await $n(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[It,Wr].some(a=>o instanceof a)?o:o instanceof rt?new pr(o,_u):new pr(o,nr)}return n}async runTest(e,t,r){var d;M("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,i=this.handleQuarantine(e);if(i)return i;let o=Jt(this.options)&&this.handleMobileTest(e);if(o)return o;M("before runTest onTestStarted");let a=e.getAppSource,l=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=l.config.baseUrl;let c=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await At(),await this.runTestOnce(e,c)}finally{await $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 O,B;if(Ye(g,this.options)||qr(_,(O=this.options.gridData)==null?void 0:O.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let w=G=>y==null?void 0:y.message.includes(G),b=y&&y instanceof pr,S=w(Ih),E=y&&(w(Ou)||S&&!e.retryOnInfraErrors),D=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||S)&&e.retryOnInfraErrors,j=E&&e.hasMoreTimeoutRetries(),R=e.hasMoreRetries()&&!b&&!E,x=!g.success&&(R||j||D);try{let G=e.retryKey;g.testRetryKey=G;let z=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,T,x,z),await this.runTestCleanup(),x){if(j&&await e.startNewTimeoutRetry(),D){wt.info(`retry test id: ${this.testId} name: ${this.testName} again due to infrastructure issues`,{testId:e.testId,retryReason:g.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId,err:y});let X=(B=this.options.projectData)==null?void 0:B.projectId,fe=e.testResultId,Ze=e.testId;await Wo(X,fe,Ze,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return R&&!D&&!j&&await e.startNewRetry(),wt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:E,testRetryKey:G,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(x)}t(this.id,...r);return}catch(G){if(G instanceof qt)return;wt.error("failed to process test result",{error:G}),t(this.id,...r);return}},i=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
213
|
+
Please make sure the CLI has stable access to the internet. ${Ac()?"(Internal: network connectivity test failed)":""}`,o=g=>{let{DEVICE_OS_VERSION_TOO_LOW:y,APP_NOT_EXIST_ON_DEVICE:T,APP_NEVER_STARTED:w,TIMEOUT_ERROR:b,SAUCELABS_APP_IS_NOT_INSTALLED:S}=Nc,E=g instanceof Error?g.message:g;return E.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),E.includes(Eh)||E.includes(b)?{errorType:Wn,reason:"timeout while getting device"}:E.includes(T)||E.includes(S)?{errorType:Bo,reason:"app doesn't exist on device"}:E.includes(w)?{errorType:Bo,reason:"app never started, check app permission or app activity"}:E.includes(y)?{errorType:Bo,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Bo,reason:E}},a=(g,y)=>{let T=this.options.mode===q.APPIUM?"device":"browser";if(!y&&_.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:sE,reason:i()};let w=g instanceof Error?g.message:g;if(w.includes(Eh))return{errorType:Wn,reason:`Test couldn't get ${T}`};if(w.includes(Ih))return{errorType:Wn,reason:"Test couldn't be started"};if(w.includes(Ou)){if(!this.testRunTimeout)return{errorType:Wn,reason:"Test timeout reached: test is too long"};let b=Lu.default.duration({milliseconds:this.testRunTimeout}),S=Math.floor(b.asMinutes()),E=b.asSeconds(),A=S>0?` ${S} min`:"",D=E>0?` ${E} sec`:"";return{errorType:Wn,reason:`Test timeout reached (timeout:${A}${D}): test is too long`}}if(g instanceof pr&&g.type){if(g.type===_u)return{errorType:_u,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===nE?{errorType:nr,reason:`Session terminated, this is often caused to connection
|
|
214
|
+
problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(g.message)||/Couldn't connect to selenium server/.test(g.message)?{errorType:nr,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(g.message)?{errorType:nr,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(g.message)?{errorType:nr,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(g.message)?{errorType:nr,reason:`Session could not be created, please check that the ${T} you requested is supported in your plan`}:{errorType:iE,reason:w}},l=async g=>{var S;let y=await xc();!y&&_.flags.warnOnBadNetwork.isEnabled()&&console.warn(i()),wt.warn("error on run",{err:g});let T=(S=this.userData)==null?void 0:S.projectId,{errorType:w,reason:b}=this.options.mode===q.APPIUM?o(g):a(g,y);Wo(T,this.testResultId,this.testId,{status:qs.COMPLETED,success:!1,reason:b,errorType:w,testRetryKey:e.retryKey,setupStepResult:{status:qs.COMPLETED,success:!1,reason:b,errorType:w}},e.remoteRunId),await n(oE(this.testId,this.testName,this.testResultId,b),g)},c=async g=>{var S;let y=this.testId,T=this.testResultId,w=(S=this.userData)==null?void 0:S.projectId,b=this.branch;if(!y||!T||!w||!b)return wt.warn("Test failed. Not enough data to recover results via API",{err:g}),l(g);try{let E=await kr(y,T,w,b);if(wt.warn("Test failed. Got results via API",{err:g,testResult:Rh.default.omit(E,aE),resultId:T}),E&&E.status===qs.COMPLETED&&!g.message.includes(Ou))return await n(E);throw g}catch(E){return E!==g&&wt.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:w,branch:b,err:E}),l(g)}},d=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableResults)&&(this.options.useChromeLauncher||this.options.mode===q.SELENIUM),m=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),u=async g=>{try{await Promise.all([!m&&bs.joinToRemoteStep(this.testResultId),!d&&kt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==q.APPIUM&&e.validateRunConfig();let y=await this.runTest(e,this.customExtensionLocalLocation,g);await n(y),M("After onRunComplete"),t(this.id,...r)}catch(y){await c(y),t(this.id,...r)}finally{m||bs.unlistenToRemoteStep(this.testResultId)}};return this.testId=e.testId,this.testName=e.testName,this.testResultId=e.testResultId,this.overrideTestConfigId=e.overrideTestConfigId,this.testRunConfig=e.runConfig,this.branch=e.branch,u()}}});var Ch,Ah,Ts,Du=v(()=>{"use strict";F();Ch=I(require("p-retry"));F();W();Y();Ah=P("window-utils"),Ts=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(i,o){let a=document.elementFromPoint(i,o);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(i){let o=i.message.includes("method IWebBrowser2::Navigate2() failed");if(i.seleniumStack&&o&&n>0)return Ah.warn("selenium navigation failed. retrying to navigate",{err:i}),await ce(1500),r(n-1);throw!i.seleniumStack&&o&&Ah.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:i}),i}};return Promise.race([r(),ce(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),ce(e)])}async getZoom(){function e(){return{zoomLevel:window.outerWidth/window.innerWidth}}let{value:t}=await this.driver.executeJS(e);return t}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let r=document.body,n=document.documentElement,i=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),o=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:i,width:o}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await ce(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let r;if(typeof window<"u"&&window.location!==void 0)r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&!r.href.startsWith("res://ieframe.dll/http_404.htm")&&!r.href.startsWith("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")}if(!(await this.driver.executeJS(e)).value)throw new It("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,Ch.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}}});var Nu,ws,Mu=v(()=>{"use strict";W();Nu=P("cookies-utils"),ws=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(r){throw Nu.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw Nu.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw Nu.error("failed to remove cookie",{err:t}),t}}}});var Uu,Vo,Ph=v(()=>{"use strict";Uu=I(require("p-retry")),Vo=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,Uu.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,Uu.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 kh(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 cE.warn("missing elementRect",_h.omit(s,"image")),{};let{elementRect:o}=s,a=await Go.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 Fu("height or width is equal or lower than zero");return{elementImage:await a.crop({x:l,y:c,w:d,h:m}).getBase64(Lh)}}async function lE(s,e){let t=new Go.Jimp({width:s.width,height:s.height});for(let n of e){let i=n.image.match(/^data:[^;]*;base64,(.*)$/),o=await Go.Jimp.fromBuffer(Buffer.from(i[1],"base64"));t.composite(o,n.position.left,n.position.top)}return await t.getBase64(Lh)}function uE(s,e){return lE(s,e)}async function pE(){}async function dE(s){function e(i){let o=s[i];return typeof o=="string"&&o.startsWith("data")}async function t(i){let o=await pE(s[i]);return{key:i,url:o}}let r=await se(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(i=>[i.key,i.url]));return Object.assign(s,n)}function Oh(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 _h,Go,cE,Lh,Fu,Ho,Dh=v(()=>{"use strict";_h=I(require("lodash"));F();Go=require("jimp");W();cE=P("image-capture-utils"),Lh="image/png",Fu=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};Ho=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 kh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:Oh(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 dE({screenImage:t.image,absoluteScreenHighlight:Oh(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>ce(250),i=Boolean(e);async function o(u,f){i?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await kh({elementRect:f},h);return{position:{left:u.x+f.left,top:u.y+f.top},size:{width:f.width,height:f.height},image:g.elementImage}}async function a(u){let f=[];for(let h of u){let g=await o(h.scrollPos,h.cropData);f.push(g)}return f}function l(u,f){let h=Math.max(u.width,f.width),g=f.width,y=Math.max(u.height,f.height),T=f.height,w=Array.from({length:Math.ceil(h/g)},(S,E)=>({scrollX:Math.min(E*g,h-g),cropX:E*g-Math.min(E*g,h-g),cropW:g-(E*g-Math.min(E*g,h-g))})),b=Array.from({length:Math.ceil(y/T)},(S,E)=>({scrollY:Math.min(E*T,y-T),cropY:E*T-Math.min(E*T,y-T),cropH:T-(E*T-Math.min(E*T,y-T))}));return w.flatMap(S=>b.map(E=>({scrollPos:{x:S.scrollX,y:E.scrollY},cropData:{top:E.cropY,left:S.cropX,width:S.cropW,height:E.cropH}})))}async function c(u,f){let h=await t.getCurrentScrollPosition(),g=l(u,f),y=await a(g);return await t.scrollToPosition(h),uE(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await c(d,m)}}});var Nh,Mh,qo,zo,Uh=v(()=>{"use strict";Nh=I(require("p-retry")),Mh=I(require("semver"));F();W();Du();Ph();Dh();we();qo=P("tab-service"),zo=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),qo.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,i={}){let o=await this.getTabDetails(t,e,i),a=re();function l(c){return i.checkForMainTab?o.isMainTab:!o.isMainTab||o.isMainTab==="unknown"?!c.getMainTabInfo(e):o.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:o.url,title:o.title,favIconUrl:o.favIconUrl,order:r,from:this.getTabInfo(e,o.openerTabId),isMain:l(this),openerStepId:n},a}async addTab(e,t,r,n,i={}){let o=await this.buildTabInfo(e,t,r,n,i),a=new Ts(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new Ho(t,a,new Vo(t,this.driver,{takeScreenshots:i.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(o=>r[o]).filter(o=>!o.isMain);if(n.length===1)return this._utils[n[0].infoId];let i=Object.keys(e).map(o=>e[o]).filter(o=>this.isSameTab(e,t,o));return i.length>0?this._utils[i[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(i=>i===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:i}=Z(),o=i.urlBreaker(e.url||e.currentUrl),a=i.urlBreaker(t.url||t.currentUrl),l=n(o),c=n(a),d=r.map(m=>i.urlBreaker(m)).map(m=>n(m)).filter(m=>m===l);return l===c&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=Z();if(n){let c=this.getAllTabInfos(e),d=Object.keys(c).map(m=>c[m]);return n.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let i=this.getAllTabInfos(e),o=Object.keys(i).map(c=>i[c].url);if(this.exactUrlMatch(t,r,o))return!0;let a=c=>`${c.domain}/${c.path.join("/")}`;if(this.singleExactMatchForParts(t,r,o,a))return!0;let l=c=>`${c.domain}/${c.path.join("/")}#${c.hash}`;return!!(this.singleExactMatchForParts(t,r,o,l)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(i=>i.value));try{let[i,o,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:i,url:o,isMainTab:a}}catch(i){qo.error("failed to get url or title",{err:i})}}catch(n){qo.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await ce(500),await this.waitForTabToOpen(e))}async tryToAddTab(e){if(this.pendingTabs[e])return;let t=await this.getUnregisteredTabId(e);t&&(await this.addNewTab(e,t),await this.addFrameHandler(t),Object.assign(this.sessionTabs[e],{currentTab:null}))}async addNewPopup(e,t){let r=this.getAllTabInfos(e);if(Object.keys(r).find(o=>r[o].openerStepId===t))return;if(this.pendingTabs[e]){qo.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,Nh.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=Mh.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(i=>i.type==="locate"&&!i.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var l,c;let{tabMatcher:r,commonConstants:n}=Z();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((l=t.useCurrentTab)!=null&&l.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let i=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,i),await this.tryToAddTab(e);let o=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,o);if(!a)throw new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(u=>d.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var Bu,Ko,ju=v(()=>{"use strict";Bu=class{select(){return console.log(`
|
|
215
215
|
internal error - cant use port selector in selenium!!!!
|
|
216
|
-
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},Ko=new
|
|
216
|
+
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},Ko=new Bu});var Gn,Jo,Yo=v(()=>{"use strict";Mu();F();we();Gn={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"},Jo=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Qs;this.getLinksFromUnescapeHTML=Zs;this.cookieUtils=new ws(this.driver)}get sessionPlayerInit(){return Z()}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}getClickOffset(e,t){let{utils:r,positionUtils:n}=this.sessionPlayerInit,i=n.calculateElementMiddlePoint(t);return e&&r.isWithinBounds(t.left,t.left+t.width,e.x)&&r.isWithinBounds(t.top,t.top+t.height,e.y)?{x:e.x-i.x,y:e.y-i.y}:{x:0,y:0}}async executeInAut(e,t){let{value:r}=await this.driver.executeJS(t);return r}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t){await this.driver.markDynamicParent(e,t)}getCookie(e){return this.cookieUtils.get({name:e})}setCookie(e){return this.cookieUtils.set(e)}async getNextDynamicParent(e,t){let r=this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t),{value:n}=await this.driver.executeJS(`return (function() { ${r} })();`);return n}}});function Bh(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=Fh(r.seleniumFrameElement);n&&this.cacheResults(n,r.frameLocateResultUrl)}}async foundFrameCallback(r,n,i){let{frameOffset:o,locatedElement:a}=r,{locatorBuilderUtils:l}=Z();if(l.isEmptyResult(a)){let u="got empty result in frame result, not rejected from locate element player";throw mE.error(u),new Error(u)}let c=await s.switchToLocatedFrame(a),d=Fh(c.value),m=this.getResultsFromCache(d);return{url:"",frameId:-1,frameOffset:o,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:i,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${i}`,seleniumFrameElement:c.value,frameLocateResultUrl:m}}async locate(r,n,i,o,a,l){let c=new this.LocateElementPlayer(o);r.targetId=`frameLocator_${n}`;let d=await c.locate(r,i,r.targetId);d.isVisible=!0;let m=await c.handleLocateResult(d,l,r).catch(()=>{throw new Error("")}),{locatedElement:u}=o.data[r.targetId],h=(await s.getElementLocationWithPadding(u)).value||{top:0,left:0};m.frameOffset={top:i.frameOffset.top+h.top,left:i.frameOffset.left+h.left},c.addFrameDataToContext&&c.addFrameDataToContext(m.targetId,m.locateResult);let g=await this.foundFrameCallback(m,a,r.testimFrameId);return this.currentFrameHandler=g,g}async findFrame(r,n,i,o){let a=_.flags.enableFrameSwitchOptimization.isEnabled(),c=i.playback.resultsHandler.resultsByChronologicOrder.at(-1),d=1,m=c&&c.stepId===r.id&&c.results.length>d;if(a&&!m&&this.currentFrameHandler){let y=n.findIndex(T=>T.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let T=n.slice(y+1),w=0;for(let b of T)w++,this.currentFrameHandler=await this.locate(b,w,this.currentFrameHandler,i,o,r);return this.currentFrameHandler}}let u=await o.getTopFrameHandler();u.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===u?this.currentFrameHandler:s.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=u;let h=0,g=u;for(let y of n)h++,g=await this.locate(y,h,g,i,o,r);return g}}return e}var mE,fE,Fh,jh=v(()=>{"use strict";W();ue();we();jr();mE=P("frame-locator"),fE="ELEMENT",Fh=s=>s?s[fE]||s[Gt]:null});var Xo,$u=v(()=>{"use strict";de();Xo=()=>{try{if(wd)return!1;if(require("inspector").url())return!0}catch{}return!1}});var V,pe=v(()=>{"use strict";we();V=class{constructor(e,t,r,n={},i=void 0,o=void 0,a={}){this.step=e;this.context=t;this.frameHandler=r;this.exportsGlobal=n;this.stepActionUtils=i;this.locateElementPlayer=o;this.exportsTest=a;this.frameId=0}get driver(){var e;return(e=this.context.project.defaults)!=null&&e.ignoreVisibilityForExisting&&!this.stepActionUtils.driver.getIgnoreVisibility()&&this.stepActionUtils.driver.setIgnoreVisibility(!0),this.stepActionUtils.driver}get sessionPlayerInit(){return Z()}async performAction(){throw new Error("not implemented")}getTarget(){let e=this.step.targetId||"targetId";return this.context.data[e]}async execute(){try{return{success:!0,...await this.performAction()}}catch(e){let t=e==null?void 0:e.message,r=e==null?void 0:e.displayMessage;return{success:!1,reason:t,exception:e,errorType:this.sessionPlayerInit.commonConstants.stepResult.ACTION_EXCEPTION,resultInfo:{exception:`selenium exception: ${t}`,error:r||t}}}}}});function hE(s,e,t,r){return s.opacity===0||s.isShadowed?!1:e===void 0||t===void 0?!0:_.flags.useClickimVisibilityChecks.isEnabled()?!1:r.isSafari()?_.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0}function yE(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 $h.DOMParser().parseFromString("<html><body></body></html>","text/html");return n.body.outerHTML=e,Object.assign(n,{TESTIM_URL:t,parsedUsingLinkedom:!0})},async isVisible(e,t,r,n,i,o,a){let{locatorBuilderUtils:l,codeSnippets:c,visibilityUtils:d,positionUtils:m}=Z();if(hE(n,d,m,s))return s.isVisible(e.seleniumElement);if(s.getIgnoreVisibility())return{visible:!0,invisibleReason:"visibility is ignored"};if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await s.isVisible(e.seleniumElement)}catch{}if(!t||l.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let h=[m.calculateElementMiddlePoint(r),m.calculateClickPoint(n.clickOffset,r)].filter(Boolean),g=c.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,n),y;try{y=await s.execute(`return ${g}`)}catch(E){throw _r.error("failed to execute getVisibilityCode",{err:E}),E}let{value:T}=y||{},w=T.elementVisibilityInfo||gE,[b,S]=T.elementsFromPointResults||[null,null];return d.checkElementVisibility(w,n,S,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=Z();await s.execute(r(t))}}}var $h,_r,gE,Hn,Wh=v(()=>{"use strict";pe();W();ue();we();$h=require("linkedom"),_r=P("locate-step-action"),gE={opacity:1,clientRects:{}};Hn=class extends V{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return yE(e)}static getFrameIdByTestimFrameId(){throw _r.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw _r.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw _r.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw _r.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw _r.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw _r.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var Vh={};H(Vh,{scroll:()=>bE});var bE,Gh=v(()=>{"use strict";bE=function(s,e,t,r,n,i,o,a){function l(w,b){if(!b)return{success:!1};elementScrollTo(b,w.x,w.y);let S=b.scrollLeft,E=b.scrollTop;return{success:Math.abs(E-w.y)<1&&Math.abs(S-w.x)<1,actualX:S,actualY:E}}function c(w,b){if(!t)return{x:n,y:i};let S=getLocatedElement(b);if(r&&!S)return{x:w.scrollWidth,y:w.scrollHeight};if(!S)throw new Error("could not find target element");let E=S.getBoundingClientRect(),A=0,D=0,j=Math.max(window.innerHeight-(E.height+10),0),R=Math.max(window.innerWidth-(E.width+10),0);return A=a?w.scrollTop+E.top-Math.min(i,j):w.scrollTop,D=o?w.scrollLeft+E.left-Math.min(n,R):w.scrollLeft,{x:Math.round(D),y:Math.round(A)}}let d=!s,m=d?document.scrollingElement||document.documentElement:getLocatedElement(s);if(!m)throw new Error("could not find target to scroll on");let u={top:m.scrollTop,left:m.scrollLeft},f=c(m,e),h=l(f,m);d&&!document.scrollingElement&&!h.success&&u.top===m.scrollTop&&u.left===m.scrollLeft&&(m=document.body,f=c(m,e),h=l(f,m));let g=h.actualX,y=h.actualY,T=getLocatedElement(e);if(t&&r&&!T)return{success:!1,expectedPosition:f};if(t){if(!T)throw new Error("could not find target to scroll to");let w=T.getBoundingClientRect();g=w.left,y=w.top}return{success:h.success,actualX:g,actualY:y}}});var Qo,Hh=v(()=>{"use strict";pe();Qo=class extends V{getFailureString(e,t,r,n,i){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${r}, x: ${t}); Actual:(y:${i}, x: ${n})`;let o="Scrolling limit reached";return e.shouldScrollTop&&(o+=`. Expected top margin: ${r}, actual: ${i}`),e.shouldScrollLeft&&(o+=`. Expected left margin: ${t}, actual: ${n}`),o}async scroll(e,t,r){let{codeSnippets:n,commonConstants:{stepResult:i}}=this.sessionPlayerInit,o=Math.round(Number(t.isScrollToElement?t.marginTop:t.y)),a=Math.round(Number(t.isScrollToElement?t.marginLeft:t.x)),l=this.driver.isFirefox()?function(m,u,f){m.scrollTo(u,f)}:function(m,u,f){m.scrollTop=f,m.scrollLeft=u},{scroll:c}=await Promise.resolve().then(()=>(Gh(),Vh)),d=`
|
|
217
217
|
const getLocatedElement = ${n.getLocatedElementCode};
|
|
218
218
|
const elementScrollTo = ${l.toString()};
|
|
219
219
|
const scroll = ${c.toString()};
|
|
220
220
|
return scroll.apply(null, arguments)
|
|
221
|
-
`;try{let m=await this.driver.executeJS(d,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,o,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:i.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:h}=m.value;return u?{success:!0}:{errorType:i.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,o,f,h)}}}catch{return{errorType:i.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,r=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,r):this.scrollOnElement(t,r)}}});var Gh,Hh=v(()=>{"use strict";Gh=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 qh,zh=v(()=>{"use strict";qh=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",n=typeof PointerEvent=="function",i={};window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(x){e({status:"done",result:x,success:!0})}function a(x){x||={},e({status:"failed",result:x,success:!1,keep:!0})}function l(x){return x!=null&&x.toLowerCase?(x=x.toLowerCase(),x==="text"?"text/plain":x==="url"?"text/uri-list":x):x}function c(){try{return new DataTransfer}catch{return{data:{},setData(O,B){i[l(O)]=B},getData(O){return i[l(O)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(x){let O=x;for(;O&&O!==document.documentElement;){if(O.draggable)return O;O=O.parentElement}return null}function h(x,O,B){let G=O.element,{dispatchDragEventsOnClosestDraggable:z}=B;if(d.includes(x.type)&&z){if(!G&&O.lastDraggedElement)return O.lastDraggedElement;let X=f(G);if(X)return O.lastDraggedElement=X,X}return G}function g(x,O,B){function G(St,Br,k){return k>St&&k<Br}let z=x.pointerPosition||{};if(O)return{x:z.originX||0,y:z.originY||0};let X=B.getBoundingClientRect(),fe=z.originX&&G(X.left,X.left+X.width,z.originX)?z.originX:X.left+X.width/2,Ze=z.originY&&G(X.top,X.top+X.height,z.originY)?z.originY:X.top+X.height/2;return{x:fe,y:Ze}}function y(x,O,B){let G=(O==null?void 0:O.modifiers)||{},z=g(x,B.isDrag,B.element),X=(O==null?void 0:O.button)||0,fe=x.event;return m.includes(fe)?w(fe,G,z.x,z.y,X):u.includes(fe)?S(fe,G,z.x,z.y):b(fe,G,z.x,z.y,X)}function T(x,O,B){return{screenX:0,screenY:0,clientX:O,clientY:B,ctrlKey:Boolean(x.ctrl),altKey:Boolean(x.alt),shiftKey:Boolean(x.shift),metaKey:Boolean(x.meta),bubbles:!0,cancelable:!0,composed:!0}}function w(x,O,B,G,z){if(n){let fe=T(O,B,G);return fe.pointerType="mouse",fe.isPrimary=!0,new window.PointerEvent(x,fe)}let X=document.createEvent("PointerEvent");return X.initPointerEvent(x,!0,!0,document.defaultView,1,0,0,B,G,Boolean(O.ctrl),Boolean(O.alt),Boolean(O.shift),Boolean(O.meta),z,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),X}function b(x,O,B,G,z){let X=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return X.initMouseEvent(x,!0,!0,document.defaultView,1,0,0,B,G,Boolean(O.ctrl),Boolean(O.alt),Boolean(O.shift),Boolean(O.meta),z,document.body?document.body.parentNode:document.documentElement),X}function S(x,O,B,G){if(x==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=c()),!r){let fe=document.createEvent("CustomEvent");return fe.initCustomEvent(x,!0,!0,null),Object.assign(fe,{dataTransfer:window.TSTA.dataTransfer}),fe}let z=T(O,B,G),X=new window.DragEvent(x,z);return Object.defineProperties(X,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),X}function E(x,O,B){let G=h(x,O,B);G==null||G.dispatchEvent(x)}function A(x,O){function B(){return x.event==="click"&&O.isDrag&&!O.allEventsOnSameElement}return B()}function D(x,O,B){if(B){let G=Math.min(B.timeStamp-O.timeStamp,40);setTimeout(()=>{j(x)},G)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),o()}function j(x){let O,B=x.events[x.eventIndex],G=x.events[++x.eventIndex];try{x.element=getLocatedElement(B.locatedElement),O=y(B,s,x)}catch(z){return a(`exception in get event in drag step:${z.message}`)}if(A(B,x))return D(x,B,G);if(O)try{E(O,x,B)}catch(z){return a(`exception in executeEvent in drag step:${z.message}`)}else return a(`cannot execute event ${B.event}`);D(x,B,G)}let R={eventIndex:0,allEventsOnSameElement:s.allEventsOnSameElement,events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement};setTimeout(()=>{try{j(R)}catch(x){a(x)}},0)}});var Kh={};H(Kh,{doClick:()=>bE});var bE,Jh=v(()=>{"use strict";bE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function r(b,S){var D;function E(j){function R(){return i(j).find(B=>[...B.classList||[]].includes("Select-control"))}function x(){let B=R();return B?B.querySelector("input"):null}let O=x();O==null||O.focus()}let A=(D=b.quirks)==null?void 0:D.isReactSelect;S.type==="mousedown"&&A&&E(b.element)}function n(b,S){var A;let E=(A=b.quirks)==null?void 0:A.isCKEditorFrame;S.type==="click"&&E&&document.body.focus()}function i(b){let S=[];for(;b!=null&&b.parentNode;)S.push(b),b=b.parentNode;return S}function o(b){let S={status:"done",result:b,success:!0,...w.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(S)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function l(b){let S=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");S.initEvent("mouseover",!0,!0),b.dispatchEvent(S)}function c(b){let S={},E=b.getBoundingClientRect(),A=E.left+E.width/2,D=E.top+E.height/2,x=f("mousemove",S,A,D,0);b.dispatchEvent(x)}function d(b,S){function E(x,O,B){return B>x&&B<O}let A=b.pointerPosition||{},D=S.getBoundingClientRect(),j=A.originX&&E(D.left,D.left+D.width,A.originX)?A.originX:D.left+D.width/2,R=A.originY&&E(D.top,D.top+D.height,A.originY)?A.originY:D.top+D.height/2;return{x:j,y:R}}function m(b,S,E){return{screenX:0,screenY:0,clientX:S,clientY:E,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function u(b,S,E,A){if(!window.PointerEvent)return;let D=m(S,E,A);return D.pointerType="mouse",D.isPrimary=!0,new window.PointerEvent(b,D)}function f(b,S,E,A,D){let j=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return j.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,E,A,Boolean(S.ctrl),Boolean(S.alt),Boolean(S.shift),Boolean(S.meta),D,document.body?document.body.parentNode:document.documentElement),j}function h(b,S){let E=["pointerup","pointerdown","pointermove"],A=S.modifiers||{},D=d(b,S.element),j=S.button||0,R=b.event;return E.includes(R)?u(R,A,D.x,D.y):f(R,A,D.x,D.y,j)}function g(){var S;let b=document.activeElement;for(;(S=b.shadowRoot)!=null&&S.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(S=>{try{return h(S,b)}catch{return}}).filter(Boolean).forEach(S=>{b.element.dispatchEvent(S),r(b,S),n(b,S)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let w={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!w.element){a("element not found");return}l(w.element),c(w.element);try{y(w);let b=g(),S=w.quirks,E=S==null?void 0:S.isReactSelect,A=S==null?void 0:S.isCKEditorFrame;!E&&!A&&dispatchFocus(s.elementToFocusLocatedElement,b),o()}catch(b){a(b.toString())}}});var Yh={};H(Yh,{doDragPath:()=>TE});var TE,Xh=v(()=>{"use strict";TE=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",n=40;window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(b){e({status:"done",result:b,success:!0})}function o(b){b||="",e({status:"failed",result:b,success:!1})}function a(b){let S=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");S.initEvent("mouseover",!0,!0),b.dispatchEvent(S)}function l(b){let S={},E=b.getBoundingClientRect(),A=E.left+E.width/2,D=E.top+E.height/2,x=u("mousemove",S,A,D,0);b.dispatchEvent(x)}function c(b,S){function E(x,O,B){return B>x&&B<O}let A=b.pointerPosition||{};if(w.isDrag)return{x:A.originX||0,y:A.originY||0};let D=S.getBoundingClientRect(),j=A.originX&&E(D.left,D.left+D.width,A.originX)?A.originX:D.left+D.width/2,R=A.originY&&E(D.top,D.top+D.height,A.originY)?A.originY:D.top+D.height/2;return{x:j,y:R}}function d(b,S,E){return{screenX:0,screenY:0,clientX:S,clientY:E,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function m(b,S,E,A,D){if(r){let R=d(S,E,A);return R.pointerType="mouse",R.isPrimary=!0,new window.PointerEvent(b,R)}let j=document.createEvent("PointerEvent");return j.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,E,A,Boolean(S.ctrl),Boolean(S.alt),Boolean(S.shift),Boolean(S.meta),D,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),j}function u(b,S,E,A,D){let j=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return j.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,E,A,Boolean(S.ctrl),Boolean(S.alt),Boolean(S.shift),Boolean(S.meta),D,document.body?document.body.parentNode:document.documentElement),j}function f(b,S){let E=["pointerup","pointerdown","pointermove"],A=S.modifiers||{},D=c(b,S.element),j=S.button||0,R=b.event;return E.includes(R)?m(R,A,D.x,D.y,j):u(R,A,D.x,D.y,j)}function h(b,S){function E(){return b.event==="click"&&S.isDrag&&!S.allEventsOnSameElement}return E()}function g(b,S,E){try{let A=f(S.events[b],S);h(A,S)||S.element.dispatchEvent(A)}catch{}if(b+1===S.events.length)E();else{let A=Math.min(S.events[b+1].timeStamp-S.events[b].timeStamp,n);setTimeout(()=>{g(b+1,S,E)},A)}}function y(b,S){g(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),S()})}let w={eventIndex:0,element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,quirks:s.quirks,isDoubleClick:s.isDoubleClick,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement,allEventsOnSameElement:s.allEventsOnSameElement};if(!w.element){o("element not found");return}a(w.element),l(w.element),y(w,()=>{i()})}});var qn,Zo,Qh=v(()=>{"use strict";qn=I(require("lodash"));pe();Hh();ue();zh();Zo=class extends V{getDnDRectsAndOffsets(e,t,r,n){let i=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),o=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:i.x,fromY:i.y,toRect:t.rectWithoutFrameOffset,toX:o.x,toY:o.y}}async clickJs(){var d;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3,i=e.events;if(!(i!=null&&i.length))return{success:!1,reason:"Malformed step: missing recorded events"};let o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:l}]=await Promise.all([Promise.resolve().then(()=>(Jh(),Kh)),Promise.resolve().then(()=>(Ln(),_n))]),c=`
|
|
221
|
+
`;try{let m=await this.driver.executeJS(d,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,o,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:i.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:h}=m.value;return u?{success:!0}:{errorType:i.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,o,f,h)}}}catch{return{errorType:i.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,r=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,r):this.scrollOnElement(t,r)}}});var qh,zh=v(()=>{"use strict";qh=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 Kh,Jh=v(()=>{"use strict";Kh=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",n=typeof PointerEvent=="function",i={};window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(x){e({status:"done",result:x,success:!0})}function a(x){x||={},e({status:"failed",result:x,success:!1,keep:!0})}function l(x){return x!=null&&x.toLowerCase?(x=x.toLowerCase(),x==="text"?"text/plain":x==="url"?"text/uri-list":x):x}function c(){try{return new DataTransfer}catch{return{data:{},setData(O,B){i[l(O)]=B},getData(O){return i[l(O)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(x){let O=x;for(;O&&O!==document.documentElement;){if(O.draggable)return O;O=O.parentElement}return null}function h(x,O,B){let G=O.element,{dispatchDragEventsOnClosestDraggable:z}=B;if(d.includes(x.type)&&z){if(!G&&O.lastDraggedElement)return O.lastDraggedElement;let X=f(G);if(X)return O.lastDraggedElement=X,X}return G}function g(x,O,B){function G(St,Br,k){return k>St&&k<Br}let z=x.pointerPosition||{};if(O)return{x:z.originX||0,y:z.originY||0};let X=B.getBoundingClientRect(),fe=z.originX&&G(X.left,X.left+X.width,z.originX)?z.originX:X.left+X.width/2,Ze=z.originY&&G(X.top,X.top+X.height,z.originY)?z.originY:X.top+X.height/2;return{x:fe,y:Ze}}function y(x,O,B){let G=(O==null?void 0:O.modifiers)||{},z=g(x,B.isDrag,B.element),X=(O==null?void 0:O.button)||0,fe=x.event;return m.includes(fe)?w(fe,G,z.x,z.y,X):u.includes(fe)?S(fe,G,z.x,z.y):b(fe,G,z.x,z.y,X)}function T(x,O,B){return{screenX:0,screenY:0,clientX:O,clientY:B,ctrlKey:Boolean(x.ctrl),altKey:Boolean(x.alt),shiftKey:Boolean(x.shift),metaKey:Boolean(x.meta),bubbles:!0,cancelable:!0,composed:!0}}function w(x,O,B,G,z){if(n){let fe=T(O,B,G);return fe.pointerType="mouse",fe.isPrimary=!0,new window.PointerEvent(x,fe)}let X=document.createEvent("PointerEvent");return X.initPointerEvent(x,!0,!0,document.defaultView,1,0,0,B,G,Boolean(O.ctrl),Boolean(O.alt),Boolean(O.shift),Boolean(O.meta),z,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),X}function b(x,O,B,G,z){let X=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return X.initMouseEvent(x,!0,!0,document.defaultView,1,0,0,B,G,Boolean(O.ctrl),Boolean(O.alt),Boolean(O.shift),Boolean(O.meta),z,document.body?document.body.parentNode:document.documentElement),X}function S(x,O,B,G){if(x==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=c()),!r){let fe=document.createEvent("CustomEvent");return fe.initCustomEvent(x,!0,!0,null),Object.assign(fe,{dataTransfer:window.TSTA.dataTransfer}),fe}let z=T(O,B,G),X=new window.DragEvent(x,z);return Object.defineProperties(X,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),X}function E(x,O,B){let G=h(x,O,B);G==null||G.dispatchEvent(x)}function A(x,O){function B(){return x.event==="click"&&O.isDrag&&!O.allEventsOnSameElement}return B()}function D(x,O,B){if(B){let G=Math.min(B.timeStamp-O.timeStamp,40);setTimeout(()=>{j(x)},G)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),o()}function j(x){let O,B=x.events[x.eventIndex],G=x.events[++x.eventIndex];try{x.element=getLocatedElement(B.locatedElement),O=y(B,s,x)}catch(z){return a(`exception in get event in drag step:${z.message}`)}if(A(B,x))return D(x,B,G);if(O)try{E(O,x,B)}catch(z){return a(`exception in executeEvent in drag step:${z.message}`)}else return a(`cannot execute event ${B.event}`);D(x,B,G)}let R={eventIndex:0,allEventsOnSameElement:s.allEventsOnSameElement,events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement};setTimeout(()=>{try{j(R)}catch(x){a(x)}},0)}});var Yh={};H(Yh,{doClick:()=>TE});var TE,Xh=v(()=>{"use strict";TE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function r(b,S){var D;function E(j){function R(){return i(j).find(B=>[...B.classList||[]].includes("Select-control"))}function x(){let B=R();return B?B.querySelector("input"):null}let O=x();O==null||O.focus()}let A=(D=b.quirks)==null?void 0:D.isReactSelect;S.type==="mousedown"&&A&&E(b.element)}function n(b,S){var A;let E=(A=b.quirks)==null?void 0:A.isCKEditorFrame;S.type==="click"&&E&&document.body.focus()}function i(b){let S=[];for(;b!=null&&b.parentNode;)S.push(b),b=b.parentNode;return S}function o(b){let S={status:"done",result:b,success:!0,...w.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(S)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function l(b){let S=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");S.initEvent("mouseover",!0,!0),b.dispatchEvent(S)}function c(b){let S={},E=b.getBoundingClientRect(),A=E.left+E.width/2,D=E.top+E.height/2,x=f("mousemove",S,A,D,0);b.dispatchEvent(x)}function d(b,S){function E(x,O,B){return B>x&&B<O}let A=b.pointerPosition||{},D=S.getBoundingClientRect(),j=A.originX&&E(D.left,D.left+D.width,A.originX)?A.originX:D.left+D.width/2,R=A.originY&&E(D.top,D.top+D.height,A.originY)?A.originY:D.top+D.height/2;return{x:j,y:R}}function m(b,S,E){return{screenX:0,screenY:0,clientX:S,clientY:E,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function u(b,S,E,A){if(!window.PointerEvent)return;let D=m(S,E,A);return D.pointerType="mouse",D.isPrimary=!0,new window.PointerEvent(b,D)}function f(b,S,E,A,D){let j=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return j.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,E,A,Boolean(S.ctrl),Boolean(S.alt),Boolean(S.shift),Boolean(S.meta),D,document.body?document.body.parentNode:document.documentElement),j}function h(b,S){let E=["pointerup","pointerdown","pointermove"],A=S.modifiers||{},D=d(b,S.element),j=S.button||0,R=b.event;return E.includes(R)?u(R,A,D.x,D.y):f(R,A,D.x,D.y,j)}function g(){var S;let b=document.activeElement;for(;(S=b.shadowRoot)!=null&&S.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(S=>{try{return h(S,b)}catch{return}}).filter(Boolean).forEach(S=>{b.element.dispatchEvent(S),r(b,S),n(b,S)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let w={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!w.element){a("element not found");return}l(w.element),c(w.element);try{y(w);let b=g(),S=w.quirks,E=S==null?void 0:S.isReactSelect,A=S==null?void 0:S.isCKEditorFrame;!E&&!A&&dispatchFocus(s.elementToFocusLocatedElement,b),o()}catch(b){a(b.toString())}}});var Qh={};H(Qh,{doDragPath:()=>wE});var wE,Zh=v(()=>{"use strict";wE=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",n=40;window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(b){e({status:"done",result:b,success:!0})}function o(b){b||="",e({status:"failed",result:b,success:!1})}function a(b){let S=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");S.initEvent("mouseover",!0,!0),b.dispatchEvent(S)}function l(b){let S={},E=b.getBoundingClientRect(),A=E.left+E.width/2,D=E.top+E.height/2,x=u("mousemove",S,A,D,0);b.dispatchEvent(x)}function c(b,S){function E(x,O,B){return B>x&&B<O}let A=b.pointerPosition||{};if(w.isDrag)return{x:A.originX||0,y:A.originY||0};let D=S.getBoundingClientRect(),j=A.originX&&E(D.left,D.left+D.width,A.originX)?A.originX:D.left+D.width/2,R=A.originY&&E(D.top,D.top+D.height,A.originY)?A.originY:D.top+D.height/2;return{x:j,y:R}}function d(b,S,E){return{screenX:0,screenY:0,clientX:S,clientY:E,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function m(b,S,E,A,D){if(r){let R=d(S,E,A);return R.pointerType="mouse",R.isPrimary=!0,new window.PointerEvent(b,R)}let j=document.createEvent("PointerEvent");return j.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,E,A,Boolean(S.ctrl),Boolean(S.alt),Boolean(S.shift),Boolean(S.meta),D,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),j}function u(b,S,E,A,D){let j=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return j.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,E,A,Boolean(S.ctrl),Boolean(S.alt),Boolean(S.shift),Boolean(S.meta),D,document.body?document.body.parentNode:document.documentElement),j}function f(b,S){let E=["pointerup","pointerdown","pointermove"],A=S.modifiers||{},D=c(b,S.element),j=S.button||0,R=b.event;return E.includes(R)?m(R,A,D.x,D.y,j):u(R,A,D.x,D.y,j)}function h(b,S){function E(){return b.event==="click"&&S.isDrag&&!S.allEventsOnSameElement}return E()}function g(b,S,E){try{let A=f(S.events[b],S);h(A,S)||S.element.dispatchEvent(A)}catch{}if(b+1===S.events.length)E();else{let A=Math.min(S.events[b+1].timeStamp-S.events[b].timeStamp,n);setTimeout(()=>{g(b+1,S,E)},A)}}function y(b,S){g(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),S()})}let w={eventIndex:0,element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,quirks:s.quirks,isDoubleClick:s.isDoubleClick,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement,allEventsOnSameElement:s.allEventsOnSameElement};if(!w.element){o("element not found");return}a(w.element),l(w.element),y(w,()=>{i()})}});var qn,Zo,ey=v(()=>{"use strict";qn=I(require("lodash"));pe();zh();ue();Jh();Zo=class extends V{getDnDRectsAndOffsets(e,t,r,n){let i=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),o=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:i.x,fromY:i.y,toRect:t.rectWithoutFrameOffset,toX:o.x,toY:o.y}}async clickJs(){var d;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3,i=e.events;if(!(i!=null&&i.length))return{success:!1,reason:"Malformed step: missing recorded events"};let o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:l}]=await Promise.all([Promise.resolve().then(()=>(Xh(),Yh)),Promise.resolve().then(()=>(Ln(),_n))]),c=`
|
|
222
222
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
223
223
|
var dispatchFocus = ${l.toString()};
|
|
224
224
|
var doClick = ${a.toString()};
|
|
225
225
|
var eventData = arguments[0];
|
|
226
226
|
var done = arguments[1];
|
|
227
227
|
return doClick.call(null, eventData, done);
|
|
228
|
-
`;try{return(d=(await this.driver.executeCodeAsync(c,n,o)).value)!=null&&d.success?{success:!0}:{success:!1}}catch(m){return{success:!1,reason:m.message,exception:m}}}isWithinBounds(e,t,r){return r>e&&r<t}getEventSequenceOffset(){var l;let e=(l=this.step.events[0])==null?void 0:l.pointerPosition;if(!e)return{xOffset:0,yOffset:0};let r=this.getTarget().rectWithoutFrameOffset,n=this.isWithinBounds(r.left,r.left+r.width,e.originX),i=this.isWithinBounds(r.top,r.top+r.height,e.originY),o=n?0:r.left+r.width/2-e.originX,a=i?0:r.top+r.height/2-e.originY;return{xOffset:o,yOffset:a}}addOffsetToEvents(e){this.step.events.forEach(t=>{t!=null&&t.pointerPosition&&(t.pointerPosition.originX+=e.xOffset,t.pointerPosition.originY+=e.yOffset)})}generateEventOfType(e,t){let r=qn.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(qn.findLastIndex(e,c=>c.event==="mousemove")||o&&qn.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(()=>(
|
|
228
|
+
`;try{return(d=(await this.driver.executeCodeAsync(c,n,o)).value)!=null&&d.success?{success:!0}:{success:!1}}catch(m){return{success:!1,reason:m.message,exception:m}}}isWithinBounds(e,t,r){return r>e&&r<t}getEventSequenceOffset(){var l;let e=(l=this.step.events[0])==null?void 0:l.pointerPosition;if(!e)return{xOffset:0,yOffset:0};let r=this.getTarget().rectWithoutFrameOffset,n=this.isWithinBounds(r.left,r.left+r.width,e.originX),i=this.isWithinBounds(r.top,r.top+r.height,e.originY),o=n?0:r.left+r.width/2-e.originX,a=i?0:r.top+r.height/2-e.originY;return{xOffset:o,yOffset:a}}addOffsetToEvents(e){this.step.events.forEach(t=>{t!=null&&t.pointerPosition&&(t.pointerPosition.originX+=e.xOffset,t.pointerPosition.originY+=e.yOffset)})}generateEventOfType(e,t){let r=qn.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(qn.findLastIndex(e,c=>c.event==="mousemove")||o&&qn.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(()=>(Zh(),Qh)),Promise.resolve().then(()=>(Ln(),_n))]),c=`
|
|
229
229
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
230
230
|
var dispatchFocus = ${l.toString()};
|
|
231
231
|
var doDragPath = ${a.toString()};
|
|
232
232
|
return doDragPath.apply(null, arguments);
|
|
233
233
|
`;try{return(m=(await this.driver.executeCodeAsync(c,n,o)).value)!=null&&m.success?{success:!0}:{success:!1}}catch(u){return{success:!1,reason:u.message,exception:u}}}async chooseAndRunAction(){let e=this.getTarget(),{locatedElement:t,seleniumElement:r,rectWithoutFrameOffset:n,rect:i}=e,o={frameOffset:{x:i.left-n.left,y:i.top-n.top},rect:n,clickOffset:this.stepActionUtils.getClickOffset(this.step.element.clickOffset,n)};if(_.flags.skipFileInputClicks.isEnabled()&&e.tagName==="INPUT"&&(e.elementSymbol.includes('type="file"')||e.elementSymbol.includes("type='file'")||e.elementSymbol.includes("type=file")))return{keep:!0,success:"skipped",reason:"Clicking on input type=file is disabled"};if(this.step.isDoubleClick){let d={elementToFocusLocatedElement:e.elementToFocusLocatedElement,locatedElement:t,events:this.step.events,timeout:this.context.data.timeToPlayStep+3e3};return this.driver.doubleClick(r,d,o)}if(this.step.isDrag){if(this.step.toElement){let d=this.context.data.toElement;if(this.step.isHTML5Drag){if(_.flags.usePortedHtml5DragDrop.isEnabled()){let h=this.generateHTML5DragEventSequence(),g=this.context.data.timeToPlayStep+3e3,y=this.getTarget(),T={transactionId:`${this.context.testResultId}:${this.step.id}`,id:this.step.id,testResultId:this.context.testResultId,eventType:this.step.type,events:h,eventData:{modifiers:this.step.modifiers,button:this.step.button},quirks:this.step.quirks,isDrag:this.step.isDrag,useRecordedMousedown:this.step.useRecordedMousedown,allEventsOnSameElement:this.step.allEventsOnSameElement,elementToFocusLocatedElement:y.elementToFocusLocatedElement,trackActiveElement:this.step.trackActiveElement,locatedElement:y.locatedElement,isRoot:y.isRoot},w=`
|
|
234
234
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
235
|
-
var dnd = ${
|
|
235
|
+
var dnd = ${Kh.toString()};
|
|
236
236
|
var eventData = arguments[0];
|
|
237
237
|
var done = arguments[1];
|
|
238
238
|
return dnd.call(null, eventData, done);
|
|
239
239
|
`;return this.driver.executeCodeAsync(w,g,T)}let u=`
|
|
240
240
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
241
|
-
var dnd = ${
|
|
241
|
+
var dnd = ${qh.toString()};
|
|
242
242
|
var eventData = arguments[0];
|
|
243
243
|
return dnd.call(null, eventData);
|
|
244
|
-
`,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(u,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,d.seleniumElement,m)}return this.dragPathJs()}let l=this.driver.isSafari()&&this.step.button===2,c=this.driver.isSafari()&&e.tagName==="SELECT";return c?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!c&&(!this.step.nativeEvents||l)?this.clickJs():this.step.button===2?this.driver.rightClick(r,o):this.driver.leftClick(r,o)}async performAction(){let e=await this.chooseAndRunAction();if(!e.status&&e.value&&e.value.keep&&(e=e.value),e.keep)return delete e.keep,e}addDragendIfNeeded(e){if(e.some(r=>r.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,r;if(!((r=(t=this.context.data)==null?void 0:t.toElement)!=null&&r.rect))return;let{rect:e}=this.context.data.toElement;return{originX:e.left+e.width/2,originY:e.top+e.height/2}}addDragOverBeforeDragEnd(e){let t=e.findIndex(n=>["dragend","drop"].includes(n.event)),r=e[t-1];if(!r||r.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else Object.assign(r,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let n=i=>i.fireOnTarget||["drop","dragenter"].includes(i.event);return e.forEach(i=>Object.assign(i,{locatedElement:n(i)?r:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(n=>Object.assign(n,{dispatchDragEventsOnClosestDraggable:!0})),r}}});var zn,
|
|
244
|
+
`,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(u,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,d.seleniumElement,m)}return this.dragPathJs()}let l=this.driver.isSafari()&&this.step.button===2,c=this.driver.isSafari()&&e.tagName==="SELECT";return c?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!c&&(!this.step.nativeEvents||l)?this.clickJs():this.step.button===2?this.driver.rightClick(r,o):this.driver.leftClick(r,o)}async performAction(){let e=await this.chooseAndRunAction();if(!e.status&&e.value&&e.value.keep&&(e=e.value),e.keep)return delete e.keep,e}addDragendIfNeeded(e){if(e.some(r=>r.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,r;if(!((r=(t=this.context.data)==null?void 0:t.toElement)!=null&&r.rect))return;let{rect:e}=this.context.data.toElement;return{originX:e.left+e.width/2,originY:e.top+e.height/2}}addDragOverBeforeDragEnd(e){let t=e.findIndex(n=>["dragend","drop"].includes(n.event)),r=e[t-1];if(!r||r.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else Object.assign(r,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let n=i=>i.fireOnTarget||["drop","dragenter"].includes(i.event);return e.forEach(i=>Object.assign(i,{locatedElement:n(i)?r:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(n=>Object.assign(n,{dispatchDragEventsOnClosestDraggable:!0})),r}}});var zn,ty=v(()=>{"use strict";pe();zn=class extends V{async performAction(){let{step:e,context:t,sessionPlayerInit:{stepParamExpressionEvaluator:r,utils:n,commonConstants:i}}=this,o=this.getTarget();try{let a=await this.stepActionUtils.extractTargetText(o),{evaluatedText:l}=r.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return n.compareOrMatch(l,a)?{success:!0}:{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(l),actual:a}}}catch{return{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:l.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var ry,vE,ea,sy=v(()=>{"use strict";ry=I(require("lodash"));pe();W();vE=P("evaluate-expression-step-action"),ea=class extends V{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{vE.info("runner running incoming params evaluation");let i=t.incomingParams||{};ry.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 ny={};H(ny,{setText:()=>SE});var SE,iy=v(()=>{"use strict";SE=function(s,e){let t=typeof Event=="function",r=s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),n={eventIndex:0,element:r,events:s.events,eventType:s.eventType,quirks:s.quirks};if(!r)throw new Error("element not found");window.__unloadNavigator=function(){Ze()},window.addEventListener("unload",window.__unloadNavigator);let i=new Set(["keydown","keyup","keypress"]),o=15;function a(k){try{if(!t)return;let N=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return k.eventData&&(N.data=k.eventData.data),N}catch{}}function l(k){try{let N=document.createEvent("TextEvent");N.data=k.eventData.data;let $=1,K=k.eventData.locale||"en-US";return N.initTextEvent("textInput",!0,!0,window,k.eventData.data,$,K),N}catch{}}function c(k){return a(k)||l(k)}function d(k,N,$){try{return new KeyboardEvent(k,{bubbles:!0,cancelable:!0,location:N.location||0,key:N.key||"",ctrlKey:Boolean($.ctrl),shiftKey:Boolean($.shift),altKey:Boolean($.alt),metaKey:Boolean($.meta)})}catch{}}function m(k,N,$){try{let K=document.createEvent("KeyboardEvent");return K.initKeyEvent(k,!0,!0,null,Boolean($.ctrl),Boolean($.alt),Boolean($.shift),Boolean($.meta),N.key||"",0),K}catch{}}function u(k,N,$){try{let K=document.createEvent("Events");return K.initEvent(k,!0,!0),Object.assign(K,{altKey:Boolean($.alt),ctrlKey:Boolean($.ctrl),metaKey:Boolean($.meta),shiftKey:Boolean($.shift),keyCode:N.key||""}),K}catch{}}function f(k,N,$){return d(k,N,$)||m(k,N,$)||u(k,N,$)}function h(k){if(!i.has(k.event))return null;let N=k.eventData,$=N.modifiers||{},K=f(k.event,N,$);return Object.defineProperties(K,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(K,{_keyCode_:N.keyCode,_charCode_:N.charCode||0}),K}function g(k){return k.event==="textInput"?c(k):h(k)}function y(k,N){return(()=>{var K;return k.event==="textInput"&&!((K=N.quirks)!=null&&K.isAuth0Form)})()}function T(k,N){return k.event==="keyup"&&N.event==="keydown"?o:0}function w(k,N){let $=T(k,N);return Math.min(N.timeStamp-k.timeStamp,$)}function b(k){let N=Object.getOwnPropertyDescriptor(k,"value");if(!N)return;let $=k.value;k.value=`${$}#`,N.configurable&&delete k.value,k.value=$;let K=document.createEvent("HTMLEvents");K.initEvent("input",!0,!1),k.dispatchEvent(K),Object.defineProperty(k,"value",N)}function S(k){if(G(k.element))try{if(b(k.element),t)k.element.dispatchEvent(new Event("change"));else{let N=document.createEvent("HTMLEvents");N.initEvent("change",!1,!0),k.element.dispatchEvent(N)}}catch{}}function E(k,N,$){$?setTimeout(()=>{B(k)},w(N,$)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),S(k),Ze())}function A(k,N){return(k==="change"||k==="blur")&&N.element.tagName==="OPTION"}function D(k,N,$){return A(k.type,N)?N.element.parentElement:$.locatedElement?getLocatedElement($.locatedElement):N.element}function j(k,N){let $=k.firstChild,K;for(;$;){if($.nodeType===3){if(N.offset--<=0)return $}else if($.nodeType===1&&(K=j($,N),K))return K;$=$.nextSibling}return null}function R(k,N){if(!(!k||!N)){if(!isNaN(N.start))Object.assign(k,{selectionStart:N.start,selectionEnd:N.end});else if(!isNaN(N.nodeOffset)){let $;if(k.firstChild?$=j(k,{offset:N.nodeOffset}):$=k,$){let K=window.getSelection(),Pe=document.createRange();try{K.removeAllRanges(),Pe.setStart($,N.textOffset),Pe.setEnd($,N.textOffset),K.addRange(Pe)}catch{}}}}}function x(k,N){return k==="submit"&&Boolean(N.action)}function O(k,N,$){if(N.isFocusable&&N.isSelectable(k)&&k.type!=="submit")try{R(N.element,$.eventData.selection)}catch{}let K=D(k,N,$);if(!K)throw new Error("could not find element");x(k.type,K)?K.submit():K.dispatchEvent(k)}function B(k){let N,$=k.events[k.eventIndex],K=k.events[++k.eventIndex];try{N=g($)}catch(Pe){return St(`exception in get event in text step:${Pe.message}`)}if(y($,k))return E(k,$,K);if(N)try{O(N,k,$)}catch(Pe){return St(`exception in executeEvent in text step:${Pe.message}`)}else if(k.noEventExecuter)k.noEventExecuter(k,$);else return St(`cannot execute event ${$.event}`);E(k,$,K)}function G(k){let N=k.tagName;return N==="INPUT"||N==="TEXTAREA"}function z(k){return k.getAttribute?Boolean(k.getAttribute("contenteditable")==="true"):!1}function X(k,N){if(G(k.element)){k.element.value=N.eventData.text;let $=document.createEvent("Event");$.initEvent("input",!0,!1),k.element.dispatchEvent($)}else k.isContentEditable&&(k.element.innerHTML=N.eventData.text)}function fe(){var N;let k=document.activeElement;for(;(N=k.shadowRoot)!=null&&N.activeElement;)k=k.shadowRoot.activeElement;return k}function Ze(k){let N={status:"done",result:k,success:!0,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(N)}function St(k){k||="";let N={status:"failed",result:k,success:!1,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(N)}try{let k=G(n.element);n.isContentEditable=z(n.element),!k&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=k||n.isContentEditable,n.isSelectable=N=>N.type!=="keyup",n.noEventExecuter=X}catch(k){St(`exception in set text step:${k.message}`);return}let Br=fe();dispatchFocus(s.elementToFocusLocatedElement,Br),B(n)}});var ta,oy=v(()=>{"use strict";pe();F();ta=class extends V{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(Le(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var h;let{step:{events:e,type:t,quirks:r},context:n,sessionPlayerInit: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(()=>(iy(),ny)),Promise.resolve().then(()=>(Ln(),_n))]),u=`
|
|
245
245
|
var getLocatedElement = ${i.codeSnippets.getLocatedElementCode};
|
|
246
246
|
var dispatchFocus = ${m};
|
|
247
247
|
var setText = ${d.toString()};
|
|
248
248
|
var eventData = arguments[0];
|
|
249
249
|
var done = arguments[1];
|
|
250
250
|
return setText.call(null, eventData, done);
|
|
251
|
-
`,f=await this.driver.executeCodeAsync(u,a,c);return{success:Boolean((h=f.value)==null?void 0:h.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let r=0;r<e.length;r++)await this.driver.elementIdValue(Le(t.seleniumElement),e[r]),r<e.length-1&&await ce(this.step.delayBetweenChars||0)}async setValueAppendNative(){let e=[],t=this.context,r=this.getTarget();if(r!=null&&r.seleniumElement)return this.step.delayBetweenChars?this.setTextDelayed():(e.push(Array.from(t.stepText)),this.driver.elementIdValue(Le(r.seleniumElement),e));throw new Error("missing selenium element")}async performAction(){let e=this.getTarget(),t=this.driver.isSafari()&&e.locatedElement&&e.locatedElement.shadowPath&&Array.isArray(e.locatedElement.shadowPath)&&e.locatedElement.shadowPath.length>1;return this.step.nativeEvents&&!t?this.setValueNative():this.setValueJS()}}});var
|
|
251
|
+
`,f=await this.driver.executeCodeAsync(u,a,c);return{success:Boolean((h=f.value)==null?void 0:h.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let r=0;r<e.length;r++)await this.driver.elementIdValue(Le(t.seleniumElement),e[r]),r<e.length-1&&await ce(this.step.delayBetweenChars||0)}async setValueAppendNative(){let e=[],t=this.context,r=this.getTarget();if(r!=null&&r.seleniumElement)return this.step.delayBetweenChars?this.setTextDelayed():(e.push(Array.from(t.stepText)),this.driver.elementIdValue(Le(r.seleniumElement),e));throw new Error("missing selenium element")}async performAction(){let e=this.getTarget(),t=this.driver.isSafari()&&e.locatedElement&&e.locatedElement.shadowPath&&Array.isArray(e.locatedElement.shadowPath)&&e.locatedElement.shadowPath.length>1;return this.step.nativeEvents&&!t?this.setValueNative():this.setValueJS()}}});var ay={};H(ay,{runCode:()=>EE});var EE,cy=v(()=>{"use strict";EE=function(s,e){var d;function t(m,u){let f=`data-testim-${m}`,h="Native sessionStorage is not available";function g(y){return y!=null&&y.toString?y.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(g))throw new Error(h);let T={...JSON.parse(window.sessionStorage.getItem(f)||"{}"),...u};window.sessionStorage.setItem(f,JSON.stringify(T))}catch(y){let T=y.message.toLowerCase().includes("quota"),w=y.message===h;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||T||w){let b=document.head.querySelector("#testim-storage-backup");b||(b=document.createElement("meta"),b.id="testim-storage-backup",document.head.append(b));let E={...JSON.parse(b.getAttribute(f)||"{}"),...u};if(b.setAttribute(f,JSON.stringify(E)),T||w)try{window.sessionStorage.removeItem(f)}catch{}return}throw y}}function r(m){return m.function?m.function.args.map(u=>u!=null&&u.locatedElement?getLocatedElement(u.locatedElement):u):m.directParams.map(u=>u.selector?document.querySelector(u.selector):u.value).concat(m.otherParams)}function n(m,u){function f(){return m.apply(null,u)}return f.prototype=m.prototype,new f}let i={},o={},a={},l=s.functionParams,c=s.transactionId;try{let m=r(s);m.push(i,o,a);let u=((d=s.function)==null?void 0:d.params)||l,h=(e||n(Function,u)).apply(null,m);typeof Promise<"u"&&h instanceof Promise?(t(c,{type:"promise"}),h.then(g=>{t(c,{status:"done",success:!0,result:{resultValue:g,exports:i,exportsTest:o,exportsGlobal:a}})},g=>{t(c,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:i,exportsTest:o,exportsGlobal:a}})})):t(c,{status:"done",success:!0,result:{resultValue:h,exports:i,exportsTest:o,exportsGlobal:a}})}catch(m){t(c,{status:"failed",success:!1,result:{resultValue:m.toString(),exports:i,exportsTest:o,exportsGlobal:a}})}}});var ra,Kn,ir,sa=v(()=>{"use strict";ra=I(require("lodash"));F();pe();W();ue();Kn=P("base-js-step-action"),ir=class extends V{isExceedingMaxResultSize(t,r){var n;try{let i=(n=r.project.defaults)==null?void 0:n.enforceMaximumJsResultSize,o=_.flags.maximumJsResultSize.getValue(),a=JSON.stringify(t).length>o;return i?a:(a&&Kn.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=>{ra.isObject(o)&&ki(o,"seleniumElement",ra.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){Kn.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{Kn.warn("non object value",{selRes:c}),d={status:"exception"}}let m=n.abortedSteps.find(u=>u.id===i);return m||(d?d.status==="done"?d:d.status==="failed"?{success:!1,shouldRetry:!0,result:d.result}:a-o<=0?Object.assign(d,{success:!1,shouldRetry:!0}):(a-=o,await ce(o),l()):{success:!0})};return l()}async executeInAut(t){let r=_.flags.experimentalPreCodeCompilation.isEnabled(),n=_.flags.experimentalAsyncCustomCode.isEnabled(),i=this.constructJSFunParams(t),o=i.function.args.some(m=>Boolean(m==null?void 0:m.locatedElement)),a="undefined";if(r){let m=i.function.params.slice(0,-1);a=n?`async function(${m.join(",")}) {
|
|
252
252
|
${t.code}
|
|
253
253
|
};`:`function(${m.join(",")}) {
|
|
254
254
|
${t.code}
|
|
255
|
-
};`,i.function.params.pop()}let{codeSnippets:l}=this.sessionPlayerInit,{runCode:c}=await Promise.resolve().then(()=>(
|
|
255
|
+
};`,i.function.params.pop()}let{codeSnippets:l}=this.sessionPlayerInit,{runCode:c}=await Promise.resolve().then(()=>(cy(),ay)),d=`
|
|
256
256
|
${o?`var getLocatedElement = ${l.getLocatedElementCode};`:";"}
|
|
257
257
|
var runCode = ${c.toString()};
|
|
258
258
|
var eventData = arguments[0];
|
|
259
259
|
var funcToRun = ${a};
|
|
260
260
|
return runCode.call(null, eventData, funcToRun);
|
|
261
|
-
`;if(!r)return this.driver.executeJS(d,i);try{return await this.driver.executeJS(d,i)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:i={},tstConsoleLogs:o,nodeVersion:a,navigateToDifferentDomain:l}=t;i.exports&&(n.data.exports=i.exports);let c={nodeVersion:a,tstConsoleLogs:o,data:n.data};return this.isFailedResult(i.resultValue)?{...c,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:i,tstConsoleLogs:o},n)?{...c,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...c,success:!0,exportsTest:i.exportsTest,exportsGlobal:i.exportsGlobal,...l&&{navigateToDifferentDomain:l}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this;if(t.type==="promise")return{data:n.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return{...t,errorType:r.STOPPED};let{result:i={},tstConsoleLogs:o}=t;return{tstConsoleLogs:o,data:n.data,exportsGlobal:i.exportsGlobal,exportsTest:i.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:i.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}getTransactionId(t,r){var i;let n=t.id;return t.id||(Kn.warn("step.id doesn't exist on step",{step:t,context:r}),n=r.stepResultId),"stepResultId"in r&&((i=r.stepResultId)!=null&&i.length)?n=r.stepResultId:Kn.warn("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,
|
|
261
|
+
`;if(!r)return this.driver.executeJS(d,i);try{return await this.driver.executeJS(d,i)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:i={},tstConsoleLogs:o,nodeVersion:a,navigateToDifferentDomain:l}=t;i.exports&&(n.data.exports=i.exports);let c={nodeVersion:a,tstConsoleLogs:o,data:n.data};return this.isFailedResult(i.resultValue)?{...c,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:i,tstConsoleLogs:o},n)?{...c,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...c,success:!0,exportsTest:i.exportsTest,exportsGlobal:i.exportsGlobal,...l&&{navigateToDifferentDomain:l}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this;if(t.type==="promise")return{data:n.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return{...t,errorType:r.STOPPED};let{result:i={},tstConsoleLogs:o}=t;return{tstConsoleLogs:o,data:n.data,exportsGlobal:i.exportsGlobal,exportsTest:i.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:i.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}getTransactionId(t,r){var i;let n=t.id;return t.id||(Kn.warn("step.id doesn't exist on step",{step:t,context:r}),n=r.stepResultId),"stepResultId"in r&&((i=r.stepResultId)!=null&&i.length)?n=r.stepResultId:Kn.warn("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,ly=v(()=>{"use strict";sa();Wt=class extends ir{isFailedResult(e){return e===!1}}});var vs,uy=v(()=>{"use strict";sa();vs=class extends ir{isFailedResult(e){return!e}}});var na,py=v(()=>{"use strict";pe();F();Yo();na=class extends V{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(Le(t.seleniumElement),e):Promise.reject(new Error("missing selenium element"))}performAction(){let e=[],t=this.step.events[0].eventData.keyCode;return t>=32&&t<=127?e.push(String.fromCharCode(t)):e.push(Gn[t]),this.setWithValueApi(e)}}});var ia,dy=v(()=>{"use strict";pe();Yo();ia=class extends V{async performAction(){var i,o;let e=this.context.config.os.startsWith("Mac");if(e&&!((i=this.step.keys)!=null&&i.mac)||!e&&!((o=this.step.keys)!=null&&o.windows))return;let t=[],r=e?this.step.keys.mac:this.step.keys.windows;r.altKey&&t.push("\uE052"),r.ctrlKey&&t.push("\uE051"),r.metaKey&&t.push("\uE03D"),r.shiftKey&&t.push("\uE050");let n=r.keyCode;if(n>=32&&n<=127)t.push(r.key);else if(Gn[n])t.push(Gn[n]);else throw new Error(`Invalid key with keyCode ${n}.`);return await this.driver.sendKeyboardShortcut(t)}}});var my={};H(my,{selectOption:()=>IE});function IE(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 fy=v(()=>{"use strict"});var oa,gy=v(()=>{"use strict";pe();F();ue();oa=class extends V{async performAction(){var u,f;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,i=(await this.driver.getBrowserAndOS()).browserMajor,o=this.driver.isSafari(),a=Boolean((u=this.step.element)==null?void 0:u.isShadowed);if(!o||o&&i>=13&&!a)try{return await this.driver.elementIdClick(Le(t))}catch(h){if(!h.message.includes("Cannot check the displayedness of a non-Element argument"))throw h}let{selectOption:l}=await Promise.resolve().then(()=>(fy(),my)),c=_.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),d=`
|
|
262
262
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
263
263
|
const isNativeFunction = ${this.sessionPlayerInit.utils.isNativeFunction.toString()};
|
|
264
264
|
const selectOption = ${l.toString()};
|
|
265
265
|
return selectOption.apply(null, arguments);
|
|
266
|
-
`;return(f=(await this.driver.executeJS(d,r,c)).value)!=null&&f.success?{success:!0}:{success:!1}}}});var aa,
|
|
266
|
+
`;return(f=(await this.driver.executeJS(d,r,c)).value)!=null&&f.success?{success:!0}:{success:!1}}}});var aa,hy=v(()=>{"use strict";pe();aa=class extends V{async performAction(){await this.driver.submit(this.getTarget().seleniumElement)}}});var RE,ca,yy=v(()=>{"use strict";pe();RE=(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(){}}),ca=class extends V{getRect(){return this.driver.isFirefox()?this.getTarget().rectWithoutFrameOffset:this.getTarget().rect}async performAction(){let e=this.getTarget(),{seleniumElement:t,rectWithoutFrameOffset:r,rect:n}=e,{width:i,height:o}=n,a=i/2,l=o/2,c=this.step.element.clickOffset;if(c&&this.step.shouldAccountForMouseOffsetInHover){let{x:m,y:u}=c;this.sessionPlayerInit.utils.isWithinTargetRect(RE(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 by={};H(by,{wheel:()=>xE});var xE,Ty=v(()=>{"use strict";xE=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 la,wy=v(()=>{"use strict";pe();la=class extends V{async performAction(){var m;let{step:e,context:t}=this,{events:r,modifiers:n,button:i}=e;if(!(r!=null&&r.length))return;let o={events:r,eventData:{modifiers:n,button:i},locatedElement:this.getTarget().locatedElement},a=t.data.timeToPlayStep+3e3,{wheel:l}=await Promise.resolve().then(()=>(Ty(),by)),c=`
|
|
267
267
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
268
268
|
var wheel = ${l.toString()};
|
|
269
269
|
var eventData = arguments[0];
|
|
270
270
|
var done = arguments[1];
|
|
271
271
|
return wheel.call(null, eventData, done);
|
|
272
|
-
`;return{success:((m=(await this.driver.executeCodeAsync(c,a,o)).value)==null?void 0:m.state)==="success"}}}});var
|
|
272
|
+
`;return{success:((m=(await this.driver.executeCodeAsync(c,a,o)).value)==null?void 0:m.state)==="success"}}}});var vy={};H(vy,{downloadFileAndFireDropEvent:()=>AE});var AE,Sy=v(()=>{"use strict";AE=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 CE,ua,Ey=v(()=>{"use strict";pe();W();ue();CE=P("drop-file-step-action"),ua=class extends V{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:r,step:n}=this,i=this.getTarget(),o=_.flags.overrideAzureStorageUrl.isEnabled(),a=await t.addTokenToFileUrls(r.project.id,n.fileUrls,this.stepActionUtils.testimServicesApi,o,CE),{downloadFileAndFireDropEvent:l}=await Promise.resolve().then(()=>(Sy(),vy)),c=`
|
|
273
273
|
const getLocatedElement = ${e.getLocatedElementCode};
|
|
274
274
|
const createDropEvent = ${e.createDropEvent.toString()};
|
|
275
275
|
const downloadFileAndFireDropEvent = ${l.toString()};
|
|
276
276
|
return downloadFileAndFireDropEvent.apply(null, arguments)
|
|
277
|
-
`;return await this.driver.executeJS(c,i.locatedElement,a)}}});function
|
|
277
|
+
`;return await this.driver.executeJS(c,i.locatedElement,a)}}});function xy(s={width:"2px",height:"2px",left:"0px",top:"400px"}){return`function getVisibleElement(locatedElement) {
|
|
278
278
|
var input = getLocatedElement(locatedElement);
|
|
279
279
|
if(input) {
|
|
280
280
|
function parents(element, _elements) {
|
|
@@ -316,7 +316,7 @@ Please make sure the CLI has stable access to the internet. ${Rc()?"(Internal: n
|
|
|
316
316
|
input.removeAttribute("disabled");
|
|
317
317
|
input.focus();
|
|
318
318
|
}
|
|
319
|
-
}`}async function
|
|
319
|
+
}`}async function kE(s,e){let t=null;try{t=(await Rc(s)).body}catch(n){if(PE.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=`${Iy.tmpdir()}/${e}`;return await Ry.promises.writeFile(r,t),r}function OE(s){return se(s,e=>kE(e.url,e.name))}function _E(s,e){return e(s)}async function Ay(s,e){let t=await OE(s),r=await se(t,n=>_E(n,e));return Array.isArray(r)&&r.map(n=>n==null?void 0:n.value)}var Iy,Ry,PE,Cy=v(()=>{"use strict";Iy=I(require("os"));Ve();Ry=require("fs");F();W();PE=P("input-file-utils")});function DE(){return`async function downloadAndUpload(locatedElement, fileUrls) {
|
|
320
320
|
const fileIsNative = typeof window.File === 'function' && (window.File.toString().indexOf('native code') > -1);
|
|
321
321
|
const File = fileIsNative ? window.File : (function obtainSafeGlobals() {
|
|
322
322
|
const attachTo = document.body || document.documentElement;
|
|
@@ -393,31 +393,31 @@ Please make sure the CLI has stable access to the internet. ${Rc()?"(Internal: n
|
|
|
393
393
|
element.dispatchEvent(new Event("change", { bubbles: true }));
|
|
394
394
|
}
|
|
395
395
|
element.removeEventListener("change", changeFiredHandler, true);
|
|
396
|
-
}`}var pa,da,
|
|
396
|
+
}`}var pa,da,Py=v(()=>{"use strict";Cy();pe();W();F();ue();pa=P("input-file-step-action"),da=class extends V{constructor(){super(...arguments);this.uploadFile=t=>this.driver.uploadFile(t)}forceInputToBeVisible(t,r){pa.info("workaround - stepaction - move element to visible position");let n=`
|
|
397
397
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
398
|
-
var getVisibleElement = ${
|
|
398
|
+
var getVisibleElement = ${xy(r)};
|
|
399
399
|
return getVisibleElement.apply(null, arguments);
|
|
400
400
|
`;return this.driver.executeJS(n,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(n){throw pa.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 pa.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(Le(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=_.flags.overrideAzureStorageUrl.isEnabled(),n=_.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:i,context:o,step:a,stepActionUtils:l,driver:c}=this,d=await i.utils.addTokenToFileUrls(o.project.id,a.fileUrls,l.testimServicesApi,r,pa);if(d.length===0)throw new Error("No files urls to upload");if(n&&(d=await Promise.all(d.map(async({name:u,url:f})=>{let h=await Mt(f);return{name:u,url:`data:${h.type};base64,${Buffer.from(h.body).toString("base64")}`}}))),c.isSafari()||c.isFirefox()||c.isEdgeChromium()){await this.driver.executeJS(`
|
|
401
401
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
402
|
-
const downloadAndUploadFile = ${
|
|
403
|
-
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Ry(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ma,fa,Cy=v(()=>{"use strict";ma=require("url");pe();fa=class extends V{async updateBaseUrl(e){let t=new ma.URL(e),r=new ma.URL(this.context.recordedBaseUrl),n=new ma.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 ga,Py=v(()=>{"use strict";pe();U();ga=class extends V{async performAction(){await ce(this.step.durationMS||0)}}});var ha,ky=v(()=>{"use strict";pe();ha=class extends V{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Jn,Oy=v(()=>{"use strict";pe();Jn=class extends V{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let i=await this.driver.executeCodeAsync(r,t,e);return(i==null?void 0:i.value)||{}}catch(i){throw(n=i==null?void 0:i.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):i}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},i=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),o=i.result||{},a={method:t.method,status:o.status,url:t.url};return i.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.exception?void 0:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var ya,_y=v(()=>{"use strict";pe();ya=class extends V{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var Ly,ju,$u,Dy=v(()=>{"use strict";Ly=I(require("@applitools/spec-driver-webdriverio"));fi();we();ju=class{constructor(){let{EyeSdkBuilder:e}=Z(),t=fd["@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:Ly.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=Z(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},$u=new ju});var My,Ny,Yn,Fy=v(()=>{"use strict";My=I(require("lodash"));pe();W();Dy();Ny=P("pixel-validation-step-action"),Yn=class extends V{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,l=await $u.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"};My.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),Ny.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){Ny.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await $u.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Ss,Wu=v(()=>{"use strict";hs();Y();sa();Ss=class extends ir{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:i="",id:o=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await gs(i,o,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof oe?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var or,Uy=v(()=>{"use strict";Wu();or=class extends Ss{isFailedResult(e){return e===!1}}});var ba,By=v(()=>{"use strict";Wu();ba=class extends Ss{isFailedResult(e){return!e}}});var Ta,jy=v(()=>{"use strict";hs();pe();Y();Ta=class extends V{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await fs(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof Rt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof oe?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Lr,$y=v(()=>{"use strict";pe();Lr=class extends V{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var be,Wy=v(()=>{"use strict";pe();be=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var wa,Vy=v(()=>{"use strict";pe();wa=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var va,Gy=v(()=>{"use strict";pe();va=class extends V{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function DE(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Sa(s,e){DE(NE,e),e.registerLocateStepActionUtils(Hn.getUtils(s))}var NE,Vu=v(()=>{"use strict";jh();Vh();Qh();Zh();ty();ny();ay();cy();ly();uy();my();fy();gy();by();vy();Ay();Cy();Py();ky();Oy();_y();Fy();Uy();By();jy();$y();Wy();Vy();Gy();NE={locate:Hn,scroll:Qo,mouse:Zo,submit:aa,text:ta,"special-key":na,"user-code":Wt,"validation-code-step":Wt,"wait-for-code-step":Wt,"action-code-step":Wt,"condition-step":vs,"skip-code-step":vs,"element-code-step":vs,"evaluate-expression":ea,"text-validation":zn,"wait-for-text-validation":zn,"select-option":oa,"drop-file":ua,"input-file":da,hover:ca,navigation:fa,wheel:la,sleep:ga,refresh:ha,"keyboard-shortcut-step":ia,"api-validation":Jn,"api-action":Jn,"api-code-step":Wt,"extract-text":ya,"simple-ui-verification":Yn,"wait-for-simple-ui-verification":Yn,"cli-validation-download-file":Lr,"cli-wait-for-download-file":Lr,"network-validation-step":Lr,"cli-validation-code-step":or,"cli-wait-for-code-step":or,"cli-action-code-step":or,"cli-api-code-step":or,"cli-condition-step":ba,"node-package":Ta,"email-code-step":Wt,"cli-email-code-step":or,"sfdc-internal-test-step":va,"sfdc-recorded-step":wa,"sfdc-step-login":be,"sfdc-step-loginas":be,"sfdc-step-logout":be,"sfdc-step-sobjectcreate":be,"sfdc-step-sobjectdelete":be,"sfdc-step-findrecord":be,"sfdc-step-quickaction":be,"sfdc-step-sobjectedit":be,"sfdc-step-sobjectvalidate":be,"sfdc-step-launchapp":be,"sfdc-step-wait-for-page-load":be,"sfdc-step-closeconsoletabs":be,"sfdc-step-relatedlistaction":be,"sfdc-step-permission-validation":be,"sfdc-step-convert-lead-to-opportunity":be,"sfdc-step-quotelineeditor":be,"sfdc-document-validation":Lr,"sfdc-step-flow-screen-completion":be,"sfdc-step-sobjectverifyoptions":be}});var Hy,ME,Es,Gu=v(()=>{"use strict";Hy=["simple-ui-verification","wait-for-simple-ui-verification"],ME=[...Hy,"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=ME.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 Hy.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 zy={};H(zy,{SeleniumTestPlayer:()=>Xn});var qy,FE,Xn,Hu=v(()=>{"use strict";U();qy=require("@applitools/eyes-sdk-core");Dn();Y();W();Du();Nh();Uu();Yo();Uh();Bu();we();Vu();Gu();FE=P("SeleniumTestPlayer"),Xn=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Es(Xo());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=Z();this.driver=n??new Ar;let d=new Jo(this.driver);this.stepActionFactory=new c(d),Sa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new zo(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=Fh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new ws(this.driver),FrameLocator:m,portSelector:Ko,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:qy.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Z(),t=1e3*60*2;try{await le((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof oe&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){FE.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 zu={};H(zu,{WorkerSelenium:()=>qu});function BE(s){let{playback:e}=Z().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>M(`Got event ${t}`))}var Ea,UE,qu,Ku=v(()=>{"use strict";U();je();Vn();W();Pt();Oo();ie();_u();Y();Hu();we();at();Ea=P("worker-selenium"),UE=1e9,qu=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){M("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new Ts(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await o.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),M("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),M("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,UE),await this.windowUtils.validatePageIsAvailable(),M("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof It||d||m?new It(`Page '${l}' is not available`):(Ea.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Ji(),initializedFromCache:Yi()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=Z(),{driver:o,sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),BE(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 Fn(this.options))[this.testId]);let d=async()=>le(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(f)}),this.testRunTimeout,Me.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof oe&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(Ea.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&&(Ea.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});o.start(),M("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),M("right after super.runTestOnce in workerSelenium");let u=await d();return M("right after runSeleniumTest"),u}catch(u){throw Ea.error("failed to run test once",{err:u}),u}}}});var Ky,Jy,Ge,jE,$E,Ju,vt,Ia=v(()=>{"use strict";Ky=I(require("ora")),Jy=require("jimp");de();Ve();ge();W();ie();we();ue();Ge=P("mobile-grid-service"),jE="https://tdc.tricentis-cloud.com",$E="https://ui.headspin.io",Ju=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||cc}/${uc}/devices`:t===L.TESTIM_TDC?`${r||lc}/${uc}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),i=this.buildRequestBody(e,t);try{await We({url:r,headers:n,body:i})}catch(o){throw Ge.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await Te(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw Ge.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await Hs(`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 Zn({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===L.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===L.SAUCELABS)return e.testobject_device_name;if(t===L.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n,i=!1){let{executionId:o,testId:a,testResultId:l}=e,{project:c,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===L.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:w}=Z();y=w(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,c,d,m,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await Ir(c,o,a,l,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),Ge.info("device details updated on testResult",{testResultId:l,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===L.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),l=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:l}}try{let{AppiumApi:o}=Z(),a=new o(t,r.sessionId,null,i),[l,c]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),d=Buffer.from(l,"base64"),m=await Jy.Jimp.fromBuffer(d),u=m.bitmap.width,f=m.bitmap.height;return{scaleFactor:u/c.width,width:u,height:f}}catch(o){return Ge.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,i,o,a,l,c,d){let[m,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n,d),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:l,gridId:c})]),f=this.getOsVersion(e,i);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...m}}async buildRemoteResultLink(e,t,r){return e.type===L.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Us}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===L.SAUCELABS?r.testobject_test_report_url:e.type===L.TESTIM_TVC?r.replayUrl:e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC?`${e.type===L.TESTIM_HEADSPIN?$E:jE}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let n=(await Te(`${e}/api/devices`)).find(i=>i.udid===t);if(!n)throw new Error(`device ${t} not found`);return{udid:n.udid,name:n.name,model:n.model,height:n.height,width:n.width,geo:"local",osVersion:n.osVersion,osType:n.deviceType.toLowerCase(),scaleFactor:n.scaleFactor??0,isVirtual:n.virtual??!1,minApiVersion:n.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:i,testResultId:o}=r,{project:a,localTmaUrl:l}=t,c=await this.getTmaDeviceDetails(l,e);return await Ir(a,n,i,o,"RUNNING",{device:c}),Ge.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:c}),c}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(_.flags.allowFixingAppIdStructure.isEnabled()&&(Ge.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Xu({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 Qn({appId:e,projectId:t});return{appUrl:`${he}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(kd*60))+1)*60*1e3,Math.max(Pd,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,Ky.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 Yu({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),Ge.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){Ge.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else Ge.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===L.BROWSERSTACK||f===L.TESTIM_TVC||f===L.P_CLOUDY;if(g){let T=t.projectData.type,w=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});w&&(Ge.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=g),!w&&y&&(Ge.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!w&&!y&&Ge.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:i,host:o,key:a,type:l,apiUrl:c}=t;if(l===L.BROWSERSTACK){let u=`${Us}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(l===L.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a})).items.some(h=>h.id===e)}if(l===L.TESTIM_HEADSPIN||l===L.TESTIM_TDC){let u=`${c}/${pc}/apps`;return c||(u=`${l===L.TESTIM_HEADSPIN?cc:lc}/${pc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===L.TESTIM_TVC){let u=`${Od}/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 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 Te(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await Te(e,void 0,i)}},vt=new Ju});function Yy({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"&&!WE.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function VE({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 GE(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 HE(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===L.TESTIM_TDC,a=s===L.TESTIM_HEADSPIN,l=o?"tdc":"headspin",c=a&&_.flags.enableBatchHeadSpin.isEnabled(),d=o&&(_.flags.enableBatchTDC.isEnabled()||_.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=_.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture.video`]:!0,..._.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...i&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:GE(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function Ra(s){return"id"in s?s.id:s.packageName}function qE(s,e){return{[`${e===L.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function zE({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=qE(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":Ra(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":Ra(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Nr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:i="",shouldRunInEnhancedMode:o}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:o?"WaldoTestim":"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:Ra(t)},...r&&{[`${i}app`]:r},...e};case"android":return{platformName:"Android",[`${i}autoGrantPermissions`]:!0,[`${i}automationName`]:o?"WaldoTestim":"UiAutomator2",...n&&{[`${i}appWaitActivity`]:`${n}, *`},...t&&{[`${i}appPackage`]:Ra(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Xy({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o,shouldRunInEnhancedMode:a}){let l=HE(o.type,i,n);return zE({projectType:s,sessionCaps:l,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function Aa({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 Ca({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?dc:i.deviceNameRegex:t==="ios"&&r===L.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":dc:".*")}function KE(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 JE(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...xa(s,Is)}}function Qy(s,e,t){return s?Object.entries(s).reduce((r,[n,i])=>{if(e(n)){if(!t)return r[n]=i,r;let o=n.replace(t,"");r[o]=i}return r},{}):{}}function YE(s){return Qy(s,e=>e.startsWith("browserstack."),"browserstack.")}function XE(s){return Qy(s,e=>!e.startsWith("browserstack."))}function Zy(s){return!s||!eb(s)?"2.0.0":s}function eb(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function tb({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=eb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function xa(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}async function QE({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=KE(i,s),h=await Zn({gridId:i.gridId,projectType:s,projectId:n.project,companyId:n.company.companyId}),g=h==null?void 0:h.find(({udid:S})=>{var E;return((E=m.staticAllocation)==null?void 0:E.deviceUdid)===S}),y=(g==null?void 0:g.osVersion)??Aa({osVersion:c,mobileConfig:m}),T=(g==null?void 0:g.name)??Ca({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),w=qe(n.editorUrl,n.project,o.testId,o.testResultId,o.branch),b={device:T,os_version:y,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":w,...l&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return Nr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:l})}function ZE({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=i,h=_.flags.enableAppium2pCloudy.isEnabled(),g=Aa({osVersion:l,mobileConfig:d}),y=Ca({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(_d),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=JE(b)),t="",Nr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Is}})}function eI({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=Aa({osVersion:l,mobileConfig:d}),f=Ca({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Dr.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],tb({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},w={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:Zy(g.appiumVersion),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,...xa(h,Is),"sauce:options":{...T,...w,...(0,Dr.omit)(g,"appiumVersion")}};return Nr({projectType:s,sessionCaps:b,appiumPrefix:Is,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:u,deviceName:f,tags:Object.values(o),name:o.testResultId,build:o.executionId,...h,...g};return Nr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function tI({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=Aa({osVersion:l,mobileConfig:d}),f=Ca({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=YE(n.browserstack),g=(0,Dr.omit)(XE(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:w}=n.browserstack||{},b=_.flags.enableAppium2BrowserStack.isEnabled();if(b||tb({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let E={userName:i.user,accessKey:i.key,appiumVersion:b?"2.0.1":Zy(h.appiumVersion),projectName:y||o.project,buildName:T||o.executionId,debug:!0,networkLogs:!0},A={"appium:platformVersion":u,"appium:deviceName":f,...xa(g,Is),"bstack:options":{...E,...(0,Dr.omit)(h,"appiumVersion")}};return Nr({projectType:s,sessionCaps:A,appiumPrefix:Is,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let S={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:w||o.testResultId,project:y||o.project,build:T||o.executionId,buildTags:Object.values(o).join(","),"browserstack.user":i.user,"browserstack.key":i.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,...xa(h,"browserstack.")};return Nr({projectType:s,sessionCaps:S,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}async function rI(s){if(L.TESTIM_TDC===s.gridInfo.type||L.TESTIM_HEADSPIN===s.gridInfo.type)return Xy(s);if(L.TESTIM_TVC===s.gridInfo.type)return await QE(s);if(L.P_CLOUDY===s.gridInfo.type)return ZE(s);if(L.SAUCELABS===s.gridInfo.type)return eI(s);if(L.BROWSERSTACK===s.gridInfo.type)return tI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function sI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,l={};return n==="dynamic"&&(!i&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!o&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),i&&(l.manufacturer=i),o&&(l.os_version=o),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}async function rb(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}`);Yy({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=vt.getGridConnection(e),l=await rI(s);if(e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC){let y=e.type===L.TESTIM_HEADSPIN?"headspin":"tdc",T=sI(r,i==null?void 0:i.mobile);if(!(0,Dr.isEmpty)(T)){let w=Object.entries(T).map(([b,S])=>S.split(",").map(E=>E===".*"||E==="="?"":`${b}:${E}`).join(",")).join(" ").trim();l[`${y}:selector`]=w}}let c=e.type===L.TESTIM_TVC?{alwaysMatch:l}:l,d=_.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,Qu.default)("2m"),f=(0,Qu.default)("12m"),h=mr(_.flags.appiumConnectionRetryCount.getValue(),m),g=mr(_.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&g<f&&(g=f),{...a,desiredCapabilities:l,connectionRetryTimeout:g,capabilities:c,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function sb(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;Yy({nativeAppMetadata:r,appPath:i,gridInfo:t}),VE({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((g=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await vt.getGridDirectConnection(t,d),f=Xy({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 nb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=Nr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function ib(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 Qu,Dr,Is,WE,Zu=v(()=>{"use strict";Qu=I(require("ms"));ue();ie();Ia();Dr=require("lodash");U();de();ge();Is="appium:",WE=[L.BROWSERSTACK,L.SAUCELABS,L.TESTIM_HEADSPIN,L.TESTIM_TDC,L.TESTIM_TVC,L.P_CLOUDY]});var Pa,ab=v(()=>{"use strict";Pa=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var ka,cb=v(()=>{"use strict";U();ka=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Qs;this.getLinksFromUnescapeHTML=Zs}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 ep,Oa,lb=v(()=>{"use strict";W();ep=P("mobile-frame-locator-mock"),Oa=class{foundFrameCallback(){return ep.info("foundFrameCallback-mock invoked"),{}}locate(){return ep.info("locate-mock invoked"),{}}async findFrame(){return ep.info("findFrame-mock invoked"),{}}}});var nI,pb,ub,Rs,tp=v(()=>{"use strict";nI=I(require("webdriverio")),pb=require("@applitools/eyes-sdk-core");ab();Uu();W();cb();Bu();we();Vu();lb();Gu();ub=P("appium-test-player"),Rs=class{constructor(e,t,r,n=nI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=Z(),m=new ka(this.driver);this.stepActionFactory=new c(m),Sa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Es(Xo()),this.sessionPlayer=new a(e,{tabService:new Pa,cookieUtils:void 0,FrameLocator:Oa,portSelector:Ko,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:pb.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()),ub.info("appium session deleted",{...i}))}catch(o){ub.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=Z();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function iI(s){return await Te(`${s}/api/status`)}async function db(s,e){return await Te(`${s}/api/devices/${e}/status`)}async function mb(s){if((await iI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var fb=v(()=>{"use strict";Ve()});var gb={};H(gb,{WorkerLocalTma:()=>ip});var Mr,rp,sp,np,ip,hb=v(()=>{"use strict";Ve();Zu();Vn();U();W();Pt();tp();we();fb();Ia();Mr=P("worker-appium"),rp=class extends Error{},sp=class extends Error{},np=class extends Error{},ip=class extends Ot{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Rs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=Z(),{DOMParser:n}=await import("linkedom"),i=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n,!1);return t.sessionPlayer.playbackManager.appiumApi=i,i}async getBrowserOnce(t,r,n,i){var E;if(Q.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:l}=this.options;await mb(o);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{mobileApp:A}=await vt.getMobileAppDataByAppId({appId:f,projectId:c,token:d});t.nativeApp=A}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:w,version:b},S]=await Promise.all([this.getAppStateFromDevice(o,a,T),db(o,a)]).catch(A=>{throw this.handleDeviceNotFoundError(A),A});if(Mr.info("device status and app state",{deviceStatus:S,appInstalled:w,version:b,executionId:this.executionId,testResultId:this.testResultId}),!w&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!w&&y&&(await this.installApp(o,a,y),Mr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let A={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(E=this.options.projectData)==null?void 0:E.name}-${this.options.project}`},D=nb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:A,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),j={capabilities:{udid:a,...D}};Mr.info("requesting new appium session from TMA",{tmaSessionSettings:j,executionId:this.executionId,testResultId:this.testResultId});let R=await this.requestNewAppiumSessionFromTma(o,j,g);this.sessionData=R;let x=await m.attach({sessionId:R.sessionId,capabilities:D,options:{capabilities:D}});this.device=await vt.updateTmaDeviceDetails(a,this.options,t),Mr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:x.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:x.capabilities})}catch(A){throw Mr.error("failed to start application",{err:A}),A}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await We({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new np(l):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,l=(await Te(o)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await Mt(n);await Gs(`${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 sp(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 rp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=Z(),{sessionPlayer:o}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await i.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Mr.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Mr.error("failed to run test once",{err:c}),c}}}});var bb={};H(bb,{WorkerAppium:()=>op});var yb,Fr,op,Tb=v(()=>{"use strict";U();Zu();yb=require("linkedom");Vn();W();Pt();tp();we();Ia();ie();os();Fr=P("worker-appium"),op=class extends Ot{initPlayer(t){return new Rs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){let o=this.options.projectData.type,a=(o==="android"||o==="ios")&&await t.isTestRecordedWithEnhancedMode();if(i.type!==L.TESTIM_TVC&&a)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Q.onGetSession(this.id,this.testName,t.runMode);let{driver:l}=n,c=await vt.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),d=o==="android"?t.androidActivityWait:null,m=t.nativeAppMetadata;if(!m)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let u={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.uniqueId}`},f={projectType:o,nativeAppMetadata:m,appPath:c,androidActivityWait:d,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await vt.lockDevice(i,this.options.deviceUdid),h=await sb(f)):h=await rb({...f,shouldRunInEnhancedMode:a}),Fr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:m,capabilities:ib(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await l.remote(h),this.device=await vt.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,a);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),Fr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(u){throw Fr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:u}),u}}startKeepAlive(t){let{errors:r}=Z(),n=async()=>{try{await t.getOrientation()}catch(i){Fr.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"&&Bf(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){Fr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===L.TESTIM_HEADSPIN||i===L.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===L.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:n,path:i}=this.activeSession.options;if(t&&r&&n&&i)return`${t}://${r}:${n}${i}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=Z(),{sessionPlayer:a}=r,l=n||"runner",c=this.options.timeout;Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let d;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:w,port:b,path:S}=await vt.getHeadSpinDeviceConnection(this.options.gridData,y);d=`${T}://${w}:${b}${S}`}else d=this.getDirectAddressConnection()||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(h=this.options.company)==null?void 0:h.companyId,device:this.device},a.playbackManager.appiumApi=new i(d,this.activeSession.sessionId,yb.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 Fr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:y}),this.stopKeepAlive(),y}};try{return await super.runTestOnce(t,r),await le(u(),c)}catch(y){throw Fr.error("failed to run test once",{err:y}),y}}getUserAgentString(){return"Testim/CI-Branch:runner-v4.151.0"}}});var _a,wb=v(()=>{"use strict";U();Dn();Y();_a=class{constructor(e){this.id=e;this.driver=new Ar}async onDone(){try{await le(this.driver.end(),12e4)}catch(t){t instanceof oe&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var vb,La,Sb=v(()=>{"use strict";vb=I(require("ws"));U();La=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 vb.default(this._cdpUrl,{timeout:e}),r=Kt(i=>{t.once("open",i)}),n=Kt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",i=>this.onCDPMessage(i)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let i=this._lastWsId++,o=new Promise((l,c)=>{this._cdpCallbacks.set(i,{resolve:l,reject:c})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var Na,ap,Da,Eb=v(()=>{"use strict";U();Na=I(require("chrome-launcher"));Ao();Sb();In();ap=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new La}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=xo({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)??[],...Na.Launcher.defaultFlags().filter(w=>w!=="--disable-extensions")];this.chrome=await Na.launch({chromeFlags:u,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let f=await gr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),as(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},Da=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new ap(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var cp={};H(cp,{WorkerExtension:()=>ei});function oI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Ib(s){return oI(s)?s:new Error(s)}var dt,ei,Ma=v(()=>{"use strict";je();Y();Vn();U();W();Pt();ie();wb();Eb();at();dt=P("worker-ext"),ei=class extends Ot{initPlayer(){return this.options.useChromeLauncher?new Da(this.id):new _a(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw dt.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Ji(),initializedFromCache:Yi(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var i;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((i=this.options.browserstack)!=null&&i["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:i}=this;M("WorkerExtension runTestOnce");let o=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await le(e.runTestUsingCDP(d.cdpTestRunner),m,Me.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof oe))throw u;return dt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw dt.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:i,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(M("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw dt.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await le(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Me.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof oe))throw T;dt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),dt.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:i}),m.unregisterToClosedBrowser(y),T.type=zs.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=le(e.onCompleted(),this.testRunTimeout,Me.TEST_COMPLETE_TIMEOUT_MSG),w=await yc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(w.success),w.reason)}catch(E){dt.error("Could not update the grid about the test status",{err:E})}m.isAlive()||(dt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(dt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.keepAliveIssue=b),{...w,...e.seleniumPerfStats.getStats()}}catch(T){throw dt.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:i}),Ib(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw dt.warn("failed to start url",{err:h}),Ib(h)}};t.driver.start();try{return await super.runTestOnce(e,t),M("WorkerExtension super.runTestOnce"),await c()}catch(d){throw dt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var up={};H(up,{WorkerExtensionSingleBrowser:()=>lp});var aI,cI,lp,pp=v(()=>{"use strict";je();U();W();Cu();Pt();Ma();aI=P("base-worker"),cI=500,lp=class extends ei{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()&&(aI.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let i=this.handleQuarantine(t);if(i)return i;M("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=o.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ce(cI)}}});var dp,Fa,Rb=v(()=>{"use strict";Dn();de();je();bl();at();lu();Y();W();ie();bh();Uo();dp=P("worker-manager"),Fa=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(()=>(Ku(),zu))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(hb(),gb))).WorkerLocalTma:(await Promise.resolve().then(()=>(Tb(),bb))).WorkerAppium;default:return Nn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(pp(),up))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(Ma(),cp))).WorkerExtension}else switch(r){case(Or.find(n=>n===r)&&Nn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(pp(),up))).WorkerExtensionSingleBrowser;case Or.find(n=>n===r):return(await Promise.resolve().then(()=>(Ma(),cp))).WorkerExtension;case jn.find(n=>n===r):return(await Promise.resolve().then(()=>(Ku(),zu))).WorkerSelenium;default:throw new C(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],n=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return M("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{M("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,l){if(e&&e.length===0)return;let c=!1,d=0,m=(u,f)=>new Promise(h=>{var fe,Ze,St,Br,k,N,$,K;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new Fo(r,n,e,i,o,t),this.combinedTestResults={};let T=((fe=i.company)==null?void 0:fe.ucid)||"",w=(Ze=i.company)==null?void 0:Ze.companyId,b=(St=i.company)==null?void 0:St.name,S=i.source||"cli",E=i.user,A=(Br=i.company)==null?void 0:Br.planType,D=(k=i.company)==null?void 0:k.isStartUp,j=(N=i.projectData)==null?void 0:N.name,R=($=i.projectData)==null?void 0:$.type,x=i.lightweightMode,O=(K=i.gridData)==null?void 0:K.type,B=(Pe,Et,ve,ec,ii,tc)=>(d++,Ef({executionId:r,projectId:g,testId:Et,resultId:ve,ucid:T,companyId:w,companyName:b,projectName:j,companyPlan:A,source:S,user:E,lightweightMode:x,isStartUp:D,projectType:R,appSource:tc,gridType:O}),t.testStartAndReport(Pe,r,ve,ec,ii)),G=async(Pe,Et,ve,ec,ii,tc)=>{var cd,ld,ud;d--;let et={...(x==null?void 0:x.onlyTestIdsNoSuite)&&{show:!0},...ve.seleniumStats&&{seleniumStats:ve.seleniumStats},...ve.gridIssues&&{gridIssues:ve.gridIssues},...ve.keepAliveIssue&&{keepAliveIssue:ve.keepAliveIssue},...i.host&&{gridHost:i.host}};if(ve.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ve.seleniumPerfMarks),delete ve.seleniumPerfMarks),i.grid||i.gridId?(et.gridName=i.grid||((cd=i.gridData)==null?void 0:cd.name),et.gridType=(ld=i.gridData)==null?void 0:ld.type,et.gridProvider=(ud=i.gridData)==null?void 0:ud.provider):i.localTmaUrl?(et.gridName="local-tma-from-options",et.gridType="local-tma"):i.useLocalChromeDriver?(et.gridName="local-chrome-driver-from-options",et.gridType="local-chrome"):i.useChromeLauncher?(et.gridName="chrome-launcher-from-options",et.gridType="local-chrome"):i.browserstack?et.gridName="browserstack-from-options":i.saucelabs&&(et.gridName="saucelabs-from-options"),await t.testEndAndReport(Pe,ve,r,ec,ii,et).catch($T=>dp.error("testEndAndReport threw an error",{err:$T})),ii)return;this.combinedTestResults[ve.resultId]=ve,If({executionId:r,projectId:g,testId:Et,resultId:ve.resultId,result:ve,ucid:T,companyId:w,companyName:b,projectName:j,companyPlan:A,source:S,user:E,lightweightMode:x,logger:dp,isStartUp:D,projectType:R,appSource:tc}),l&&!ve.success&&(this.executionQueue.stop(),c=!0),(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},z=(Pe,Et)=>{this.combinedTestResults[Et.resultId]=Et,t.onTestIgnored(Pe,Et.resultId),d--,(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},X=(Pe,Et)=>t.onGridSlot(Pe,Et);for(i.userData={loginData:{...wr(),refreshToken:zi(),authData:wr(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:he},M("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,B,G,X,z)});try{let u=await At(),f=await Ki(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),c)throw new qt;return h}catch(u){throw dp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var mp,ae,xb=v(()=>{"use strict";mp=class{static colorString(e,t){return`${e}${t}${mp.Reset}`}},ae=mp;ae.Reset="\x1B[0m",ae.Bright="\x1B[1m",ae.Dim="\x1B[2m",ae.Underscore="\x1B[4m",ae.Blink="\x1B[5m",ae.Reverse="\x1B[7m",ae.Hidden="\x1B[8m",ae.FgBlack="\x1B[30m",ae.FgRed="\x1B[31m",ae.FgGreen="\x1B[32m",ae.FgYellow="\x1B[33m",ae.FgBlue="\x1B[34m",ae.FgMagenta="\x1B[35m",ae.FgCyan="\x1B[36m",ae.FgWhite="\x1B[37m",ae.FgGray="\x1B[90m",ae.BgBlack="\x1B[40m",ae.BgRed="\x1B[41m",ae.BgGreen="\x1B[42m",ae.BgYellow="\x1B[43m",ae.BgBlue="\x1B[44m",ae.BgMagenta="\x1B[45m",ae.BgCyan="\x1B[46m",ae.BgWhite="\x1B[47m",ae.BgGray="\x1B[100m"});var ti,Ab,Ua,fp,gp,Ur,hp=v(()=>{"use strict";ti=I(require("lodash"));U();W();de();ie();je();ts();yl();bl();ge();ue();Pt();ug();Y();Rb();Uo();Ab=require("uuid");xb();({CLI_MODE:Ua}=Ft),fp=P("test-plan-runner"),gp=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}static get id(){return gp._id}async runTestAllPhases(e,t,r,n,i,o,a,l){let c={},d=new Fa(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=yi||i.parallel,y=!1;M("right before this.workerManager.runTests");let T=await d.runTests(t,l,o,a,i,n,g,y);M("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await d.runTests(r,l,o,a,i,n,g,y);Object.assign(c,T)};Rf({executionId:o,projectId:i.project}),M("right before runBeforeTests");try{return await m(),M("right before runTestPlanTests"),await u(),M("right after runTestPlanTests"),await f(),c}catch(g){if(fp.error("error running test plan",{err:g}),g instanceof qt)return l.markAllQueuedTests(o,me.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,w,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===Ua.SELENIUM){let[{getSessionPlayer:S},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(we(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:A}=S();await A.closeBatch(o,E);return}let g;try{if(!((b=(w=(T=i.company)==null?void 0:T.activePlan)==null?void 0:w.premiumFeatures)!=null&&b.applitools)||(g=await wp(i.project),ti.default.isEmpty(g)||!o))return;let{runKey:S,url:E}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[o],serverUrl:E,apiKey:S}})}catch{}}}async runTestPlan(e,t,r,n,i,o,a,l){var b,S,E;let c=re(),d=n.project;Gd(c),e.forEach(A=>Object.assign(A,{isBeforeTestPlan:!0})),r.forEach(A=>Object.assign(A,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new To(m,n,o,a),f=ti.default.chain(m).map(A=>{var D;return((D=A.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(A=>A.name),y=(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,i,g);M("before testListInfoPromise");let T=await y;(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,c,l,h),M("before runTestAllPhases");let w=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,i||"All Tests",u);return M("before executionEnd"),await u.executionEnd(c),M("after executionEnd"),{results:w,executionId:c,testPlanName:i,configName:h}}isJsonString(e){try{JSON.parse(e)}catch{return!1}return!0}handleReportFailure(e,t){try{e.text?t=e.text:t=JSON.stringify(e)}catch{}console.error(ae.colorString(ae.FgMagenta,t)),process.exit(-1)}async reportTestRunnerStarted(e,t){try{return await yp(e,t.testOptimization)}catch(r){return this.handleReportFailure(r,"Failed Report: Test Runner Started")}}async reportTestRunnerFinished(e){try{return await bp(e)}catch(t){return this.handleReportFailure(t,"Failed Report: Test Runner Finished")}}async runTestPlans(e,t){fp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return ti.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a={testPlans:[],testPlansData:{}};_.flags.enableTestPlanAggregation.isEnabled()?(await se(e.testPlanIds,async d=>{let m=await ri(o,e.testPlan,[d],t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})}),await se(e.testPlan,async d=>{let m=await ri(o,[d],e.testPlanIds,t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})})):a=await ri(o,e.testPlan,e.testPlanIds,t,e.intersections);let l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Ua.APPIUM&&await xu(e,r(c)),await se(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await uf(e,d);let f=u.overrideExecutionName||d.name;return await se(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(E=>({executionId:E,status:Ru(n[m][E])})),w=Object.keys(n[m]).map(E=>n[m][E]).reduce((E,A)=>Object.assign(E,A),{}),b=Ru(w);Object.assign(i,w);let S=b?T[0].executionId:T.find(E=>!E.status).executionId;return await Tp(o,m,{success:b,executions:T,executionId:S}),y})})}async runAnonymousTestPlan(e,t){var l;fp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),M("before getSuite");let r=await wh(e,t);if(M("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new C("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new C("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new C("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let i=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),o=!0;M("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===Ua.APPIUM&&(a=await Qn({appId:e.appId,projectId:e.project})),await se(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==Ua.APPIUM&&await xu(e,c),M("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,i,null,t,o);return M("right after runTestPlan"),await Q.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=gn(),r=[];await this.reportTestRunnerStarted(e.project,e),Js(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let n=ti.default.flattenDeep(r);return M("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),M("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}},Ur=gp;Ur._id=(0,Ab.v4)()});var Re={};H(Re,{addTestRetry:()=>Yl,clearTestResult:()=>Eu,deleteCloudflareTunnel:()=>Cp,fetchLambdatestConfig:()=>Ql,fixGridAppIDStructure:()=>Xu,forceUpdateCloudflareTunnelRoutes:()=>Ap,getAllGrids:()=>hl,getAppDetails:()=>Qn,getApplitoolsIntegrationData:()=>wp,getBrowserStackSessionMetaData:()=>bI,getCloudflareTunnel:()=>xp,getEditorUrl:()=>gI,getGridSlot:()=>gl,getHybridGridProvider:()=>fl,getLabFeaturesByProjectId:()=>uu,getMobileDevicesFromGrid:()=>Zn,getRealData:()=>Vl,getS3Artifact:()=>An,getS3ArtifactText:()=>Wl,getSuiteTestList:()=>Au,getTestPlan:()=>fI,getTestPlanTestList:()=>ri,getTestResults:()=>kr,getUsageForCurrentBillingPeriod:()=>Ip,initializeUserWithAuth:()=>Rp,isTestResultCompleted:()=>Su,keepAliveCompanySlots:()=>jl,keepAliveGrid:()=>dl,loadSfdcCredential:()=>Ep,loadTest:()=>Un,releaseCompanySlot:()=>Ul,releaseGridSlot:()=>ml,reportExecutionFinished:()=>wo,reportExecutionStarted:()=>Jl,reportRunnerFinished:()=>bp,reportRunnerStarted:()=>yp,requestCompanySlot:()=>Fl,saveRemoteStep:()=>du,saveTestPlanResult:()=>Tp,updateCompanySlot:()=>Bl,updateExecutionTests:()=>Kl,updateRemoteRunFailure:()=>Pp,updateTestDataArtifact:()=>vo,updateTestResult:()=>Wo,updateTestStatus:()=>Ir,uploadAppToGrid:()=>Yu,uploadRunDataArtifact:()=>Iu,validateUserAccessKey:()=>ul});async function xs(){let s=await At();if(!s)throw new Error("Failed to get token from server");return{[Dc]:Ur.id,Authorization:`Bearer ${s}`}}async function Ee({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await xs(),o={...t,...i};return We({url:`${he}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function dI(s,e,t,r={},n=void 0){let i=await xs(),o={...r,...i};return await Gs(`${he}${s||""}`,e,t,o,n)}async function si(s,e){let t=await xs();return await Sc(`${he}${s||""}`,e,t)}async function Pb(s,e){let t=await xs();return await Vs(`${he}${s||""}`,e,t)}async function mI(s,e){let t=await xs();return await Hs(`${he}${s||""}`,e||void 0,t)}async function Ae(s,e,t,r){let n=await xs();return await Te(`${he}${s||""}`,e||void 0,n,r,t)}function An(s,e){return(0,ee.default)(()=>Ae(`/storage${s}`,null,{isBinary:!0},e),{retries:te,factor:1})}function Wl(s){return(0,ee.default)(()=>mI(`/storage${s}`))}async function yp(s,e){return await Ee({url:"/test-runner",body:{projectId:s,testOptimization:e}})}async function bp(s){return await Pb("/test-runner",{projectId:s})}async function fI(s,e){let t=n=>n===null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,ee.default)(()=>Ae("/testPlan",{projectId:s,name:e.join(",")}),{retries:te,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function Ep({branch:s,projectId:e}){let t=await(0,ee.default)(()=>Ae(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:te,factor:1});return t==null?void 0:t.sfdcCredential}function Un({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,ee.default)(()=>Ae(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:te,factor:1})}function Tp(s,e,t){return(0,ee.default)(()=>Ee({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:te,factor:1})}function Ir(s,e,t,r,n,i,o=te){return(0,ee.default)(()=>si("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:lI,...i}),{retries:o,factor:1})}function Kl(s,e,t,r,n,i,o,a){return(0,ee.default)(()=>si("/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 Jl({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(()=>(eo(),wf));return Ee({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function wo(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,ee.default)(()=>si("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:te,factor:1})}async function ri(s,e,t,r,n){return(0,ee.default)(()=>Ee({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:te,factor:1})}function Au({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,ee.default)(()=>Ee({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:te,factor:1})}async function Qn({appId:s,projectId:e}){try{return await(0,ee.default)(()=>Ae(`/mobile-app/app/${s}?projectId=${e}`),{retries:te,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function Ip(s){try{return await(0,ee.default)(()=>Ae(`/plan/project/${s}/usage-current-billing-period`),{retries:te,factor:1})}catch(e){_t.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function Su(s,e,t){return(0,ee.default)(()=>Ae(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:te,factor:1})}function kr(s,e,t,r){return(0,ee.default)(()=>Ae(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:te,factor:1})}function dl(s,e){return Ee({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function ml(s,e,t,r,n){return Ee({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function fl(s){return Ee({url:"/grid/hybrid/provider",body:s})}function gl(s){return(0,ee.default)(()=>Ae("/grid/grid-slot",{...s,reqId:re()}),{retries:te,factor:1})}async function Rp({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a,clientCliVersion:l,clientNodeVersion:c,clientNpmVersion:d}){var m,u;try{return await(0,ee.default)(()=>We({url:`${he}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a,clientCliVersion:l,clientNodeVersion:c,clientNpmVersion:d},timeout:6e4}),{retries:te,factor:1})}catch(f){if(_t.error("error initializing info from server",f),(m=f.message)!=null&&m.includes("Bad Request"))throw new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file.");if((u=f.code)!=null&&u.includes("ENOTFOUND"))throw new C("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend.");if(f.text)try{let h=JSON.parse(f.text),g=h.clientMessage.color||"red",y=h.clientMessage.bgColor||"bgBlack";console.log(vp.default[y](vp.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{_t.error("Error parsing error message from server",f)}throw f}}async function gI(){if(Ms)return{editorUrl:Ms};try{return await(0,ee.default)(()=>Ae("/system-info/editor-url"),{retries:te,onFailedAttempt:s=>{if(s.attemptNumber>=te)throw s},factor:1})}catch(s){return _t.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function hl(s){return(0,ee.default)(()=>Ae("/grid",{companyId:s}),{retries:te,factor:1})}function Vl(s,e,t){return(0,ee.default)(()=>Ae(`/real-data/${e}?${t}&projectId=${s}`),{retries:te,factor:1})}function Wo(s,e,t,r,n){return(0,ee.default)(()=>Ee({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:te,factor:1})}function Eu(s,e,t,r){return(0,ee.default)(()=>Ee({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:te,factor:1})}function du(s,e,t,r){return(0,ee.default)(()=>Ee({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:te,factor:1})}function hI(s){return s.startsWith("/")?s:`/${s}`}function yI(s,e,t){let r=hI(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function kb(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=yI(l,pI,s),d=Buffer.from(Cb.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,ee.default)(()=>dI(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:te,factor:1}),c}function Yl({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,ee.default)(()=>Ee({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:i,testId:t,runId:e,testResult:o}}),{retries:te,factor:1})}async function wp(s){try{return await Ae(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return _t.warn("could'nt get applitools integration data.",{err:e}),{}}}async function xp(s,e){try{return await si("/tunnel",{companyId:s,routes:e})}catch(t){return _t.warn("could'nt get tunnel.",{err:t}),{}}}async function Ap(s,e){try{return await Ee({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){_t.warn("could'nt get tunnel.",{err:t});return}}async function Cp(s,e){try{return await Pb(`/tunnel/${e}`,{companyId:s})}catch(t){_t.warn("could'nt get tunnel.",{err:t});return}}function Pp(s){return We({url:`${he}/result/remoteRunFailure`,body:s})}async function Zn({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${uI}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,ee.default)(()=>Ae(i,{projectId:s}),{retries:te,factor:1})}catch(o){return _t.warn("could'nt get devices from headspin grid.",{err:o}),null}}async function Yu({projectId:s,gridId:e,app:t,timeout:r}){return(0,ee.default)(()=>Ee({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:te,factor:1})}async function Xu(s){return(0,ee.default)(()=>Ee({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:te,factor:1})}async function Fl(s,e){return(0,ee.default)(()=>Ee({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:te,factor:1})}async function Ul(s,e,t){return(0,ee.default)(()=>Ee({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:te,factor:1})}async function Bl(s,e,t){return(0,ee.default)(()=>si("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:te,factor:1})}function jl(s,e,t){return Ee({url:`/slot-management/keep-alive?reqId=${re()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function bI(s,e){return await Te(`${Us}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function ul(s){try{return await Ae("/v2/project/validateUserAccessKey",s),!0}catch(e){return _t.error("error validating user access key",{error:e}),!1}}var vp,ar,Cb,ee,Sp,lI,_t,te,uI,pI,Ql,uu,Iu,vo,ge=v(()=>{"use strict";vp=I(require("chalk")),ar=I(require("lodash")),Cb=I(require("pako"));U();de();ie();Ve();at();ee=I(require("p-retry")),Sp=I(require("object-hash"));Y();W();hp();lI=tt(),_t=P("testim service api"),te=3,uI="/grid",pI="test-result-artifacts";Ql=async s=>(0,ee.default)(()=>Ae("/grid/lt/config",{companyId:s}),{retries:te,factor:1}),uu=async s=>(0,ee.default)(()=>Ae(`/labFeature/v2/project/${s}`),{retries:te,factor:1});Iu=ar.memoize(async(s,e,t,r)=>{if(!ar.isEmpty(r))return await kb(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,Sp.default)(r)}:${e}:${t}`),vo=ar.memoize(async(s,e,t,r,n)=>!r||ar.isEmpty(r)?void 0:await kb(s,e,t,JSON.stringify((()=>{let o=ar.clone(r);if(n!=null&&n.hiddenParams){let a=n.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(c=>{o[c]&&Object.assign(o,{[c]:Oc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,Sp.default)(r)}:${e}:${t}`)});async function Ob(){let s=await Promise.any(TI.map(async e=>{try{return await Te(e)}catch{return null}}));return s==null?void 0:s.ip}var TI,_b=v(()=>{"use strict";Ve();TI=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"]});function Ba(){return tt()}var kp=v(()=>{"use strict";U()});function SI(s){q.EXTENSION!==s&&process.nextTick(()=>{try{(we(),He(tr)).getSessionPlayer()}catch{}})}function EI(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(Op.default[i](Op.default[n](r.text)))})}async function ni(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?vI:wI,f=Ba(),h=Cc(),g=await Fm(),y=null;if(_.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{y=await Ob()}catch(b){Lb.error("failed to get public ip",b)}let T=!0;M("before initializeUserWithAuth");let w=await Bt(async()=>(SI(a),T=!1,await Rp({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 EI(w),s.publicIps=[w.clientPublicIp],M("after initializeUserWithAuth"),y&&w.clientPublicIp&&w.clientPublicIp!==y&&(Lb.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:w.clientPublicIp}),s.publicIps.push(y)),sf(w.authData,{projectId:e,token:t,userAccessKey:r,publicIp:w.clientPublicIp,initializedFromCache:T}),w}var Op,Lb,wI,vI,Db=v(()=>{"use strict";Op=I(require("chalk"));je();ge();Yt();at();_b();ie();W();ue();kp();U();Zr();Lb=P("initializeUserWithAuth"),wI=1e3*60*5,vI=1e3*60*60*10});async function Fb(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await qi():s.chromeBinaryLocation,e=rn({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==q.EXTENSION&&await br(s.playerLocation,s.canary),s.mode!==q.SELENIUM&&s.mode!==q.APPIUM&&!s.ext&&await el(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await Zc(s.installCustomExtension,n)}return await e,t}async function Ub(s){var o;II.info("prepare MockNetwork",{location:s});let e=await xc(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>Nb*1e6)throw new Error(`${_p} exceeded ${Nb}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${_p} cannot be parsed.${ja.EOL}${a}`)}let n=new Mb.default;if(!n.validate($c,r)){let a=(o=n.errors)==null?void 0:o.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(ja.EOL);throw new Error(`${_p} is malformed.${ja.EOL}${a}`)}return r.entries}var ja,Mb,Nb,_p,II,Lp=v(()=>{"use strict";ja=I(require("node:os"));U();hm();nn();Mb=I(require("ajv"));ie();nl();W();Db();Nb=1,_p="JSON file supplied to --mock-network-pattern",II=P("prepare runner")});function Vb(s){return s.start&&hn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function Gb(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new C("Agent port is not number");let t=So(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 Hb=v(()=>{"use strict";Pn();rs();Y()});var As,Fp,qb=v(()=>{"use strict";As="SECRETS",Fp={get secretsKey(){return As},get proxySecrets(){return new Proxy({},{get(s,e){return`${As}.${e}`}})},injectProxySecretsStoreToGlobal(){Object.assign(globalThis,{[As]:this.proxySecrets})},containsSecrets(s){return typeof s=="string"?s.includes(As):JSON.stringify(s).includes(As)},extractSecretKeysFromCode(s){let e=new Set,r=(typeof s=="string"?s:JSON.stringify(s)).match(new RegExp(`${As}\\.\\w+`,"g"));return r==null||r.map(n=>{let i=n.split(".")[1];i&&e.add(i)}),e},replaceValuesWithDecryptedSecrets({testData:s,secretsRecord:e}){let r=this.secretsKey.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${r}\\.(\\w+)$`),i=o=>{Array.isArray(o)?o.forEach((a,l)=>{if(typeof a=="string"){let c=a.match(n);if(c){let d=c[1];o[l]=e[d]??a}}else typeof a=="object"&&a!==null&&i(a)}):o&&typeof o=="object"&&Object.entries(o).forEach(([a,l])=>{if(typeof l=="string"){let c=l.match(n);if(c){let d=c[1];o[a]=e[d]??l}}else typeof l=="object"&&l!==null&&i(l)})};i(s)}}});var Wp={};H(Wp,{doLogin:()=>$p,getProjectId:()=>kI,getToken:()=>OI});async function kI(){return Jb("projectId")}async function OI(){return Jb("token")}function Kb(s,e){return Promise.race([s,ce(e).then(()=>{throw new oe("timeout")})])}async function _I(){let s=(await import("express")).default(),e=async function(){return Kb(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();po(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function $p({overwriteExisting:s=!0,projects:e=null}={}){let t=Up.homedir(),r=Bp.join(t,".testim");if(await ye(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await Kb(_I(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,l.succeed(),await zb(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 zb(r,i);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function zb(s,e){await jp.promises.writeFile(s,Wa.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function Jb(s){let e=Up.homedir(),t=Bp.join(e,".testim"),r=await ye(t),n={};if(r)try{n=Wa.parse((await jp.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var Up,Bp,Wa,jp,Va=v(()=>{"use strict";Up=I(require("os")),Bp=I(require("path")),Wa=I(require("yaml"));U();jp=require("fs");Y();Ll()});var sT={};H(sT,{process:()=>jI,program:()=>p});var Gp,Zb,Ga,eT,Vt,Ne,tT,LI,De,zp,DI,NI,Xb,rT,MI,Hp,qp,Kp,Vp,Lt,FI,p,UI,BI,Qb,jI,Jp=v(()=>{"use strict";Gp=I(require("ms")),Zb=I(require("chalk")),Ga=I(require("node:fs")),eT=I(require("node:url")),Vt=I(require("lodash")),Ne=I(require("node:path"));U();Pn();Hb();Yt();tT=require("commander");ie();Y();jr();U();ue();qb();Uo();LI=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),De=(s,e)=>(e.push(s),e),zp=new tT.Command,DI=s=>s.split(","),NI=(s,e)=>!s||s.length===0?e:s,Xb=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],rT=()=>{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")}zp.help(g=>g.split(`
|
|
402
|
+
const downloadAndUploadFile = ${DE()};
|
|
403
|
+
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Ay(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ma,fa,ky=v(()=>{"use strict";ma=require("url");pe();fa=class extends V{async updateBaseUrl(e){let t=new ma.URL(e),r=new ma.URL(this.context.recordedBaseUrl),n=new ma.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 ga,Oy=v(()=>{"use strict";pe();F();ga=class extends V{async performAction(){await ce(this.step.durationMS||0)}}});var ha,_y=v(()=>{"use strict";pe();ha=class extends V{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Jn,Ly=v(()=>{"use strict";pe();Jn=class extends V{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let i=await this.driver.executeCodeAsync(r,t,e);return(i==null?void 0:i.value)||{}}catch(i){throw(n=i==null?void 0:i.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):i}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},i=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),o=i.result||{},a={method:t.method,status:o.status,url:t.url};return i.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.exception?void 0:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var ya,Dy=v(()=>{"use strict";pe();ya=class extends V{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var Ny,Wu,Vu,My=v(()=>{"use strict";Ny=I(require("@applitools/spec-driver-webdriverio"));fi();we();Wu=class{constructor(){let{EyeSdkBuilder:e}=Z(),t=hd["@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:Ny.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=Z(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},Vu=new Wu});var Fy,Uy,Yn,By=v(()=>{"use strict";Fy=I(require("lodash"));pe();W();My();Uy=P("pixel-validation-step-action"),Yn=class extends V{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,l=await Vu.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"};Fy.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),Uy.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){Uy.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Vu.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Ss,Gu=v(()=>{"use strict";hs();Y();sa();Ss=class extends ir{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:i="",id:o=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await gs(i,o,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof oe?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var or,jy=v(()=>{"use strict";Gu();or=class extends Ss{isFailedResult(e){return e===!1}}});var ba,$y=v(()=>{"use strict";Gu();ba=class extends Ss{isFailedResult(e){return!e}}});var Ta,Wy=v(()=>{"use strict";hs();pe();Y();Ta=class extends V{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await fs(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof Rt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof oe?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Lr,Vy=v(()=>{"use strict";pe();Lr=class extends V{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var be,Gy=v(()=>{"use strict";pe();be=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var wa,Hy=v(()=>{"use strict";pe();wa=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var va,qy=v(()=>{"use strict";pe();va=class extends V{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function NE(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Sa(s,e){NE(ME,e),e.registerLocateStepActionUtils(Hn.getUtils(s))}var ME,Hu=v(()=>{"use strict";Wh();Hh();ey();ty();sy();oy();ly();uy();py();dy();gy();hy();yy();wy();Ey();Py();ky();Oy();_y();Ly();Dy();By();jy();$y();Wy();Vy();Gy();Hy();qy();ME={locate:Hn,scroll:Qo,mouse:Zo,submit:aa,text:ta,"special-key":na,"user-code":Wt,"validation-code-step":Wt,"wait-for-code-step":Wt,"action-code-step":Wt,"condition-step":vs,"skip-code-step":vs,"element-code-step":vs,"evaluate-expression":ea,"text-validation":zn,"wait-for-text-validation":zn,"select-option":oa,"drop-file":ua,"input-file":da,hover:ca,navigation:fa,wheel:la,sleep:ga,refresh:ha,"keyboard-shortcut-step":ia,"api-validation":Jn,"api-action":Jn,"api-code-step":Wt,"extract-text":ya,"simple-ui-verification":Yn,"wait-for-simple-ui-verification":Yn,"cli-validation-download-file":Lr,"cli-wait-for-download-file":Lr,"network-validation-step":Lr,"cli-validation-code-step":or,"cli-wait-for-code-step":or,"cli-action-code-step":or,"cli-api-code-step":or,"cli-condition-step":ba,"node-package":Ta,"email-code-step":Wt,"cli-email-code-step":or,"sfdc-internal-test-step":va,"sfdc-recorded-step":wa,"sfdc-step-login":be,"sfdc-step-loginas":be,"sfdc-step-logout":be,"sfdc-step-sobjectcreate":be,"sfdc-step-sobjectdelete":be,"sfdc-step-findrecord":be,"sfdc-step-quickaction":be,"sfdc-step-sobjectedit":be,"sfdc-step-sobjectvalidate":be,"sfdc-step-launchapp":be,"sfdc-step-wait-for-page-load":be,"sfdc-step-closeconsoletabs":be,"sfdc-step-relatedlistaction":be,"sfdc-step-permission-validation":be,"sfdc-step-convert-lead-to-opportunity":be,"sfdc-step-quotelineeditor":be,"sfdc-document-validation":Lr,"sfdc-step-flow-screen-completion":be,"sfdc-step-sobjectverifyoptions":be}});var zy,UE,Es,qu=v(()=>{"use strict";zy=["simple-ui-verification","wait-for-simple-ui-verification"],UE=[...zy,"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=UE.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 zy.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 Jy={};H(Jy,{SeleniumTestPlayer:()=>Xn});var Ky,FE,Xn,zu=v(()=>{"use strict";F();Ky=require("@applitools/eyes-sdk-core");Dn();Y();W();Mu();Uh();ju();Yo();jh();$u();we();Hu();qu();FE=P("SeleniumTestPlayer"),Xn=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Es(Xo());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=Z();this.driver=n??new Ar;let d=new Jo(this.driver);this.stepActionFactory=new c(d),Sa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new zo(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=Bh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new ws(this.driver),FrameLocator:m,portSelector:Ko,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Ky.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Z(),t=1e3*60*2;try{await le((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof oe&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){FE.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 Ju={};H(Ju,{WorkerSelenium:()=>Ku});function jE(s){let{playback:e}=Z().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>M(`Got event ${t}`))}var Ea,BE,Ku,Yu=v(()=>{"use strict";F();je();Vn();W();Pt();Oo();ie();Du();Y();zu();we();at();Ea=P("worker-selenium"),BE=1e9,Ku=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){M("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new Ts(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await o.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),M("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),M("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,BE),await this.windowUtils.validatePageIsAvailable(),M("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof It||d||m?new It(`Page '${l}' is not available`):(Ea.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Ji(),initializedFromCache:Yi()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=Z(),{driver:o,sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),jE(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 Un(this.options))[this.testId]);let d=async()=>le(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(f)}),this.testRunTimeout,Me.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof oe&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(Ea.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&&(Ea.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});o.start(),M("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),M("right after super.runTestOnce in workerSelenium");let u=await d();return M("right after runSeleniumTest"),u}catch(u){throw Ea.error("failed to run test once",{err:u}),u}}}});var Yy,Xy,Ge,$E,WE,Xu,vt,Ia=v(()=>{"use strict";Yy=I(require("ora")),Xy=require("jimp");de();Ve();ge();W();ie();we();ue();Ge=P("mobile-grid-service"),$E="https://tdc.tricentis-cloud.com",WE="https://ui.headspin.io",Xu=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||uc}/${dc}/devices`:t===L.TESTIM_TDC?`${r||pc}/${dc}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),i=this.buildRequestBody(e,t);try{await We({url:r,headers:n,body:i})}catch(o){throw Ge.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await Te(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw Ge.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await Hs(`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 Zn({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===L.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===L.SAUCELABS)return e.testobject_device_name;if(t===L.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n,i=!1){let{executionId:o,testId:a,testResultId:l}=e,{project:c,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===L.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:w}=Z();y=w(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,c,d,m,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await Ir(c,o,a,l,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),Ge.info("device details updated on testResult",{testResultId:l,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===L.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),l=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:l}}try{let{AppiumApi:o}=Z(),a=new o(t,r.sessionId,null,i),[l,c]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),d=Buffer.from(l,"base64"),m=await Xy.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:`${Fs}/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?WE:$E}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let n=(await Te(`${e}/api/devices`)).find(i=>i.udid===t);if(!n)throw new Error(`device ${t} not found`);return{udid:n.udid,name:n.name,model:n.model,height:n.height,width:n.width,geo:"local",osVersion:n.osVersion,osType:n.deviceType.toLowerCase(),scaleFactor:n.scaleFactor??0,isVirtual:n.virtual??!1,minApiVersion:n.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:i,testResultId:o}=r,{project:a,localTmaUrl:l}=t,c=await this.getTmaDeviceDetails(l,e);return await Ir(a,n,i,o,"RUNNING",{device:c}),Ge.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:c}),c}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(_.flags.allowFixingAppIdStructure.isEnabled()&&(Ge.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Zu({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 Qn({appId:e,projectId:t});return{appUrl:`${he}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(_d*60))+1)*60*1e3,Math.max(Od,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,Yy.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 Qu({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),Ge.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){Ge.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else Ge.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===L.BROWSERSTACK||f===L.TESTIM_TVC||f===L.P_CLOUDY;if(g){let T=t.projectData.type,w=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});w&&(Ge.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=g),!w&&y&&(Ge.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!w&&!y&&Ge.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:i,host:o,key:a,type:l,apiUrl:c}=t;if(l===L.BROWSERSTACK){let u=`${Fs}/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}/${mc}/apps`;return c||(u=`${l===L.TESTIM_HEADSPIN?uc:pc}/${mc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===L.TESTIM_TVC){let u=`${Ld}/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 Ec({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Te(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await Te(e,void 0,i)}},vt=new Xu});function Qy({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"&&!VE.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function GE({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 HE(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 qE(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===L.TESTIM_TDC,a=s===L.TESTIM_HEADSPIN,l=o?"tdc":"headspin",c=a&&_.flags.enableBatchHeadSpin.isEnabled(),d=o&&(_.flags.enableBatchTDC.isEnabled()||_.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=_.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture.video`]:!0,..._.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...i&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:HE(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function Ra(s){return"id"in s?s.id:s.packageName}function zE(s,e){return{[`${e===L.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function KE({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=zE(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":Ra(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":Ra(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Nr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:i="",shouldRunInEnhancedMode:o}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:o?"WaldoTestim":"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:Ra(t)},...r&&{[`${i}app`]:r},...e};case"android":return{platformName:"Android",[`${i}autoGrantPermissions`]:!0,[`${i}automationName`]:o?"WaldoTestim":"UiAutomator2",...n&&{[`${i}appWaitActivity`]:`${n}, *`},...t&&{[`${i}appPackage`]:Ra(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Zy({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o,shouldRunInEnhancedMode:a}){let l=qE(o.type,i,n);return KE({projectType:s,sessionCaps:l,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function Aa({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 Ca({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?fc:i.deviceNameRegex:t==="ios"&&r===L.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":fc:".*")}function JE(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 YE(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...xa(s,Is)}}function eb(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 XE(s){return eb(s,e=>e.startsWith("browserstack."),"browserstack.")}function QE(s){return eb(s,e=>!e.startsWith("browserstack."))}function tb(s){return!s||!rb(s)?"2.0.0":s}function rb(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function sb({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=rb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function xa(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}async function ZE({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=JE(i,s),h=await Zn({gridId:i.gridId,projectType:s,projectId:n.project,companyId:n.company.companyId}),g=h==null?void 0:h.find(({udid:S})=>{var E;return((E=m.staticAllocation)==null?void 0:E.deviceUdid)===S}),y=(g==null?void 0:g.osVersion)??Aa({osVersion:c,mobileConfig:m}),T=(g==null?void 0:g.name)??Ca({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),w=qe(n.editorUrl,n.project,o.testId,o.testResultId,o.branch),b={device:T,os_version:y,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":w,...l&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return Nr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:l})}function eI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=i,h=_.flags.enableAppium2pCloudy.isEnabled(),g=Aa({osVersion:l,mobileConfig:d}),y=Ca({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(Dd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=YE(b)),t="",Nr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Is}})}function tI({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=Aa({osVersion:l,mobileConfig:d}),f=Ca({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Dr.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],sb({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:tb(g.appiumVersion),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,...xa(h,Is),"sauce:options":{...T,...w,...(0,Dr.omit)(g,"appiumVersion")}};return Nr({projectType:s,sessionCaps:b,appiumPrefix:Is,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:u,deviceName:f,tags:Object.values(o),name:o.testResultId,build:o.executionId,...h,...g};return Nr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function rI({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=Aa({osVersion:l,mobileConfig:d}),f=Ca({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=XE(n.browserstack),g=(0,Dr.omit)(QE(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:w}=n.browserstack||{},b=_.flags.enableAppium2BrowserStack.isEnabled();if(b||sb({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let E={userName:i.user,accessKey:i.key,appiumVersion:b?"2.0.1":tb(h.appiumVersion),projectName:y||o.project,buildName:T||o.executionId,debug:!0,networkLogs:!0},A={"appium:platformVersion":u,"appium:deviceName":f,...xa(g,Is),"bstack:options":{...E,...(0,Dr.omit)(h,"appiumVersion")}};return Nr({projectType:s,sessionCaps:A,appiumPrefix:Is,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let S={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:w||o.testResultId,project:y||o.project,build:T||o.executionId,buildTags:Object.values(o).join(","),"browserstack.user":i.user,"browserstack.key":i.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,...xa(h,"browserstack.")};return Nr({projectType:s,sessionCaps:S,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}async function sI(s){if(L.TESTIM_TDC===s.gridInfo.type||L.TESTIM_HEADSPIN===s.gridInfo.type)return Zy(s);if(L.TESTIM_TVC===s.gridInfo.type)return await ZE(s);if(L.P_CLOUDY===s.gridInfo.type)return eI(s);if(L.SAUCELABS===s.gridInfo.type)return tI(s);if(L.BROWSERSTACK===s.gridInfo.type)return rI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function nI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,l={};return n==="dynamic"&&(!i&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!o&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),i&&(l.manufacturer=i),o&&(l.os_version=o),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}async function nb(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}`);Qy({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=vt.getGridConnection(e),l=await sI(s);if(e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC){let y=e.type===L.TESTIM_HEADSPIN?"headspin":"tdc",T=nI(r,i==null?void 0:i.mobile);if(!(0,Dr.isEmpty)(T)){let w=Object.entries(T).map(([b,S])=>S.split(",").map(E=>E===".*"||E==="="?"":`${b}:${E}`).join(",")).join(" ").trim();l[`${y}:selector`]=w}}let c=e.type===L.TESTIM_TVC?{alwaysMatch:l}:l,d=_.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,ep.default)("2m"),f=(0,ep.default)("12m"),h=mr(_.flags.appiumConnectionRetryCount.getValue(),m),g=mr(_.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&g<f&&(g=f),{...a,desiredCapabilities:l,connectionRetryTimeout:g,capabilities:c,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function ib(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;Qy({nativeAppMetadata:r,appPath:i,gridInfo:t}),GE({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((g=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await vt.getGridDirectConnection(t,d),f=Zy({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 ob(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=Nr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function ab(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 ep,Dr,Is,VE,tp=v(()=>{"use strict";ep=I(require("ms"));ue();ie();Ia();Dr=require("lodash");F();de();ge();Is="appium:",VE=[L.BROWSERSTACK,L.SAUCELABS,L.TESTIM_HEADSPIN,L.TESTIM_TDC,L.TESTIM_TVC,L.P_CLOUDY]});var Pa,lb=v(()=>{"use strict";Pa=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var ka,ub=v(()=>{"use strict";F();ka=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Qs;this.getLinksFromUnescapeHTML=Zs}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 rp,Oa,pb=v(()=>{"use strict";W();rp=P("mobile-frame-locator-mock"),Oa=class{foundFrameCallback(){return rp.info("foundFrameCallback-mock invoked"),{}}locate(){return rp.info("locate-mock invoked"),{}}async findFrame(){return rp.info("findFrame-mock invoked"),{}}}});var iI,mb,db,Rs,sp=v(()=>{"use strict";iI=I(require("webdriverio")),mb=require("@applitools/eyes-sdk-core");lb();ju();W();ub();$u();we();Hu();pb();qu();db=P("appium-test-player"),Rs=class{constructor(e,t,r,n=iI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=Z(),m=new ka(this.driver);this.stepActionFactory=new c(m),Sa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Es(Xo()),this.sessionPlayer=new a(e,{tabService:new Pa,cookieUtils:void 0,FrameLocator:Oa,portSelector:Ko,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:mb.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()),db.info("appium session deleted",{...i}))}catch(o){db.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=Z();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function oI(s){return await Te(`${s}/api/status`)}async function fb(s,e){return await Te(`${s}/api/devices/${e}/status`)}async function gb(s){if((await oI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var hb=v(()=>{"use strict";Ve()});var yb={};H(yb,{WorkerLocalTma:()=>ap});var Mr,np,ip,op,ap,bb=v(()=>{"use strict";Ve();tp();Vn();F();W();Pt();sp();we();hb();Ia();Mr=P("worker-appium"),np=class extends Error{},ip=class extends Error{},op=class extends Error{},ap=class extends Ot{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Rs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=Z(),{DOMParser:n}=await import("linkedom"),i=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n,!1);return t.sessionPlayer.playbackManager.appiumApi=i,i}async getBrowserOnce(t,r,n,i){var E;if(Q.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:l}=this.options;await 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 vt.getMobileAppDataByAppId({appId:f,projectId:c,token:d});t.nativeApp=A}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:w,version:b},S]=await Promise.all([this.getAppStateFromDevice(o,a,T),fb(o,a)]).catch(A=>{throw this.handleDeviceNotFoundError(A),A});if(Mr.info("device status and app state",{deviceStatus:S,appInstalled:w,version:b,executionId:this.executionId,testResultId:this.testResultId}),!w&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!w&&y&&(await this.installApp(o,a,y),Mr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let A={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(E=this.options.projectData)==null?void 0:E.name}-${this.options.project}`},D=ob({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:A,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),j={capabilities:{udid:a,...D}};Mr.info("requesting new appium session from TMA",{tmaSessionSettings:j,executionId:this.executionId,testResultId:this.testResultId});let R=await this.requestNewAppiumSessionFromTma(o,j,g);this.sessionData=R;let x=await m.attach({sessionId:R.sessionId,capabilities:D,options:{capabilities:D}});this.device=await vt.updateTmaDeviceDetails(a,this.options,t),Mr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:x.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:x.capabilities})}catch(A){throw Mr.error("failed to start application",{err:A}),A}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await We({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new op(l):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,l=(await Te(o)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await Mt(n);await Gs(`${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 ip(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}=Z(),{sessionPlayer:o}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await i.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Mr.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Mr.error("failed to run test once",{err:c}),c}}}});var wb={};H(wb,{WorkerAppium:()=>cp});var Tb,Ur,cp,vb=v(()=>{"use strict";F();tp();Tb=require("linkedom");Vn();W();Pt();sp();we();Ia();ie();os();Ur=P("worker-appium"),cp=class extends Ot{initPlayer(t){return new Rs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){let o=this.options.projectData.type,a=(o==="android"||o==="ios")&&await t.isTestRecordedWithEnhancedMode();if(i.type!==L.TESTIM_TVC&&a)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Q.onGetSession(this.id,this.testName,t.runMode);let{driver:l}=n,c=await vt.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),d=o==="android"?t.androidActivityWait:null,m=t.nativeAppMetadata;if(!m)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let u={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.uniqueId}`},f={projectType:o,nativeAppMetadata:m,appPath:c,androidActivityWait:d,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await vt.lockDevice(i,this.options.deviceUdid),h=await ib(f)):h=await nb({...f,shouldRunInEnhancedMode:a}),Ur.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:m,capabilities:ab(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await l.remote(h),this.device=await vt.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,a);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),Ur.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(u){throw Ur.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:u}),u}}startKeepAlive(t){let{errors:r}=Z(),n=async()=>{try{await t.getOrientation()}catch(i){Ur.error("failed to keep appium session alive",{err:i}),r!=null&&r.AppiumSessionTerminatedError&&i instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&$f(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:t},this.id)}catch(r){Ur.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===L.TESTIM_HEADSPIN||i===L.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===L.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:n,path:i}=this.activeSession.options;if(t&&r&&n&&i)return`${t}://${r}:${n}${i}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=Z(),{sessionPlayer:a}=r,l=n||"runner",c=this.options.timeout;Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let d;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:w,port:b,path:S}=await vt.getHeadSpinDeviceConnection(this.options.gridData,y);d=`${T}://${w}:${b}${S}`}else d=this.getDirectAddressConnection()||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(h=this.options.company)==null?void 0:h.companyId,device:this.device},a.playbackManager.appiumApi=new i(d,this.activeSession.sessionId,Tb.DOMParser,((g=this.device)==null?void 0:g.domMode)==="enhanced"),this.startKeepAlive(a.playbackManager.appiumApi),o.initialize({serverUrl:this.options.localRCASaver});let u=async()=>{try{let y=await new Promise((w,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:w,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(b)});return this.stopKeepAlive(),await o.drain(),y.stepsResults=null,y.resultId=this.testResultId,{...y,...t.seleniumPerfStats.getStats()}}catch(y){throw Ur.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:y}),this.stopKeepAlive(),y}};try{return await super.runTestOnce(t,r),await le(u(),c)}catch(y){throw Ur.error("failed to run test once",{err:y}),y}}getUserAgentString(){return"Testim/CI-Branch:runner-v4.152.0"}}});var _a,Sb=v(()=>{"use strict";F();Dn();Y();_a=class{constructor(e){this.id=e;this.driver=new Ar}async onDone(){try{await le(this.driver.end(),12e4)}catch(t){t instanceof oe&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});async function Eb(){let s=await Promise.any(aI.map(async e=>{try{return await Te(e)}catch{return null}}));return s==null?void 0:s.ip}var aI,La,Da=v(()=>{"use strict";Ve();aI=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"];La=({timeout:s})=>({timeout:s,...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}})});var Ib,Na,Rb=v(()=>{"use strict";Ib=I(require("ws"));F();Da();Na=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=La({timeout:e}),r=new Ib.default(this._cdpUrl,t),n=Kt(o=>{r.once("open",o)}),i=Kt(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return r.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([n,i]).then(()=>r),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 Ua,lp,Ma,xb=v(()=>{"use strict";F();Ua=I(require("chrome-launcher"));Ao();Rb();In();lp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Na}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=xo({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)??[],...Ua.Launcher.defaultFlags().filter(w=>w!=="--disable-extensions")];this.chrome=await Ua.launch({chromeFlags:u,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let f=await gr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),as(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},Ma=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new lp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var up={};H(up,{WorkerExtension:()=>ei});function cI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Ab(s){return cI(s)?s:new Error(s)}var dt,ei,Fa=v(()=>{"use strict";je();Y();Vn();F();W();Pt();ie();Sb();xb();at();dt=P("worker-ext"),ei=class extends Ot{initPlayer(){return this.options.useChromeLauncher?new Ma(this.id):new _a(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw dt.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Ji(),initializedFromCache:Yi(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var i;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((i=this.options.browserstack)!=null&&i["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:i}=this;M("WorkerExtension runTestOnce");let o=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await le(e.runTestUsingCDP(d.cdpTestRunner),m,Me.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof oe))throw u;return dt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw dt.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:i,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(M("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw dt.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await le(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Me.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof oe))throw T;dt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),dt.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:i}),m.unregisterToClosedBrowser(y),T.type=zs.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=le(e.onCompleted(),this.testRunTimeout,Me.TEST_COMPLETE_TIMEOUT_MSG),w=await Tc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(w.success),w.reason)}catch(E){dt.error("Could not update the grid about the test status",{err:E})}m.isAlive()||(dt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(dt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.keepAliveIssue=b),{...w,...e.seleniumPerfStats.getStats()}}catch(T){throw dt.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:i}),Ab(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw dt.warn("failed to start url",{err:h}),Ab(h)}};t.driver.start();try{return await super.runTestOnce(e,t),M("WorkerExtension super.runTestOnce"),await c()}catch(d){throw dt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var dp={};H(dp,{WorkerExtensionSingleBrowser:()=>pp});var lI,uI,pp,mp=v(()=>{"use strict";je();F();W();ku();Pt();Fa();lI=P("base-worker"),uI=500,pp=class extends ei{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()&&(lI.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let i=this.handleQuarantine(t);if(i)return i;M("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=o.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ce(uI)}}});var fp,Ba,Cb=v(()=>{"use strict";Dn();de();je();wl();at();pu();Y();W();ie();wh();Fo();fp=P("worker-manager"),Ba=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(()=>(Yu(),Ju))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(bb(),yb))).WorkerLocalTma:(await Promise.resolve().then(()=>(vb(),wb))).WorkerAppium;default:return Nn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(mp(),dp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(Fa(),up))).WorkerExtension}else switch(r){case(Or.find(n=>n===r)&&Nn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(mp(),dp))).WorkerExtensionSingleBrowser;case Or.find(n=>n===r):return(await Promise.resolve().then(()=>(Fa(),up))).WorkerExtension;case jn.find(n=>n===r):return(await Promise.resolve().then(()=>(Yu(),Ju))).WorkerSelenium;default:throw new C(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],n=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return M("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{M("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,l){if(e&&e.length===0)return;let c=!1,d=0,m=(u,f)=>new Promise(h=>{var fe,Ze,St,Br,k,N,$,K;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new Uo(r,n,e,i,o,t),this.combinedTestResults={};let T=((fe=i.company)==null?void 0:fe.ucid)||"",w=(Ze=i.company)==null?void 0:Ze.companyId,b=(St=i.company)==null?void 0:St.name,S=i.source||"cli",E=i.user,A=(Br=i.company)==null?void 0:Br.planType,D=(k=i.company)==null?void 0:k.isStartUp,j=(N=i.projectData)==null?void 0:N.name,R=($=i.projectData)==null?void 0:$.type,x=i.lightweightMode,O=(K=i.gridData)==null?void 0:K.type,B=(Pe,Et,ve,rc,ii,sc)=>(d++,Rf({executionId:r,projectId:g,testId:Et,resultId:ve,ucid:T,companyId:w,companyName:b,projectName:j,companyPlan:A,source:S,user:E,lightweightMode:x,isStartUp:D,projectType:R,appSource:sc,gridType:O}),t.testStartAndReport(Pe,r,ve,rc,ii)),G=async(Pe,Et,ve,rc,ii,sc)=>{var ud,pd,dd;d--;let et={...(x==null?void 0:x.onlyTestIdsNoSuite)&&{show:!0},...ve.seleniumStats&&{seleniumStats:ve.seleniumStats},...ve.gridIssues&&{gridIssues:ve.gridIssues},...ve.keepAliveIssue&&{keepAliveIssue:ve.keepAliveIssue},...i.host&&{gridHost:i.host}};if(ve.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ve.seleniumPerfMarks),delete ve.seleniumPerfMarks),i.grid||i.gridId?(et.gridName=i.grid||((ud=i.gridData)==null?void 0:ud.name),et.gridType=(pd=i.gridData)==null?void 0:pd.type,et.gridProvider=(dd=i.gridData)==null?void 0:dd.provider):i.localTmaUrl?(et.gridName="local-tma-from-options",et.gridType="local-tma"):i.useLocalChromeDriver?(et.gridName="local-chrome-driver-from-options",et.gridType="local-chrome"):i.useChromeLauncher?(et.gridName="chrome-launcher-from-options",et.gridType="local-chrome"):i.browserstack?et.gridName="browserstack-from-options":i.saucelabs&&(et.gridName="saucelabs-from-options"),await t.testEndAndReport(Pe,ve,r,rc,ii,et).catch(WT=>fp.error("testEndAndReport threw an error",{err:WT})),ii)return;this.combinedTestResults[ve.resultId]=ve,xf({executionId:r,projectId:g,testId:Et,resultId:ve.resultId,result:ve,ucid:T,companyId:w,companyName:b,projectName:j,companyPlan:A,source:S,user:E,lightweightMode:x,logger:fp,isStartUp:D,projectType:R,appSource:sc}),l&&!ve.success&&(this.executionQueue.stop(),c=!0),(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},z=(Pe,Et)=>{this.combinedTestResults[Et.resultId]=Et,t.onTestIgnored(Pe,Et.resultId),d--,(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},X=(Pe,Et)=>t.onGridSlot(Pe,Et);for(i.userData={loginData:{...wr(),refreshToken:zi(),authData:wr(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:he},M("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,B,G,X,z)});try{let u=await At(),f=await Ki(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),c)throw new qt;return h}catch(u){throw fp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var gp,ae,Pb=v(()=>{"use strict";gp=class{static colorString(e,t){return`${e}${t}${gp.Reset}`}},ae=gp;ae.Reset="\x1B[0m",ae.Bright="\x1B[1m",ae.Dim="\x1B[2m",ae.Underscore="\x1B[4m",ae.Blink="\x1B[5m",ae.Reverse="\x1B[7m",ae.Hidden="\x1B[8m",ae.FgBlack="\x1B[30m",ae.FgRed="\x1B[31m",ae.FgGreen="\x1B[32m",ae.FgYellow="\x1B[33m",ae.FgBlue="\x1B[34m",ae.FgMagenta="\x1B[35m",ae.FgCyan="\x1B[36m",ae.FgWhite="\x1B[37m",ae.FgGray="\x1B[90m",ae.BgBlack="\x1B[40m",ae.BgRed="\x1B[41m",ae.BgGreen="\x1B[42m",ae.BgYellow="\x1B[43m",ae.BgBlue="\x1B[44m",ae.BgMagenta="\x1B[45m",ae.BgCyan="\x1B[46m",ae.BgWhite="\x1B[47m",ae.BgGray="\x1B[100m"});var ti,kb,ja,hp,yp,Fr,bp=v(()=>{"use strict";ti=I(require("lodash"));F();W();de();ie();je();ts();Tl();wl();ge();ue();Pt();dg();Y();Cb();Fo();kb=require("uuid");Pb();({CLI_MODE:ja}=Ut),hp=P("test-plan-runner"),yp=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}static get id(){return yp._id}async runTestAllPhases(e,t,r,n,i,o,a,l){let c={},d=new Ba(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=yi||i.parallel,y=!1;M("right before this.workerManager.runTests");let T=await d.runTests(t,l,o,a,i,n,g,y);M("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await d.runTests(r,l,o,a,i,n,g,y);Object.assign(c,T)};Af({executionId:o,projectId:i.project}),M("right before runBeforeTests");try{return await m(),M("right before runTestPlanTests"),await u(),M("right after runTestPlanTests"),await f(),c}catch(g){if(hp.error("error running test plan",{err:g}),g instanceof qt)return l.markAllQueuedTests(o,me.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,w,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===ja.SELENIUM){let[{getSessionPlayer:S},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(we(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:A}=S();await A.closeBatch(o,E);return}let g;try{if(!((b=(w=(T=i.company)==null?void 0:T.activePlan)==null?void 0:w.premiumFeatures)!=null&&b.applitools)||(g=await Sp(i.project),ti.default.isEmpty(g)||!o))return;let{runKey:S,url:E}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[o],serverUrl:E,apiKey:S}})}catch{}}}async runTestPlan(e,t,r,n,i,o,a,l){var b,S,E;let c=re(),d=n.project;qd(c),e.forEach(A=>Object.assign(A,{isBeforeTestPlan:!0})),r.forEach(A=>Object.assign(A,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new To(m,n,o,a),f=ti.default.chain(m).map(A=>{var D;return((D=A.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(A=>A.name),y=(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,i,g);M("before testListInfoPromise");let T=await y;(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,c,l,h),M("before runTestAllPhases");let w=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,i||"All Tests",u);return M("before executionEnd"),await u.executionEnd(c),M("after executionEnd"),{results:w,executionId:c,testPlanName:i,configName:h}}isJsonString(e){try{JSON.parse(e)}catch{return!1}return!0}handleReportFailure(e,t){try{e.text?t=e.text:t=JSON.stringify(e)}catch{}console.error(ae.colorString(ae.FgMagenta,t)),process.exit(-1)}async reportTestRunnerStarted(e,t){try{return await Tp(e,t.testOptimization)}catch(r){return this.handleReportFailure(r,"Failed Report: Test Runner Started")}}async reportTestRunnerFinished(e){try{return await wp(e)}catch(t){return this.handleReportFailure(t,"Failed Report: Test Runner Finished")}}async runTestPlans(e,t){hp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return ti.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a={testPlans:[],testPlansData:{}};_.flags.enableTestPlanAggregation.isEnabled()?(await se(e.testPlanIds,async d=>{let m=await ri(o,e.testPlan,[d],t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})}),await se(e.testPlan,async d=>{let m=await ri(o,[d],e.testPlanIds,t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})})):a=await ri(o,e.testPlan,e.testPlanIds,t,e.intersections);let l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==ja.APPIUM&&await Cu(e,r(c)),await se(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await df(e,d);let f=u.overrideExecutionName||d.name;return await se(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(E=>({executionId:E,status:Au(n[m][E])})),w=Object.keys(n[m]).map(E=>n[m][E]).reduce((E,A)=>Object.assign(E,A),{}),b=Au(w);Object.assign(i,w);let S=b?T[0].executionId:T.find(E=>!E.status).executionId;return await vp(o,m,{success:b,executions:T,executionId:S}),y})})}async runAnonymousTestPlan(e,t){var l;hp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),M("before getSuite");let r=await Sh(e,t);if(M("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new C("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new C("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new C("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let i=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),o=!0;M("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===ja.APPIUM&&(a=await Qn({appId:e.appId,projectId:e.project})),await se(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==ja.APPIUM&&await Cu(e,c),M("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,i,null,t,o);return M("right after runTestPlan"),await Q.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=gn(),r=[];await this.reportTestRunnerStarted(e.project,e),Js(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let n=ti.default.flattenDeep(r);return M("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),M("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}},Fr=yp;Fr._id=(0,kb.v4)()});var Re={};H(Re,{addTestRetry:()=>Ql,clearTestResult:()=>Ru,deleteCloudflareTunnel:()=>kp,fetchLambdatestConfig:()=>eu,fixGridAppIDStructure:()=>Zu,forceUpdateCloudflareTunnelRoutes:()=>Pp,getAllGrids:()=>bl,getAppDetails:()=>Qn,getApplitoolsIntegrationData:()=>Sp,getBrowserStackSessionMetaData:()=>wI,getCloudflareTunnel:()=>Cp,getEditorUrl:()=>yI,getGridSlot:()=>yl,getHybridGridProvider:()=>hl,getLabFeaturesByProjectId:()=>du,getMobileDevicesFromGrid:()=>Zn,getRealData:()=>Hl,getS3Artifact:()=>An,getS3ArtifactText:()=>Gl,getSuiteTestList:()=>Pu,getTestPlan:()=>hI,getTestPlanTestList:()=>ri,getTestResults:()=>kr,getUsageForCurrentBillingPeriod:()=>xp,initializeUserWithAuth:()=>Ap,isTestResultCompleted:()=>Iu,keepAliveCompanySlots:()=>Wl,keepAliveGrid:()=>fl,loadSfdcCredential:()=>Rp,loadTest:()=>Fn,releaseCompanySlot:()=>jl,releaseGridSlot:()=>gl,reportExecutionFinished:()=>wo,reportExecutionStarted:()=>Xl,reportRunnerFinished:()=>wp,reportRunnerStarted:()=>Tp,requestCompanySlot:()=>Bl,saveRemoteStep:()=>fu,saveTestPlanResult:()=>vp,updateCompanySlot:()=>$l,updateExecutionTests:()=>Yl,updateRemoteRunFailure:()=>Op,updateTestDataArtifact:()=>vo,updateTestResult:()=>Wo,updateTestStatus:()=>Ir,uploadAppToGrid:()=>Qu,uploadRunDataArtifact:()=>xu,validateUserAccessKey:()=>dl});async function xs(){let s=await At();if(!s)throw new Error("Failed to get token from server");return{[Mc]:Fr.id,Authorization:`Bearer ${s}`}}async function Ee({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await xs(),o={...t,...i};return We({url:`${he}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function fI(s,e,t,r={},n=void 0){let i=await xs(),o={...r,...i};return await Gs(`${he}${s||""}`,e,t,o,n)}async function si(s,e){let t=await xs();return await Ic(`${he}${s||""}`,e,t)}async function _b(s,e){let t=await xs();return await Vs(`${he}${s||""}`,e,t)}async function gI(s,e){let t=await xs();return await Hs(`${he}${s||""}`,e||void 0,t)}async function Ae(s,e,t,r){let n=await xs();return await Te(`${he}${s||""}`,e||void 0,n,r,t)}function An(s,e){return(0,ee.default)(()=>Ae(`/storage${s}`,null,{isBinary:!0},e),{retries:te,factor:1})}function Gl(s){return(0,ee.default)(()=>gI(`/storage${s}`))}async function Tp(s,e){return await Ee({url:"/test-runner",body:{projectId:s,testOptimization:e}})}async function wp(s){return await _b("/test-runner",{projectId:s})}async function hI(s,e){let t=n=>n===null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,ee.default)(()=>Ae("/testPlan",{projectId:s,name:e.join(",")}),{retries:te,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function Rp({branch:s,projectId:e}){let t=await(0,ee.default)(()=>Ae(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:te,factor:1});return t==null?void 0:t.sfdcCredential}function Fn({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,ee.default)(()=>Ae(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:te,factor:1})}function vp(s,e,t){return(0,ee.default)(()=>Ee({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:te,factor:1})}function Ir(s,e,t,r,n,i,o=te){return(0,ee.default)(()=>si("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:pI,...i}),{retries:o,factor:1})}function Yl(s,e,t,r,n,i,o,a){return(0,ee.default)(()=>si("/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 Xl({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(()=>(eo(),Sf));return Ee({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function wo(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,ee.default)(()=>si("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:te,factor:1})}async function ri(s,e,t,r,n){return(0,ee.default)(()=>Ee({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:te,factor:1})}function Pu({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,ee.default)(()=>Ee({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:te,factor:1})}async function Qn({appId:s,projectId:e}){try{return await(0,ee.default)(()=>Ae(`/mobile-app/app/${s}?projectId=${e}`),{retries:te,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function xp(s){try{return await(0,ee.default)(()=>Ae(`/plan/project/${s}/usage-current-billing-period`),{retries:te,factor:1})}catch(e){_t.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function Iu(s,e,t){return(0,ee.default)(()=>Ae(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:te,factor:1})}function kr(s,e,t,r){return(0,ee.default)(()=>Ae(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:te,factor:1})}function fl(s,e){return Ee({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function gl(s,e,t,r,n){return Ee({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function hl(s){return Ee({url:"/grid/hybrid/provider",body:s})}function yl(s){return(0,ee.default)(()=>Ae("/grid/grid-slot",{...s,reqId:re()}),{retries:te,factor:1})}async function Ap({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a,clientCliVersion:l,clientNodeVersion:c,clientNpmVersion:d}){var m,u;try{return await(0,ee.default)(()=>We({url:`${he}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a,clientCliVersion:l,clientNodeVersion:c,clientNpmVersion:d},timeout:6e4}),{retries:te,factor:1})}catch(f){if(_t.error("error initializing info from server",f),(m=f.message)!=null&&m.includes("Bad Request"))throw new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file.");if((u=f.code)!=null&&u.includes("ENOTFOUND"))throw new C("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend.");if(f.text)try{let h=JSON.parse(f.text),g=h.clientMessage.color||"red",y=h.clientMessage.bgColor||"bgBlack";console.log(Ep.default[y](Ep.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{_t.error("Error parsing error message from server",f)}throw f}}async function yI(){if(Ms)return{editorUrl:Ms};try{return await(0,ee.default)(()=>Ae("/system-info/editor-url"),{retries:te,onFailedAttempt:s=>{if(s.attemptNumber>=te)throw s},factor:1})}catch(s){return _t.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function bl(s){return(0,ee.default)(()=>Ae("/grid",{companyId:s}),{retries:te,factor:1})}function Hl(s,e,t){return(0,ee.default)(()=>Ae(`/real-data/${e}?${t}&projectId=${s}`),{retries:te,factor:1})}function Wo(s,e,t,r,n){return(0,ee.default)(()=>Ee({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:te,factor:1})}function Ru(s,e,t,r){return(0,ee.default)(()=>Ee({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:te,factor:1})}function fu(s,e,t,r){return(0,ee.default)(()=>Ee({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:te,factor:1})}function bI(s){return s.startsWith("/")?s:`/${s}`}function TI(s,e,t){let r=bI(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Lb(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=TI(l,mI,s),d=Buffer.from(Ob.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,ee.default)(()=>fI(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:te,factor:1}),c}function Ql({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,ee.default)(()=>Ee({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:i,testId:t,runId:e,testResult:o}}),{retries:te,factor:1})}async function Sp(s){try{return await Ae(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return _t.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Cp(s,e){try{return await si("/tunnel",{companyId:s,routes:e})}catch(t){return _t.warn("could'nt get tunnel.",{err:t}),{}}}async function Pp(s,e){try{return await Ee({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){_t.warn("could'nt get tunnel.",{err:t});return}}async function kp(s,e){try{return await _b(`/tunnel/${e}`,{companyId:s})}catch(t){_t.warn("could'nt get tunnel.",{err:t});return}}function Op(s){return We({url:`${he}/result/remoteRunFailure`,body:s})}async function Zn({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${dI}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,ee.default)(()=>Ae(i,{projectId:s}),{retries:te,factor:1})}catch(o){return _t.warn("could'nt get devices from headspin grid.",{err:o}),null}}async function Qu({projectId:s,gridId:e,app:t,timeout:r}){return(0,ee.default)(()=>Ee({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:te,factor:1})}async function Zu(s){return(0,ee.default)(()=>Ee({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:te,factor:1})}async function Bl(s,e){return(0,ee.default)(()=>Ee({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:te,factor:1})}async function jl(s,e,t){return(0,ee.default)(()=>Ee({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:te,factor:1})}async function $l(s,e,t){return(0,ee.default)(()=>si("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:te,factor:1})}function Wl(s,e,t){return Ee({url:`/slot-management/keep-alive?reqId=${re()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function wI(s,e){return await Te(`${Fs}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function dl(s){try{return await Ae("/v2/project/validateUserAccessKey",s),!0}catch(e){return _t.error("error validating user access key",{error:e}),!1}}var Ep,ar,Ob,ee,Ip,pI,_t,te,dI,mI,eu,du,xu,vo,ge=v(()=>{"use strict";Ep=I(require("chalk")),ar=I(require("lodash")),Ob=I(require("pako"));F();de();ie();Ve();at();ee=I(require("p-retry")),Ip=I(require("object-hash"));Y();W();bp();pI=tt(),_t=P("testim service api"),te=3,dI="/grid",mI="test-result-artifacts";eu=async s=>(0,ee.default)(()=>Ae("/grid/lt/config",{companyId:s}),{retries:te,factor:1}),du=async s=>(0,ee.default)(()=>Ae(`/labFeature/v2/project/${s}`),{retries:te,factor:1});xu=ar.memoize(async(s,e,t,r)=>{if(!ar.isEmpty(r))return await Lb(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,Ip.default)(r)}:${e}:${t}`),vo=ar.memoize(async(s,e,t,r,n)=>!r||ar.isEmpty(r)?void 0:await Lb(s,e,t,JSON.stringify((()=>{let o=ar.clone(r);if(n!=null&&n.hiddenParams){let a=n.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(c=>{o[c]&&Object.assign(o,{[c]:Lc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,Ip.default)(r)}:${e}:${t}`)});function $a(){return tt()}var _p=v(()=>{"use strict";F()});function EI(s){q.EXTENSION!==s&&process.nextTick(()=>{try{(we(),He(tr)).getSessionPlayer()}catch{}})}function II(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(Lp.default[i](Lp.default[n](r.text)))})}async function ni(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?SI:vI,f=$a(),h=kc(),g=await Bm(),y=null;if(_.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{y=await Eb()}catch(b){Db.error("failed to get public ip",b)}let T=!0;M("before initializeUserWithAuth");let w=await Bt(async()=>(EI(a),T=!1,await Ap({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 II(w),s.publicIps=[w.clientPublicIp],M("after initializeUserWithAuth"),y&&w.clientPublicIp&&w.clientPublicIp!==y&&(Db.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:w.clientPublicIp}),s.publicIps.push(y)),of(w.authData,{projectId:e,token:t,userAccessKey:r,publicIp:w.clientPublicIp,initializedFromCache:T}),w}var Lp,Db,vI,SI,Nb=v(()=>{"use strict";Lp=I(require("chalk"));je();ge();Yt();at();Da();ie();W();ue();_p();F();Zr();Db=P("initializeUserWithAuth"),vI=1e3*60*5,SI=1e3*60*60*10});async function Fb(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await qi():s.chromeBinaryLocation,e=rn({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==q.EXTENSION&&await br(s.playerLocation,s.canary),s.mode!==q.SELENIUM&&s.mode!==q.APPIUM&&!s.ext&&await rl(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await tl(s.installCustomExtension,n)}return await e,t}async function Bb(s){var o;RI.info("prepare MockNetwork",{location:s});let e=await Cc(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>Mb*1e6)throw new Error(`${Dp} exceeded ${Mb}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${Dp} cannot be parsed.${Wa.EOL}${a}`)}let n=new Ub.default;if(!n.validate(Vc,r)){let a=(o=n.errors)==null?void 0:o.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(Wa.EOL);throw new Error(`${Dp} is malformed.${Wa.EOL}${a}`)}return r.entries}var Wa,Ub,Mb,Dp,RI,Np=v(()=>{"use strict";Wa=I(require("node:os"));F();bm();nn();Ub=I(require("ajv"));ie();ol();W();Nb();Mb=1,Dp="JSON file supplied to --mock-network-pattern",RI=P("prepare runner")});function Gb(s){return s.start&&hn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function Hb(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new C("Agent port is not number");let t=So(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 qb=v(()=>{"use strict";Pn();rs();Y()});var As,Bp,zb=v(()=>{"use strict";As="SECRETS",Bp={get secretsKey(){return As},get proxySecrets(){return new Proxy({},{get(s,e){return`${As}.${e}`}})},injectProxySecretsStoreToGlobal(){Object.assign(globalThis,{[As]:this.proxySecrets})},containsSecrets(s){return typeof s=="string"?s.includes(As):JSON.stringify(s).includes(As)},extractSecretKeysFromCode(s){let e=new Set,r=(typeof s=="string"?s:JSON.stringify(s)).match(new RegExp(`${As}\\.\\w+`,"g"));return r==null||r.map(n=>{let i=n.split(".")[1];i&&e.add(i)}),e},replaceValuesWithDecryptedSecrets({testData:s,secretsRecord:e}){let r=this.secretsKey.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${r}\\.(\\w+)$`),i=o=>{Array.isArray(o)?o.forEach((a,l)=>{if(typeof a=="string"){let c=a.match(n);if(c){let d=c[1];o[l]=e[d]??a}}else typeof a=="object"&&a!==null&&i(a)}):o&&typeof o=="object"&&Object.entries(o).forEach(([a,l])=>{if(typeof l=="string"){let c=l.match(n);if(c){let d=c[1];o[a]=e[d]??l}}else typeof l=="object"&&l!==null&&i(l)})};i(s)}}});var Gp={};H(Gp,{doLogin:()=>Vp,getProjectId:()=>OI,getToken:()=>_I});async function OI(){return Yb("projectId")}async function _I(){return Yb("token")}function Jb(s,e){return Promise.race([s,ce(e).then(()=>{throw new oe("timeout")})])}async function LI(){let s=(await import("express")).default(),e=async function(){return Jb(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();po(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function Vp({overwriteExisting:s=!0,projects:e=null}={}){let t=jp.homedir(),r=$p.join(t,".testim");if(await ye(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await Jb(LI(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,l.succeed(),await Kb(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 Kb(r,i);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Kb(s,e){await Wp.promises.writeFile(s,Ga.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function Yb(s){let e=jp.homedir(),t=$p.join(e,".testim"),r=await ye(t),n={};if(r)try{n=Ga.parse((await Wp.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var jp,$p,Ga,Wp,Ha=v(()=>{"use strict";jp=I(require("os")),$p=I(require("path")),Ga=I(require("yaml"));F();Wp=require("fs");Y();Nl()});var nT={};H(nT,{process:()=>$I,program:()=>p});var qp,eT,qa,tT,Vt,Ne,rT,DI,De,Jp,NI,MI,Qb,sT,UI,zp,Kp,Yp,Hp,Lt,FI,p,BI,jI,Zb,$I,Xp=v(()=>{"use strict";qp=I(require("ms")),eT=I(require("chalk")),qa=I(require("node:fs")),tT=I(require("node:url")),Vt=I(require("lodash")),Ne=I(require("node:path"));F();Pn();qb();Yt();rT=require("commander");ie();Y();jr();F();ue();zb();Fo();DI=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),De=(s,e)=>(e.push(s),e),Jp=new rT.Command,NI=s=>s.split(","),MI=(s,e)=>!s||s.length===0?e:s,Qb=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],sT=()=>{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")}Jp.help(g=>g.split(`
|
|
404
404
|
`).filter(T=>!t(T)&&!e(T)&&!s(T)&&!r(T)&&!n(T)&&!a(T)&&!o(T)&&!i(T)&&!l(T)&&!c(T)&&!d(T)&&!m(T)&&!u(T)&&!f(T)&&!h(T)).join(`
|
|
405
|
-
`))},
|
|
405
|
+
`))},UI=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(eT.default.yellow(`
|
|
406
406
|
WARNING: ${s} is deprecated. ${t}
|
|
407
|
-
`))},Hp=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:qp,argv:Kp,exit:Vp,cwd:Lt}=global.process,FI=new Set(["trace","debug","info","warn","error","silent"]);Nc(Kp,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));zp.description("Testim.io CLI").option("-h --help","output usage information",rT).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-config [test-config]","test config name to override for all tests in current execution",De,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",De,[]).option("--params-file [params-file.json | params-file.js]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",De,[]).option("--test-id [test-id]","test ID to run",De,[]).option("-l, --label [label]","labels to search test by",De,[]).option("-n, --name [test-name]","test name to run",De,[]).option("--project [project-id]","project ID").option("-r, --report-file [report junit xml path]","where to save junit xml results file").option("--urls","add step urls to the junit report").option("--override-report-file-classname [override-report-file-classname]","custom junit class name for the junit reporter").option("--reporters [names]","report types",DI).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",De,[]).option("--test-plan-id [test-plan-id]","test plan to run",De,[]).option("--suite [suite-name]","suite to run",De,[]).option("--suite-id [suite-id]","suite ID to run",De,[]).option("--rerun-failed-by-run-id [run-id]","allows re-running failed tests from a specific run ID").option("--disable-grid-check [boolean]","disable checking if selenium grid is available",!1).option("--disable-native-events [boolean]","pass nativeEvents=false capability to the selenium browser (in selenium mode)",!1).option("--disable-timeout-retry [boolean]","disable retry after test pass test timeout",!1).option("--ca-file [ca-file-location]","ca certificate file location").option("--proxy [proxy-url]","proxy url to all requests").option("--proxy-for-grid [proxy-for-grid]","used together with --proxy to also router grid traffic through a proxy").option("--result-label [result-label]","result label",De,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--user-access-key [user-access-key]","EXPERIMENTAL").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("--duration [duration]","The duration of the test run in minutes",Number).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--clear-file-cache","clear internal CLI file cache").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(qp.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,Gp.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,Gp.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: ${Hp.join("/")}`,De,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",De,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--sealights-lab-id [sealights-lab-id]","SeaLight Lab ID").option("--sealights-build-session-id [sealights-build-session-id]","SeaLight Session Build ID").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",De,[]).option("--intersect-with-suite [suiteName]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite name)",De,[]).option("--intersect-with-suite-id [suiteId]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite ID)",De,[]).option("--apply-intersections-to-before-and-after-sections [boolean]","For a test plan's before/after tests, run tests that intersect with specified intersection flags",void 0).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).option("--print-grids","Print available grids and exit",!1).option("--print-final-caps","Print the final calculated capabilities",!1).option("--headless-extension-download-path [headless-extension-download-path]","Path to download headless extension","").parse(Kp);p=zp.opts(),UI=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},BI=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},Qb=s=>{var r;if(!_.flags.secrets.isEnabled({projectId:p.project}))return;let t=Ga.readFileSync(s);(r=Fp)!=null&&r.containsSecrets(t.toString())&&Fp.injectProxySecretsStoreToGlobal()},jI=async()=>{var T,w,b,S,E,A,D,j;p.inspect&&require("node:inspector").open(p.inspect);let s={},e={},t=[],r={};if(!Kp.slice(2).length)throw rT(),new $r;if(p.version){let R="Testim CLI Version: ";qp.npm_package_version&&(console.log(R,qp.npm_package_version),Vp(0));let x=tt();x&&(console.log(R,x),Vp(0)),console.log("Could not find version, please check the package.json manually"),Vp(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Cm(),p.clearFileCache&&Xr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let R=Ne.resolve(n);xm(R)}if(p.usePrefechedData&&Pm(),p.playerRequirePath){let R=Ne.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let x=Ne.join(R,"tsconfig.node.json"),B=require("ts-node").register({project:x,ignore:[/node_modules/,new RegExp(`^${Vt.escapeRegExp(Ne.relative(Lt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:B.config.options.paths,baseUrl:B.config.options.baseUrl}),(we(),He(tr)).options.playerPath=R;let z=require("node:module"),X=z.prototype.require;z.prototype.require=function(Ze){return Ze==="rox-alias"?X.call(this,"rox-node"):Ze==="canvas"?{}:X.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=Ga.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(Vb(p))return Gb(p);try{let R={};p.configFile?(Qb(p.configFile),R=require(Ne.join(Lt(),p.configFile)).config):p.optionsFile&&(R=require(Ne.join(Lt(),p.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(x=>{let O=LI(x);p[O]=NI(p[O],R[x])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let i=((T=p.testConfig)==null?void 0:T.length)||((w=p.testConfigId)==null?void 0:w.length),o=((b=p.testPlan)==null?void 0:b.length)||((S=p.testPlanId)==null?void 0:S.length),a=((E=p.suite)==null?void 0:E.length)||((A=p.suiteId)==null?void 0:A.length);if(p.seleniumCapsFile)try{r=require(Ne.join(Lt(),p.seleniumCapsFile))}catch(R){throw new C(`Failed to parse selenium caps file file error: ${R.message}`)}if((D=p.reporters)!=null&&D.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new C("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new C("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new C("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Ne.join(Lt(),p.chromeExtraPrefs))}catch(R){throw new C(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(p.chromeExtraArgs){let R=p.chromeExtraArgs.split(",");for(let x of R){let[O]=x.split("=");Xb.includes(O)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(x),O==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${O}), allowed values: ${JSON.stringify(Xb)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&Qb(p.paramsFile),s={...s,...require(Ne.join(Lt(),p.paramsFile))}}catch(R){throw new C(`Failed to read/open params file error: ${R.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(R){throw new C(`Failed to parse params string error: ${R.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new C("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(UI(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let R=require(Ne.join(Lt(),p.sauceOptions)),x=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let B=R.browserName.toLowerCase();switch(B){case"microsoftedge":p.browser="edge";break;default:p.browser=B}}p.browser==="edge"&&parseFloat(R.version)>=79&&(p.browser="edge-chromium");let O=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!x&&p.browser==="chrome"&&O)throw new C("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...R}}catch(R){throw new C(`Failed to parse saucelabs options file error: ${R.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new C("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(BI(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let R=require(Ne.join(Lt(),p.browserstackOptions)),x=R.platform&&["mac","android"].includes(R.platform.toLowerCase());if(R.browserName&&(p.browser=R.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(R.browser_version)>=79&&(p.browser="edge-chromium"),!x&&parseFloat(R.browser_version)<50&&p.browser==="chrome")throw new C("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...R}}catch(R){throw new C(`Failed to parse browserstack options file error: ${R.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let R=require(Ne.join(Lt(),p.perfectoOptions)),x={location:"US East",securityToken:p.perfectoToken};p.perfecto={...x,...R}}catch(R){throw new C(`Failed to parse perfecto options file error: ${R.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let R=require(Ne.join(Lt(),p.testobjectOptions)),x={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...x,...R}}catch(R){throw new C(`Failed to parse test object options file error: ${R.message}`)}let l={seaLights:{buildSessionId:p.sealightsBuildSessionId,labId:p.sealightsLabId}};if(p.testOptimization=l,!p.project){let x=await(await Promise.resolve().then(()=>(Va(),Wp))).getProjectId();if(x)p.project=x;else throw new C("missing project-id info, either --login to provide new credentials or use --project <project-id>")}_.flags.forceTurboModeIfNeeded.isEnabled({projectId:p.project})&&(p.turboMode=!0),p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),p.retries=!p.retries||typeof p.retries=="boolean"?1:Number(p.retries)+1,p.browserTimeout=!p.browserTimeout||typeof p.browserTimeout=="boolean"?60*1e3:p.browserTimeout,p.newBrowserWaitTimeout=!p.newBrowserWaitTimeout||typeof p.newBrowserWaitTimeout=="boolean"?10*60*1e3:p.newBrowserWaitTimeout*60*1e3,p.getBrowserTimeout||(p.getBrowserTimeout=p.browserTimeout),p.getBrowserRetries||(p.getBrowserRetries=Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=Math.max(p.browserTimeout,p.getSessionTimeout),p.driverRequestTimeout=Math.max(p.browserTimeout,p.driverRequestTimeout);let d=Boolean(p.timeout);if(p.timeout=!p.timeout||typeof p.timeout=="boolean"?10*60*1e3:p.timeout,p.beforeParallel=!p.beforeParallel||typeof p.beforeParallel=="boolean"?1:Number(p.beforeParallel),p.parallel=!p.parallel||typeof p.parallel=="boolean"?1:Number(p.parallel),p.afterParallel=!p.afterParallel||typeof p.afterParallel=="boolean"?1:Number(p.afterParallel),p.tunnelPort=!p.tunnelPort||typeof p.tunnelPort=="boolean"?"80":p.tunnelPort,p.port&&=Number(p.port),!p.token){let x=await(await Promise.resolve().then(()=>(Va(),Wp))).getToken();if(x)p.token=x;else throw new C("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let m=R=>R<=0||!Number.isInteger(R);if(m(p.retries))throw new C("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new C("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(m(p.browserTimeout))throw new C("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(m(p.newBrowserWaitTimeout))throw new C("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(m(p.timeout))throw new C("test run timeout could not be a negative number, --timeout <run-timeout>");if(m(p.beforeParallel))throw new C("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(m(p.parallel))throw new C("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(m(p.afterParallel))throw new C("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(p.mode&&![q.EXTENSION,q.SELENIUM,q.APPIUM].includes(p.mode))throw new C(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Or,...jn].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"),!FI.has(p.appiumLogLevel))throw new C(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData&&!p.printGrids)throw new C("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(p.testId.length||p.label.length||p.name.length||i||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new C("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --local-tma-url, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!o&&(p.beforeParallel!==1||p.afterParallel!==1))throw new C("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new C("please define exactly one of --grid or --grid-id or --host");if((j=p.host)!=null&&j.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=eT.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(x=>x.trim()).filter(Boolean);let R=p.resultLabel.filter(x=>x.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&fr()&&p.resultLabel.unshift(fr()),R.length)throw new C("A result label cannot exceed 250 characters")}let f=So(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new C("cannot set --w3c-capabilities and --old-capabilities options as false");if(p.protocol||=p.port===443?"https":"http",!["http","https"].includes(p.protocol))throw new C("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new C("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(p.rerunFailedByRunId&&(a||p.name.length||p.testId.length||p.label.length||o))throw new C("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(p.setRetention&&!Vt.inRange(Vt.parseInt(p.setRetention),1,11))throw new C("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");p.setRetention&&=Number(p.setRetention);let h="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new C(`--mock-network-har ${h}`);if(p.mockNetworkPattern)throw new C(`--mock-network-pattern ${h}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new C("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new C("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new C("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new C("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&Vt.difference(p.codeCoverageReporter,Hp).length){let R=Vt.difference(p.codeCoverageReporter,Hp);throw new C(`invalid --code-coverage-reporter parameters ${R.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let g={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},y=Object.keys(g).filter(R=>Boolean(p[R]));if([q.APPIUM,q.SELENIUM].includes(p.mode)&&y.length){let R=y.length>1?"are":"is";throw new C(`${y.map(x=>g[x]).join(" and ")} ${R} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let R=Ga.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(R)}catch(R){throw new C(`failed to parse field file error: ${R.message}`)}if(p.applyIntersectionsToBeforeAndAfterSections&&!p.intersectWithLabel&&!p.intersectWithSuite&&!p.intersectWithSuiteId)throw new C("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(p.highSpeed&&(MI("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new C("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new C("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(p.setNoReset&&p.fullReset)throw new C("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.lightweightMode)try{let R={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},x=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...R,...x}}catch(R){throw new C(`failed to parse lightweightMode settings error: ${R.message}`)}else p.turboMode&&![q.APPIUM,q.SELENIUM].includes(p.mode)?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&[q.APPIUM,q.SELENIUM].includes(p.mode)&&console.warn(`
|
|
408
|
-
When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they are not compatible concurrently`);if(typeof p.baseUrl=="boolean")throw new C("base url cannot be used as a flag, and must contain a string value");return{testId:[p.testId].flat(),name:[p.name].flat(),label:[p.label].flat(),suites:[p.suite].flat(),suiteIds:[p.suiteId].flat(),testPlan:[p.testPlan].flat(),testPlanIds:[p.testPlanId].flat(),reportFile:p.reportFile,urls:p.urls,reportFileClassname:p.overrideReportFileClassname,reporters:p.reporters,project:p.project,host:p.host,headless:p.headless,localTmaUrl:p.localTmaUrl,useLocalChromeDriver:p.useLocalChromeDriver,chromeBinaryLocation:p.chromeBinaryLocation,useChromeLauncher:p.useChromeLauncher,port:p.port,grid:p.grid,gridId:p.gridId,disableNativeEvents:p.disableNativeEvents,saucelabs:p.saucelabs,browserstack:p.browserstack,baseUrl:p.baseUrl,branch:(p.branch==="auto-detect"?fr():p.branch)||"master",autoDetect:p.branch==="auto-detect",token:p.token,userAccessKey:p.userAccessKey,userParamsData:s,mode:p.mode,browser:p.browser,beforeParallel:p.beforeParallel,parallel:p.parallel,afterParallel:p.afterParallel,canary:p.canary,rerunFailedByRunId:p.rerunFailedByRunId,disableGridCheck:p.disableGridCheck,disableTimeoutRetry:p.disableTimeoutRetry,resultLabels:p.resultLabel,path:p.path,protocol:p.protocol,perfecto:p.perfecto,experitestToken:p.experitestToken,testobjectSauce:p.testobjectSauce,testOptimization:p.testOptimization,gridUsername:p.gridUsername,gridPassword:p.gridPassword,overrideExecutionName:p.overrideExecutionName,tmsSuppressReporting:Boolean(p.suppressTmsReporting)||Boolean(p.tmsSuppressReporting),tmsRunId:p.tmsRunId,tmsCustomFields:p.tmsCustomFields,proxyForGrid:p.proxyForGrid,retentionDays:p.setRetention,passZeroTests:Boolean(p.passZeroTests),runQuarantinedTests:Boolean(p.runQuarantinedTests),deviceName:p.deviceName,deviceUdid:p.deviceUdid,customTag:p.customTag,osVersion:p.osVersion,duration:p.duration,skipLoadBalancer:p.skipLoadBalancer,lockDevice:p.lockDevice,appId:p.appId,appiumLogLevel:p.appiumLogLevel,setNoReset:p.setNoReset,fullReset:p.fullReset,ext:p.ext,extensionPath:p.extensionPath,extensionLocation:[p.extensionPath].filter(Boolean),playerLocation:p.playerPath||f,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:d,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0,applyIntersectionsToBeforeAndAfterSections:p.applyIntersectionsToBeforeAndAfterSections},downloadBrowser:p.downloadBrowser,slotService:"mongo",printGrids:p.printGrids,printFinalCaps:p.printFinalCaps}}});var
|
|
409
|
-
${r.stdoutResult}`:n)}},
|
|
407
|
+
`))},zp=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:Kp,argv:Yp,exit:Hp,cwd:Lt}=global.process,FI=new Set(["trace","debug","info","warn","error","silent"]);Uc(Yp,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));Jp.description("Testim.io CLI").option("-h --help","output usage information",sT).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-config [test-config]","test config name to override for all tests in current execution",De,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",De,[]).option("--params-file [params-file.json | params-file.js]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",De,[]).option("--test-id [test-id]","test ID to run",De,[]).option("-l, --label [label]","labels to search test by",De,[]).option("-n, --name [test-name]","test name to run",De,[]).option("--project [project-id]","project ID").option("-r, --report-file [report junit xml path]","where to save junit xml results file").option("--urls","add step urls to the junit report").option("--override-report-file-classname [override-report-file-classname]","custom junit class name for the junit reporter").option("--reporters [names]","report types",NI).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",De,[]).option("--test-plan-id [test-plan-id]","test plan to run",De,[]).option("--suite [suite-name]","suite to run",De,[]).option("--suite-id [suite-id]","suite ID to run",De,[]).option("--rerun-failed-by-run-id [run-id]","allows re-running failed tests from a specific run ID").option("--disable-grid-check [boolean]","disable checking if selenium grid is available",!1).option("--disable-native-events [boolean]","pass nativeEvents=false capability to the selenium browser (in selenium mode)",!1).option("--disable-timeout-retry [boolean]","disable retry after test pass test timeout",!1).option("--ca-file [ca-file-location]","ca certificate file location").option("--proxy [proxy-url]","proxy url to all requests").option("--proxy-for-grid [proxy-for-grid]","used together with --proxy to also router grid traffic through a proxy").option("--result-label [result-label]","result label",De,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--user-access-key [user-access-key]","EXPERIMENTAL").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("--duration [duration]","The duration of the test run in minutes",Number).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--clear-file-cache","clear internal CLI file cache").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(Kp.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,qp.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,qp.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: ${zp.join("/")}`,De,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",De,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--sealights-lab-id [sealights-lab-id]","SeaLight Lab ID").option("--sealights-build-session-id [sealights-build-session-id]","SeaLight Session Build ID").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",De,[]).option("--intersect-with-suite [suiteName]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite name)",De,[]).option("--intersect-with-suite-id [suiteId]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite ID)",De,[]).option("--apply-intersections-to-before-and-after-sections [boolean]","For a test plan's before/after tests, run tests that intersect with specified intersection flags",void 0).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).option("--print-grids","Print available grids and exit",!1).option("--print-final-caps","Print the final calculated capabilities",!1).option("--headless-extension-download-path [headless-extension-download-path]","Path to download headless extension","").parse(Yp);p=Jp.opts(),BI=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},jI=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},Zb=s=>{var r;if(!_.flags.secrets.isEnabled({projectId:p.project}))return;let t=qa.readFileSync(s);(r=Bp)!=null&&r.containsSecrets(t.toString())&&Bp.injectProxySecretsStoreToGlobal()},$I=async()=>{var T,w,b,S,E,A,D,j;p.inspect&&require("node:inspector").open(p.inspect);let s={},e={},t=[],r={};if(!Yp.slice(2).length)throw sT(),new $r;if(p.version){let R="Testim CLI Version: ";Kp.npm_package_version&&(console.log(R,Kp.npm_package_version),Hp(0));let x=tt();x&&(console.log(R,x),Hp(0)),console.log("Could not find version, please check the package.json manually"),Hp(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&km(),p.clearFileCache&&Xr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let R=Ne.resolve(n);Cm(R)}if(p.usePrefechedData&&Om(),p.playerRequirePath){let R=Ne.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let x=Ne.join(R,"tsconfig.node.json"),B=require("ts-node").register({project:x,ignore:[/node_modules/,new RegExp(`^${Vt.escapeRegExp(Ne.relative(Lt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:B.config.options.paths,baseUrl:B.config.options.baseUrl}),(we(),He(tr)).options.playerPath=R;let z=require("node:module"),X=z.prototype.require;z.prototype.require=function(Ze){return Ze==="rox-alias"?X.call(this,"rox-node"):Ze==="canvas"?{}:X.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=qa.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(Gb(p))return Hb(p);try{let R={};p.configFile?(Zb(p.configFile),R=require(Ne.join(Lt(),p.configFile)).config):p.optionsFile&&(R=require(Ne.join(Lt(),p.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(x=>{let O=DI(x);p[O]=MI(p[O],R[x])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let i=((T=p.testConfig)==null?void 0:T.length)||((w=p.testConfigId)==null?void 0:w.length),o=((b=p.testPlan)==null?void 0:b.length)||((S=p.testPlanId)==null?void 0:S.length),a=((E=p.suite)==null?void 0:E.length)||((A=p.suiteId)==null?void 0:A.length);if(p.seleniumCapsFile)try{r=require(Ne.join(Lt(),p.seleniumCapsFile))}catch(R){throw new C(`Failed to parse selenium caps file file error: ${R.message}`)}if((D=p.reporters)!=null&&D.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new C("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new C("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new C("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Ne.join(Lt(),p.chromeExtraPrefs))}catch(R){throw new C(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(p.chromeExtraArgs){let R=p.chromeExtraArgs.split(",");for(let x of R){let[O]=x.split("=");Qb.includes(O)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(x),O==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${O}), allowed values: ${JSON.stringify(Qb)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&Zb(p.paramsFile),s={...s,...require(Ne.join(Lt(),p.paramsFile))}}catch(R){throw new C(`Failed to read/open params file error: ${R.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(R){throw new C(`Failed to parse params string error: ${R.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new C("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(BI(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let R=require(Ne.join(Lt(),p.sauceOptions)),x=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let B=R.browserName.toLowerCase();switch(B){case"microsoftedge":p.browser="edge";break;default:p.browser=B}}p.browser==="edge"&&parseFloat(R.version)>=79&&(p.browser="edge-chromium");let O=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!x&&p.browser==="chrome"&&O)throw new C("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...R}}catch(R){throw new C(`Failed to parse saucelabs options file error: ${R.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new C("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(jI(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let R=require(Ne.join(Lt(),p.browserstackOptions)),x=R.platform&&["mac","android"].includes(R.platform.toLowerCase());if(R.browserName&&(p.browser=R.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(R.browser_version)>=79&&(p.browser="edge-chromium"),!x&&parseFloat(R.browser_version)<50&&p.browser==="chrome")throw new C("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...R}}catch(R){throw new C(`Failed to parse browserstack options file error: ${R.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let R=require(Ne.join(Lt(),p.perfectoOptions)),x={location:"US East",securityToken:p.perfectoToken};p.perfecto={...x,...R}}catch(R){throw new C(`Failed to parse perfecto options file error: ${R.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let R=require(Ne.join(Lt(),p.testobjectOptions)),x={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...x,...R}}catch(R){throw new C(`Failed to parse test object options file error: ${R.message}`)}let l={seaLights:{buildSessionId:p.sealightsBuildSessionId,labId:p.sealightsLabId}};if(p.testOptimization=l,!p.project){let x=await(await Promise.resolve().then(()=>(Ha(),Gp))).getProjectId();if(x)p.project=x;else throw new C("missing project-id info, either --login to provide new credentials or use --project <project-id>")}_.flags.forceTurboModeIfNeeded.isEnabled({projectId:p.project})&&(p.turboMode=!0),p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),p.retries=!p.retries||typeof p.retries=="boolean"?1:Number(p.retries)+1,p.browserTimeout=!p.browserTimeout||typeof p.browserTimeout=="boolean"?60*1e3:p.browserTimeout,p.newBrowserWaitTimeout=!p.newBrowserWaitTimeout||typeof p.newBrowserWaitTimeout=="boolean"?10*60*1e3:p.newBrowserWaitTimeout*60*1e3,p.getBrowserTimeout||(p.getBrowserTimeout=p.browserTimeout),p.getBrowserRetries||(p.getBrowserRetries=Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=Math.max(p.browserTimeout,p.getSessionTimeout),p.driverRequestTimeout=Math.max(p.browserTimeout,p.driverRequestTimeout);let d=Boolean(p.timeout);if(p.timeout=!p.timeout||typeof p.timeout=="boolean"?10*60*1e3:p.timeout,p.beforeParallel=!p.beforeParallel||typeof p.beforeParallel=="boolean"?1:Number(p.beforeParallel),p.parallel=!p.parallel||typeof p.parallel=="boolean"?1:Number(p.parallel),p.afterParallel=!p.afterParallel||typeof p.afterParallel=="boolean"?1:Number(p.afterParallel),p.tunnelPort=!p.tunnelPort||typeof p.tunnelPort=="boolean"?"80":p.tunnelPort,p.port&&=Number(p.port),!p.token){let x=await(await Promise.resolve().then(()=>(Ha(),Gp))).getToken();if(x)p.token=x;else throw new C("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let m=R=>R<=0||!Number.isInteger(R);if(m(p.retries))throw new C("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new C("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(m(p.browserTimeout))throw new C("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(m(p.newBrowserWaitTimeout))throw new C("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(m(p.timeout))throw new C("test run timeout could not be a negative number, --timeout <run-timeout>");if(m(p.beforeParallel))throw new C("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(m(p.parallel))throw new C("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(m(p.afterParallel))throw new C("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(p.mode&&![q.EXTENSION,q.SELENIUM,q.APPIUM].includes(p.mode))throw new C(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Or,...jn].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"),!FI.has(p.appiumLogLevel))throw new C(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData&&!p.printGrids)throw new C("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(p.testId.length||p.label.length||p.name.length||i||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new C("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --local-tma-url, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!o&&(p.beforeParallel!==1||p.afterParallel!==1))throw new C("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new C("please define exactly one of --grid or --grid-id or --host");if((j=p.host)!=null&&j.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=tT.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(x=>x.trim()).filter(Boolean);let R=p.resultLabel.filter(x=>x.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&fr()&&p.resultLabel.unshift(fr()),R.length)throw new C("A result label cannot exceed 250 characters")}let f=So(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new C("cannot set --w3c-capabilities and --old-capabilities options as false");if(p.protocol||=p.port===443?"https":"http",!["http","https"].includes(p.protocol))throw new C("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new C("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(p.rerunFailedByRunId&&(a||p.name.length||p.testId.length||p.label.length||o))throw new C("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(p.setRetention&&!Vt.inRange(Vt.parseInt(p.setRetention),1,11))throw new C("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");p.setRetention&&=Number(p.setRetention);let h="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new C(`--mock-network-har ${h}`);if(p.mockNetworkPattern)throw new C(`--mock-network-pattern ${h}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new C("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new C("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new C("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new C("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&Vt.difference(p.codeCoverageReporter,zp).length){let R=Vt.difference(p.codeCoverageReporter,zp);throw new C(`invalid --code-coverage-reporter parameters ${R.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let g={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},y=Object.keys(g).filter(R=>Boolean(p[R]));if([q.APPIUM,q.SELENIUM].includes(p.mode)&&y.length){let R=y.length>1?"are":"is";throw new C(`${y.map(x=>g[x]).join(" and ")} ${R} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let R=qa.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&&(UI("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new C("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new C("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(p.setNoReset&&p.fullReset)throw new C("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.lightweightMode)try{let R={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},x=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...R,...x}}catch(R){throw new C(`failed to parse lightweightMode settings error: ${R.message}`)}else p.turboMode&&![q.APPIUM,q.SELENIUM].includes(p.mode)?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&[q.APPIUM,q.SELENIUM].includes(p.mode)&&console.warn(`
|
|
408
|
+
When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they are not compatible concurrently`);if(typeof p.baseUrl=="boolean")throw new C("base url cannot be used as a flag, and must contain a string value");return{testId:[p.testId].flat(),name:[p.name].flat(),label:[p.label].flat(),suites:[p.suite].flat(),suiteIds:[p.suiteId].flat(),testPlan:[p.testPlan].flat(),testPlanIds:[p.testPlanId].flat(),reportFile:p.reportFile,urls:p.urls,reportFileClassname:p.overrideReportFileClassname,reporters:p.reporters,project:p.project,host:p.host,headless:p.headless,localTmaUrl:p.localTmaUrl,useLocalChromeDriver:p.useLocalChromeDriver,chromeBinaryLocation:p.chromeBinaryLocation,useChromeLauncher:p.useChromeLauncher,port:p.port,grid:p.grid,gridId:p.gridId,disableNativeEvents:p.disableNativeEvents,saucelabs:p.saucelabs,browserstack:p.browserstack,baseUrl:p.baseUrl,branch:(p.branch==="auto-detect"?fr():p.branch)||"master",autoDetect:p.branch==="auto-detect",token:p.token,userAccessKey:p.userAccessKey,userParamsData:s,mode:p.mode,browser:p.browser,beforeParallel:p.beforeParallel,parallel:p.parallel,afterParallel:p.afterParallel,canary:p.canary,rerunFailedByRunId:p.rerunFailedByRunId,disableGridCheck:p.disableGridCheck,disableTimeoutRetry:p.disableTimeoutRetry,resultLabels:p.resultLabel,path:p.path,protocol:p.protocol,perfecto:p.perfecto,experitestToken:p.experitestToken,testobjectSauce:p.testobjectSauce,testOptimization:p.testOptimization,gridUsername:p.gridUsername,gridPassword:p.gridPassword,overrideExecutionName:p.overrideExecutionName,tmsSuppressReporting:Boolean(p.suppressTmsReporting)||Boolean(p.tmsSuppressReporting),tmsRunId:p.tmsRunId,tmsCustomFields:p.tmsCustomFields,proxyForGrid:p.proxyForGrid,retentionDays:p.setRetention,passZeroTests:Boolean(p.passZeroTests),runQuarantinedTests:Boolean(p.runQuarantinedTests),deviceName:p.deviceName,deviceUdid:p.deviceUdid,customTag:p.customTag,osVersion:p.osVersion,duration:p.duration,skipLoadBalancer:p.skipLoadBalancer,lockDevice:p.lockDevice,appId:p.appId,appiumLogLevel:p.appiumLogLevel,setNoReset:p.setNoReset,fullReset:p.fullReset,ext:p.ext,extensionPath:p.extensionPath,extensionLocation:[p.extensionPath].filter(Boolean),playerLocation:p.playerPath||f,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:d,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0,applyIntersectionsToBeforeAndAfterSections:p.applyIntersectionsToBeforeAndAfterSections},downloadBrowser:p.downloadBrowser,slotService:"mongo",printGrids:p.printGrids,printFinalCaps:p.printFinalCaps}}});var Qp,WI,Cs,iT,oT,Zp,aT,cT=v(()=>{"use strict";F();Y();W();Rn();Qp=P("testimNgrok"),WI=".whitelisted-ngrok.testim.io",Cs="",oT=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}${WI}`);let r={proto:"http",addr:s.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};s.tunnelHostHeader&&(r.host_header=s.tunnelHostHeader),s.tunnelRegion&&(r.region=s.tunnelRegion);let i=await(await lt("ngrok")).connect(r);s.tunnelUseHttpAddress&&i.startsWith("https://")?(Qp.info("replace https to http"),Cs=i.replace("https://","http://")):Cs=i,s.tunnelDiagnostics&&Zp(),s.baseUrl=Cs},Zp=async(s=!0)=>{try{let t=(await lt("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(i=>i.public_url===Cs);console.log("ngrok stats",n),Qp.info("ngrok stats",{tunnel:n})}catch(e){Qp.error("error collecting ngrok stats",{err:e})}s&&(iT=setTimeout(()=>Zp(),1e4))},aT=async s=>{if(!Cs)return;clearTimeout(iT),s.tunnelDiagnostics&&await Zp(!1),await(await lt("ngrok")).disconnect(Cs)}});var cr,td,lT,GI,HI,ed,za,Ja,Ka,qI,uT,pT,dT=v(()=>{"use strict";cr=I(require("os")),td=I(require("fs")),lT=I(require("child_process"));F();ge();GI="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",HI={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"}},ed=cr.tmpdir(),za=`${ed}/cloudflared`,Ja=null,Ka=null,qI=async()=>{if(await ye(za))return;let e=HI[cr.platform()+cr.arch()];if(!e)throw new Error(`tunnel on ${cr.platform()+cr.arch()} platform is not supported.`);let t=e.extract?ed+e.path:za;await Ke(`${GI}/${e.path}`,t),e.extract&&await it(t,ed),await td.promises.chmod(za,"755")},uT=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Cp(s.company.companyId,t),qI()]);Ja=r._id,Ka=lT.spawn(za,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await Pp(s.company.companyId,Ja),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await td.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},pT=async s=>{let e=[];return Ja&&e.push(kp(s.company.companyId,Ja)),Ka&&e.push(new Promise((t,r)=>{Ka.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),Ka.kill()})),await Promise.all(e)}});var rd={};H(rd,{connect:()=>Xa,disconnect:()=>Qa,serveTunneling:()=>JI});var Ya,mT,fT,KI,Xa,Qa,JI,sd=v(()=>{"use strict";cT();In();dT();at();Ya=I(require("ora"));W();ie();Io();mT=P("tunnel"),fT=s=>{var e;return[L.TESTIM_LAMBDATEST,L.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},KI=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===L.HYBRID&&s.gridData.tunnel==="cloudflare"},Xa=async s=>{if(!s.tunnel)return;let e=wr(),t;try{fT(s)?(t=(0,Ya.default)("Starting testim lambdatest tunnel...").start(),await ne.connectTunnel(s)):KI(s)?(t=(0,Ya.default)("Starting testim cloudflare tunnel...").start(),await uT(s)):(t=(0,Ya.default)("Starting testim ngrok tunnel...").start(),await oT(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."),mT.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(r.isInvalidCredsForLT?`${n}
|
|
409
|
+
${r.stdoutResult}`:n)}},Qa=async s=>{if(s.tunnel)try{fT(s)?await ne.disconnectTunnel(s):"tunnelRoutes"in s?await pT(s):await aT(s)}catch(e){let t="catch error - failed to close tunnel";throw mT.error(t,{err:e}),new Error(t)}},JI=async(s,e=new Promise(()=>{}))=>(await Xa(s),as(()=>Qa(s)),await e)});var bT={};H(bT,{init:()=>yR,run:()=>mR});async function YI(s){let e=s.project,t=await xp(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"),hn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Bs}function QI(s,e){var i,o,a,l,c,d,m,u,f,h,g,y,T;let t=Oi(e.activePlan),r=s.parallel;if(t==="free"&&r>hT)throw new C(`The free plan allows only ${hT} 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?XI[s.projectData.type]:void 0,b=(o=e.activePlan)!=null&&o.premiumFeatures.parallelism&&w?(a=e.activePlan)==null?void 0:a.premiumFeatures.parallelism[w]:0;b&&r>b&&(console.warn(`It looks like your command used more parallel processing than your plan supports (${r} vs. ${b}).
|
|
410
410
|
We'll use the maximum of ${b} for now. To use more, you can adjust your command or upgrade your plan.`),s.parallel=b);let S=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.tunnel;if(s.tunnel&&!S)throw new C("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let E=(m=(d=e.activePlan)==null?void 0:d.premiumFeatures)==null?void 0:m.runInTurboMode;s.lightweightMode&&!E&&(console.warn(`
|
|
411
|
-
Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((u=s.gridData)==null?void 0:u.type)===L.TESTIM_TVC){let w=e.tvcLicense.expireAt||1;if(Date.now()>w&&!e.churnedByL2C)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let b=Number((h=(f=e.plan.premiumFeatures)==null?void 0:f.parallelism)==null?void 0:h.mobile);if(r>b)throw new C(`Your license allows only ${b} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((g=s.gridData)==null?void 0:g.type)===L.TESTIM_TDC){let w=e.tdcLicense.expireAt||1;if(Date.now()>w)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted")}let n=s.retentionDays;if(n){let w=(T=(y=e.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:T.resultRetention;if(n>w)throw new C(`Retention days (${n}) cannot be greater than the company's retention days (${w}). Run aborted`)}if(Jt(s)){if(_.flags.removeMobileTrialRestrictions.isEnabled())return;let w=e.tvcLicense,b=e.tdcLicense;if(w!=null&&w.isPaid||b!=null&&b.isPaid)return;let S=e==null?void 0:e.createdAt;if(new Date(S)<new Date(_.flags.applyMobileRestrictionFromDate.getValue()))return;s.timeout>=6e5&&(s.timeout=6e5,console.warn("Mobile Trial projects are limited to 10 minutes of execution time. The timeout has been reduced to 10 minutes."));let A=s.retries;A&&A>=1&&(s.retries=0,console.warn("Mobile Trial projects are not allowed to have test retries."))}}async function
|
|
411
|
+
Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((u=s.gridData)==null?void 0:u.type)===L.TESTIM_TVC){let w=e.tvcLicense.expireAt||1;if(Date.now()>w&&!e.churnedByL2C)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let b=Number((h=(f=e.plan.premiumFeatures)==null?void 0:f.parallelism)==null?void 0:h.mobile);if(r>b)throw new C(`Your license allows only ${b} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((g=s.gridData)==null?void 0:g.type)===L.TESTIM_TDC){let w=e.tdcLicense.expireAt||1;if(Date.now()>w)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted")}let n=s.retentionDays;if(n){let w=(T=(y=e.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:T.resultRetention;if(n>w)throw new C(`Retention days (${n}) cannot be greater than the company's retention days (${w}). Run aborted`)}if(Jt(s)){if(_.flags.removeMobileTrialRestrictions.isEnabled())return;let w=e.tvcLicense,b=e.tdcLicense;if(w!=null&&w.isPaid||b!=null&&b.isPaid)return;let S=e==null?void 0:e.createdAt;if(new Date(S)<new Date(_.flags.applyMobileRestrictionFromDate.getValue()))return;s.timeout>=6e5&&(s.timeout=6e5,console.warn("Mobile Trial projects are limited to 10 minutes of execution time. The timeout has been reduced to 10 minutes."));let A=s.retries;A&&A>=1&&(s.retries=0,console.warn("Mobile Trial projects are not allowed to have test retries."))}}async function ZI(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await YI(s)}catch(t){if([C,Bs].some(r=>t instanceof r))throw t;nd.error("could not validate cli account",{err:t})}}function eR(s){let e=wr();return vf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function tR(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(_.flags.useNewWSCLI.isEnabled()&&!e&&!t)return Tt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(Do(),uh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(No(),mh));r.init(s)}}function rR(s,e){let{branch:t,autoDetect:r}=s;if(hf(e,r),!e&&!r)throw new C(`branch ${t} does not exist, run aborted.`)}async function sR(s,e){let{id:t,type:r}=e,i=yT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&_.flags.sfdcHybridCompany.isEnabled(),o=gn();i&&(s.sfdcCredential=await Rp({projectId:t,branch:o}))}function nR(s,e){let{id:t,name:r,activePlan:n={}}=e,i=Boolean(n.isPoc),o=Boolean(n.isStartUp),a=Oi(n);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<gT?gT:s.newBrowserWaitTimeout),_.setCompanyId(t),_.setIsPOC(i),_.setIsStartUp(o),_.setPlanType(a),Ct.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:i,isStartUp:o,activePlan:n}}function iR(s,e){s.editorUrl=Ms||e.editorUrl}function oR(s,e){s.allGrids=e}function aR(s,e){s.authData=e}function cR(s,e){let{id:t,name:r,type:n,defaults:i}=e;_.setProjectId(t),_.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:i}}async function lR(s){var e;s.gridData=await mf(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function uR(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}async function pR(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(yt("user-override-file",t),s.mockNetworkRules=await Bb(s.overrideMappingFile))}async function dR(s,e){M("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:i}=s;r||(s.source=n||i?"cli-local":"cli"),await ZI(s),M("in runRunner before tunnel.connect"),await Xa(s),M("in runRunner after tunnel.connect");let a=await new Fr(e).run(s);return M("before tunnel.disconnect"),await Qa(s),await hR(s.slotService,t,s.company.companyId),M("after tunnel.disconnect and gridService.keepAlive.end"),a}function fR(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 gR(s,e,t){s==="redis"&&vn.start(t,e),s==="mongo"&&mn.start(e)}async function hR(s,e,t){s==="redis"&&await vn.end(t,e),s==="mongo"&&await mn.end(e)}async function yR(s){var h,g,y,T;M("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:i}=s,o=tR(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 ni(s);if(c.disabled)throw new C("The company is disabled.");if(d.disabled)throw new C("The project is disabled.");if(s.printGrids){let w=u.sort((b,S)=>b.type.localeCompare(S.type));console.table(w.reduce((b,S)=>{class E{constructor(j,R){this.Type=j,this.Browsers=R}}let A=Object.entries(S.browsers||{"N/A":""}).map(D=>D.join(":")).join(", ");return b[S.name]=new E(S.type,A),b},{})),process.exit(0)}if(await o,M("after featureFlagsReady and socketConnected"),iR(s,l),nR(s,c),cR(s,d),uR(s,d),rR(s,m),oR(s,u),aR(s,a),await sR(s,d),await lR(s),QI(s,c),(h=s.extensionLocation)!=null&&h.length||(s.extensionLocation=[mg(s)]),_.flags.clearRunnerFileCache.isEnabled())try{await Xr(),nd.info("runner file cache cleared")}catch(w){nd.error("failed to clear runner file cache",{err:w})}(g=s.lightweightMode)!=null&&g.disableLabs||await Nn.loadLabFeatures(d.id,c.activePlan),((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&(_.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((T=s.lightweightMode)==null?void 0:T.type)==="turboMode"&&console.log(`
|
|
415
|
+
Turbo mode will ignore step delays. Test artifacts like screenshots and logs will only be saved for failed runs. For more information see our docs: https://help.testim.io/docs/turbo-mode`),gR(s.slotService,e,c.id),eR(e),await pR(s),fR(s);let f=gn();await Q.setOptions(s,f)}var yT,gT,hT,nd,XI,mR,TT=v(()=>{"use strict";yT=I(require("lodash"));F();sd();je();ts();os();rs();Tl();ge();at();Yt();W();Pt();de();ie();Y();bp();_o();pu();ue();Tn();Np();Pn();gT=30*60*1e3,hT=1,nd=P("runner");XI={desktopWeb:"web",mobileWeb:"web",android:"mobile",ios:"mobile",sfdc:"sfdc"};mR=dR});function wT(s){s.get("/",(e,t)=>{let r=id();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:$a()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());Vp({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var vT=v(()=>{"use strict";Ha();od();_p()});var ad,ST,Ps,Za,ET=v(()=>{"use strict";ad=I(require("chalk"));hs();ST=require("express");W();Y();Ps=P("cli-router"),Za=(0,ST.Router)();Za.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:i,testResultId:o,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d}=s.body;if(typeof t!="string"||!r||!n||!i||!o||typeof a!="number"||!l||typeof c!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let m={stepId:r,testResultId:o,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d,nodePackageParams:n.nodePackageParams};try{let u=await gs(t,r,n,i,o,a,l,c,d);u.success||(console.log(ad.default.red(u.result.resultValue)),Ps.error("CLI Action Failure",{message:u.result.resultValue,...m})),e.status(200).json({success:!0,data:u})}catch(u){Ps.error("failed to run cli code",{err:u,...m}),console.log(ad.default.red("failed to run cli code",u)),e.status(500).json({success:!1,code:"internal-error"})}});Za.post("/install",async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,packageData:i,stepResultId:o,timeout:a}=s.body;if(!t||typeof i!="object"||!r||typeof n!="number"||!o||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let l={stepId:t,testResultId:r,retryIndex:n,stepResultId:o,timeout:a,packageData:i};try{let c=await fs(t,r,n,i,o,a);Ps.info("installed packages successfully",l),e.status(200).json({success:!0,data:c})}catch(c){if(c instanceof Rt){Ps.error("failed to install node packages",{err:c,...l}),e.status(200).json({success:!1,code:"invalid-node-package",message:c.message});return}if(c instanceof oe){Ps.error("timeout installing node package",{err:c,...l}),e.status(200).json({success:!1,code:"timeout"});return}Ps.error("failed to install node packages",{err:c,...l}),e.status(500).json({success:!1,code:"internal-error"})}})});var IT=v(()=>{"use strict";ET()});var CT={};H(CT,{orchestrateRoutes:()=>bR});function bR(s){let e=(0,xT.default)();e.disable("x-powered-by"),s(e),e.use(cd.default.urlencoded({extended:!1,limit:"50mb"})),e.use((0,AT.default)()),e.use(cd.default.json({limit:"50mb"}));let r={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:$e||Td?"*":["http://localhost:3000","https://app.testim.io","https://app.staging.testim.io","https://app-eu.staging.testim.io","https://app.dev.testim.io","https://app-eu.dev.testim.io","https://app-eu.prod.testim.io","https://playground.testim.io","chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia","https://tta-crm.tricentis.com"]};return e.use("*",(0,RT.default)(r)),wT(e),e.use("/cliJs",Za),e.use((n,i)=>{i.status(404).send("Endpoint Not Found")}),e}var RT,xT,cd,AT,PT=v(()=>{"use strict";RT=I(require("cors")),xT=I(require("express")),cd=I(require("body-parser")),AT=I(require("compression"));vT();IT();de()});var OT={};H(OT,{init:()=>TR});async function TR({agentPort:s,agentBind:e,project:t,token:r}){let{orchestrateRoutes:n}=await Promise.resolve().then(()=>(PT(),CT));return new Promise((i,o)=>{let a=()=>{};t&&(nf(t,r),a=u=>{u.use((f,h,g)=>{Object.assign(f,{project:t}),g()})});let l=n(a),c=kT.createServer(l);c.listen(s,e),c.on("error",d),c.on("listening",m);function d(u){if(u.syscall!=="listen")return o(u);switch(u.code){case"EACCES":case"EPERM":return o(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return o(new C(`Port ${s} is already in use, is another Testim instance running?`));default:return o(u)}}function m(){let{port:u}=c.address();console.log(`Running on port: ${u}`),wR()}})}async function wR(){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 kT,_T=v(()=>{"use strict";kT=I(require("http"));at();Y()});var BT={};H(BT,{getStartedWithStart:()=>id,runAgentMode:()=>IR});async function IR(s){var r;let e;if(await br(s.playerLocation,s.canary),s.startTestimBrowser){await AR();try{e=await xR(s)}catch(n){throw(r=n==null?void 0:n.message)!=null&&r.includes("user data directory is already in use")?new C('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(_T(),OT));return e!=null&&e.webdriverApi&&setTimeout(()=>{setTimeout(()=>(zu(),He(Jy)))},6e3),t.init(s)}function id(){return UT}function LT(s){try{return process.kill(s,0)}catch{return!1}}async function RR(s,e,t){let r=lr.join(Ft,`chrome-${an}-process`),n=3e3,i=()=>{Ce.rmSync(r,{recursive:!0}),console.log(`
|
|
416
416
|
|
|
417
|
-
Browser session ended`),process.exit(0)};if(await ye(r)){let f=JSON.parse(Ce.readFileSync(r));if(
|
|
418
|
-
`).map(i=>i.trim()),r=Number.parseInt(e,10);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await gr(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function
|
|
419
|
-
`):""}overrideMimeType(t){if([Ie.LOADING,Ie.DONE].includes(this.readyState))throw new ur("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new Os("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new pi("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:"?Ls:
|
|
417
|
+
Browser session ended`),process.exit(0)};if(await ye(r)){let f=JSON.parse(Ce.readFileSync(r));if(LT(f.pid)){let h=()=>LT(f.pid)?setTimeout(h,n):i();return h(),{webdriverApi:f}}}let o=await qi();await ye(ks)||await Ce.promises.mkdir(ks,{recursive:!0});let l=[...FT(ks,e,t,o).desiredCapabilities.chromeOptions.args,...tc.Launcher.defaultFlags().filter(f=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(f))],c={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},d=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`,m=await tc.launch({chromeFlags:l,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:ks,chromePath:o,envVars:c}),u={port:m.port,pid:m.pid,cdpUrl:await gr(`localhost:${m.port}`)};return Ce.writeFileSync(r,JSON.stringify(u)),m.process.once("exit",i),m.process.once("close",i),{webdriverApi:u}}async function xR(s){let e=`${Pd}/extension/testim-full-master.zip`,t=lr.basename(e),r=lr.join(Ft,t),n=lr.join(Ft,`${t}__unzipped__`),i=!(s.ext||s.extensionPath);if(i&&await ye(r)){let f=await Ce.promises.stat(r);i=Date.now()-SR>f.mtimeMs}if(await Ce.promises.mkdir(Ft,{recursive:!0}),i){let f=(0,NT.default)("Downloading Testim Editor").start();await Ke(e,r);try{await it(r,n)}catch{await Ce.promises.rm(r,{recursive:!0,force:!0}),await Ke(e,r);try{await it(r,n)}catch{throw await Ce.promises.rm(r,{recursive:!0,force:!0}),f.fail("Failed to download Testim Editor"),new Error("Failed to download Testim Editor")}}finally{s.downloadBrowser||await Ce.promises.rm(n,{recursive:!0,force:!0})}f.succeed()}let o=s.extensionPath?null:(await Ce.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await RR(s,o,n);await rn({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=FT(ks,o,s.extensionPath,s.chromeBinaryLocations),{WebDriver:l}=(Dn(),He(Gg)),{SeleniumPerfStats:c}=(ls(),He(og)),d=new l;d.seleniumPerfStats=new c;let m=await d.initClient(a);UT=!0;let u=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`;await d.url(u),Object.assign(d,{initialUrl:u});try{d.cdpUrl=await gr(m.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:d}}function FT(s,e,t,r){let n=e?[e]:[],i=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];t&&i.push(`--load-extension=${t}`);try{let o=nu();o.length&&o.forEach(a=>i.push(`--disable-features=${a}`))}catch{}return{logLevel:vR,desiredCapabilities:{chromeOptions:{args:i,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function AR(){if(await ye(ec))try{let{webSocketDebuggerUrl:s}=await CR();await PR(s),await Ce.promises.unlink(ec)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Ce.promises.unlink(ec)}}async function CR(){let s=await Ce.promises.readFile(ec,{encoding:"utf8"}),[e,t]=s.split(`
|
|
418
|
+
`).map(i=>i.trim()),r=Number.parseInt(e,10);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await gr(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function PR(s,e=100){let t=await kR(s,e);return Kt(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function kR(s,e=100){let t=La({timeout:e}),r=new MT.default(s,t),n=Kt(o=>{r.once("open",o)}).then(()=>{r.removeAllListeners()}),i=Kt(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return Promise.race([n,i]).then(()=>r)}var DT,NT,MT,Ce,lr,tc,vR,SR,ks,ER,ec,UT,od=v(()=>{"use strict";DT=I(require("ms")),NT=I(require("ora")),MT=I(require("ws")),Ce=I(require("node:fs")),lr=I(require("node:path")),tc=I(require("chrome-launcher"));de();nn();Y();ol();F();Ao();Da();vR=hi?"verbose":"silent",SR=(0,DT.default)("1h"),ks=lr.join(Ft,"profile"),ER="DevToolsActivePort",ec=lr.join(ks,ER);UT=!1});var RN=require("source-map-support/register");var mi=I(require("os")),_s=I(require("url")),Ls=I(require("http")),nc=I(require("https")),ai=I(require("form-data")),ci=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)}},li=class extends ci{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 ai.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()}},Os=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}},ui=class extends Error{},pi=class extends Error{},di=class extends Error{},ur=class extends Error{},Ie=class extends ci{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=Ls.globalAgent;this.nodejsHttpsAgent=nc.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 (${mi.type()} ${mi.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=Ie.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new li(this);this._method=null;this._url=null;this._sync=!1;this._headers=null;this._loweredHeaders=null;this._mimeOverride=null;this._request=null;this._response=null;this._responseParts=null;this._responseHeaders=null;this._aborting=null;this._error=null;this._loadedBytes=0;this._totalBytes=0;this._lengthComputable=!1;this._anonymous=t==null?void 0:t.anon}static nodejsSet(t){Ie.prototype.nodejsSet(t)}nodejsSet(t){if("httpAgent"in t&&(this.nodejsHttpAgent=t.httpAgent),"httpsAgent"in t&&(this.nodejsHttpsAgent=t.httpsAgent),"baseUrl"in t){let r=t.baseUrl;if(r!==null&&!_s.parse(r,!1,!0).protocol)throw new ui("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new di(`HTTP method ${t} is not allowed in XHR`);let i=this._parseUrl(r);n===void 0&&(n=!0),this._method=t,this._url=i,this._sync=!n,this._headers={},this._loweredHeaders={},this._mimeOverride=null,this._setReadyState(Ie.OPENED),this._request=null,this._response=null,this.status=0,this.statusText="",this._responseParts=[],this._responseHeaders=null,this._loadedBytes=0,this._totalBytes=0,this._lengthComputable=!1}setRequestHeader(t,r){if(this.readyState!==Ie.OPENED)throw new ur("XHR readyState must be OPENED");let n=t.toLowerCase();this._restrictedHeaders[n]||n.startsWith("sec-")||n.startsWith("proxy-")||(r=r.toString(),n in this._loweredHeaders?(t=this._loweredHeaders[n],this._headers[t]=`${this._headers[t]}, ${r}`):(this._loweredHeaders[n]=t,this._headers[t]=r))}send(t){if(this.readyState!==Ie.OPENED)throw new ur("XHR readyState must be OPENED");if(this._request)throw new ur("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new pi(`XHR request to ${this._url.href} failed: unsupported protocol '${this._url.protocol}'. Please use supported protocols like HTTP, HTTPS, or file.`)}}abort(){this._request&&(this._request.abort(),this._setError(),this._dispatchProgress("abort"),this._dispatchProgress("loadend"))}getResponseHeader(t){var n;let r=t.toLowerCase();return((n=this._responseHeaders)==null?void 0:n[r])||null}getAllResponseHeaders(){return this._responseHeaders?Object.entries(this._responseHeaders).map(([t,r])=>`${t}: ${r}`).join(`\r
|
|
419
|
+
`):""}overrideMimeType(t){if([Ie.LOADING,Ie.DONE].includes(this.readyState))throw new ur("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new Os("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new pi("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:"?Ls:nc).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 ai.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 ai.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=Ls.STATUS_CODES[this.status],this._parseResponseHeaders(r);let n=this._responseHeaders["content-length"];n?(this._totalBytes=parseInt(n,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(Ie.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==Ie.LOADING&&this._setReadyState(Ie.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Ie.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend")}_onHttpResponseClose(t){if(this._response!==t)return;let r=this._request;return this._setError(),r.abort(),this._setReadyState(Ie.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ie.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ie.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let r=new Os(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:_s.resolve(this.nodejsBaseUrl,t),a=_s.parse(o,!1,!0);return a.hash=null,a.auth&&(i!=null||n!=null)&&(r=a.auth.indexOf(":"),r===-1?i||(i=a.auth):(i||(i=a.substring(0,r)),n||(n=a.substring(r+1)))),(i||n)&&(a.auth=`${i}:${n}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([r,n])=>{let i=r.toLowerCase();this._privateHeaders[i]||(this._mimeOverride!==null&&i==="content-type"&&(n=this._mimeOverride),this._responseHeaders[i]=n)}),this._mimeOverride!==null&&!("content-type"in this._responseHeaders)&&(this._responseHeaders["content-type"]=this._mimeOverride)}_parseResponse(){let t=Buffer.concat(this._responseParts);switch(this._responseHeaders["content-encoding"]==="gzip"&&(t=require("zlib").gunzipSync(t)),this._responseParts=null,this.responseType){case"text":this._parseTextResponse(t);break;case"json":this.responseText=null;try{this.response=JSON.parse(t.toString("utf-8"))}catch{this.response=null}break;case"buffer":this.responseText=null,this.response=t;break;case"arraybuffer":{this.responseText=null;let r=new ArrayBuffer(t.length),n=new Uint8Array(r);for(let i=0;i<t.length;i++)n[i]=t[i];this.response=r;break}default:this._parseTextResponse(t)}}_parseTextResponse(t){try{this.responseText=t.toString(this._parseResponseEncoding())}catch{this.responseText=t.toString("binary")}this.response=this.responseText}_parseResponseEncoding(){let t=this._responseHeaders["content-type"],r=/;\s*charset=(.*)$/.exec(t);return t&&r?r[1]:"utf-8"}},ke=Ie;ke.SyntaxError=ui,ke.ProgressEvent=Os,ke.SecurityError=di,ke.XMLHttpRequest=Ie,ke.InvalidStateError=ur,ke.XMLHttpRequestUpload=li,ke.UNSENT=0,ke.OPENED=1,ke.HEADERS_RECEIVED=2,ke.LOADING=3,ke.DONE=4;Object.assign(global,{xhr2:ke,XMLHttpRequest:ke});var jT=I(require("semver"));je();Np();Yt();nn();var ld=I(require("chalk")),$T=require("node:events");ie();In();Y();ie();eo();W();var jb=I(require("os")),Mp=I(require("path")),Up=I(require("chalk")),Va=require("fs");de();function $b(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=jb.homedir();(0,Va.mkdirSync)(Mp.resolve(n,".testim_logs"),{recursive:!0});let i=Mp.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}`),Id&&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(Up.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(Up.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Va.writeFileSync)(i,`${s}
|
|
420
420
|
${s==null?void 0:s.stack}
|
|
421
421
|
|
|
422
|
-
${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}tn();var
|
|
422
|
+
${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}tn();var AI=P("process-handler"),Wb=!1;function CI(s){return s instanceof Error?1:Wb?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 PI(){try{Xt("chromedriver").stop()}catch{}}function Vb(){Wb=!0}async function Fp(s){s!=null&&s.stack&&(ss?console.error(s,s.stack):$b(s)),PI(),await AI.waitForFlush(),process.exit(CI(s))}ge();W();ue();Xp();var OR=P("cli-entry");function _R(s){if(!jT.satisfies(process.version,s))throw new C(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=20,t=22,r=Number(process.versions.node.split(".")[0]),n=new Date("2026-04-30T00:00:00.000Z"),i=n<=new Date,o=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(n);if(r<e)throw new C(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&i)throw new C(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(ld.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${o}. please upgrade to a newer Node.js version.`))}async function LR(){console.log("Starting Testim.io CLI");let[s,e]=await Promise.all([Promise.resolve().then(()=>(F(),J)),Promise.resolve().then(()=>(Xp(),nT))]);M("Starting Testim.io CLI"),Vf(Fp);try{_R(s.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{await _.fetch({proxy:p.proxy});let t=await e.process();if(M("in main, after options.process"),Kd(global.proxyUri),$T.EventEmitter.defaultMaxListeners="parallel"in t&&t.parallel>10?t.parallel*3:30,zd(t.project),Pm("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(()=>(Rn(),zf));return await i()}if(s.isLoginMode(t))return;if(s.isCreatePrefetchedDataMode(t)){await Xr(),await ni(t);let{preloadTests:i}=await Promise.resolve().then(()=>(Oo(),nh));await i(t),!t.playerRequirePath&&t.mode!==q.EXTENSION&&await br(t.playerLocation,t.canary);let o=await Am();o.success?console.log(`created prefetched data at ${Ui()}`):console.error("failed to create prefetch data",o.error);return}let r=await Promise.resolve().then(()=>(TT(),bT));if(s.isTunnelOnlyMode(t)){await r.init(t);let{serveTunneling:i}=await Promise.resolve().then(()=>(sd(),rd));await i(t);return}if(s.isAgentMode(t)){let{runAgentMode:i}=await Promise.resolve().then(()=>(od(),BT));return i(t)}if(t.saveRCALocally){let{initServer:i}=await Promise.resolve().then(()=>(Kl(),ug)),{port:o}=await i(t);t.localRCASaver=`http://localhost:${o}`}t.exitCodeIgnoreFailingTests&&Vb(),M("right before testRunner.init/prepareRunner.prepare"),await r.init(t);let n=await Fb(t);return M("right after testRunner.init/prepareRunner.prepare"),await r.run(t,n)}catch(t){if(t instanceof $r)return;let r=s.getArgsOnRemoteRunFailure();return r&&await Op({...r,error:t.message}).catch(()=>{}),t instanceof C?(console.log(ld.default.red("Argument Error:",t.message)),t):(console.log("Error:",t.message),OR.error("runner ended with unexpected error",{err:t}),t)}}LR().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),Fp(s)});
|
|
423
423
|
//# sourceMappingURL=cli.js.map
|