@testim/testim-cli 4.13.0 → 4.14.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 +55 -55
- package/cli.js.map +3 -3
- package/npm-shrinkwrap.json +63 -63
- package/package.json +3 -3
package/cli.js
CHANGED
|
@@ -1,37 +1,37 @@
|
|
|
1
1
|
#! /usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
${l.msg}`));for(let d of DT)a[d]instanceof Error&&(l[d]={message:a[d].message,stack:a[d].stack,name:a[d].name,type:a[d].type,cause:a[d].cause,...a[d]});Object.keys(l).length>0&&(i&&!m&&(l.msg=i),p.text=l),this.logger.addLog(p),s(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Re.CoralogixLogger.configure(t),Br.options=t}}});var Ya={};$(Ya,{getLogger:()=>x,setExecutionId:()=>za,setProjectId:()=>Ka,setProxyUri:()=>Ja});function FT(){let r=[],e=()=>Promise.resolve();if(!De){let{CoralogixTransport:t}=(Ga(),ve(Ha));t.configure(id);let s=new t({category:"ROOT"});r.push(s),e=()=>s.waitForFlush()}return Kp&&r.push(new bt.transports.Console({format:bt.format.combine(bt.format.colorize(),bt.format.simple())})),[r,e]}function za(r){Va=r}function Ka(r){ad=r}function Ja(r){if(De||!r)return;let{CoralogixTransport:e}=(Ga(),ve(Ha));e.configure({...id,proxyUri:r})}function nd(r){return{projectId:ad,time:new Date().toISOString(),...Va&&!r&&{executionId:Va}}}function x(r){return new qa(WT.child({category:r}))}var od,bt,NT,MT,id,UT,jT,BT,$T,WT,Va,ad,qa,U=T(()=>{"use strict";od=E(require("os")),bt=E(require("winston"));pe();j();NT=od.hostname(),MT=ot(),id={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};[UT,jT]=FT(),BT=Jp?"debug":"info",$T={release:Boolean(!0),branch:"production"},WT=bt.createLogger({levels:bt.config.syslog.levels,level:BT,transports:UT,defaultMeta:{name:"runner",hostname:NT,nodeVersion:process.version,runnerVersion:MT,...$T}}),Va=null,ad=null;qa=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,s={}){let{executionId:n}=s;try{this._logger.log(e,Object.assign({meta:s,message:t},nd(n)))}catch(o){try{this._logger.log("crit",Object.assign({message:`failed to log message ${o.message}, ${o.stack}`},nd(n)))}catch{}}}waitForFlush(){return jT()}}});var Xa,Ie,$r,k,Wr,Gt,fr,Tt,to,te,Fs,wt,Hr,vt,ro,Gr,Vr,qr,Us,V=T(()=>{"use strict";Xa=require("p-retry"),Ie=class extends Error{constructor(t="aborted"){super(t);this.name="AbortError"}},$r=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},k=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Wr=class extends Error{constructor(t){super(t.orgStatusMessage||t.message);this.name="SeleniumError",this.errorType=t.type}},Gt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},fr=class extends Error{constructor(t,s){super(t);this.type=s}},Tt=class extends Xa.AbortError{},to=class extends Xa.AbortError{},te=class extends Error{},Fs=class extends Error{},wt=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Hr=class extends wt{constructor(){super(...arguments);this.name="GridConcurrencyError"}},vt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},ro=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Gr=class extends Error{},Vr=class extends Error{constructor(t){super();this.innerStack=t}},qr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Us=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Qa(r){return!!r&&(typeof r=="object"||typeof r=="function")&&typeof r.then=="function"&&typeof r.catch=="function"}function se(r){return new Promise(e=>{setTimeout(e,r)})}function ne(r,e,t="Timeout Error"){Qn&&!cd&&(cd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let s=new te(t);return e=Qn?Number(Qn)||6e5:e,Promise.race([r,se(e).then(()=>{throw s})])}async function ce(r,e,{concurrency:t}={}){if(t){ld||(ld=(await import("p-limit")).default);let s=ld(t);return await Promise.all(Array.from(r,(n,o)=>s(()=>e(n,o))))}return await Promise.all(Array.from(r,e))}function it(r){return new Promise((e,t)=>{r((s,n)=>s?t(s):e(n))})}var cd,ld,Za=T(()=>{"use strict";V();pe();cd=!1});var Bs,ud,HT,js,pd,GT,VT,dd,md=T(()=>{"use strict";Bs=E(require("lodash"));pe();ud=require("dns");U();Za();HT=x("http-request-counters"),js=!1,pd=async()=>{if(De)return!0;let r=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ce(r,t=>ud.promises.lookup(t)));return e||(js=!0),e}catch{return HT.error("network connectivity test failed"),js=!0,!1}},GT=Bs.throttle(pd,10*1e3),VT=60*1e3*15,dd=()=>{let r={call:new Map,success:new Map,fail:new Map};function e(n,o){let i=n.get(o)||0;n.set(o,i+1),setTimeout(()=>{let a=n.get(o)||1;n.set(o,a-1)},VT)}function t(n,o=n.name){return async function(...i){e(r.call,o);try{let a=await n.call(null,...i);return e(r.success,o),a}catch(a){throw e(r.fail,o),js||GT(),a}}}async function s(){if(js||!await pd())return!1;let n=Bs.sum([...r.fail.values()]),o=Bs.sum([...r.call.values()]);return n<o*.1}return s.counters=r,t.counters=r,t.isNetworkHealthy=s,t.didNetworkConnectivityTestFail=()=>js,t}});var St={};$(St,{deleteFullRes:()=>YT,deleteReq:()=>$s,didNetworkConnectivityTestFail:()=>ac,download:()=>oc,get:()=>Ot,getFullRes:()=>QT,getText:()=>sc,head:()=>ZT,isNetworkHealthy:()=>ic,post:()=>Qe,postForm:()=>tc,postFullRes:()=>XT,put:()=>nc});function zT(){return global.caFileContent}function KT(r,e){let t=[];r.on("data",s=>{t.push(s)}),r.on("end",()=>{e(null,Buffer.concat(t))})}function JT(){return!Et.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(Et.default),global.proxyUri}function gr(r,e=!1){let t=zT();t&&r.ca(t);let s=!e&&JT();s&&r.proxy(s)}async function fd(r,e={},t={},s=zr){let n=Et.default.delete(r).send(e).timeout(s).set(t);return gr(n),await n}async function gd(r,e,t={},s=zr,n=0){let o=Et.default.post(r).send(e).timeout(s).set(t);gr(o),n&&o.retry(n);try{return await o}catch(i){throw i.url=r,i.originalRequestTimeout=s,i.additionalSetHeaders=t,i}}async function rc(r,e,t={},s=zr,{isBinary:n=!1,skipProxy:o=!1}={}){let i=Et.default.get(r).query(e||{}).timeout(s).set(t);return n&&i.buffer(!0),gr(i,o),await i}var Et,ec,Ge,zr,qT,Vt,$s,YT,Qe,XT,tc,sc,Ot,QT,ZT,nc,oc,ic,ac,at=T(()=>{"use strict";Et=E(require("superagent"));U();md();ec=x("http-request"),Ge=dd(),zr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,qT=6e4;Vt=(r,e,t)=>{throw ec.error(r,{...t,error:e}),e};$s=Ge(async(r,e,t,s)=>{try{let n=await fd(r,e,t,s);return n.type==="text/plain"?n.text:n.body}catch(n){return Vt("failed to delete request",n,{url:r})}});YT=Ge(fd),Qe=Ge(async({url:r,body:e,headers:t,timeout:s,retry:n})=>{try{let o=await gd(r,e,t,s,n);return o.type==="text/plain"?o.text:o.body}catch(o){return Vt("failed to post request",o,{url:r})}});XT=Ge(gd),tc=Ge(async(r,e,t,s={},n=zr)=>{let o=Et.default.post(r).type("form").timeout(n).set(s);o.field(e),Object.keys(t).forEach(i=>{o.attach(i,t[i].buffer,t[i].fileName)}),gr(o);try{let i=await o;return i.type==="text/plain"?i.text:i.body}catch(i){return Vt("failed to post request",i,{url:r})}});sc=Ge(async(r,e,t)=>{try{return(await rc(r,e,t)).text}catch(s){return Vt("failed to getText request",s,{url:r,query:e})}}),Ot=Ge(async(r,e,t,s,n)=>{try{return(await rc(r,e,t,s,n)).body}catch(o){return Vt("failed to get request",o,{url:r,query:e})}}),QT=Ge((r,e,t,s)=>rc(r,e,t,s)),ZT=Ge(async r=>{let e=Et.default.head(r).timeout(zr);gr(e);try{return await e}catch(t){return Vt("failed to head request",t,{url:r})}}),nc=Ge(async(r,e,t={},s=zr)=>{let n=Et.default.put(r).send(e).timeout(s).set(t);gr(n);try{return(await n).body}catch(o){return Vt("failed to put request",o,{url:r})}}),oc=Ge(async r=>{ec.info("start to download",{url:r});let e=Et.default.get(r).timeout(qT).buffer(!0).parse(KT);gr(e);try{let t=await e;return ec.info("finished to download",{url:r}),t}catch(t){return Vt("failed to download",t,{url:r})}}),ic=Ge.isNetworkHealthy,ac=Ge.didNetworkConnectivityTestFail});function ct(){let r;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?r=_t.resolve(__dirname,"../../"):r=_t.resolve(__dirname,""),r):process.cwd()}function so(r,e){return We(r)?e||_t.join(process.cwd(),r.replace(/^.*[\\/]/,"")):e||_t.basename(r)}function ot(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function tw(){try{return Hp.node}catch{return""}}async function oo(r,e,t=!0){let s=await Ve.promises.readdir(r,{withFileTypes:!0});await Ve.promises.mkdir(e,{recursive:t});for(let n of s){let o=_t.join(r,n.name),i=_t.join(e,n.name);n.isDirectory()?await oo(o,i):await Ve.promises.copyFile(o,i)}}async function ye(r){try{return await Ve.promises.access(r),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var _t,hd,yd,Ve,ew,hr,qe,bd,no,cc,Ze,lc,uc=T(()=>{"use strict";_t=E(require("path"));ja();Yn();hd=E(require("p-retry")),yd=E(require("decompress")),Ve=require("fs"),ew=3;hr=async r=>{let e=await Promise.resolve().then(()=>(at(),St));return(0,hd.default)(()=>e.download(r),{retries:ew,factor:1})},qe=async(r,e)=>{let t=await hr(r);return Ve.promises.writeFile(e,t.body)},bd=async(r,e)=>new Promise((t,s)=>{try{let n=(0,Ve.createWriteStream)(e);(0,Ve.createReadStream)(r).pipe(n),n.on("finish",()=>{n.close(()=>t())})}catch(n){s(n)}});no=async(r,e)=>{let t=so(r,e);return We(r)?qe(r,t):bd(r,t)},cc=async r=>We(r)?hr(r):Ve.promises.readFile(r),Ze=async(r,e)=>await(0,yd.default)(r,e),lc=r=>(0,Ve.statSync)(r).size/1e6});var Dt={};$(Dt,{APPIUM_SESSION_MESSAGE:()=>gc,CLI_MODE:()=>Y,MOBILE_APP_SOURCE:()=>io,MOBILE_RUN_SKIP_REASON:()=>fc,gridMessages:()=>Kr,gridTypes:()=>W,mobileWeb:()=>dc,runnerStatus:()=>pc,runnerTestStatus:()=>de,sessionType:()=>Lt,socketEventTypes:()=>et,stepResult:()=>Hs,test:()=>mc,testRunStatus:()=>Ws,testStatus:()=>ze,timeoutMessages:()=>Be});var Be,Ws,pc,de,ze,Kr,dc,mc,et,Y,Lt,W,Hs,io,fc,gc,ie=T(()=>{"use strict";Be={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Ws={COMPLETED:"completed",RUNNING:"running"},pc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},de={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},ze={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},Kr={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},dc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},mc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},et={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},Y={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},Lt={CODELESS:"codeless",CODEFUL:"codeful"},W={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin"},Hs={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"},io={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},fc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build",MISSING_BROWSERSTACK_APP_ID:"missing-browserstack-app-id"},gc={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"}});function yr(r){return r.files.length>0?Lt.CODEFUL:Lt.CODELESS}function Gs(r,e){var t,s,n;return((t=r.testConfigNames)!=null&&t.length||(s=r.testConfigIds)!=null&&s.length||r.testPlan.length||r.testPlanIds.length)&&!r.browser?[...new Set(e.map(o=>{var i;return(i=o.runConfig)==null?void 0:i.browserValue}))]:[(n=r.browser)==null?void 0:n.toLowerCase()]}function rw(){let{argv:r}=process;if(r.includes("--remoteRunId"))return{remoteRunId:r[r.indexOf("--remoteRunId")+1],projectId:r[r.indexOf("--project")+1],token:r[r.indexOf("--token")+1]}}var Vs,Td,Ke,sw,nw,ow,iw,aw,cw,hc,wd=T(()=>{"use strict";ie();Vs=r=>{var e,t;return Boolean(((e=r.testPlan)==null?void 0:e.length)||((t=r.testPlanIds)==null?void 0:t.length))},Td=r=>Boolean(r.resultId&&r.source==="remote-run"),Ke=(r,e)=>r.testStatus===ze.QUARANTINE&&!Td(e)&&!e.runQuarantinedTests;sw=r=>Boolean(r.initCodimMode),nw=r=>Boolean(r.loginMode),ow=r=>Boolean(r.tunnelOnlyMode),iw=r=>Boolean(r.createPrefechedData),aw=r=>Boolean(r.installLazyDepsMode),cw=r=>Boolean(r.agentMode),hc=(r,e)=>{r.forEach((t,s)=>{e.has(t)&&(r[s]=`--${t}`)})}});function ao(r){let e=yc.default.duration(r);return`${e.hours()}:${e.minutes()}:${e.seconds()}.${e.milliseconds()}`}function bc(r){return yc.default.duration(r).asSeconds()}var yc,vd=T(()=>{"use strict";yc=E(require("moment"))});var qs,Jr,Yr,Ed=T(()=>{"use strict";qs=r=>!(!r||"fileName"in r),Jr=r=>r&&"fileName"in r?r.fileName.endsWith(".app"):!1,Yr=r=>{var e,t;return((e=r.projectData)==null?void 0:e.type)==="ios"||((t=r.projectData)==null?void 0:t.type)==="android"}});function Tc(r=4e3){let e=process.memoryUsage(),t=s=>Math.round(s/1024/1024*100)/100;return{isOverThreshold:t(e.rss)>r,rss:`${t(e.rss)} MB -> Resident Set Size - total memory allocated for the process execution`,heapTotal:`${t(e.heapTotal)} MB -> total size of the allocated heap`,heapUsed:`${t(e.heapUsed)} MB -> actual memory used during the execution`,external:`${t(e.external)} MB -> V8 external memory`}}var Sd=T(()=>{"use strict"});var q={};$(q,{TESTIM_BROWSER_DIR:()=>Nt,buildBasicHeader:()=>Ua,calcPercentile:()=>uo,copy:()=>bd,copyDir:()=>oo,delay:()=>se,doesPathExist:()=>ye,download:()=>hr,downloadAndSave:()=>qe,extractElementId:()=>Me,getArgsOnRemoteRunFailure:()=>rw,getBrowserInfo:()=>Ks,getCdpAddressForHost:()=>wr,getCliLocation:()=>ct,getDuration:()=>ao,getDurationSec:()=>bc,getEnginesVersion:()=>tw,getEnvironmentGitBranch:()=>Tr,getLocalFileSizeInMB:()=>lc,getMemorySnapshot:()=>Tc,getPlanType:()=>lo,getRunConfigByBrowserName:()=>Js,getRunnerVersion:()=>ot,getSessionType:()=>yr,getSource:()=>no,getSourceAsBuffer:()=>cc,getSourcePath:()=>so,getTestUrl:()=>nt,getUniqBrowsers:()=>Gs,groupTestsByRetries:()=>vc,guid:()=>J,hasTestPlanFlag:()=>Vs,isAgentMode:()=>cw,isAppForVirtualIosDevice:()=>Jr,isAppFromDevice:()=>qs,isCreatePrefetchedDataMode:()=>iw,isInitCodimMode:()=>sw,isInstallLazyDepsMode:()=>aw,isLoginMode:()=>nw,isMobileProject:()=>Yr,isPromise:()=>Qa,isQuarantineAndNotRemoteRun:()=>Ke,isRemoteRun:()=>Td,isTunnelOnlyMode:()=>ow,isURL:()=>We,promiseFromCallback:()=>it,promiseMap:()=>ce,promiseTimeout:()=>ne,removePropertyFromObject:()=>co,replaceArgsWithNoDashes:()=>hc,unzipFile:()=>Ze});function Ks(r){return r=r.toLowerCase(),wc.find(e=>e.browserValue===r)}function Js(r,e,t){r=r.toLowerCase();let s=wc.find(o=>o.browserName.toLowerCase()===r||r.includes(o.synonyms))||wc[0],n=zs.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=zs.find(o=>o.sl.platform===e.platform):e.platformName&&(n=zs.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=zs.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=zs.find(o=>o.bs.platform===t.platform))),br.merge(s,n)}function Tr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function co(r,e,t){for(let s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t(s,e)?delete r[s]:typeof r[s]=="object"&&co(r[s],e,t))}function Me(r){return r.ELEMENT||r[Ht]}function lo(r){r||(r={});let e=Date.now(),t=r.expireAt||r.expireAT;return r.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function vc(r=[]){return br.chain(r).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let s=br.orderBy(t,o=>typeof o.retryCount=="number"?o.retryCount:1),n=br.chain(s).last().cloneDeep().value();return n&&(n.retryTestResults=s,e.push(n)),e},[]).compact().value()}async function wr(r,e){let t=await Promise.resolve().then(()=>(at(),St));try{return(await t.get(`http://${r}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var Rd,br,Id,lw,Nt,zs,wc,uo,j=T(()=>{"use strict";Rd=E(require("os")),br=E(require("lodash")),Id=E(require("path"));Fr();uc();wd();vd();ja();Za();Ed();Sd();lw=Rd.homedir(),Nt=Id.join(lw,".testim-browser-profile"),zs=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{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 Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14"},sl:{platform:"macOS 11",safari_version:"14"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13"},sl:{platform:"macOS 10.15",safari_version:"13"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12"},sl:{platform:"macOS 10.14",safari_version:"12"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11"},sl:{platform:"macOS 10.13",safari_version:"11"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10"},sl:{platform:"macOS 10.12",safari_version:"10.0"}},{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:"9.0"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"8.0"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"7.0"}},{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:"6.0"}},{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"}}],wc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:"94"},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",bs:{browser:"Edge",browser_version:"18"},sl:{browserName:"MicrosoftEdge",version:"18.17763"},browserValue:"edge",eol:!0},{browserName:"Edge Chromium",bs:{browser:"Edge",browser_version:"94"},sl:{browserName:"MicrosoftEdge",version:"94"},synonyms:["edge-chromium"],browserValue:"edge-chromium",seleniumName:"MicrosoftEdge"},{browserName:"Internet Explorer 11",bs:{browser:"IE",browser_version:"11"},sl:{browserName:"internet explorer",version:"11.0"},synonyms:["ie11"],browserValue:"ie11",eol:!0},{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"}];uo=(r,e)=>{if(r.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(r=[...r].sort((s,n)=>s-n),e<=0)return r[0];if(e>=100)return r.at(-1);let t=Math.ceil(r.length*(e/100))-1;return r[t]}});var Ec={};$(Ec,{$schema:()=>uw,default:()=>gw,definitions:()=>pw,properties:()=>fw,required:()=>mw,type:()=>dw});var uw,pw,dw,mw,fw,gw,xd=T(()=>{uw="http://json-schema.org/draft-07/schema#",pw={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}}}},dw="object",mw=["entries"],fw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},gw={$schema:uw,definitions:pw,type:dw,required:mw,properties:fw}});async function Ld(){try{return await ne(po.promises.readFile(ho()).then(async r=>{let e=await _d;return bw(e,r)}),3e4)}catch{return{}}}function bw(r,e){let t=e.slice(0,16),s=e.slice(16),n=Buffer.from(r),o=Qr.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),i=o.update(s);return JSON.parse(Buffer.concat([i,o.final()]))}function lt(r,e,t=hw,s=void 0){return async()=>{if(!Cd)return await r();let n=e;s&&(e+=JSON.stringify(s));let o=await Tw(e);if(o)return Ys.debug("cache hit:",{fnName:e}),o;if(Ys.debug("cache miss:",{fnName:e}),!Ad)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let i=await r();return i&&await ww(e,i,t),i}}async function Tw(r){let t=(await yo)[r];if(!t)return;let{value:s,expiry:n}=t;if(!(n<Date.now())&&s)return s}async function ww(r,e,t){if(Sc)throw Ys.error("calling set after waitForSave is not allowed",{key:r,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let s=await yo;s[r]={value:e,expiry:Date.now()+t},Od=new Promise(n=>{go=n}),yw(s)}catch{Ys.error("failed updating cache")}}async function Dd(){let r=await yo;Object.keys(r).forEach(e=>{delete r[e]})}function Nd(r){Cd=r}function vw(r=!0){Ad=r}async function Md(){try{return Sc=!0,await Od}finally{Sc=!1}}function Fd(r){fo=r,yo=Ld()}var po,mo,Qr,kd,Ys,fo,Pd,go,Cd,Ad,Sc,Od,_d,hw,ho,yo,yw,Ud,jd,KI,Bd,qt=T(()=>{"use strict";po=E(require("fs")),mo=E(require("path")),Qr=E(require("crypto"));j();kd=require("lodash");U();Ys=x("local cache"),fo=mo.resolve(ct(),"testim-cache"),Cd=!0,Ad=!0,Sc=!1,Od=new Promise(r=>{go=r}),_d=new Promise(r=>{Pd=r}),hw=1e3*60*60*3,ho=()=>mo.resolve(mo.resolve(fo,"testim.cache"));yo=Ld(),yw=(0,kd.debounce)(async r=>{let e;try{let t=await _d,s=Qr.randomBytes(16),n=JSON.stringify(r),o=Buffer.from(t),i=Qr.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),s),a=Buffer.concat([s,i.update(n),i.final()]);await ye(fo)||await po.promises.mkdir(fo,{recursive:!0}),await po.promises.writeFile(ho(),a)}catch(t){Ys.error("failed saving cache",{err:t}),e=t}go(e?{success:!1,error:e}:{success:!0})},200);Ud=Pd,jd=Nd.bind(void 0,!1),KI=Nd.bind(void 0,!0),Bd=()=>vw(!1)});function bo(){return{cliLocation:ct(),userInfo:Zr.userInfo(),platform:Zr.platform(),release:Zr.release()}}var Zr,Rc=T(()=>{"use strict";Zr=E(require("os"));j()});function Ew(r){try{return To.resolve(To.dirname(require.resolve(`${r}/package.json`)),require(`${r}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(r);throw e}}function zt(r){let e=Ew(r);return require(e)}var To,Xs=T(()=>{"use strict";To=E(require("path"))});async function Gd(r){return(await Wd(`npm view ${r} version`)).stdout.trim()}function xc(r){try{return zt(r)}catch{return!1}}function Vd(r,e){return require(es.join(r,`./node_modules/${e}/package.json`)).version}async function vo(r,e,t){function s(c){let p=/EACCES[^']+'(.+)'/.exec(c.stderr);return p===null?!1:p[1]}function n(c){return/The "to" argument must be of type string./.exec(c.stderr)}let o=es.join(r,"npm-shrinkwrap.json"),i=es.join(r,"npm-shrinkwrap-dummy.json"),a=!1;try{try{await ye(o)&&(await Ic.promises.rename(o,i),a=!0)}catch{}return await Wd(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:r}).catch(c=>{let l=s(c),p=n(c);throw l||p?(Hd.info("Failed to install package due to insufficient write access",{...bo(),package:e,path:l||r}),console.error(`
|
|
2
|
+
"use strict";var kT=Object.create;var Wn=Object.defineProperty;var PT=Object.getOwnPropertyDescriptor;var CT=Object.getOwnPropertyNames;var AT=Object.getPrototypeOf,OT=Object.prototype.hasOwnProperty;var T=(r,e)=>()=>(r&&(e=r(r=0)),e);var $=(r,e)=>{for(var t in e)Wn(r,t,{get:e[t],enumerable:!0})},Up=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of CT(e))!OT.call(r,n)&&n!==t&&Wn(r,n,{get:()=>e[n],enumerable:!(s=PT(e,n))||s.enumerable});return r};var E=(r,e,t)=>(t=r!=null?kT(AT(r)):{},Up(e||!r||!r.__esModule?Wn(t,"default",{value:r,enumerable:!0}):t,r)),ve=r=>Up(Wn({},"__esModule",{value:!0}),r);var _e={};$(_e,{log:()=>O,measure:()=>LT});function O(...r){if(!Wp)return;let e=Date.now();console.log(`${e-_T} ${e-$p} `,...r),$p=e}function LT(r,e){if(!Wp)return;let t=Date.now();try{r()}finally{console.log(e||r.name,"took",Date.now()-t)}}var Wp,_T,$p,Le=T(()=>{"use strict";Wp=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,_T=Date.now(),$p=Date.now()});var Ma,Ht,Fa,Fr=T(()=>{"use strict";Ma={NULL:"\uE000",Unidentified:"\uE000",Cancel:"\uE001",Help:"\uE002","Back space":"\uE003",Backspace:"\uE003",Tab:"\uE004",Clear:"\uE005",Return:"\uE006",Enter:"\uE007",Shift:"\uE008",Control:"\uE009",Alt:"\uE00A",Pause:"\uE00B",Escape:"\uE00C",Space:"\uE00D"," ":"\uE00D",Pageup:"\uE00E",PageUp:"\uE00E",Page_Up:"\uE00E",Pagedown:"\uE00F",PageDown:"\uE00F",Page_Down:"\uE00F",End:"\uE010",Home:"\uE011","Left arrow":"\uE012",Arrow_Left:"\uE012",ArrowLeft:"\uE012","Up arrow":"\uE013",Arrow_Up:"\uE013",ArrowUp:"\uE013","Right arrow":"\uE014",Arrow_Right:"\uE014",ArrowRight:"\uE014","Down arrow":"\uE015",Arrow_Down:"\uE015",ArrowDown:"\uE015",Insert:"\uE016",Delete:"\uE017",Semicolon:"\uE018",Equals:"\uE019","Numpad 0":"\uE01A","Numpad 1":"\uE01B","Numpad 2":"\uE01C","Numpad 3":"\uE01D","Numpad 4":"\uE01E","Numpad 5":"\uE01F","Numpad 6":"\uE020","Numpad 7":"\uE021","Numpad 8":"\uE022","Numpad 9":"\uE023",Multiply:"\uE024",Add:"\uE025",Separator:"\uE026",Subtract:"\uE027",Decimal:"\uE028",Divide:"\uE029",F1:"\uE031",F2:"\uE032",F3:"\uE033",F4:"\uE034",F5:"\uE035",F6:"\uE036",F7:"\uE037",F8:"\uE038",F9:"\uE039",F10:"\uE03A",F11:"\uE03B",F12:"\uE03C",Command:"\uE03D",Meta:"\uE03D",Zenkaku_Hankaku:"\uE040",ZenkakuHankaku:"\uE040"},Ht="element-6066-11e4-a52e-4f735466cecf",Fa=79});function J(r=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let s=0;s<r;s++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function nt(r,e,t,s,n){let o="";return n=n?encodeURIComponent(n):"master",e&&t&&(o=`${r}/#/project/${e}/branch/${n}/test/${t}`,s&&(o+=`?result-id=${s}`)),o}function Ua(r,e){return`Basic ${Buffer.from(`${r}:${e}`).toString("base64")}`}function We(r){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(r)||t.test(r)}var ja=T(()=>{"use strict"});var $a,Hp,Gp,Yn=T(()=>{$a={ngrok:"4.3.3",webpack:"5.74.0",playwright:"0.12.1",puppeteer:"2.1.1","selenium-webdriver":"3.6.0","v8-to-istanbul":"9.1.0","istanbul-lib-coverage":"3.2.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"1.4.5-lts.1"},Hp={"@applitools/eyes-sdk-core":"13.11.32","@applitools/spec-driver-webdriverio":"1.4.29","@testim/coralogix-logger":"1.1.27-beta.1","abort-controller":"3.0.0",ajv:"6.12.6","analytics-node":"5.0.0","body-parser":"1.20.1",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",decompress:"4.2.1",express:"4.17.3",fkill:"7.2.1","form-data":"3.0.0",glob:"7.2.0","https-proxy-agent":"5.0.0","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"0.16.2",jsdom:"19.0.0",jsonwebtoken:"9.0.0",linkedom:"^0.14.25",lodash:"4.17.21","memory-fs":"0.5.0",moment:"2.29.4",ms:"2.1.2",npm:"8.19.2","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":"5.0.0","rox-node":"4.9.18",semver:"7.3.2","serialize-error":"7.0.1","socket.io-client":"4.5.4","source-map-support":"0.5.19",superagent:"3.8.3","superagent-proxy":"3.0.0","test-exclude":"6.0.0","ua-parser-js":"0.7.33","validate-npm-package-name":"3.0.0",webdriverio:"7.24.0",winston:"3.6.0","winston-transport":"4.5.0",ws:"8.5.0",xml2js:"0.5.0",yaml:"2.2.2"},Gp={node:">= 16.0.0"}});var Ms,Vp,qp,Xn,zp,Qn,Ur,Kp,me,Jp,Yp,Zn,De,Wa,RI,eo,Xp,II,Qp,xI,Zp,ed,jr,td,rd,sd,pe=T(()=>{"use strict";Ms=process.env.SERVICES_HOST||"https://services.testim.io",Vp="https://testimstatic.blob.core.windows.net",qp="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:Ms,Ms=process.env.SERVICES_HOST);Xn=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),zp=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),Qn=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),Ur=process.env.EDITOR_URL,Kp=process.env.WEBSOCKET_HOST||`${Ms}/ws`,me=Ms,Jp=parseInt(process.env.LOGGER_CONSOLE||"0",10),Yp=parseInt(process.env.LOGGER_DEBUG||"0",10),Zn=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),De=parseInt(process.env.IS_ON_PREM||"0",10),Wa=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,RI=parseInt(process.env.DEBUG_MODE||"0",10),eo=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,Xp=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",II=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),Qp=parseInt(process.env.START_WORKER_DELAY_MS||"1500",10),xI=process.env.APPIUM_VERSION||"1.10.1",Zp=process.env.GATEWAY_URL,ed=process.env.EXTENSION_SERVICES_HOST||Ms,jr=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:Vp,td=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:qp,rd=Vp,sd=qp});var Ha={};$(Ha,{CoralogixTransport:()=>Br});var Re,nd,MT,FT,Br,Ga=T(()=>{"use strict";Re=require("@testim/coralogix-logger"),nd=E(require("winston-transport")),MT={silly:Re.Severity.verbose,verbose:Re.Severity.verbose,info:Re.Severity.info,http:Re.Severity.info,warn:Re.Severity.warning,warning:Re.Severity.warning,error:Re.Severity.error,silent:Re.Severity.verbose,critical:Re.Severity.critical,crit:Re.Severity.critical,debug:Re.Severity.debug},FT=["err","error","reason","e"],Br=class extends nd.default{constructor(t){t=Object.assign({},Br.options,t);super(t);this.options=t,this.logger=new Re.CoralogixLogger(t.category||""),this.name="Coralogix Transport",t.timestamp&&(this.timestamp=t.timestamp)}log(t,s){let{category:n,level:o,message:i,meta:a={},...c}=t,l=Object.assign({},a,this.options.extraFields,c),m=new Re.Log;m.severity=MT[o],m.text=i,m.category=n,l.className&&(m.className=l.className),l.methodName&&(m.methodName=l.methodName),l.threadId&&(m.threadId=l.threadId),delete l.className,delete l.methodName,delete l.threadId,delete l.category,delete l.level,delete l.message;let d=!1;a instanceof Error&&(d=!0,l.msg=a.message+a.stack,i&&(l.msg=`${i}
|
|
3
|
+
${l.msg}`));for(let p of FT)a[p]instanceof Error&&(l[p]={message:a[p].message,stack:a[p].stack,name:a[p].name,type:a[p].type,cause:a[p].cause,...a[p]});Object.keys(l).length>0&&(i&&!d&&(l.msg=i),m.text=l),this.logger.addLog(m),s(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Re.CoralogixLogger.configure(t),Br.options=t}}});var Ya={};$(Ya,{getLogger:()=>x,setExecutionId:()=>za,setProjectId:()=>Ka,setProxyUri:()=>Ja});function BT(){let r=[],e=()=>Promise.resolve();if(!De){let{CoralogixTransport:t}=(Ga(),ve(Ha));t.configure(ad);let s=new t({category:"ROOT"});r.push(s),e=()=>s.waitForFlush()}return Jp&&r.push(new bt.transports.Console({format:bt.format.combine(bt.format.colorize(),bt.format.simple())})),[r,e]}function za(r){Va=r}function Ka(r){cd=r}function Ja(r){if(De||!r)return;let{CoralogixTransport:e}=(Ga(),ve(Ha));e.configure({...ad,proxyUri:r})}function od(r){return{projectId:cd,time:new Date().toISOString(),...Va&&!r&&{executionId:Va}}}function x(r){return new qa(VT.child({category:r}))}var id,bt,UT,jT,ad,$T,WT,HT,GT,VT,Va,cd,qa,U=T(()=>{"use strict";id=E(require("os")),bt=E(require("winston"));pe();j();UT=id.hostname(),jT=ot(),ad={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};[$T,WT]=BT(),HT=Yp?"debug":"info",GT={release:Boolean(!0),branch:"production"},VT=bt.createLogger({levels:bt.config.syslog.levels,level:HT,transports:$T,defaultMeta:{name:"runner",hostname:UT,nodeVersion:process.version,runnerVersion:jT,...GT}}),Va=null,cd=null;qa=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,s={}){let{executionId:n}=s;try{this._logger.log(e,Object.assign({meta:s,message:t},od(n)))}catch(o){try{this._logger.log("crit",Object.assign({message:`failed to log message ${o.message}, ${o.stack}`},od(n)))}catch{}}}waitForFlush(){return WT()}}});var Xa,Ie,$r,k,Wr,Gt,fr,Tt,to,te,Fs,wt,Hr,vt,ro,Gr,Vr,qr,Us,V=T(()=>{"use strict";Xa=require("p-retry"),Ie=class extends Error{constructor(t="aborted"){super(t);this.name="AbortError"}},$r=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},k=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Wr=class extends Error{constructor(t){super(t.orgStatusMessage||t.message);this.name="SeleniumError",this.errorType=t.type}},Gt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},fr=class extends Error{constructor(t,s){super(t);this.type=s}},Tt=class extends Xa.AbortError{},to=class extends Xa.AbortError{},te=class extends Error{},Fs=class extends Error{},wt=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Hr=class extends wt{constructor(){super(...arguments);this.name="GridConcurrencyError"}},vt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},ro=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Gr=class extends Error{},Vr=class extends Error{constructor(t){super();this.innerStack=t}},qr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Us=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Qa(r){return!!r&&(typeof r=="object"||typeof r=="function")&&typeof r.then=="function"&&typeof r.catch=="function"}function se(r){return new Promise(e=>{setTimeout(e,r)})}function Za(r,e){let t=new Promise((s,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([r,t])}function ne(r,e,t="Timeout Error"){Qn&&!ld&&(ld=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let s=new te(t);return e=Qn?Number(Qn)||6e5:e,Promise.race([r,se(e).then(()=>{throw s})])}async function ce(r,e,{concurrency:t}={}){if(t){ud||(ud=(await import("p-limit")).default);let s=ud(t);return await Promise.all(Array.from(r,(n,o)=>s(()=>e(n,o))))}return await Promise.all(Array.from(r,e))}function it(r){return new Promise((e,t)=>{r((s,n)=>s?t(s):e(n))})}var ld,ud,ec=T(()=>{"use strict";V();pe();ld=!1});var Bs,pd,qT,js,dd,zT,KT,md,fd=T(()=>{"use strict";Bs=E(require("lodash"));pe();pd=require("dns");U();ec();qT=x("http-request-counters"),js=!1,dd=async()=>{if(De)return!0;let r=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ce(r,t=>pd.promises.lookup(t)));return e||(js=!0),e}catch{return qT.error("network connectivity test failed"),js=!0,!1}},zT=Bs.throttle(dd,10*1e3),KT=60*1e3*15,md=()=>{let r={call:new Map,success:new Map,fail:new Map};function e(n,o){let i=n.get(o)||0;n.set(o,i+1),setTimeout(()=>{let a=n.get(o)||1;n.set(o,a-1)},KT)}function t(n,o=n.name){return async function(...i){e(r.call,o);try{let a=await n.call(null,...i);return e(r.success,o),a}catch(a){throw e(r.fail,o),js||zT(),a}}}async function s(){if(js||!await dd())return!1;let n=Bs.sum([...r.fail.values()]),o=Bs.sum([...r.call.values()]);return n<o*.1}return s.counters=r,t.counters=r,t.isNetworkHealthy=s,t.didNetworkConnectivityTestFail=()=>js,t}});var St={};$(St,{deleteFullRes:()=>ZT,deleteReq:()=>$s,didNetworkConnectivityTestFail:()=>cc,download:()=>ic,get:()=>Ot,getFullRes:()=>tw,getText:()=>nc,head:()=>rw,isNetworkHealthy:()=>ac,post:()=>Qe,postForm:()=>rc,postFullRes:()=>ew,put:()=>oc});function YT(){return global.caFileContent}function XT(r,e){let t=[];r.on("data",s=>{t.push(s)}),r.on("end",()=>{e(null,Buffer.concat(t))})}function QT(){return!Et.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(Et.default),global.proxyUri}function gr(r,e=!1){let t=YT();t&&r.ca(t);let s=!e&&QT();s&&r.proxy(s)}async function gd(r,e={},t={},s=zr){let n=Et.default.delete(r).send(e).timeout(s).set(t);return gr(n),await n}async function hd(r,e,t={},s=zr,n=0){let o=Et.default.post(r).send(e).timeout(s).set(t);gr(o),n&&o.retry(n);try{return await o}catch(i){throw i.url=r,i.originalRequestTimeout=s,i.additionalSetHeaders=t,i}}async function sc(r,e,t={},s=zr,{isBinary:n=!1,skipProxy:o=!1}={}){let i=Et.default.get(r).query(e||{}).timeout(s).set(t);return n&&i.buffer(!0),gr(i,o),await i}var Et,tc,Ge,zr,JT,Vt,$s,ZT,Qe,ew,rc,nc,Ot,tw,rw,oc,ic,ac,cc,at=T(()=>{"use strict";Et=E(require("superagent"));U();fd();tc=x("http-request"),Ge=md(),zr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,JT=6e4;Vt=(r,e,t)=>{throw tc.error(r,{...t,error:e}),e};$s=Ge(async(r,e,t,s)=>{try{let n=await gd(r,e,t,s);return n.type==="text/plain"?n.text:n.body}catch(n){return Vt("failed to delete request",n,{url:r})}});ZT=Ge(gd),Qe=Ge(async({url:r,body:e,headers:t,timeout:s,retry:n})=>{try{let o=await hd(r,e,t,s,n);return o.type==="text/plain"?o.text:o.body}catch(o){return Vt("failed to post request",o,{url:r})}});ew=Ge(hd),rc=Ge(async(r,e,t,s={},n=zr)=>{let o=Et.default.post(r).type("form").timeout(n).set(s);o.field(e),Object.keys(t).forEach(i=>{o.attach(i,t[i].buffer,t[i].fileName)}),gr(o);try{let i=await o;return i.type==="text/plain"?i.text:i.body}catch(i){return Vt("failed to post request",i,{url:r})}});nc=Ge(async(r,e,t)=>{try{return(await sc(r,e,t)).text}catch(s){return Vt("failed to getText request",s,{url:r,query:e})}}),Ot=Ge(async(r,e,t,s,n)=>{try{return(await sc(r,e,t,s,n)).body}catch(o){return Vt("failed to get request",o,{url:r,query:e})}}),tw=Ge((r,e,t,s)=>sc(r,e,t,s)),rw=Ge(async r=>{let e=Et.default.head(r).timeout(zr);gr(e);try{return await e}catch(t){return Vt("failed to head request",t,{url:r})}}),oc=Ge(async(r,e,t={},s=zr)=>{let n=Et.default.put(r).send(e).timeout(s).set(t);gr(n);try{return(await n).body}catch(o){return Vt("failed to put request",o,{url:r})}}),ic=Ge(async r=>{tc.info("start to download",{url:r});let e=Et.default.get(r).timeout(JT).buffer(!0).parse(XT);gr(e);try{let t=await e;return tc.info("finished to download",{url:r}),t}catch(t){return Vt("failed to download",t,{url:r})}}),ac=Ge.isNetworkHealthy,cc=Ge.didNetworkConnectivityTestFail});function ct(){let r;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?r=_t.resolve(__dirname,"../../"):r=_t.resolve(__dirname,""),r):process.cwd()}function so(r,e){return We(r)?e||_t.join(process.cwd(),r.replace(/^.*[\\/]/,"")):e||_t.basename(r)}function ot(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function nw(){try{return Gp.node}catch{return""}}async function oo(r,e,t=!0){let s=await Ve.promises.readdir(r,{withFileTypes:!0});await Ve.promises.mkdir(e,{recursive:t});for(let n of s){let o=_t.join(r,n.name),i=_t.join(e,n.name);n.isDirectory()?await oo(o,i):await Ve.promises.copyFile(o,i)}}async function ye(r){try{return await Ve.promises.access(r),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var _t,yd,bd,Ve,sw,hr,qe,Td,no,lc,Ze,uc,pc=T(()=>{"use strict";_t=E(require("path"));ja();Yn();yd=E(require("p-retry")),bd=E(require("decompress")),Ve=require("fs"),sw=3;hr=async r=>{let e=await Promise.resolve().then(()=>(at(),St));return(0,yd.default)(()=>e.download(r),{retries:sw,factor:1})},qe=async(r,e)=>{let t=await hr(r);return Ve.promises.writeFile(e,t.body)},Td=async(r,e)=>new Promise((t,s)=>{try{let n=(0,Ve.createWriteStream)(e);(0,Ve.createReadStream)(r).pipe(n),n.on("finish",()=>{n.close(()=>t())})}catch(n){s(n)}});no=async(r,e)=>{let t=so(r,e);return We(r)?qe(r,t):Td(r,t)},lc=async r=>We(r)?hr(r):Ve.promises.readFile(r),Ze=async(r,e)=>await(0,bd.default)(r,e),uc=r=>(0,Ve.statSync)(r).size/1e6});var Dt={};$(Dt,{APPIUM_SESSION_MESSAGE:()=>hc,CLI_MODE:()=>Y,MOBILE_APP_SOURCE:()=>io,MOBILE_RUN_SKIP_REASON:()=>gc,gridMessages:()=>Kr,gridTypes:()=>W,mobileWeb:()=>mc,runnerStatus:()=>dc,runnerTestStatus:()=>de,sessionType:()=>Lt,socketEventTypes:()=>et,stepResult:()=>Hs,test:()=>fc,testRunStatus:()=>Ws,testStatus:()=>ze,timeoutMessages:()=>Be});var Be,Ws,dc,de,ze,Kr,mc,fc,et,Y,Lt,W,Hs,io,gc,hc,ie=T(()=>{"use strict";Be={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Ws={COMPLETED:"completed",RUNNING:"running"},dc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},de={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},ze={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},Kr={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},mc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},fc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},et={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},Y={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},Lt={CODELESS:"codeless",CODEFUL:"codeful"},W={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin"},Hs={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"},io={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},gc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build",MISSING_BROWSERSTACK_APP_ID:"missing-browserstack-app-id"},hc={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"}});function yr(r){return r.files.length>0?Lt.CODEFUL:Lt.CODELESS}function Gs(r,e){var t,s,n;return((t=r.testConfigNames)!=null&&t.length||(s=r.testConfigIds)!=null&&s.length||r.testPlan.length||r.testPlanIds.length)&&!r.browser?[...new Set(e.map(o=>{var i;return(i=o.runConfig)==null?void 0:i.browserValue}))]:[(n=r.browser)==null?void 0:n.toLowerCase()]}function ow(){let{argv:r}=process;if(r.includes("--remoteRunId"))return{remoteRunId:r[r.indexOf("--remoteRunId")+1],projectId:r[r.indexOf("--project")+1],token:r[r.indexOf("--token")+1]}}var Vs,wd,Ke,iw,aw,cw,lw,uw,pw,yc,vd=T(()=>{"use strict";ie();Vs=r=>{var e,t;return Boolean(((e=r.testPlan)==null?void 0:e.length)||((t=r.testPlanIds)==null?void 0:t.length))},wd=r=>Boolean(r.resultId&&r.source==="remote-run"),Ke=(r,e)=>r.testStatus===ze.QUARANTINE&&!wd(e)&&!e.runQuarantinedTests;iw=r=>Boolean(r.initCodimMode),aw=r=>Boolean(r.loginMode),cw=r=>Boolean(r.tunnelOnlyMode),lw=r=>Boolean(r.createPrefechedData),uw=r=>Boolean(r.installLazyDepsMode),pw=r=>Boolean(r.agentMode),yc=(r,e)=>{r.forEach((t,s)=>{e.has(t)&&(r[s]=`--${t}`)})}});function ao(r){let e=bc.default.duration(r);return`${e.hours()}:${e.minutes()}:${e.seconds()}.${e.milliseconds()}`}function Tc(r){return bc.default.duration(r).asSeconds()}var bc,Ed=T(()=>{"use strict";bc=E(require("moment"))});var qs,Jr,Yr,Sd=T(()=>{"use strict";qs=r=>!(!r||"fileName"in r),Jr=r=>r&&"fileName"in r?r.fileName.endsWith(".app"):!1,Yr=r=>{var e,t;return((e=r.projectData)==null?void 0:e.type)==="ios"||((t=r.projectData)==null?void 0:t.type)==="android"}});function wc(r=4e3){let e=process.memoryUsage(),t=s=>Math.round(s/1024/1024*100)/100;return{isOverThreshold:t(e.rss)>r,rss:`${t(e.rss)} MB -> Resident Set Size - total memory allocated for the process execution`,heapTotal:`${t(e.heapTotal)} MB -> total size of the allocated heap`,heapUsed:`${t(e.heapUsed)} MB -> actual memory used during the execution`,external:`${t(e.external)} MB -> V8 external memory`}}var Rd=T(()=>{"use strict"});var q={};$(q,{TESTIM_BROWSER_DIR:()=>Nt,buildBasicHeader:()=>Ua,calcPercentile:()=>uo,copy:()=>Td,copyDir:()=>oo,delay:()=>se,doesPathExist:()=>ye,download:()=>hr,downloadAndSave:()=>qe,extractElementId:()=>Me,getArgsOnRemoteRunFailure:()=>ow,getBrowserInfo:()=>Ks,getCdpAddressForHost:()=>wr,getCliLocation:()=>ct,getDuration:()=>ao,getDurationSec:()=>Tc,getEnginesVersion:()=>nw,getEnvironmentGitBranch:()=>Tr,getLocalFileSizeInMB:()=>uc,getMemorySnapshot:()=>wc,getPlanType:()=>lo,getRunConfigByBrowserName:()=>Js,getRunnerVersion:()=>ot,getSessionType:()=>yr,getSource:()=>no,getSourceAsBuffer:()=>lc,getSourcePath:()=>so,getTestUrl:()=>nt,getUniqBrowsers:()=>Gs,groupTestsByRetries:()=>Ec,guid:()=>J,hasTestPlanFlag:()=>Vs,isAgentMode:()=>pw,isAppForVirtualIosDevice:()=>Jr,isAppFromDevice:()=>qs,isCreatePrefetchedDataMode:()=>lw,isInitCodimMode:()=>iw,isInstallLazyDepsMode:()=>uw,isLoginMode:()=>aw,isMobileProject:()=>Yr,isPromise:()=>Qa,isQuarantineAndNotRemoteRun:()=>Ke,isRemoteRun:()=>wd,isTunnelOnlyMode:()=>cw,isURL:()=>We,promiseAbort:()=>Za,promiseFromCallback:()=>it,promiseMap:()=>ce,promiseTimeout:()=>ne,removePropertyFromObject:()=>co,replaceArgsWithNoDashes:()=>yc,unzipFile:()=>Ze});function Ks(r){return r=r.toLowerCase(),vc.find(e=>e.browserValue===r)}function Js(r,e,t){r=r.toLowerCase();let s=vc.find(o=>o.browserName.toLowerCase()===r||r.includes(o.synonyms))||vc[0],n=zs.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=zs.find(o=>o.sl.platform===e.platform):e.platformName&&(n=zs.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=zs.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=zs.find(o=>o.bs.platform===t.platform))),br.merge(s,n)}function Tr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function co(r,e,t){for(let s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t(s,e)?delete r[s]:typeof r[s]=="object"&&co(r[s],e,t))}function Me(r){return r.ELEMENT||r[Ht]}function lo(r){r||(r={});let e=Date.now(),t=r.expireAt||r.expireAT;return r.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Ec(r=[]){return br.chain(r).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let s=br.orderBy(t,o=>typeof o.retryCount=="number"?o.retryCount:1),n=br.chain(s).last().cloneDeep().value();return n&&(n.retryTestResults=s,e.push(n)),e},[]).compact().value()}async function wr(r,e){let t=await Promise.resolve().then(()=>(at(),St));try{return(await t.get(`http://${r}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var Id,br,xd,dw,Nt,zs,vc,uo,j=T(()=>{"use strict";Id=E(require("os")),br=E(require("lodash")),xd=E(require("path"));Fr();pc();vd();Ed();ja();ec();Sd();Rd();dw=Id.homedir(),Nt=xd.join(dw,".testim-browser-profile"),zs=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{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 Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14"},sl:{platform:"macOS 11",safari_version:"14"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13"},sl:{platform:"macOS 10.15",safari_version:"13"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12"},sl:{platform:"macOS 10.14",safari_version:"12"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11"},sl:{platform:"macOS 10.13",safari_version:"11"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10"},sl:{platform:"macOS 10.12",safari_version:"10.0"}},{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:"9.0"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"8.0"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"7.0"}},{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:"6.0"}},{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"}}],vc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:"94"},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",bs:{browser:"Edge",browser_version:"18"},sl:{browserName:"MicrosoftEdge",version:"18.17763"},browserValue:"edge",eol:!0},{browserName:"Edge Chromium",bs:{browser:"Edge",browser_version:"94"},sl:{browserName:"MicrosoftEdge",version:"94"},synonyms:["edge-chromium"],browserValue:"edge-chromium",seleniumName:"MicrosoftEdge"},{browserName:"Internet Explorer 11",bs:{browser:"IE",browser_version:"11"},sl:{browserName:"internet explorer",version:"11.0"},synonyms:["ie11"],browserValue:"ie11",eol:!0},{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"}];uo=(r,e)=>{if(r.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(r=[...r].sort((s,n)=>s-n),e<=0)return r[0];if(e>=100)return r.at(-1);let t=Math.ceil(r.length*(e/100))-1;return r[t]}});var Sc={};$(Sc,{$schema:()=>mw,default:()=>bw,definitions:()=>fw,properties:()=>yw,required:()=>hw,type:()=>gw});var mw,fw,gw,hw,yw,bw,kd=T(()=>{mw="http://json-schema.org/draft-07/schema#",fw={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}}}},gw="object",hw=["entries"],yw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},bw={$schema:mw,definitions:fw,type:gw,required:hw,properties:yw}});async function Dd(){try{return await ne(po.promises.readFile(ho()).then(async r=>{let e=await Ld;return vw(e,r)}),3e4)}catch{return{}}}function vw(r,e){let t=e.slice(0,16),s=e.slice(16),n=Buffer.from(r),o=Qr.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),i=o.update(s);return JSON.parse(Buffer.concat([i,o.final()]))}function lt(r,e,t=Tw,s=void 0){return async()=>{if(!Ad)return await r();let n=e;s&&(e+=JSON.stringify(s));let o=await Ew(e);if(o)return Ys.debug("cache hit:",{fnName:e}),o;if(Ys.debug("cache miss:",{fnName:e}),!Od)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let i=await r();return i&&await Sw(e,i,t),i}}async function Ew(r){let t=(await yo)[r];if(!t)return;let{value:s,expiry:n}=t;if(!(n<Date.now())&&s)return s}async function Sw(r,e,t){if(Rc)throw Ys.error("calling set after waitForSave is not allowed",{key:r,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let s=await yo;s[r]={value:e,expiry:Date.now()+t},_d=new Promise(n=>{go=n}),ww(s)}catch{Ys.error("failed updating cache")}}async function Nd(){let r=await yo;Object.keys(r).forEach(e=>{delete r[e]})}function Md(r){Ad=r}function Rw(r=!0){Od=r}async function Fd(){try{return Rc=!0,await _d}finally{Rc=!1}}function Ud(r){fo=r,yo=Dd()}var po,mo,Qr,Pd,Ys,fo,Cd,go,Ad,Od,Rc,_d,Ld,Tw,ho,yo,ww,jd,Bd,QI,$d,qt=T(()=>{"use strict";po=E(require("fs")),mo=E(require("path")),Qr=E(require("crypto"));j();Pd=require("lodash");U();Ys=x("local cache"),fo=mo.resolve(ct(),"testim-cache"),Ad=!0,Od=!0,Rc=!1,_d=new Promise(r=>{go=r}),Ld=new Promise(r=>{Cd=r}),Tw=1e3*60*60*3,ho=()=>mo.resolve(mo.resolve(fo,"testim.cache"));yo=Dd(),ww=(0,Pd.debounce)(async r=>{let e;try{let t=await Ld,s=Qr.randomBytes(16),n=JSON.stringify(r),o=Buffer.from(t),i=Qr.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),s),a=Buffer.concat([s,i.update(n),i.final()]);await ye(fo)||await po.promises.mkdir(fo,{recursive:!0}),await po.promises.writeFile(ho(),a)}catch(t){Ys.error("failed saving cache",{err:t}),e=t}go(e?{success:!1,error:e}:{success:!0})},200);jd=Cd,Bd=Md.bind(void 0,!1),QI=Md.bind(void 0,!0),$d=()=>Rw(!1)});function bo(){return{cliLocation:ct(),userInfo:Zr.userInfo(),platform:Zr.platform(),release:Zr.release()}}var Zr,Ic=T(()=>{"use strict";Zr=E(require("os"));j()});function Iw(r){try{return To.resolve(To.dirname(require.resolve(`${r}/package.json`)),require(`${r}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(r);throw e}}function zt(r){let e=Iw(r);return require(e)}var To,Xs=T(()=>{"use strict";To=E(require("path"))});async function Vd(r){return(await Hd(`npm view ${r} version`)).stdout.trim()}function kc(r){try{return zt(r)}catch{return!1}}function qd(r,e){return require(es.join(r,`./node_modules/${e}/package.json`)).version}async function vo(r,e,t){function s(c){let m=/EACCES[^']+'(.+)'/.exec(c.stderr);return m===null?!1:m[1]}function n(c){return/The "to" argument must be of type string./.exec(c.stderr)}let o=es.join(r,"npm-shrinkwrap.json"),i=es.join(r,"npm-shrinkwrap-dummy.json"),a=!1;try{try{await ye(o)&&(await xc.promises.rename(o,i),a=!0)}catch{}return await Hd(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:r}).catch(c=>{let l=s(c),m=n(c);throw l||m?(Gd.info("Failed to install package due to insufficient write access",{...bo(),package:e,path:l||r}),console.error(`
|
|
4
4
|
|
|
5
5
|
Testim failed installing the package ${e} 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 ${l||r}
|
|
8
8
|
|
|
9
|
-
`),new qr(l||r)):c})}finally{if(a)try{await
|
|
10
|
-
stdout: ${c} stderr: ${l}`}
|
|
9
|
+
`),new qr(l||r)):c})}finally{if(a)try{await xc.promises.rename(i,o)}catch{}}}function zd(r,e,t,s){return new Promise((n,o)=>{let i=t?["--proxy",t]:[],a=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},c="",l="",m="--no-save --no-package-lock --no-prune --prefer-offline --no-audit --progress=false".split(" "),d=(0,wo.spawn)("node",[xw,"i","--prefix",r,...m,...e,...i],a);d.stderr.pipe(process.stderr),d.stdout.pipe(process.stdout),d.stdout.on("data",p=>{c+=p}),d.stderr.on("data",p=>{l+=p}),d.on("close",p=>{var g;if(p){let f;try{let h=(g=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(l))==null?void 0:g[1];f=`404 Not Found - GET https://registry.npmjs.org/${h==null?void 0:h.split("@")[0]} - Not found`}catch{f=`Npm Install closed with exit code ${p}
|
|
10
|
+
stdout: ${c} stderr: ${l}`}Gd.debug(`Npm Install closed with exit code ${p}`,{message:f}),o(new vt(f))}else n(c)}),setTimeout(()=>{try{d.kill()}finally{o(new te)}},s)})}var xc,es,Wd,wo,Hd,Gd,xw,Qs=T(()=>{"use strict";xc=E(require("fs")),es=E(require("path"));j();Wd=require("util"),wo=require("child_process");U();Ic();Xs();V();Hd=(0,Wd.promisify)(wo.exec),Gd=x("cli-service");xw=es.resolve(require.resolve("npm").replace("index.js",""),"bin","npm-cli.js")});var Qd={};$(Qd,{install:()=>Pw,isReady:()=>Aw,start:()=>Cw});var Kd,Jd,Yd,Xd,Pc,kw,Pw,Cw,Aw,Zd=T(()=>{"use strict";Kd=E(require("fkill")),Jd=E(require("p-retry"));Qs();at();j();Xs();Yd="chromedriver",Xd=9515,Pc=`http://localhost:${Xd}/wd/hub`,kw=["--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],Pw=async()=>{await vo(ct(),`${Yd} --detect_chromedriver_version`)},Cw=async()=>{process.env.NODE_OPTIONS="",await(0,Kd.default)(`:${Xd}`,{silent:!0}),await zt(Yd).start(kw,!0)},Aw=async({chromeBinaryLocation:r})=>{await(0,Jd.default)(async()=>{var n;let e=await Ot(`${Pc}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...r&&{binary:r}},s=await Qe({url:`${Pc}/session`,body:{desiredCapabilities:{browserName:"chrome",chromeOptions:t}},headers:{"Content-Type":"application/json"}});if(!s||s.status!==0||!s.sessionId)throw new Error("create session failed");await $s(`${Pc}/session/${s.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var Zs={};$(Zs,{getSessionPlayerFolder:()=>_c,prepareChromeDriver:()=>Er,prepareCustomExtension:()=>Ac,prepareExtension:()=>Oc,preparePlayer:()=>Sr});async function Ac(r,e=!1){if(!r)return;if(We(r)){let n=ts.join(process.cwd(),r.replace(/^.*[\\/]/,""));if(await Ow(r)>Cc&&!e)throw new k(em);return await qe(r,n),n}let t=ts.resolve(r);if(!rm.existsSync(t))throw new k(`Failed to find custom extension in location: ${t}`);if(uc(t)>Cc&&!e)throw new k(em);return t}async function Ow(r){let e=(at(),ve(St));try{let s=(await e.head(r)).headers["content-length"];return(s?parseInt(s,10):0)/1e6}catch(t){throw So.warn("failed to download custom extension",{err:t}),new k(`Failed to download custom extension from location: ${r}`)}}function Oc(r){So.info("prepare extension",{locations:r});let e=r.map(t=>({location:t,path:so(t)}));return lt(()=>ce(e,({location:t,path:s})=>no(t,s)),"prepareExtension",nm,e)()}async function Er(r={},e={},t=!1){let n=require("ora")("Starting Driver").start(),o=await Promise.resolve().then(()=>(Zd(),Qd));try{await o.install(),await o.start(),t||await o.isReady(e),n.succeed("Chrome Driver initiated successfully")}catch(i){let a="Failed to initiate Chrome Driver";throw i instanceof qr||(So.error(a,{...r,...bo(),error:(0,sm.serializeError)(i)}),console.log(`
|
|
11
11
|
1. If you don't have Chrome, please install it from https://www.google.com/chrome.
|
|
12
12
|
2. If Chrome is installed, please verify it's binary directory:
|
|
13
13
|
- installed where chromedriver expects it (see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver#requirements).
|
|
14
14
|
- exists in your PATH environment variables.
|
|
15
15
|
3. Try adding --chrome-binary-location flag to Testim CLI specifying the exact location of chrome binary in your computer (e.g on Windows "C:/Program Files/Google/Chrome/Application/chrome.exe").
|
|
16
|
-
4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),i}}async function Cw(){let r=`${jr}/extension/sessionPlayer_LATEST_RELEASE`;return(await hr(r)).body.toString("utf8")}async function Aw(r,e){if(!We(r)||We(r)&&e||De)return r;let t=await Cw();return`${r}-${t}`}function Oc(){let r=ct();return ts.resolve(r,"testim-bin")}function Ow(){let r=Oc();return ts.resolve(r,"sessionPlayer.zip")}async function nm(r,e,t=!1){try{return await no(r,e),await Ze(e,Oc())}catch(s){if(t)throw s;return await nm(r,e,!0)}}async function Sr(r,e){So.info("prepare player",{location:r,canary:e});let t=Ow();return lt(async()=>{let s=await Aw(r,e);return await nm(s,t),{}},"preparePlayer",sm,[r,e,t])()}var em,tm,ts,rm,So,sm,Pc,Zd,rs=T(()=>{"use strict";em=E(require("ms")),tm=E(require("fs")),ts=E(require("path"));pe();qt();rm=require("serialize-error");U();Rc();V();j();So=x("prepare runner and testim start"),sm=(0,em.default)("0.5 day"),Pc=16,Zd=`The size of the custom extension is more than ${Pc}MB`});function _w(){let r=en.type().toLowerCase();return r==="darwin"?en.arch()==="arm"?"mac_arm":"mac":r==="windows_nt"?en.arch()==="x64"?"win64":"win32":"linux"}async function Io(){let r=_w(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(r in t))throw new k(`Unsupported platform: ${r}`);let s=parseInt(tn,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:s,win64:s},o={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},i=`${e}/${t[r]}/${tn}/${n[r]}.zip`,a=Ro.join(_c,n[r]),c=`${a}.zip`,l=Ro.join(a,o[r]);if(await ye(l))return l;if(!await ye(c)){let m=(0,Lc.default)("Downloading Chromium").start();try{await om.promises.mkdir(_c),await qe(i,c)}catch(d){let g=`Failed to download Chromium: ${d.message}`;throw m.fail(g),new Error(g)}m.succeed()}let p=(0,Lc.default)("Extracting Chromium").start();try{await Ze(c,_c)}catch(m){let d=`Failed to extract Chromium: ${m.message}`;throw p.fail(d),new Error(d)}return p.succeed(),l}var om,en,Ro,Lc,tn,_c,Dc=T(()=>{"use strict";om=E(require("fs")),en=E(require("os")),Ro=E(require("path")),Lc=E(require("ora"));V();j();tn="1000968",_c=Ro.join(Nt,`chrome-${tn}`)});async function am(r,e){return ko=r,Uc=e,await Nc()}function cm(r,e,t){tt=r.token,ko=e,Uc=t,sn=jc(tt),xo=r.refreshToken,Mc=r.ngrokToken,Fc=r.isNgrokWhitelisted}function Lw(r=ko,e=Uc){return lt(()=>(rn.info("request to get cli token from server"),Qe({url:`${me}/auth/token`,body:{projectId:r,token:e}})),"getTokenV3",im*10,{projectId:r,token:e})()}async function Dw(){return rn.info("request to refresh JWT cli token from server"),tt=(await Qe({url:`${me}/auth/refreshToken`,body:{token:tt,refreshToken:xo}})).token,sn=jc(tt),tt}async function Nc(){try{let r=await Lw();return rn.info("successfully get cli token from server"),tt=r.token,sn=jc(tt),xo=r.refreshToken,Mc=r.ngrokToken,Fc=r.isNgrokWhitelisted,tt}catch(r){throw r.message.includes("Unauthorized")?new k("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."):(rn.error(`While trying to retrieve CLI token. caught error: ${r}`,{projectId:ko}),new k(`While trying to retrieve CLI token, caught error: ${r}`))}}function jc(r){return require("jsonwebtoken").decode(r).exp*1e3}async function Kt(){if(!sn)return Nc();if(sn<Date.now()+4*im)try{return await Dw()}catch(r){return rn.error("failed to refresh token, executing fallback",r),Nc()}return tt}function Po(){return xo}function Mt(){return tt?{uid:require("jsonwebtoken").decode(tt).id,ngrokToken:Mc,isNgrokWhitelisted:Fc}:{}}var rn,tt,sn,xo,Mc,Fc,ko,Uc,im,Rt=T(()=>{"use strict";pe();at();qt();V();U();rn=x("testim-custom-token"),ko=null,Uc=null,im=5*60*1e3});var lm={};$(lm,{isCi:()=>ss});var ss,Co=T(()=>{"use strict";ss=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var ke={};$(ke,{addTestRetry:()=>ul,clearTestResult:()=>al,deleteCloudflareTunnel:()=>fl,fetchLambdatestConfig:()=>nl,forceUpdateCloudflareTunnelRoutes:()=>ml,getAllGrids:()=>sl,getAppDetails:()=>Jc,getApplitoolsIntegrationData:()=>pl,getCloudflareTunnel:()=>dl,getEditorUrl:()=>$w,getGridById:()=>_o,getGridByName:()=>tl,getHybridGridProvider:()=>el,getLabFeaturesByProjectId:()=>ol,getMobileDevicesFromGrid:()=>hl,getRealData:()=>on,getS3Artifact:()=>nn,getS3ArtifactText:()=>$c,getSuiteTestList:()=>Kc,getTestPlan:()=>Bw,getTestPlanTestList:()=>zc,getTestResults:()=>Rr,getUsageForCurrentBillingPeriod:()=>Yc,initializeUserWithAuth:()=>rl,isTestResultCompleted:()=>Xc,keepAliveGrid:()=>Qc,loadSfdcCredential:()=>Wc,loadTest:()=>Hc,releaseGridSlot:()=>Zc,reportExecutionFinished:()=>Oo,reportExecutionStarted:()=>qc,saveRemoteStep:()=>cl,saveTestPlanResult:()=>Gc,updateExecutionTests:()=>Vc,updateRemoteRunFailure:()=>gl,updateTestDataArtifact:()=>Lo,updateTestResult:()=>il,updateTestStatus:()=>os,uploadRunDataArtifact:()=>ll});async function ns(){let r=await Kt();if(!r)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${r}`}}async function rt({url:r,body:e,headers:t={},timeout:s,retry:n}){let o=await ns(),i=Object.assign({},t,o);return Qe({url:`${me}${r||""}`,body:e,headers:i,timeout:s,retry:n})}async function Fw(r,e,t,s={},n=void 0){let o=await ns(),i=Object.assign({},s,o);return await tc(`${me}${r||""}`,e,t,i,n)}async function Ao(r,e){let t=await ns();return await nc(`${me}${r||""}`,e,t)}async function Uw(r,e){let t=await ns();return await $s(`${me}${r||""}`,e,t)}async function jw(r,e){let t=await ns();return await sc(`${me}${r||""}`,e||void 0,t)}async function xe(r,e,t,s){let n=await ns();return await Ot(`${me}${r||""}`,e||void 0,n,s,t)}function nn(r,e){return(0,oe.default)(()=>xe(`/storage${r}`,null,{isBinary:!0},e),{retries:ae,factor:1})}function $c(r){return(0,oe.default)(()=>jw(`/storage${r}`))}async function Bw(r,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,oe.default)(()=>xe("/testPlan",{projectId:r,name:e.join(",")}),{retries:ae,factor:1})).map(({testConfigIds:n,beforeAllLabels:o,testLabels:i,afterAllLabels:a,...c})=>Object.assign(c,{testConfigIds:t(n),beforeAllLabels:t(o),testLabels:t(i),afterAllLabels:t(a)}))}async function Wc({branch:r,projectId:e}){let t=await(0,oe.default)(()=>xe(`/branch/branchData/${r}`,{projectId:e}),{retries:ae,factor:1});return t==null?void 0:t.sfdcCredential}function Hc({testId:r,branch:e,projectId:t,skipSharedSteps:s=!1,useBranchMap:n=!0}){return(0,oe.default)(()=>xe(`/test/${r}`,{projectId:t,branch:e,skipSharedSteps:s,useBranchMap:n}),{retries:ae,factor:1})}function Gc(r,e,t){return(0,oe.default)(()=>rt({url:"/testPlan/result",body:{projectId:r,testPlanId:e,result:t}}),{retries:ae,factor:1})}function os(r,e,t,s,n,o,i=ae){return(0,oe.default)(()=>Ao("/result/run/test",{runId:e,testId:t,resultId:s,status:n,projectId:r,runnerVersion:Nw,...o}),{retries:i,factor:1})}function Vc(r,e,t,s,n,o,i,a){return(0,oe.default)(()=>Ao("/result/run/tests",{runId:r,runnerStatuses:e,status:t,reason:s,success:n,startTime:o,endTime:i,projectId:a}),{retries:ae,factor:1})}async function qc({executionId:r,projectId:e,labels:t,startTime:s,executions:n,config:o,resultLabels:i,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:p}){let{isCi:m}=await Promise.resolve().then(()=>(Co(),lm));return rt({timeout:9e4,url:"/result/run",body:{runId:r,projectId:e,labels:t,startTime:s,execution:n,status:"RUNNING",config:o,resultLabels:i,remoteRunId:a,intersections:p,metadata:{isCiRun:m,localRunUserId:c,isLocalRun:l}},retry:3})}function Oo(r,e,t,s,n={},o=void 0,i=void 0){let a=Date.now();return(0,oe.default)(()=>Ao("/result/run",{runId:e,projectId:t,endTime:a,status:r,success:s,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:ae,factor:1})}async function zc(r,e,t,s,n){return(0,oe.default)(()=>rt({url:"/testPlan/list",body:{projectId:r,names:e,planIds:t,branch:s,intersections:n},timeout:12e4}),{retries:ae,factor:1})}function Kc({projectId:r,labels:e,testIds:t,testNames:s,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:p}){return(0,oe.default)(()=>rt({url:"/suite/v2/list",body:{projectId:r,labels:e,testIds:t,testNames:s,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:p}}),{retries:ae,factor:1})}async function Jc({appId:r,projectId:e}){try{return await(0,oe.default)(()=>xe(`/mobile-app/app/${r}?projectId=${e}`),{retries:ae,factor:1})}catch(t){Ut.error("failed getting application details",{appId:r,error:t});return}}async function Yc(r){try{return await(0,oe.default)(()=>xe(`/plan/project/${r}/usage-current-billing-period`),{retries:ae,factor:1})}catch(e){Ut.error("failed getting usage for current billing period",{projectId:r,error:e});return}}function Xc(r,e,t){return(0,oe.default)(()=>xe(`/result/${r}/isComplete`,{projectId:e,testRetryKey:t}),{retries:ae,factor:1})}function Rr(r,e,t,s){return(0,oe.default)(()=>xe(`/test/v2/${r}/result/${e}`,{projectId:t,branch:s}),{retries:ae,factor:1})}function Qc(r,e){return rt({url:`/grid/keep-alive?reqId=${J()}`,body:{projectId:r,slots:e},timeout:1e4})}function Zc(r,e,t,s,n){return rt({url:`/grid/release?reqId=${J()}`,body:{companyId:r,projectId:e,slotId:t,gridId:s,browser:n}})}function el(r){return rt({url:"/grid/hybrid/provider",body:r})}function tl(r,e,t,s,n){return(0,oe.default)(()=>xe("/grid/name",{companyId:r,projectId:e,name:t,browser:s,executionId:n,reqId:J()}),{retries:ae,factor:1})}function _o(r,e,t,s,n){return(0,oe.default)(()=>xe(`/grid/${t}`,{companyId:r,projectId:e,browser:s,executionId:n,reqId:J()}),{retries:ae,factor:1})}async function rl({projectId:r,token:e,branchName:t,lightweightMode:s,localGrid:n}){var o,i;try{return await(0,oe.default)(()=>Qe({url:`${me}/executions/initialize`,body:{projectId:r,token:e,branchName:t||"master",lightweightMode:s,localGrid:n}}),{retries:ae,factor:1})}catch(a){throw Ut.error("error initializing info from server",a),(o=a==null?void 0:a.message)!=null&&o.includes("Bad Request")?new k("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."):(i=a==null?void 0:a.code)!=null&&i.includes("ENOTFOUND")?new k("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):a}}async function $w(){if(Ur)return{editorUrl:Ur};try{return await(0,oe.default)(()=>xe("/system-info/editor-url"),{retries:ae,onFailedAttempt:r=>{if(r.attemptNumber>=ae)throw r},factor:1})}catch{return Ut.error("cannot retrieve editor-url from server"),{editorUrl:"https://app.testim.io"}}}function sl(r){return(0,oe.default)(()=>xe("/grid",{companyId:r}),{retries:ae,factor:1})}function on(r,e,t){return(0,oe.default)(()=>xe(`/real-data/${e}?${t}&projectId=${r}`),{retries:ae,factor:1})}function il(r,e,t,s,n){return(0,oe.default)(()=>rt({url:"/result/test",body:{projectId:r,resultId:e,testId:t,testResult:s,remoteRunId:n}}),{retries:ae,factor:1})}function al(r,e,t,s){return(0,oe.default)(()=>rt({url:"/result/test/clear",body:{projectId:r,resultId:e,testId:t,testResult:s}}),{retries:ae,factor:1})}function cl(r,e,t,s){return(0,oe.default)(()=>rt({url:"/remoteStep",body:{projectId:r,resultId:e,stepId:t,remoteStep:s}}),{retries:ae,factor:1})}function Ww(r){return r.startsWith("/")?r:`/${r}`}function Hw(r,e,t){let s=Ww(r);return t&&(s=`/${t}${s}`),e&&(s=`/${e}${s}`),s}async function pm(r,e,t,s,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${J()}${i||""}`,c=`${e}/${t}/${a}`,l=Hw(c,"test-result-artifacts",r),p=Buffer.from(um.gzip(s,{level:3})),m={file:{fileName:a,buffer:p}};return await(0,oe.default)(()=>Fw(`/storage${l}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:ae,factor:1}),l}function ul({projectId:r,runId:e,testId:t,newResultId:s,originalTestResultId:n,previousTestResultId:o,testResult:i}){return(0,oe.default)(()=>rt({url:"/result/test/retry",body:{projectId:r,newResultId:s,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:ae,factor:1})}async function pl(r){try{return await xe(`/integration/applitools/v3/connected?projectId=${r}`)}catch(e){return Ut.warn("could'nt get applitools integration data.",{err:e}),{}}}async function dl(r,e){try{return await Ao("/tunnel",{companyId:r,routes:e})}catch(t){return Ut.warn("could'nt get tunnel.",{err:t}),{}}}async function ml(r,e){try{return await rt({url:`/tunnel/${e}`,body:{companyId:r}})}catch(t){Ut.warn("could'nt get tunnel.",{err:t});return}}async function fl(r,e){try{return await Uw(`/tunnel/${e}`,{companyId:r})}catch(t){Ut.warn("could'nt get tunnel.",{err:t});return}}function gl(r){return Qe({url:`${me}/result/remoteRunFailure`,body:r})}async function hl({projectId:r,projectType:e,gridId:t,companyId:s,selectors:n}){let o=`${Mw}/mobileDevices/${t}/${s}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await(0,oe.default)(()=>xe(o,{projectId:r}),{retries:ae,factor:1})}catch(i){return Ut.warn("could'nt get devices from headspin grid.",{err:i}),null}}var Jt,um,oe,Bc,Nw,Ut,ae,Mw,nl,ol,ll,Lo,be=T(()=>{"use strict";Jt=E(require("lodash")),um=E(require("pako"));j();pe();ie();at();Rt();oe=E(require("p-retry")),Bc=E(require("object-hash"));V();U();Nw=ot(),Ut=x("testim service api"),ae=3,Mw="/grid";nl=async()=>(0,oe.default)(()=>xe("/grid/lt/config"),{retries:ae,factor:1}),ol=async r=>(0,oe.default)(()=>xe(`/labFeature/v2/project/${r}`),{retries:ae,factor:1});ll=Jt.memoize(async(r,e,t,s)=>{if(!Jt.isEmpty(s))return await pm(r,e,t,JSON.stringify(s),"test-run-data","application/json")},(r,e,t,s)=>`${(0,Bc.default)(s)}:${e}:${t}`),Lo=Jt.memoize(async(r,e,t,s,n)=>!s||Jt.isEmpty(s)?void 0:await pm(r,e,t,JSON.stringify((()=>{let i=Jt.clone(s);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(c=>{i[c]&&Object.assign(i,{[c]:mc.HIDDEN_PARAM})})}return i})()),"test-test-data","application/json"),(r,e,t,s)=>`${(0,Bc.default)(s)}:${e}:${t}`)});var Ir={};$(Ir,{getSessionPlayer:()=>re,options:()=>bl});var Do,bl,yl,re,Ee=T(()=>{"use strict";Do=require("path"),bl={playerPath:void 0},re=()=>{if(yl)return yl;let r=(Le(),ve(_e));r.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(rs(),ve(Zs)),t=e(),s=bl.playerPath?(0,Do.resolve)(bl.playerPath,"src/background/sessionPlayerInit.ts"):(0,Do.join)(t,"sessionPlayer.js"),n=require(s);return r.log("getSessionPlayerRequire end"),yl=n,n}});function qw(r){process.nextTick(()=>{if([Y.SELENIUM,Y.APPIUM].includes(r))try{(Ee(),ve(Ir)).getSessionPlayer(),require("jsdom")}catch{}})}async function an(r){let{project:e,token:t,lightweightMode:s,useLocalChromeDriver:n,useChromeLauncher:o,mode:i}=r,a=Boolean(s==null?void 0:s.general),c=Boolean(n||o),l=a?Vw:Gw;O("before initializeUserWithAuth");let p=await lt(async()=>(qw(i),await rl({projectId:e,token:t,branchName:r.branch,lightweightMode:s,localGrid:c})),"initializeUserWithAuth",l,{project:e,token:t,branchName:r.branch,lightweightModeGeneral:a,localGrid:c})();return O("after initializeUserWithAuth"),cm(p.authData,r.project,r.token),p}var Gw,Vw,dm=T(()=>{"use strict";Le();be();qt();Rt();ie();Gw=1e3*60*5,Vw=1e3*60*60*10});async function gm(r){var o;let e=Promise.resolve(),t=!r.host&&!r.gridId&&!r.grid&&(!r.testPlan||r.testPlan.length===0),s=r.files.length!==0;(t&&s||r.useLocalChromeDriver)&&(r.chromeBinaryLocation=r.downloadBrowser?await Io():r.chromeBinaryLocation,e=Er({projectId:r.project,userId:r.user},{chromeBinaryLocation:r.chromeBinaryLocation},Boolean((o=r.lightweightMode)==null?void 0:o.general)),r.useLocalChromeDriver=!0),!r.playerRequirePath&&r.mode!==Y.EXTENSION&&await Sr(r.playerLocation,r.canary),r.mode===Y.EXTENSION&&!r.ext&&await Ac(r.extensionLocation);let n;if(r.installCustomExtension){let i=Boolean(r.useLocalChromeDriver||r.useChromeLauncher);n=await Cc(r.installCustomExtension,i)}return await e,n}async function hm(r){var i;zw.info("prepare MockNetwork",{location:r});let e=await cc(r),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>mm*1e6)throw new Error(`${Tl} exceeded ${mm}MB`);let s;try{s=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${Tl} cannot be parsed.${No.EOL}${a}`)}let n=new fm.default;if(!n.validate(Ec,s)){let a=(i=n.errors)==null?void 0:i.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(No.EOL);throw new Error(`${Tl} is malformed.${No.EOL}${a}`)}return s.entries}var No,fm,mm,Tl,zw,wl=T(()=>{"use strict";No=E(require("os"));j();xd();rs();fm=E(require("ajv"));ie();Dc();dm();mm=1,Tl="JSON file supplied to --mock-network-pattern",zw=(U(),ve(Ya)).getLogger("prepare runner")});function bm(r,e=process){async function t(s){await ne(ce(ym,async n=>n()),1e4).catch(()=>null),r(s)}e.on("uncaughtException",async s=>{cn.error("Caught exception",{err:s}),console.log("Uncaught exception"),s.message&&console.log("Message =",s.message),s.reason&&console.log("Reason =",s.reason),await t(s)}),e.on("unhandledRejection",s=>{var n;if(cn.fatal("Caught unhandled promise rejection",s),!((n=s==null?void 0:s.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw s}),e.on("rejectionHandled",()=>{cn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let s="Runner aborted - SIGTERM event",n=new Error(s);throw cn.error(s),t(n),n}),e.once("SIGINT",()=>{let s="Runner aborted - SIGINT event",n=new Error(s);throw cn.error(s),t(n),n}),e.once("exit",s=>{r(s)})}function is(r){ym.push(r)}var cn,ym,ln=T(()=>{"use strict";U();j();cn=x("process-handler"),ym=[]});function Rl(r,e){let t=r.canary?"-master.zip":".zip",s=`${e?td:jr}/extension/testim-firefox-profile${t}`,n=`${e?rd:jr}/extension/testim-headless${t}`;return{firefox:s,chrome:n,"edge-chromium":n}}function Sm(r){let{chrome:e,firefox:t}=Rl(r,!1);return r.browser==="firefox"?t:r.browser==="chrome"?e:[e,t]}function Fo(r){let e=`${jr}/extension/sessionPlayer`;return r.canary?`${e}-master`:e}var Uo=T(()=>{"use strict";pe()});function Pm(r){De||(r!=null&&r.userId||(r={anonymousId:km}),xm.identify(r))}function ut(r,e){return as("ci",r,e)}function as(r,e,t){if(De)return;let s=r?{userId:r}:{anonymousId:km};xm.track(Object.assign(s,{event:e,properties:t}))}var Im,xm,km,cs=T(()=>{"use strict";pe();Im=E(require("analytics-node")),xm=new Im.default("sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",{flushAt:1}),km=require("crypto").randomBytes(20).toString("hex")});function Cm(r){return r.start&&as(null,"cli-start-command",{downloadBrowser:Boolean(r.downloadBrowser)}),!!(r.startV2||r.start||r.agent)}async function Am(r){let e=["playground-playwright","playground-puppeteer","playground-selenium"],t=!1,s=!1,n=!1,o=!1;if(r.start&&(o=!0),Number.isNaN(r.agentPort))throw new k("Agent port is not number");if(typeof r.agent=="string"&&e.some(a=>r.agent.includes(a))){let a=r.agent.split(",").map(c=>c.trim());a.includes("playground-playwright")&&(t=!0),a.includes("playground-puppeteer")&&(s=!0),a.includes("playground-selenium")&&(n=!0)}let i=Fo(r);return console.log("Start Testim CLI on Agent mode"),{project:r.project,token:r.token,agentMode:!0,agentPort:r.agentPort,agentBind:r.agentBind,openEditor:r.openEditor,installPlaygroundPlaywrightDeps:t,installPlaygroundPuppeteerDeps:s,installPlaygroundSeleniumDeps:n,startTestimBrowser:o,ext:r.ext,extensionPath:r.extensionPath,playerLocation:r.playerPath||i,canary:r.canary,playerPath:r.playerPath,playerRequirePath:r.playerRequirePath,downloadBrowser:Boolean(r.downloadBrowser)}}var Om=T(()=>{"use strict";Uo();cs();V()});function Bo(r){let{platform:e}=process;e==="win32"?(0,jo.exec)(`start chrome ${r}`):e==="darwin"?(0,jo.exec)(`open -a "Google Chrome" ${r}`):e==="linux"&&(0,jo.exec)(`google-chrome ${r}`)}var jo,Il=T(()=>{"use strict";jo=require("child_process")});var pn={};$(pn,{doLogin:()=>Cl,getProjectId:()=>ev,getToken:()=>tv});async function ev(){return Dm("projectId")}async function tv(){return Dm("token")}function Lm(r,e){return Promise.race([r,se(e).then(()=>{throw new te("timeout")})])}async function rv(){let r=(await import("express")).default(),e=async function(){return Lm(new Promise(n=>{r.get("/loginInfo",(o,i)=>{n(JSON.parse(Buffer.from(o.query.info,"base64").toString())),i.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((s,n)=>{let o=r.listen(42543,i=>{i&&n(i),s(o.address().port)})});try{let{getEditorUrl:s}=await Promise.resolve().then(()=>(be(),ke)),{editorUrl:n}=await s();Bo(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function Cl({overwriteExisting:r=!0,projects:e=null}={}){let t=xl.homedir(),s=kl.join(t,".testim");if(await ye(s)&&!r)return;let o={},[{default:i},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await Lm(rv(),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,c.succeed(),await _m(s,o);return}if(e!=null&&e.length){c.succeed();let l=e.length===1?{project:e[0]}:await i({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(p=>({title:p.name,value:p}))});o.token=l.project.ci.token,o.projectId=l.project.id,await _m(s,o);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function _m(r,e){await Pl.promises.writeFile(r,$o.stringify(e)),console.log(`Testim credentials saved in '${r}'`)}async function Dm(r){let e=xl.homedir(),t=kl.join(e,".testim"),s=await ye(t),n={};if(s)try{n=$o.parse((await Pl.promises.readFile(t)).toString())}catch{}return n||(n={}),n[r]}var xl,kl,$o,Pl,ls=T(()=>{"use strict";xl=E(require("os")),kl=E(require("path")),$o=E(require("yaml"));j();Pl=require("fs");V();Il()});var Bm={};$(Bm,{process:()=>pv});var Al,Mm,Ol,Fm,pt,Fe,Um,sv,Pe,Ll,nv,ov,Nm,jm,iv,_l,Ho,Dl,av,Wo,It,cv,u,lv,uv,pv,$m=T(()=>{"use strict";Al=E(require("ms")),Mm=E(require("chalk")),Ol=E(require("fs")),Fm=E(require("url")),pt=E(require("lodash")),Fe=E(require("path"));j();Uo();Om();qt();Um=require("commander");ie();V();Fr();j();sv=r=>r.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Pe=(r,e)=>(e.push(r),e),Ll=new Um.Command,nv=r=>r.split(","),ov=(r,e)=>!r||r.length===0?e:r,Nm=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],jm=()=>{function r(f){return f.includes("-h, --help")}function e(f){return f.includes("--params [params-json-string]")}function t(f){return f.includes("--ext")||f.includes("--extension-path")}function s(f){return f.includes("--player-path")||f.includes("--player-require-path")}function n(f){return f.includes("--executionId")||f.includes("--source")||f.includes("--resultId")||f.includes("--remoteRunId")||f.includes("--schedulerId")}function o(f){return f.includes("--get-browser-timeout")||f.includes("--get-browser-retries")||f.includes("--get-session-timeout")||f.includes("--get-session-retries")||f.includes("--driver-request-timeout")||f.includes("--driver-request-retries")}function i(f){return f.includes("--user")}function a(f){return f.includes("shouldMonitorPerformance")}function c(f){return f.includes("--save-rca-locally")}function l(f){return f.includes("--exit-code-ignore-failing-tests")}function p(f){return f.includes("--high-speed")}function m(f){return f.includes("--urls")}function d(f){return f.includes("--test-start-timeout")}function g(f){return f.includes("--install-lazy-deps")}Ll.help(f=>f.split(`
|
|
17
|
-
`).filter(y=>!t(y)&&!e(y)&&!r(y)&&!s(y)&&!n(y)&&!a(y)&&!i(y)&&!o(y)&&!c(y)&&!l(y)&&!
|
|
18
|
-
`))},
|
|
16
|
+
4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),i}}async function _w(){let r=`${jr}/extension/sessionPlayer_LATEST_RELEASE`;return(await hr(r)).body.toString("utf8")}async function Lw(r,e){if(!We(r)||We(r)&&e||De)return r;let t=await _w();return`${r}-${t}`}function _c(){let r=ct();return ts.resolve(r,"testim-bin")}function Dw(){let r=_c();return ts.resolve(r,"sessionPlayer.zip")}async function om(r,e,t=!1){try{return await no(r,e),await Ze(e,_c())}catch(s){if(t)throw s;return await om(r,e,!0)}}async function Sr(r,e){So.info("prepare player",{location:r,canary:e});let t=Dw();return lt(async()=>{let s=await Lw(r,e);return await om(s,t),{}},"preparePlayer",nm,[r,e,t])()}var tm,rm,ts,sm,So,nm,Cc,em,rs=T(()=>{"use strict";tm=E(require("ms")),rm=E(require("fs")),ts=E(require("path"));pe();qt();sm=require("serialize-error");U();Ic();V();j();So=x("prepare runner and testim start"),nm=(0,tm.default)("0.5 day"),Cc=16,em=`The size of the custom extension is more than ${Cc}MB`});function Nw(){let r=en.type().toLowerCase();return r==="darwin"?en.arch()==="arm"?"mac_arm":"mac":r==="windows_nt"?en.arch()==="x64"?"win64":"win32":"linux"}async function Io(){let r=Nw(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(r in t))throw new k(`Unsupported platform: ${r}`);let s=parseInt(tn,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:s,win64:s},o={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},i=`${e}/${t[r]}/${tn}/${n[r]}.zip`,a=Ro.join(Lc,n[r]),c=`${a}.zip`,l=Ro.join(a,o[r]);if(await ye(l))return l;if(!await ye(c)){let d=(0,Dc.default)("Downloading Chromium").start();try{await im.promises.mkdir(Lc),await qe(i,c)}catch(p){let g=`Failed to download Chromium: ${p.message}`;throw d.fail(g),new Error(g)}d.succeed()}let m=(0,Dc.default)("Extracting Chromium").start();try{await Ze(c,Lc)}catch(d){let p=`Failed to extract Chromium: ${d.message}`;throw m.fail(p),new Error(p)}return m.succeed(),l}var im,en,Ro,Dc,tn,Lc,Nc=T(()=>{"use strict";im=E(require("fs")),en=E(require("os")),Ro=E(require("path")),Dc=E(require("ora"));V();j();tn="1000968",Lc=Ro.join(Nt,`chrome-${tn}`)});async function cm(r,e){return ko=r,jc=e,await Mc()}function lm(r,e,t){tt=r.token,ko=e,jc=t,sn=Bc(tt),xo=r.refreshToken,Fc=r.ngrokToken,Uc=r.isNgrokWhitelisted}function Mw(r=ko,e=jc){return lt(()=>(rn.info("request to get cli token from server"),Qe({url:`${me}/auth/token`,body:{projectId:r,token:e}})),"getTokenV3",am*10,{projectId:r,token:e})()}async function Fw(){return rn.info("request to refresh JWT cli token from server"),tt=(await Qe({url:`${me}/auth/refreshToken`,body:{token:tt,refreshToken:xo}})).token,sn=Bc(tt),tt}async function Mc(){try{let r=await Mw();return rn.info("successfully get cli token from server"),tt=r.token,sn=Bc(tt),xo=r.refreshToken,Fc=r.ngrokToken,Uc=r.isNgrokWhitelisted,tt}catch(r){throw r.message.includes("Unauthorized")?new k("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."):(rn.error(`While trying to retrieve CLI token. caught error: ${r}`,{projectId:ko}),new k(`While trying to retrieve CLI token, caught error: ${r}`))}}function Bc(r){return require("jsonwebtoken").decode(r).exp*1e3}async function Kt(){if(!sn)return Mc();if(sn<Date.now()+4*am)try{return await Fw()}catch(r){return rn.error("failed to refresh token, executing fallback",r),Mc()}return tt}function Po(){return xo}function Mt(){return tt?{uid:require("jsonwebtoken").decode(tt).id,ngrokToken:Fc,isNgrokWhitelisted:Uc}:{}}var rn,tt,sn,xo,Fc,Uc,ko,jc,am,Rt=T(()=>{"use strict";pe();at();qt();V();U();rn=x("testim-custom-token"),ko=null,jc=null,am=5*60*1e3});var um={};$(um,{isCi:()=>ss});var ss,Co=T(()=>{"use strict";ss=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var ke={};$(ke,{addTestRetry:()=>pl,clearTestResult:()=>cl,deleteCloudflareTunnel:()=>gl,fetchLambdatestConfig:()=>ol,forceUpdateCloudflareTunnelRoutes:()=>fl,getAllGrids:()=>nl,getAppDetails:()=>Yc,getApplitoolsIntegrationData:()=>dl,getCloudflareTunnel:()=>ml,getEditorUrl:()=>Gw,getGridById:()=>_o,getGridByName:()=>rl,getHybridGridProvider:()=>tl,getLabFeaturesByProjectId:()=>il,getMobileDevicesFromGrid:()=>yl,getRealData:()=>on,getS3Artifact:()=>nn,getS3ArtifactText:()=>Wc,getSuiteTestList:()=>Jc,getTestPlan:()=>Hw,getTestPlanTestList:()=>Kc,getTestResults:()=>Rr,getUsageForCurrentBillingPeriod:()=>Xc,initializeUserWithAuth:()=>sl,isTestResultCompleted:()=>Qc,keepAliveGrid:()=>Zc,loadSfdcCredential:()=>Hc,loadTest:()=>Gc,releaseGridSlot:()=>el,reportExecutionFinished:()=>Oo,reportExecutionStarted:()=>zc,saveRemoteStep:()=>ll,saveTestPlanResult:()=>Vc,updateExecutionTests:()=>qc,updateRemoteRunFailure:()=>hl,updateTestDataArtifact:()=>Lo,updateTestResult:()=>al,updateTestStatus:()=>os,uploadRunDataArtifact:()=>ul});async function ns(){let r=await Kt();if(!r)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${r}`}}async function rt({url:r,body:e,headers:t={},timeout:s,retry:n}){let o=await ns(),i=Object.assign({},t,o);return Qe({url:`${me}${r||""}`,body:e,headers:i,timeout:s,retry:n})}async function Bw(r,e,t,s={},n=void 0){let o=await ns(),i=Object.assign({},s,o);return await rc(`${me}${r||""}`,e,t,i,n)}async function Ao(r,e){let t=await ns();return await oc(`${me}${r||""}`,e,t)}async function $w(r,e){let t=await ns();return await $s(`${me}${r||""}`,e,t)}async function Ww(r,e){let t=await ns();return await nc(`${me}${r||""}`,e||void 0,t)}async function xe(r,e,t,s){let n=await ns();return await Ot(`${me}${r||""}`,e||void 0,n,s,t)}function nn(r,e){return(0,oe.default)(()=>xe(`/storage${r}`,null,{isBinary:!0},e),{retries:ae,factor:1})}function Wc(r){return(0,oe.default)(()=>Ww(`/storage${r}`))}async function Hw(r,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,oe.default)(()=>xe("/testPlan",{projectId:r,name:e.join(",")}),{retries:ae,factor:1})).map(({testConfigIds:n,beforeAllLabels:o,testLabels:i,afterAllLabels:a,...c})=>Object.assign(c,{testConfigIds:t(n),beforeAllLabels:t(o),testLabels:t(i),afterAllLabels:t(a)}))}async function Hc({branch:r,projectId:e}){let t=await(0,oe.default)(()=>xe(`/branch/branchData/${r}`,{projectId:e}),{retries:ae,factor:1});return t==null?void 0:t.sfdcCredential}function Gc({testId:r,branch:e,projectId:t,skipSharedSteps:s=!1,useBranchMap:n=!0}){return(0,oe.default)(()=>xe(`/test/${r}`,{projectId:t,branch:e,skipSharedSteps:s,useBranchMap:n}),{retries:ae,factor:1})}function Vc(r,e,t){return(0,oe.default)(()=>rt({url:"/testPlan/result",body:{projectId:r,testPlanId:e,result:t}}),{retries:ae,factor:1})}function os(r,e,t,s,n,o,i=ae){return(0,oe.default)(()=>Ao("/result/run/test",{runId:e,testId:t,resultId:s,status:n,projectId:r,runnerVersion:Uw,...o}),{retries:i,factor:1})}function qc(r,e,t,s,n,o,i,a){return(0,oe.default)(()=>Ao("/result/run/tests",{runId:r,runnerStatuses:e,status:t,reason:s,success:n,startTime:o,endTime:i,projectId:a}),{retries:ae,factor:1})}async function zc({executionId:r,projectId:e,labels:t,startTime:s,executions:n,config:o,resultLabels:i,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:m}){let{isCi:d}=await Promise.resolve().then(()=>(Co(),um));return rt({timeout:9e4,url:"/result/run",body:{runId:r,projectId:e,labels:t,startTime:s,execution:n,status:"RUNNING",config:o,resultLabels:i,remoteRunId:a,intersections:m,metadata:{isCiRun:d,localRunUserId:c,isLocalRun:l}},retry:3})}function Oo(r,e,t,s,n={},o=void 0,i=void 0){let a=Date.now();return(0,oe.default)(()=>Ao("/result/run",{runId:e,projectId:t,endTime:a,status:r,success:s,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:ae,factor:1})}async function Kc(r,e,t,s,n){return(0,oe.default)(()=>rt({url:"/testPlan/list",body:{projectId:r,names:e,planIds:t,branch:s,intersections:n},timeout:12e4}),{retries:ae,factor:1})}function Jc({projectId:r,labels:e,testIds:t,testNames:s,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:m}){return(0,oe.default)(()=>rt({url:"/suite/v2/list",body:{projectId:r,labels:e,testIds:t,testNames:s,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:m}}),{retries:ae,factor:1})}async function Yc({appId:r,projectId:e}){try{return await(0,oe.default)(()=>xe(`/mobile-app/app/${r}?projectId=${e}`),{retries:ae,factor:1})}catch(t){Ut.error("failed getting application details",{appId:r,error:t});return}}async function Xc(r){try{return await(0,oe.default)(()=>xe(`/plan/project/${r}/usage-current-billing-period`),{retries:ae,factor:1})}catch(e){Ut.error("failed getting usage for current billing period",{projectId:r,error:e});return}}function Qc(r,e,t){return(0,oe.default)(()=>xe(`/result/${r}/isComplete`,{projectId:e,testRetryKey:t}),{retries:ae,factor:1})}function Rr(r,e,t,s){return(0,oe.default)(()=>xe(`/test/v2/${r}/result/${e}`,{projectId:t,branch:s}),{retries:ae,factor:1})}function Zc(r,e){return rt({url:`/grid/keep-alive?reqId=${J()}`,body:{projectId:r,slots:e},timeout:1e4})}function el(r,e,t,s,n){return rt({url:`/grid/release?reqId=${J()}`,body:{companyId:r,projectId:e,slotId:t,gridId:s,browser:n}})}function tl(r){return rt({url:"/grid/hybrid/provider",body:r})}function rl(r,e,t,s,n){return(0,oe.default)(()=>xe("/grid/name",{companyId:r,projectId:e,name:t,browser:s,executionId:n,reqId:J()}),{retries:ae,factor:1})}function _o(r,e,t,s,n){return(0,oe.default)(()=>xe(`/grid/${t}`,{companyId:r,projectId:e,browser:s,executionId:n,reqId:J()}),{retries:ae,factor:1})}async function sl({projectId:r,token:e,branchName:t,lightweightMode:s,localGrid:n}){var o,i;try{return await(0,oe.default)(()=>Qe({url:`${me}/executions/initialize`,body:{projectId:r,token:e,branchName:t||"master",lightweightMode:s,localGrid:n}}),{retries:ae,factor:1})}catch(a){throw Ut.error("error initializing info from server",a),(o=a==null?void 0:a.message)!=null&&o.includes("Bad Request")?new k("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."):(i=a==null?void 0:a.code)!=null&&i.includes("ENOTFOUND")?new k("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):a}}async function Gw(){if(Ur)return{editorUrl:Ur};try{return await(0,oe.default)(()=>xe("/system-info/editor-url"),{retries:ae,onFailedAttempt:r=>{if(r.attemptNumber>=ae)throw r},factor:1})}catch{return Ut.error("cannot retrieve editor-url from server"),{editorUrl:"https://app.testim.io"}}}function nl(r){return(0,oe.default)(()=>xe("/grid",{companyId:r}),{retries:ae,factor:1})}function on(r,e,t){return(0,oe.default)(()=>xe(`/real-data/${e}?${t}&projectId=${r}`),{retries:ae,factor:1})}function al(r,e,t,s,n){return(0,oe.default)(()=>rt({url:"/result/test",body:{projectId:r,resultId:e,testId:t,testResult:s,remoteRunId:n}}),{retries:ae,factor:1})}function cl(r,e,t,s){return(0,oe.default)(()=>rt({url:"/result/test/clear",body:{projectId:r,resultId:e,testId:t,testResult:s}}),{retries:ae,factor:1})}function ll(r,e,t,s){return(0,oe.default)(()=>rt({url:"/remoteStep",body:{projectId:r,resultId:e,stepId:t,remoteStep:s}}),{retries:ae,factor:1})}function Vw(r){return r.startsWith("/")?r:`/${r}`}function qw(r,e,t){let s=Vw(r);return t&&(s=`/${t}${s}`),e&&(s=`/${e}${s}`),s}async function dm(r,e,t,s,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${J()}${i||""}`,c=`${e}/${t}/${a}`,l=qw(c,"test-result-artifacts",r),m=Buffer.from(pm.gzip(s,{level:3})),d={file:{fileName:a,buffer:m}};return await(0,oe.default)(()=>Bw(`/storage${l}`,{},d,{"X-Asset-Encoding":"gzip"}),{retries:ae,factor:1}),l}function pl({projectId:r,runId:e,testId:t,newResultId:s,originalTestResultId:n,previousTestResultId:o,testResult:i}){return(0,oe.default)(()=>rt({url:"/result/test/retry",body:{projectId:r,newResultId:s,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:ae,factor:1})}async function dl(r){try{return await xe(`/integration/applitools/v3/connected?projectId=${r}`)}catch(e){return Ut.warn("could'nt get applitools integration data.",{err:e}),{}}}async function ml(r,e){try{return await Ao("/tunnel",{companyId:r,routes:e})}catch(t){return Ut.warn("could'nt get tunnel.",{err:t}),{}}}async function fl(r,e){try{return await rt({url:`/tunnel/${e}`,body:{companyId:r}})}catch(t){Ut.warn("could'nt get tunnel.",{err:t});return}}async function gl(r,e){try{return await $w(`/tunnel/${e}`,{companyId:r})}catch(t){Ut.warn("could'nt get tunnel.",{err:t});return}}function hl(r){return Qe({url:`${me}/result/remoteRunFailure`,body:r})}async function yl({projectId:r,projectType:e,gridId:t,companyId:s,selectors:n}){let o=`${jw}/mobileDevices/${t}/${s}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await(0,oe.default)(()=>xe(o,{projectId:r}),{retries:ae,factor:1})}catch(i){return Ut.warn("could'nt get devices from headspin grid.",{err:i}),null}}var Jt,pm,oe,$c,Uw,Ut,ae,jw,ol,il,ul,Lo,be=T(()=>{"use strict";Jt=E(require("lodash")),pm=E(require("pako"));j();pe();ie();at();Rt();oe=E(require("p-retry")),$c=E(require("object-hash"));V();U();Uw=ot(),Ut=x("testim service api"),ae=3,jw="/grid";ol=async()=>(0,oe.default)(()=>xe("/grid/lt/config"),{retries:ae,factor:1}),il=async r=>(0,oe.default)(()=>xe(`/labFeature/v2/project/${r}`),{retries:ae,factor:1});ul=Jt.memoize(async(r,e,t,s)=>{if(!Jt.isEmpty(s))return await dm(r,e,t,JSON.stringify(s),"test-run-data","application/json")},(r,e,t,s)=>`${(0,$c.default)(s)}:${e}:${t}`),Lo=Jt.memoize(async(r,e,t,s,n)=>!s||Jt.isEmpty(s)?void 0:await dm(r,e,t,JSON.stringify((()=>{let i=Jt.clone(s);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(c=>{i[c]&&Object.assign(i,{[c]:fc.HIDDEN_PARAM})})}return i})()),"test-test-data","application/json"),(r,e,t,s)=>`${(0,$c.default)(s)}:${e}:${t}`)});var Ir={};$(Ir,{getSessionPlayer:()=>re,options:()=>Tl});var Do,Tl,bl,re,Ee=T(()=>{"use strict";Do=require("path"),Tl={playerPath:void 0},re=()=>{if(bl)return bl;let r=(Le(),ve(_e));r.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(rs(),ve(Zs)),t=e(),s=Tl.playerPath?(0,Do.resolve)(Tl.playerPath,"src/background/sessionPlayerInit.ts"):(0,Do.join)(t,"sessionPlayer.js"),n=require(s);return r.log("getSessionPlayerRequire end"),bl=n,n}});function Jw(r){process.nextTick(()=>{if([Y.SELENIUM,Y.APPIUM].includes(r))try{(Ee(),ve(Ir)).getSessionPlayer(),require("jsdom")}catch{}})}async function an(r){let{project:e,token:t,lightweightMode:s,useLocalChromeDriver:n,useChromeLauncher:o,mode:i}=r,a=Boolean(s==null?void 0:s.general),c=Boolean(n||o),l=a?Kw:zw;O("before initializeUserWithAuth");let m=await lt(async()=>(Jw(i),await sl({projectId:e,token:t,branchName:r.branch,lightweightMode:s,localGrid:c})),"initializeUserWithAuth",l,{project:e,token:t,branchName:r.branch,lightweightModeGeneral:a,localGrid:c})();return O("after initializeUserWithAuth"),lm(m.authData,r.project,r.token),m}var zw,Kw,mm=T(()=>{"use strict";Le();be();qt();Rt();ie();zw=1e3*60*5,Kw=1e3*60*60*10});async function hm(r){var o;let e=Promise.resolve(),t=!r.host&&!r.gridId&&!r.grid&&(!r.testPlan||r.testPlan.length===0),s=r.files.length!==0;(t&&s||r.useLocalChromeDriver)&&(r.chromeBinaryLocation=r.downloadBrowser?await Io():r.chromeBinaryLocation,e=Er({projectId:r.project,userId:r.user},{chromeBinaryLocation:r.chromeBinaryLocation},Boolean((o=r.lightweightMode)==null?void 0:o.general)),r.useLocalChromeDriver=!0),!r.playerRequirePath&&r.mode!==Y.EXTENSION&&await Sr(r.playerLocation,r.canary),r.mode===Y.EXTENSION&&!r.ext&&await Oc(r.extensionLocation);let n;if(r.installCustomExtension){let i=Boolean(r.useLocalChromeDriver||r.useChromeLauncher);n=await Ac(r.installCustomExtension,i)}return await e,n}async function ym(r){var i;Yw.info("prepare MockNetwork",{location:r});let e=await lc(r),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>fm*1e6)throw new Error(`${wl} exceeded ${fm}MB`);let s;try{s=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${wl} cannot be parsed.${No.EOL}${a}`)}let n=new gm.default;if(!n.validate(Sc,s)){let a=(i=n.errors)==null?void 0:i.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(No.EOL);throw new Error(`${wl} is malformed.${No.EOL}${a}`)}return s.entries}var No,gm,fm,wl,Yw,vl=T(()=>{"use strict";No=E(require("os"));j();kd();rs();gm=E(require("ajv"));ie();Nc();mm();fm=1,wl="JSON file supplied to --mock-network-pattern",Yw=(U(),ve(Ya)).getLogger("prepare runner")});function Tm(r,e=process){async function t(s){await ne(ce(bm,async n=>n()),1e4).catch(()=>null),r(s)}e.on("uncaughtException",async s=>{cn.error("Caught exception",{err:s}),console.log("Uncaught exception"),s.message&&console.log("Message =",s.message),s.reason&&console.log("Reason =",s.reason),await t(s)}),e.on("unhandledRejection",s=>{var n;if(cn.fatal("Caught unhandled promise rejection",s),!((n=s==null?void 0:s.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw s}),e.on("rejectionHandled",()=>{cn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let s="Runner aborted - SIGTERM event",n=new Error(s);throw cn.error(s),t(n),n}),e.once("SIGINT",()=>{let s="Runner aborted - SIGINT event",n=new Error(s);throw cn.error(s),t(n),n}),e.once("exit",s=>{r(s)})}function is(r){bm.push(r)}var cn,bm,ln=T(()=>{"use strict";U();j();cn=x("process-handler"),bm=[]});function Il(r,e){let t=r.canary?"-master.zip":".zip",s=`${e?rd:jr}/extension/testim-firefox-profile${t}`,n=`${e?sd:jr}/extension/testim-headless${t}`;return{firefox:s,chrome:n,"edge-chromium":n}}function Rm(r){let{chrome:e,firefox:t}=Il(r,!1);return r.browser==="firefox"?t:r.browser==="chrome"?e:[e,t]}function Fo(r){let e=`${jr}/extension/sessionPlayer`;return r.canary?`${e}-master`:e}var Uo=T(()=>{"use strict";pe()});function Cm(r){De||(r!=null&&r.userId||(r={anonymousId:Pm}),km.identify(r))}function ut(r,e){return as("ci",r,e)}function as(r,e,t){if(De)return;let s=r?{userId:r}:{anonymousId:Pm};km.track(Object.assign(s,{event:e,properties:t}))}var xm,km,Pm,cs=T(()=>{"use strict";pe();xm=E(require("analytics-node")),km=new xm.default("sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",{flushAt:1}),Pm=require("crypto").randomBytes(20).toString("hex")});function Am(r){return r.start&&as(null,"cli-start-command",{downloadBrowser:Boolean(r.downloadBrowser)}),!!(r.startV2||r.start||r.agent)}async function Om(r){let e=["playground-playwright","playground-puppeteer","playground-selenium"],t=!1,s=!1,n=!1,o=!1;if(r.start&&(o=!0),Number.isNaN(r.agentPort))throw new k("Agent port is not number");if(typeof r.agent=="string"&&e.some(a=>r.agent.includes(a))){let a=r.agent.split(",").map(c=>c.trim());a.includes("playground-playwright")&&(t=!0),a.includes("playground-puppeteer")&&(s=!0),a.includes("playground-selenium")&&(n=!0)}let i=Fo(r);return console.log("Start Testim CLI on Agent mode"),{project:r.project,token:r.token,agentMode:!0,agentPort:r.agentPort,agentBind:r.agentBind,openEditor:r.openEditor,installPlaygroundPlaywrightDeps:t,installPlaygroundPuppeteerDeps:s,installPlaygroundSeleniumDeps:n,startTestimBrowser:o,ext:r.ext,extensionPath:r.extensionPath,playerLocation:r.playerPath||i,canary:r.canary,playerPath:r.playerPath,playerRequirePath:r.playerRequirePath,downloadBrowser:Boolean(r.downloadBrowser)}}var _m=T(()=>{"use strict";Uo();cs();V()});function Bo(r){let{platform:e}=process;e==="win32"?(0,jo.exec)(`start chrome ${r}`):e==="darwin"?(0,jo.exec)(`open -a "Google Chrome" ${r}`):e==="linux"&&(0,jo.exec)(`google-chrome ${r}`)}var jo,xl=T(()=>{"use strict";jo=require("child_process")});var pn={};$(pn,{doLogin:()=>Al,getProjectId:()=>sv,getToken:()=>nv});async function sv(){return Nm("projectId")}async function nv(){return Nm("token")}function Dm(r,e){return Promise.race([r,se(e).then(()=>{throw new te("timeout")})])}async function ov(){let r=(await import("express")).default(),e=async function(){return Dm(new Promise(n=>{r.get("/loginInfo",(o,i)=>{n(JSON.parse(Buffer.from(o.query.info,"base64").toString())),i.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((s,n)=>{let o=r.listen(42543,i=>{i&&n(i),s(o.address().port)})});try{let{getEditorUrl:s}=await Promise.resolve().then(()=>(be(),ke)),{editorUrl:n}=await s();Bo(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function Al({overwriteExisting:r=!0,projects:e=null}={}){let t=kl.homedir(),s=Pl.join(t,".testim");if(await ye(s)&&!r)return;let o={},[{default:i},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await Dm(ov(),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,c.succeed(),await Lm(s,o);return}if(e!=null&&e.length){c.succeed();let l=e.length===1?{project:e[0]}:await i({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(m=>({title:m.name,value:m}))});o.token=l.project.ci.token,o.projectId=l.project.id,await Lm(s,o);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Lm(r,e){await Cl.promises.writeFile(r,$o.stringify(e)),console.log(`Testim credentials saved in '${r}'`)}async function Nm(r){let e=kl.homedir(),t=Pl.join(e,".testim"),s=await ye(t),n={};if(s)try{n=$o.parse((await Cl.promises.readFile(t)).toString())}catch{}return n||(n={}),n[r]}var kl,Pl,$o,Cl,ls=T(()=>{"use strict";kl=E(require("os")),Pl=E(require("path")),$o=E(require("yaml"));j();Cl=require("fs");V();xl()});var $m={};$($m,{process:()=>fv});var Ol,Fm,_l,Um,pt,Fe,jm,iv,Pe,Dl,av,cv,Mm,Bm,lv,Ll,Ho,Nl,uv,Wo,It,pv,u,dv,mv,fv,Wm=T(()=>{"use strict";Ol=E(require("ms")),Fm=E(require("chalk")),_l=E(require("fs")),Um=E(require("url")),pt=E(require("lodash")),Fe=E(require("path"));j();Uo();_m();qt();jm=require("commander");ie();V();Fr();j();iv=r=>r.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Pe=(r,e)=>(e.push(r),e),Dl=new jm.Command,av=r=>r.split(","),cv=(r,e)=>!r||r.length===0?e:r,Mm=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],Bm=()=>{function r(f){return f.includes("-h, --help")}function e(f){return f.includes("--params [params-json-string]")}function t(f){return f.includes("--ext")||f.includes("--extension-path")}function s(f){return f.includes("--player-path")||f.includes("--player-require-path")}function n(f){return f.includes("--executionId")||f.includes("--source")||f.includes("--resultId")||f.includes("--remoteRunId")||f.includes("--schedulerId")}function o(f){return f.includes("--get-browser-timeout")||f.includes("--get-browser-retries")||f.includes("--get-session-timeout")||f.includes("--get-session-retries")||f.includes("--driver-request-timeout")||f.includes("--driver-request-retries")}function i(f){return f.includes("--user")}function a(f){return f.includes("shouldMonitorPerformance")}function c(f){return f.includes("--save-rca-locally")}function l(f){return f.includes("--exit-code-ignore-failing-tests")}function m(f){return f.includes("--high-speed")}function d(f){return f.includes("--urls")}function p(f){return f.includes("--test-start-timeout")}function g(f){return f.includes("--install-lazy-deps")}Dl.help(f=>f.split(`
|
|
17
|
+
`).filter(y=>!t(y)&&!e(y)&&!r(y)&&!s(y)&&!n(y)&&!a(y)&&!i(y)&&!o(y)&&!c(y)&&!l(y)&&!m(y)&&!d(y)&&!p(y)&&!g(y)).join(`
|
|
18
|
+
`))},lv=(r,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(Fm.default.yellow(`
|
|
19
19
|
WARNING: ${r} is deprecated. ${t}
|
|
20
|
-
`))},_l=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:Ho,argv:Dl,stdout:av,exit:Wo,cwd:It}=global.process,cv=["trace","debug","info","warn","error","silent"];hc(Dl,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));Ll.description("Testim.io CLI").option("--run [file-glob-pattern]","codeful test files to run",Pe,[]).option("-h --help","output usage information",jm).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",Pe,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Pe,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Pe,[]).option("-w, --webpackConfig [webpack-configuration]","webpack configuration used to build the code based project").option("--test-id [test-id]","test ID to run",Pe,[]).option("-l, --label [label]","labels to search test by",Pe,[]).option("-n, --name [test-name]","test name to run",Pe,[]).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",nv).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("--is-regression-baseline-run","save doms and run results as regression baseline data").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",Pe,[]).option("--test-plan-id [test-plan-id]","test plan to run",Pe,[]).option("--suite [suite-name]","suite to run",Pe,[]).option("--suite-id [suite-id]","suite ID to run",Pe,[]).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",Pe,[]).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("--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("-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("-rad --reset-app-data [reset-app-data]","set noReset appium capability to false, noReset capability is true by default",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("-roso --reset-on-session-start-only [reset-on-session-start-only]","set resetOnSessionStartOnly appium capability to true to avoid uninstall app on session end (ios run only)",!1).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("--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(Ho.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,Al.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,Al.default)("90s")).option("--driver-request-retries [driver-request-retries]","Retries for any WebDriver request to the grid server",Number,3).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: ${_l.join("/")}`,Pe,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Pe,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--init [init]","Path for an initial test app").option("--inspect [port]","Opens node inspector at given port",Number).option("--login","Log in to Testim").option("--require-credentials","Log in to Testim if not already logged in").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("--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").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",Pe,[]).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)",Pe,[]).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)",Pe,[]).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).parse(Dl);u=Ll.opts(),lv=()=>{u.grid||u.gridId||(u.host||(u.host="ondemand.saucelabs.com"),u.port||(u.port=80))},uv=()=>{u.grid||u.gridId||(u.host||(u.host="hub-cloud.browserstack.com"),u.port||(u.port=80))},pv=async()=>{var h,y,w,S,b,v,I,A,_;u.inspect&&require("inspector").open(u.inspect);let r={},e={},t=[],s={};if(!Dl.slice(2).length)throw jm(),new $r;if(u.requireCredentials){let R=await Promise.resolve().then(()=>(ls(),pn)),L=await R.getProjectId(),C=await R.getToken();(!L||!C)&&await R.doLogin()}if(u.login)return await(await Promise.resolve().then(()=>(ls(),pn))).doLogin(),{loginMode:!0};if(u.init)return{initCodimMode:!0,initTestProject:u.init};if(u.version){let R="Testim CLI Version: ";Ho.npm_package_version&&(console.log(R,Ho.npm_package_version),Wo(0));let L=ot();L&&(console.log(R,L),Wo(0)),console.log("Could not find version, please check the package.json manually"),Wo(0)}if(u.installLazyDeps)return{installLazyDepsMode:!0};u.disableFileCache&&jd();let n=u.fileCacheLocation||u.usePrefechedData||u.createPrefechedData;if(n){let R=Fe.resolve(n);Fd(R)}if(u.usePrefechedData&&Bd(),u.playerRequirePath){let R=Fe.resolve(u.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let L=Fe.join(R,"tsconfig.node.json"),N=require("ts-node").register({project:L,ignore:[/node_modules/,new RegExp(`^${pt.escapeRegExp(Fe.relative(It(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:N.config.options.paths,baseUrl:N.config.options.baseUrl}),(Ee(),ve(Ir)).options.playerPath=R;let K=require("module"),X=K.prototype.require;K.prototype.require=function(fe){return fe==="rox-alias"?X.call(this,"rox-node"):X.apply(this,arguments)}}if(u.caFile&&(global.caFileContent=Ol.readFileSync(u.caFile)),u.proxy&&(global.proxyUri=u.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent"),global.HttpsProxyAgent=require("https-proxy-agent")),u.proxyForGrid&&!u.proxy)throw new k("missing --proxy option");if(Cm(u))return Am(u);try{let R={};u.configFile?R=require(Fe.join(It(),u.configFile)).config:u.optionsFile&&(R=require(Fe.join(It(),u.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(L=>{let C=sv(L);u[C]=ov(u[C],R[L])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}if(u.tunneld)return{tunnel:!0,tunnelPort:u.tunnelPort,tunnelRoutes:u.tunnelRoutes,tunnelRoutesOutput:u.tunnelRoutesOutput,tunnelHostHeader:u.tunnelHostHeader,tunnelRegion:u.tunnelRegion,tunnelDiagnostics:u.tunnelDiagnostics,tunnelUseHttpAddress:u.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:u.token,project:u.project};let o=((h=u.testConfig)==null?void 0:h.length)||((y=u.testConfigId)==null?void 0:y.length),i=((w=u.testPlan)==null?void 0:w.length)||((S=u.testPlanId)==null?void 0:S.length),a=((b=u.suite)==null?void 0:b.length)||((v=u.suiteId)==null?void 0:v.length);if(u.seleniumCapsFile)try{s=require(Fe.join(It(),u.seleniumCapsFile))}catch(R){throw new k(`Failed to parse selenium caps file file error: ${R.message}`)}if((I=u.reporters)!=null&&I.includes("junit")&&!u.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!u.tunnel&&u.externalLambdatestTunnelId)throw new k("missing --tunnel parameter");if(!u.tunnel&&u.externalLambdatestUseWss)throw new k("missing --tunnel parameter");if(!u.tunnel&&[u.tunnelPort,u.tunnelHostHeader,u.tunnelRegion,u.tunnelDiagnostics].some(Boolean))throw new k("missing --tunnel parameter");if(u.chromeExtraPrefs)try{e=require(Fe.join(It(),u.chromeExtraPrefs))}catch(R){throw new k(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(u.chromeExtraArgs){let R=u.chromeExtraArgs.split(",");for(let L of R){let[C]=L.split("=");Nm.includes(C)||u.useLocalChromeDriver||u.useChromeLauncher?(t.push(L),C==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${C}), allowed values: ${JSON.stringify(Nm)}`)}}if(u.paramsFile)try{r=Object.assign({},r,require(Fe.join(It(),u.paramsFile)))}catch(R){throw new k(`Failed to read/open params file error: ${R.message}`)}if(u.params)try{r=Object.assign({},r,JSON.parse(u.params))}catch(R){throw new k(`Failed to parse params string error: ${R.message}`)}if(u.sauceUser&&!u.sauceKey||!u.sauceUser&&u.sauceKey)throw new k("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(u.sauceUser&&u.sauceKey&&(lv(),u.saucelabs={},u.saucelabs.username=u.sauceUser,u.saucelabs.accessKey=u.sauceKey),u.sauceOptions)try{let R=require(Fe.join(It(),u.sauceOptions)),L=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let N=R.browserName.toLowerCase();switch(N){case"microsoftedge":u.browser="edge";break;default:u.browser=N}}u.browser==="edge"&&parseFloat(R.version)>=Fa&&(u.browser="edge-chromium");let C=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!L&&u.browser==="chrome"&&C)throw new k("The minimum chrome supported version is 50.0");u.saucelabs=Object.assign({},u.saucelabs,R)}catch(R){throw new k(`Failed to parse saucelabs options file error: ${R.message}`)}if(u.browserstackUser&&!u.browserstackKey||!u.browserstackUser&&u.browserstackKey)throw new k("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(u.browserstackUser&&u.browserstackKey&&(uv(),u.browserstack={},u.browserstack["browserstack.user"]=u.browserstackUser,u.browserstack["browserstack.key"]=u.browserstackKey),u.browserstackOptions)try{let R=require(Fe.join(It(),u.browserstackOptions)),L=R.platform&&["mac","android"].includes(R.platform.toLowerCase());if(R.browserName&&(u.browser=R.browserName.toLowerCase()),u.browser==="edge"&&parseFloat(R.browser_version)>=Fa&&(u.browser="edge-chromium"),!L&&parseFloat(R.browser_version)<50&&u.browser==="chrome")throw new k("The minimum chrome supported version is 50.0");u.browserstack=Object.assign({},u.browserstack,R)}catch(R){throw new k(`Failed to parse browserstack options file error: ${R.message}`)}if(u.perfecto={},u.perfectoToken&&(u.perfecto.securityToken=u.perfectoToken),u.perfectoOptions)try{let R=require(Fe.join(It(),u.perfectoOptions)),L={location:"US East",securityToken:u.perfectoToken};u.perfecto=Object.assign({},L,R)}catch(R){throw new k(`Failed to parse perfecto options file error: ${R.message}`)}if(u.testobjectSauce={},u.testobjectKey&&(u.testobjectSauce.testobjectApiKey=u.testobjectKey),u.testobjectOptions)try{let R=require(Fe.join(It(),u.testobjectOptions)),L={testobjectApiKey:u.testobjectKey};u.testobjectSauce=Object.assign({},L,R)}catch(R){throw new k(`Failed to parse test object options file error: ${R.message}`)}if(!u.project){let L=await(await Promise.resolve().then(()=>(ls(),pn))).getProjectId();if(L)u.project=L;else throw new k("missing project-id info, either --login to provide new credentials or use --project <project-id>")}u.mode||(u.mode=u.run.length?"selenium":"extension"),u.testConfig&&(u.testConfig=[u.testConfig].flat()),u.testConfigId&&(u.testConfigId=[u.testConfigId].flat()),u.retries=!u.retries||typeof u.retries=="boolean"?1:Number(u.retries)+1,u.browserTimeout=!u.browserTimeout||typeof u.browserTimeout=="boolean"?60*1e3:u.browserTimeout,u.newBrowserWaitTimeout=!u.newBrowserWaitTimeout||typeof u.newBrowserWaitTimeout=="boolean"?10*60*1e3:u.newBrowserWaitTimeout*60*1e3,u.getBrowserTimeout||(u.getBrowserTimeout=u.browserTimeout),u.getBrowserRetries||(u.getBrowserRetries=u.mode===Y.APPIUM?1:Math.round(u.newBrowserWaitTimeout/u.browserTimeout)),u.getSessionTimeout=u.browserTimeout<u.getSessionTimeout?u.getSessionTimeout:u.browserTimeout,u.driverRequestTimeout=u.browserTimeout<u.driverRequestTimeout?u.driverRequestTimeout:u.browserTimeout;let c=Boolean(u.timeout);if(u.timeout=!u.timeout||typeof u.timeout=="boolean"?10*60*1e3:u.timeout,u.beforeParallel=!u.beforeParallel||typeof u.beforeParallel=="boolean"?1:Number(u.beforeParallel),u.parallel=!u.parallel||typeof u.parallel=="boolean"?1:Number(u.parallel),u.afterParallel=!u.afterParallel||typeof u.afterParallel=="boolean"?1:Number(u.afterParallel),u.parallel>1&&u.run&&!u.gridId&&!u.grid&&(!u.testPlan||u.testPlan.length===0)&&!((A=u.testPlanId)!=null&&A.length)&&av.isTTY&&!u.headless&&!Ho.TERM&&((await require("prompts")({type:"toggle",name:"isSure",message:"Running in parallel without --headless flag will open several browsers on your computer. Are you sure?",initial:!1,active:"yes",inactive:"no"})).isSure||Wo(0)),u.tunnelPort=!u.tunnelPort||typeof u.tunnelPort=="boolean"?"80":u.tunnelPort,u.port&&(u.port=Number(u.port)),u.retries<=0||Number.isNaN(u.retries))throw new k("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(u.retries>21)throw new k("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(!u.token){let L=await(await Promise.resolve().then(()=>(ls(),pn))).getToken();if(L)u.token=L;else throw new k("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.")}if(u.browserTimeout<=0||Number.isNaN(u.browserTimeout))throw new k("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(u.newBrowserWaitTimeout<=0||Number.isNaN(u.newBrowserWaitTimeout))throw new k("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(u.timeout<=0||Number.isNaN(u.timeout))throw new k("test run timeout could not be a negative number, --timeout <run-timeout>");if(u.beforeParallel<=0||Number.isNaN(u.beforeParallel))throw new k("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(u.parallel<=0||Number.isNaN(u.parallel))throw new k("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(u.afterParallel<=0||Number.isNaN(u.afterParallel))throw new k("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![Y.EXTENSION,Y.SELENIUM,Y.APPIUM].includes(u.mode))throw new k(`runner mode <${u.mode}> is not supported`);if(u.mode!==Y.SELENIUM&&u.disableNativeEvents)throw new k("disable-native-events is only applicable in selenium mode");if(!u.browser&&!o&&!i&&(u.browser="chrome"),u.appiumLogLevel||(u.appiumLogLevel="silent"),!cv.includes(u.appiumLogLevel))throw new k(`runner appium-log-level <${u.appiumLogLevel}> is not supported`);if(u.testPlan&&u.testPlan.length===0&&u.testPlanId&&u.testPlanId.length===0){if(typeof u.host!="string"&&typeof u.grid!="string"&&typeof u.gridId!="string"&&u.run.length===0&&!u.useLocalChromeDriver&&!u.useChromeLauncher&&!u.createPrefechedData)throw new k("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(u.testId.length||u.label.length||u.name.length||o||u.browser||a||u.useLocalChromeDriver||u.useChromeLauncher)throw new k("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!i&&(u.beforeParallel!==1||u.afterParallel!==1))throw new k("cannot set --before-parallel or --after-parallel without --test-plan option");if((u.testId.length||i||u.label.length||u.name.length||a)&&u.file)throw new k("Cannot pass codeful automation tests with --testId --label --name or --suite");if([u.host,u.grid,u.gridId].filter(Boolean).length>1)throw new k("please define exactly one of --grid or --grid-id or --host");if((_=u.host)!=null&&_.includes("/")&&(/^(f|ht)tps?:\/\//i.test(u.host)||(u.host=`http://${u.host}`),u.host=Fm.parse(u.host).hostname),u.resultLabel.length){u.resultLabel=u.resultLabel.map(L=>L.trim()).filter(Boolean);let R=u.resultLabel.filter(L=>L.length>=250).filter(Boolean);if(u.branch==="auto-detect"&&u.resultLabel.includes("auto-detect-branch")&&Tr()&&u.resultLabel.unshift(Tr()),R.length)throw new k("A result label cannot exceed 250 characters")}let p=Sm(u),m=Fo(u);if(!u.w3cCapabilities&&!u.oldCapabilities)throw new k("cannot set --w3c-capabilities and --old-capabilities options as false");if(u.protocol||(u.protocol=u.port===443?"https":"http"),!["http","https"].includes(u.protocol))throw new k("invalid --protocol value, allow --protocol http or https");if(u.rerunFailedByRunId&&u.branch)throw new k("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(u.rerunFailedByRunId&&(a||u.name.length||u.testId.length||u.label.length||i))throw new k("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(u.run.length){let R=require("glob");if(u.files=pt.flatMap(u.run,L=>R.sync(L)),u.files.length===0)throw new k(`No files found at path '${u.run}'.`)}else u.files=[];if(u.setRetention&&!pt.inRange(pt.parseInt(u.setRetention),1,11))throw new k("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");u.setRetention&&(u.setRetention=Number(u.setRetention));let d="is no longer supported, please use --override-mapping-file";if(u.mockNetworkHar)throw new k(`--mock-network-har ${d}`);if(u.mockNetworkPattern)throw new k(`--mock-network-pattern ${d}`);if(u.disableMockNetwork&&u.overrideMappingFile)throw new k("You can either use --disable-mock-network or --override-mapping-file");if(!u.collectCodeCoverage&&u.codeCoverageSourceMapPath)throw new k("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!u.collectCodeCoverage&&u.codeCoverageReporter.length)throw new k("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!u.collectCodeCoverage&&u.codeCoverageInclude.length)throw new k("cannot set --code-coverage-include without passing --collect-code-coverage");if(u.collectCodeCoverage&&u.codeCoverageReporter&&pt.difference(u.codeCoverageReporter,_l).length){let R=pt.difference(u.codeCoverageReporter,_l);throw new k(`invalid --code-coverage-reporter parameters ${R.join("/")}`)}u.codeCoverageReporter=u.codeCoverageReporter.length===0?["html","text"]:u.codeCoverageReporter,u.codeCoverageInclude=u.codeCoverageInclude.length===0?["src/**"]:u.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"},f=Object.keys(g).filter(R=>Boolean(u[R]));if(u.mode!==Y.EXTENSION&&f.length){let R=f.length>1?"are":"is";throw new k(`${f.map(L=>g[L]).join(" and ")} ${R} only applicable in extension mode`)}if(u.tmsFieldFile)try{let R=Ol.readFileSync(u.tmsFieldFile);u.tmsCustomFields=JSON.parse(R)}catch(R){throw new k(`failed to parse field file error: ${R.message}`)}if(u.highSpeed&&(iv("--high-speed"," --turbo-mode"),u.turboMode=!0),u.skipLoadBalancer&&!u.deviceUdid)throw new k("It is not possible to skip load balancer without specifying deviceUdid");if(u.deviceUdid&&(u.deviceName||u.osVersion))throw new k("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(u.resetAppData&&u.fullReset)throw new k("It is not possible to set both --reset-app-data and --full-reset capabilities to true at the same time!");if(u.resetOnSessionStartOnly&&!u.fullReset&&console.warn("Ignoring --reset-on-session-start-only flag, should be used when --full-reset is provided for ios runs"),u.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"},L=typeof u.lightweightMode=="string"?JSON.parse(u.lightweightMode):{};u.lightweightMode=Object.assign({},R,L)}catch(R){throw new k(`failed to parse lightweightMode settings error: ${R.message}`)}else u.turboMode&&u.mode===Y.EXTENSION&&(u.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"});if(typeof u.baseUrl=="boolean")throw new k("base url cannot be used as a flag, and must contain a string value");return{testId:[u.testId].flat(),name:[u.name].flat(),label:[u.label].flat(),suites:[u.suite].flat(),suiteIds:[u.suiteId].flat(),testPlan:[u.testPlan].flat(),testPlanIds:[u.testPlanId].flat(),files:[u.files].flat(),webpackConfig:u.webpackConfig,reportFile:u.reportFile,urls:u.urls,reportFileClassname:u.overrideReportFileClassname,reporters:u.reporters,project:u.project,host:u.host,headless:u.headless,useLocalChromeDriver:u.useLocalChromeDriver,chromeBinaryLocation:u.chromeBinaryLocation,useChromeLauncher:u.useChromeLauncher,port:u.port,grid:u.grid,gridId:u.gridId,disableNativeEvents:u.disableNativeEvents,saucelabs:u.saucelabs,browserstack:u.browserstack,baseUrl:u.baseUrl,branch:(u.branch==="auto-detect"?Tr():u.branch)||"master",autoDetect:u.branch==="auto-detect",token:u.token,userParamsData:r,mode:u.mode,isRegressionBaselineRun:u.isRegressionBaselineRun,browser:u.browser,beforeParallel:u.beforeParallel,parallel:u.parallel,afterParallel:u.afterParallel,canary:u.canary,rerunFailedByRunId:u.rerunFailedByRunId,disableGridCheck:u.disableGridCheck,disableTimeoutRetry:u.disableTimeoutRetry,resultLabels:u.resultLabel,path:u.path,protocol:u.protocol,perfecto:u.perfecto,experitestToken:u.experitestToken,testobjectSauce:u.testobjectSauce,gridUsername:u.gridUsername,gridPassword:u.gridPassword,overrideExecutionName:u.overrideExecutionName,tmsSuppressReporting:Boolean(u.suppressTmsReporting)||Boolean(u.tmsSuppressReporting),tmsRunId:u.tmsRunId,tmsCustomFields:u.tmsCustomFields,proxyForGrid:u.proxyForGrid,retentionDays:u.setRetention,passZeroTests:Boolean(u.passZeroTests),runQuarantinedTests:Boolean(u.runQuarantinedTests),deviceName:u.deviceName,deviceUdid:u.deviceUdid,osVersion:u.osVersion,skipLoadBalancer:u.skipLoadBalancer,lockDevice:u.lockDevice,appId:u.appId,appiumLogLevel:u.appiumLogLevel,resetAppData:u.resetAppData,fullReset:u.fullReset,resetOnSessionStartOnly:u.resetOnSessionStartOnly,ext:u.ext,extensionLocation:[u.extensionPath||p].flat(),extensionPath:u.extensionPath,playerLocation:u.playerPath||m,playerPath:u.playerPath,playerRequirePath:u.playerRequirePath,tunnel:u.tunnel,tunnelPort:u.tunnelPort,tunnelRoutes:u.tunnelRoutes,tunnelRoutesOutput:u.tunnelRoutesOutput,tunnelHostHeader:u.tunnelHostHeader,tunnelRegion:u.tunnelRegion,tunnelDiagnostics:u.tunnelDiagnostics,tunnelUseHttpAddress:u.tunnelUseHttpAddress,externalLambdatestTunnelId:u.externalLambdatestTunnelId,externalLambdatestUseWss:u.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(u.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(u.externalLambdatestMitm),beforeTest:u.beforeTest,afterTest:u.afterTest,beforeSuite:u.beforeSuite,afterSuite:u.afterSuite,timeout:u.timeout,timeoutWasGiven:c,browserTimeout:u.browserTimeout,newBrowserWaitTimeout:u.newBrowserWaitTimeout,getBrowserTimeout:u.getBrowserTimeout,getBrowserRetries:u.getBrowserRetries,getSessionTimeout:u.getSessionTimeout,getSessionRetries:u.getSessionRetries,driverRequestTimeout:u.driverRequestTimeout,driverRequestRetries:u.driverRequestRetries,testStartTimeout:u.testStartTimeout,testConfigNames:u.testConfig,testConfigIds:u.testConfigId,overrideMappingFile:u.overrideMappingFile,disableMockNetwork:u.disableMockNetwork,codeCoverageUrlFilter:u.codeCoverageUrlFilter,collectCodeCoverage:u.collectCodeCoverage,codeCoverageReportPath:u.codeCoverageReportPath,codeCoverageSourceMapPath:u.codeCoverageSourceMapPath,codeCoverageReporter:u.codeCoverageReporter,codeCoverageInclude:u.codeCoverageInclude,executionId:u.executionId,remoteRunId:u.remoteRunId,schedulerId:u.schedulerId,source:u.source,resultId:u.resultId,installCustomExtension:u.installCustomExtension,w3cCapabilities:u.w3cCapabilities,oldCapabilities:u.oldCapabilities,chromeBlockLocation:u.chromeBlockLocation,chromeUserDataDir:u.chromeUserDataDir,retries:u.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:u.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:s,shouldMonitorPerformance:u.monitorPerformance,user:u.user,lightweightMode:u.lightweightMode,createPrefechedData:u.createPrefechedData,saveRCALocally:u.saveRcaLocally,exitCodeIgnoreFailingTests:u.exitCodeIgnoreFailingTests,disableSockets:u.disableSockets,intersections:{labels:u.intersectWithLabel.length?[u.intersectWithLabel].flat():void 0,suiteNames:u.intersectWithSuite.length?[u.intersectWithSuite].flat():void 0,suiteIds:u.intersectWithSuiteId.length?[u.intersectWithSuiteId].flat():void 0},downloadBrowser:u.downloadBrowser}}});var Vm={};$(Vm,{installAllLazyDependencies:()=>fv,lazyRequire:()=>le});async function le(r,e={}){let t=xc(r);if(t)return t;let s;e.silent||(s=(0,Wm.default)(`Installing ${r} before first usage...`).start());try{let n=await mv(r);return s&&s.succeed(),n}catch(n){dv.warn("failed to install dependency lazily",{dependency:r,err:n});let o=Gm(r),i=`${r}@${o}`,c=process.argv.includes("npx")?"":"-g ",l=`Installation of ${r} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${i}`;throw s&&s.fail(l),n}}async function mv(r){return us.has(r)||(us.set(r,Hm(r)),us.get(r).catch(()=>{us.delete(r)})),us.get(r)}async function Hm(r){let e=xc(r);if(e)return e;let t=Gm(r),s=`${r}@${t}`;return await vo(ct(),s),zt(r)}async function fv(){let r=Object.keys($a);for(let e of r)await Hm(e)}function Gm(r){let e=Object.entries($a).find(([t])=>t===r);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Wm,dv,us,dt=T(()=>{"use strict";Wm=E(require("ora"));Qs();U();j();Yn();Xs();dv=x("lazy-require"),us=new Map});var Jm={};$(Jm,{init:()=>hv});async function hv(r){var w,S;let e=typeof r=="string"?r:"";(typeof r!="string"||!r.trim())&&(e=(await(0,Ml.default)({type:"text",name:"project",message:"Please enter Project name",validate:v=>String(v).length>3})).project);let t=Yt.resolve(e);Xt.existsSync(t)&&Xt.readdirSync(t).length!==0&&(console.log(`${t} is not empty. Quitting...`),process.exit(1));let s=t.substr(Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"))+1),n=(0,zm.default)(s);if(!n.validForNewPackages){let b=`The name '${s}' is not a valid package name:`;throw console.log(Go.default.red(b)),n.errors&&n.errors.forEach(v=>console.log(Go.default.red(v))),n.warnings&&n.warnings.forEach(v=>console.log(Go.default.yellowBright(`warning: ${v}`))),new k(`${b}
|
|
20
|
+
`))},Ll=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:Ho,argv:Nl,stdout:uv,exit:Wo,cwd:It}=global.process,pv=["trace","debug","info","warn","error","silent"];yc(Nl,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));Dl.description("Testim.io CLI").option("--run [file-glob-pattern]","codeful test files to run",Pe,[]).option("-h --help","output usage information",Bm).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",Pe,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Pe,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Pe,[]).option("-w, --webpackConfig [webpack-configuration]","webpack configuration used to build the code based project").option("--test-id [test-id]","test ID to run",Pe,[]).option("-l, --label [label]","labels to search test by",Pe,[]).option("-n, --name [test-name]","test name to run",Pe,[]).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",av).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("--is-regression-baseline-run","save doms and run results as regression baseline data").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",Pe,[]).option("--test-plan-id [test-plan-id]","test plan to run",Pe,[]).option("--suite [suite-name]","suite to run",Pe,[]).option("--suite-id [suite-id]","suite ID to run",Pe,[]).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",Pe,[]).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("--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("-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("-rad --reset-app-data [reset-app-data]","set noReset appium capability to false, noReset capability is true by default",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("-roso --reset-on-session-start-only [reset-on-session-start-only]","set resetOnSessionStartOnly appium capability to true to avoid uninstall app on session end (ios run only)",!1).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("--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(Ho.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,Ol.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,Ol.default)("90s")).option("--driver-request-retries [driver-request-retries]","Retries for any WebDriver request to the grid server",Number,3).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: ${Ll.join("/")}`,Pe,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Pe,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--init [init]","Path for an initial test app").option("--inspect [port]","Opens node inspector at given port",Number).option("--login","Log in to Testim").option("--require-credentials","Log in to Testim if not already logged in").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("--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").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",Pe,[]).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)",Pe,[]).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)",Pe,[]).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).parse(Nl);u=Dl.opts(),dv=()=>{u.grid||u.gridId||(u.host||(u.host="ondemand.saucelabs.com"),u.port||(u.port=80))},mv=()=>{u.grid||u.gridId||(u.host||(u.host="hub-cloud.browserstack.com"),u.port||(u.port=80))},fv=async()=>{var h,y,w,S,b,v,I,A,_;u.inspect&&require("inspector").open(u.inspect);let r={},e={},t=[],s={};if(!Nl.slice(2).length)throw Bm(),new $r;if(u.requireCredentials){let R=await Promise.resolve().then(()=>(ls(),pn)),L=await R.getProjectId(),C=await R.getToken();(!L||!C)&&await R.doLogin()}if(u.login)return await(await Promise.resolve().then(()=>(ls(),pn))).doLogin(),{loginMode:!0};if(u.init)return{initCodimMode:!0,initTestProject:u.init};if(u.version){let R="Testim CLI Version: ";Ho.npm_package_version&&(console.log(R,Ho.npm_package_version),Wo(0));let L=ot();L&&(console.log(R,L),Wo(0)),console.log("Could not find version, please check the package.json manually"),Wo(0)}if(u.installLazyDeps)return{installLazyDepsMode:!0};u.disableFileCache&&Bd();let n=u.fileCacheLocation||u.usePrefechedData||u.createPrefechedData;if(n){let R=Fe.resolve(n);Ud(R)}if(u.usePrefechedData&&$d(),u.playerRequirePath){let R=Fe.resolve(u.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let L=Fe.join(R,"tsconfig.node.json"),N=require("ts-node").register({project:L,ignore:[/node_modules/,new RegExp(`^${pt.escapeRegExp(Fe.relative(It(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:N.config.options.paths,baseUrl:N.config.options.baseUrl}),(Ee(),ve(Ir)).options.playerPath=R;let K=require("module"),X=K.prototype.require;K.prototype.require=function(fe){return fe==="rox-alias"?X.call(this,"rox-node"):X.apply(this,arguments)}}if(u.caFile&&(global.caFileContent=_l.readFileSync(u.caFile)),u.proxy&&(global.proxyUri=u.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent"),global.HttpsProxyAgent=require("https-proxy-agent")),u.proxyForGrid&&!u.proxy)throw new k("missing --proxy option");if(Am(u))return Om(u);try{let R={};u.configFile?R=require(Fe.join(It(),u.configFile)).config:u.optionsFile&&(R=require(Fe.join(It(),u.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(L=>{let C=iv(L);u[C]=cv(u[C],R[L])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}if(u.tunneld)return{tunnel:!0,tunnelPort:u.tunnelPort,tunnelRoutes:u.tunnelRoutes,tunnelRoutesOutput:u.tunnelRoutesOutput,tunnelHostHeader:u.tunnelHostHeader,tunnelRegion:u.tunnelRegion,tunnelDiagnostics:u.tunnelDiagnostics,tunnelUseHttpAddress:u.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:u.token,project:u.project};let o=((h=u.testConfig)==null?void 0:h.length)||((y=u.testConfigId)==null?void 0:y.length),i=((w=u.testPlan)==null?void 0:w.length)||((S=u.testPlanId)==null?void 0:S.length),a=((b=u.suite)==null?void 0:b.length)||((v=u.suiteId)==null?void 0:v.length);if(u.seleniumCapsFile)try{s=require(Fe.join(It(),u.seleniumCapsFile))}catch(R){throw new k(`Failed to parse selenium caps file file error: ${R.message}`)}if((I=u.reporters)!=null&&I.includes("junit")&&!u.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!u.tunnel&&u.externalLambdatestTunnelId)throw new k("missing --tunnel parameter");if(!u.tunnel&&u.externalLambdatestUseWss)throw new k("missing --tunnel parameter");if(!u.tunnel&&[u.tunnelPort,u.tunnelHostHeader,u.tunnelRegion,u.tunnelDiagnostics].some(Boolean))throw new k("missing --tunnel parameter");if(u.chromeExtraPrefs)try{e=require(Fe.join(It(),u.chromeExtraPrefs))}catch(R){throw new k(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(u.chromeExtraArgs){let R=u.chromeExtraArgs.split(",");for(let L of R){let[C]=L.split("=");Mm.includes(C)||u.useLocalChromeDriver||u.useChromeLauncher?(t.push(L),C==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${C}), allowed values: ${JSON.stringify(Mm)}`)}}if(u.paramsFile)try{r=Object.assign({},r,require(Fe.join(It(),u.paramsFile)))}catch(R){throw new k(`Failed to read/open params file error: ${R.message}`)}if(u.params)try{r=Object.assign({},r,JSON.parse(u.params))}catch(R){throw new k(`Failed to parse params string error: ${R.message}`)}if(u.sauceUser&&!u.sauceKey||!u.sauceUser&&u.sauceKey)throw new k("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(u.sauceUser&&u.sauceKey&&(dv(),u.saucelabs={},u.saucelabs.username=u.sauceUser,u.saucelabs.accessKey=u.sauceKey),u.sauceOptions)try{let R=require(Fe.join(It(),u.sauceOptions)),L=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let N=R.browserName.toLowerCase();switch(N){case"microsoftedge":u.browser="edge";break;default:u.browser=N}}u.browser==="edge"&&parseFloat(R.version)>=Fa&&(u.browser="edge-chromium");let C=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!L&&u.browser==="chrome"&&C)throw new k("The minimum chrome supported version is 50.0");u.saucelabs=Object.assign({},u.saucelabs,R)}catch(R){throw new k(`Failed to parse saucelabs options file error: ${R.message}`)}if(u.browserstackUser&&!u.browserstackKey||!u.browserstackUser&&u.browserstackKey)throw new k("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(u.browserstackUser&&u.browserstackKey&&(mv(),u.browserstack={},u.browserstack["browserstack.user"]=u.browserstackUser,u.browserstack["browserstack.key"]=u.browserstackKey),u.browserstackOptions)try{let R=require(Fe.join(It(),u.browserstackOptions)),L=R.platform&&["mac","android"].includes(R.platform.toLowerCase());if(R.browserName&&(u.browser=R.browserName.toLowerCase()),u.browser==="edge"&&parseFloat(R.browser_version)>=Fa&&(u.browser="edge-chromium"),!L&&parseFloat(R.browser_version)<50&&u.browser==="chrome")throw new k("The minimum chrome supported version is 50.0");u.browserstack=Object.assign({},u.browserstack,R)}catch(R){throw new k(`Failed to parse browserstack options file error: ${R.message}`)}if(u.perfecto={},u.perfectoToken&&(u.perfecto.securityToken=u.perfectoToken),u.perfectoOptions)try{let R=require(Fe.join(It(),u.perfectoOptions)),L={location:"US East",securityToken:u.perfectoToken};u.perfecto=Object.assign({},L,R)}catch(R){throw new k(`Failed to parse perfecto options file error: ${R.message}`)}if(u.testobjectSauce={},u.testobjectKey&&(u.testobjectSauce.testobjectApiKey=u.testobjectKey),u.testobjectOptions)try{let R=require(Fe.join(It(),u.testobjectOptions)),L={testobjectApiKey:u.testobjectKey};u.testobjectSauce=Object.assign({},L,R)}catch(R){throw new k(`Failed to parse test object options file error: ${R.message}`)}if(!u.project){let L=await(await Promise.resolve().then(()=>(ls(),pn))).getProjectId();if(L)u.project=L;else throw new k("missing project-id info, either --login to provide new credentials or use --project <project-id>")}u.mode||(u.mode=u.run.length?"selenium":"extension"),u.testConfig&&(u.testConfig=[u.testConfig].flat()),u.testConfigId&&(u.testConfigId=[u.testConfigId].flat()),u.retries=!u.retries||typeof u.retries=="boolean"?1:Number(u.retries)+1,u.browserTimeout=!u.browserTimeout||typeof u.browserTimeout=="boolean"?60*1e3:u.browserTimeout,u.newBrowserWaitTimeout=!u.newBrowserWaitTimeout||typeof u.newBrowserWaitTimeout=="boolean"?10*60*1e3:u.newBrowserWaitTimeout*60*1e3,u.getBrowserTimeout||(u.getBrowserTimeout=u.browserTimeout),u.getBrowserRetries||(u.getBrowserRetries=u.mode===Y.APPIUM?1:Math.round(u.newBrowserWaitTimeout/u.browserTimeout)),u.getSessionTimeout=u.browserTimeout<u.getSessionTimeout?u.getSessionTimeout:u.browserTimeout,u.driverRequestTimeout=u.browserTimeout<u.driverRequestTimeout?u.driverRequestTimeout:u.browserTimeout;let c=Boolean(u.timeout);if(u.timeout=!u.timeout||typeof u.timeout=="boolean"?10*60*1e3:u.timeout,u.beforeParallel=!u.beforeParallel||typeof u.beforeParallel=="boolean"?1:Number(u.beforeParallel),u.parallel=!u.parallel||typeof u.parallel=="boolean"?1:Number(u.parallel),u.afterParallel=!u.afterParallel||typeof u.afterParallel=="boolean"?1:Number(u.afterParallel),u.parallel>1&&u.run&&!u.gridId&&!u.grid&&(!u.testPlan||u.testPlan.length===0)&&!((A=u.testPlanId)!=null&&A.length)&&uv.isTTY&&!u.headless&&!Ho.TERM&&((await require("prompts")({type:"toggle",name:"isSure",message:"Running in parallel without --headless flag will open several browsers on your computer. Are you sure?",initial:!1,active:"yes",inactive:"no"})).isSure||Wo(0)),u.tunnelPort=!u.tunnelPort||typeof u.tunnelPort=="boolean"?"80":u.tunnelPort,u.port&&(u.port=Number(u.port)),u.retries<=0||Number.isNaN(u.retries))throw new k("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(u.retries>21)throw new k("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(!u.token){let L=await(await Promise.resolve().then(()=>(ls(),pn))).getToken();if(L)u.token=L;else throw new k("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.")}if(u.browserTimeout<=0||Number.isNaN(u.browserTimeout))throw new k("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(u.newBrowserWaitTimeout<=0||Number.isNaN(u.newBrowserWaitTimeout))throw new k("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(u.timeout<=0||Number.isNaN(u.timeout))throw new k("test run timeout could not be a negative number, --timeout <run-timeout>");if(u.beforeParallel<=0||Number.isNaN(u.beforeParallel))throw new k("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(u.parallel<=0||Number.isNaN(u.parallel))throw new k("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(u.afterParallel<=0||Number.isNaN(u.afterParallel))throw new k("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![Y.EXTENSION,Y.SELENIUM,Y.APPIUM].includes(u.mode))throw new k(`runner mode <${u.mode}> is not supported`);if(u.mode!==Y.SELENIUM&&u.disableNativeEvents)throw new k("disable-native-events is only applicable in selenium mode");if(!u.browser&&!o&&!i&&(u.browser="chrome"),u.appiumLogLevel||(u.appiumLogLevel="silent"),!pv.includes(u.appiumLogLevel))throw new k(`runner appium-log-level <${u.appiumLogLevel}> is not supported`);if(u.testPlan&&u.testPlan.length===0&&u.testPlanId&&u.testPlanId.length===0){if(typeof u.host!="string"&&typeof u.grid!="string"&&typeof u.gridId!="string"&&u.run.length===0&&!u.useLocalChromeDriver&&!u.useChromeLauncher&&!u.createPrefechedData)throw new k("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(u.testId.length||u.label.length||u.name.length||o||u.browser||a||u.useLocalChromeDriver||u.useChromeLauncher)throw new k("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!i&&(u.beforeParallel!==1||u.afterParallel!==1))throw new k("cannot set --before-parallel or --after-parallel without --test-plan option");if((u.testId.length||i||u.label.length||u.name.length||a)&&u.file)throw new k("Cannot pass codeful automation tests with --testId --label --name or --suite");if([u.host,u.grid,u.gridId].filter(Boolean).length>1)throw new k("please define exactly one of --grid or --grid-id or --host");if((_=u.host)!=null&&_.includes("/")&&(/^(f|ht)tps?:\/\//i.test(u.host)||(u.host=`http://${u.host}`),u.host=Um.parse(u.host).hostname),u.resultLabel.length){u.resultLabel=u.resultLabel.map(L=>L.trim()).filter(Boolean);let R=u.resultLabel.filter(L=>L.length>=250).filter(Boolean);if(u.branch==="auto-detect"&&u.resultLabel.includes("auto-detect-branch")&&Tr()&&u.resultLabel.unshift(Tr()),R.length)throw new k("A result label cannot exceed 250 characters")}let m=Rm(u),d=Fo(u);if(!u.w3cCapabilities&&!u.oldCapabilities)throw new k("cannot set --w3c-capabilities and --old-capabilities options as false");if(u.protocol||(u.protocol=u.port===443?"https":"http"),!["http","https"].includes(u.protocol))throw new k("invalid --protocol value, allow --protocol http or https");if(u.rerunFailedByRunId&&u.branch)throw new k("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(u.rerunFailedByRunId&&(a||u.name.length||u.testId.length||u.label.length||i))throw new k("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(u.run.length){let R=require("glob");if(u.files=pt.flatMap(u.run,L=>R.sync(L)),u.files.length===0)throw new k(`No files found at path '${u.run}'.`)}else u.files=[];if(u.setRetention&&!pt.inRange(pt.parseInt(u.setRetention),1,11))throw new k("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");u.setRetention&&(u.setRetention=Number(u.setRetention));let p="is no longer supported, please use --override-mapping-file";if(u.mockNetworkHar)throw new k(`--mock-network-har ${p}`);if(u.mockNetworkPattern)throw new k(`--mock-network-pattern ${p}`);if(u.disableMockNetwork&&u.overrideMappingFile)throw new k("You can either use --disable-mock-network or --override-mapping-file");if(!u.collectCodeCoverage&&u.codeCoverageSourceMapPath)throw new k("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!u.collectCodeCoverage&&u.codeCoverageReporter.length)throw new k("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!u.collectCodeCoverage&&u.codeCoverageInclude.length)throw new k("cannot set --code-coverage-include without passing --collect-code-coverage");if(u.collectCodeCoverage&&u.codeCoverageReporter&&pt.difference(u.codeCoverageReporter,Ll).length){let R=pt.difference(u.codeCoverageReporter,Ll);throw new k(`invalid --code-coverage-reporter parameters ${R.join("/")}`)}u.codeCoverageReporter=u.codeCoverageReporter.length===0?["html","text"]:u.codeCoverageReporter,u.codeCoverageInclude=u.codeCoverageInclude.length===0?["src/**"]:u.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"},f=Object.keys(g).filter(R=>Boolean(u[R]));if(u.mode!==Y.EXTENSION&&f.length){let R=f.length>1?"are":"is";throw new k(`${f.map(L=>g[L]).join(" and ")} ${R} only applicable in extension mode`)}if(u.tmsFieldFile)try{let R=_l.readFileSync(u.tmsFieldFile);u.tmsCustomFields=JSON.parse(R)}catch(R){throw new k(`failed to parse field file error: ${R.message}`)}if(u.highSpeed&&(lv("--high-speed"," --turbo-mode"),u.turboMode=!0),u.skipLoadBalancer&&!u.deviceUdid)throw new k("It is not possible to skip load balancer without specifying deviceUdid");if(u.deviceUdid&&(u.deviceName||u.osVersion))throw new k("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(u.resetAppData&&u.fullReset)throw new k("It is not possible to set both --reset-app-data and --full-reset capabilities to true at the same time!");if(u.resetOnSessionStartOnly&&!u.fullReset&&console.warn("Ignoring --reset-on-session-start-only flag, should be used when --full-reset is provided for ios runs"),u.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"},L=typeof u.lightweightMode=="string"?JSON.parse(u.lightweightMode):{};u.lightweightMode=Object.assign({},R,L)}catch(R){throw new k(`failed to parse lightweightMode settings error: ${R.message}`)}else u.turboMode&&u.mode===Y.EXTENSION&&(u.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"});if(typeof u.baseUrl=="boolean")throw new k("base url cannot be used as a flag, and must contain a string value");return{testId:[u.testId].flat(),name:[u.name].flat(),label:[u.label].flat(),suites:[u.suite].flat(),suiteIds:[u.suiteId].flat(),testPlan:[u.testPlan].flat(),testPlanIds:[u.testPlanId].flat(),files:[u.files].flat(),webpackConfig:u.webpackConfig,reportFile:u.reportFile,urls:u.urls,reportFileClassname:u.overrideReportFileClassname,reporters:u.reporters,project:u.project,host:u.host,headless:u.headless,useLocalChromeDriver:u.useLocalChromeDriver,chromeBinaryLocation:u.chromeBinaryLocation,useChromeLauncher:u.useChromeLauncher,port:u.port,grid:u.grid,gridId:u.gridId,disableNativeEvents:u.disableNativeEvents,saucelabs:u.saucelabs,browserstack:u.browserstack,baseUrl:u.baseUrl,branch:(u.branch==="auto-detect"?Tr():u.branch)||"master",autoDetect:u.branch==="auto-detect",token:u.token,userParamsData:r,mode:u.mode,isRegressionBaselineRun:u.isRegressionBaselineRun,browser:u.browser,beforeParallel:u.beforeParallel,parallel:u.parallel,afterParallel:u.afterParallel,canary:u.canary,rerunFailedByRunId:u.rerunFailedByRunId,disableGridCheck:u.disableGridCheck,disableTimeoutRetry:u.disableTimeoutRetry,resultLabels:u.resultLabel,path:u.path,protocol:u.protocol,perfecto:u.perfecto,experitestToken:u.experitestToken,testobjectSauce:u.testobjectSauce,gridUsername:u.gridUsername,gridPassword:u.gridPassword,overrideExecutionName:u.overrideExecutionName,tmsSuppressReporting:Boolean(u.suppressTmsReporting)||Boolean(u.tmsSuppressReporting),tmsRunId:u.tmsRunId,tmsCustomFields:u.tmsCustomFields,proxyForGrid:u.proxyForGrid,retentionDays:u.setRetention,passZeroTests:Boolean(u.passZeroTests),runQuarantinedTests:Boolean(u.runQuarantinedTests),deviceName:u.deviceName,deviceUdid:u.deviceUdid,osVersion:u.osVersion,skipLoadBalancer:u.skipLoadBalancer,lockDevice:u.lockDevice,appId:u.appId,appiumLogLevel:u.appiumLogLevel,resetAppData:u.resetAppData,fullReset:u.fullReset,resetOnSessionStartOnly:u.resetOnSessionStartOnly,ext:u.ext,extensionLocation:[u.extensionPath||m].flat(),extensionPath:u.extensionPath,playerLocation:u.playerPath||d,playerPath:u.playerPath,playerRequirePath:u.playerRequirePath,tunnel:u.tunnel,tunnelPort:u.tunnelPort,tunnelRoutes:u.tunnelRoutes,tunnelRoutesOutput:u.tunnelRoutesOutput,tunnelHostHeader:u.tunnelHostHeader,tunnelRegion:u.tunnelRegion,tunnelDiagnostics:u.tunnelDiagnostics,tunnelUseHttpAddress:u.tunnelUseHttpAddress,externalLambdatestTunnelId:u.externalLambdatestTunnelId,externalLambdatestUseWss:u.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(u.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(u.externalLambdatestMitm),beforeTest:u.beforeTest,afterTest:u.afterTest,beforeSuite:u.beforeSuite,afterSuite:u.afterSuite,timeout:u.timeout,timeoutWasGiven:c,browserTimeout:u.browserTimeout,newBrowserWaitTimeout:u.newBrowserWaitTimeout,getBrowserTimeout:u.getBrowserTimeout,getBrowserRetries:u.getBrowserRetries,getSessionTimeout:u.getSessionTimeout,getSessionRetries:u.getSessionRetries,driverRequestTimeout:u.driverRequestTimeout,driverRequestRetries:u.driverRequestRetries,testStartTimeout:u.testStartTimeout,testConfigNames:u.testConfig,testConfigIds:u.testConfigId,overrideMappingFile:u.overrideMappingFile,disableMockNetwork:u.disableMockNetwork,codeCoverageUrlFilter:u.codeCoverageUrlFilter,collectCodeCoverage:u.collectCodeCoverage,codeCoverageReportPath:u.codeCoverageReportPath,codeCoverageSourceMapPath:u.codeCoverageSourceMapPath,codeCoverageReporter:u.codeCoverageReporter,codeCoverageInclude:u.codeCoverageInclude,executionId:u.executionId,remoteRunId:u.remoteRunId,schedulerId:u.schedulerId,source:u.source,resultId:u.resultId,installCustomExtension:u.installCustomExtension,w3cCapabilities:u.w3cCapabilities,oldCapabilities:u.oldCapabilities,chromeBlockLocation:u.chromeBlockLocation,chromeUserDataDir:u.chromeUserDataDir,retries:u.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:u.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:s,shouldMonitorPerformance:u.monitorPerformance,user:u.user,lightweightMode:u.lightweightMode,createPrefechedData:u.createPrefechedData,saveRCALocally:u.saveRcaLocally,exitCodeIgnoreFailingTests:u.exitCodeIgnoreFailingTests,disableSockets:u.disableSockets,intersections:{labels:u.intersectWithLabel.length?[u.intersectWithLabel].flat():void 0,suiteNames:u.intersectWithSuite.length?[u.intersectWithSuite].flat():void 0,suiteIds:u.intersectWithSuiteId.length?[u.intersectWithSuiteId].flat():void 0},downloadBrowser:u.downloadBrowser}}});var qm={};$(qm,{installAllLazyDependencies:()=>yv,lazyRequire:()=>le});async function le(r,e={}){let t=kc(r);if(t)return t;let s;e.silent||(s=(0,Hm.default)(`Installing ${r} before first usage...`).start());try{let n=await hv(r);return s&&s.succeed(),n}catch(n){gv.warn("failed to install dependency lazily",{dependency:r,err:n});let o=Vm(r),i=`${r}@${o}`,c=process.argv.includes("npx")?"":"-g ",l=`Installation of ${r} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${i}`;throw s&&s.fail(l),n}}async function hv(r){return us.has(r)||(us.set(r,Gm(r)),us.get(r).catch(()=>{us.delete(r)})),us.get(r)}async function Gm(r){let e=kc(r);if(e)return e;let t=Vm(r),s=`${r}@${t}`;return await vo(ct(),s),zt(r)}async function yv(){let r=Object.keys($a);for(let e of r)await Gm(e)}function Vm(r){let e=Object.entries($a).find(([t])=>t===r);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Hm,gv,us,dt=T(()=>{"use strict";Hm=E(require("ora"));Qs();U();j();Yn();Xs();gv=x("lazy-require"),us=new Map});var Ym={};$(Ym,{init:()=>Tv});async function Tv(r){var w,S;let e=typeof r=="string"?r:"";(typeof r!="string"||!r.trim())&&(e=(await(0,Fl.default)({type:"text",name:"project",message:"Please enter Project name",validate:v=>String(v).length>3})).project);let t=Yt.resolve(e);Xt.existsSync(t)&&Xt.readdirSync(t).length!==0&&(console.log(`${t} is not empty. Quitting...`),process.exit(1));let s=t.substr(Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"))+1),n=(0,Km.default)(s);if(!n.validForNewPackages){let b=`The name '${s}' is not a valid package name:`;throw console.log(Go.default.red(b)),n.errors&&n.errors.forEach(v=>console.log(Go.default.red(v))),n.warnings&&n.warnings.forEach(v=>console.log(Go.default.yellowBright(`warning: ${v}`))),new k(`${b}
|
|
21
21
|
validation errors:
|
|
22
22
|
${((w=n.errors)==null?void 0:w.join(`
|
|
23
23
|
`))||""}
|
|
24
24
|
warnings:
|
|
25
25
|
${((S=n.warnings)==null?void 0:S.join(`
|
|
26
|
-
`))||""}`)}let i=(await(0,Ml.default)({type:"toggle",name:"isJs",message:"Add support for TypeScript?",initial:!0,active:"no",inactive:"yes"})).isJs?"template.js":"template.ts",a="codim",c=Yt.join(__dirname,a,i),l=Yt.join(process.cwd(),e),p=(0,Nl.default)(`Creating new test project in ${l}`).start();await oo(c,l);let m=Yt.join(__dirname,a,i,"package.json"),d=Yt.join(process.cwd(),e,"package.json"),f=(await Xt.promises.readFile(m)).toString().replace("~testim-codeful-test-project~",s);await Xt.promises.writeFile(d,f);let h="node_modules",y=Yt.join(process.cwd(),e,".gitignore");await Xt.promises.writeFile(y,h),p.succeed(),p=(0,Nl.default)("Installing dependencies").start(),await gv("npm install",{cwd:l}),p.succeed(),console.log(`Testim Dev Kit project folder successfully created in ${l}.`)}var Xt,Yt,qm,Nl,Go,Ml,zm,Km,gv,Ym=T(()=>{"use strict";Xt=E(require("fs")),Yt=E(require("path")),qm=E(require("child_process")),Nl=E(require("ora")),Go=E(require("chalk")),Ml=E(require("prompts")),zm=E(require("validate-npm-package-name")),Km=require("util");V();uc();gv=(0,Km.promisify)(qm.exec)});var Qm={};$(Qm,{preloadTests:()=>dn});async function dn(r){if(!Array.isArray(r.testId)||!r.testId.length)return{};let e={branch:r.branch,projectId:r.project};return await lt(async()=>{let t=await ce(r.testId,s=>Hc({...e,testId:s}),{concurrency:2});return Xm.keyBy(t,"testData.id")},"loadTests",yv,[e,r.testId])()}var Xm,yv,Vo=T(()=>{"use strict";Xm=E(require("lodash"));qt();be();j();yv=1e3*60*60*10});function Fl(){return ot()}async function tf(){if(!De)try{let r=await ne(Tv(),5e3,"The API call to NPM timed out"),e=Fl();e&&ef.lt(e,r)&&console.log(Zm.default.yellow(`Warning: You are using version ${e}, a newer version is available. To update please run npm install (npm install -g @testim/testim-cli)`))}catch(r){bv.warn("Failed to get NPM version",{err:r})}}var Zm,ef,bv,Tv,Ul=T(()=>{"use strict";Zm=E(require("chalk")),ef=E(require("semver"));j();pe();Qs();qt();U();bv=x("npm-driver"),Tv=lt(()=>Gd("@testim/testim-cli"),"getNpmVersion")});var jl,vv,ps,rf,sf,Bl,nf,of=T(()=>{"use strict";j();V();U();dt();jl=x("testimNgrok"),vv=".whitelisted-ngrok.testim.io",ps="",sf=async(r,e={})=>{if(!e.ngrokToken)throw new k("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${J()}-${r.projectData.projectId}${vv}`);let s={proto:"http",addr:r.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};r.tunnelHostHeader&&(s.host_header=r.tunnelHostHeader),r.tunnelRegion&&(s.region=r.tunnelRegion);let o=await(await le("ngrok")).connect(s);r.tunnelUseHttpAddress&&o.startsWith("https://")?(jl.info("replace https to http"),ps=o.replace("https://","http://")):ps=o,r.tunnelDiagnostics&&Bl(),r.baseUrl=ps},Bl=async(r=!0)=>{try{let t=(await le("ngrok")).getApi(),{tunnels:s}=await t.listTunnels(),n=s.find(o=>o.public_url===ps);console.log("ngrok stats",n),jl.info("ngrok stats",{tunnel:n})}catch(e){jl.error("error collecting ngrok stats",{err:e})}r&&(rf=setTimeout(()=>Bl(),1e4))},nf=async r=>{if(!ps)return;clearTimeout(rf),r.tunnelDiagnostics&&await Bl(!1),await(await le("ngrok")).disconnect(ps)}});var Qt,Wl,af,Sv,Rv,$l,qo,Ko,zo,Iv,cf,lf,uf=T(()=>{"use strict";Qt=E(require("os")),Wl=E(require("fs")),af=E(require("child_process"));j();be();Sv="https://github.com/cloudflare/cloudflared/releases/download/2022.4.1/",Rv={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"}},$l=Qt.tmpdir(),qo=`${$l}/cloudflared`,Ko=null,zo=null,Iv=async()=>{if(await ye(qo))return;let e=Rv[Qt.platform()+Qt.arch()];if(!e)throw new Error(`tunnel on ${Qt.platform()+Qt.arch()} platform is not supported.`);let t=e.extract?$l+e.path:qo;await qe(`${Sv}/${e.path}`,t),e.extract&&await Ze(t,$l),await Wl.promises.chmod(qo,"755")},cf=async r=>{let e=r.baseUrl||`http://localhost:${r.tunnelPort||80}`,t="tunnelRoutes"in r&&r.tunnelRoutes||[e],[s]=await Promise.all([dl(r.company.companyId,t),Iv()]);Ko=s._id,zo=af.spawn(qo,["tunnel","--no-autoupdate","run","--force","--token",s.token],{stdio:"inherit"}),await ml(r.company.companyId,Ko),"tunnelRoutesOutput"in r&&r.tunnelRoutesOutput&&await Wl.promises.writeFile(r.tunnelRoutesOutput,JSON.stringify(s.routesMapping,null,2)),r.baseUrl=`${r.tunnelUseHttpAddress?"http":"https"}://${s.routesMapping[e]}`},lf=async r=>{let e=[];return Ko&&e.push(fl(r.company.companyId,Ko)),zo&&e.push(new Promise((t,s)=>{zo.on("close",n=>{n&&s(new Error(`tunnel process exited with code ${n}`)),t()}),zo.kill()})),await Promise.all(e)}});var z,df,kv,Pv,Cv,pf,Jo,Hl,M,Te=T(()=>{"use strict";z=E(require("rox-node"));U();j();pe();df=x("FeatureFlagsService"),kv=!De&&!0&&!Qp,Pv=2e4,Cv=60*60*24,pf=["labs","disabled","enabled"],Jo=class extends z.default.Variant{constructor(e="disabled"){super(e,pf)}getValue(){let e=super.getValue();return pf.includes(e)?e:(df.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},Hl=class{constructor(){this.flags={useNewWSCLI:new z.default.Flag,useSafariWebdriverVisibilityChecks:new z.default.Flag,useClickimVisibilityChecks:new z.default.Flag,runGetElementCodeInAut:new z.default.Flag,enableFrameSwitchOptimization:new z.default.Flag,maximumJsResultSize:new z.default.Configuration(2e3*1024),skipFileInputClicks:new z.default.Flag,errorMessageOnBadNetwork:new z.default.Flag(!0),warnOnBadNetwork:new z.default.Flag(!1),overrideAzureStorageUrl:new z.default.Flag,useJsInputCodeInSafari:new z.default.Flag,useJsInputCodeInFirefox:new z.default.Flag,autoSaveDownloadFileFireFox:new z.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new z.default.Flag(!0),experimentalPreCodeCompilation:new z.default.Flag(!0),experimentalAsyncCustomCode:new z.default.Flag,useSameBrowserForMultiTests:new Jo("labs"),highSpeedMode:new Jo,usePortedHtml5DragDrop:new z.default.Flag,testNamesToBeforeSuiteHook:new z.default.Flag,addCustomCapabilities:new z.default.Variant("{}"),LTNetworkCapabilities:new z.default.Flag,downloadToBase64:new z.default.Flag,dec2022eolBrowsers:new z.default.Flag,publicGridURL:new z.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new z.default.Flag(!0),unsupportedCapsFields:new z.default.Variant("[]"),useLinkedomToParseHtml:new z.default.Flag,dontFocusOnInit:new z.default.Flag},z.default.register("default",this.flags)}setProjectId(e){z.default.setCustomStringProperty("projectId",e)}setProjectType(e){z.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){z.default.setCustomStringProperty("productType",e)}setCompanyId(e){z.default.setCustomStringProperty("companyId",e)}setPlanType(e){z.default.setCustomStringProperty("planType",e)}setIsPOC(e){z.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){z.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){z.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!kv)return;let e={fetchIntervalInSec:Cv,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return ne(z.default.setup(Yp,e),Pv).catch(t=>df.error("failed to get feature flag status",t))}},M=new Hl});var ff,gf,Zt,hf,yf,mf,Av,Ov,Yo,_v,Lv,Z,Xo=T(()=>{"use strict";ff=E(require("ms")),gf=E(require("p-retry")),Zt=E(require("os")),hf=E(require("portfinder")),yf=E(require("child_process"));j();at();be();V();U();Uo();ie();Te();mf=x("lambdatestService"),Av="https://downloads.lambdatest.com/tunnel/v3",Ov={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"},Yo=`${Zt.tmpdir()}/LT`,_v=`${Yo}/LT`,Lv=(0,ff.default)("15m"),Z=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===W.LAMBDATEST||e.type===W.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){Z.isLambdatestGrid(e)&&(Z.lambdatestConfigPromise||(Z.lambdatestConfigPromise=nl()),Z.lambdatestConfig=await Z.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?Lv:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ye(_v))return;let t=Ov[Zt.platform()+Zt.arch()];if(!t)throw new Error(`tunnel on ${Zt.platform()+Zt.arch()} platform is not supported.`);let s=`${Yo}.zip`;await qe(`${Av}/${t}`,s),await Ze(s,Yo)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){Z.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await hf.getPortPromise(),{gridData:s={},gridUsername:n,gridPassword:o}=e,i=global.proxyUri;Z.tunnelName=J();let a=["--tunnelName",Z.tunnelName,"--infoAPIPort",String(t)];if(e.externalLambdatestUseWss&&(a=[...a,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(a=[...a,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),s.tunnelUser&&s.tunnelKey)a=[...a,"--user",s.tunnelUser,"--key",s.tunnelKey];else if(n&&o)a=[...a,"--user",n,"--key",o];else throw new k("tunnel requires username and password");if(i)try{let p=new URL(i);a=[...a,"--proxy-host",p.hostname],p.port&&(a=[...a,"--proxy-port",p.port]),p.username&&p.password&&(a=[...a,"--proxy-user",p.username,"--proxy-pass",p.password])}catch{throw new k("proxy url is invalid")}e.externalLambdatestMitm&&(a=[...a,"--mitm"]),Z.tunnel=yf.spawn("./LT",a,{cwd:Yo});let c="",l="";Z.tunnel.stdout.on("data",p=>{c+=p.toString()}),Z.tunnel.stderr.on("data",p=>{l+=p.toString()});try{let p=await(0,gf.default)(()=>Ot(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});mf.info("LT tunnel info",p)}catch(p){throw mf.error("Failed to start LT tunnel",{err:p,stdoutResult:c,stderrResult:l}),p}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!Z.tunnel))return new Promise((t,s)=>{Z.tunnel.on("close",n=>{n&&s(new Error(`tunnel process exited with code ${n}`)),t()}),Z.tunnel.kill()})}getCapabilities(e,t,s,n,o){if(!this.isActive)return{};let i=Z.lambdatestConfig.CAPABILITIES[t]||{},a={...Z.tunnelName&&{tunnel:!0,tunnelName:Z.tunnelName}},c=[],{mode:l,canary:p,ext:m,extensionPath:d,installCustomExtension:g}=e;if(l===Y.EXTENSION&&!m){let f=Rl({canary:p},!0);!d&&f[t]&&(c=[...c,f[t]]),d&&We(d)&&(c=[...c,d])}return g&&We(g)&&(c=[...c,g]),{build:s,name:`${n} - ${o}`,platform:Z.lambdatestConfig.PLATFORM,selenium_version:Z.lambdatestConfig.SELENIUM_VERSION,resolution:Z.lambdatestConfig.RESOLUTION,timezone:Z.lambdatestConfig.TIMEZONE,...i,loadExtension:c,...a,console:!0,queueTimeout:300,network:M.flags.LTNetworkCapabilities.isEnabled()}}}});var Gl={};$(Gl,{connect:()=>Zo,disconnect:()=>ei,serveTunneling:()=>Nv});var Qo,bf,Tf,Dv,Zo,ei,Nv,Vl=T(()=>{"use strict";of();ln();uf();Rt();Qo=E(require("ora"));U();ie();Xo();bf=x("tunnel"),Tf=r=>{var e;return[W.LAMBDATEST,W.HYBRID].includes((e=r.gridData)==null?void 0:e.type)&&r.gridData.tunnel==="lambdatest"},Dv=r=>{var e;return r.tunnelRoutes||((e=r.gridData)==null?void 0:e.type)===W.HYBRID&&r.gridData.tunnel==="cloudflare"},Zo=async r=>{if(!r.tunnel)return;let e=Mt(),t;try{Tf(r)?(t=(0,Qo.default)("Starting testim lambdatest tunnel...").start(),await Z.connectTunnel(r)):Dv(r)?(t=(0,Qo.default)("Starting testim cloudflare tunnel...").start(),await cf(r)):(t=(0,Qo.default)("Starting testim ngrok tunnel...").start(),await sf(r,e)),t.succeed()}catch(s){let n="Failed to start tunnel. Please contact support@testim.io";throw bf.error("Failed to open tunnel",{err:s}),t==null||t.fail(n),new Error(n)}},ei=async r=>{if(r.tunnel)try{Tf(r)?await Z.disconnectTunnel(r):"tunnelRoutes"in r?await lf(r):await nf(r)}catch(e){let t="catch error - failed to close tunnel";throw bf.error(t,{err:e}),new Error(t)}},Nv=async(r,e=new Promise(()=>{}))=>(await Zo(r),is(()=>ei(r)),await e)});function Mv(r){if(r.protocol)return r.protocol;if([W.TESTIM,W.BROWSERSTACK,W.SAUCELABS].includes(r.type)&&r.port===443)return"https";if([W.TESTIM_ENTERPRISE,W.LAMBDATEST,W.DEVICE_FARM].includes(r.type)){let e=wf.exec(r.host);return(e==null?void 0:e[2])||"https"}return""}function Fv(r){let e=wf.exec(r);return e==null?void 0:e[3]}function ri(r){var y,w,S,b,v,I,A,_,R;let e=r&&Fv(r.host),t=r==null?void 0:r.port,s=r==null?void 0:r.path,n=r&&Mv(r),o=r==null?void 0:r.token,i=r==null?void 0:r.slotId,a=(y=r==null?void 0:r.hybrid)==null?void 0:y.tunnel,c=(w=r==null?void 0:r.external)==null?void 0:w.user,l=(S=r==null?void 0:r.external)==null?void 0:S.key,p=r==null?void 0:r.type,m=p===W.HYBRID?a&&((I=(v=(b=r.hybrid)==null?void 0:b.external)==null?void 0:v[r.hybrid.tunnel])==null?void 0:I.user):c,d=p===W.HYBRID?a&&((R=(_=(A=r.hybrid)==null?void 0:A.external)==null?void 0:_[r.hybrid.tunnel])==null?void 0:R.key):l,g=r==null?void 0:r.name,f=r&&(r._id||r.gridId),h=r==null?void 0:r.provider;return{host:e,port:t,path:s,protocol:n,accessToken:o,slotId:i,gridId:f,tunnel:a,user:c,key:l,type:p,name:g,provider:h,tunnelUser:m,tunnelKey:d}}async function Ef(r,e,t,s,n){let o;try{o=await n()}catch(i){throw Je.error("failed to get grid",{projectId:r,companyId:e,err:i}),new Error(Kr.UNKNOWN)}if(Je.info("get grid info",Object.assign({},o,{projectId:r,companyId:e})),!o||!["success","error"].includes(o.status))throw Je.error("invalid response - get grid",{res:o}),new Error(Kr.UNKNOWN);if(o.status==="success"){let i=ri(o.grid);return Uv(t,e,i.gridId,i.slotId,s),i}throw o.code==="not-found"?new wt(Kr.NOT_FOUND):o.code==="no-available-slot"?new Hr(`Failed to run test on ${s} - concurrency limit reached`):(Je.error("invalid code error response - get grid",{res:o}),new wt(Kr.UNKNOWN))}function jv(r,e,t,s,n,o){return Ef(t,e,r,n,()=>_o(e,t,s,n,o))}function Bv(r,e,t,s,n,o,i){return Ef(t,e,r,n,()=>{var l;let c=(l=i.allGrids)==null?void 0:l.find(p=>(p.name||"").toLowerCase()===s.toLowerCase());return c!=null&&c._id?_o(e,t,c._id,n,o):tl(e,t,s,n,o)})}function Sf(r){return sl(r)}async function Rf(r,e,t){let n=(t||await Sf(r)).find(o=>o._id===e);if(!n)throw new k(`Failed to find grid id: ${e}`);return ri(n)}async function $v(r,e,t){let n=(t||await Sf(r)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new k(`Failed to find grid name: ${e}`);return ri(n)}async function ql(r,e){let t=mn[r];if(!t)return;let{slotId:s,gridId:n,browser:o,companyId:i}=t;if(delete mn[r],!s){Je.warn("failed to find grid slot id",{projectId:e});return}Je.info("release slot id",{projectId:e,companyId:i,slotId:s,gridId:n,browser:o});try{await Zc(i,e,s,n,o)}catch(a){Je.error("failed to release slot",{projectId:e,err:a})}}async function Wv(r){let e=Object.values(mn).filter(Boolean);if(e.length!==0){Je.info("keep alive worker slots",{projectId:r,slots:e});try{await Qc(r,e)}catch(t){Je.error("failed to update grid keep alive",{err:t,slots:e,projectId:r})}}}function Hv(r){vf=global.setInterval(Wv,1e4,r)}async function Gv(r){let e=Object.keys(mn);if(e.length){Je.warn("not all slots released before end runner flow",{projectId:r});try{await ce(e,t=>ql(Number(t),r))}catch(t){Je.error("failed to release all slots",{err:t,projectId:r})}}}async function Vv(r){await Gv(r),clearInterval(vf)}function qv(r,e){let{testobjectSauce:t,saucelabs:s}=e;if(r==="testobject")return t.testobjectApiKey;if(r==="saucelabs")return s.accessKey}function zv(r,e){let{saucelabs:t}=e;if(r==="saucelabs")return t.username}function If(r){let t=(()=>ti.isEmpty(r.testobjectSauce)?ti.isEmpty(r.saucelabs)?ti.isEmpty(r.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:s,port:n,path:o,protocol:i}=r,a=qv(t,r),c=zv(t,r);return{host:s,port:n,path:o,protocol:i,type:t,user:c,key:a}}async function xf(r,e){let t=r.company.companyId;return await Rf(t,e.gridId,r.allGrids)}async function kf(r){let{allGrids:e=void 0,company:t,host:s,useLocalChromeDriver:n,useChromeLauncher:o,gridId:i,grid:a}=r;if(n||o)return{mode:"local"};if(s)return If(r);let c=t==null?void 0:t.companyId;if(i)return Rf(c,i,e);if(a)return $v(c,a,e);if(Vs(r)||r.tunnelOnlyMode){Je.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new wt("Missing host or grid configuration")}async function Pf(r,e,t,s){return await(async()=>{let{host:i,project:a,grid:c,gridId:l,useLocalChromeDriver:p,useChromeLauncher:m,company:d}=t,g=d==null?void 0:d.companyId;if(p||m)return{mode:"local"};if(i)return If(t);if(l)return jv(s,g,a,l,r,e);if(c)return Bv(s,g,a,c,r,e,t);throw new wt("Missing host or grid configuration")})()}var ti,Je,mn,wf,vf,Uv,fn,Cf,ds=T(()=>{"use strict";ti=E(require("lodash"));be();U();j();ie();V();Je=x("grid-service"),mn={},wf=/(^(https?):\/{2})?(.*)/,vf=null;Uv=(r,e,t,s,n)=>{mn[r]={gridId:t,companyId:e,slotId:s,browser:n}};fn={start:Hv,end:Vv};Cf=async(r={},e={},t={},s={},n={})=>{var f,h,y;let{company:{companyId:o}={}}=r,{gridId:i,type:a}=e,c=r.browser||t.browserValue,l=Boolean(r.tunnel),{maxRetries:p,currentRetry:m}=n;if(!i||!a||(a===W.LAMBDATEST&&await((f=s.enableIfNeeded)==null?void 0:f.call(s,e)),a!==W.HYBRID||!o||!c||!p||!m))return e;let d=await el({companyId:o,gridId:i,maxRetries:p,currentRetry:m,browser:c,usingTunnel:l});Je.info("handling hybrid grid",{response:d,companyId:o});let g=ri({...e,...d.connectionDetails,provider:d.provider});return d.provider!=="lambdatest"&&((h=s.disable)==null||h.call(s)),d.provider==="lambdatest"&&await((y=s.enableIfNeeded)==null?void 0:y.call(s,g)),g}});function hn(){return si||"master"}function Af(r="master",e="false"){if(typeof r!="string"&&(r!=null&&r.branch)&&r.branch==="master"){si="master";return}if(r&&!r.isArchived){si=r.branch||r;return}si=e?"master":void 0}var si,zl=T(()=>{"use strict"});var yn,Kl,Kv,Jl,Jv,Yl,ni,oi,ii,ai,ci,li=T(()=>{"use strict";j();ie();yn=r=>{let{status:e,sessionType:t,success:s,mobile:n}=r;return n!=null&&n.isAppFromDevice||n!=null&&n.isAppForIosVirtualDevice||n!=null&&n.isMissingBrowserStackAppId?!1:e===de.FAILED||t===Lt.CODEFUL&&s===!1},Kl=r=>{let{status:e}=r;return e===de.ABORTED},Kv=r=>{let{status:e,sessionType:t,success:s}=r;return e===de.PASSED||t===Lt.CODEFUL&&s===!0},Jl=r=>r.runnerStatus===pc.SKIPPED,Jv=r=>r.testStatus===ze.EVALUATING,Yl=(r,e)=>e?!r.runConfig:!1,ni=(r,e)=>Object.values(r).filter(t=>{var s,n,o;return Jl(t)&&(Ke(t,e)||((s=t.mobile)==null?void 0:s.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice)||((o=t.mobile)==null?void 0:o.isMissingBrowserStackAppId))}).length,oi=r=>Object.values(r).filter(e=>yn(e)&&Jv(e)).length,ii=(r,e)=>Object.values(r).filter(t=>yn(t)&&!Yl(t,e)),ai=(r,e)=>Object.values(r).filter(t=>Kv(t)&&!Yl(t,e)),ci=(r,e)=>Object.values(r).filter(t=>Kl(t)&&!Yl(t,e))});function Yv(r){let e=r.indexOf("--token");if(e===-1&&(e=r.indexOf("--t")),e!==-1)try{let t=r.slice();return t.splice(e,2),t}catch{}return r}var ui,_f,pi,Lf=T(()=>{"use strict";U();li();ui=x("debug-reporter"),_f={token:void 0,userParamsData:void 0,projectData:void 0,allGrids:void 0,gridData:void 0,awsAccessKeyId:void 0,awsSecretAccessKey:void 0,runParams:void 0,perfecto:void 0,testobjectSauce:void 0},pi=class{constructor(e){this.options=e}onTestStarted(e,t){ui.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let s=this.options.gridData||{},n=s.provider,o=s.host,i=s.gridId,a=s.type,c=s.failedGetBrowserAttempts;ui.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:o,failedGetBrowserAttempts:c,id:i,type:a},workerId:t})}onTestPlanStarted(e,t,s,n,o,i,a){let c=Yv(process.argv);ui.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:Object.assign({},this.options,_f),args:c})}onTestPlanFinished(e,t,s,n,o,i){let a=ai(e,i).length,c=Object.keys(e).length-a;ui.info("Test Plan Finished",{isAnonymous:o,passed:a,failed:c,testPlanName:t,options:Object.assign({},this.options,_f),duration:s,executionId:n})}}});var Xl,xt,bn=T(()=>{"use strict";ie();Xl=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===W.DEVICE_FARM}},xt=new Xl});var Zl={};$(Zl,{Reporter:()=>Xv});var er,Tn,xr,di,Df,Ql,Xv,eu=T(()=>{"use strict";er=E(require("chalk")),Tn=E(require("lodash"));j();ie();bn();li();xr={success:er.default.green,warn:er.default.yellow,error:er.default.red},{CLI_MODE:di}=Dt,Df="device",Ql=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,s,n){let o=n?"File":"Test",i=e.isTestsContainer?"":`(${e.testId})`,a=e.isTestsContainer?"":`url: ${er.default.underline(nt(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`${o} "${e.name}" started ${i} ${a}`.trim())}onTestFinished(e,t,s,n){if(n)return;let o=e.success?de.PASSED:de.FAILED,i=e.isTestsContainer?" ":`(${e.testId})`,a=xr[e.success?"success":"error"];console.log(a(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${o} ${i} duration: ${ao(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(s=>{let n=nt(this.options.editorUrl,this.options.project,s.testId,s.resultId,this.branchToUse);return s.isTestsContainer?s.name:`${s.name} : ${n}`});console.log(xr.error("Failed runs are:")),console.log(xr.error(t.join(`
|
|
27
|
-
\r`)))}onTestPlanFinished(e,t,s,n,o,i){let a=ii(e,i),c=ai(e,i),l=ci(e,i),p=c.length,m=l.length,d=a.length,g="",f="";if(xt.isTestStatusEnabled){let b=oi(e);g=` FAILED-EVALUATING: ${b}`,d-=b,f=` SKIPPED: ${ni(e,this.options)}`}let h=this.buildTestPlanName(o,t,i),y,w=xr[d?"error":"success"],S=`PASSED: ${p} FAILED: ${d}${g} ABORTED: ${m}${f} Duration: ${ao(s)}`;i||h.trim()===""||h.trim()==="Anonymous"?y=`Tests completed. ${S} (Execution ID: ${n})`:y=`Test plan${h} completed ${S} (${n})`,this.printWorkerDivider(),console.log(w(y)),this.printWorkerDivider(),this.printAllFailedTests(a)}buildTestPlanName(e,t,s){if(s)return"";let n=Tn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,o=Tn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=Tn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,a=Tn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,c=[i,o,n,a].filter(Boolean).join(", ");return e?` anonymous (${c})`:` '${t}'`}onTestPlanStarted(e,t,s,n,o,i,a,c){let l=d=>{d.forEach((g,f)=>{var w;let h=(w=g.testData)!=null&&w.index?`- ${g.testData.index} / ${g.testData.total} Data set`:"",y=c?"":`(${g.testId})`;console.log(" ",f+1,":",`${g.name}${Ke(g,this.options)?"-quarantine":""}`,y,h)})},p=a?`config '${a}'`:"default configs";if(c)console.log(`Run test plan, Project: ${this.options.project} (Execution ID: ${o}):`);else{let d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",g=`${p}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${g} (${o})`)}this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log(c?"File list:":"Test list:"),l(t),s.length>0&&(console.log("After all:"),l(s)),this.printWorkerDivider()}onGetSlot(e,t){let s=this.options.grid||this.options.gridId,n=this.options.mode===di.APPIUM?Df:t;s&&console.log(this.toWorkerIdPrefix(e),`Get ${er.default.underline(n)} slot from ${er.default.underline(s)}`)}onGetSession(e,t,s){let n=s===di.APPIUM?Df:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${er.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e,t,s){let n=t?"file":"test";console.log(this.toWorkerIdPrefix(e),`Wait for ${n} complete`),s&&t&&console.log(this.toWorkerIdPrefix(e),`Chrome Debugger available at ${s}`)}onGetBrowserFailure(e,t,s){if(s!==2)return;let n=this.options.grid||this.options.gridId,o=this.options.mode===di.APPIUM?"device":"browser";if(n)console.log(xr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${o} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(xr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===di.APPIUM?"Appium":"Selenium";console.log(xr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},Xv=Ql});var su={};$(su,{Reporter:()=>sE});function Qv(r){let e=r.testData||{},t=typeof e.total=="number"?` - ${e.index} / ${e.total} Data set`:"";return`${r.name}${t}`}function Zv(r){return r.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${r.visitedUrlsList||""}`}function eE(r){return`${r.visitedUrlsJson||""}`}async function tE(r,e,t,s,n,o){function i(d){let g=nt(r,t,d.testId,d.resultId,s),f={$:{name:Qv(d),classname:n,time:bc(d.duration),ownedBy:d.testOwnerName,ownerEmail:d.testOwnerEmail},"system-out":g};if(yn(d)||Kl(d)){let h=`Step Failed: ${d.failureReason||d.reason}`,y=yn(d)?`${h} More info at: ${g}`:h;f.failure={$:{message:y}}}return Jl(d)&&Ke(d,o)&&xt.isTestStatusEnabled&&(f.skipped={}),o.urls&&(f["visited-urls-list"]=Zv(d),f["visited-urls-json"]=eE(d)),f}function a(d){let{results:g,testPlanName:f,configName:h}=d,y=g||{},S={name:(h&&f?`${f} with config '${h}'`:f)||"selenium run",tests:l(y),failure:p(y),timestamp:c(e)};if(xt.isTestStatusEnabled){S.skipped=ni(y,o);let b=oi(y);S.failure-=b,S["failure-evaluating"]=b}return{$:S,testcase:Object.keys(y).map(b=>i(y[b]))}}function c(d){let g=Object.keys(d).map(h=>d[h].startTime),f=Math.min.apply(null,g);return f?new Date(f).toISOString():new Date().toISOString()}function l(d){return Object.keys(d).length}function p(d){return ii(d).length+ci(d).length}let m={testsuites:{testsuite:e.map(d=>a(d))}};try{return new ru.Builder().buildObject(m)}catch(d){return rE(d)}}function rE(r){let e=new ru.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:r.message}}}}}};return e.buildObject(t)}var ru,Nf,tu,sE,nu=T(()=>{"use strict";ru=E(require("xml2js"));j();Nf=require("fs");bn();li();tu=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,s=this.options.project,n=await tE(this.options.editorUrl,e,s,this.branchToUse,this.classname,this.options);if(t)try{return await Nf.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(o){return console.error("could not save report file",t,o),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};sE=tu});var Mf={};$(Mf,{Reporter:()=>nE});function ms(r){return r?r.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var ou,iu,nE,Ff=T(()=>{"use strict";U();ou=x("team-city-reporter");iu=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},s=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${s}`;return ms(n)}onTestStarted(e,t,s,n,o){if(s){ou.debug("skip report test started because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testStarted name='${i}' captureStandardOutput='true' flowId='${o}']`)}onTestFailed(e,t,s,n,o,i){if(o){ou.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ms(t)}' details='${ms(s)}' flowId='${i}']`)}onTestFinished(e,t,s){if(s){ou.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,s="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${ms(s)}']`)}onTestPlanStarted(e,t,s,n){console.log(`##teamcity[testSuiteStarted name='${ms(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ms(t)}']`)}},nE=iu});var Uf={};$(Uf,{Reporter:()=>oE});var au,oE,jf=T(()=>{"use strict";au=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,s,n,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},oE=au});var Bf={};$(Bf,{Reporter:()=>iE});var cu,iE,$f=T(()=>{"use strict";j();Il();cu=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e,t,s,n){if(n)return;let o=nt(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Bo(o)}},iE=cu});var aE,lu,Q,jt=T(()=>{"use strict";Lf();U();aE=x("reporter"),lu=class{constructor(){this.reporters=[];this.onGetBrowserFailure=this.generateHook("onGetBrowserFailure");this.onGetBrowserSuccess=this.generateHook("onGetBrowserSuccess");this.onTestPlanStarted=this.generateHook("onTestPlanStarted");this.onGetSlot=this.generateHook("onGetSlot");this.onGetSession=this.generateHook("onGetSession");this.onTestFinished=this.generateHook("onTestFinished");this.onTestFailed=this.generateHook("onTestFailed");this.onTestPassed=this.generateHook("onTestPassed");this.onTestStarted=this.generateHook("onTestStarted");this.onTestIgnored=this.generateHook("onTestIgnored");this.onWaitToTestStart=this.generateHook("onWaitToTestStart");this.onWaitToTestComplete=this.generateHook("onWaitToTestComplete");this.onTestPlanFinished=this.generateHook("onTestPlanFinished",this.onTestPlanFinishedMutator);this.onAllTestPlansFinished=this.generateHook("onAllTestPlansFinished",this.onAllTestPlansFinishedMutator)}async setOptions(e,t){this.reporters=[];let s=e.reporters;if(this.reporters.push(new pi(e)),s===void 0||s.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(eu(),Zl));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(nu(),su));this.reporters.push(new o(e,t))}}else(await Promise.all([s.includes("teamcity")&&Promise.resolve().then(()=>(Ff(),Mf)),s.includes("console")&&Promise.resolve().then(()=>(eu(),Zl)),s.includes("junit")&&Promise.resolve().then(()=>(nu(),su)),s.includes("json")&&Promise.resolve().then(()=>(jf(),Uf)),s.includes("chrome")&&Promise.resolve().then(()=>($f(),Bf))])).forEach(o=>{o&&this.reporters.push(new o.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,s,n,o,i,a){let c={};if(a){let p=Object.values(a);if(p.length>0){for(let m of Object.values(a))c[m.id]=m;for(let m of Object.keys(e))p.some(d=>d.parentResultId!==m)||(c[m]=e[m])}else aE.warn("childTestResults is not array"),c=e}else c=e;let l=Date.now()-(s||0);return[c,t,l,n,o,i,void 0]}onAllTestPlansFinishedMutator(e){for(let t of e)if(t.childTestResults){t.results={};let s=Object.values(t.childTestResults);for(let n of s)t.results[n.id]=n;for(let n of Object.keys(e))s.some(o=>o.parentResultId!==n)||(t.results[n]=e[n])}return[e]}generateHook(e,t){return async(...s)=>{var o;let n=t==null?void 0:t(...s);for(let i of this.reporters)await((o=i[e])==null?void 0:o.call(i,...n||s))}}},Q=new lu});function Hf(r,e){return e!=null&&e.type&&(r[`${e.type}Mode`]=!0),r}function Gf({executionId:r,projectId:e,testId:t,resultId:s,companyId:n,companyName:o,projectName:i,companyPlan:a,sessionType:c,source:l,user:p,lightweightMode:m,isStartUp:d,projectType:g,appSource:f}){let h=Hf({executionId:r,projectId:e,testId:t,resultId:s,companyId:n,companyName:o,projectName:i,companyPlan:a,sessionType:c,source:Wf(l,p),isStartUp:d,projectType:g,...["android","ios"].includes(g)&&f&&{appSource:f}},m);ut("test-run-ci",h)}function Vf({executionId:r,projectId:e,testId:t,resultId:s,result:n,companyId:o,companyName:i,projectName:a,companyPlan:c,sessionType:l,source:p,user:m,lightweightMode:d,logger:g,isStartUp:f,projectType:h,appSource:y}){try{let w=Hf({executionId:r,projectId:e,testId:t,resultId:s,companyId:o,companyName:i,projectName:a,companyPlan:c,sessionType:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:Wf(p,m),isStartUp:f,projectType:h,...["android","ios"].includes(h)&&y&&{appSource:y}},d);if(n.success){ut("test-run-ci-success",w);return}ut("test-run-ci-fail",Object.assign({},w,{failureReason:n.failureReason}))}catch(w){g.error("failed to update test end analytics",{err:w})}}function qf({executionId:r,projectId:e,sessionType:t}){ut("batch-run-ci",{executionId:r,projectId:e,sessionType:t})}var Wf,uu=T(()=>{"use strict";cs();Co();Wf=(r,e)=>r!=="cli"&&r!=="cli-local"?r:ss&&e?"ci-with-user":ss?"ci":e?"cli-with-user":r});var Kf,mi,Jf=T(()=>{"use strict";Kf=require("istanbul-lib-report"),mi=class extends Kf.ReportBase{constructor(t){super();t||(t={}),this.appendToObject=t.appendToObject||{}}onStart(t){let s=t.getCoverageSummary(!1);this.appendToObject=Object.assign(this.appendToObject,s.toJSON())}}});var Yf,Xf,Qf,wn,mt,Zf,fi,pu,eg,cE,tg,rg,lE,uE,sg,pE,dE,mE,fE,gE,ng,og=T(()=>{"use strict";Yf=E(require("ora")),Xf=E(require("moment")),Qf=E(require("test-exclude")),wn=E(require("fs")),mt=E(require("path")),Zf=E(require("istanbul-reports")),fi=E(require("istanbul-lib-report"));be();V();j();U();dt();Jf();pu=x("test-run-status"),eg=r=>{try{return new URL(r)}catch{try{return new URL(`file://${r}`)}catch{return{}}}},cE=r=>!!eg(r).search,tg=r=>r?eg(r).pathname.substring(1):"",rg=(r,e)=>{let t=tg(e);return!new Qf.default({relativePath:!1,include:r}).shouldInstrument(t)},lE=r=>r.substring(0,r.indexOf("?")),uE=async({source:r,sourceMapDir:e,sourceMapType:t})=>{let s=await le("convert-source-map");if(t==="file"&&!e)throw new k("--code-coverage-source-map-path [path]");return e?s.fromMapFileSource(r,e):s.fromSource(r)},sg=(r,e)=>`${mt.resolve(r,tg(e))}.js`,pE=async(r,e,t)=>{let{codeCoverageInclude:s}=r;await ce(Object.values(t),async n=>{if(!n)return;let o=n.toObject();await ce(o.sources,async(i,a)=>{if(rg(s,i))return;let c=sg(e,i);await wn.promises.mkdir(mt.parse(c).dir,{recursive:!0}),await wn.promises.writeFile(c,o.sourcesContent[a])})})},dE={getPath(r){if(typeof r=="string")return r;let e=r.getQualifiedName();return r.isSummary()?e!==""?e+="/index.html":e="index.html":(cE(e)&&(e=lE(e)),e+=".html"),e},relativePath(r,e){let t=this.getPath(e),s=mt.dirname(this.getPath(r));return mt.posix.relative(s,t)},assetPath(r,e){return this.relativePath(this.getPath(r),e)}},mE=async(r,e,t,s)=>{let{codeCoverageReporter:n}=r,o={},i=fi.createContext({dir:t,coverageMap:e,watermarks:fi.getDefaultWatermarks(),sourceFinder:a=>{try{let c=sg(s,a);return wn.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new mi({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:dE}),Zf.create(a,c).execute(i)}),o},fE=async(r,{source:e,sourceMap:t,functions:s})=>{let{codeCoverageInclude:n}=r;if(!t||t.sourcemap.sources.length===0)return;let i=(await le("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>rg(n,a));return await i.load(),i.applyCoverage(s),i.toIstanbul()},gE=async(r,e)=>{let{mergeProcessCovs:s}=await le("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await on(r,"testResult",`runId=${e}`)).data.docs;return await ce(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await nn(c,9e4);await ce(l,async p=>{if(!o.has(p.url)){let m=p.text;p.sourceUrl&&(o.set(p.url,"TEMP"),m=await $c(p.sourceUrl)),o.set(p.url,{text:m,url:p.url,sourceMapType:p.sourceMapType,hash:p.hash})}delete p.text,n=s([n,{result:[p]}])})},{concurrency:20}),{covUrlMap:o,mergedCoverages:n}},ng=async(r,e,t,s)=>{if(!r.collectCodeCoverage)return;pu.info("start js coverage process");let n=(0,Yf.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=mt.resolve(r.codeCoverageReportPath||"./coverage"),i=mt.resolve(o,`.js/${(0,Xf.default)().format("DDMMYYYYHHmmss")}`),a=r.codeCoverageSourceMapPath?mt.resolve(r.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:p}]=await Promise.all([le("istanbul-lib-coverage"),gE(r.project,s)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}pu.info("start js coverage merge and remap",{numOfFiles:p.size,numMergedCoverages:l.result.length});let m=c.createCoverageMap({}),d={};await ce(l.result,async({url:f,functions:h})=>{let{text:y,sourceMapType:w}=p.get(f),S=await uE({sourceMapType:w,source:y,sourceMapDir:a});d[f]=S;let b=await fE(r,{source:y,sourceMap:S,functions:h});m.merge(b)}),await pE(r,i,d);let g=await mE(r,m,o,i);return n.succeed(),g}catch(c){let l="Failed to report coverage information";c instanceof k?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),pu.error(l,{err:c})}}});var ig={};$(ig,{SELENIUM_PERF_MARKS:()=>Ce,SeleniumPerfStats:()=>Bt});var Ce,Bt,fs=T(()=>{"use strict";j();Ce={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Bt=class{constructor(){this.marks=Object.fromEntries(Object.values(Object.assign({ALL:"ALL"},Ce)).map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=J();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let s=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(s);return}this.marks[t].push(s)}getStats(){let e=Object.entries(this.marks).flatMap(([t,s])=>!Array.isArray(s)||!s.length?[]:[[`${t}_COUNT`,s.length],[`${t}_P50`,uo(s,50)],[`${t}_P95`,uo(s,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var ug={};$(ug,{initServer:()=>bE,mapFilesToLocalDrive:()=>mu});function mu(r,e){var t;try{r.failurePath=(r.failurePath||[]).map(s=>Object.assign(s,gi[s.id]?{screenshot:gi[s.id]}:{})),Object.keys(gs).forEach(s=>{r.assets||(r.assets={}),r.assets[lg[s]]=gs[s]}),r.assets||(r.assets={}),r.assets.screenshots=Object.values(gi)}catch(s){e&&e.error("failed to map files to local drive",{err:s}),r.failurePath||(r.failurePath=[]),r.assets||(r.assets={}),(t=r.assets).screenshots||(t.screenshots=[])}}async function bE({agentPort:r,agentBind:e,saveRCALocally:t}){let s=await le("multer"),n=typeof t=="string"?t:hE;await du.promises.mkdir(n,{recursive:!0});let o=s({storage:s.diskStorage({async destination(c,l,p){let m=JSON.parse(c.body.metadata||"{}");if(!m.testResultId)return p(new Error("missing testResultId"),"");let d=vn.join(n,m.testResultId);try{await du.promises.mkdir(d,{recursive:!0})}catch(g){return p(g,"")}return p(null,d)},filename(c,l,p){let{fileName:m}=c.body,d=JSON.parse(c.body.metadata||"{}");if(!d.stepId&&!m)return p(new Error("missing stepId or fileName"),"");if(d.stepId){let g=vn.extname(m);return p(null,`step_${d.stepId}_${d.stepName||""}${g}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return p(null,m)}})}),i=(0,cg.default)();i.post("/",o.single("file"),(c,l)=>{var m;let p=JSON.parse(c.body.metadata||"{}");p.stepId&&(gi[p.stepId]=c.file.path),p.testResultId&&yE.includes(p.subType)&&(gs[m=p.subType]||(gs[m]=[]),gs[p.subType].push(c.file.path)),l.sendStatus(200)}),i.use((c,l)=>l.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,l)=>{let p=a(i);p.listen(r,e),p.on("error",m),p.on("listening",()=>c(p.address()));function m(d){if(d.syscall!=="listen")return l(d);switch(d.code){case"EACCES":case"EPERM":return l(new k(`Port ${r} requires elevated privileges`));case"EADDRINUSE":return l(new k(`Port ${r} is already in use`));default:return l(d)}}})}var du,ag,vn,cg,hE,gi,gs,lg,yE,fu=T(()=>{"use strict";du=E(require("fs")),ag=E(require("os")),vn=E(require("path")),cg=E(require("express"));V();dt();hE=vn.join(ag.tmpdir(),"testim/rca/"),gi={},gs={},lg={"test-log":"consoleLogs","har-file":"networkLogs"},yE=Object.keys(lg)});var tr,gu,hi,pg=T(()=>{"use strict";tr=E(require("lodash"));j();U();gu=x("override-test-data-builder"),hi=class{constructor(e,t,s){this.params=e;this.testInfoList=t;this.projectId=s}isObjectNotArray(e){return tr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&typeof e.overrideTestData<"u"&&(this.isObjectNotArray(e.overrideTestData)&&!tr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(s=>this.overrideSingleTest(s,e.overrideTestData[s])),delete e.overrideTestData):gu.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&typeof e.overrideAllTestsData<"u"&&(tr.isObject(e.overrideAllTestsData)&&!tr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):gu.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:s}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}gu.error("skip override test data to test name",{testName:e,projectId:s}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let s=this.mapTestListToUniqueId(e);if(s.length!==0)return this.createNewTestPerOverrideTestData(s,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return tr.chain(t).map(s=>{if(s.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(s)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:s}=this;return[...new Set(e)].map(n=>{let o=s.map(p=>this.generateTestUniqId(p)),i=o.indexOf(n),a=o.lastIndexOf(n),c=s[i],l=this.createNewTestItems(c,t);return s.splice(i,a-i+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((s,n)=>{let o=J();return Object.assign({},e,{resultId:o,testData:{value:s,index:n+1,total:t.length||1}})})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function yi(r,...e){if(!(!r||typeof r!="function"))try{return await r(...e)||{}}catch(t){throw Ye.warn("failed to run hook",{err:t}),new k(`failed to run hook promise ${t.message}`)}}var kr,Ye,TE,wE,vE,EE,bi,dg=T(()=>{"use strict";kr=E(require("lodash"));j();ie();ds();be();V();U();jt();ln();og();fs();fu();pe();Te();pg();bn();Ye=x("test-run-status"),TE=Tr(),wE=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,vE=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,EE=ot();bi=class{constructor(e,t,s,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new Bt;var a,c,l,p,m;(a=this.options).runParams||(a.runParams={}),this.fileUserParamsData=this.options.userParamsData;let o=Gs(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:eo||t.parallel||1,browser:o,gitBranch:TE,gitCommit:wE,gitRepoUrl:vE,runnerVersion:EE,gridHost:t.host||((c=t.gridData)==null?void 0:c.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:s,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(d=>d.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:i,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((p=t.gridData)==null?void 0:p.name),gridType:(m=t.gridData)==null?void 0:m.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:yr(t)},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:s,projectId:n,executionId:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:c,isTestsContainer:l,testId:p,name:m,testStatus:d,testCreatorName:g,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:y,testLabels:w,testSuites:S,allLabels:b}=a,v={originalTestResultId:t,previousTestResultId:s,config:kr.cloneDeep(c),testId:p,status:"QUEUED",name:m,resultId:e,isTestsContainer:l,retryCount:i,testStatus:d};return this.testRunStatus[e]=Object.assign({},v,{testCreatorName:g,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:y,testLabels:w,testSuites:S,allLabels:b}),ul({projectId:n,runId:o,testId:p,newResultId:e,originalTestResultId:t,previousTestResultId:s,testResult:v})}getAllTestResults(){return this.testRunStatus}testStart(e,t,s,n){let o=this.getTestResult(s);o.workerId=e;let i=this.options.files.length>0;return Q.onTestStarted(o,e,n,i,s),o}async updateTestStatusRunning(e,t,s){var l;let{project:n,remoteRunId:o,projectData:i}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Lo(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(p){Ye.error("failed to upload test data artifact (runner)",{err:p})}let c=kr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,os(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:o,testRetryKey:s})}async testStartReport(e,t,s){if(Ke(e,this.options))return;let n=this.exportsGlobal;try{let o=await yi(this.options.beforeTest,Object.assign({},e,{exportsGlobal:n,globalParameters:n}),this.options.userData.loginData.token);return e.config.testData=Object.assign({},e.config.testData,this.exportsGlobal,this.fileUserParamsData,this.beforeSuiteParams,o),this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,s),e}catch(o){throw Ye.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,s,n,o){let i=this.testStart(e,t,s,n);return this.testStartReport(i,t,o)}onGridSlot(e,t){let s=this.getTestResult(e);s.config.gridInfo=Object.assign({},t,{key:void 0,user:void 0}),Ye.info("on get grid info",{gridInfo:s.config.gridInfo})}reportTestStatus(e,t,s,n){let{name:o,testId:i,testStatus:a}=s,{resultId:c,success:l}=t;if(a===ze.EVALUATING&&xt.isTestStatusEnabled){Q.onTestIgnored(e,s,`test in ${ze.EVALUATING} status`);return}if(l){Q.onTestPassed(o);return}Q.onTestFailed(s,s.failureReason,nt(this.options.editorUrl,this.options.project,i,c,this.branchToUse),i,n,c)}calcResultText(e){return e.success?de.PASSED:de.FAILED}onTestIgnored(e,t){let s=this.getTestResult(t);Q.onTestIgnored(e,s,`test in ${ze.QUARANTINE}`)}monitorMemoryUsage(e){let t=Tc();if(t.isOverThreshold){let s=M.flags.useLinkedomToParseHtml.isEnabled()?"linkedom":"jsdom";Ye.info(`using ${s} to parse html`,{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}}testEnd(e,t,s,n,o){let i=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;i.sessionId=n,i.startTime=t.startTime||i.startTime||Date.now(),i.duration=a,t.duration=a,i.failureReason=t.failureReason||t.reason,t.failureReason=i.failureReason,i.failurePath=t.failurePath,i.resultId=t.resultId,i.success=t.success,this.options.saveRCALocally&&mu(i,Ye),i.resultUrl=nt(this.options.editorUrl,this.options.project,i.testId,i.resultId,this.branchToUse),i.status=this.calcResultText(t),t.status=i.status,t.name=i.name,t.testStatus=i.testStatus,t.testId||(t.testId=i.testId),t.testCreatorName=i.testCreatorName,t.testCreatorEmail=i.testCreatorEmail,t.testOwnerName=i.testOwnerName,t.testOwnerEmail=i.testOwnerEmail,t.testData=i.config&&typeof i.config.testDataTotal=="number"?{total:i.config.testDataTotal,index:i.config.testDataIndex}:{},this.reportTestStatus(e,t,i,o);let c=this.options.files.length>0;this.monitorMemoryUsage(i),Q.onTestFinished(i,e,o,c);let l=Object.assign({},this.exportsGlobal,t.exportsGlobal);return this.exportsGlobal=l,i}async testEndReport(e,t,s,n){var i;let o=s.exportsGlobal;try{try{await yi(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){Ye.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(i=this.options.lightweightMode)!=null&&i.onlyTestIdsNoSuite?void 0:await os(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:s.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw Ye.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,s,n,o,i){let a=this.testEnd(e,t,s,n,o);return this.testEndReport(a,s,t,i)}getMobileRunSkippedReason(e,t,s){let n="",{APP_FROM_DEVICE:o,VIRTUAL_BUILD:i,MISSING_BROWSERSTACK_APP_ID:a}=fc;return e&&(n=o),Jr(s)&&(n=i),t&&(n=a),n}calcTestRunStatus(){let{options:e,testInfoList:t}=this,s=e.company.companyId,n=t.map(o=>{var g,f,h,y,w,S;let i=e.browser?Js(e.browser,e.saucelabs,e.browserstack):o.runConfig;if(i&&M.flags.dec2022eolBrowsers.isEnabled()&&((g=Ks(i.browserValue))!=null&&g.eol))throw new k(`Unsupported Browser: ${i.browserName}`);let a=!M.flags.allowAppFromDeviceRuns.isEnabled()&&qs(o.nativeApp),l=((f=e.gridData)==null?void 0:f.type)===W.BROWSERSTACK&&!((h=o.nativeApp)!=null&&h.browserStackAppId),p=Yr(e)&&(Jr(o.nativeApp)||a||l),m=Ke(o,e)||p,d={testId:o.testId,status:m?de.SKIPPED:de.QUEUED,name:o.name,resultId:o.resultId,isTestsContainer:o.isTestsContainer,testStatus:o.testStatus||ze.DRAFT,testCreatorName:o.creatorName,testCreatorEmail:o.creatorEmail,testOwnerName:o.testOwnerName,testOwnerEmail:o.testOwnerEmail,testLabels:o.testLabels,testSuites:o.testSuites,allLabels:o.allLabels,...p&&{reason:this.getMobileRunSkippedReason(a,l,o.nativeApp)},config:Object.assign({},this.execConfig,{companyId:s,testData:((y=o.testData)==null?void 0:y.value)||null,isBeforeTestPlan:o.isBeforeTestPlan,isAfterTestPlan:o.isAfterTestPlan,testDataTotal:((w=o.testData)==null?void 0:w.total)||null,testDataIndex:((S=o.testData)==null?void 0:S.index)||null,baseUrl:e.baseUrl||o.baseUrl||o.testConfig.baseUrl,testConfig:o.overrideTestConfig||o.testConfig,browser:i.browserValue.toLowerCase()})};return[o.resultId,d]});return Object.fromEntries(n)}async executionStart(e,t,s,n,o){Ye.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:c}=i;is(()=>Promise.all([fn.end(t),Oo("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=s||Date.now();let l={projectId:t,executionId:e,...M.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},p=await yi(i.beforeSuite,l),m=new hi(p,kr.cloneDeep(this.testInfoList),t);this.testInfoList=m.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=p;let{testInfoList:d}=this,g=[],f=[],h=[];for(let w of d){if(w.isBeforeTestPlan){g.push(w);continue}if(w.isAfterTestPlan){h.push(w);continue}f.push(w)}let y=async()=>{let w=kr.cloneDeep(this.testRunStatus);await ce(Object.keys(w),async I=>{var C;let A=w[I],_=(C=A.config)==null?void 0:C.testData,R=A.testId,L=await Lo(t,R,I,_,c.defaults);L&&(delete A.config.testData,A.config.testDataUrl=L)});let S=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),b={executionId:e,projectId:t,labels:n||[],startTime:s,executions:w,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:S,intersections:i.intersections},v=qc(b);return this.executionStartedPromise=v,v.catch(I=>Ye.error(I)),v};try{await y()}catch(w){Ye.error("Failed to start suite",{err:w}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:f,afterTests:h}}concatSeleniumPerfMarks(e){kr.chain(e).keys().each(t=>{let s=t;this.seleniumPerfStats.marks[s]&&(this.seleniumPerfStats.marks[s]=[...this.seleniumPerfStats.marks[s],...e[s]])}).value()}async executionEnd(e){var p;let t=vc(this.testRunStatus),s=t.length,n=0,o=0,i=0;for(let{status:m,testStatus:d}of t)m===de.PASSED&&n++,m===de.SKIPPED&&o++,m===de.FAILED&&d===ze.EVALUATING&&i++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await yi(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:s,passed:n,skipped:o})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Ye.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await ng(this.options,this.branchToUse,s,e);if(Object.assign(c,{coverageSummary:l}),!((p=this.options.lightweightMode)!=null&&p.onlyTestIdsNoSuite))try{return await Oo("FINISHED",e,this.options.project,s===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(m){throw Ye.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,s,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await Vc(e,["QUEUED"],t,s,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=s,a.success=n}return this.testRunStatus}}});function SE(r){let e=fg(r);return r===W.TESTIM_HEADSPIN?`${e}/lock`:""}function fg(r){return r===W.TESTIM_HEADSPIN?"https://api-dev.headspin.io/v0/devices":""}function gg(r){return{...r.type===W.TESTIM_HEADSPIN&&{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`}}}function RE(r,e){return{...r.type===W.TESTIM_HEADSPIN&&{device_id:e}}}async function hg(r,e){let t=SE(r.type),s=gg(r),n=RE(r,e);try{await Qe({url:t,headers:s,body:n})}catch(o){throw mg.debug(`error while locking device ${e}`,{error:o}),o.status===401?new Error(`failed to lock device ${e}, device may be already locked and in use`):o}}async function hu(r,e){let s=`${fg(r.type)}/device_id:${e}/automation-config`;try{let n=await Ot(s,void 0,gg(r));return IE(n,r.accessToken)}catch(n){throw mg.error("error while getting automation config for device",{error:n,deviceId:e}),n}}function IE(r,e){let t=Object.keys(r)[0],s=r[t].driver_url,n=new URL(s);return{hostname:n.hostname,port:Number(n.port),protocol:n.protocol.slice(0,-1),path:`/v0/${e}/wd/hub`}}async function yg(r,e){let t={};return r.type===W.TESTIM_HEADSPIN&&(t=await hu(r,e)),t}function bg(r){if(r.type===W.TESTIM_HEADSPIN)return{protocol:r.protocol||"https",hostname:r.host,port:r.port,path:`/v0/${r.accessToken}/wd/hub`};if([W.BROWSERSTACK,W.SAUCELABS].includes(r.type))return{protocol:r.protocol||"https",hostname:r.host,port:r.port,path:"/wd/hub",user:r.user,key:r.key}}async function Tg(r,e,t){var g;let{executionId:s,testId:n,testResultId:o}=r,{project:i,projectData:{type:a}={},company:{companyId:c=""}={},gridData:{gridId:l="",type:p=""}={}}=t,m=e.capabilities.device||e.capabilities.testobject_device_name;if(p===W.TESTIM_HEADSPIN){let f=await hl({projectId:i,projectType:a,companyId:c,gridId:l,selectors:`device_id:${e.capabilities.udid}`});m=(g=f==null?void 0:f[0])==null?void 0:g.name}let d={name:m,model:e.capabilities.deviceModel,osVersion:e.capabilities.platformVersion,udid:e.capabilities.udid,osType:e.capabilities.platformName,scaleFactor:e.capabilities.pixelRatio,virtual:!1};await os(i,s,n,o,"RUNNING",{device:d})}var mg,yu=T(()=>{"use strict";U();ie();be();at();mg=x("mobile-grid-service")});function kE(r,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(r.desiredCapabilities,t),r}function Eu(r){return Eg.readFileSync(r,{encoding:"base64"})}function Ig(r,e,t){if(!(t!=null&&t.isLambdatestRun()&&We(r))&&r){let s=Eu(r);hs.info(`adding extension: custom, path: ${r} length: ${s.length} hash: ${vu(s)} current extension count: ${e.length}`),e.push(s)}}function xg(r,e,t,s,n){if(n!=null&&n.isLambdatestRun())return;if(r.ext||s){let c=typeof r.ext=="string"?r.ext:`${__dirname}/..`,l=s||c,p=`--load-extension=${l}`;hs.info(`adding extension: testim unpacked , path: ${l}`),t.push(p);return}let o=r.canary?"-master.zip":".zip",i=wu.join(process.cwd(),`testim-headless${o}`),a=Eu(i);hs.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${vu(a)} current extension count: ${e.length}`),e.push(a)}function PE(r,e,t,s,n,o,i){var f,h;let a=t.seleniumName||t.browserValue,c=[],l=[...Rg];e.headless&&l.push("--headless");let p={prefs:{"profile.default_content_setting_values.popups":bu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":bu.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1},w3c:!0};Tu(n)&&(p.prefs["download.default_directory"]="C:\\Users\\testnode",r.desiredCapabilities.version="latest-1",r.desiredCapabilities["aws:maxDurationSecs"]=2400,r.desiredCapabilities["aws:idleTimeoutSecs"]=60),Tu(n)&&a==="MicrosoftEdge"&&(r.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(p.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(y=>l.push(`--${y}`)),e.chromeBlockLocation&&(p.prefs["profile.default_content_setting_values.geolocation"]=bu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&l.push(`--user-data-dir=${e.chromeUserDataDir}`),(h=(f=e.projectData)==null?void 0:f.defaults)!=null&&h.disableChromiumGpu&&l.push("--disable-gpu"),Object.assign(r.desiredCapabilities,{browserName:a});function m(){t.mobileEmulation&&(p.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+dc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}m(),Ig(s,c,i),e.mode===Y.EXTENSION&&xg(e,c,l,o,i),c.length>0&&(p.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(p.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),p.args=l;let d={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],g={MicrosoftEdge:"ms",chrome:"goog"}[a];return Z.isLambdatestGrid(n)&&delete p.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(r.desiredCapabilities[d]=p),(e.w3cCapabilities||n.type==="testimEnterprise")&&(r.desiredCapabilities[`${g}:${d}`]=p),r}function AE(r,e,t){let s={"pdfjs.disabled":!0};if(M.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(s,{"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(r.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:s}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(r.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.mode===Y.EXTENSION)if(e.ext)r.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=wu.join(process.cwd(),`testim-firefox-profile${n}`);r.desiredCapabilities.firefox_profile=Eu(o)}return e.headless&&(r.desiredCapabilities["moz:firefoxOptions"].args||(r.desiredCapabilities["moz:firefoxOptions"].args=[]),r.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),r}function OE(r,e,t){let{saucelabs:s}=r;if(s!=null&&s.username&&s.accessKey){let n={"sauce:options":{name:e}};return t?(t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=s.appiumVersion||t.sl.appiumVersion,Object.assign({},t.sl,s,n)):Object.assign({},s,n)}return{}}function _E(r,e,t){return ft.isEmpty(r.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}}),Object.assign({},t.bs,r.browserstack,{name:e})):Object.assign({},r.browserstack,{name:e})}function LE(r){return r.perfecto?r.perfecto:{}}function DE(r,e,t){if(r.experitestToken){let s=e==="safari";return{accessKey:r.experitestToken,browserVersion:"latest",platformName:s?"MAC":"WIN10",seleniumScreenshot:s,newSessionWaitTimeout:t}}return{}}function NE(r,e={}){let{gridData:t={},gridUsername:s,gridPassword:n}=r,o=s||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=Ua(o,i)),a}function Ti(r,e,t,s,n,o,i,a=null){var h,y,w,S,b,v;if(s.mode==="local"){let I=[],A=[...Rg],_={};return r.headless&&A.push("--headless"),r.silentDebuggerExtensionApi&&A.push("--silent-debugger-extension-api"),r.remoteDebuggingPort!==void 0&&A.push(`--remote-debugging-port=${r.remoteDebuggingPort}`),r.chromeExtraArgs&&r.chromeExtraArgs.forEach(R=>A.push(`--${R}`)),r.chromeBinaryLocation&&(_.binary=r.chromeBinaryLocation),r.mode!=="selenium"&&xg(r,I,A,null,a),Ig(n,I,a),{logLevel:wg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:A,extensions:I,..._},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:c,driverRequestRetries:l}=r,p=NE(r,s),m={hostname:s.host,host:s.host,port:s.port||4444,path:s.path||"/wd/hub",protocol:s.protocol||"http",logLevel:wg,connectionRetryTimeout:c,connectionRetryCount:l,getSessionTimeout:Math.max(a.getSessionTimeout,r.getSessionTimeout),getSessionRetries:a.getSessionRetries||r.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!ft.isEmpty(p)&&{headers:p},...r.proxyForGrid&&{agent:global.ProxyAgent(global.proxyUri)}};Tu(s)&&(r.oldCapabilities=!1,r.w3cCapabilities=!0,m.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),r.disableNativeEvents&&(m.desiredCapabilities.nativeEvents=!1),s.user&&s.key&&(s.type==="saucelabs"&&(r.saucelabs||(r.saucelabs={}),(h=r.saucelabs).username||(h.username=s.user),(y=r.saucelabs).accessKey||(y.accessKey=s.key)),s.type==="browserstack"&&(r.browserstack||(r.browserstack={}),(w=r.browserstack)["browserstack.user"]||(w["browserstack.user"]=s.user),(S=r.browserstack)["browserstack.key"]||(S["browserstack.key"]=s.key))),s.key&&s.type==="perfecto"&&(r.perfecto.securityToken=s.key);let d=Number(r.browserTimeout/1e3),g=r.browser||(t==null?void 0:t.browserValue);ft.merge(m.desiredCapabilities,OE(r,e,t),_E(r,e,t),LE(r),DE(r,g,d),a==null?void 0:a.getCapabilities(r,g,o,i,e));let f=null;switch(!r.ext&&!r.extensionPath&&((b=s.host)!=null&&b.endsWith(".testim.io"))&&!r.canary&&r.mode===Y.EXTENSION&&(g==="chrome"?f="/opt/testim-headless":g==="edge-chromium"&&(f="C:/selenium/testim-headless")),(v=s.host)!=null&&v.endsWith(".testim.io")&&g==="edge-chromium"&&(m.desiredCapabilities.version="83"),g){case"chrome":case"edge-chromium":m=CE(m,r,t,n,s,f,a);break;case"firefox":m=AE(m,r,a);break;case"safari":case"safari technology preview":m=kE(m,g);break;default:break}ft.merge(m.desiredCapabilities,r.seleniumCapsFileContent);try{let I={"hub.lambdatest.com":"lambdatest",[M.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},A=C=>C[s.provider]||C[m.host]||C[I[m.host]],_=C=>{var N,B;return A(C)||C[(N=m.desiredCapabilities)==null?void 0:N.browserName]||C[(B=m.desiredCapabilities)==null?void 0:B.version]||C||{}},R=JSON.parse(M.flags.addCustomCapabilities.getValue()||"{}"),L=_(_(R));Object.keys(L).length&&(hs.info(`Adding custom capabilities: ${JSON.stringify(L)}`),Object.assign(m.desiredCapabilities,L))}catch(I){hs.error("Failed to load custom capabilities",{error:I,customCapabilities:M.flags.addCustomCapabilities.getValue()})}return m.desiredCapabilities&&!m.capabilities&&(xE(m),m.capabilities={alwaysMatch:m.desiredCapabilities,firstMatch:[{}]},delete m.desiredCapabilities),m.hostname=m.host,m}function kg({nativeApp:r,appPath:e,gridInfo:t}){if(!r&&!e)throw Error("missing mobile app!");if(![W.BROWSERSTACK,W.SAUCELABS,W.TESTIM_HEADSPIN].includes(t.type))throw Error("unsupported grid was detected please make sure to select supported mobile grid")}function Pg({projectType:r,nativeApp:e,appPath:t,androidActivityWait:s,sessionTags:n,options:o,isHSAppIdExists:i}){let{fullReset:a,resetAppData:c,resetOnSessionStartOnly:l,skipLoadBalancer:p}=o,{executionId:m,testResultId:d}=n,g=i?{"headspin:app.id":t}:{"appium:app":t},f={"headspin:capture":!0,...p&&{"headspin:controlLock":!0},"headspin:retryNewSessionFailure":!1,"headspin:sessionTags":[{executionId:m},{testResultId:d}],...!a&&!c&&{"appium:noReset":!0},...!a&&c&&{"appium:noReset":!1}};switch(r){case"ios":f={...f,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest",...a&&{"appium:fullReset":a,"appium:resetOnSessionStartOnly":l},...e&&{"appium:bundleId":e.id},...t&&g};break;case"android":f={...f,platformName:"Android",...a&&{"appium:fullReset":a},...!a&&c&&{"appium:autoGrantPermissions":!0},"appium:automationName":"UiAutomator2","appium:appWaitActivity":s,...e&&{"appium:appPackage":e.id||e.packageName,"appium:appActivity":e.activity},...t&&g};break;default:throw Error(`unsupported mobile project ${r}`)}return f}function ME({projectType:r,nativeApp:e,appPath:t,androidActivityWait:s,options:n,gridInfo:o,sessionTags:i}){let{fullReset:a,resetAppData:c,resetOnSessionStartOnly:l,osVersion:p,deviceName:m}=n,{type:d}=o,g=d===W.BROWSERSTACK?"browserstack":"saucelabs",f={...d===W.BROWSERSTACK&&{os_version:p,device:m,realDevice:!0,project:i.project,buildTags:Object.values(i).join(",")},...d===W.SAUCELABS&&{platformVersion:p,deviceName:m,tags:Object.values(i)},name:i.testResultId,build:i.executionId,[`${g}.user`]:o.user,[`${g}.key`]:o.key,[`${g}.debug`]:!0,[`${g}.networkLogs`]:!0,...!a&&!c&&{noReset:!0},...!a&&c&&{noReset:!1}};switch(r){case"ios":f={...f,platformName:"iOS",autoAcceptAlerts:!0,automationName:"XCUITest",...a&&{fullReset:a,resetOnSessionStartOnly:l},...e&&{bundleId:e.id},...t&&{app:t}};break;case"android":f={...f,platformName:"Android",...a&&{fullReset:a},...!a&&c&&{autoGrantPermissions:!0},automationName:"UiAutomator2",appWaitActivity:s,...e&&{appPackage:e.id||e.packageName,appActivity:e.activity},...t&&{app:t}};break;default:throw Error(`unsupported mobile project ${r}`)}return f}function FE({projectType:r,nativeApp:e,appPath:t,androidActivityWait:s,options:n,sessionTags:o,gridInfo:i,isHSAppIdExists:a}){return W.TESTIM_HEADSPIN===i.type?Pg({projectType:r,nativeApp:e,appPath:t,androidActivityWait:s,options:n,sessionTags:o,isHSAppIdExists:a}):ME({projectType:r,nativeApp:e,appPath:t,androidActivityWait:s,options:n,gridInfo:i,sessionTags:o})}function Cg({projectType:r,gridInfo:e,nativeApp:t,options:s,appPath:n,androidActivityWait:o,sessionTags:i,isHSAppIdExists:a}){let{deviceName:c,osVersion:l,deviceUdid:p}=s;kg({nativeApp:t,appPath:n,gridInfo:e});let m=bg(e),d=FE({projectType:r,nativeApp:t,appPath:n,androidActivityWait:o,options:s,sessionTags:i,gridInfo:e,isHSAppIdExists:a});if(e.type===W.TESTIM_HEADSPIN){let g={};c&&(g.model=c),l&&(g.os_version=l),p&&(g.device_id=p,delete g.model,delete g.os_version),ft.isEmpty(g)||(d["headspin:selector"]=g)}return{...m,desiredCapabilities:d,capabilities:d,connectionRetryCount:0,logLevel:s.appiumLogLevel}}async function Ag({projectType:r,gridInfo:e,nativeApp:t,options:s,appPath:n,androidActivityWait:o,sessionTags:i,isHSAppIdExists:a}){let{deviceUdid:c}=s;kg({nativeApp:t,appPath:n,gridInfo:e});let l=await yg(e,c),p=Pg({projectType:r,nativeApp:t,appPath:n,androidActivityWait:o,options:s,sessionTags:i,isHSAppIdExists:a});return c&&(p["appium:udid"]=c),{...l,desiredCapabilities:p,capabilities:p,connectionRetryCount:0,logLevel:s.appiumLogLevel}}var Eg,wu,Sg,ft,hs,wg,bu,Rg,vu,Tu,xE,CE,vg,wi=T(()=>{"use strict";Eg=E(require("fs")),wu=E(require("path")),Sg=E(require("crypto")),ft=E(require("lodash"));j();pe();U();Te();ie();Xo();yu();hs=x("testim-desired-capabilities-builder"),wg=Zn?"debug":"silent",bu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Rg=["--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"],vu=(...r)=>Sg.createHash("sha256").update(r.join("")).digest("hex"),Tu=r=>r.type===W.DEVICE_FARM||r.type===W.HYBRID&&r.provider==="devicefarm",xE=r=>{var s;let{desiredCapabilities:e}=r;Object.prototype.hasOwnProperty.call(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.prototype.hasOwnProperty.call(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.prototype.hasOwnProperty.call(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.prototype.hasOwnProperty.call(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.prototype.hasOwnProperty.call(e,"chromeOptions")&&(e["goog:chromeOptions"]??(e["goog:chromeOptions"]=e.chromeOptions),delete e.chromeOptions),Object.prototype.hasOwnProperty.call(e,"edgeOptions")&&(e["ms:edgeOptions"]??(e["ms:edgeOptions"]=e.edgeOptions),delete e.edgeOptions),Object.prototype.hasOwnProperty.call(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??(e["moz:firefoxOptions"]=e.firefoxOptions),delete e.firefoxOptions),((s=e["goog:chromeOptions"])==null?void 0:s.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in r.desiredCapabilities&&(r.user=r.desiredCapabilities.username,delete r.desiredCapabilities.username),"accessKey"in r.desiredCapabilities&&(r.key=r.desiredCapabilities.accessKey,delete r.desiredCapabilities.accessKey);let t;try{t=M.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(o=>{delete e[o]})}catch{hs.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};CE=ft.memoize(PE,(r,e,t,s,n,o)=>{let i=JSON.stringify(r.desiredCapabilities),a=JSON.stringify(ft.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return vu(i,a,c,s,l,o)}),vg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Ue(r){var e,t,s,n,o,i,a;return((e=r.message)==null?void 0:e.match(/Command not found/))||r.message==="HTTP method not allowed"||r.message==="Unknown error"||((t=r.message)==null?void 0:t.match(/Unknown timeout type/))||r.name==="unknown command"||((s=r.message)==null?void 0:s.match(/did not match a known command/))||((n=r.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=r.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=r.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=r.message)==null?void 0:a.match(/\.\w* is not a function/))}function Og(r,e,t){if(!e||!r)return r;if(r.includes("%"))return r.replace(/ /g,"%20");try{return decodeURI(r)!==r?r:encodeURI(r)}catch(s){return t&&t.warn("tried to encode url but failed",{err:s,url:r}),r}}async function _g(r){var e;if(!vi||!Ei)try{let t=require.resolve("webdriver/build/utils.js"),[s,n]=await Promise.all([import("got"),import(t)]);[vi,Ei]=[s.RequestError,n.CustomRequestError]}catch{}return!vi||!Ei?(e=r.stack)==null?void 0:e.includes("node_modules/webdriver"):r instanceof vi||r instanceof Ei}var vi,Ei,Ru=T(()=>{"use strict"});function Iu(r){function e(d){return d?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(d.nodeType):!1}function t(d){return d?s(d.parentNode,e):null}function s(d,g){for(let f=d;f&&f!==d.ownerDocument;f=f.parentNode)if(g(f))return f;return null}function n(d,g){for(let f=d;f&&f!==d.ownerDocument;f=t(f))if(g(f))return f;return null}function o(d,g){if(!d||!g)return null;d instanceof DocumentFragment&&(d=d.host);let h=window.getComputedStyle(d).getPropertyValue(g);if(h&&h!=="inherit")return h;let y=t(d);return o(y,g)}function i(d){let g=d.getBoundingClientRect();if(g.width>0&&g.height>0)return!0;if(d.tagName.toUpperCase()==="PATH"&&g.width+g.height>0){let h=o(d,"stroke-width");return!!h&&parseInt(h,10)>0}return o(d,"overflow")==="hidden"?!1:Array.from(d.childNodes).some(h=>h.nodeType===Node.TEXT_NODE?!0:e(h)?i(h):!1)}function a(d){return o(d,"overflow")==="hidden"}function c(d){return!d||!a(d)||!d.childNodes.length?!1:Array.from(d.childNodes).every(g=>g.nodeType===Node.TEXT_NODE?!1:!e(g)||!i(g)?!0:c(g))}function l(d){var g;return d?(g=d.parentNode)!=null&&g.host?!0:l(d.parentNode):!1}if(!r||!l(r)&&!document.contains(r))return!1;switch(r.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let g=s(r,f=>f.tagName.toUpperCase()==="SELECT");return Iu(g)}case"INPUT":if(r.type==="hidden")return!1;break;default:break}if(o(r,"visibility")!=="visible")return!1;let p=!!n(r,d=>Number(o(d,"opacity"))===0),m=!!n(r,d=>o(d,"display")==="none");return!(p||m||!i(r)||c(r))}var Lg=T(()=>{"use strict"});var Dg,Ng,En,UE,jE,Si,Mg=T(()=>{"use strict";Dg=E(require("promise-queue")),Ng=E(require("webdriverio"));pe();Le();j();U();Fr();Lg();Ru();fs();En=x("WebDriverApi"),UE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},jE={implicit:0,pageLoad:1,script:2},Si=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:s,testResultId:n}=this,o=t?t.toString().substr(0,2e3):"";throw En.warn("error from selenium",{err:e,testResultId:n,testName:s,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),typeof Wa<"u"&&(e=Wa);let t=1/0;this.queue=new Dg.default(e,t)}async addToQueue(e){var s,n;let t=(s=this.seleniumPerfStats)==null?void 0:s.markStart();try{return await this.queue.add(e)}catch(o){return this.rejectWithLog(o,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,s){var o,i;this.testName=t,this.testResultId=s,e.deprecationWarnings=!1,this.initQueueRequests(),O("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(Ce.GET_BROWSER);try{await this.addToQueue(async()=>{En.info("requesting browser",{testResultId:s,testName:t}),O("before this.client.init"),this.client=await Ng.remote(e)}),O("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,Ce.GET_BROWSER)}}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},o=()=>this.client.execute(e,t).catch(n),i=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return o();t=t.map(a=>{if(a===null){En.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await i()}catch(a){if(Ue(a))return this.unsupportedActions.add("execute"),o();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),o=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await o()}catch(i){if(Ue(i))return this.unsupportedActions.add("executeAsync"),n();throw i}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let s=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return s!=null&&s.targetInfos?s.targetInfos:[]}async takeScreenshot(){var t,s;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Ce.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.takeScreenshot()})}}finally{(s=this.seleniumPerfStats)==null||s.markEnd(e,Ce.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Ce.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Me(e)))}finally{this.seleniumPerfStats.markEnd(t,Ce.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),s=()=>this.execute(Iu,{ELEMENT:e,[Ht]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return s();try{return await t()}catch(n){if(Ue(n))return this.unsupportedActions.add("elementIdDisplayed"),s();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(Og(e,this.isSafari(),En))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let s=()=>{let o=[];return o[jE[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await s()}catch(o){if(Ue(o))return this.unsupportedActions.add("timeouts"),n();throw o}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let s=function(n,o){window.scrollTo(n,o)};return this.execute(s,e,t)}async setValue(e,t){return await this.elementIdClear(Me(e)),await this.elementIdValue(Me(e),t)}async getViewportSize(e){let t=await this.execute(UE);if(typeof e=="string"&&e.match(/(width|height)/)){let s=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[s]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async keys(e){let t=i=>Ma.hasOwnProperty(i)?[Ma[i]]:i.split(""),s=[];if(typeof e=="string")s=t(e);else if(Array.isArray(e))for(let i of e)s=s.concat(t(i));else throw new Error("number or type of arguments don't agree with keys protocol command");let n=()=>{var i;return(i=this.client)==null?void 0:i.requestHandler.create("/session/:sessionId/keys",{value:s})},o=()=>{let i=s.map(c=>({type:"keyDown",value:c})),a=s.map(c=>({type:"keyUp",value:c}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};if(this.unsupportedActions.has("keys"))return o();try{return await this.addToQueue(()=>n())}catch(i){if(Ue(i))return this.unsupportedActions.add("keys"),o();throw i}}async elementIdValue(e,t){let s=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.elementSendKeys(e,s)})}}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(Me(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(e)),s=await t.$('button[type="submit"]');return await s.isExisting()?s.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,s,n){return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).click({x:t,y:s,button:n})})}}_rightClick(e,t,s){return this.findElementAndPress(e,t,s,"right")}_leftClick(e,t,s){return this.findElementAndPress(e,t,s,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}async actions(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}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,s){let n={...typeof t=="number"&&{xOffset:t},...typeof s=="number"&&{yOffset:s}};return this.isSafari()&&!Object.prototype.hasOwnProperty.call(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.prototype.hasOwnProperty.call(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let s=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let o=Math.abs(e.width),i=Math.abs(e.height);s=async()=>await this.client.setWindowSize(o,i),n=async()=>await this.client._setWindowSize(o,i)}if(this.unsupportedActions.has("windowHandleSize"))return s();try{return await n()}catch(o){if(Ue(o))return this.unsupportedActions.add("windowHandleSize"),s();throw o}})}}setCookie(e,t,s,n,o,i,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:s,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var s;return(await((s=this.client)==null?void 0:s.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).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(){if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.isAppInstalled(e)});return En.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 Fg={};$(Fg,{doubleClick:()=>BE});var BE,Ug=T(()=>{"use strict";BE=function(r,e){let t=["pointerup","pointerdown","pointermove"],s=getLocatedElement(r.locatedElement);if(!s)throw new Error("element not found");let n=r.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(d){function g(S,b,v){return v>S&&v<b}let f=d.pointerPosition||{},h=s.getBoundingClientRect(),y=f.originX&&g(h.left,h.left+h.width,f.originX)?f.originX:h.left+h.width/2,w=f.originY&&g(h.top,h.top+h.height,f.originY)?f.originY:h.top+h.height/2;return{x:y,y:w}},a=function(d,g){return{screenX:0,screenY:0,clientX:d,clientY:g,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(d,g,f){if(!window.PointerEvent)return;let h=a(g,f);return new window.PointerEvent(d,h)},l=function(d,g,f){let h=document.createEvent("MouseEvents");return h.initMouseEvent(d,!0,!0,document.defaultView,1,0,0,g,f,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),h},p=function(){var g;let d=document.activeElement;for(;(g=d.shadowRoot)!=null&&g.activeElement;)d=d.shadowRoot.activeElement;return d},m=function(d){let g=i(d),f=d.event;return t.includes(f)?c(f,g.x,g.y):l(f,g.x,g.y)};try{n.map(g=>m(g)).filter(Boolean).forEach(g=>s.dispatchEvent(g));let d=p();dispatchFocus(r.elementToFocusLocatedElement,d),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(d){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:d.toString(),success:!1})}}});var Sn={};$(Sn,{dispatchFocus:()=>$E});function $E(r,e){function t(o){let i=document.createEvent("HTMLEvents");return i.initEvent(o,!0,!1),i}function s(){var i;let o=document.activeElement;for(;(i=o.shadowRoot)!=null&&i.activeElement;)o=o.shadowRoot.activeElement;return o}function n(o,i){i&&(i.dispatchEvent(t("focusout")),i.dispatchEvent(t("blur"))),o.dispatchEvent(t("focusin")),o.dispatchEvent(t("focus")),typeof o.focus=="function"&&o.focus();let a=s();i&&a===i&&typeof i.blur=="function"&&i.blur()}if(r){let o=getLocatedElement(r);if(o&&o!==e)try{n(o,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var Rn=T(()=>{"use strict"});var Hg={};$(Hg,{WebDriver:()=>Pr});async function VE(r){var e,t;try{let s=(t=(e=r==null?void 0:r.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return s?await HE(s):void 0}catch(s){He.info("Error getting cdpAddress",s);return}}var Ri,$g,Wg,He,rr,WE,jg,HE,sr,GE,Bg,Pr,In=T(()=>{"use strict";Ri=E(require("lodash"));j();Le();wi();$g=E(require("p-retry")),Wg=E(require("ua-parser-js"));Fr();U();Ru();Mg();V();Te();fs();He=x("webdriver"),[rr,WE]=[0,2],{extractElementId:jg,getCdpAddressForHost:HE}=q,sr=()=>(Ee(),ve(Ir)).getSessionPlayer().codeSnippets,GE=()=>(Ee(),ve(Ir)).getSessionPlayer().locatorBuilderUtils,Bg=()=>(Ee(),ve(Ir)).getSessionPlayer().utils;Pr=class extends Si{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}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(s=>s!==t)}async init(t,s,n,o,i,a,c,l=new Bt,p=!1,m=void 0){var h,y,w,S,b,v,I,A;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((w=(y=(h=t==null?void 0:t.company)==null?void 0:h.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:w.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let d=Ti(t,s,n,o,i,a,c,m);d.desiredCapabilities&&delete d.desiredCapabilities.marionette,d.capabilities&&delete d.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(m==null?void 0:m.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=l;let g=p?0:1500,f=p?()=>null:()=>this.executeJS("window.focus()");try{O("before initClient in webdriver.js init");let _=await this.initClient(d,s,c);O("after initResult before getCdpAddress in init"),this.cdpUrl=await VE(_),O("after getCdpAddress in webdriver.js init"),He.info(`init new session testName: ${s}`,{sessionId:this.getSessionId(),testResultId:c}),await se(g),M.flags.dontFocusOnInit.isEnabled()||await f(),O("after focus and delay in webdriver.js init")}catch(_){He.error("failed to init webdriver",{err:_,capabilities:d});let R=((b=(S=t==null?void 0:t.company)==null?void 0:S.activePlan)==null?void 0:b.plan)==="free";throw(v=_.stack)!=null&&v.includes("at startWebDriverSession")&&((I=_.message)!=null&&I.startsWith("Failed to create session"))&&((A=_.message)!=null&&A.includes("Timeout awaiting 'request'"))&&R?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):_.message.match(/capabilit(y|ies)/)?new to(_.message):new Error("failed to init client driver")}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>Ri.zip(o.slice(0,-1),o.slice(1)),s=this._keepAliveRequests.map(({start:o})=>o).filter(Boolean),n=t(s).map(([o,i])=>i-o);return Math.max(...n)}async isClosedBrowserError(t){return["session-not-found","no such window"].includes(t==null?void 0:t.name)?!0:await _g(t)?["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(n=>t.message.includes(n)):!1}start(){if(this.started)return;this.started=!0;let t=async()=>{let s=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,c)=>{let l=this._keepAliveRequests.find(p=>p.id===c);l&&(l[a]=Date.now())};function o(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let i=J();s(i);try{await this.executeJS(o),this._isAlive=!0,n("end",i),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",i),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,He.warn("close unexpected alert open"),await this.alertAccept().catch(c=>He.warn("failed to click on alert",{err:c}));return}if(He.warn("err while getting testim status",{err:a}),this._isAlive=!1,await this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;this.browserClosedFailedKeepAlives>=c&&this.browserClosedCallbacks.forEach(l=>{try{l(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4)}async switchToLocatedFrame(t){let s=await this.getElement(t),n=jg(s.value);return await this.switchToFrame({ELEMENT:n,[Ht]:n}),s}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(s){throw(t=s.message)!=null&&t.includes("ECONNREFUSED")?new ro:s}}async getElement(t){var o;let s=this.seleniumPerfStats.markStart(Ce.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(s,Ce.GET_ELEMENT)}if(((o=t==null?void 0:t.shadowPath)==null?void 0:o.length)||M.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
26
|
+
`))||""}`)}let i=(await(0,Fl.default)({type:"toggle",name:"isJs",message:"Add support for TypeScript?",initial:!0,active:"no",inactive:"yes"})).isJs?"template.js":"template.ts",a="codim",c=Yt.join(__dirname,a,i),l=Yt.join(process.cwd(),e),m=(0,Ml.default)(`Creating new test project in ${l}`).start();await oo(c,l);let d=Yt.join(__dirname,a,i,"package.json"),p=Yt.join(process.cwd(),e,"package.json"),f=(await Xt.promises.readFile(d)).toString().replace("~testim-codeful-test-project~",s);await Xt.promises.writeFile(p,f);let h="node_modules",y=Yt.join(process.cwd(),e,".gitignore");await Xt.promises.writeFile(y,h),m.succeed(),m=(0,Ml.default)("Installing dependencies").start(),await bv("npm install",{cwd:l}),m.succeed(),console.log(`Testim Dev Kit project folder successfully created in ${l}.`)}var Xt,Yt,zm,Ml,Go,Fl,Km,Jm,bv,Xm=T(()=>{"use strict";Xt=E(require("fs")),Yt=E(require("path")),zm=E(require("child_process")),Ml=E(require("ora")),Go=E(require("chalk")),Fl=E(require("prompts")),Km=E(require("validate-npm-package-name")),Jm=require("util");V();pc();bv=(0,Jm.promisify)(zm.exec)});var Zm={};$(Zm,{preloadTests:()=>dn});async function dn(r){if(!Array.isArray(r.testId)||!r.testId.length)return{};let e={branch:r.branch,projectId:r.project};return await lt(async()=>{let t=await ce(r.testId,s=>Gc({...e,testId:s}),{concurrency:2});return Qm.keyBy(t,"testData.id")},"loadTests",wv,[e,r.testId])()}var Qm,wv,Vo=T(()=>{"use strict";Qm=E(require("lodash"));qt();be();j();wv=1e3*60*60*10});function Ul(){return ot()}async function rf(){if(!De)try{let r=await ne(Ev(),5e3,"The API call to NPM timed out"),e=Ul();e&&tf.lt(e,r)&&console.log(ef.default.yellow(`Warning: You are using version ${e}, a newer version is available. To update please run npm install (npm install -g @testim/testim-cli)`))}catch(r){vv.warn("Failed to get NPM version",{err:r})}}var ef,tf,vv,Ev,jl=T(()=>{"use strict";ef=E(require("chalk")),tf=E(require("semver"));j();pe();Qs();qt();U();vv=x("npm-driver"),Ev=lt(()=>Vd("@testim/testim-cli"),"getNpmVersion")});var Bl,Rv,ps,sf,nf,$l,of,af=T(()=>{"use strict";j();V();U();dt();Bl=x("testimNgrok"),Rv=".whitelisted-ngrok.testim.io",ps="",nf=async(r,e={})=>{if(!e.ngrokToken)throw new k("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${J()}-${r.projectData.projectId}${Rv}`);let s={proto:"http",addr:r.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};r.tunnelHostHeader&&(s.host_header=r.tunnelHostHeader),r.tunnelRegion&&(s.region=r.tunnelRegion);let o=await(await le("ngrok")).connect(s);r.tunnelUseHttpAddress&&o.startsWith("https://")?(Bl.info("replace https to http"),ps=o.replace("https://","http://")):ps=o,r.tunnelDiagnostics&&$l(),r.baseUrl=ps},$l=async(r=!0)=>{try{let t=(await le("ngrok")).getApi(),{tunnels:s}=await t.listTunnels(),n=s.find(o=>o.public_url===ps);console.log("ngrok stats",n),Bl.info("ngrok stats",{tunnel:n})}catch(e){Bl.error("error collecting ngrok stats",{err:e})}r&&(sf=setTimeout(()=>$l(),1e4))},of=async r=>{if(!ps)return;clearTimeout(sf),r.tunnelDiagnostics&&await $l(!1),await(await le("ngrok")).disconnect(ps)}});var Qt,Hl,cf,xv,kv,Wl,qo,Ko,zo,Pv,lf,uf,pf=T(()=>{"use strict";Qt=E(require("os")),Hl=E(require("fs")),cf=E(require("child_process"));j();be();xv="https://github.com/cloudflare/cloudflared/releases/download/2022.4.1/",kv={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"}},Wl=Qt.tmpdir(),qo=`${Wl}/cloudflared`,Ko=null,zo=null,Pv=async()=>{if(await ye(qo))return;let e=kv[Qt.platform()+Qt.arch()];if(!e)throw new Error(`tunnel on ${Qt.platform()+Qt.arch()} platform is not supported.`);let t=e.extract?Wl+e.path:qo;await qe(`${xv}/${e.path}`,t),e.extract&&await Ze(t,Wl),await Hl.promises.chmod(qo,"755")},lf=async r=>{let e=r.baseUrl||`http://localhost:${r.tunnelPort||80}`,t="tunnelRoutes"in r&&r.tunnelRoutes||[e],[s]=await Promise.all([ml(r.company.companyId,t),Pv()]);Ko=s._id,zo=cf.spawn(qo,["tunnel","--no-autoupdate","run","--force","--token",s.token],{stdio:"inherit"}),await fl(r.company.companyId,Ko),"tunnelRoutesOutput"in r&&r.tunnelRoutesOutput&&await Hl.promises.writeFile(r.tunnelRoutesOutput,JSON.stringify(s.routesMapping,null,2)),r.baseUrl=`${r.tunnelUseHttpAddress?"http":"https"}://${s.routesMapping[e]}`},uf=async r=>{let e=[];return Ko&&e.push(gl(r.company.companyId,Ko)),zo&&e.push(new Promise((t,s)=>{zo.on("close",n=>{n&&s(new Error(`tunnel process exited with code ${n}`)),t()}),zo.kill()})),await Promise.all(e)}});var z,mf,Av,Ov,_v,df,Jo,Gl,M,Te=T(()=>{"use strict";z=E(require("rox-node"));U();j();pe();mf=x("FeatureFlagsService"),Av=!De&&!0&&!Zp,Ov=2e4,_v=60*60*24,df=["labs","disabled","enabled"],Jo=class extends z.default.Variant{constructor(e="disabled"){super(e,df)}getValue(){let e=super.getValue();return df.includes(e)?e:(mf.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},Gl=class{constructor(){this.flags={useNewWSCLI:new z.default.Flag,useSafariWebdriverVisibilityChecks:new z.default.Flag,useClickimVisibilityChecks:new z.default.Flag,runGetElementCodeInAut:new z.default.Flag,enableFrameSwitchOptimization:new z.default.Flag,maximumJsResultSize:new z.default.Configuration(2e3*1024),skipFileInputClicks:new z.default.Flag,errorMessageOnBadNetwork:new z.default.Flag(!0),warnOnBadNetwork:new z.default.Flag(!1),overrideAzureStorageUrl:new z.default.Flag,useJsInputCodeInSafari:new z.default.Flag,useJsInputCodeInFirefox:new z.default.Flag,autoSaveDownloadFileFireFox:new z.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new z.default.Flag(!0),experimentalPreCodeCompilation:new z.default.Flag(!0),experimentalAsyncCustomCode:new z.default.Flag,useSameBrowserForMultiTests:new Jo("labs"),highSpeedMode:new Jo,usePortedHtml5DragDrop:new z.default.Flag,testNamesToBeforeSuiteHook:new z.default.Flag,addCustomCapabilities:new z.default.Variant("{}"),LTNetworkCapabilities:new z.default.Flag,downloadToBase64:new z.default.Flag,dec2022eolBrowsers:new z.default.Flag,publicGridURL:new z.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new z.default.Flag(!0),unsupportedCapsFields:new z.default.Variant("[]"),useLinkedomToParseHtml:new z.default.Flag,dontFocusOnInit:new z.default.Flag},z.default.register("default",this.flags)}setProjectId(e){z.default.setCustomStringProperty("projectId",e)}setProjectType(e){z.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){z.default.setCustomStringProperty("productType",e)}setCompanyId(e){z.default.setCustomStringProperty("companyId",e)}setPlanType(e){z.default.setCustomStringProperty("planType",e)}setIsPOC(e){z.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){z.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){z.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!Av)return;let e={fetchIntervalInSec:_v,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return ne(z.default.setup(Xp,e),Ov).catch(t=>mf.error("failed to get feature flag status",t))}},M=new Gl});var gf,hf,Zt,yf,bf,ff,Lv,Dv,Yo,Nv,Mv,Z,Xo=T(()=>{"use strict";gf=E(require("ms")),hf=E(require("p-retry")),Zt=E(require("os")),yf=E(require("portfinder")),bf=E(require("child_process"));j();at();be();V();U();Uo();ie();Te();ff=x("lambdatestService"),Lv="https://downloads.lambdatest.com/tunnel/v3",Dv={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"},Yo=`${Zt.tmpdir()}/LT`,Nv=`${Yo}/LT`,Mv=(0,gf.default)("15m"),Z=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===W.LAMBDATEST||e.type===W.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){Z.isLambdatestGrid(e)&&(Z.lambdatestConfigPromise||(Z.lambdatestConfigPromise=ol()),Z.lambdatestConfig=await Z.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?Mv:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ye(Nv))return;let t=Dv[Zt.platform()+Zt.arch()];if(!t)throw new Error(`tunnel on ${Zt.platform()+Zt.arch()} platform is not supported.`);let s=`${Yo}.zip`;await qe(`${Lv}/${t}`,s),await Ze(s,Yo)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){Z.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await yf.getPortPromise(),{gridData:s={},gridUsername:n,gridPassword:o}=e,i=global.proxyUri;Z.tunnelName=J();let a=["--tunnelName",Z.tunnelName,"--infoAPIPort",String(t)];if(e.externalLambdatestUseWss&&(a=[...a,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(a=[...a,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),s.tunnelUser&&s.tunnelKey)a=[...a,"--user",s.tunnelUser,"--key",s.tunnelKey];else if(n&&o)a=[...a,"--user",n,"--key",o];else throw new k("tunnel requires username and password");if(i)try{let m=new URL(i);a=[...a,"--proxy-host",m.hostname],m.port&&(a=[...a,"--proxy-port",m.port]),m.username&&m.password&&(a=[...a,"--proxy-user",m.username,"--proxy-pass",m.password])}catch{throw new k("proxy url is invalid")}e.externalLambdatestMitm&&(a=[...a,"--mitm"]),Z.tunnel=bf.spawn("./LT",a,{cwd:Yo});let c="",l="";Z.tunnel.stdout.on("data",m=>{c+=m.toString()}),Z.tunnel.stderr.on("data",m=>{l+=m.toString()});try{let m=await(0,hf.default)(()=>Ot(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});ff.info("LT tunnel info",m)}catch(m){throw ff.error("Failed to start LT tunnel",{err:m,stdoutResult:c,stderrResult:l}),m}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!Z.tunnel))return new Promise((t,s)=>{Z.tunnel.on("close",n=>{n&&s(new Error(`tunnel process exited with code ${n}`)),t()}),Z.tunnel.kill()})}getCapabilities(e,t,s,n,o){if(!this.isActive)return{};let i=Z.lambdatestConfig.CAPABILITIES[t]||{},a={...Z.tunnelName&&{tunnel:!0,tunnelName:Z.tunnelName}},c=[],{mode:l,canary:m,ext:d,extensionPath:p,installCustomExtension:g}=e;if(l===Y.EXTENSION&&!d){let f=Il({canary:m},!0);!p&&f[t]&&(c=[...c,f[t]]),p&&We(p)&&(c=[...c,p])}return g&&We(g)&&(c=[...c,g]),{build:s,name:`${n} - ${o}`,platform:Z.lambdatestConfig.PLATFORM,selenium_version:Z.lambdatestConfig.SELENIUM_VERSION,resolution:Z.lambdatestConfig.RESOLUTION,timezone:Z.lambdatestConfig.TIMEZONE,...i,loadExtension:c,...a,console:!0,queueTimeout:300,network:M.flags.LTNetworkCapabilities.isEnabled()}}}});var Vl={};$(Vl,{connect:()=>Zo,disconnect:()=>ei,serveTunneling:()=>Uv});var Qo,Tf,wf,Fv,Zo,ei,Uv,ql=T(()=>{"use strict";af();ln();pf();Rt();Qo=E(require("ora"));U();ie();Xo();Tf=x("tunnel"),wf=r=>{var e;return[W.LAMBDATEST,W.HYBRID].includes((e=r.gridData)==null?void 0:e.type)&&r.gridData.tunnel==="lambdatest"},Fv=r=>{var e;return r.tunnelRoutes||((e=r.gridData)==null?void 0:e.type)===W.HYBRID&&r.gridData.tunnel==="cloudflare"},Zo=async r=>{if(!r.tunnel)return;let e=Mt(),t;try{wf(r)?(t=(0,Qo.default)("Starting testim lambdatest tunnel...").start(),await Z.connectTunnel(r)):Fv(r)?(t=(0,Qo.default)("Starting testim cloudflare tunnel...").start(),await lf(r)):(t=(0,Qo.default)("Starting testim ngrok tunnel...").start(),await nf(r,e)),t.succeed()}catch(s){let n="Failed to start tunnel. Please contact support@testim.io";throw Tf.error("Failed to open tunnel",{err:s}),t==null||t.fail(n),new Error(n)}},ei=async r=>{if(r.tunnel)try{wf(r)?await Z.disconnectTunnel(r):"tunnelRoutes"in r?await uf(r):await of(r)}catch(e){let t="catch error - failed to close tunnel";throw Tf.error(t,{err:e}),new Error(t)}},Uv=async(r,e=new Promise(()=>{}))=>(await Zo(r),is(()=>ei(r)),await e)});function jv(r){if(r.protocol)return r.protocol;if([W.TESTIM,W.BROWSERSTACK,W.SAUCELABS].includes(r.type)&&r.port===443)return"https";if([W.TESTIM_ENTERPRISE,W.LAMBDATEST,W.DEVICE_FARM].includes(r.type)){let e=vf.exec(r.host);return(e==null?void 0:e[2])||"https"}return""}function Bv(r){let e=vf.exec(r);return e==null?void 0:e[3]}function ri(r){var y,w,S,b,v,I,A,_,R;let e=r&&Bv(r.host),t=r==null?void 0:r.port,s=r==null?void 0:r.path,n=r&&jv(r),o=r==null?void 0:r.token,i=r==null?void 0:r.slotId,a=(y=r==null?void 0:r.hybrid)==null?void 0:y.tunnel,c=(w=r==null?void 0:r.external)==null?void 0:w.user,l=(S=r==null?void 0:r.external)==null?void 0:S.key,m=r==null?void 0:r.type,d=m===W.HYBRID?a&&((I=(v=(b=r.hybrid)==null?void 0:b.external)==null?void 0:v[r.hybrid.tunnel])==null?void 0:I.user):c,p=m===W.HYBRID?a&&((R=(_=(A=r.hybrid)==null?void 0:A.external)==null?void 0:_[r.hybrid.tunnel])==null?void 0:R.key):l,g=r==null?void 0:r.name,f=r&&(r._id||r.gridId),h=r==null?void 0:r.provider;return{host:e,port:t,path:s,protocol:n,accessToken:o,slotId:i,gridId:f,tunnel:a,user:c,key:l,type:m,name:g,provider:h,tunnelUser:d,tunnelKey:p}}async function Sf(r,e,t,s,n){let o;try{o=await n()}catch(i){throw Je.error("failed to get grid",{projectId:r,companyId:e,err:i}),new Error(Kr.UNKNOWN)}if(Je.info("get grid info",Object.assign({},o,{projectId:r,companyId:e})),!o||!["success","error"].includes(o.status))throw Je.error("invalid response - get grid",{res:o}),new Error(Kr.UNKNOWN);if(o.status==="success"){let i=ri(o.grid);return $v(t,e,i.gridId,i.slotId,s),i}throw o.code==="not-found"?new wt(Kr.NOT_FOUND):o.code==="no-available-slot"?new Hr(`Failed to run test on ${s} - concurrency limit reached`):(Je.error("invalid code error response - get grid",{res:o}),new wt(Kr.UNKNOWN))}function Wv(r,e,t,s,n,o){return Sf(t,e,r,n,()=>_o(e,t,s,n,o))}function Hv(r,e,t,s,n,o,i){return Sf(t,e,r,n,()=>{var l;let c=(l=i.allGrids)==null?void 0:l.find(m=>(m.name||"").toLowerCase()===s.toLowerCase());return c!=null&&c._id?_o(e,t,c._id,n,o):rl(e,t,s,n,o)})}function Rf(r){return nl(r)}async function If(r,e,t){let n=(t||await Rf(r)).find(o=>o._id===e);if(!n)throw new k(`Failed to find grid id: ${e}`);return ri(n)}async function Gv(r,e,t){let n=(t||await Rf(r)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new k(`Failed to find grid name: ${e}`);return ri(n)}async function zl(r,e){let t=mn[r];if(!t)return;let{slotId:s,gridId:n,browser:o,companyId:i}=t;if(delete mn[r],!s){Je.warn("failed to find grid slot id",{projectId:e});return}Je.info("release slot id",{projectId:e,companyId:i,slotId:s,gridId:n,browser:o});try{await el(i,e,s,n,o)}catch(a){Je.error("failed to release slot",{projectId:e,err:a})}}async function Vv(r){let e=Object.values(mn).filter(Boolean);if(e.length!==0){Je.info("keep alive worker slots",{projectId:r,slots:e});try{await Zc(r,e)}catch(t){Je.error("failed to update grid keep alive",{err:t,slots:e,projectId:r})}}}function qv(r){Ef=global.setInterval(Vv,1e4,r)}async function zv(r){let e=Object.keys(mn);if(e.length){Je.warn("not all slots released before end runner flow",{projectId:r});try{await ce(e,t=>zl(Number(t),r))}catch(t){Je.error("failed to release all slots",{err:t,projectId:r})}}}async function Kv(r){await zv(r),clearInterval(Ef)}function Jv(r,e){let{testobjectSauce:t,saucelabs:s}=e;if(r==="testobject")return t.testobjectApiKey;if(r==="saucelabs")return s.accessKey}function Yv(r,e){let{saucelabs:t}=e;if(r==="saucelabs")return t.username}function xf(r){let t=(()=>ti.isEmpty(r.testobjectSauce)?ti.isEmpty(r.saucelabs)?ti.isEmpty(r.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:s,port:n,path:o,protocol:i}=r,a=Jv(t,r),c=Yv(t,r);return{host:s,port:n,path:o,protocol:i,type:t,user:c,key:a}}async function kf(r,e){let t=r.company.companyId;return await If(t,e.gridId,r.allGrids)}async function Pf(r){let{allGrids:e=void 0,company:t,host:s,useLocalChromeDriver:n,useChromeLauncher:o,gridId:i,grid:a}=r;if(n||o)return{mode:"local"};if(s)return xf(r);let c=t==null?void 0:t.companyId;if(i)return If(c,i,e);if(a)return Gv(c,a,e);if(Vs(r)||r.tunnelOnlyMode){Je.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new wt("Missing host or grid configuration")}async function Cf(r,e,t,s){return await(async()=>{let{host:i,project:a,grid:c,gridId:l,useLocalChromeDriver:m,useChromeLauncher:d,company:p}=t,g=p==null?void 0:p.companyId;if(m||d)return{mode:"local"};if(i)return xf(t);if(l)return Wv(s,g,a,l,r,e);if(c)return Hv(s,g,a,c,r,e,t);throw new wt("Missing host or grid configuration")})()}var ti,Je,mn,vf,Ef,$v,fn,Af,ds=T(()=>{"use strict";ti=E(require("lodash"));be();U();j();ie();V();Je=x("grid-service"),mn={},vf=/(^(https?):\/{2})?(.*)/,Ef=null;$v=(r,e,t,s,n)=>{mn[r]={gridId:t,companyId:e,slotId:s,browser:n}};fn={start:qv,end:Kv};Af=async(r={},e={},t={},s={},n={})=>{var f,h,y;let{company:{companyId:o}={}}=r,{gridId:i,type:a}=e,c=r.browser||t.browserValue,l=Boolean(r.tunnel),{maxRetries:m,currentRetry:d}=n;if(!i||!a||(a===W.LAMBDATEST&&await((f=s.enableIfNeeded)==null?void 0:f.call(s,e)),a!==W.HYBRID||!o||!c||!m||!d))return e;let p=await tl({companyId:o,gridId:i,maxRetries:m,currentRetry:d,browser:c,usingTunnel:l});Je.info("handling hybrid grid",{response:p,companyId:o});let g=ri({...e,...p.connectionDetails,provider:p.provider});return p.provider!=="lambdatest"&&((h=s.disable)==null||h.call(s)),p.provider==="lambdatest"&&await((y=s.enableIfNeeded)==null?void 0:y.call(s,g)),g}});function hn(){return si||"master"}function Of(r="master",e="false"){if(typeof r!="string"&&(r!=null&&r.branch)&&r.branch==="master"){si="master";return}if(r&&!r.isArchived){si=r.branch||r;return}si=e?"master":void 0}var si,Kl=T(()=>{"use strict"});var yn,Jl,Xv,Yl,Qv,Xl,ni,oi,ii,ai,ci,li=T(()=>{"use strict";j();ie();yn=r=>{let{status:e,sessionType:t,success:s,mobile:n}=r;return n!=null&&n.isAppFromDevice||n!=null&&n.isAppForIosVirtualDevice||n!=null&&n.isMissingBrowserStackAppId?!1:e===de.FAILED||t===Lt.CODEFUL&&s===!1},Jl=r=>{let{status:e}=r;return e===de.ABORTED},Xv=r=>{let{status:e,sessionType:t,success:s}=r;return e===de.PASSED||t===Lt.CODEFUL&&s===!0},Yl=r=>r.runnerStatus===dc.SKIPPED,Qv=r=>r.testStatus===ze.EVALUATING,Xl=(r,e)=>e?!r.runConfig:!1,ni=(r,e)=>Object.values(r).filter(t=>{var s,n,o;return Yl(t)&&(Ke(t,e)||((s=t.mobile)==null?void 0:s.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice)||((o=t.mobile)==null?void 0:o.isMissingBrowserStackAppId))}).length,oi=r=>Object.values(r).filter(e=>yn(e)&&Qv(e)).length,ii=(r,e)=>Object.values(r).filter(t=>yn(t)&&!Xl(t,e)),ai=(r,e)=>Object.values(r).filter(t=>Xv(t)&&!Xl(t,e)),ci=(r,e)=>Object.values(r).filter(t=>Jl(t)&&!Xl(t,e))});function Zv(r){let e=r.indexOf("--token");if(e===-1&&(e=r.indexOf("--t")),e!==-1)try{let t=r.slice();return t.splice(e,2),t}catch{}return r}var ui,Lf,pi,Df=T(()=>{"use strict";U();li();ui=x("debug-reporter"),Lf={token:void 0,userParamsData:void 0,projectData:void 0,allGrids:void 0,gridData:void 0,awsAccessKeyId:void 0,awsSecretAccessKey:void 0,runParams:void 0,perfecto:void 0,testobjectSauce:void 0},pi=class{constructor(e){this.options=e}onTestStarted(e,t){ui.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let s=this.options.gridData||{},n=s.provider,o=s.host,i=s.gridId,a=s.type,c=s.failedGetBrowserAttempts;ui.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:o,failedGetBrowserAttempts:c,id:i,type:a},workerId:t})}onTestPlanStarted(e,t,s,n,o,i,a){let c=Zv(process.argv);ui.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:Object.assign({},this.options,Lf),args:c})}onTestPlanFinished(e,t,s,n,o,i){let a=ai(e,i).length,c=Object.keys(e).length-a;ui.info("Test Plan Finished",{isAnonymous:o,passed:a,failed:c,testPlanName:t,options:Object.assign({},this.options,Lf),duration:s,executionId:n})}}});var Ql,xt,bn=T(()=>{"use strict";ie();Ql=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===W.DEVICE_FARM}},xt=new Ql});var eu={};$(eu,{Reporter:()=>eE});var er,Tn,xr,di,Nf,Zl,eE,tu=T(()=>{"use strict";er=E(require("chalk")),Tn=E(require("lodash"));j();ie();bn();li();xr={success:er.default.green,warn:er.default.yellow,error:er.default.red},{CLI_MODE:di}=Dt,Nf="device",Zl=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,s,n){let o=n?"File":"Test",i=e.isTestsContainer?"":`(${e.testId})`,a=e.isTestsContainer?"":`url: ${er.default.underline(nt(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`${o} "${e.name}" started ${i} ${a}`.trim())}onTestFinished(e,t,s,n){if(n)return;let o=e.success?de.PASSED:de.FAILED,i=e.isTestsContainer?" ":`(${e.testId})`,a=xr[e.success?"success":"error"];console.log(a(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${o} ${i} duration: ${ao(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(s=>{let n=nt(this.options.editorUrl,this.options.project,s.testId,s.resultId,this.branchToUse);return s.isTestsContainer?s.name:`${s.name} : ${n}`});console.log(xr.error("Failed runs are:")),console.log(xr.error(t.join(`
|
|
27
|
+
\r`)))}onTestPlanFinished(e,t,s,n,o,i){let a=ii(e,i),c=ai(e,i),l=ci(e,i),m=c.length,d=l.length,p=a.length,g="",f="";if(xt.isTestStatusEnabled){let b=oi(e);g=` FAILED-EVALUATING: ${b}`,p-=b,f=` SKIPPED: ${ni(e,this.options)}`}let h=this.buildTestPlanName(o,t,i),y,w=xr[p?"error":"success"],S=`PASSED: ${m} FAILED: ${p}${g} ABORTED: ${d}${f} Duration: ${ao(s)}`;i||h.trim()===""||h.trim()==="Anonymous"?y=`Tests completed. ${S} (Execution ID: ${n})`:y=`Test plan${h} completed ${S} (${n})`,this.printWorkerDivider(),console.log(w(y)),this.printWorkerDivider(),this.printAllFailedTests(a)}buildTestPlanName(e,t,s){if(s)return"";let n=Tn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,o=Tn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=Tn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,a=Tn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,c=[i,o,n,a].filter(Boolean).join(", ");return e?` anonymous (${c})`:` '${t}'`}onTestPlanStarted(e,t,s,n,o,i,a,c){let l=p=>{p.forEach((g,f)=>{var w;let h=(w=g.testData)!=null&&w.index?`- ${g.testData.index} / ${g.testData.total} Data set`:"",y=c?"":`(${g.testId})`;console.log(" ",f+1,":",`${g.name}${Ke(g,this.options)?"-quarantine":""}`,y,h)})},m=a?`config '${a}'`:"default configs";if(c)console.log(`Run test plan, Project: ${this.options.project} (Execution ID: ${o}):`);else{let p=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",g=`${m}, Project: ${this.options.project}, Branch: ${this.branchToUse}${p}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${g} (${o})`)}this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log(c?"File list:":"Test list:"),l(t),s.length>0&&(console.log("After all:"),l(s)),this.printWorkerDivider()}onGetSlot(e,t){let s=this.options.grid||this.options.gridId,n=this.options.mode===di.APPIUM?Nf:t;s&&console.log(this.toWorkerIdPrefix(e),`Get ${er.default.underline(n)} slot from ${er.default.underline(s)}`)}onGetSession(e,t,s){let n=s===di.APPIUM?Nf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${er.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e,t,s){let n=t?"file":"test";console.log(this.toWorkerIdPrefix(e),`Wait for ${n} complete`),s&&t&&console.log(this.toWorkerIdPrefix(e),`Chrome Debugger available at ${s}`)}onGetBrowserFailure(e,t,s){if(s!==2)return;let n=this.options.grid||this.options.gridId,o=this.options.mode===di.APPIUM?"device":"browser";if(n)console.log(xr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${o} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(xr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===di.APPIUM?"Appium":"Selenium";console.log(xr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},eE=Zl});var nu={};$(nu,{Reporter:()=>iE});function tE(r){let e=r.testData||{},t=typeof e.total=="number"?` - ${e.index} / ${e.total} Data set`:"";return`${r.name}${t}`}function rE(r){return r.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${r.visitedUrlsList||""}`}function sE(r){return`${r.visitedUrlsJson||""}`}async function nE(r,e,t,s,n,o){function i(p){let g=nt(r,t,p.testId,p.resultId,s),f={$:{name:tE(p),classname:n,time:Tc(p.duration),ownedBy:p.testOwnerName,ownerEmail:p.testOwnerEmail},"system-out":g};if(yn(p)||Jl(p)){let h=`Step Failed: ${p.failureReason||p.reason}`,y=yn(p)?`${h} More info at: ${g}`:h;f.failure={$:{message:y}}}return Yl(p)&&Ke(p,o)&&xt.isTestStatusEnabled&&(f.skipped={}),o.urls&&(f["visited-urls-list"]=rE(p),f["visited-urls-json"]=sE(p)),f}function a(p){let{results:g,testPlanName:f,configName:h}=p,y=g||{},S={name:(h&&f?`${f} with config '${h}'`:f)||"selenium run",tests:l(y),failure:m(y),timestamp:c(e)};if(xt.isTestStatusEnabled){S.skipped=ni(y,o);let b=oi(y);S.failure-=b,S["failure-evaluating"]=b}return{$:S,testcase:Object.keys(y).map(b=>i(y[b]))}}function c(p){let g=Object.keys(p).map(h=>p[h].startTime),f=Math.min.apply(null,g);return f?new Date(f).toISOString():new Date().toISOString()}function l(p){return Object.keys(p).length}function m(p){return ii(p).length+ci(p).length}let d={testsuites:{testsuite:e.map(p=>a(p))}};try{return new su.Builder().buildObject(d)}catch(p){return oE(p)}}function oE(r){let e=new su.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:r.message}}}}}};return e.buildObject(t)}var su,Mf,ru,iE,ou=T(()=>{"use strict";su=E(require("xml2js"));j();Mf=require("fs");bn();li();ru=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,s=this.options.project,n=await nE(this.options.editorUrl,e,s,this.branchToUse,this.classname,this.options);if(t)try{return await Mf.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(o){return console.error("could not save report file",t,o),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};iE=ru});var Ff={};$(Ff,{Reporter:()=>aE});function ms(r){return r?r.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var iu,au,aE,Uf=T(()=>{"use strict";U();iu=x("team-city-reporter");au=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},s=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${s}`;return ms(n)}onTestStarted(e,t,s,n,o){if(s){iu.debug("skip report test started because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testStarted name='${i}' captureStandardOutput='true' flowId='${o}']`)}onTestFailed(e,t,s,n,o,i){if(o){iu.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ms(t)}' details='${ms(s)}' flowId='${i}']`)}onTestFinished(e,t,s){if(s){iu.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,s="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${ms(s)}']`)}onTestPlanStarted(e,t,s,n){console.log(`##teamcity[testSuiteStarted name='${ms(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ms(t)}']`)}},aE=au});var jf={};$(jf,{Reporter:()=>cE});var cu,cE,Bf=T(()=>{"use strict";cu=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,s,n,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},cE=cu});var $f={};$($f,{Reporter:()=>lE});var lu,lE,Wf=T(()=>{"use strict";j();xl();lu=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e,t,s,n){if(n)return;let o=nt(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Bo(o)}},lE=lu});var uE,uu,Q,jt=T(()=>{"use strict";Df();U();uE=x("reporter"),uu=class{constructor(){this.reporters=[];this.onGetBrowserFailure=this.generateHook("onGetBrowserFailure");this.onGetBrowserSuccess=this.generateHook("onGetBrowserSuccess");this.onTestPlanStarted=this.generateHook("onTestPlanStarted");this.onGetSlot=this.generateHook("onGetSlot");this.onGetSession=this.generateHook("onGetSession");this.onTestFinished=this.generateHook("onTestFinished");this.onTestFailed=this.generateHook("onTestFailed");this.onTestPassed=this.generateHook("onTestPassed");this.onTestStarted=this.generateHook("onTestStarted");this.onTestIgnored=this.generateHook("onTestIgnored");this.onWaitToTestStart=this.generateHook("onWaitToTestStart");this.onWaitToTestComplete=this.generateHook("onWaitToTestComplete");this.onTestPlanFinished=this.generateHook("onTestPlanFinished",this.onTestPlanFinishedMutator);this.onAllTestPlansFinished=this.generateHook("onAllTestPlansFinished",this.onAllTestPlansFinishedMutator)}async setOptions(e,t){this.reporters=[];let s=e.reporters;if(this.reporters.push(new pi(e)),s===void 0||s.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(tu(),eu));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(ou(),nu));this.reporters.push(new o(e,t))}}else(await Promise.all([s.includes("teamcity")&&Promise.resolve().then(()=>(Uf(),Ff)),s.includes("console")&&Promise.resolve().then(()=>(tu(),eu)),s.includes("junit")&&Promise.resolve().then(()=>(ou(),nu)),s.includes("json")&&Promise.resolve().then(()=>(Bf(),jf)),s.includes("chrome")&&Promise.resolve().then(()=>(Wf(),$f))])).forEach(o=>{o&&this.reporters.push(new o.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,s,n,o,i,a){let c={};if(a){let m=Object.values(a);if(m.length>0){for(let d of Object.values(a))c[d.id]=d;for(let d of Object.keys(e))m.some(p=>p.parentResultId!==d)||(c[d]=e[d])}else uE.warn("childTestResults is not array"),c=e}else c=e;let l=Date.now()-(s||0);return[c,t,l,n,o,i,void 0]}onAllTestPlansFinishedMutator(e){for(let t of e)if(t.childTestResults){t.results={};let s=Object.values(t.childTestResults);for(let n of s)t.results[n.id]=n;for(let n of Object.keys(e))s.some(o=>o.parentResultId!==n)||(t.results[n]=e[n])}return[e]}generateHook(e,t){return async(...s)=>{var o;let n=t==null?void 0:t(...s);for(let i of this.reporters)await((o=i[e])==null?void 0:o.call(i,...n||s))}}},Q=new uu});function Gf(r,e){return e!=null&&e.type&&(r[`${e.type}Mode`]=!0),r}function Vf({executionId:r,projectId:e,testId:t,resultId:s,companyId:n,companyName:o,projectName:i,companyPlan:a,sessionType:c,source:l,user:m,lightweightMode:d,isStartUp:p,projectType:g,appSource:f}){let h=Gf({executionId:r,projectId:e,testId:t,resultId:s,companyId:n,companyName:o,projectName:i,companyPlan:a,sessionType:c,source:Hf(l,m),isStartUp:p,projectType:g,...["android","ios"].includes(g)&&f&&{appSource:f}},d);ut("test-run-ci",h)}function qf({executionId:r,projectId:e,testId:t,resultId:s,result:n,companyId:o,companyName:i,projectName:a,companyPlan:c,sessionType:l,source:m,user:d,lightweightMode:p,logger:g,isStartUp:f,projectType:h,appSource:y}){try{let w=Gf({executionId:r,projectId:e,testId:t,resultId:s,companyId:o,companyName:i,projectName:a,companyPlan:c,sessionType:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:Hf(m,d),isStartUp:f,projectType:h,...["android","ios"].includes(h)&&y&&{appSource:y}},p);if(n.success){ut("test-run-ci-success",w);return}ut("test-run-ci-fail",Object.assign({},w,{failureReason:n.failureReason}))}catch(w){g.error("failed to update test end analytics",{err:w})}}function zf({executionId:r,projectId:e,sessionType:t}){ut("batch-run-ci",{executionId:r,projectId:e,sessionType:t})}var Hf,pu=T(()=>{"use strict";cs();Co();Hf=(r,e)=>r!=="cli"&&r!=="cli-local"?r:ss&&e?"ci-with-user":ss?"ci":e?"cli-with-user":r});var Jf,mi,Yf=T(()=>{"use strict";Jf=require("istanbul-lib-report"),mi=class extends Jf.ReportBase{constructor(t){super();t||(t={}),this.appendToObject=t.appendToObject||{}}onStart(t){let s=t.getCoverageSummary(!1);this.appendToObject=Object.assign(this.appendToObject,s.toJSON())}}});var Xf,Qf,Zf,wn,mt,eg,fi,du,tg,pE,rg,sg,dE,mE,ng,fE,gE,hE,yE,bE,og,ig=T(()=>{"use strict";Xf=E(require("ora")),Qf=E(require("moment")),Zf=E(require("test-exclude")),wn=E(require("fs")),mt=E(require("path")),eg=E(require("istanbul-reports")),fi=E(require("istanbul-lib-report"));be();V();j();U();dt();Yf();du=x("test-run-status"),tg=r=>{try{return new URL(r)}catch{try{return new URL(`file://${r}`)}catch{return{}}}},pE=r=>!!tg(r).search,rg=r=>r?tg(r).pathname.substring(1):"",sg=(r,e)=>{let t=rg(e);return!new Zf.default({relativePath:!1,include:r}).shouldInstrument(t)},dE=r=>r.substring(0,r.indexOf("?")),mE=async({source:r,sourceMapDir:e,sourceMapType:t})=>{let s=await le("convert-source-map");if(t==="file"&&!e)throw new k("--code-coverage-source-map-path [path]");return e?s.fromMapFileSource(r,e):s.fromSource(r)},ng=(r,e)=>`${mt.resolve(r,rg(e))}.js`,fE=async(r,e,t)=>{let{codeCoverageInclude:s}=r;await ce(Object.values(t),async n=>{if(!n)return;let o=n.toObject();await ce(o.sources,async(i,a)=>{if(sg(s,i))return;let c=ng(e,i);await wn.promises.mkdir(mt.parse(c).dir,{recursive:!0}),await wn.promises.writeFile(c,o.sourcesContent[a])})})},gE={getPath(r){if(typeof r=="string")return r;let e=r.getQualifiedName();return r.isSummary()?e!==""?e+="/index.html":e="index.html":(pE(e)&&(e=dE(e)),e+=".html"),e},relativePath(r,e){let t=this.getPath(e),s=mt.dirname(this.getPath(r));return mt.posix.relative(s,t)},assetPath(r,e){return this.relativePath(this.getPath(r),e)}},hE=async(r,e,t,s)=>{let{codeCoverageReporter:n}=r,o={},i=fi.createContext({dir:t,coverageMap:e,watermarks:fi.getDefaultWatermarks(),sourceFinder:a=>{try{let c=ng(s,a);return wn.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new mi({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:gE}),eg.create(a,c).execute(i)}),o},yE=async(r,{source:e,sourceMap:t,functions:s})=>{let{codeCoverageInclude:n}=r;if(!t||t.sourcemap.sources.length===0)return;let i=(await le("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>sg(n,a));return await i.load(),i.applyCoverage(s),i.toIstanbul()},bE=async(r,e)=>{let{mergeProcessCovs:s}=await le("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await on(r,"testResult",`runId=${e}`)).data.docs;return await ce(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await nn(c,9e4);await ce(l,async m=>{if(!o.has(m.url)){let d=m.text;m.sourceUrl&&(o.set(m.url,"TEMP"),d=await Wc(m.sourceUrl)),o.set(m.url,{text:d,url:m.url,sourceMapType:m.sourceMapType,hash:m.hash})}delete m.text,n=s([n,{result:[m]}])})},{concurrency:20}),{covUrlMap:o,mergedCoverages:n}},og=async(r,e,t,s)=>{if(!r.collectCodeCoverage)return;du.info("start js coverage process");let n=(0,Xf.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=mt.resolve(r.codeCoverageReportPath||"./coverage"),i=mt.resolve(o,`.js/${(0,Qf.default)().format("DDMMYYYYHHmmss")}`),a=r.codeCoverageSourceMapPath?mt.resolve(r.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:m}]=await Promise.all([le("istanbul-lib-coverage"),bE(r.project,s)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}du.info("start js coverage merge and remap",{numOfFiles:m.size,numMergedCoverages:l.result.length});let d=c.createCoverageMap({}),p={};await ce(l.result,async({url:f,functions:h})=>{let{text:y,sourceMapType:w}=m.get(f),S=await mE({sourceMapType:w,source:y,sourceMapDir:a});p[f]=S;let b=await yE(r,{source:y,sourceMap:S,functions:h});d.merge(b)}),await fE(r,i,p);let g=await hE(r,d,o,i);return n.succeed(),g}catch(c){let l="Failed to report coverage information";c instanceof k?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),du.error(l,{err:c})}}});var ag={};$(ag,{SELENIUM_PERF_MARKS:()=>Ce,SeleniumPerfStats:()=>Bt});var Ce,Bt,fs=T(()=>{"use strict";j();Ce={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Bt=class{constructor(){this.marks=Object.fromEntries(Object.values(Object.assign({ALL:"ALL"},Ce)).map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=J();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let s=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(s);return}this.marks[t].push(s)}getStats(){let e=Object.entries(this.marks).flatMap(([t,s])=>!Array.isArray(s)||!s.length?[]:[[`${t}_COUNT`,s.length],[`${t}_P50`,uo(s,50)],[`${t}_P95`,uo(s,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var pg={};$(pg,{initServer:()=>vE,mapFilesToLocalDrive:()=>fu});function fu(r,e){var t;try{r.failurePath=(r.failurePath||[]).map(s=>Object.assign(s,gi[s.id]?{screenshot:gi[s.id]}:{})),Object.keys(gs).forEach(s=>{r.assets||(r.assets={}),r.assets[ug[s]]=gs[s]}),r.assets||(r.assets={}),r.assets.screenshots=Object.values(gi)}catch(s){e&&e.error("failed to map files to local drive",{err:s}),r.failurePath||(r.failurePath=[]),r.assets||(r.assets={}),(t=r.assets).screenshots||(t.screenshots=[])}}async function vE({agentPort:r,agentBind:e,saveRCALocally:t}){let s=await le("multer"),n=typeof t=="string"?t:TE;await mu.promises.mkdir(n,{recursive:!0});let o=s({storage:s.diskStorage({async destination(c,l,m){let d=JSON.parse(c.body.metadata||"{}");if(!d.testResultId)return m(new Error("missing testResultId"),"");let p=vn.join(n,d.testResultId);try{await mu.promises.mkdir(p,{recursive:!0})}catch(g){return m(g,"")}return m(null,p)},filename(c,l,m){let{fileName:d}=c.body,p=JSON.parse(c.body.metadata||"{}");if(!p.stepId&&!d)return m(new Error("missing stepId or fileName"),"");if(p.stepId){let g=vn.extname(d);return m(null,`step_${p.stepId}_${p.stepName||""}${g}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return m(null,d)}})}),i=(0,lg.default)();i.post("/",o.single("file"),(c,l)=>{var d;let m=JSON.parse(c.body.metadata||"{}");m.stepId&&(gi[m.stepId]=c.file.path),m.testResultId&&wE.includes(m.subType)&&(gs[d=m.subType]||(gs[d]=[]),gs[m.subType].push(c.file.path)),l.sendStatus(200)}),i.use((c,l)=>l.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,l)=>{let m=a(i);m.listen(r,e),m.on("error",d),m.on("listening",()=>c(m.address()));function d(p){if(p.syscall!=="listen")return l(p);switch(p.code){case"EACCES":case"EPERM":return l(new k(`Port ${r} requires elevated privileges`));case"EADDRINUSE":return l(new k(`Port ${r} is already in use`));default:return l(p)}}})}var mu,cg,vn,lg,TE,gi,gs,ug,wE,gu=T(()=>{"use strict";mu=E(require("fs")),cg=E(require("os")),vn=E(require("path")),lg=E(require("express"));V();dt();TE=vn.join(cg.tmpdir(),"testim/rca/"),gi={},gs={},ug={"test-log":"consoleLogs","har-file":"networkLogs"},wE=Object.keys(ug)});var tr,hu,hi,dg=T(()=>{"use strict";tr=E(require("lodash"));j();U();hu=x("override-test-data-builder"),hi=class{constructor(e,t,s){this.params=e;this.testInfoList=t;this.projectId=s}isObjectNotArray(e){return tr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&typeof e.overrideTestData<"u"&&(this.isObjectNotArray(e.overrideTestData)&&!tr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(s=>this.overrideSingleTest(s,e.overrideTestData[s])),delete e.overrideTestData):hu.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&typeof e.overrideAllTestsData<"u"&&(tr.isObject(e.overrideAllTestsData)&&!tr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):hu.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:s}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}hu.error("skip override test data to test name",{testName:e,projectId:s}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let s=this.mapTestListToUniqueId(e);if(s.length!==0)return this.createNewTestPerOverrideTestData(s,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return tr.chain(t).map(s=>{if(s.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(s)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:s}=this;return[...new Set(e)].map(n=>{let o=s.map(m=>this.generateTestUniqId(m)),i=o.indexOf(n),a=o.lastIndexOf(n),c=s[i],l=this.createNewTestItems(c,t);return s.splice(i,a-i+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((s,n)=>{let o=J();return Object.assign({},e,{resultId:o,testData:{value:s,index:n+1,total:t.length||1}})})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function yi(r,...e){if(!(!r||typeof r!="function"))try{return await r(...e)||{}}catch(t){throw Ye.warn("failed to run hook",{err:t}),new k(`failed to run hook promise ${t.message}`)}}var kr,Ye,EE,SE,RE,IE,bi,mg=T(()=>{"use strict";kr=E(require("lodash"));j();ie();ds();be();V();U();jt();ln();ig();fs();gu();pe();Te();dg();bn();Ye=x("test-run-status"),EE=Tr(),SE=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,RE=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,IE=ot();bi=class{constructor(e,t,s,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new Bt;var a,c,l,m,d;(a=this.options).runParams||(a.runParams={}),this.fileUserParamsData=this.options.userParamsData;let o=Gs(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:eo||t.parallel||1,browser:o,gitBranch:EE,gitCommit:SE,gitRepoUrl:RE,runnerVersion:IE,gridHost:t.host||((c=t.gridData)==null?void 0:c.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:s,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(p=>p.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:i,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((m=t.gridData)==null?void 0:m.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:yr(t)},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:s,projectId:n,executionId:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:c,isTestsContainer:l,testId:m,name:d,testStatus:p,testCreatorName:g,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:y,testLabels:w,testSuites:S,allLabels:b}=a,v={originalTestResultId:t,previousTestResultId:s,config:kr.cloneDeep(c),testId:m,status:"QUEUED",name:d,resultId:e,isTestsContainer:l,retryCount:i,testStatus:p};return this.testRunStatus[e]=Object.assign({},v,{testCreatorName:g,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:y,testLabels:w,testSuites:S,allLabels:b}),pl({projectId:n,runId:o,testId:m,newResultId:e,originalTestResultId:t,previousTestResultId:s,testResult:v})}getAllTestResults(){return this.testRunStatus}testStart(e,t,s,n){let o=this.getTestResult(s);o.workerId=e;let i=this.options.files.length>0;return Q.onTestStarted(o,e,n,i,s),o}async updateTestStatusRunning(e,t,s){var l;let{project:n,remoteRunId:o,projectData:i}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Lo(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(m){Ye.error("failed to upload test data artifact (runner)",{err:m})}let c=kr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,os(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:o,testRetryKey:s})}async testStartReport(e,t,s){if(Ke(e,this.options))return;let n=this.exportsGlobal;try{let o=await yi(this.options.beforeTest,Object.assign({},e,{exportsGlobal:n,globalParameters:n}),this.options.userData.loginData.token);return e.config.testData=Object.assign({},e.config.testData,this.exportsGlobal,this.fileUserParamsData,this.beforeSuiteParams,o),this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,s),e}catch(o){throw Ye.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,s,n,o){let i=this.testStart(e,t,s,n);return this.testStartReport(i,t,o)}onGridSlot(e,t){let s=this.getTestResult(e);s.config.gridInfo=Object.assign({},t,{key:void 0,user:void 0}),Ye.info("on get grid info",{gridInfo:s.config.gridInfo})}reportTestStatus(e,t,s,n){let{name:o,testId:i,testStatus:a}=s,{resultId:c,success:l}=t;if(a===ze.EVALUATING&&xt.isTestStatusEnabled){Q.onTestIgnored(e,s,`test in ${ze.EVALUATING} status`);return}if(l){Q.onTestPassed(o);return}Q.onTestFailed(s,s.failureReason,nt(this.options.editorUrl,this.options.project,i,c,this.branchToUse),i,n,c)}calcResultText(e){return e.success?de.PASSED:de.FAILED}onTestIgnored(e,t){let s=this.getTestResult(t);Q.onTestIgnored(e,s,`test in ${ze.QUARANTINE}`)}monitorMemoryUsage(e){let t=wc();if(t.isOverThreshold){let s=M.flags.useLinkedomToParseHtml.isEnabled()?"linkedom":"jsdom";Ye.info(`using ${s} to parse html`,{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}}testEnd(e,t,s,n,o){let i=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;i.sessionId=n,i.startTime=t.startTime||i.startTime||Date.now(),i.duration=a,t.duration=a,i.failureReason=t.failureReason||t.reason,t.failureReason=i.failureReason,i.failurePath=t.failurePath,i.resultId=t.resultId,i.success=t.success,this.options.saveRCALocally&&fu(i,Ye),i.resultUrl=nt(this.options.editorUrl,this.options.project,i.testId,i.resultId,this.branchToUse),i.status=this.calcResultText(t),t.status=i.status,t.name=i.name,t.testStatus=i.testStatus,t.testId||(t.testId=i.testId),t.testCreatorName=i.testCreatorName,t.testCreatorEmail=i.testCreatorEmail,t.testOwnerName=i.testOwnerName,t.testOwnerEmail=i.testOwnerEmail,t.testData=i.config&&typeof i.config.testDataTotal=="number"?{total:i.config.testDataTotal,index:i.config.testDataIndex}:{},this.reportTestStatus(e,t,i,o);let c=this.options.files.length>0;this.monitorMemoryUsage(i),Q.onTestFinished(i,e,o,c);let l=Object.assign({},this.exportsGlobal,t.exportsGlobal);return this.exportsGlobal=l,i}async testEndReport(e,t,s,n){var i;let o=s.exportsGlobal;try{try{await yi(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){Ye.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(i=this.options.lightweightMode)!=null&&i.onlyTestIdsNoSuite?void 0:await os(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:s.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw Ye.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,s,n,o,i){let a=this.testEnd(e,t,s,n,o);return this.testEndReport(a,s,t,i)}getMobileRunSkippedReason(e,t,s){let n="",{APP_FROM_DEVICE:o,VIRTUAL_BUILD:i,MISSING_BROWSERSTACK_APP_ID:a}=gc;return e&&(n=o),Jr(s)&&(n=i),t&&(n=a),n}calcTestRunStatus(){let{options:e,testInfoList:t}=this,s=e.company.companyId,n=t.map(o=>{var g,f,h,y,w,S;let i=e.browser?Js(e.browser,e.saucelabs,e.browserstack):o.runConfig;if(i&&M.flags.dec2022eolBrowsers.isEnabled()&&((g=Ks(i.browserValue))!=null&&g.eol))throw new k(`Unsupported Browser: ${i.browserName}`);let a=!M.flags.allowAppFromDeviceRuns.isEnabled()&&qs(o.nativeApp),l=((f=e.gridData)==null?void 0:f.type)===W.BROWSERSTACK&&!((h=o.nativeApp)!=null&&h.browserStackAppId),m=Yr(e)&&(Jr(o.nativeApp)||a||l),d=Ke(o,e)||m,p={testId:o.testId,status:d?de.SKIPPED:de.QUEUED,name:o.name,resultId:o.resultId,isTestsContainer:o.isTestsContainer,testStatus:o.testStatus||ze.DRAFT,testCreatorName:o.creatorName,testCreatorEmail:o.creatorEmail,testOwnerName:o.testOwnerName,testOwnerEmail:o.testOwnerEmail,testLabels:o.testLabels,testSuites:o.testSuites,allLabels:o.allLabels,...m&&{reason:this.getMobileRunSkippedReason(a,l,o.nativeApp)},config:Object.assign({},this.execConfig,{companyId:s,testData:((y=o.testData)==null?void 0:y.value)||null,isBeforeTestPlan:o.isBeforeTestPlan,isAfterTestPlan:o.isAfterTestPlan,testDataTotal:((w=o.testData)==null?void 0:w.total)||null,testDataIndex:((S=o.testData)==null?void 0:S.index)||null,baseUrl:e.baseUrl||o.baseUrl||o.testConfig.baseUrl,testConfig:o.overrideTestConfig||o.testConfig,browser:i.browserValue.toLowerCase()})};return[o.resultId,p]});return Object.fromEntries(n)}async executionStart(e,t,s,n,o){Ye.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:c}=i;is(()=>Promise.all([fn.end(t),Oo("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=s||Date.now();let l={projectId:t,executionId:e,...M.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},m=await yi(i.beforeSuite,l),d=new hi(m,kr.cloneDeep(this.testInfoList),t);this.testInfoList=d.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=m;let{testInfoList:p}=this,g=[],f=[],h=[];for(let w of p){if(w.isBeforeTestPlan){g.push(w);continue}if(w.isAfterTestPlan){h.push(w);continue}f.push(w)}let y=async()=>{let w=kr.cloneDeep(this.testRunStatus);await ce(Object.keys(w),async I=>{var C;let A=w[I],_=(C=A.config)==null?void 0:C.testData,R=A.testId,L=await Lo(t,R,I,_,c.defaults);L&&(delete A.config.testData,A.config.testDataUrl=L)});let S=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),b={executionId:e,projectId:t,labels:n||[],startTime:s,executions:w,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:S,intersections:i.intersections},v=zc(b);return this.executionStartedPromise=v,v.catch(I=>Ye.error(I)),v};try{await y()}catch(w){Ye.error("Failed to start suite",{err:w}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:f,afterTests:h}}concatSeleniumPerfMarks(e){kr.chain(e).keys().each(t=>{let s=t;this.seleniumPerfStats.marks[s]&&(this.seleniumPerfStats.marks[s]=[...this.seleniumPerfStats.marks[s],...e[s]])}).value()}async executionEnd(e){var m;let t=Ec(this.testRunStatus),s=t.length,n=0,o=0,i=0;for(let{status:d,testStatus:p}of t)d===de.PASSED&&n++,d===de.SKIPPED&&o++,d===de.FAILED&&p===ze.EVALUATING&&i++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await yi(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:s,passed:n,skipped:o})}catch(d){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Ye.warn("error while running afterSuite Hook",{err:d,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await og(this.options,this.branchToUse,s,e);if(Object.assign(c,{coverageSummary:l}),!((m=this.options.lightweightMode)!=null&&m.onlyTestIdsNoSuite))try{return await Oo("FINISHED",e,this.options.project,s===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(d){throw Ye.error("Failed to update suite finished",{err:d}),d}}async markAllQueuedTests(e,t,s,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await qc(e,["QUEUED"],t,s,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=s,a.success=n}return this.testRunStatus}}});function xE(r){let e=gg(r);return r===W.TESTIM_HEADSPIN?`${e}/lock`:""}function gg(r){return r===W.TESTIM_HEADSPIN?"https://api-dev.headspin.io/v0/devices":""}function hg(r){return{...r.type===W.TESTIM_HEADSPIN&&{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`}}}function kE(r,e){return{...r.type===W.TESTIM_HEADSPIN&&{device_id:e}}}async function yg(r,e){let t=xE(r.type),s=hg(r),n=kE(r,e);try{await Qe({url:t,headers:s,body:n})}catch(o){throw fg.debug(`error while locking device ${e}`,{error:o}),o.status===401?new Error(`failed to lock device ${e}, device may be already locked and in use`):o}}async function yu(r,e){let s=`${gg(r.type)}/device_id:${e}/automation-config`;try{let n=await Ot(s,void 0,hg(r));return PE(n,r.accessToken)}catch(n){throw fg.error("error while getting automation config for device",{error:n,deviceId:e}),n}}function PE(r,e){let t=Object.keys(r)[0],s=r[t].driver_url,n=new URL(s);return{hostname:n.hostname,port:Number(n.port),protocol:n.protocol.slice(0,-1),path:`/v0/${e}/wd/hub`}}async function bg(r,e){let t={};return r.type===W.TESTIM_HEADSPIN&&(t=await yu(r,e)),t}function Tg(r){if(r.type===W.TESTIM_HEADSPIN)return{protocol:r.protocol||"https",hostname:r.host,port:r.port,path:`/v0/${r.accessToken}/wd/hub`};if([W.BROWSERSTACK,W.SAUCELABS].includes(r.type))return{protocol:r.protocol||"https",hostname:r.host,port:r.port,path:"/wd/hub",user:r.user,key:r.key}}async function wg(r,e,t){var g;let{executionId:s,testId:n,testResultId:o}=r,{project:i,projectData:{type:a}={},company:{companyId:c=""}={},gridData:{gridId:l="",type:m=""}={}}=t,d=e.capabilities.device||e.capabilities.testobject_device_name;if(m===W.TESTIM_HEADSPIN){let f=await yl({projectId:i,projectType:a,companyId:c,gridId:l,selectors:`device_id:${e.capabilities.udid}`});d=(g=f==null?void 0:f[0])==null?void 0:g.name}let p={name:d,model:e.capabilities.deviceModel,osVersion:e.capabilities.platformVersion,udid:e.capabilities.udid,osType:e.capabilities.platformName,scaleFactor:e.capabilities.pixelRatio,virtual:!1};await os(i,s,n,o,"RUNNING",{device:p})}var fg,bu=T(()=>{"use strict";U();ie();be();at();fg=x("mobile-grid-service")});function AE(r,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(r.desiredCapabilities,t),r}function Su(r){return Sg.readFileSync(r,{encoding:"base64"})}function kg(r,e,t){if(!(t!=null&&t.isLambdatestRun()&&We(r))&&r){let s=Su(r);hs.info(`adding extension: custom, path: ${r} length: ${s.length} hash: ${Eu(s)} current extension count: ${e.length}`),e.push(s)}}function Pg(r,e,t,s,n){if(n!=null&&n.isLambdatestRun())return;if(r.ext||s){let c=typeof r.ext=="string"?r.ext:`${__dirname}/..`,l=s||c,m=`--load-extension=${l}`;hs.info(`adding extension: testim unpacked , path: ${l}`),t.push(m);return}let o=r.canary?"-master.zip":".zip",i=vu.join(process.cwd(),`testim-headless${o}`),a=Su(i);hs.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${Eu(a)} current extension count: ${e.length}`),e.push(a)}function OE(r,e,t,s,n,o,i){var f,h;let a=t.seleniumName||t.browserValue,c=[],l=[...xg];e.headless&&l.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},w3c:!0};wu(n)&&(m.prefs["download.default_directory"]="C:\\Users\\testnode",r.desiredCapabilities.version="latest-1",r.desiredCapabilities["aws:maxDurationSecs"]=2400,r.desiredCapabilities["aws:idleTimeoutSecs"]=60),wu(n)&&a==="MicrosoftEdge"&&(r.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(y=>l.push(`--${y}`)),e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Tu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&l.push(`--user-data-dir=${e.chromeUserDataDir}`),(h=(f=e.projectData)==null?void 0:f.defaults)!=null&&h.disableChromiumGpu&&l.push("--disable-gpu"),Object.assign(r.desiredCapabilities,{browserName:a});function d(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+mc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}d(),kg(s,c,i),e.mode===Y.EXTENSION&&Pg(e,c,l,o,i),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=l;let p={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],g={MicrosoftEdge:"ms",chrome:"goog"}[a];return Z.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(r.desiredCapabilities[p]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(r.desiredCapabilities[`${g}:${p}`]=m),r}function LE(r,e,t){let s={"pdfjs.disabled":!0};if(M.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(s,{"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(r.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:s}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(r.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.mode===Y.EXTENSION)if(e.ext)r.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=vu.join(process.cwd(),`testim-firefox-profile${n}`);r.desiredCapabilities.firefox_profile=Su(o)}return e.headless&&(r.desiredCapabilities["moz:firefoxOptions"].args||(r.desiredCapabilities["moz:firefoxOptions"].args=[]),r.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),r}function DE(r,e,t){let{saucelabs:s}=r;if(s!=null&&s.username&&s.accessKey){let n={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=s.appiumVersion||t.sl.appiumVersion;let o=(0,Ig.cloneDeep)(t.sl);return t.sl.screenResolution&&(n["sauce:options"].screenResolution=t.sl.screenResolution,delete o.screenResolution),Object.assign({},o,s,n)}return Object.assign({},s,n)}return{}}function NE(r,e,t){return ft.isEmpty(r.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}}),Object.assign({},t.bs,r.browserstack,{name:e})):Object.assign({},r.browserstack,{name:e})}function ME(r){return r.perfecto?r.perfecto:{}}function FE(r,e,t){if(r.experitestToken){let s=e==="safari";return{accessKey:r.experitestToken,browserVersion:"latest",platformName:s?"MAC":"WIN10",seleniumScreenshot:s,newSessionWaitTimeout:t}}return{}}function UE(r,e={}){let{gridData:t={},gridUsername:s,gridPassword:n}=r,o=s||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=Ua(o,i)),a}function Ti(r,e,t,s,n,o,i,a=null){var h,y,w,S,b,v;if(s.mode==="local"){let I=[],A=[...xg],_={};return r.headless&&A.push("--headless"),r.silentDebuggerExtensionApi&&A.push("--silent-debugger-extension-api"),r.remoteDebuggingPort!==void 0&&A.push(`--remote-debugging-port=${r.remoteDebuggingPort}`),r.chromeExtraArgs&&r.chromeExtraArgs.forEach(R=>A.push(`--${R}`)),r.chromeBinaryLocation&&(_.binary=r.chromeBinaryLocation),r.mode!=="selenium"&&Pg(r,I,A,null,a),kg(n,I,a),{logLevel:vg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:A,extensions:I,..._},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:c,driverRequestRetries:l}=r,m=UE(r,s),d={hostname:s.host,host:s.host,port:s.port||4444,path:s.path||"/wd/hub",protocol:s.protocol||"http",logLevel:vg,connectionRetryTimeout:c,connectionRetryCount:l,getSessionTimeout:Math.max(a.getSessionTimeout,r.getSessionTimeout),getSessionRetries:a.getSessionRetries||r.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!ft.isEmpty(m)&&{headers:m},...r.proxyForGrid&&{agent:global.ProxyAgent(global.proxyUri)}};wu(s)&&(r.oldCapabilities=!1,r.w3cCapabilities=!0,d.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),r.disableNativeEvents&&(d.desiredCapabilities.nativeEvents=!1),s.user&&s.key&&(s.type==="saucelabs"&&(r.saucelabs||(r.saucelabs={}),(h=r.saucelabs).username||(h.username=s.user),(y=r.saucelabs).accessKey||(y.accessKey=s.key)),s.type==="browserstack"&&(r.browserstack||(r.browserstack={}),(w=r.browserstack)["browserstack.user"]||(w["browserstack.user"]=s.user),(S=r.browserstack)["browserstack.key"]||(S["browserstack.key"]=s.key))),s.key&&s.type==="perfecto"&&(r.perfecto.securityToken=s.key);let p=Number(r.browserTimeout/1e3),g=r.browser||(t==null?void 0:t.browserValue);ft.merge(d.desiredCapabilities,DE(r,e,t),NE(r,e,t),ME(r),FE(r,g,p),a==null?void 0:a.getCapabilities(r,g,o,i,e));let f=null;switch(!r.ext&&!r.extensionPath&&((b=s.host)!=null&&b.endsWith(".testim.io"))&&!r.canary&&r.mode===Y.EXTENSION&&(g==="chrome"?f="/opt/testim-headless":g==="edge-chromium"&&(f="C:/selenium/testim-headless")),(v=s.host)!=null&&v.endsWith(".testim.io")&&g==="edge-chromium"&&(d.desiredCapabilities.version="83"),g){case"chrome":case"edge-chromium":d=_E(d,r,t,n,s,f,a);break;case"firefox":d=LE(d,r,a);break;case"safari":case"safari technology preview":d=AE(d,g);break;default:break}ft.merge(d.desiredCapabilities,r.seleniumCapsFileContent);try{let I={"hub.lambdatest.com":"lambdatest",[M.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},A=C=>C[s.provider]||C[d.host]||C[I[d.host]],_=C=>{var N,B;return A(C)||C[(N=d.desiredCapabilities)==null?void 0:N.browserName]||C[(B=d.desiredCapabilities)==null?void 0:B.version]||C||{}},R=JSON.parse(M.flags.addCustomCapabilities.getValue()||"{}"),L=_(_(R));Object.keys(L).length&&(hs.info(`Adding custom capabilities: ${JSON.stringify(L)}`),Object.assign(d.desiredCapabilities,L))}catch(I){hs.error("Failed to load custom capabilities",{error:I,customCapabilities:M.flags.addCustomCapabilities.getValue()})}return d.desiredCapabilities&&!d.capabilities&&(CE(d),d.capabilities={alwaysMatch:d.desiredCapabilities,firstMatch:[{}]},delete d.desiredCapabilities),d.hostname=d.host,d}function Cg({nativeApp:r,appPath:e,gridInfo:t}){if(!r&&!e)throw Error("missing mobile app!");if(![W.BROWSERSTACK,W.SAUCELABS,W.TESTIM_HEADSPIN].includes(t.type))throw Error("unsupported grid was detected please make sure to select supported mobile grid")}function Ag({projectType:r,nativeApp:e,appPath:t,androidActivityWait:s,sessionTags:n,options:o,isHSAppIdExists:i}){let{fullReset:a,resetAppData:c,resetOnSessionStartOnly:l,skipLoadBalancer:m}=o,{executionId:d,testResultId:p}=n,g=i?{"headspin:app.id":t}:{"appium:app":t},f={"headspin:capture":!0,...m&&{"headspin:controlLock":!0},"headspin:retryNewSessionFailure":!1,"headspin:sessionTags":[{executionId:d},{testResultId:p}],...!a&&!c&&{"appium:noReset":!0},...!a&&c&&{"appium:noReset":!1}};switch(r){case"ios":f={...f,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest",...a&&{"appium:fullReset":a,"appium:resetOnSessionStartOnly":l},...e&&{"appium:bundleId":e.id},...t&&g};break;case"android":f={...f,platformName:"Android",...a&&{"appium:fullReset":a},...!a&&c&&{"appium:autoGrantPermissions":!0},"appium:automationName":"UiAutomator2","appium:appWaitActivity":s,...e&&{"appium:appPackage":e.id||e.packageName,"appium:appActivity":e.activity},...t&&g};break;default:throw Error(`unsupported mobile project ${r}`)}return f}function jE({projectType:r,nativeApp:e,appPath:t,androidActivityWait:s,options:n,gridInfo:o,sessionTags:i}){let{fullReset:a,resetAppData:c,resetOnSessionStartOnly:l,osVersion:m,deviceName:d}=n,{type:p}=o,g=p===W.BROWSERSTACK?"browserstack":"saucelabs",f={...p===W.BROWSERSTACK&&{os_version:m,device:d,realDevice:!0,project:i.project,buildTags:Object.values(i).join(",")},...p===W.SAUCELABS&&{platformVersion:m,deviceName:d,tags:Object.values(i)},name:i.testResultId,build:i.executionId,[`${g}.user`]:o.user,[`${g}.key`]:o.key,[`${g}.debug`]:!0,[`${g}.networkLogs`]:!0,...!a&&!c&&{noReset:!0},...!a&&c&&{noReset:!1}};switch(r){case"ios":f={...f,platformName:"iOS",autoAcceptAlerts:!0,automationName:"XCUITest",...a&&{fullReset:a,resetOnSessionStartOnly:l},...e&&{bundleId:e.id},...t&&{app:t}};break;case"android":f={...f,platformName:"Android",...a&&{fullReset:a},...!a&&c&&{autoGrantPermissions:!0},automationName:"UiAutomator2",appWaitActivity:s,...e&&{appPackage:e.id||e.packageName,appActivity:e.activity},...t&&{app:t}};break;default:throw Error(`unsupported mobile project ${r}`)}return f}function BE({projectType:r,nativeApp:e,appPath:t,androidActivityWait:s,options:n,sessionTags:o,gridInfo:i,isHSAppIdExists:a}){return W.TESTIM_HEADSPIN===i.type?Ag({projectType:r,nativeApp:e,appPath:t,androidActivityWait:s,options:n,sessionTags:o,isHSAppIdExists:a}):jE({projectType:r,nativeApp:e,appPath:t,androidActivityWait:s,options:n,gridInfo:i,sessionTags:o})}function Og({projectType:r,gridInfo:e,nativeApp:t,options:s,appPath:n,androidActivityWait:o,sessionTags:i,isHSAppIdExists:a}){let{deviceName:c,osVersion:l,deviceUdid:m}=s;Cg({nativeApp:t,appPath:n,gridInfo:e});let d=Tg(e),p=BE({projectType:r,nativeApp:t,appPath:n,androidActivityWait:o,options:s,sessionTags:i,gridInfo:e,isHSAppIdExists:a});if(e.type===W.TESTIM_HEADSPIN){let g={};c&&(g.model=c),l&&(g.os_version=l),m&&(g.device_id=m,delete g.model,delete g.os_version),ft.isEmpty(g)||(p["headspin:selector"]=g)}return{...d,desiredCapabilities:p,capabilities:p,connectionRetryCount:0,logLevel:s.appiumLogLevel}}async function _g({projectType:r,gridInfo:e,nativeApp:t,options:s,appPath:n,androidActivityWait:o,sessionTags:i,isHSAppIdExists:a}){let{deviceUdid:c}=s;Cg({nativeApp:t,appPath:n,gridInfo:e});let l=await bg(e,c),m=Ag({projectType:r,nativeApp:t,appPath:n,androidActivityWait:o,options:s,sessionTags:i,isHSAppIdExists:a});return c&&(m["appium:udid"]=c),{...l,desiredCapabilities:m,capabilities:m,connectionRetryCount:0,logLevel:s.appiumLogLevel}}var Sg,vu,Rg,ft,Ig,hs,vg,Tu,xg,Eu,wu,CE,_E,Eg,wi=T(()=>{"use strict";Sg=E(require("fs")),vu=E(require("path")),Rg=E(require("crypto")),ft=E(require("lodash"));j();pe();U();Te();ie();Xo();bu();Ig=require("lodash"),hs=x("testim-desired-capabilities-builder"),vg=Zn?"debug":"silent",Tu={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"],Eu=(...r)=>Rg.createHash("sha256").update(r.join("")).digest("hex"),wu=r=>r.type===W.DEVICE_FARM||r.type===W.HYBRID&&r.provider==="devicefarm",CE=r=>{var s;let{desiredCapabilities:e}=r;Object.prototype.hasOwnProperty.call(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.prototype.hasOwnProperty.call(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.prototype.hasOwnProperty.call(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.prototype.hasOwnProperty.call(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.prototype.hasOwnProperty.call(e,"chromeOptions")&&(e["goog:chromeOptions"]??(e["goog:chromeOptions"]=e.chromeOptions),delete e.chromeOptions),Object.prototype.hasOwnProperty.call(e,"edgeOptions")&&(e["ms:edgeOptions"]??(e["ms:edgeOptions"]=e.edgeOptions),delete e.edgeOptions),Object.prototype.hasOwnProperty.call(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??(e["moz:firefoxOptions"]=e.firefoxOptions),delete e.firefoxOptions),((s=e["goog:chromeOptions"])==null?void 0:s.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in r.desiredCapabilities&&(r.user=r.desiredCapabilities.username,delete r.desiredCapabilities.username),"accessKey"in r.desiredCapabilities&&(r.key=r.desiredCapabilities.accessKey,delete r.desiredCapabilities.accessKey);let t;try{t=M.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(o=>{delete e[o]})}catch{hs.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};_E=ft.memoize(OE,(r,e,t,s,n,o)=>{let i=JSON.stringify(r.desiredCapabilities),a=JSON.stringify(ft.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return Eu(i,a,c,s,l,o)}),Eg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Ue(r){var e,t,s,n,o,i,a;return((e=r.message)==null?void 0:e.match(/Command not found/))||r.message==="HTTP method not allowed"||r.message==="Unknown error"||((t=r.message)==null?void 0:t.match(/Unknown timeout type/))||r.name==="unknown command"||((s=r.message)==null?void 0:s.match(/did not match a known command/))||((n=r.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=r.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=r.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=r.message)==null?void 0:a.match(/\.\w* is not a function/))}function Lg(r,e,t){if(!e||!r)return r;if(r.includes("%"))return r.replace(/ /g,"%20");try{return decodeURI(r)!==r?r:encodeURI(r)}catch(s){return t&&t.warn("tried to encode url but failed",{err:s,url:r}),r}}async function Dg(r){var e;if(!vi||!Ei)try{let t=require.resolve("webdriver/build/utils.js"),[s,n]=await Promise.all([import("got"),import(t)]);[vi,Ei]=[s.RequestError,n.CustomRequestError]}catch{}return!vi||!Ei?(e=r.stack)==null?void 0:e.includes("node_modules/webdriver"):r instanceof vi||r instanceof Ei}var vi,Ei,Iu=T(()=>{"use strict"});function xu(r){function e(p){return p?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(p.nodeType):!1}function t(p){return p?s(p.parentNode,e):null}function s(p,g){for(let f=p;f&&f!==p.ownerDocument;f=f.parentNode)if(g(f))return f;return null}function n(p,g){for(let f=p;f&&f!==p.ownerDocument;f=t(f))if(g(f))return f;return null}function o(p,g){if(!p||!g)return null;p instanceof DocumentFragment&&(p=p.host);let h=window.getComputedStyle(p).getPropertyValue(g);if(h&&h!=="inherit")return h;let y=t(p);return o(y,g)}function i(p){let g=p.getBoundingClientRect();if(g.width>0&&g.height>0)return!0;if(p.tagName.toUpperCase()==="PATH"&&g.width+g.height>0){let h=o(p,"stroke-width");return!!h&&parseInt(h,10)>0}return o(p,"overflow")==="hidden"?!1:Array.from(p.childNodes).some(h=>h.nodeType===Node.TEXT_NODE?!0:e(h)?i(h):!1)}function a(p){return o(p,"overflow")==="hidden"}function c(p){return!p||!a(p)||!p.childNodes.length?!1:Array.from(p.childNodes).every(g=>g.nodeType===Node.TEXT_NODE?!1:!e(g)||!i(g)?!0:c(g))}function l(p){var g;return p?(g=p.parentNode)!=null&&g.host?!0:l(p.parentNode):!1}if(!r||!l(r)&&!document.contains(r))return!1;switch(r.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let g=s(r,f=>f.tagName.toUpperCase()==="SELECT");return xu(g)}case"INPUT":if(r.type==="hidden")return!1;break;default:break}if(o(r,"visibility")!=="visible")return!1;let m=!!n(r,p=>Number(o(p,"opacity"))===0),d=!!n(r,p=>o(p,"display")==="none");return!(m||d||!i(r)||c(r))}var Ng=T(()=>{"use strict"});var Mg,Fg,En,$E,WE,Si,Ug=T(()=>{"use strict";Mg=E(require("promise-queue")),Fg=E(require("webdriverio"));pe();Le();j();U();Fr();Ng();Iu();fs();En=x("WebDriverApi"),$E=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},WE={implicit:0,pageLoad:1,script:2},Si=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:s,testResultId:n}=this,o=t?t.toString().substr(0,2e3):"";throw En.warn("error from selenium",{err:e,testResultId:n,testName:s,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),typeof Wa<"u"&&(e=Wa);let t=1/0;this.queue=new Mg.default(e,t)}async addToQueue(e){var s,n;let t=(s=this.seleniumPerfStats)==null?void 0:s.markStart();try{return await this.queue.add(e)}catch(o){return this.rejectWithLog(o,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,s){var o,i;this.testName=t,this.testResultId=s,e.deprecationWarnings=!1,this.initQueueRequests(),O("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(Ce.GET_BROWSER);try{await this.addToQueue(async()=>{En.info("requesting browser",{testResultId:s,testName:t}),O("before this.client.init"),this.client=await Fg.remote(e)}),O("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,Ce.GET_BROWSER)}}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},o=()=>this.client.execute(e,t).catch(n),i=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return o();t=t.map(a=>{if(a===null){En.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await i()}catch(a){if(Ue(a))return this.unsupportedActions.add("execute"),o();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),o=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await o()}catch(i){if(Ue(i))return this.unsupportedActions.add("executeAsync"),n();throw i}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let s=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return s!=null&&s.targetInfos?s.targetInfos:[]}async takeScreenshot(){var t,s;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Ce.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.takeScreenshot()})}}finally{(s=this.seleniumPerfStats)==null||s.markEnd(e,Ce.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Ce.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Me(e)))}finally{this.seleniumPerfStats.markEnd(t,Ce.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),s=()=>this.execute(xu,{ELEMENT:e,[Ht]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return s();try{return await t()}catch(n){if(Ue(n))return this.unsupportedActions.add("elementIdDisplayed"),s();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(Lg(e,this.isSafari(),En))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let s=()=>{let o=[];return o[WE[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await s()}catch(o){if(Ue(o))return this.unsupportedActions.add("timeouts"),n();throw o}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let s=function(n,o){window.scrollTo(n,o)};return this.execute(s,e,t)}async setValue(e,t){return await this.elementIdClear(Me(e)),await this.elementIdValue(Me(e),t)}async getViewportSize(e){let t=await this.execute($E);if(typeof e=="string"&&e.match(/(width|height)/)){let s=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[s]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async keys(e){let t=i=>Ma.hasOwnProperty(i)?[Ma[i]]:i.split(""),s=[];if(typeof e=="string")s=t(e);else if(Array.isArray(e))for(let i of e)s=s.concat(t(i));else throw new Error("number or type of arguments don't agree with keys protocol command");let n=()=>{var i;return(i=this.client)==null?void 0:i.requestHandler.create("/session/:sessionId/keys",{value:s})},o=()=>{let i=s.map(c=>({type:"keyDown",value:c})),a=s.map(c=>({type:"keyUp",value:c}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};if(this.unsupportedActions.has("keys"))return o();try{return await this.addToQueue(()=>n())}catch(i){if(Ue(i))return this.unsupportedActions.add("keys"),o();throw i}}async elementIdValue(e,t){let s=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.elementSendKeys(e,s)})}}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(Me(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(e)),s=await t.$('button[type="submit"]');return await s.isExisting()?s.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,s,n){return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).click({x:t,y:s,button:n})})}}_rightClick(e,t,s){return this.findElementAndPress(e,t,s,"right")}_leftClick(e,t,s){return this.findElementAndPress(e,t,s,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}async actions(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}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,s){let n={...typeof t=="number"&&{xOffset:t},...typeof s=="number"&&{yOffset:s}};return this.isSafari()&&!Object.prototype.hasOwnProperty.call(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.prototype.hasOwnProperty.call(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let s=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let o=Math.abs(e.width),i=Math.abs(e.height);s=async()=>await this.client.setWindowSize(o,i),n=async()=>await this.client._setWindowSize(o,i)}if(this.unsupportedActions.has("windowHandleSize"))return s();try{return await n()}catch(o){if(Ue(o))return this.unsupportedActions.add("windowHandleSize"),s();throw o}})}}setCookie(e,t,s,n,o,i,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:s,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var s;return(await((s=this.client)==null?void 0:s.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).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(){if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.isAppInstalled(e)});return En.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 jg={};$(jg,{doubleClick:()=>HE});var HE,Bg=T(()=>{"use strict";HE=function(r,e){let t=["pointerup","pointerdown","pointermove"],s=getLocatedElement(r.locatedElement);if(!s)throw new Error("element not found");let n=r.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(p){function g(S,b,v){return v>S&&v<b}let f=p.pointerPosition||{},h=s.getBoundingClientRect(),y=f.originX&&g(h.left,h.left+h.width,f.originX)?f.originX:h.left+h.width/2,w=f.originY&&g(h.top,h.top+h.height,f.originY)?f.originY:h.top+h.height/2;return{x:y,y:w}},a=function(p,g){return{screenX:0,screenY:0,clientX:p,clientY:g,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(p,g,f){if(!window.PointerEvent)return;let h=a(g,f);return new window.PointerEvent(p,h)},l=function(p,g,f){let h=document.createEvent("MouseEvents");return h.initMouseEvent(p,!0,!0,document.defaultView,1,0,0,g,f,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),h},m=function(){var g;let p=document.activeElement;for(;(g=p.shadowRoot)!=null&&g.activeElement;)p=p.shadowRoot.activeElement;return p},d=function(p){let g=i(p),f=p.event;return t.includes(f)?c(f,g.x,g.y):l(f,g.x,g.y)};try{n.map(g=>d(g)).filter(Boolean).forEach(g=>s.dispatchEvent(g));let p=m();dispatchFocus(r.elementToFocusLocatedElement,p),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(p){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:p.toString(),success:!1})}}});var Sn={};$(Sn,{dispatchFocus:()=>GE});function GE(r,e){function t(o){let i=document.createEvent("HTMLEvents");return i.initEvent(o,!0,!1),i}function s(){var i;let o=document.activeElement;for(;(i=o.shadowRoot)!=null&&i.activeElement;)o=o.shadowRoot.activeElement;return o}function n(o,i){i&&(i.dispatchEvent(t("focusout")),i.dispatchEvent(t("blur"))),o.dispatchEvent(t("focusin")),o.dispatchEvent(t("focus")),typeof o.focus=="function"&&o.focus();let a=s();i&&a===i&&typeof i.blur=="function"&&i.blur()}if(r){let o=getLocatedElement(r);if(o&&o!==e)try{n(o,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var Rn=T(()=>{"use strict"});var Vg={};$(Vg,{WebDriver:()=>Pr});async function KE(r){var e,t;try{let s=(t=(e=r==null?void 0:r.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return s?await qE(s):void 0}catch(s){He.info("Error getting cdpAddress",s);return}}var Ri,Hg,Gg,He,rr,VE,$g,qE,sr,zE,Wg,Pr,In=T(()=>{"use strict";Ri=E(require("lodash"));j();Le();wi();Hg=E(require("p-retry")),Gg=E(require("ua-parser-js"));Fr();U();Iu();Ug();V();Te();fs();He=x("webdriver"),[rr,VE]=[0,2],{extractElementId:$g,getCdpAddressForHost:qE}=q,sr=()=>(Ee(),ve(Ir)).getSessionPlayer().codeSnippets,zE=()=>(Ee(),ve(Ir)).getSessionPlayer().locatorBuilderUtils,Wg=()=>(Ee(),ve(Ir)).getSessionPlayer().utils;Pr=class extends Si{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}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(s=>s!==t)}async init(t,s,n,o,i,a,c,l=new Bt,m=!1,d=void 0){var h,y,w,S,b,v,I,A;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((w=(y=(h=t==null?void 0:t.company)==null?void 0:h.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:w.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let p=Ti(t,s,n,o,i,a,c,d);p.desiredCapabilities&&delete p.desiredCapabilities.marionette,p.capabilities&&delete p.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(d==null?void 0:d.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=l;let g=m?0:1500,f=m?()=>null:()=>this.executeJS("window.focus()");try{O("before initClient in webdriver.js init");let _=await this.initClient(p,s,c);O("after initResult before getCdpAddress in init"),this.cdpUrl=await KE(_),O("after getCdpAddress in webdriver.js init"),He.info(`init new session testName: ${s}`,{sessionId:this.getSessionId(),testResultId:c}),await se(g),M.flags.dontFocusOnInit.isEnabled()||await f(),O("after focus and delay in webdriver.js init")}catch(_){He.error("failed to init webdriver",{err:_,capabilities:p});let R=((b=(S=t==null?void 0:t.company)==null?void 0:S.activePlan)==null?void 0:b.plan)==="free";throw(v=_.stack)!=null&&v.includes("at startWebDriverSession")&&((I=_.message)!=null&&I.startsWith("Failed to create session"))&&((A=_.message)!=null&&A.includes("Timeout awaiting 'request'"))&&R?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):_.message.match(/capabilit(y|ies)/)?new to(_.message):new Error("failed to init client driver")}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>Ri.zip(o.slice(0,-1),o.slice(1)),s=this._keepAliveRequests.map(({start:o})=>o).filter(Boolean),n=t(s).map(([o,i])=>i-o);return Math.max(...n)}async isClosedBrowserError(t){return["session-not-found","no such window"].includes(t==null?void 0:t.name)?!0:await Dg(t)?["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(n=>t.message.includes(n)):!1}start(){if(this.started)return;this.started=!0;let t=async()=>{let s=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,c)=>{let l=this._keepAliveRequests.find(m=>m.id===c);l&&(l[a]=Date.now())};function o(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let i=J();s(i);try{await this.executeJS(o),this._isAlive=!0,n("end",i),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",i),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,He.warn("close unexpected alert open"),await this.alertAccept().catch(c=>He.warn("failed to click on alert",{err:c}));return}if(He.warn("err while getting testim status",{err:a}),this._isAlive=!1,await this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;this.browserClosedFailedKeepAlives>=c&&this.browserClosedCallbacks.forEach(l=>{try{l(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4)}async switchToLocatedFrame(t){let s=await this.getElement(t),n=$g(s.value);return await this.switchToFrame({ELEMENT:n,[Ht]:n}),s}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(s){throw(t=s.message)!=null&&t.includes("ECONNREFUSED")?new ro:s}}async getElement(t){var o;let s=this.seleniumPerfStats.markStart(Ce.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(s,Ce.GET_ELEMENT)}if(((o=t==null?void 0:t.shadowPath)==null?void 0:o.length)||M.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
28
28
|
var fn = ${sr().getLocatedElementCode};
|
|
29
29
|
return fn.apply(null, arguments);
|
|
30
30
|
`,t)}finally{this.seleniumPerfStats.markEnd(s,Ce.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(s,Ce.GET_ELEMENT)}}executeJS(t,...s){return this.execute(t,...s)}async executeCodeAsync(t,s,...n){return await this.timeouts("script",s),await this.executeAsync(t,...n)}async markDynamicParent(t,s){function n({attributeName:o,attributeValue:i,locatedElement:a}){let c=getLocatedElement(a);if(!c)throw new Error("could not find dynamic parent");c.setAttribute(o,i)}await this.executeJS(`
|
|
31
31
|
var getLocatedElement = ${sr().getLocatedElementCode};
|
|
32
32
|
var setDynamicParentAttribute = ${n.toString()};
|
|
33
33
|
return setDynamicParentAttribute.apply(null, arguments)
|
|
34
|
-
`,{attributeName:
|
|
34
|
+
`,{attributeName:zE().DYNAMIC_PARENT_FIELD_NAME,attributeValue:s,locatedElement:t.locatedElement})}getLocatedElementRectWithPadding(t){function s(n){let o=getLocatedElement(n);if(!o)return null;let i=parseInt(window.getComputedStyle(o).paddingTop.replace("px",""),10)||0,a=parseInt(window.getComputedStyle(o).paddingLeft.replace("px",""),10)||0,c=o.getBoundingClientRect();return{top:Math.round(c.top+i),left:Math.round(c.left+a)}}return this.executeJS(`
|
|
35
35
|
const getLocatedElement = ${sr().getLocatedElementCode};
|
|
36
36
|
const getLocation = ${s.toString()};
|
|
37
37
|
return getLocation.apply(null, arguments)
|
|
@@ -39,26 +39,26 @@ ${((S=n.warnings)==null?void 0:S.join(`
|
|
|
39
39
|
const getLocatedElement = ${sr().getLocatedElementCode};
|
|
40
40
|
const getLocation = ${s.toString()};
|
|
41
41
|
return getLocation.apply(null, arguments)
|
|
42
|
-
`,t)}getElementLocation(t){return this.getLocatedElementRect(t.locatedElement)}getTargetText(t){return this.getElementTextJS(t.locatedElement)}async getElementTextJS(t){function s(o,i){function a(
|
|
42
|
+
`,t)}getElementLocation(t){return this.getLocatedElementRect(t.locatedElement)}getTargetText(t){return this.getElementTextJS(t.locatedElement)}async getElementTextJS(t){function s(o,i){function a(p){var f;return(f=p.childNodes)!=null&&f.length&&Array.from(p.childNodes).filter(h=>h.nodeType===Node.ELEMENT_NODE).forEach(h=>{typeof h.tagName=="string"&&h.tagName.toLowerCase()==="title"?p.removeChild(h):a(h)}),p}function c(p){return["INPUT","TEXTAREA"].includes(p.tagName)}function l(p){var g,f,h;try{if(p.shadowRoot&&!((h=(f=Object.getOwnPropertyDescriptor((g=p.ownerDocument.defaultView)==null?void 0:g.Node.prototype,"textContent"))==null?void 0:f.get)!=null&&h.toString().includes("[native code]")))return p.shadowRoot.textContent.replace(/(\r\n|\n|\r)/gm,"")}catch{}if(i&&Array.prototype.some.call(p.children,y=>y.hidden)){let y=p.cloneNode(!0);return Array.prototype.filter.call(y.children,S=>S.hidden).forEach(S=>y.removeChild(S)),y.textContent.replace(/(\r\n|\n|\r)/gm,"")}return p.textContent.replace(/(\r\n|\n|\r)/gm,"")}function m(p){if(c(p))return p.value;if(p instanceof SVGElement){let g=p.cloneNode(!0);return a(g).textContent.replace(/(\r\n|\n|\r)/gm,"")}return l(p)}let d=getLocatedElement(o);return d?m(d):""}let{value:n}=await this.executeJS(`
|
|
43
43
|
const getLocatedElement = ${sr().getLocatedElementCode};
|
|
44
44
|
const extractText = ${s.toString()};
|
|
45
45
|
return extractText.apply(null, arguments)
|
|
46
|
-
`,t,this.ignoreHiddenTagsText);return n}async getHTML(t){var o,i;let s=sr().getHtmlCode(null,t),n=this.seleniumPerfStats.markStart(Ce.GET_HTML);try{let{value:a}=await this.executeJS(s);return this.seleniumPerfStats.markEnd(n,Ce.GET_HTML),a}catch(a){this.seleniumPerfStats.markEnd(n,Ce.GET_HTML);let c=Object.assign(new Error(""),{success:!1,reason:a.toString(),errorType:"internal-error"});throw(i=(o=this.client)==null?void 0:o.requestHandler)!=null&&i.sessionID||Object.assign(c,{extraInfo:"Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated"}),c}}maximizeWithoutValidation(){return this.windowHandleMaximize()}setViewportSizeNEW(t,s){class o extends Error{}function i(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}}let a=()=>(0
|
|
46
|
+
`,t,this.ignoreHiddenTagsText);return n}async getHTML(t){var o,i;let s=sr().getHtmlCode(null,t),n=this.seleniumPerfStats.markStart(Ce.GET_HTML);try{let{value:a}=await this.executeJS(s);return this.seleniumPerfStats.markEnd(n,Ce.GET_HTML),a}catch(a){this.seleniumPerfStats.markEnd(n,Ce.GET_HTML);let c=Object.assign(new Error(""),{success:!1,reason:a.toString(),errorType:"internal-error"});throw(i=(o=this.client)==null?void 0:o.requestHandler)!=null&&i.sessionID||Object.assign(c,{extraInfo:"Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated"}),c}}maximizeWithoutValidation(){return this.windowHandleMaximize()}setViewportSizeNEW(t,s){class o extends Error{}function i(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}}let a=()=>(0,Hg.default)(async()=>{let{value:l}=await this.windowHandleSize(),{value:m}=await this.execute(i),d=l.width-m.screenWidth,p=l.height-m.screenHeight;await this.windowHandleSize({width:t.width+d,height:t.height+p});let{value:g}=await this.execute(i);if(g.screenWidth!==t.width||g.screenHeight!==t.height)throw new o},{retries:5-1,factor:1,minTimeout:0}).catch(l=>{if(!(l instanceof o))throw l});if(typeof t!="object"||typeof t.width!="number"||typeof t.height!="number"||typeof s<"u"&&typeof s!="boolean")throw new Error("number or type of arguments don't agree with setViewportSize command");return(typeof s>"u"?!0:s)?a():this.windowHandleSize(t)}setViewportSize(t,s){return this.setViewportSizeNEW({width:t,height:s},!0)}getBrowserMajorVersion(t){try{return parseInt(t.browser.major,10)}catch(s){return He.error("failed to get browser version",{err:s}),0}}async getBrowserAndOS(){function t(a){let c=a.match(/(opera|chrome|safari|firefox)\/?\s*(\d+)/i)||[];if(c[1]==="Chrome"&&a.match(/\bOPR\/(\d+)/)!==null)return"opera";if(c[1]==="Chrome"&&a.match(/\bEdge|Edg\/(\d+)/)!==null)return"edge";c=c[2]?[c[1],c[2]]:[a.appName,a.appVersion,"-?"];let l=a.match(/version\/(\d+)/i);return l!==null&&c.splice(1,1,l[1]),c[0].toLowerCase()}if(this.browserAndOS)return this.browserAndOS;function s(){return typeof window>"u"||!window.navigator||!window.navigator.userAgent?"unknown":window.navigator.userAgent}let{value:n}=await this.executeJS(s),o=(0,Gg.default)(n),i=o.os;return this.browserAndOS={os:`${i.name} ${i.version}`,browserMajor:this.getBrowserMajorVersion(o),browser:t(n),userAgent:n,browserVersion:o.browser.version},this.browserAndOS}async getUserAgentInfo(){let{value:t}=await this.executeJS(`return ${sr().getUserAgentInfo()}`);return t}setValue(t,s){return super.setValue(t,s)}getRelativeMoveActions(t,s){let{rect:n,clickOffset:o}=t,i=this.inViewCenter(n),a=Math.floor(o.x-i.x),c=Math.floor(o.y-i.y);return!Wg().isWithinBounds(-i.x,i.x,a)||!Wg().isWithinBounds(-i.y,i.y,c)?(He.warn("using center as fallback for offset"),this.getMoveActions(0,0,s)):this.getMoveActions(a,c,s)}computeAbsoluteMovement(t){let{frameOffset:s,rect:n,clickOffset:o}=t,i=n.left+o.x+s.x,a=n.top+o.y+s.y;return{x:i,y:a}}async actWithActionsAPI(t,s,n,o){let i=this.getRelativeMoveActions(t,n),a=this.getClickActions(o,s);try{return await this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:i.concat(a)}])}catch(c){He.error("tried to use element origin but failed because of visibility, trying absolute",c);let{x:l,y:m}=this.computeAbsoluteMovement(t),d=this.getMoveActions(l,m);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:d.concat(a)}])}}doubleClickWithActionsAPI(t,s){return this.actWithActionsAPI(s,rr,t,["pointerDown","pointerUp","pointerDown","pointerUp"])}async doubleClickWithJS(t){let[{doubleClick:s},{dispatchFocus:n}]=await Promise.all([Promise.resolve().then(()=>(Bg(),jg)),Promise.resolve().then(()=>(Rn(),Sn))]);return this.executeCodeAsync(`
|
|
47
47
|
var getLocatedElement = ${sr().getLocatedElementCode};
|
|
48
48
|
var dispatchFocus = ${n.toString()};
|
|
49
49
|
var doubleClick = ${s.toString()};
|
|
50
50
|
var eventData = arguments[0];
|
|
51
51
|
var done = arguments[1];
|
|
52
52
|
return doubleClick.call(null, eventData, done);
|
|
53
|
-
`,t.timeout,t)}getClickActions(t=[],s=void 0){return t.map(n=>({type:n,button:s}))}getClickActionList(t=[],s=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,s)}]}leftClickWithActionsAPI(t,s){return this.actWithActionsAPI(s,rr,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,s){return this.actWithActionsAPI(s,
|
|
54
|
-
var res = requireOrImportMethod('${
|
|
53
|
+
`,t.timeout,t)}getClickActions(t=[],s=void 0){return t.map(n=>({type:n,button:s}))}getClickActionList(t=[],s=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,s)}]}leftClickWithActionsAPI(t,s){return this.actWithActionsAPI(s,rr,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,s){return this.actWithActionsAPI(s,VE,t,["pointerDown","pointerUp"])}async rightClick(t,s){if(this.unsupportedActions.has("move"))return this.rightClickWithActionsAPI(t,s);try{return await super._rightClick(t)}catch(n){if(Ue(n))return this.unsupportedActions.add("move"),this.rightClickWithActionsAPI(t,s);throw n}}async leftClick(t,s){if(this.unsupportedActions.has("move"))return this.leftClickWithActionsAPI(t,s);try{return await super._leftClick(t)}catch(n){if(Ue(n))return this.unsupportedActions.add("move"),this.leftClickWithActionsAPI(t,s);throw n}}async dragAndDropOldAPI(t,s){return await this.moveTo(t),await this.buttonDown(),await this.moveTo(s),await this.buttonUp()}async calculateElementMiddlePoint(t,s={top:0,left:0}){let n=await this.getLocatedElementRect(t);if(!(n!=null&&n.value))throw He.warn(`could not find element for locatedElement ${t}`),new Error("could not calculate rect");let{x:o,y:i,width:a,height:c}=n.value;return{x:s.left+o+a/2,y:s.top+i+c/2}}async hover(t,s){if(this.unsupportedActions.has("move"))return this.moveToElementWithActionsAPI(t,s);let{x:n,y:o}=s.clickOffset;try{return await this.moveTo(t,n,o)}catch(i){if(Ue(i))return this.unsupportedActions.add("move"),this.moveToElementWithActionsAPI(t,s);throw i}}getMoveActions(t=1,s=1,n="viewport",o=0){return[{type:"pointerMove",duration:o,x:Math.floor(t)||1,y:Math.floor(s)||1,origin:n}]}moveWithActionsAPI(t){let s=this.getMoveActions(t.x,t.y);return this.actions([{type:"pointer",id:"mouse",actions:s}])}async moveToElementWithActionsAPI(t,s){try{return await this.actions([{type:"pointer",id:"mouse",actions:this.getRelativeMoveActions(s,t)}])}catch(n){He.error("tried to use element origin but failed because of visibility, trying location",n);let o=this.computeAbsoluteMovement(s);return await this.moveWithActionsAPI(o)}}getDragCoordinates(t){let s=t.filter(i=>i.event==="mousemove"||i.event==="pointermove"),n=s[0].pointerPosition,o=s.at(-1).pointerPosition;return{xDiff:o.screenX-n.screenX,yDiff:o.screenY-n.screenY}}async dragWithMoveTo(t,s,n,o,i){return await this.moveTo(t,o,i),await this.buttonDown(),await this.moveTo(t,s,n),await this.buttonUp()}dragWithActionsAPI(t,s,n,o,i){let a=this.getMoveActions(o,i,t,1),c=this.getClickActions(["pointerDown"],rr),l=this.getMoveActions(s,n,"pointer",1),m=this.getClickActions(["pointerUp"],rr);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(c).concat(l).concat(m)}])}async drag(t,s,n,o,i){let{width:a,height:c}=s,l=n-a/2+1,m=o-c/2,d=this.getDragCoordinates(i),{xDiff:p,yDiff:g}=d;if(this.unsupportedActions.has("move"))return this.dragWithActionsAPI(t,p,g,l,m);try{return await this.dragWithMoveTo(t,p,g,l,m)}catch(f){if(Ue(f))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,p,g,l,m);throw f}}getMoveRelativeSequence(t,s,n,o){let i=(p,g)=>Math.hypot(p.x-g.x,p.y-g.y),a={x:t,y:s},c={x:n,y:o},l=10,m=Math.round(i(a,c)/l),d=Array.from({length:m},()=>({x:Math.round((c.x-a.x)/m),y:Math.round((c.y-a.y)/m)}));return[{x:1,y:1}].concat(d)}getMoveAbsoluteSequence(t,s,n,o){return this.getMoveRelativeSequence(t,s,n,o).reduce((a,c)=>{let l=a.at(-1);return a.concat({x:Math.round(l.x+c.x),y:Math.round(l.y+c.y)})},[{x:Math.round(t),y:Math.round(s)}])}async dragAndDropWithGeneratedMoves(t,s,n){let{fromRect:o,fromX:i,fromY:a,toRect:c,toX:l,toY:m}=n,d=this.getMoveRelativeSequence(o.left+i,o.top+a,c.left+l,c.top+m);await this.moveTo(t,Math.round(i),Math.round(a)),await this.buttonDown();for(let p of d)await this.moveTo(null,p.x,p.y);return await this.moveTo(s,Math.round(l),Math.round(m)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:s,fromX:n,fromY:o,toRect:i,toX:a,toY:c}=t,l=Math.round(s.left+n),m=Math.round(s.top+o),d=Math.round(i.left+a),p=Math.round(i.top+c),g=this.getMoveAbsoluteSequence(s.left+n,s.top+o,i.left+a,i.top+c),f=this.getMoveActions(l,m),h=this.getClickActions(["pointerDown"],rr),y=Ri.flatMap(g,v=>this.getMoveActions(v.x,v.y)),w=this.getMoveActions(d,p),S=this.getClickActions(["pointerUp"],rr),b=f.concat(h).concat(y).concat(w).concat(S);return this.actions([{type:"pointer",id:"mouse",actions:b}])}async dragAndDrop(t,s,n){if(this.isSafari()){if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPIWithGeneratedMoves(n);try{return await this.dragAndDropWithGeneratedMoves(t,s,n)}catch(o){if(Ue(o))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPIWithGeneratedMoves(n);throw o}}if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPI(n);try{return await this.dragAndDropOldAPI(t,s)}catch(o){if(Ue(o))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPI(n);throw o}}doubleClickFallback(t,s,n){return this.isSafari()?this.doubleClickWithJS(s):this.doubleClickWithActionsAPI(t,n)}async doubleClick(t,s,n){if(this.unsupportedActions.has("move")||this.isSafari())return this.doubleClickFallback(t,s,n);try{return await this.doDoubleClick(t)}catch(o){if(Ue(o))return this.unsupportedActions.add("move"),this.doubleClickFallback(t,s,n);throw o}}async dragAndDropWithActionsAPI(t){let{fromRect:s,fromX:n,fromY:o,toRect:i,toX:a,toY:c}=t,l=Math.round(s.left+n),m=Math.round(s.top+o),d=Math.round(i.left+a),p=Math.round(i.top+c);await this.moveWithActionsAPI({x:l,y:m});let g=this.getClickActionList(["pointerDown"],rr);await this.actions(g),await this.moveWithActionsAPI({x:d,y:p});let f=this.getClickActionList(["pointerUp"],rr);return this.actions(f)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:s}=await this.elementIdDisplayed($g(t));return s}getSource(){return this.source()}async getElementRect(t){let s={width:0,height:0,top:0,left:0},n;try{n=await this.getElementLocation(t)}catch(o){He.error("error getting element location",{err:o})}return n!=null&&n.value?{top:n.value.y,left:n.value.x,width:n.value.width,height:n.value.height}:s}async end(){He.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||He.warn("failed to close session because session is undefined"),clearInterval(this.keepAliveTimer);try{return await super.end()}catch{return}}inViewCenter(t){return{x:t.width/2,y:t.height/2}}async submit(t){if(this.unsupportedActions.has("submit"))return await super.submitFormManually(t);try{return await super.submitForm(t)}catch(s){if(Ue(s))return this.unsupportedActions.add("submit"),super.submitFormManually(t);throw s}}}});var ku,Pu,Ii,Cu=T(()=>{"use strict";U();Te();be();ku=x("lab-features-service"),Pu=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(ku.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let s=this.isLabsEnabledForCompany(t),n=s?await il(e):[];this.featuresForProject=n,this.labBatman=s}catch(s){ku.error("failed loading lab features",{err:s,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=M.flags[e];this.validateAsLabFeatureFlag(t);let s=t.getValue();if(s==="disabled")return!1;if(s==="enabled")return!0;let{featuresForProject:n,labBatman:o}=this,i=n.find(c=>c.featureFlagName===e),a=i==null?void 0:i.enabled;return Boolean(o&&a)}isLabsEnabledForCompany(e){var t;return Boolean((t=e==null?void 0:e.premiumFeatures)==null?void 0:t.enableLabFeatures)}validateAsLabFeatureFlag(e){if("getValue"in e)return;let t=`Attempted querying a lab feature flag which isn't a variant. This means that a wrong configuration is being used in FeatureFlagsService (for feature flag: ${e.name}`;throw ku.error(t,{featureFlagName:e.name}),new Error(t)}},Ii=new Pu});function JE(r){let e=/^\\\\\?\\/.test(r),t=/[^\u0000-\u0080]+/.test(r);return e||t?r:r.replace(/\\/g,"/")}function YE(r){try{return{sync:!0,lib:globalThis.require(r)}}catch(e){if(e.code!=="ERR_REQUIRE_ESM")throw e;let{sep:t,join:s}=globalThis.require("path"),{promises:n}=globalThis.require("fs");return{sync:!1,lib:n.readFile(`${r}${t}package.json`).then(i=>{let a=JSON.parse(i);return import(s(r,a.main||`${t}index.js`))})}}}function XE(r){let e=Object.getPrototypeOf(async()=>null).constructor;function t(){return e.apply(null,r)}return t.prototype=e.prototype,new t}async function QE(r,e,t,s,n={},o=void 0,i=void 0){let a=Object.keys(n).map(f=>`
|
|
54
|
+
var res = requireOrImportMethod('${JE(n[f])}');
|
|
55
55
|
if (res.sync) {
|
|
56
56
|
var ${f} = res.lib;
|
|
57
57
|
} else {
|
|
58
58
|
var ${f} = await res.lib;
|
|
59
59
|
}
|
|
60
60
|
`).join(""),c=i?`
|
|
61
|
-
${
|
|
61
|
+
${Kg.default.toString()}
|
|
62
62
|
var fileBuffer = dataUriToBuffer('${i}');
|
|
63
63
|
`:"var fileBuffer = null;",l=`
|
|
64
64
|
const getMessage = arguments => {
|
|
@@ -112,9 +112,9 @@ ${((S=n.warnings)==null?void 0:S.join(`
|
|
|
112
112
|
oldMethod?.apply(console, arguments);
|
|
113
113
|
};
|
|
114
114
|
});
|
|
115
|
-
`,
|
|
115
|
+
`,m=`
|
|
116
116
|
function injectCode(params, args, incomingParams, context, code) {
|
|
117
|
-
const constructWithArguments = ${
|
|
117
|
+
const constructWithArguments = ${XE.toString()}
|
|
118
118
|
|
|
119
119
|
const resolve = result => {
|
|
120
120
|
parentPort.postMessage({
|
|
@@ -175,12 +175,12 @@ ${((S=n.warnings)==null?void 0:S.join(`
|
|
|
175
175
|
});
|
|
176
176
|
}
|
|
177
177
|
}
|
|
178
|
-
`,
|
|
178
|
+
`,d=`
|
|
179
179
|
(async function() {
|
|
180
180
|
// A hack to fix an issue with stringified functions which use require. when compiling to JS, calls to require change to __require.
|
|
181
181
|
const __require = require;
|
|
182
182
|
const { parentPort } = require('worker_threads');
|
|
183
|
-
const requireOrImportMethod = ${
|
|
183
|
+
const requireOrImportMethod = ${YE.toString()}
|
|
184
184
|
|
|
185
185
|
// requireCode will set async to be true if needed.
|
|
186
186
|
${a}
|
|
@@ -213,75 +213,75 @@ ${((S=n.warnings)==null?void 0:S.join(`
|
|
|
213
213
|
args.push(fileBuffer);
|
|
214
214
|
}
|
|
215
215
|
|
|
216
|
-
${
|
|
216
|
+
${m}
|
|
217
217
|
|
|
218
218
|
injectCode(params, args, incomingParams, context, code);
|
|
219
219
|
});
|
|
220
220
|
})();
|
|
221
|
-
`,d=[],g=new zg.Worker(m,{eval:!0});try{return await ne(new Promise(f=>{g.on("message",h=>{if(h.action==="finish"){let{data:y}=h,w=Object.assign({},y,{tstConsoleLogs:d});gt.debug("Run code worker response",{messageWithLogs:w,transactionId:r}),f(w)}else h.action==="progress"&&d.push(h.data)}).on("error",h=>{h.message==="malformed data: URI"?gt.error("Run code worker error",{err:h,transactionId:r,fileDataUrl:i}):gt.error("Run code worker error",{err:h,transactionId:r}),f({tstConsoleLogs:d,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{gt.debug("Run code worker has been terminated",{transactionId:r})}),g.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:s})}),o)}catch(f){if(!(f instanceof te))throw f;return gt.warn("timeout to run code",{transactionId:r,err:f}),{tstConsoleLogs:d,status:"failed",result:{resultValue:f==null?void 0:f.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{g==null||g.terminate()}}async function YE(r){try{await Gg.promises.rm(r,{recursive:!0,force:!0})}catch(e){gt.warn("failed to remove install npm packages folder",{err:e})}}function Kg(r,e,t,s){return`${e}_${t}_${r}_${s}`}async function ys(r,e,t,s,n,o){let i=Kg(n,e,r,t),{data:a}=await XE(i,s,o);return a}async function bs(r,e,t,s,n,o,i,a,c,l){var f;let p=Object.fromEntries(((f=t.nodePackageParams)==null?void 0:f.map(h=>[h.paramName,h.testimPackageLocalLocation]))||[]),m=Kg(i,n,e,o);if(l){let h=await nn(l);h&&(c=h)}Buffer.isBuffer(c)&&(gt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let d="data:,";c==="data:"&&(gt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=d);let g=await JE(m,t,s,r,p,a,c);return Object.assign({},g,{nodeVersion:process.version})}async function XE(r,e,t){let s=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Jg(),o=xn.join(n,`/${r}`),i=global.proxyUri;async function a(){let c="";try{if(c=await qd(o,s,i,t),gt.info("npm package install finished",{transactionId:r,output:c,timeout:t}),Number(c.trim().split(" ")[1])<s.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(p=>{let m=Vd(o,p.packageName);return{...p,packageFullName:`${p.packageName}@${m}`,packageLocalLocation:xn.resolve(o,"node_modules",p.packageName)}}),installFolder:o}}catch(l){throw gt.warn("npm package install failed",{transactionId:r,err:l}),l}}try{return await ne(a(),t)}catch(c){throw c instanceof te&>.warn("timeout to install package",{packages:s,transactionId:r,err:c,timeout:t}),c}}function Jg(){return xn.join(Vg.tmpdir(),"/testim_local_packages")}function Yg(){let r=Jg();return YE(r)}var Gg,Vg,xn,qg,zg,gt,Cr=T(()=>{"use strict";Gg=E(require("fs")),Vg=E(require("os")),xn=E(require("path"));j();Qs();qg=E(require("data-uri-to-buffer")),zg=require("worker_threads");V();U();be();gt=x("cli-service")});var nr={};$(nr,{run:()=>ZE});function QE(r,e){try{let t=e.defaults.enforceMaximumJsResultSize,s=M.flags.maximumJsResultSize.getValue(),n=JSON.stringify(r).length>s;return t?n:!1}catch{return!1}}var ZE,Xg=T(()=>{"use strict";Cr();V();Te();ZE=async(r,e,t)=>{let{code:s,stepId:n,incomingParams:o,context:i,testResultId:a,retryIndex:c,stepResultId:l,runTimeout:p,fileDataUrl:m,s3filepath:d}=e.data;try{let g=await bs(s,n,o,i,a,c,l,p,m,d);return g&&QE({result:g.result,tstConsoleLogs:g.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:g,success:!0}}catch(g){throw g instanceof te?new Error("Timeout while running action"):g}}});var Cu,ws,Au=T(()=>{"use strict";U();Cu=x("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(s){throw Cu.error("failed to set cookie",{err:s}),s}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw Cu.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw Cu.error("failed to remove cookie",{err:t}),t}}}});var Ou,Qg,vs,_u=T(()=>{"use strict";j();Ou=E(require("p-retry"));j();U();V();Qg=x("window-utils"),vs=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function s(o,i){let a=document.elementFromPoint(o,i);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(s,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(s){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:s.x,top:s.y,behavior:"instant"}):window.scrollTo(s.x,s.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let s=async(n=3)=>{try{await this.driver.url(e)}catch(o){let i=o.message.includes("method IWebBrowser2::Navigate2() failed");if(o.seleniumStack&&i&&n>0)return Qg.warn("selenium navigation failed. retrying to navigate",{err:o}),await se(1500),s(n-1);throw!o.seleniumStack&&i&&Qg.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:o}),o}};return Promise.race([s(),se(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),se(e)])}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let s=document.body,n=document.documentElement,o=Math.max(s.scrollHeight,s.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),i=Math.max(s.scrollWidth,s.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:o,width:i}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await se(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let s;if(typeof location<"u")s=location;else if(typeof window<"u"&&typeof window.location<"u")s=window.location;else return!1;return s.href!=="chrome-error://chromewebdata/"&&s.href!=="safari-resource:/ErrorPage.html"&&s.href.indexOf("res://ieframe.dll/http_404.htm")!==0&&s.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new Tt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,Ou.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,Ou.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var Lu,xi,Zg=T(()=>{"use strict";Lu=E(require("p-retry")),xi=class{constructor(e,t,s={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=s;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,s=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([s,this.driver.takeScreenshot()]),[o,i]=await(0,Lu.default)(n,{retries:e,minTimeout:t,factor:1}),a=i?i.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,s=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),o=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[i,a]=await(0,Lu.default)(o,{retries:t,minTimeout:s,factor:1}),c=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(c.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function eh(r,e){let t=e.image||e,s=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let o=r.offset||{top:0,left:0};if(o.top*=s,o.left*=s,!r.elementRect)return eS.warn("missing elementRect",rh.omit(r,"image")),{};let{elementRect:i}=r,a=await Es.default.read(Buffer.from(n[1],"base64")),c=i.left*s+o.left*s,l=i.top*s+o.top*s,p=i.width*s,m=i.height*s;c<0&&(p+=c,p=p<0?0:p,c=0),l<0&&(m+=l,m=m<0?0:m,l=0);let d=a.bitmap.width,g=a.bitmap.height;if(c+p>d&&(p=d-c),l+m>g&&(m=g-l),m<=0||p<=0)throw new Du("height or width is equal or lower than zero");return{elementImage:await a.crop(c,l,p,m).getBase64Async(Es.default.MIME_PNG)}}async function tS(r,e){let t=await Es.default.read(r.width,r.height);for(let n of e){let o=n.image.match(/^data:[^;]*;base64,(.*)$/),i=await Es.default.read(Buffer.from(o[1],"base64"));await new Promise((a,c)=>{t.composite(i,n.position.left,n.position.top,l=>{if(l){c(l);return}a()})})}return await t.getBase64Async(Es.default.MIME_PNG)}function rS(r,e){return tS(r,e)}async function sS(){}async function nS(r){function e(o){let i=r[o];return typeof i=="string"&&i.startsWith("data")}async function t(o){let i=await sS(r[o]);return{key:o,url:i}}let s=await ce(Object.keys(r).filter(e),t),n=Object.fromEntries(s.map(o=>[o.key,o.url]));return Object.assign(r,n)}function th(r,e){return e||(e=1),r||(r={left:0,top:0,width:0,height:0}),{left:e*Math.round(r.left),top:e*Math.round(r.top),width:e*Math.round(r.width),height:e*Math.round(r.height),pixelRatio:e}}var rh,Es,eS,Du,ki,sh=T(()=>{"use strict";rh=E(require("lodash"));j();Es=E(require("jimp"));U();eS=x("image-capture-utils"),Du=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};ki=class{constructor(e,t,s){this.windowUtils=t;this.screenshotUtils=s}async takeViewPortImage(){let e=await this.screenshotUtils.takeScreenshot();return typeof e=="string"?e:e.image}takeImageForComparison(){return this.takeViewPortImage()}async takeAreaDataUrl(e){let t=await this.screenshotUtils.takeScreenshot(),s=await eh(e,t);return Object.assign(s,{screenImage:t.image,absoluteScreenHighlight:th(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 nS({screenImage:t.image,absoluteScreenHighlight:th(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:s}=this,n=()=>se(250),o=Boolean(e);async function i(d,g){o?await t.scrollToPositionWithoutAnimation(d):await t.scrollToPosition(d),await n();let f=await s.takeScreenshot(),h=await eh({elementRect:g},f);return{position:{left:d.x+g.left,top:d.y+g.top},size:{width:g.width,height:g.height},image:h.elementImage}}async function a(d){let g=[];for(let f of d){let h=await i(f.scrollPos,f.cropData);g.push(h)}return g}function c(d,g){let f=Math.max(d.width,g.width),h=g.width,y=Math.max(d.height,g.height),w=g.height,S=Array.from({length:Math.ceil(f/h)},(v,I)=>({scrollX:Math.min(I*h,f-h),cropX:I*h-Math.min(I*h,f-h),cropW:h-(I*h-Math.min(I*h,f-h))})),b=Array.from({length:Math.ceil(y/w)},(v,I)=>({scrollY:Math.min(I*w,y-w),cropY:I*w-Math.min(I*w,y-w),cropH:w-(I*w-Math.min(I*w,y-w))}));return S.flatMap(v=>b.map(I=>({scrollPos:{x:v.scrollX,y:I.scrollY},cropData:{top:I.cropY,left:v.cropX,width:v.cropW,height:I.cropH}})))}async function l(d,g){let f=await t.getCurrentScrollPosition(),h=c(d,g),y=await a(h);return await t.scrollToPosition(f),rS(d,y)}let[p,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(p,m)}}});var nh,oh,Pi,Ci,ih=T(()=>{"use strict";nh=E(require("p-retry")),oh=E(require("semver"));j();U();_u();Zg();sh();Ee();Pi=x("tab-service"),Ci=class{constructor(e){this.driver=e;this.sessionTabs={};this._utils={};this.pendingTabs={};this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(s=>!t[s].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={pendingInfos:{},tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(s=>{let n=this.getTabInfo(e,s);return`tabId=${s}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,s,n){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),Pi.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${s}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,s,n)}addOpenerStepId(e,t,s){this.sessionTabs[e].tabInfos[t].openerStepId=s}addOpenerStep(e,t,s){this.sessionTabs[e].tabInfos[t].openerStepId=s.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=s.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let s=this.getAllTabInfos(e);Object.keys(s).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,s,n,o={}){let i=await this.getTabDetails(t,e,o),a=J();function c(l){return o.checkForMainTab?i.isMainTab:!i.isMainTab||i.isMainTab==="unknown"?!l.getMainTabInfo(e):i.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:i.url,title:i.title,favIconUrl:i.favIconUrl,order:s,from:this.getTabInfo(e,i.openerTabId),isMain:c(this),openerStepId:n},a}async addTab(e,t,s,n,o={}){let i=await this.buildTabInfo(e,t,s,n,o),a=new vs(t,this.driver);this._utils[i]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new ki(t,a,new xi(t,this.driver,{takeScreenshots:o.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let s=this.sessionTabs[e].tabInfos[t];return this._utils[s.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(s=>this._utils[s].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let s=this.getAllTabInfos(e),n=Object.keys(s).map(i=>s[i]).filter(i=>!i.isMain);if(n.length===1)return this._utils[n[0].infoId];let o=Object.keys(e).map(i=>e[i]).filter(i=>this.isSameTab(e,t,i));return o.length>0?this._utils[o[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,s){let n=s.filter(o=>o===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,s,n){let{urlUtils:o}=re(),i=o.urlBreaker(e.url||e.currentUrl),a=o.urlBreaker(t.url||t.currentUrl),c=n(i),l=n(a),p=s.map(m=>o.urlBreaker(m)).map(m=>n(m)).filter(m=>m===c);return c===l&&p.length===1}isSameTab(e,t,s){let{tabMatcher:n}=re();if(n){let l=this.getAllTabInfos(e),p=Object.keys(l).map(m=>l[m]);return n.isSameTab(p,t,s)}if(t.isMain&&s.isMain||t.openerStepId&&s.openerStepId&&t.openerStepId===s.openerStepId)return!0;let o=this.getAllTabInfos(e),i=Object.keys(o).map(l=>o[l].url);if(this.exactUrlMatch(t,s,i))return!0;let a=l=>`${l.domain}/${l.path.join("/")}`;if(this.singleExactMatchForParts(t,s,i,a))return!0;let c=l=>`${l.domain}/${l.path.join("/")}#${l.hash}`;return!!(this.singleExactMatchForParts(t,s,i,c)||t.order===s.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(s=>t[s]).find(s=>s.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(s=>t[s].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(s=>this.removeTabInfo(e,s))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(s=>!t[s].isMain).forEach(s=>this.removeTabInfo(e,s)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:s=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||s)return this.driver.switchTab(e)}async getTabDetails(e,t,s={}){try{if(await this.switchTab(e,t,s),s.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");s.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(o=>o.value));try{let[o,i,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:o,url:i,isMainTab:a}}catch(o){Pi.error("failed to get url or title",{err:o})}}catch(n){Pi.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(s=>!this.getAllTabIds(e).includes(s))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await se(500),await this.waitForTabToOpen(e))}async tryToAddTab(e){if(this.pendingTabs[e])return;let t=await this.getUnregisteredTabId(e);t&&(await this.addNewTab(e,t),await this.addFrameHandler(t),Object.assign(this.sessionTabs[e],{currentTab:null}))}async addNewPopup(e,t){let s=this.getAllTabInfos(e);if(Object.keys(s).find(i=>s[i].openerStepId===t))return;if(this.pendingTabs[e]){Pi.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let o=await this.waitForTabToOpen(e);await this.addNewTab(e,o,this.pendingTabs[e]),this.addFrameHandler(o),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,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=oh.lt(e._version||e.version,"1.2.0"),s=!!e.parameterValues,n=s&&e.parameterValues.some(o=>o.type==="locate"&&!o.frameLocators);return t&&(!s||n)}async getTabIdByTabInfo(e,t){var a,c;let{tabMatcher:s,commonConstants:n}=re();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((a=t.useCurrentTab)!=null&&a.call(t)){let l=await this.driver.getCurrentTabId();if(l)return l;let p=this.getMainTabId(e);if(p)return p;throw new Error("Current tab not found")}let o=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,o);let i;if(s){let l=this.getAllTabIds(e).map(p=>Object.assign({},this.getTabInfo(e,p),{tabId:p})).filter(p=>!p.isClosed);i=s.matchTabs(t,l)}else{let l=t.tabInfo;l?i=this.getAllTabIds(e).find(p=>{let m=this.getTabInfo(e,p);return this.isSameTab(e,m,l)}):i=this.getMainTabId(e)}if(!i)throw await this.tryToAddTab(e),new Error("No tab ID found");if(this.sessionTabs[e].currentTab===i)return i;try{return await this.switchTab(i,e),Object.assign(this.sessionTabs[e],{currentTab:i}),i}catch(l){let p=["no such window","no window found","the window could not be found"];if(l.message&&p.some(m=>l.message.toLowerCase().includes(m)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[i].isClosed=!0,this.getTabIdByTabInfo(e,t);throw l}}}});var Nu,Ai,Mu=T(()=>{"use strict";Nu=class{select(){return console.log(`
|
|
221
|
+
`,p=[],g=new Jg.Worker(d,{eval:!0});try{return await ne(new Promise(f=>{g.on("message",h=>{if(h.action==="finish"){let{data:y}=h,w=Object.assign({},y,{tstConsoleLogs:p});gt.debug("Run code worker response",{messageWithLogs:w,transactionId:r}),f(w)}else h.action==="progress"&&p.push(h.data)}).on("error",h=>{h.message==="malformed data: URI"?gt.error("Run code worker error",{err:h,transactionId:r,fileDataUrl:i}):gt.error("Run code worker error",{err:h,transactionId:r}),f({tstConsoleLogs:p,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{gt.debug("Run code worker has been terminated",{transactionId:r})}),g.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:s})}),o)}catch(f){if(!(f instanceof te))throw f;return gt.warn("timeout to run code",{transactionId:r,err:f}),{tstConsoleLogs:p,status:"failed",result:{resultValue:f==null?void 0:f.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{g==null||g.terminate()}}async function ZE(r){try{await qg.promises.rm(r,{recursive:!0,force:!0})}catch(e){gt.warn("failed to remove install npm packages folder",{err:e})}}function Yg(r,e,t,s){return`${e}_${t}_${r}_${s}`}async function ys(r,e,t,s,n,o){let i=Yg(n,e,r,t),{data:a}=await eS(i,s,o);return a}async function bs(r,e,t,s,n,o,i,a,c,l){var f;let m=Object.fromEntries(((f=t.nodePackageParams)==null?void 0:f.map(h=>[h.paramName,h.testimPackageLocalLocation]))||[]),d=Yg(i,n,e,o);if(l){let h=await nn(l);h&&(c=h)}Buffer.isBuffer(c)&&(gt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let p="data:,";c==="data:"&&(gt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=p);let g=await QE(d,t,s,r,m,a,c);return Object.assign({},g,{nodeVersion:process.version})}async function eS(r,e,t){let s=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Xg(),o=xn.join(n,`/${r}`),i=global.proxyUri;async function a(){let c="";try{if(c=await zd(o,s,i,t),gt.info("npm package install finished",{transactionId:r,output:c,timeout:t}),Number(c.trim().split(" ")[1])<s.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(m=>{let d=qd(o,m.packageName);return{...m,packageFullName:`${m.packageName}@${d}`,packageLocalLocation:xn.resolve(o,"node_modules",m.packageName)}}),installFolder:o}}catch(l){throw gt.warn("npm package install failed",{transactionId:r,err:l}),l}}try{return await ne(a(),t)}catch(c){throw c instanceof te&>.warn("timeout to install package",{packages:s,transactionId:r,err:c,timeout:t}),c}}function Xg(){return xn.join(zg.tmpdir(),"/testim_local_packages")}function Qg(){let r=Xg();return ZE(r)}var qg,zg,xn,Kg,Jg,gt,Cr=T(()=>{"use strict";qg=E(require("fs")),zg=E(require("os")),xn=E(require("path"));j();Qs();Kg=E(require("data-uri-to-buffer")),Jg=require("worker_threads");V();U();be();gt=x("cli-service")});var nr={};$(nr,{run:()=>rS});function tS(r,e){try{let t=e.defaults.enforceMaximumJsResultSize,s=M.flags.maximumJsResultSize.getValue(),n=JSON.stringify(r).length>s;return t?n:!1}catch{return!1}}var rS,Zg=T(()=>{"use strict";Cr();V();Te();rS=async(r,e,t)=>{let{code:s,stepId:n,incomingParams:o,context:i,testResultId:a,retryIndex:c,stepResultId:l,runTimeout:m,fileDataUrl:d,s3filepath:p}=e.data;try{let g=await bs(s,n,o,i,a,c,l,m,d,p);return g&&tS({result:g.result,tstConsoleLogs:g.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:g,success:!0}}catch(g){throw g instanceof te?new Error("Timeout while running action"):g}}});var Au,ws,Ou=T(()=>{"use strict";U();Au=x("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(s){throw Au.error("failed to set cookie",{err:s}),s}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw Au.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw Au.error("failed to remove cookie",{err:t}),t}}}});var _u,eh,vs,Lu=T(()=>{"use strict";j();_u=E(require("p-retry"));j();U();V();eh=x("window-utils"),vs=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function s(o,i){let a=document.elementFromPoint(o,i);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(s,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(s){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:s.x,top:s.y,behavior:"instant"}):window.scrollTo(s.x,s.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let s=async(n=3)=>{try{await this.driver.url(e)}catch(o){let i=o.message.includes("method IWebBrowser2::Navigate2() failed");if(o.seleniumStack&&i&&n>0)return eh.warn("selenium navigation failed. retrying to navigate",{err:o}),await se(1500),s(n-1);throw!o.seleniumStack&&i&&eh.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:o}),o}};return Promise.race([s(),se(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),se(e)])}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let s=document.body,n=document.documentElement,o=Math.max(s.scrollHeight,s.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),i=Math.max(s.scrollWidth,s.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:o,width:i}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await se(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let s;if(typeof location<"u")s=location;else if(typeof window<"u"&&typeof window.location<"u")s=window.location;else return!1;return s.href!=="chrome-error://chromewebdata/"&&s.href!=="safari-resource:/ErrorPage.html"&&s.href.indexOf("res://ieframe.dll/http_404.htm")!==0&&s.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new Tt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,_u.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,_u.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var Du,xi,th=T(()=>{"use strict";Du=E(require("p-retry")),xi=class{constructor(e,t,s={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=s;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,s=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([s,this.driver.takeScreenshot()]),[o,i]=await(0,Du.default)(n,{retries:e,minTimeout:t,factor:1}),a=i?i.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,s=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),o=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[i,a]=await(0,Du.default)(o,{retries:t,minTimeout:s,factor:1}),c=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(c.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function rh(r,e){let t=e.image||e,s=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let o=r.offset||{top:0,left:0};if(o.top*=s,o.left*=s,!r.elementRect)return sS.warn("missing elementRect",nh.omit(r,"image")),{};let{elementRect:i}=r,a=await Es.default.read(Buffer.from(n[1],"base64")),c=i.left*s+o.left*s,l=i.top*s+o.top*s,m=i.width*s,d=i.height*s;c<0&&(m+=c,m=m<0?0:m,c=0),l<0&&(d+=l,d=d<0?0:d,l=0);let p=a.bitmap.width,g=a.bitmap.height;if(c+m>p&&(m=p-c),l+d>g&&(d=g-l),d<=0||m<=0)throw new Nu("height or width is equal or lower than zero");return{elementImage:await a.crop(c,l,m,d).getBase64Async(Es.default.MIME_PNG)}}async function nS(r,e){let t=await Es.default.read(r.width,r.height);for(let n of e){let o=n.image.match(/^data:[^;]*;base64,(.*)$/),i=await Es.default.read(Buffer.from(o[1],"base64"));await new Promise((a,c)=>{t.composite(i,n.position.left,n.position.top,l=>{if(l){c(l);return}a()})})}return await t.getBase64Async(Es.default.MIME_PNG)}function oS(r,e){return nS(r,e)}async function iS(){}async function aS(r){function e(o){let i=r[o];return typeof i=="string"&&i.startsWith("data")}async function t(o){let i=await iS(r[o]);return{key:o,url:i}}let s=await ce(Object.keys(r).filter(e),t),n=Object.fromEntries(s.map(o=>[o.key,o.url]));return Object.assign(r,n)}function sh(r,e){return e||(e=1),r||(r={left:0,top:0,width:0,height:0}),{left:e*Math.round(r.left),top:e*Math.round(r.top),width:e*Math.round(r.width),height:e*Math.round(r.height),pixelRatio:e}}var nh,Es,sS,Nu,ki,oh=T(()=>{"use strict";nh=E(require("lodash"));j();Es=E(require("jimp"));U();sS=x("image-capture-utils"),Nu=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};ki=class{constructor(e,t,s){this.windowUtils=t;this.screenshotUtils=s}async takeViewPortImage(){let e=await this.screenshotUtils.takeScreenshot();return typeof e=="string"?e:e.image}takeImageForComparison(){return this.takeViewPortImage()}async takeAreaDataUrl(e){let t=await this.screenshotUtils.takeScreenshot(),s=await rh(e,t);return Object.assign(s,{screenImage:t.image,absoluteScreenHighlight:sh(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 aS({screenImage:t.image,absoluteScreenHighlight:sh(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:s}=this,n=()=>se(250),o=Boolean(e);async function i(p,g){o?await t.scrollToPositionWithoutAnimation(p):await t.scrollToPosition(p),await n();let f=await s.takeScreenshot(),h=await rh({elementRect:g},f);return{position:{left:p.x+g.left,top:p.y+g.top},size:{width:g.width,height:g.height},image:h.elementImage}}async function a(p){let g=[];for(let f of p){let h=await i(f.scrollPos,f.cropData);g.push(h)}return g}function c(p,g){let f=Math.max(p.width,g.width),h=g.width,y=Math.max(p.height,g.height),w=g.height,S=Array.from({length:Math.ceil(f/h)},(v,I)=>({scrollX:Math.min(I*h,f-h),cropX:I*h-Math.min(I*h,f-h),cropW:h-(I*h-Math.min(I*h,f-h))})),b=Array.from({length:Math.ceil(y/w)},(v,I)=>({scrollY:Math.min(I*w,y-w),cropY:I*w-Math.min(I*w,y-w),cropH:w-(I*w-Math.min(I*w,y-w))}));return S.flatMap(v=>b.map(I=>({scrollPos:{x:v.scrollX,y:I.scrollY},cropData:{top:I.cropY,left:v.cropX,width:v.cropW,height:I.cropH}})))}async function l(p,g){let f=await t.getCurrentScrollPosition(),h=c(p,g),y=await a(h);return await t.scrollToPosition(f),oS(p,y)}let[m,d]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(m,d)}}});var ih,ah,Pi,Ci,ch=T(()=>{"use strict";ih=E(require("p-retry")),ah=E(require("semver"));j();U();Lu();th();oh();Ee();Pi=x("tab-service"),Ci=class{constructor(e){this.driver=e;this.sessionTabs={};this._utils={};this.pendingTabs={};this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(s=>!t[s].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={pendingInfos:{},tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(s=>{let n=this.getTabInfo(e,s);return`tabId=${s}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,s,n){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),Pi.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${s}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,s,n)}addOpenerStepId(e,t,s){this.sessionTabs[e].tabInfos[t].openerStepId=s}addOpenerStep(e,t,s){this.sessionTabs[e].tabInfos[t].openerStepId=s.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=s.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let s=this.getAllTabInfos(e);Object.keys(s).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,s,n,o={}){let i=await this.getTabDetails(t,e,o),a=J();function c(l){return o.checkForMainTab?i.isMainTab:!i.isMainTab||i.isMainTab==="unknown"?!l.getMainTabInfo(e):i.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:i.url,title:i.title,favIconUrl:i.favIconUrl,order:s,from:this.getTabInfo(e,i.openerTabId),isMain:c(this),openerStepId:n},a}async addTab(e,t,s,n,o={}){let i=await this.buildTabInfo(e,t,s,n,o),a=new vs(t,this.driver);this._utils[i]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new ki(t,a,new xi(t,this.driver,{takeScreenshots:o.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let s=this.sessionTabs[e].tabInfos[t];return this._utils[s.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(s=>this._utils[s].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let s=this.getAllTabInfos(e),n=Object.keys(s).map(i=>s[i]).filter(i=>!i.isMain);if(n.length===1)return this._utils[n[0].infoId];let o=Object.keys(e).map(i=>e[i]).filter(i=>this.isSameTab(e,t,i));return o.length>0?this._utils[o[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,s){let n=s.filter(o=>o===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,s,n){let{urlUtils:o}=re(),i=o.urlBreaker(e.url||e.currentUrl),a=o.urlBreaker(t.url||t.currentUrl),c=n(i),l=n(a),m=s.map(d=>o.urlBreaker(d)).map(d=>n(d)).filter(d=>d===c);return c===l&&m.length===1}isSameTab(e,t,s){let{tabMatcher:n}=re();if(n){let l=this.getAllTabInfos(e),m=Object.keys(l).map(d=>l[d]);return n.isSameTab(m,t,s)}if(t.isMain&&s.isMain||t.openerStepId&&s.openerStepId&&t.openerStepId===s.openerStepId)return!0;let o=this.getAllTabInfos(e),i=Object.keys(o).map(l=>o[l].url);if(this.exactUrlMatch(t,s,i))return!0;let a=l=>`${l.domain}/${l.path.join("/")}`;if(this.singleExactMatchForParts(t,s,i,a))return!0;let c=l=>`${l.domain}/${l.path.join("/")}#${l.hash}`;return!!(this.singleExactMatchForParts(t,s,i,c)||t.order===s.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(s=>t[s]).find(s=>s.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(s=>t[s].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(s=>this.removeTabInfo(e,s))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(s=>!t[s].isMain).forEach(s=>this.removeTabInfo(e,s)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:s=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||s)return this.driver.switchTab(e)}async getTabDetails(e,t,s={}){try{if(await this.switchTab(e,t,s),s.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");s.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(o=>o.value));try{let[o,i,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:o,url:i,isMainTab:a}}catch(o){Pi.error("failed to get url or title",{err:o})}}catch(n){Pi.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(s=>!this.getAllTabIds(e).includes(s))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await se(500),await this.waitForTabToOpen(e))}async tryToAddTab(e){if(this.pendingTabs[e])return;let t=await this.getUnregisteredTabId(e);t&&(await this.addNewTab(e,t),await this.addFrameHandler(t),Object.assign(this.sessionTabs[e],{currentTab:null}))}async addNewPopup(e,t){let s=this.getAllTabInfos(e);if(Object.keys(s).find(i=>s[i].openerStepId===t))return;if(this.pendingTabs[e]){Pi.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let o=await this.waitForTabToOpen(e);await this.addNewTab(e,o,this.pendingTabs[e]),this.addFrameHandler(o),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,ih.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=ah.lt(e._version||e.version,"1.2.0"),s=!!e.parameterValues,n=s&&e.parameterValues.some(o=>o.type==="locate"&&!o.frameLocators);return t&&(!s||n)}async getTabIdByTabInfo(e,t){var a,c;let{tabMatcher:s,commonConstants:n}=re();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((a=t.useCurrentTab)!=null&&a.call(t)){let l=await this.driver.getCurrentTabId();if(l)return l;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let o=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,o);let i;if(s){let l=this.getAllTabIds(e).map(m=>Object.assign({},this.getTabInfo(e,m),{tabId:m})).filter(m=>!m.isClosed);i=s.matchTabs(t,l)}else{let l=t.tabInfo;l?i=this.getAllTabIds(e).find(m=>{let d=this.getTabInfo(e,m);return this.isSameTab(e,d,l)}):i=this.getMainTabId(e)}if(!i)throw await this.tryToAddTab(e),new Error("No tab ID found");if(this.sessionTabs[e].currentTab===i)return i;try{return await this.switchTab(i,e),Object.assign(this.sessionTabs[e],{currentTab:i}),i}catch(l){let m=["no such window","no window found","the window could not be found"];if(l.message&&m.some(d=>l.message.toLowerCase().includes(d)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[i].isClosed=!0,this.getTabIdByTabInfo(e,t);throw l}}}});var Mu,Ai,Fu=T(()=>{"use strict";Mu=class{select(){return console.log(`
|
|
222
222
|
internal error - cant use port selector in selenium!!!!
|
|
223
|
-
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},Ai=new
|
|
223
|
+
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},Ai=new Mu});var Ss,Uu=T(()=>{"use strict";Ou();Ee();Ss=class{constructor(e,t){this.driver=e;this._abortedSteps=[];this.cookieUtils=t||new ws(this.driver)}get sessionPlayerInit(){return re()}getTimeStamp(){return Date.now()}getTestimId(e){if(!e)return;let{locatorBuilderUtils:t}=this.sessionPlayerInit,s=t.TESTIM_ID_FIELD_NAME;return t.isEmptyResult(e)?t.EMPTY_RESULT_ID:e.getAttribute(s)}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async restoreNativeAlerts(){}executeOverloadNativeAlertsInFrame(){}getClickOffset(e,t){let{utils:s}=this.sessionPlayerInit;return e&&s.isWithinBounds(0,t.width,e.x)&&s.isWithinBounds(0,t.height,e.y)?{xOffset:e.x,yOffset:e.y}:{xOffset:t.width/2,yOffset:t.height/2}}async executeInAut(e,t){let{value:s}=await this.driver.executeJS(t);return s}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 s=`return ${this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t)}`,{value:n}=await this.driver.executeJS(s);return n}}});function uh(r){class e{constructor(s,n){this.frameManager=s;this.LocateElementPlayer=n;this._cache={}}cacheResults(s,n){this._cache[s]=n}getResultsFromCache(s){return this._cache[s]}cacheFrameLocateResults(s){if(s!=null&&s.seleniumFrameElement&&s.frameLocateResultUrl){let n=lh(s.seleniumFrameElement);n&&this.cacheResults(n,s.frameLocateResultUrl)}}async foundFrameCallback(s,n,o){let{frameOffset:i,locatedElement:a}=s,{locatorBuilderUtils:c}=re();if(c.isEmptyResult(a)){let p="got empty result in frame result, not rejected from locate element player";throw cS.error(p),new Error(p)}let l=await r.switchToLocatedFrame(a),m=lh(l.value),d=this.getResultsFromCache(m);return{url:"",frameId:-1,frameOffset:i,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:o,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${o}`,seleniumFrameElement:l.value,frameLocateResultUrl:d}}async locate(s,n,o,i,a,c){let l=new this.LocateElementPlayer(i);s.targetId=`frameLocator_${n}`;let m=await l.locate(s,o,s.targetId);m.isVisible=!0;let d=await l.handleLocateResult(m,c,s).catch(()=>{throw new Error("")}),{locatedElement:p}=i.data[s.targetId],f=(await r.getElementLocationWithPadding(p)).value||{top:0,left:0};d.frameOffset={top:o.frameOffset.top+f.top,left:o.frameOffset.left+f.left},l.addFrameDataToContext&&l.addFrameDataToContext(d.targetId,d.locateResult);let h=await this.foundFrameCallback(d,a,s.testimFrameId);return this.currentFrameHandler=h,h}async findFrame(s,n,o,i){let a=M.flags.enableFrameSwitchOptimization.isEnabled(),l=o.playback.resultsHandler.resultsByChronologicOrder.at(-1),m=1,d=l&&l.stepId===s.id&&l.results.length>m;if(a&&!d&&this.currentFrameHandler){let y=n.findIndex(w=>w.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let w=n.slice(y+1),S=0;for(let b of w)S++,this.currentFrameHandler=await this.locate(b,S,this.currentFrameHandler,o,i,s);return this.currentFrameHandler}}let p=await i.getTopFrameHandler();p.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===p?this.currentFrameHandler:r.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=p;let f=0,h=p;for(let y of n)f++,h=await this.locate(y,f,h,o,i,s);return h}}return e}var cS,lS,lh,ph=T(()=>{"use strict";U();Te();Ee();Fr();cS=x("frame-locator"),lS="ELEMENT",lh=r=>r?r[lS]||r[Ht]:null});var Oi,ju=T(()=>{"use strict";pe();Oi=()=>{try{if(zp)return!1;if(require("inspector").url())return!0}catch{}return!1}});var H,ue=T(()=>{"use strict";Ee();H=class{constructor(e,t,s,n={},o=void 0,i=void 0,a={}){this.step=e;this.context=t;this.frameHandler=s;this.exportsGlobal=n;this.stepActionUtils=o;this.locateElementPlayer=i;this.exportsTest=a;this.frameId=0}get driver(){return this.stepActionUtils.driver}get sessionPlayerInit(){return re()}async performAction(e,t){throw new Error("not implemented")}getTarget(){let e=this.step.targetId||"targetId";return this.context.data[e]}async execute(e,t){var s;try{return{success:!0,...await this.performAction(e,t)}}catch(n){let o=(n==null?void 0:n.message)||((s=n==null?void 0:n.seleniumStack)==null?void 0:s.message),i=n==null?void 0:n.displayMessage;return{success:!1,reason:o,exception:n,errorType:this.sessionPlayerInit.commonConstants.stepResult.ACTION_EXCEPTION,resultInfo:{exception:`selenium exception: ${o}`,error:i||o}}}}}});function pS(r){let t=new dh.DOMParser().parseFromString("<html><body></body></html>","text/html");return t.body.outerHTML=r,Object.assign(t,{parsedUsingLinkedom:!0})}function dS(r,e,t,s){return r.opacity===0||r.isShadowed?!1:e===void 0||t===void 0?!0:M.flags.useClickimVisibilityChecks.isEnabled()?!1:s.isSafari()?M.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0}function mS(r){return{getFrameIdByTestimFrameId(){},async setElementResultDataOnContext(e){let t=await r.getElement(e.locatedElement);e.seleniumElement=t.value},getElementRectangle(e){return r.getElementRect(e)},async getOffsets(e){return[e.frameOffset||{}]},htmlStringToDom(e,t,s,n,o=!1){let i;if(o)i=pS(e);else{let a=new _i.VirtualConsole;i=new _i.JSDOM(e,{virtualConsole:a}).window.document}return Object.assign(i,{TESTIM_URL:t})},async isVisible(e,t,s,n,o,i,a){let{locatorBuilderUtils:c,codeSnippets:l,visibilityUtils:m,positionUtils:d}=re();if(dS(n,m,d,r))return r.isVisible(e.seleniumElement);if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await r.isVisible(e.seleniumElement)}catch{}if(!t||c.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let f=[d.calculateElementMiddlePoint(s),d.calculateClickPoint(n.clickOffset,s)].filter(Boolean),h=l.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,f,!1,n),y;try{y=await r.execute(`return ${h}`)}catch(I){throw Ar.error("failed to execute getVisibilityCode",{err:I}),I}let{value:w}=y||{},S=w.elementVisibilityInfo||uS,[b,v]=w.elementsFromPointResults||[null,null];return m.checkElementVisibility(S,n,v,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:s}}=re();await r.execute(s(t))},get useLocatedElement(){return!0}}}var _i,dh,Ar,uS,kn,mh=T(()=>{"use strict";_i=require("jsdom");ue();U();Te();Ee();dh=require("linkedom"),Ar=x("locate-step-action"),uS={opacity:1,clientRects:{}};kn=class extends H{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return mS(e)}static getFrameIdByTestimFrameId(){throw Ar.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw Ar.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw Ar.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw Ar.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw Ar.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw Ar.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var fh={};$(fh,{scroll:()=>fS});var fS,gh=T(()=>{"use strict";fS=function(r,e,t,s,n,o,i,a){function c(S,b){if(!b)return{success:!1};elementScrollTo(b,S.x,S.y);let v=b.scrollLeft,I=b.scrollTop;return{success:Math.abs(I-S.y)<1&&Math.abs(v-S.x)<1,actualX:v,actualY:I}}function l(S,b){if(!t)return{x:n,y:o};let v=getLocatedElement(b);if(s&&!v)return{x:S.scrollWidth,y:S.scrollHeight};if(!v)throw new Error("could not find target element");let I=v.getBoundingClientRect(),A=0,_=0,R=Math.max(window.innerHeight-(I.height+10),0),L=Math.max(window.innerWidth-(I.width+10),0);return A=a?S.scrollTop+I.top-Math.min(o,R):S.scrollTop,_=i?S.scrollLeft+I.left-Math.min(n,L):S.scrollLeft,{x:Math.round(_),y:Math.round(A)}}let m=!r,d=m?document.scrollingElement||document.documentElement:getLocatedElement(r);if(!d)throw new Error("could not find target to scroll on");let p={top:d.scrollTop,left:d.scrollLeft},g=l(d,e),f=c(g,d);m&&!document.scrollingElement&&!f.success&&p.top===d.scrollTop&&p.left===d.scrollLeft&&(d=document.body,g=l(d,e),f=c(g,d));let h=f.actualX,y=f.actualY,w=getLocatedElement(e);if(t&&s&&!w)return{success:!1,expectedPosition:g};if(t){if(!w)throw new Error("could not find target to scroll to");let S=w.getBoundingClientRect();h=S.left,y=S.top}return{success:f.success,actualX:h,actualY:y}}});var Li,hh=T(()=>{"use strict";ue();Li=class extends H{getFailureString(e,t,s,n,o){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${s}, x: ${t}); Actual:(y:${o}, x: ${n})`;let i="Scrolling limit reached";return e.shouldScrollTop&&(i+=`. Expected top margin: ${s}, actual: ${o}`),e.shouldScrollLeft&&(i+=`. Expected left margin: ${t}, actual: ${n}`),i}async scroll(e,t,s){let{codeSnippets:n,commonConstants:{stepResult:o}}=this.sessionPlayerInit,i=Math.round(Number(t.isScrollToElement?t.marginTop:t.y)),a=Math.round(Number(t.isScrollToElement?t.marginLeft:t.x)),c=this.driver.isFirefox()?function(d,p,g){d.scrollTo(p,g)}:function(d,p,g){d.scrollTop=g,d.scrollLeft=p},{scroll:l}=await Promise.resolve().then(()=>(gh(),fh)),m=`
|
|
224
224
|
const getLocatedElement = ${n.getLocatedElementCode};
|
|
225
225
|
const elementScrollTo = ${c.toString()};
|
|
226
226
|
const scroll = ${l.toString()};
|
|
227
227
|
return scroll.apply(null, arguments)
|
|
228
|
-
`;try{let m=await this.driver.executeJS(p,s,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,i,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:o.SCROLL_ACTION_FAILURE,success:!1};let{success:d,actualX:g,actualY:f}=m.value;return d?{success:!0}:{errorType:o.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,i,g,f)}}}catch{return{errorType:o.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,s=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,s):this.scrollOnElement(t,s)}}});var gh,hh=T(()=>{"use strict";gh=function(r){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let s={data:{},setData(a,c){e[t(a)]=c},getData(a){return e[t(a)]}},n=getLocatedElement(r.fromLocatedElement),o=getLocatedElement(r.toLocatedElement);if(!n)throw new Error("from element not found");if(!o)throw new Error("to element not found");let i=function(a,c){let l=document.createEvent("CustomEvent");l.initCustomEvent(c,!0,!0,null),Object.assign(l,{dataTransfer:s}),a.dispatchEvent?a.dispatchEvent(l):a.fireEvent&&a.fireEvent(`on${c}`,l)};i(n,"dragstart"),i(o,"drop"),i(n,"dragend")}});var yh,bh=T(()=>{"use strict";yh=function(r,e){let t=typeof MouseEvent=="function",s=typeof DragEvent=="function",n=typeof PointerEvent=="function",o={};window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(C){e({status:"done",result:C,success:!0})}function a(C){C||(C={}),e({status:"failed",result:C,success:!1,keep:!0})}function c(C){return C!=null&&C.toLowerCase?(C=C.toLowerCase(),C==="text"?"text/plain":C==="url"?"text/uri-list":C):C}function l(){try{return new DataTransfer}catch{return{data:{},setData(N,B){o[c(N)]=B},getData(N){return o[c(N)]}}}}let p=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],d=p.concat(["drop","dragenter","dragover"]);function g(C){let N=C;for(;N&&N!==document.documentElement;){if(N.draggable)return N;N=N.parentElement}return null}function f(C,N,B){let K=N.element,{dispatchDragEventsOnClosestDraggable:X}=B;if(p.includes(C.type)&&X){if(!K&&N.lastDraggedElement)return N.lastDraggedElement;let ee=g(K);if(ee)return N.lastDraggedElement=ee,ee}return K}function h(C,N,B){function K(At,Mr,P){return P>At&&P<Mr}let X=C.pointerPosition||{};if(N)return{x:X.originX||0,y:X.originY||0};let ee=B.getBoundingClientRect(),fe=X.originX&&K(ee.left,ee.left+ee.width,X.originX)?X.originX:ee.left+ee.width/2,dr=X.originY&&K(ee.top,ee.top+ee.height,X.originY)?X.originY:ee.top+ee.height/2;return{x:fe,y:dr}}function y(C,N,B){let K=(N==null?void 0:N.modifiers)||{},X=h(C,B.isDrag,B.element),ee=(N==null?void 0:N.button)||0,fe=C.event;return m.includes(fe)?S(fe,K,X.x,X.y,ee):d.includes(fe)?v(fe,K,X.x,X.y):b(fe,K,X.x,X.y,ee)}function w(C,N,B){return{screenX:0,screenY:0,clientX:N,clientY:B,ctrlKey:Boolean(C.ctrl),altKey:Boolean(C.alt),shiftKey:Boolean(C.shift),metaKey:Boolean(C.meta),bubbles:!0,cancelable:!0,composed:!0}}function S(C,N,B,K,X){if(n){let fe=w(N,B,K);return fe.pointerType="mouse",fe.isPrimary=!0,new window.PointerEvent(C,fe)}let ee=document.createEvent("PointerEvent");return ee.initPointerEvent(C,!0,!0,document.defaultView,1,0,0,B,K,Boolean(N.ctrl),Boolean(N.alt),Boolean(N.shift),Boolean(N.meta),X,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),ee}function b(C,N,B,K,X){let ee=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return ee.initMouseEvent(C,!0,!0,document.defaultView,1,0,0,B,K,Boolean(N.ctrl),Boolean(N.alt),Boolean(N.shift),Boolean(N.meta),X,document.body?document.body.parentNode:document.documentElement),ee}function v(C,N,B,K){if(C==="dragstart"&&(window.TSTA||(window.TSTA={}),window.TSTA.dataTransfer=l()),!s){let fe=document.createEvent("CustomEvent");return fe.initCustomEvent(C,!0,!0,null),Object.assign(fe,{dataTransfer:window.TSTA.dataTransfer}),fe}let X=w(N,B,K),ee=new window.DragEvent(C,X);return Object.defineProperties(ee,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),ee}function I(C,N,B){let K=f(C,N,B);K==null||K.dispatchEvent(C)}function A(C,N){function B(){return C.event==="click"&&N.isDrag&&!N.allEventsOnSameElement}return B()}function _(C,N,B){if(B){let K=Math.min(B.timeStamp-N.timeStamp,40);setTimeout(()=>{R(C)},K)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),i()}function R(C){let N,B=C.events[C.eventIndex],K=C.events[++C.eventIndex];try{C.element=getLocatedElement(B.locatedElement),N=y(B,r,C)}catch(X){return a(`exception in get event in drag step:${X.message}`)}if(A(B,C))return _(C,B,K);if(N)try{I(N,C,B)}catch(X){return a(`exception in executeEvent in drag step:${X.message}`)}else return a(`cannot execute event ${B.event}`);_(C,B,K)}let L={eventIndex:0,allEventsOnSameElement:r.allEventsOnSameElement,events:r.events,eventType:r.eventType,eventData:r.eventData,stepId:r.id,testResultId:r.testResultId,isDrag:r.isDrag,useRecordedMousedown:r.useRecordedMousedown,trackActiveElement:r.trackActiveElement};setTimeout(()=>{try{R(L)}catch(C){a(C)}},0)}});var Th={};$(Th,{doClick:()=>dS});var dS,wh=T(()=>{"use strict";dS=(r,e)=>{let t=typeof Event=="function";window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function s(b,v){var _;function I(R){function L(){return o(R).find(B=>[...B.classList||[]].includes("Select-control"))}function C(){let B=L();return B?B.querySelector("input"):null}let N=C();N==null||N.focus()}let A=(_=b.quirks)==null?void 0:_.isReactSelect;v.type==="mousedown"&&A&&I(b.element)}function n(b,v){var A;let I=(A=b.quirks)==null?void 0:A.isCKEditorFrame;v.type==="click"&&I&&document.body.focus()}function o(b){return b?[b].concat(o(b.parentNode)):[]}function i(b){let v={status:"done",result:b,success:!0,...S.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(v)}function a(b){b||(b=""),e({status:"failed",result:b,success:!1})}function c(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function l(b){let v={},I=b.getBoundingClientRect(),A=I.left+I.width/2,_=I.top+I.height/2,C=g("mousemove",v,A,_,0);b.dispatchEvent(C)}function p(b,v){function I(C,N,B){return B>C&&B<N}let A=b.pointerPosition||{},_=v.getBoundingClientRect(),R=A.originX&&I(_.left,_.left+_.width,A.originX)?A.originX:_.left+_.width/2,L=A.originY&&I(_.top,_.top+_.height,A.originY)?A.originY:_.top+_.height/2;return{x:R,y:L}}function m(b,v,I){return{screenX:0,screenY:0,clientX:v,clientY:I,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function d(b,v,I,A){if(!window.PointerEvent)return;let _=m(v,I,A);return _.pointerType="mouse",_.isPrimary=!0,new window.PointerEvent(b,_)}function g(b,v,I,A,_){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,I,A,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement),R}function f(b,v){let I=["pointerup","pointerdown","pointermove"],A=v.modifiers||{},_=p(b,v.element),R=v.button||0,L=b.event;return I.includes(L)?d(L,A,_.x,_.y):g(L,A,_.x,_.y,R)}function h(){var v;let b=document.activeElement;for(;(v=b.shadowRoot)!=null&&v.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(v=>{try{return f(v,b)}catch{return}}).filter(Boolean).forEach(v=>{b.element.dispatchEvent(v),s(b,v),n(b,v)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let S={element:r.isRoot?document.documentElement:getLocatedElement(r.locatedElement),events:r.events,quirks:r.quirks,modifiers:r.modifiers,button:r.button};if(!S.element){a("element not found");return}c(S.element),l(S.element);try{y(S);let b=h(),v=S.quirks,I=v==null?void 0:v.isReactSelect,A=v==null?void 0:v.isCKEditorFrame;!I&&!A&&dispatchFocus(r.elementToFocusLocatedElement,b),i()}catch(b){a(b.toString())}}});var vh={};$(vh,{doDragPath:()=>mS});var mS,Eh=T(()=>{"use strict";mS=function(r,e){let t=typeof Event=="function",s=typeof PointerEvent=="function",n=40;window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(b){e({status:"done",result:b,success:!0})}function i(b){b||(b=""),e({status:"failed",result:b,success:!1})}function a(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function c(b){let v={},I=b.getBoundingClientRect(),A=I.left+I.width/2,_=I.top+I.height/2,C=d("mousemove",v,A,_,0);b.dispatchEvent(C)}function l(b,v){function I(C,N,B){return B>C&&B<N}let A=b.pointerPosition||{};if(S.isDrag)return{x:A.originX||0,y:A.originY||0};let _=v.getBoundingClientRect(),R=A.originX&&I(_.left,_.left+_.width,A.originX)?A.originX:_.left+_.width/2,L=A.originY&&I(_.top,_.top+_.height,A.originY)?A.originY:_.top+_.height/2;return{x:R,y:L}}function p(b,v,I){return{screenX:0,screenY:0,clientX:v,clientY:I,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function m(b,v,I,A,_){if(s){let L=p(v,I,A);return L.pointerType="mouse",L.isPrimary=!0,new window.PointerEvent(b,L)}let R=document.createEvent("PointerEvent");return R.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,I,A,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),R}function d(b,v,I,A,_){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,I,A,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement),R}function g(b,v){let I=["pointerup","pointerdown","pointermove"],A=v.modifiers||{},_=l(b,v.element),R=v.button||0,L=b.event;return I.includes(L)?m(L,A,_.x,_.y,R):d(L,A,_.x,_.y,R)}function f(b,v){function I(){return b.event==="click"&&v.isDrag&&!v.allEventsOnSameElement}return I()}function h(b,v,I){try{let A=g(v.events[b],v);f(A,v)||v.element.dispatchEvent(A)}catch{}if(b+1===v.events.length)I();else{let A=Math.min(v.events[b+1].timeStamp-v.events[b].timeStamp,n);setTimeout(()=>{h(b+1,v,I)},A)}}function y(b,v){h(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v()})}let S={eventIndex:0,element:r.isRoot?document.documentElement:getLocatedElement(r.locatedElement),events:r.events,eventType:r.eventType,eventData:r.eventData,stepId:r.id,testResultId:r.testResultId,quirks:r.quirks,isDoubleClick:r.isDoubleClick,isDrag:r.isDrag,useRecordedMousedown:r.useRecordedMousedown,trackActiveElement:r.trackActiveElement,allEventsOnSameElement:r.allEventsOnSameElement};if(!S.element){i("element not found");return}a(S.element),c(S.element),y(S,()=>{o()})}});var Pn,Di,Sh=T(()=>{"use strict";Pn=E(require("lodash"));ue();hh();Te();bh();Di=class extends H{getDnDRectsAndOffsets(e,t,s,n){let o=this.stepActionUtils.getClickOffset(s,e.rectWithoutFrameOffset),i=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:o.xOffset,fromY:o.yOffset,toRect:t.rectWithoutFrameOffset,toX:i.xOffset,toY:i.yOffset}}async clickJs(){var p;let{step:e,context:t}=this,s=this.getTarget(),n=t.data.timeToPlayStep+3e3,o=e.events;if(!(o!=null&&o.length))return{success:!1,reason:"Malformed step: missing recorded events"};let i={isRoot:s.isRoot,locatedElement:s.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(wh(),Th)),Promise.resolve().then(()=>(Rn(),Sn))]),l=`
|
|
228
|
+
`;try{let d=await this.driver.executeJS(m,s,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,i,t.shouldScrollLeft,t.shouldScrollTop);if(!(d!=null&&d.value))return{errorType:o.SCROLL_ACTION_FAILURE,success:!1};let{success:p,actualX:g,actualY:f}=d.value;return p?{success:!0}:{errorType:o.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,i,g,f)}}}catch{return{errorType:o.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,s=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,s):this.scrollOnElement(t,s)}}});var yh,bh=T(()=>{"use strict";yh=function(r){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let s={data:{},setData(a,c){e[t(a)]=c},getData(a){return e[t(a)]}},n=getLocatedElement(r.fromLocatedElement),o=getLocatedElement(r.toLocatedElement);if(!n)throw new Error("from element not found");if(!o)throw new Error("to element not found");let i=function(a,c){let l=document.createEvent("CustomEvent");l.initCustomEvent(c,!0,!0,null),Object.assign(l,{dataTransfer:s}),a.dispatchEvent?a.dispatchEvent(l):a.fireEvent&&a.fireEvent(`on${c}`,l)};i(n,"dragstart"),i(o,"drop"),i(n,"dragend")}});var Th,wh=T(()=>{"use strict";Th=function(r,e){let t=typeof MouseEvent=="function",s=typeof DragEvent=="function",n=typeof PointerEvent=="function",o={};window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(C){e({status:"done",result:C,success:!0})}function a(C){C||(C={}),e({status:"failed",result:C,success:!1,keep:!0})}function c(C){return C!=null&&C.toLowerCase?(C=C.toLowerCase(),C==="text"?"text/plain":C==="url"?"text/uri-list":C):C}function l(){try{return new DataTransfer}catch{return{data:{},setData(N,B){o[c(N)]=B},getData(N){return o[c(N)]}}}}let m=["drag","dragstart","dragend"],d=["pointerup","pointerdown","pointermove"],p=m.concat(["drop","dragenter","dragover"]);function g(C){let N=C;for(;N&&N!==document.documentElement;){if(N.draggable)return N;N=N.parentElement}return null}function f(C,N,B){let K=N.element,{dispatchDragEventsOnClosestDraggable:X}=B;if(m.includes(C.type)&&X){if(!K&&N.lastDraggedElement)return N.lastDraggedElement;let ee=g(K);if(ee)return N.lastDraggedElement=ee,ee}return K}function h(C,N,B){function K(At,Mr,P){return P>At&&P<Mr}let X=C.pointerPosition||{};if(N)return{x:X.originX||0,y:X.originY||0};let ee=B.getBoundingClientRect(),fe=X.originX&&K(ee.left,ee.left+ee.width,X.originX)?X.originX:ee.left+ee.width/2,dr=X.originY&&K(ee.top,ee.top+ee.height,X.originY)?X.originY:ee.top+ee.height/2;return{x:fe,y:dr}}function y(C,N,B){let K=(N==null?void 0:N.modifiers)||{},X=h(C,B.isDrag,B.element),ee=(N==null?void 0:N.button)||0,fe=C.event;return d.includes(fe)?S(fe,K,X.x,X.y,ee):p.includes(fe)?v(fe,K,X.x,X.y):b(fe,K,X.x,X.y,ee)}function w(C,N,B){return{screenX:0,screenY:0,clientX:N,clientY:B,ctrlKey:Boolean(C.ctrl),altKey:Boolean(C.alt),shiftKey:Boolean(C.shift),metaKey:Boolean(C.meta),bubbles:!0,cancelable:!0,composed:!0}}function S(C,N,B,K,X){if(n){let fe=w(N,B,K);return fe.pointerType="mouse",fe.isPrimary=!0,new window.PointerEvent(C,fe)}let ee=document.createEvent("PointerEvent");return ee.initPointerEvent(C,!0,!0,document.defaultView,1,0,0,B,K,Boolean(N.ctrl),Boolean(N.alt),Boolean(N.shift),Boolean(N.meta),X,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),ee}function b(C,N,B,K,X){let ee=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return ee.initMouseEvent(C,!0,!0,document.defaultView,1,0,0,B,K,Boolean(N.ctrl),Boolean(N.alt),Boolean(N.shift),Boolean(N.meta),X,document.body?document.body.parentNode:document.documentElement),ee}function v(C,N,B,K){if(C==="dragstart"&&(window.TSTA||(window.TSTA={}),window.TSTA.dataTransfer=l()),!s){let fe=document.createEvent("CustomEvent");return fe.initCustomEvent(C,!0,!0,null),Object.assign(fe,{dataTransfer:window.TSTA.dataTransfer}),fe}let X=w(N,B,K),ee=new window.DragEvent(C,X);return Object.defineProperties(ee,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),ee}function I(C,N,B){let K=f(C,N,B);K==null||K.dispatchEvent(C)}function A(C,N){function B(){return C.event==="click"&&N.isDrag&&!N.allEventsOnSameElement}return B()}function _(C,N,B){if(B){let K=Math.min(B.timeStamp-N.timeStamp,40);setTimeout(()=>{R(C)},K)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),i()}function R(C){let N,B=C.events[C.eventIndex],K=C.events[++C.eventIndex];try{C.element=getLocatedElement(B.locatedElement),N=y(B,r,C)}catch(X){return a(`exception in get event in drag step:${X.message}`)}if(A(B,C))return _(C,B,K);if(N)try{I(N,C,B)}catch(X){return a(`exception in executeEvent in drag step:${X.message}`)}else return a(`cannot execute event ${B.event}`);_(C,B,K)}let L={eventIndex:0,allEventsOnSameElement:r.allEventsOnSameElement,events:r.events,eventType:r.eventType,eventData:r.eventData,stepId:r.id,testResultId:r.testResultId,isDrag:r.isDrag,useRecordedMousedown:r.useRecordedMousedown,trackActiveElement:r.trackActiveElement};setTimeout(()=>{try{R(L)}catch(C){a(C)}},0)}});var vh={};$(vh,{doClick:()=>gS});var gS,Eh=T(()=>{"use strict";gS=(r,e)=>{let t=typeof Event=="function";window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function s(b,v){var _;function I(R){function L(){return o(R).find(B=>[...B.classList||[]].includes("Select-control"))}function C(){let B=L();return B?B.querySelector("input"):null}let N=C();N==null||N.focus()}let A=(_=b.quirks)==null?void 0:_.isReactSelect;v.type==="mousedown"&&A&&I(b.element)}function n(b,v){var A;let I=(A=b.quirks)==null?void 0:A.isCKEditorFrame;v.type==="click"&&I&&document.body.focus()}function o(b){return b?[b].concat(o(b.parentNode)):[]}function i(b){let v={status:"done",result:b,success:!0,...S.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(v)}function a(b){b||(b=""),e({status:"failed",result:b,success:!1})}function c(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function l(b){let v={},I=b.getBoundingClientRect(),A=I.left+I.width/2,_=I.top+I.height/2,C=g("mousemove",v,A,_,0);b.dispatchEvent(C)}function m(b,v){function I(C,N,B){return B>C&&B<N}let A=b.pointerPosition||{},_=v.getBoundingClientRect(),R=A.originX&&I(_.left,_.left+_.width,A.originX)?A.originX:_.left+_.width/2,L=A.originY&&I(_.top,_.top+_.height,A.originY)?A.originY:_.top+_.height/2;return{x:R,y:L}}function d(b,v,I){return{screenX:0,screenY:0,clientX:v,clientY:I,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function p(b,v,I,A){if(!window.PointerEvent)return;let _=d(v,I,A);return _.pointerType="mouse",_.isPrimary=!0,new window.PointerEvent(b,_)}function g(b,v,I,A,_){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,I,A,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement),R}function f(b,v){let I=["pointerup","pointerdown","pointermove"],A=v.modifiers||{},_=m(b,v.element),R=v.button||0,L=b.event;return I.includes(L)?p(L,A,_.x,_.y):g(L,A,_.x,_.y,R)}function h(){var v;let b=document.activeElement;for(;(v=b.shadowRoot)!=null&&v.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(v=>{try{return f(v,b)}catch{return}}).filter(Boolean).forEach(v=>{b.element.dispatchEvent(v),s(b,v),n(b,v)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let S={element:r.isRoot?document.documentElement:getLocatedElement(r.locatedElement),events:r.events,quirks:r.quirks,modifiers:r.modifiers,button:r.button};if(!S.element){a("element not found");return}c(S.element),l(S.element);try{y(S);let b=h(),v=S.quirks,I=v==null?void 0:v.isReactSelect,A=v==null?void 0:v.isCKEditorFrame;!I&&!A&&dispatchFocus(r.elementToFocusLocatedElement,b),i()}catch(b){a(b.toString())}}});var Sh={};$(Sh,{doDragPath:()=>hS});var hS,Rh=T(()=>{"use strict";hS=function(r,e){let t=typeof Event=="function",s=typeof PointerEvent=="function",n=40;window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(b){e({status:"done",result:b,success:!0})}function i(b){b||(b=""),e({status:"failed",result:b,success:!1})}function a(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function c(b){let v={},I=b.getBoundingClientRect(),A=I.left+I.width/2,_=I.top+I.height/2,C=p("mousemove",v,A,_,0);b.dispatchEvent(C)}function l(b,v){function I(C,N,B){return B>C&&B<N}let A=b.pointerPosition||{};if(S.isDrag)return{x:A.originX||0,y:A.originY||0};let _=v.getBoundingClientRect(),R=A.originX&&I(_.left,_.left+_.width,A.originX)?A.originX:_.left+_.width/2,L=A.originY&&I(_.top,_.top+_.height,A.originY)?A.originY:_.top+_.height/2;return{x:R,y:L}}function m(b,v,I){return{screenX:0,screenY:0,clientX:v,clientY:I,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function d(b,v,I,A,_){if(s){let L=m(v,I,A);return L.pointerType="mouse",L.isPrimary=!0,new window.PointerEvent(b,L)}let R=document.createEvent("PointerEvent");return R.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,I,A,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),R}function p(b,v,I,A,_){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,I,A,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement),R}function g(b,v){let I=["pointerup","pointerdown","pointermove"],A=v.modifiers||{},_=l(b,v.element),R=v.button||0,L=b.event;return I.includes(L)?d(L,A,_.x,_.y,R):p(L,A,_.x,_.y,R)}function f(b,v){function I(){return b.event==="click"&&v.isDrag&&!v.allEventsOnSameElement}return I()}function h(b,v,I){try{let A=g(v.events[b],v);f(A,v)||v.element.dispatchEvent(A)}catch{}if(b+1===v.events.length)I();else{let A=Math.min(v.events[b+1].timeStamp-v.events[b].timeStamp,n);setTimeout(()=>{h(b+1,v,I)},A)}}function y(b,v){h(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v()})}let S={eventIndex:0,element:r.isRoot?document.documentElement:getLocatedElement(r.locatedElement),events:r.events,eventType:r.eventType,eventData:r.eventData,stepId:r.id,testResultId:r.testResultId,quirks:r.quirks,isDoubleClick:r.isDoubleClick,isDrag:r.isDrag,useRecordedMousedown:r.useRecordedMousedown,trackActiveElement:r.trackActiveElement,allEventsOnSameElement:r.allEventsOnSameElement};if(!S.element){i("element not found");return}a(S.element),c(S.element),y(S,()=>{o()})}});var Pn,Di,Ih=T(()=>{"use strict";Pn=E(require("lodash"));ue();bh();Te();wh();Di=class extends H{getDnDRectsAndOffsets(e,t,s,n){let o=this.stepActionUtils.getClickOffset(s,e.rectWithoutFrameOffset),i=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:o.xOffset,fromY:o.yOffset,toRect:t.rectWithoutFrameOffset,toX:i.xOffset,toY:i.yOffset}}async clickJs(){var m;let{step:e,context:t}=this,s=this.getTarget(),n=t.data.timeToPlayStep+3e3,o=e.events;if(!(o!=null&&o.length))return{success:!1,reason:"Malformed step: missing recorded events"};let i={isRoot:s.isRoot,locatedElement:s.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(Eh(),vh)),Promise.resolve().then(()=>(Rn(),Sn))]),l=`
|
|
229
229
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
230
230
|
var dispatchFocus = ${c.toString()};
|
|
231
231
|
var doClick = ${a.toString()};
|
|
232
232
|
var eventData = arguments[0];
|
|
233
233
|
var done = arguments[1];
|
|
234
234
|
return doClick.call(null, eventData, done);
|
|
235
|
-
`;try{return(
|
|
235
|
+
`;try{return(m=(await this.driver.executeCodeAsync(l,n,i)).value)!=null&&m.success?{success:!0}:{success:!1}}catch(d){return{success:!1,reason:d.message,exception:d}}}isWithinBounds(e,t,s){return s>e&&s<t}getEventSequenceOffset(){var c;let e=(c=this.step.events[0])==null?void 0:c.pointerPosition;if(!e)return{xOffset:0,yOffset:0};let s=this.getTarget().rectWithoutFrameOffset,n=this.isWithinBounds(s.left,s.left+s.width,e.originX),o=this.isWithinBounds(s.top,s.top+s.height,e.originY),i=n?0:s.left+s.width/2-e.originX,a=o?0:s.top+s.height/2-e.originY;return{xOffset:i,yOffset:a}}addOffsetToEvents(e){this.step.events.forEach(t=>{t!=null&&t.pointerPosition&&(t.pointerPosition.originX+=e.xOffset,t.pointerPosition.originY+=e.yOffset)})}generateEventOfType(e,t){let s=Pn.cloneDeep(e);return s.event=t,s}fixAbsoluteDragEventSequence(){let{events:e=[],allEventsOnSameElement:t,isHTML5Drag:s,toElement:n}=this.step,o=e.find(l=>["mousedown","pointerdown"].includes(l.event));if(o){let l=e.indexOf(o);e.splice(l,0,this.generateEventOfType(o,"mouseover"))}let{recordPointerMoveEvents:i=!1}=this.context.project.defaults||{},a=e.find(l=>l.event==="mouseup")||i&&e.find(l=>l.event==="pointerup"),c=Number(Pn.findLastIndex(e,l=>l.event==="mousemove")||i&&Pn.findLastIndex(e,l=>l.event==="pointermove"));a&&c>0&&!t&&e.splice(c+1,0,this.generateEventOfType(a,"mouseover")),s&&!n&&(this.step.events=this.addDragendIfNeeded(e)),this.addOffsetToEvents(this.getEventSequenceOffset())}async dragPathJs(){var m,d;let{step:e,context:t}=this,s=this.getTarget(),n=t.data.timeToPlayStep+3e3;if(!((m=e.events)!=null&&m.length))return{success:!1,reason:"Malformed step: missing recorded events"};this.fixAbsoluteDragEventSequence();let o=e.events,i={isRoot:s.isRoot,locatedElement:s.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button,isDrag:!0,allEventsOnSameElement:e.allEventsOnSameElement},[{doDragPath:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(Rh(),Sh)),Promise.resolve().then(()=>(Rn(),Sn))]),l=`
|
|
236
236
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
237
237
|
var dispatchFocus = ${c.toString()};
|
|
238
238
|
var doDragPath = ${a.toString()};
|
|
239
239
|
return doDragPath.apply(null, arguments);
|
|
240
|
-
`;try{return(
|
|
240
|
+
`;try{return(d=(await this.driver.executeCodeAsync(l,n,i)).value)!=null&&d.success?{success:!0}:{success:!1}}catch(p){return{success:!1,reason:p.message,exception:p}}}async chooseAndRunAction(){let e=this.getTarget(),{locatedElement:t,seleniumElement:s,rectWithoutFrameOffset:n,rect:o}=e,{xOffset:i,yOffset:a}=this.stepActionUtils.getClickOffset(this.step.element.clickOffset,n),c={frameOffset:{x:o.left-n.left,y:o.top-n.top},rect:n,clickOffset:{x:i,y:a}};if(M.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 p={elementToFocusLocatedElement:e.elementToFocusLocatedElement,locatedElement:t,events:this.step.events,timeout:this.context.data.timeToPlayStep+3e3};return this.driver.doubleClick(s,p,c)}if(this.step.isDrag){if(this.step.toElement){let p=this.context.data.toElement;if(this.step.isHTML5Drag){if(M.flags.usePortedHtml5DragDrop.isEnabled()){let y=this.generateHTML5DragEventSequence(),w=this.context.data.timeToPlayStep+3e3,S=this.getTarget(),b={transactionId:`${this.context.testResultId}:${this.step.id}`,id:this.step.id,testResultId:this.context.testResultId,eventType:this.step.type,events:y,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:S.elementToFocusLocatedElement,trackActiveElement:this.step.trackActiveElement,locatedElement:S.locatedElement,isRoot:S.isRoot},v=`
|
|
241
241
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
242
|
-
var dnd = ${
|
|
242
|
+
var dnd = ${Th.toString()};
|
|
243
243
|
var eventData = arguments[0];
|
|
244
244
|
var done = arguments[1];
|
|
245
245
|
return dnd.call(null, eventData, done);
|
|
246
246
|
`;return this.driver.executeCodeAsync(v,w,b)}let f=`
|
|
247
247
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
248
|
-
var dnd = ${
|
|
248
|
+
var dnd = ${yh.toString()};
|
|
249
249
|
var eventData = arguments[0];
|
|
250
250
|
return dnd.call(null, eventData);
|
|
251
|
-
`,h={fromLocatedElement:t,toLocatedElement:
|
|
251
|
+
`,h={fromLocatedElement:t,toLocatedElement:p.locatedElement};return this.driver.executeJS(f,h)}let g=this.getDnDRectsAndOffsets(e,p,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(s,p.seleniumElement,g)}return this.dragPathJs()}let m=this.driver.isSafari()&&this.step.button===2,d=this.driver.isSafari()&&e.tagName==="SELECT";return d?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!d&&(!this.step.nativeEvents||m)?this.clickJs():this.step.button===2?this.driver.rightClick(s,c):this.driver.leftClick(s,c)}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(s=>s.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,s;if(!((s=(t=this.context.data)==null?void 0:t.toElement)!=null&&s.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)),s=e[t-1];if(!s||s.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else Object.assign(s,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,s){let n=o=>o.fireOnTarget||["drop","dragenter"].includes(o.event);return e.forEach(o=>Object.assign(o,{locatedElement:n(o)?s:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,s=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return s=this.fixEventSequence(s),s=this.addElementLocatedElementToDragEvents(s,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&s.forEach(n=>Object.assign(n,{dispatchDragEventsOnClosestDraggable:!0})),s}}});var Cn,xh=T(()=>{"use strict";ue();Cn=class extends H{async performAction(){let{step:e,context:t,sessionPlayerInit:{stepParamExpressionEvaluator:s,utils:n,commonConstants:o}}=this,i=this.getTarget();try{let a=await this.stepActionUtils.extractTargetText(i),{evaluatedText:c}=s.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return n.compareOrMatch(c,a)?{success:!0}:{success:!1,errorType:o.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(c),actual:a}}}catch{return{success:!1,errorType:o.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:c.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var kh,yS,Ni,Ph=T(()=>{"use strict";kh=E(require("lodash"));ue();U();yS=x("evaluate-expression-step-action"),Ni=class extends H{async execute(){let{step:e,context:t,exportsGlobal:s,exportsTest:n}=this;try{yS.info("runner running incoming params evaluation");let o=t.incomingParams||{};kh.isEmpty(o)&&(o=this.sessionPlayerInit.stepParamBuilder.getStepInputs(e,t,s,n));let i=["context",...o.as.functionParameters],a=[t,...o.as.functionArguments],l=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),d=Function.apply(Function,i.concat([l]))(...a);return t.data[e.targetName]=d,t.data[e.targetId]=d,t.internalParams&&t.internalParams.add(e.targetId),{success:!0,evaluatedText:d,data:t.data}}catch(o){let{stepResult:i}=this.sessionPlayerInit.commonConstants;throw{errorType:i.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:o.toString()},success:!1}}}}});var Ch={};$(Ch,{setText:()=>bS});var bS,Ah=T(()=>{"use strict";bS=function(r,e){let t=typeof Event=="function",s=r.isRoot?document.documentElement:getLocatedElement(r.locatedElement),n={eventIndex:0,element:s,events:r.events,eventType:r.eventType,quirks:r.quirks};if(!s)throw new Error("element not found");window.__unloadNavigator=function(){dr()},window.addEventListener("unload",window.__unloadNavigator);let o=new Set(["keydown","keyup","keypress"]),i=15;function a(P){try{if(!t)return;let D=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return P.eventData&&(D.data=P.eventData.data),D}catch{}}function c(P){try{let D=document.createEvent("TextEvent");D.data=P.eventData.data;let F=1,G=P.eventData.locale||"en-US";return D.initTextEvent("textInput",!0,!0,window,P.eventData.data,F,G),D}catch{}}function l(P){return a(P)||c(P)}function m(P,D,F){try{return new KeyboardEvent(P,{bubbles:!0,cancelable:!0,location:D.location||0,key:D.key||"",ctrlKey:Boolean(F.ctrl),shiftKey:Boolean(F.shift),altKey:Boolean(F.alt),metaKey:Boolean(F.meta)})}catch{}}function d(P,D,F){try{let G=document.createEvent("KeyboardEvent");return G.initKeyEvent(P,!0,!0,null,Boolean(F.ctrl),Boolean(F.alt),Boolean(F.shift),Boolean(F.meta),D.key||"",0),G}catch{}}function p(P,D,F){try{let G=document.createEvent("Events");return G.initEvent(P,!0,!0),Object.assign(G,{altKey:Boolean(F.alt),ctrlKey:Boolean(F.ctrl),metaKey:Boolean(F.meta),shiftKey:Boolean(F.shift),keyCode:D.key||""}),G}catch{}}function g(P,D,F){return m(P,D,F)||d(P,D,F)||p(P,D,F)}function f(P){if(!o.has(P.event))return null;let D=P.eventData,F=D.modifiers||{},G=g(P.event,D,F);return Object.defineProperties(G,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(G,{_keyCode_:D.keyCode,_charCode_:D.charCode||0}),G}function h(P){return P.event==="textInput"?l(P):f(P)}function y(P,D){return(()=>{var G;return P.event==="textInput"&&!((G=D.quirks)!=null&&G.isAuth0Form)})()}function w(P,D){return P.event==="keyup"&&D.event==="keydown"?i:0}function S(P,D){let F=w(P,D);return Math.min(D.timeStamp-P.timeStamp,F)}function b(P){let D=Object.getOwnPropertyDescriptor(P,"value");if(!D)return;let F=P.value;P.value=`${F}#`,D.configurable&&delete P.value,P.value=F;let G=document.createEvent("HTMLEvents");G.initEvent("input",!0,!1),P.dispatchEvent(G),Object.defineProperty(P,"value",D)}function v(P){if(K(P.element))try{if(b(P.element),t)P.element.dispatchEvent(new Event("change"));else{let D=document.createEvent("HTMLEvents");D.initEvent("change",!1,!0),P.element.dispatchEvent(D)}}catch{}}function I(P,D,F){F?setTimeout(()=>{B(P)},S(D,F)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v(P),dr())}function A(P,D){return(P==="change"||P==="blur")&&D.element.tagName==="OPTION"}function _(P,D,F){return A(P.type,D)?D.element.parentElement:F.locatedElement?getLocatedElement(F.locatedElement):D.element}function R(P,D){let F=P.firstChild,G;for(;F;){if(F.nodeType===3){if(D.offset--<=0)return F}else if(F.nodeType===1&&(G=R(F,D),G))return G;F=F.nextSibling}return null}function L(P,D){if(!(!P||!D)){if(!isNaN(D.start))Object.assign(P,{selectionStart:D.start,selectionEnd:D.end});else if(!isNaN(D.nodeOffset)){let F;if(P.firstChild?F=R(P,{offset:D.nodeOffset}):F=P,F){let G=window.getSelection(),ge=document.createRange();try{G.removeAllRanges(),ge.setStart(F,D.textOffset),ge.setEnd(F,D.textOffset),G.addRange(ge)}catch{}}}}}function C(P,D){return P==="submit"&&Boolean(D.action)}function N(P,D,F){if(D.isFocusable&&D.isSelectable(P)&&P.type!=="submit")try{L(D.element,F.eventData.selection)}catch{}let G=_(P,D,F);if(!G)throw new Error("could not find element");C(P.type,G)?G.submit():G.dispatchEvent(P)}function B(P){let D,F=P.events[P.eventIndex],G=P.events[++P.eventIndex];try{D=h(F)}catch(ge){return At(`exception in get event in text step:${ge.message}`)}if(y(F,P))return I(P,F,G);if(D)try{N(D,P,F)}catch(ge){return At(`exception in executeEvent in text step:${ge.message}`)}else if(P.noEventExecuter)P.noEventExecuter(P,F);else return At(`cannot execute event ${F.event}`);I(P,F,G)}function K(P){let D=P.tagName;return D==="INPUT"||D==="TEXTAREA"}function X(P){return P.getAttribute?Boolean(P.getAttribute("contenteditable")==="true"):!1}function ee(P,D){if(K(P.element)){P.element.value=D.eventData.text;let F=document.createEvent("Event");F.initEvent("input",!0,!1),P.element.dispatchEvent(F)}else P.isContentEditable&&(P.element.innerHTML=D.eventData.text)}function fe(){var D;let P=document.activeElement;for(;(D=P.shadowRoot)!=null&&D.activeElement;)P=P.shadowRoot.activeElement;return P}function dr(P){let D={status:"done",result:P,success:!0,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(D)}function At(P){P||(P="");let D={status:"failed",result:P,success:!1,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(D)}try{let P=K(n.element);n.isContentEditable=X(n.element),!P&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=P||n.isContentEditable,n.isSelectable=D=>D.type!=="keyup",n.noEventExecuter=ee}catch(P){At(`exception in set text step:${P.message}`);return}let Mr=fe();dispatchFocus(r.elementToFocusLocatedElement,Mr),B(n)}});var Mi,Oh=T(()=>{"use strict";ue();j();Mi=class extends H{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(Me(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var f;let{step:{events:e,type:t,quirks:s},context:n,sessionPlayerInit:o}=this,i=this.getTarget(),a=n.data.timeToPlayStep+3e3,{setTextDraftJs:c}=o.codeSnippets;if(i.isDraftEditor&&c)return this.driver.executeJS(c(i.locatedElement,n.stepText));if(!(e!=null&&e.length))return;let l={eventType:t,events:e,quirks:s,locatedElement:i.locatedElement,isRoot:i.isRoot,elementToFocusLocatedElement:i.elementToFocusLocatedElement},[{setText:m},{dispatchFocus:d}]=await Promise.all([Promise.resolve().then(()=>(Ah(),Ch)),Promise.resolve().then(()=>(Rn(),Sn))]),p=`
|
|
252
252
|
var getLocatedElement = ${o.codeSnippets.getLocatedElementCode};
|
|
253
|
-
var dispatchFocus = ${
|
|
254
|
-
var setText = ${
|
|
253
|
+
var dispatchFocus = ${d};
|
|
254
|
+
var setText = ${m.toString()};
|
|
255
255
|
var eventData = arguments[0];
|
|
256
256
|
var done = arguments[1];
|
|
257
257
|
return setText.call(null, eventData, done);
|
|
258
|
-
`,g=await this.driver.executeCodeAsync(
|
|
258
|
+
`,g=await this.driver.executeCodeAsync(p,a,l);return{success:Boolean((f=g.value)==null?void 0:f.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let s=0;s<e.length;s++)await this.driver.elementIdValue(Me(t.seleniumElement),e[s]),s<e.length-1&&await se(this.step.delayBetweenChars||0)}async setValueAppendNative(){let e=[],t=this.context,s=this.getTarget();if(s!=null&&s.seleniumElement)return this.step.delayBetweenChars?this.setTextDelayed():(e.push(Array.from(t.stepText)),this.driver.elementIdValue(Me(s.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;if(this.step.appendText){if(this.step.nativeEvents)return this.setValueAppendNative();let{stepResult:s}=this.sessionPlayerInit.commonConstants;return{success:!1,errorType:s.TEXT_ACTION_FAILURE,resultInfo:{error:"'Append Text' is only supported in Native Mode"}}}return this.step.nativeEvents&&!t?this.setValueNative():this.setValueJS()}}});var _h={};$(_h,{runCode:()=>TS});var TS,Lh=T(()=>{"use strict";TS=function(r,e){var m;function t(d,p){let g=`data-testim-${d}`,f="Native sessionStorage is not available";function h(y){return y!=null&&y.toString?y.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(h))throw new Error(f);let y=JSON.parse(window.sessionStorage.getItem(g)||"{}"),w=Object.assign({},y,p);window.sessionStorage.setItem(g,JSON.stringify(w))}catch(y){let w=y.message.toLowerCase().includes("quota"),S=y.message===f;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||w||S){let b=document.head.querySelector("#testim-storage-backup");b||(b=document.createElement("meta"),b.id="testim-storage-backup",document.head.append(b));let v=JSON.parse(b.getAttribute(g)||"{}"),I=Object.assign({},v,p);if(b.setAttribute(g,JSON.stringify(I)),w||S){try{window.sessionStorage.removeItem(g)}catch{}(window.TSTA||(window.TSTA={})).useFallbackStorage=!0}return}throw y}}function s(d){return d.function?d.function.args.map(p=>p!=null&&p.locatedElement?getLocatedElement(p.locatedElement):p):d.directParams.map(p=>p.selector?document.querySelector(p.selector):p.value).concat(d.otherParams)}function n(d,p){function g(){return d.apply(null,p)}return g.prototype=d.prototype,new g}let o={},i={},a={},c=r.functionParams,l=r.transactionId;try{let d=s(r);d.push(o,i,a);let p=((m=r.function)==null?void 0:m.params)||c,f=(e||n(Function,p)).apply(null,d);typeof Promise<"u"&&f instanceof Promise?(t(l,{type:"promise"}),f.then(h=>{t(l,{status:"done",success:!0,result:{resultValue:h,exports:o,exportsTest:i,exportsGlobal:a}})},h=>{t(l,{status:"failed",success:!1,result:{resultValue:h.toString(),exports:o,exportsTest:i,exportsGlobal:a}})})):t(l,{status:"done",success:!0,result:{resultValue:f,exports:o,exportsTest:i,exportsGlobal:a}})}catch(d){t(l,{status:"failed",success:!1,result:{resultValue:d.toString(),exports:o,exportsTest:i,exportsGlobal:a}})}}});var Fi,Bu,or,Ui=T(()=>{"use strict";Fi=E(require("lodash"));j();ue();U();Te();Bu=x("base-js-step-action"),or=class extends H{isExceedingMaxResultSize(t,s){var n;try{let o=(n=s.project.defaults)==null?void 0:n.enforceMaximumJsResultSize,i=M.flags.maximumJsResultSize.getValue(),a=JSON.stringify(t).length>i;return o?a:(a&&Bu.warn(`js result size exceeded ${i}, stepId: ${this.step.id}`),!1)}catch{return!1}}executeGetStatus(t){return this.driver.executeJS(s=>{let n=`data-testim-${s}`;try{return window.sessionStorage.getItem(n)}catch(o){if(o.message.includes("sessionStorage")||o.message.includes("The operation is insecure")){let i=document.head.querySelector("#testim-storage-backup");return i?i.getAttribute(n):"{}"}throw o}},t)}constructJSFunParams(t){let s=t.incomingParams,n=["context",...s.as.functionParameters,"exports","exportsTest","exportsGlobal"],o=[t.context,...s.as.functionArguments];return n.push(t.code),o.forEach(i=>{Fi.isObject(i)&&co(i,"seleniumElement",Fi.isEqual)}),{function:{params:n,args:o},transactionId:t.transactionId,browser:t.browser,browserMajor:t.browserMajor}}checkStatus(t){let{context:s,stepActionUtils:n,step:{id:o=""}}=this,i=s.config.retryTimeout,a=s.data.timeToPlayStep-i,c=async()=>{let l;try{l=await this.executeGetStatus(t)}catch(p){Bu.warn("failed to get js status",{err:p}),l={value:'{ "status": "exception" }'}}let m;try{m=JSON.parse((l==null?void 0:l.value)||"{}")}catch{Bu.warn("non object value",{selRes:l}),m={status:"exception"}}let d=n.abortedSteps.find(p=>p.id===o);return d||(m?m.status==="done"?m:m.status==="failed"?{success:!1,shouldRetry:!0,result:m.result}:a-i<=0?Object.assign(m,{success:!1,shouldRetry:!0}):(a-=i,await se(i),c()):{success:!0})};return c()}async executeInAut(t){let s=M.flags.experimentalPreCodeCompilation.isEnabled(),n=M.flags.experimentalAsyncCustomCode.isEnabled(),o=this.constructJSFunParams(t),i=o.function.args.some(d=>Boolean(d==null?void 0:d.locatedElement)),a="undefined";if(s){let d=o.function.params.slice(0,-1);a=n?`async function(${d.join(",")}) {
|
|
259
259
|
${t.code}
|
|
260
|
-
};`:`function(${
|
|
260
|
+
};`:`function(${d.join(",")}) {
|
|
261
261
|
${t.code}
|
|
262
|
-
};`,o.function.params.pop()}let{codeSnippets:c}=this.sessionPlayerInit,{runCode:l}=await Promise.resolve().then(()=>(
|
|
262
|
+
};`,o.function.params.pop()}let{codeSnippets:c}=this.sessionPlayerInit,{runCode:l}=await Promise.resolve().then(()=>(Lh(),_h)),m=`
|
|
263
263
|
${i?`var getLocatedElement = ${c.getLocatedElementCode};`:";"}
|
|
264
264
|
var runCode = ${l.toString()};
|
|
265
265
|
var eventData = arguments[0];
|
|
266
266
|
var funcToRun = ${a};
|
|
267
267
|
return runCode.call(null, eventData, funcToRun);
|
|
268
|
-
`;if(!s)return this.driver.executeJS(
|
|
268
|
+
`;if(!s)return this.driver.executeJS(m,o);try{return await this.driver.executeJS(m,o)}catch(d){return this.handleExecutionError(d)}}codeExecDone(t){let{stepResult:s}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:o={},tstConsoleLogs:i,nodeVersion:a,navigateToDifferentDomain:c}=t;o.exports&&(n.data.exports=o.exports);let l={nodeVersion:a,tstConsoleLogs:i,data:n.data};return this.isFailedResult(o.resultValue)?Object.assign(l,{success:!1,errorType:s.JS_ASSERTION_FAILED}):this.isExceedingMaxResultSize({result:o,tstConsoleLogs:i},n)?Object.assign(l,{success:!1,errorType:s.JS_RESULT_MAX_SIZE_EXCEEDED}):Object.assign(l,{success:!0,exportsTest:o.exportsTest,exportsGlobal:o.exportsGlobal,...c&&{navigateToDifferentDomain:c}}),l}codeExecFailed(t){let{stepResult:s}=this.sessionPlayerInit.commonConstants,{context:n}=this;if(t.type==="promise")return{data:n.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:s.JS_ASSERTION_FAILED};if(t.reason==="stopped")return Object.assign({},t,{errorType:s.STOPPED});let{result:o={},tstConsoleLogs:i}=t;return{tstConsoleLogs:i,data:n.data,exportsGlobal:o.exportsGlobal,exportsTest:o.exportsTest,success:!1,errorType:s.UNWRAPPED_AUT_REJECT,resultInfo:{error:o.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}async performAction(){let{step:t,context:s}=this;this.startTimestamp=Date.now();let n=await this.driver.getBrowserAndOS(),o={transactionId:`${s.testResultId}:${t.id}`,id:t.id,eventType:t.type,code:t.code,incomingParams:s.incomingParams,exportsGlobal:this.exportsGlobal,exportsTest:this.exportsTest,context:{config:s.config,data:s.data},testResultId:s.testResultId,browser:n.browser,browserMajor:n.browserMajor};s.isPendingPromise||await this.executeInAut(o);let i=await this.checkStatus(o.transactionId);return this.checkCodeResponse(i)}handleExecutionError(t){throw(t==null?void 0:t.name)==="javascript error"?new Error(t.message):t}}});var $t,Dh=T(()=>{"use strict";Ui();$t=class extends or{isFailedResult(e){return e===!1}}});var Rs,Nh=T(()=>{"use strict";Ui();Rs=class extends or{isFailedResult(e){return!e}}});var wS,ji,Mh=T(()=>{"use strict";ue();j();wS={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"},ji=class extends H{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(Me(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(wS[t]),this.setWithValueApi(e)}}});var Fh={};$(Fh,{selectOption:()=>vS});function vS(r,e){function t(s,n){let o=Element.prototype.matches,i=o&&isNativeFunction(o)?o:document.createElement(s.tagName).__proto__.matches;do{if(i.call(s,n))return s;s=s.parentElement||s.parentNode}while(s!==null&&s.nodeType===1);return null}try{let s=getLocatedElement(r);if(!s)return{success:!1,status:"failed",result:"option element not found"};let n=t(s,"select");return n?(n.focus(),s.selected?{success:!0,status:"done"}:(s.selected=!0,["input","change"].map(i=>{let a=document.createEvent("HTMLEvents");return a.initEvent(i,!0,!1),a}).forEach(i=>{if(e){n.dispatchEvent(i);return}s.dispatchEvent(i)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(s){return{success:!1,status:"failed",result:s.toString()}}}var Uh=T(()=>{"use strict"});var Bi,jh=T(()=>{"use strict";ue();j();Te();Bi=class extends H{async performAction(){var p,g;let e=this.getTarget(),{seleniumElement:t,locatedElement:s}=e,o=(await this.driver.getBrowserAndOS()).browserMajor,i=this.driver.isSafari(),a=Boolean((p=this.step.element)==null?void 0:p.isShadowed);if(!i||i&&o>=13&&!a)try{return await this.driver.elementIdClick(Me(t))}catch(f){if(!f.message.includes("Cannot check the displayedness of a non-Element argument"))throw f}let{selectOption:c}=await Promise.resolve().then(()=>(Uh(),Fh)),l=M.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),m=`
|
|
269
269
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
270
270
|
const isNativeFunction = ${this.sessionPlayerInit.utils.isNativeFunction.toString()};
|
|
271
271
|
const selectOption = ${c.toString()};
|
|
272
272
|
return selectOption.apply(null, arguments);
|
|
273
|
-
`;return(g=(await this.driver.executeJS(
|
|
273
|
+
`;return(g=(await this.driver.executeJS(m,s,l)).value)!=null&&g.success?{success:!0}:{success:!1}}}});var $i,Bh=T(()=>{"use strict";ue();$i=class extends H{async performAction(){await this.driver.submit(this.getTarget().seleniumElement)}}});var ES,Wi,$h=T(()=>{"use strict";ue();ES=(r,e,t,s)=>({x:t,y:s,width:e,height:r,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(){}}),Wi=class extends H{getRect(){return this.driver.isFirefox()?this.getTarget().rectWithoutFrameOffset:this.getTarget().rect}async performAction(){let e=this.getTarget(),{seleniumElement:t,rectWithoutFrameOffset:s,rect:n}=e,{width:o,height:i}=n,a=o/2,c=i/2,l=this.step.element.clickOffset;if(l&&this.step.shouldAccountForMouseOffsetInHover){let{x:d,y:p}=l;this.sessionPlayerInit.utils.isWithinTargetRect(ES(i,o,0,0),d,p)&&(a=d,c=p)}let m={frameOffset:{x:n.left-s.left,y:n.top-s.top},rect:s,clickOffset:{x:Math.floor(a),y:Math.floor(c)}};return await this.driver.hover(t,m),{success:!0}}}});var Wh={};$(Wh,{wheel:()=>SS});var SS,Hh=T(()=>{"use strict";SS=function(r,e){function s(a,c){function l(f,h,y){return y>f&&y<h}let m=a.pointerPosition||{},d=c.getBoundingClientRect(),p=m.originX&&l(d.left,d.left+d.width,m.originX)?m.originX:d.left+d.width/2,g=m.originY&&l(d.top,d.top+d.height,m.originY)?m.originY:d.top+d.height/2;return{x:p,y:g}}function n(a,c,l){let m=s(a,l),d=(c==null?void 0:c.modifiers)||{},p={deltaX:a.deltaX,deltaY:a.deltaY,deltaZ:a.deltaZ,deltaMode:a.deltaMode,clientX:m.x,clientY:m.y,bubbles:!0,cancelable:!0,ctrl:Boolean(d.ctrl),alt:Boolean(d.alt),shift:Boolean(d.shift),meta:Boolean(d.meta)};return new WheelEvent("wheel",p)}function o(a,c){if(a.length===0){e({state:"success"});return}if(!c)throw new Error("element not found");let l=a.shift(),m=n(l,r.eventData,c),d=a[0]?Math.min(a[0].timeStamp-l.timeStamp,200):200;c.dispatchEvent(m),setTimeout(()=>{o(a,c)},d)}let i=getLocatedElement(r.locatedElement);o(r.events,i)}});var Hi,Gh=T(()=>{"use strict";ue();Hi=class extends H{async performAction(){var d;let{step:e,context:t}=this,{events:s,modifiers:n,button:o}=e;if(!(s!=null&&s.length))return;let i={events:s,eventData:{modifiers:n,button:o},locatedElement:this.getTarget().locatedElement},a=t.data.timeToPlayStep+3e3,{wheel:c}=await Promise.resolve().then(()=>(Hh(),Wh)),l=`
|
|
274
274
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
275
275
|
var wheel = ${c.toString()};
|
|
276
276
|
var eventData = arguments[0];
|
|
277
277
|
var done = arguments[1];
|
|
278
278
|
return wheel.call(null, eventData, done);
|
|
279
|
-
`;return{success:((
|
|
279
|
+
`;return{success:((d=(await this.driver.executeCodeAsync(l,a,i)).value)==null?void 0:d.state)==="success"}}}});var Vh={};$(Vh,{downloadFileAndFireDropEvent:()=>RS});var RS,qh=T(()=>{"use strict";RS=function(r,e){let t=getLocatedElement(r);if(!t)throw new Error("element not found");function s(){let i=-1,a=0,c=[],l={endWithCallback:void 0,waitOn(){let m=++i;return function(d){m in c||(c[m]=d,a++,e.length===a&&l.endWithCallback(c))}},endWith(m){l.endWithCallback=m}};return l}function n(i,a,c){let l=new XMLHttpRequest;l.open("GET",i),l.responseType="blob",l.onload=function(){if(this.status>=200&&this.status<300)c({blob:l.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},l.onerror=function(){throw new Error("Failed to load blob")},l.send()}let o=s();e.forEach(i=>{n(i.url,i.name,o.waitOn())}),o.endWith(i=>{let a=createDropEvent(i);t.dispatchEvent(a)})}});var IS,Gi,zh=T(()=>{"use strict";ue();U();Te();IS=x("drop-file-step-action"),Gi=class extends H{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:s,step:n}=this,o=this.getTarget(),i=M.flags.overrideAzureStorageUrl.isEnabled(),a=await t.addTokenToFileUrl(s.project.id,n.fileUrls,this.stepActionUtils.testimServicesApi,i,IS),{downloadFileAndFireDropEvent:c}=await Promise.resolve().then(()=>(qh(),Vh)),l=`
|
|
280
280
|
const getLocatedElement = ${e.getLocatedElementCode};
|
|
281
281
|
const createDropEvent = ${e.createDropEvent.toString()};
|
|
282
282
|
const downloadFileAndFireDropEvent = ${c.toString()};
|
|
283
283
|
return downloadFileAndFireDropEvent.apply(null, arguments)
|
|
284
|
-
`;return await this.driver.executeJS(l,o.locatedElement,a)}}});function
|
|
284
|
+
`;return await this.driver.executeJS(l,o.locatedElement,a)}}});function Yh(r={width:"2px",height:"2px",left:"0px",top:"400px"}){return`function getVisibleElement(locatedElement) {
|
|
285
285
|
var input = getLocatedElement(locatedElement);
|
|
286
286
|
if(input) {
|
|
287
287
|
function parents(element, _elements) {
|
|
@@ -323,7 +323,7 @@ ${((S=n.warnings)==null?void 0:S.join(`
|
|
|
323
323
|
input.removeAttribute("disabled");
|
|
324
324
|
input.focus();
|
|
325
325
|
}
|
|
326
|
-
}`}async function
|
|
326
|
+
}`}async function kS(r,e){let t=null;try{t=(await ic(r)).body}catch(n){if(xS.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 s=`${Kh.tmpdir()}/${e}`;return await Jh.promises.writeFile(s,t),s}function PS(r){return ce(r,e=>kS(e.url,e.name))}function CS(r,e){return e(r)}async function Xh(r,e){let t=await PS(r),s=await ce(t,n=>CS(n,e));return Array.isArray(s)&&s.map(n=>n==null?void 0:n.value)}var Kh,Jh,xS,Qh=T(()=>{"use strict";Kh=E(require("os"));at();Jh=require("fs");j();U();xS=x("input-file-utils")});function OS(){return`async function downloadAndUpload(locatedElement, fileUrls) {
|
|
327
327
|
const fileIsNative = typeof window.File === 'function' && (window.File.toString().indexOf('native code') > -1);
|
|
328
328
|
const File = fileIsNative ? window.File : (function obtainSafeGlobals() {
|
|
329
329
|
const attachTo = document.body || document.documentElement;
|
|
@@ -400,23 +400,23 @@ ${((S=n.warnings)==null?void 0:S.join(`
|
|
|
400
400
|
element.dispatchEvent(new Event("change", { bubbles: true }));
|
|
401
401
|
}
|
|
402
402
|
element.removeEventListener("change", changeFiredHandler, true);
|
|
403
|
-
}`}var Vi,qi,
|
|
403
|
+
}`}var Vi,qi,Zh=T(()=>{"use strict";Qh();ue();U();j();Te();Vi=x("input-file-step-action"),qi=class extends H{constructor(){super(...arguments);this.uploadFile=t=>this.driver.uploadFile(t)}forceInputToBeVisible(t,s){Vi.info("workaround - stepaction - move element to visible position");let n=`
|
|
404
404
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
405
|
-
var getVisibleElement = ${
|
|
405
|
+
var getVisibleElement = ${Yh(s)};
|
|
406
406
|
return getVisibleElement.apply(null, arguments);
|
|
407
|
-
`;return this.driver.executeJS(n,t.locatedElement)}async safariPreUploadActions(t){let s={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,s)}catch(n){throw Vi.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,s){try{this.driver.isSafari()&&await this.safariPreUploadActions(s),await this.uploadFiles(t,s)}catch(n){let o="The element is not editable",i="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",c="element not interactable",l="element is not pointer- or keyboard interactable",
|
|
407
|
+
`;return this.driver.executeJS(n,t.locatedElement)}async safariPreUploadActions(t){let s={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,s)}catch(n){throw Vi.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,s){try{this.driver.isSafari()&&await this.safariPreUploadActions(s),await this.uploadFiles(t,s)}catch(n){let o="The element is not editable",i="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",c="element not interactable",l="element is not pointer- or keyboard interactable",m="invalid element state: Element is not currently interactable and may not be manipulated",d="Element must not be hidden, disabled or read-only",p="is not reachable by keyboard",g=n?n.message:"";if(g===m||g.startsWith(d)||g.startsWith(o)||g.startsWith(i)||g.startsWith(a)||g.includes(p)||g.includes(c)||g.includes(l)){await this.forceInputToBeVisible(s),await this.uploadFiles(t,s);return}throw Vi.error("failed to set input file",{err:n}),n}}async uploadFiles(t,s){for(let n of t)await this.driver.elementIdValue(Me(s.seleniumElement),n)}async performAction(){let t=this.getTarget(),s=M.flags.overrideAzureStorageUrl.isEnabled(),n=M.flags.useJsInputCodeInSafari.isEnabled(),o=M.flags.useJsInputCodeInFirefox.isEnabled(),i=M.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:a,context:c,step:l,stepActionUtils:m,driver:d}=this,p=await a.utils.addTokenToFileUrl(c.project.id,l.fileUrls,m.testimServicesApi,s,Vi),g=d.isSafari()&&(n||p.length>1),f=d.isFirefox()&&(o||p.length>1);if(i&&(p=await Promise.all(p.map(async({name:y,url:w})=>{let S=await hr(w);return{name:y,url:`data:${S.type};base64,${Buffer.from(S.body).toString("base64")}`}}))),g||f){await this.driver.executeJS(`
|
|
408
408
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
409
|
-
const downloadAndUploadFile = ${
|
|
410
|
-
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let h=await Jh(d,this.uploadFile);await this.uploadFilesAndForceVisibility(h,t)}}});var zi,Ki,Qh=T(()=>{"use strict";zi=require("url");ue();Ki=class extends H{async updateBaseUrl(e){let t=new zi.URL(e),s=new zi.URL(this.context.recordedBaseUrl),n=new zi.URL(this.context.baseUrl);return t.host===s.host&&s.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var Ji,Zh=T(()=>{"use strict";ue();j();Ji=class extends H{async performAction(){await se(this.step.durationMS||0)}}});var Yi,ey=T(()=>{"use strict";ue();Yi=class extends H{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var An,ty=T(()=>{"use strict";ue();An=class extends H{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:s}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(s,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return new Promise(s=>{t(e,s)})}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:s}=this,n={id:t.id,url:s.apiUrl,method:t.method,headers:s.apiHeaders,body:s.apiBody,timeout:s.data.maxTotalStepTime,omitCookies:t.omitCookies,formData:t.formData,fileUrls:s.fileUrls},o=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),i=o.result||{},a={method:t.method,status:i.status,url:t.url};return o.success?i.status===0?{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:i,resultInfo:a,shouldRetry:!1,success:!0}:{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:i.error||e.error.REQUEST_TIMED_OUT,errorType:i.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Xi,ry=T(()=>{"use strict";ue();Xi=class extends H{async performAction(){var s;let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return(s=this.context.data).exports||(s.exports={}),this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var Qi,sy=T(()=>{"use strict";ue();Zi();Qi=class extends H{async performAction(){return await Is(this.step,this.context,this.driver,this.stepActionUtils.testimServicesApi.authenticationManager.getLoggedUserInfo(),this.frameHandler.frameManager)}}});var ny,oy,Bu,$u,iy=T(()=>{"use strict";ny=E(require("@applitools/spec-driver-webdriverio")),oy=require("@applitools/eyes-sdk-core");Yn();Ee();Bu=class{constructor(){let{EyeSdkBuilder:e}=re(),t=Wp["@applitools/eyes-sdk-core"]||"N/A";this.sdk=(0,oy.makeSDK)({name:"Testim.io",version:`4.0.1/eyes-sdk-core/${t}`,spec:ny.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,s,n){let{EyeSdkBuilder:o}=re(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(s,n),i}},$u=new Bu});var cy,ay,On,ly=T(()=>{"use strict";cy=E(require("lodash"));ue();U();iy();ay=x("pixel-validation-step-action"),On=class extends H{async performAction(){var m,d;let{shouldUseVisualGrid:t,applitoolsSdkConfig:s,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((d=s.batch)==null?void 0:d.id)||o,c=await $u.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},p;try{let g=await c.openEyes({driver:this.driver.client,config:s,logger:n}),h={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};cy.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(h,i.applitoolsStepSettings),ay.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await g.check({settings:h}),p={isApplitoolsSdkResult:!0,success:!0,eyesResults:await g.close()}}catch(g){ay.error("Applitools SDK step failed",{err:g,info:g.info}),p={isApplitoolsSdkResult:!0,success:!1,err:g}}return await $u.handleApplitoolsSdkResult(this.context,p,this.step)}}});var xs,Wu=T(()=>{"use strict";Cr();V();Ui();xs=class extends or{async executeCliCode(){var f,h,y;let{step:e,context:t}=this,s=this.stepActionUtils.driver.isMobile;if(!((y=(h=(f=t.company)==null?void 0:f.activePlan)==null?void 0:h.premiumFeatures)==null?void 0:y.cliAction)&&!s)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o="",id:i=""}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:p}=t,m={config:t.config,data:t.data},d=t.data.timeToPlayStep,g=await bs(o,i,a,m,c,l,p,d);return this.checkCodeResponse(g)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof te?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ir,uy=T(()=>{"use strict";Wu();ir=class extends xs{isFailedResult(e){return e===!1}}});var ea,py=T(()=>{"use strict";Wu();ea=class extends xs{isFailedResult(e){return!e}}});var ta,dy=T(()=>{"use strict";Cr();ue();V();ta=class extends H{async performAction(){let{stepId:e,packageData:t,resultId:s,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await ys(e,s,n,t,o,i),success:!0}}catch(a){return a instanceof vt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof te?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var ks,my=T(()=>{"use strict";ue();ks=class extends H{async performAction(){return{success:"skipped",reason:"This step can run only on Chrome"}}}});var je,fy=T(()=>{"use strict";ue();je=class extends H{async performAction(){var s,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(s=this.step).getStepPreview)==null?void 0:n.call(s)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var ra,gy=T(()=>{"use strict";ue();ra=class extends H{async performAction(){var s,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(s=this.step).getStepPreview)==null?void 0:n.call(s)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});function CS(r,e){Object.keys(r).forEach(t=>{e.registerStepAction(t,r[t])})}function sa(r,e){CS(AS,e),e.registerLocateStepActionUtils(kn.getUtils(r))}var AS,Hu=T(()=>{"use strict";ph();fh();Sh();Rh();xh();Ch();_h();Lh();Dh();Fh();Uh();jh();Wh();Vh();Xh();Qh();Zh();ey();ty();ry();sy();ly();uy();py();dy();my();fy();gy();AS={locate:kn,scroll:Li,mouse:Di,submit:$i,text:Mi,"special-key":ji,"user-code":$t,"validation-code-step":$t,"wait-for-code-step":$t,"action-code-step":$t,"condition-step":Rs,"skip-code-step":Rs,"element-code-step":Rs,"evaluate-expression":Ni,"text-validation":Cn,"wait-for-text-validation":Cn,"select-option":Bi,"drop-file":Gi,"input-file":qi,hover:Wi,navigation:Ki,wheel:Hi,sleep:Ji,refresh:Yi,"api-validation":An,"api-action":An,"api-code-step":$t,"extract-text":Xi,"simple-ui-verification":On,"wait-for-simple-ui-verification":On,"cli-validation-download-file":ks,"cli-wait-for-download-file":ks,"network-validation-step":ks,"cli-validation-code-step":ir,"cli-wait-for-code-step":ir,"cli-action-code-step":ir,"cli-api-code-step":ir,"cli-condition-step":ea,"node-package":ta,"email-code-step":$t,"cli-email-code-step":ir,"tdk-hybrid":Qi,"sfdc-recorded-step":ra,"sfdc-step-login":je,"sfdc-step-loginas":je,"sfdc-step-logout":je,"sfdc-step-sobjectcreate":je,"sfdc-step-sobjectdelete":je,"sfdc-step-findrecord":je,"sfdc-step-quickaction":je,"sfdc-step-sobjectedit":je,"sfdc-step-sobjectvalidate":je,"sfdc-step-launchapp":je,"sfdc-step-closeconsoletabs":je,"sfdc-step-relatedlistaction":je,"sfdc-step-permission-validation":je}});var hy,OS,yy,_S,Ps,Gu=T(()=>{"use strict";hy=E(require("lodash")),OS=1e3,yy=["simple-ui-verification","wait-for-simple-ui-verification"],_S=[...yy,"custom-validation","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-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation"],Ps=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let s=Date.now();this.currentRetryStart=s,this.lastUpdateTime=s}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let s=this.getTotalStepRunTime(e),n=_S.includes(e.stepType)?[s]:t(s);this.resetStepVariables(s,n),e.context.data.maxTotalStepTime=s}getStepTimes(){return this.totalStepTimesReport.push(this.currentRetryTimesReport),hy.cloneDeep(this.totalStepTimesReport)}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let s=e.context.config.stepTimeout;return yy.includes(e.stepType)&&(s=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(s=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:s}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let s=Date.now()-e.startTimestamp;return t-s}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+OS}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}calcAndroidScrollTimeout(e){let s=2e3;return e.step.isScrollToElement&&(s=4e3),e.step.events.length*s+5e3}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,s=e.step.type,n=3e4,o;return s==="sleep"?o=e.step.durationMS+t:s==="android-scroll"?o=Math.max(this.calcAndroidScrollTimeout(e),n):o=Math.max(this.getTotalStepTimeLeftToPlay(e),n),o}setStepPhaseTime(e){let t=Date.now(),s=t-this.lastUpdateTime;this.lastUpdateTime=t,this.currentRetryTimesReport[e]=s}reportGetTabTime(){this.setStepPhaseTime("tab")}reportGetFrameTime(){this.setStepPhaseTime("frame")}reportCalcConditionTime(){this.setStepPhaseTime("condition")}reportPreLocateActionsTime(){this.setStepPhaseTime("pre-locate")}reportFindElementsTime(){this.setStepPhaseTime("locate")}reportStepActionTime(){this.setStepPhaseTime("action")}}});var Vu={};$(Vu,{SeleniumTestPlayer:()=>_n});var _n,na=T(()=>{"use strict";j();In();V();Au();ih();Mu();Fu();lh();Uu();Ee();Hu();Gu();_n=class{constructor(e,t,s,n,o,i=void 0,a=void 0){this.id=e;this.playbackTimeoutCalculator=new Ps(Oi());let{sessionPlayer:c,commonConstants:l,stepActionFactory:p}=re();this.driver=o??new Pr;let m=new Ss(this.driver);this.stepActionFactory=new p(m),sa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ci(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let d=ch(this.driver);this.sessionPlayer=new c(e,this.tabService,new ws(this.driver),void 0,d,Ai,null,null,m,this.stepActionFactory,this.playbackTimeoutCalculator,null,n),this.sessionPlayer.setShouldMonitorPerformance(Boolean(s)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=a,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,s,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var s,n;let{commonConstants:e}=re(),t=1e3*60*2;try{await ne((s=this.driver)==null?void 0:s.end(),t)}catch(o){o instanceof te&&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 n=(await this.driver.getTabIds()).at(-1);return await this.tabService.addNewTab(this.id,n,e,t),this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},s=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(s);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(c=>a.url.includes(c))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var wy={};$(wy,{buildCodeTests:()=>qu});async function LS(r,e,t,s,n){try{return await by(r,e,t,s,n)}catch(o){if((o==null?void 0:o.code)==="ENOENT")return ar.compiler=null,ar.webpackConfig=null,s&&(s.data={}),await by(r,e,t,s,n);throw o}}async function by(r,e={mode:"development"},t=void 0,s=void 0,n=void 0){let o=await le("webpack"),i=cr.cloneDeep(e);e.externals={testim:"__testim"},e.devtool||(e.devtool="inline-source-map"),e.plugins||(e.plugins=[]),e.plugins.push(new o.DefinePlugin(DS(t)),new o.DefinePlugin({"process.argv":JSON.stringify(process.argv)})),r=r.map(f=>oa.resolve(f));let a=r.map(()=>J(30));if(e.optimization={minimize:!1},Number(process.versions.node.split(".")[0])>=17){let f=require("crypto"),h=f.createHash;f.createHash=(y,w)=>h(y==="md4"?"sha256":y,w)}e.entry=Object.fromEntries(cr.zip(r,a).map(([f,h])=>[h,f])),e.output=Object.assign({devtoolModuleFilenameTemplate:f=>`file:///${f.absoluteResourcePath}`,filename:"[name].bundle.js"},e.output);let l;s?(cr.isEqual(ar.webpackConfig,i)&&ar.compiler||(ar.webpackConfig=i,ar.compiler=o(e)),l=ar.compiler):l=o(e);let p=s||new Ty.default;l.outputFileSystem=p;let m=it(f=>{n==null||n.addEventListener("abort",()=>{f(new Ie,void 0)})});try{let f=await Promise.race([it(h=>l.run(h)),m]);if(f!=null&&f.hasErrors()){let{errors:h}=f.toJson(),y=h.map(w=>`
|
|
411
|
-
${typeof w=="string"?w:w.message||"Unknown error"}`).join("");throw new Error(y)}}catch(f){let h=f.message.match(/Entry module not found: Error: Can't resolve '(.*)'/);throw h&&h.length===2?e.output&&e.output.library==="tdk"?new k(`Could not open dev-kit functions file in ${h[1]}`):new k(`Can't find test files in: '${h[1]}'`):new k(`Compilation Webpack Error in tests: ${f.message}`)}return{tests:[r.map((f,h)=>({code:
|
|
409
|
+
const downloadAndUploadFile = ${OS()};
|
|
410
|
+
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,p);return}let h=await Xh(p,this.uploadFile);await this.uploadFilesAndForceVisibility(h,t)}}});var zi,Ki,ey=T(()=>{"use strict";zi=require("url");ue();Ki=class extends H{async updateBaseUrl(e){let t=new zi.URL(e),s=new zi.URL(this.context.recordedBaseUrl),n=new zi.URL(this.context.baseUrl);return t.host===s.host&&s.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var Ji,ty=T(()=>{"use strict";ue();j();Ji=class extends H{async performAction(){await se(this.step.durationMS||0)}}});var Yi,ry=T(()=>{"use strict";ue();Yi=class extends H{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var An,sy=T(()=>{"use strict";ue();An=class extends H{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:s}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(s,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return new Promise(s=>{t(e,s)})}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:s}=this,n={id:t.id,url:s.apiUrl,method:t.method,headers:s.apiHeaders,body:s.apiBody,timeout:s.data.maxTotalStepTime,omitCookies:t.omitCookies,formData:t.formData,fileUrls:s.fileUrls},o=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),i=o.result||{},a={method:t.method,status:i.status,url:t.url};return o.success?i.status===0?{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:i,resultInfo:a,shouldRetry:!1,success:!0}:{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:i.error||e.error.REQUEST_TIMED_OUT,errorType:i.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Xi,ny=T(()=>{"use strict";ue();Xi=class extends H{async performAction(){var s;let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return(s=this.context.data).exports||(s.exports={}),this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var Qi,oy=T(()=>{"use strict";ue();Zi();Qi=class extends H{async performAction(){return await Is(this.step,this.context,this.driver,this.stepActionUtils.testimServicesApi.authenticationManager.getLoggedUserInfo(),this.frameHandler.frameManager)}}});var iy,ay,$u,Wu,cy=T(()=>{"use strict";iy=E(require("@applitools/spec-driver-webdriverio")),ay=require("@applitools/eyes-sdk-core");Yn();Ee();$u=class{constructor(){let{EyeSdkBuilder:e}=re(),t=Hp["@applitools/eyes-sdk-core"]||"N/A";this.sdk=(0,ay.makeSDK)({name:"Testim.io",version:`4.0.1/eyes-sdk-core/${t}`,spec:iy.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,s,n){let{EyeSdkBuilder:o}=re(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(s,n),i}},Wu=new $u});var uy,ly,On,py=T(()=>{"use strict";uy=E(require("lodash"));ue();U();cy();ly=x("pixel-validation-step-action"),On=class extends H{async performAction(){var d,p;let{shouldUseVisualGrid:t,applitoolsSdkConfig:s,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((d=this.runContext.incomingParams)==null?void 0:d.final)||{},a=((p=s.batch)==null?void 0:p.id)||o,c=await Wu.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},m;try{let g=await c.openEyes({driver:this.driver.client,config:s,logger:n}),h={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};uy.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(h,i.applitoolsStepSettings),ly.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await g.check({settings:h}),m={isApplitoolsSdkResult:!0,success:!0,eyesResults:await g.close()}}catch(g){ly.error("Applitools SDK step failed",{err:g,info:g.info}),m={isApplitoolsSdkResult:!0,success:!1,err:g}}return await Wu.handleApplitoolsSdkResult(this.context,m,this.step)}}});var xs,Hu=T(()=>{"use strict";Cr();V();Ui();xs=class extends or{async executeCliCode(){var f,h,y;let{step:e,context:t}=this,s=this.stepActionUtils.driver.isMobile;if(!((y=(h=(f=t.company)==null?void 0:f.activePlan)==null?void 0:h.premiumFeatures)==null?void 0:y.cliAction)&&!s)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o="",id:i=""}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:m}=t,d={config:t.config,data:t.data},p=t.data.timeToPlayStep,g=await bs(o,i,a,d,c,l,m,p);return this.checkCodeResponse(g)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof te?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ir,dy=T(()=>{"use strict";Hu();ir=class extends xs{isFailedResult(e){return e===!1}}});var ea,my=T(()=>{"use strict";Hu();ea=class extends xs{isFailedResult(e){return!e}}});var ta,fy=T(()=>{"use strict";Cr();ue();V();ta=class extends H{async performAction(){let{stepId:e,packageData:t,resultId:s,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await ys(e,s,n,t,o,i),success:!0}}catch(a){return a instanceof vt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof te?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var ks,gy=T(()=>{"use strict";ue();ks=class extends H{async performAction(){return{success:"skipped",reason:"This step can run only on Chrome"}}}});var je,hy=T(()=>{"use strict";ue();je=class extends H{async performAction(){var s,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(s=this.step).getStepPreview)==null?void 0:n.call(s)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var ra,yy=T(()=>{"use strict";ue();ra=class extends H{async performAction(){var s,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(s=this.step).getStepPreview)==null?void 0:n.call(s)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});function _S(r,e){Object.keys(r).forEach(t=>{e.registerStepAction(t,r[t])})}function sa(r,e){_S(LS,e),e.registerLocateStepActionUtils(kn.getUtils(r))}var LS,Gu=T(()=>{"use strict";mh();hh();Ih();xh();Ph();Oh();Dh();Nh();Mh();jh();Bh();$h();Gh();zh();Zh();ey();ty();ry();sy();ny();oy();py();dy();my();fy();gy();hy();yy();LS={locate:kn,scroll:Li,mouse:Di,submit:$i,text:Mi,"special-key":ji,"user-code":$t,"validation-code-step":$t,"wait-for-code-step":$t,"action-code-step":$t,"condition-step":Rs,"skip-code-step":Rs,"element-code-step":Rs,"evaluate-expression":Ni,"text-validation":Cn,"wait-for-text-validation":Cn,"select-option":Bi,"drop-file":Gi,"input-file":qi,hover:Wi,navigation:Ki,wheel:Hi,sleep:Ji,refresh:Yi,"api-validation":An,"api-action":An,"api-code-step":$t,"extract-text":Xi,"simple-ui-verification":On,"wait-for-simple-ui-verification":On,"cli-validation-download-file":ks,"cli-wait-for-download-file":ks,"network-validation-step":ks,"cli-validation-code-step":ir,"cli-wait-for-code-step":ir,"cli-action-code-step":ir,"cli-api-code-step":ir,"cli-condition-step":ea,"node-package":ta,"email-code-step":$t,"cli-email-code-step":ir,"tdk-hybrid":Qi,"sfdc-recorded-step":ra,"sfdc-step-login":je,"sfdc-step-loginas":je,"sfdc-step-logout":je,"sfdc-step-sobjectcreate":je,"sfdc-step-sobjectdelete":je,"sfdc-step-findrecord":je,"sfdc-step-quickaction":je,"sfdc-step-sobjectedit":je,"sfdc-step-sobjectvalidate":je,"sfdc-step-launchapp":je,"sfdc-step-closeconsoletabs":je,"sfdc-step-relatedlistaction":je,"sfdc-step-permission-validation":je}});var by,DS,Ty,NS,Ps,Vu=T(()=>{"use strict";by=E(require("lodash")),DS=1e3,Ty=["simple-ui-verification","wait-for-simple-ui-verification"],NS=[...Ty,"custom-validation","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-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation"],Ps=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let s=Date.now();this.currentRetryStart=s,this.lastUpdateTime=s}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let s=this.getTotalStepRunTime(e),n=NS.includes(e.stepType)?[s]:t(s);this.resetStepVariables(s,n),e.context.data.maxTotalStepTime=s}getStepTimes(){return this.totalStepTimesReport.push(this.currentRetryTimesReport),by.cloneDeep(this.totalStepTimesReport)}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let s=e.context.config.stepTimeout;return Ty.includes(e.stepType)&&(s=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(s=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:s}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let s=Date.now()-e.startTimestamp;return t-s}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+DS}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}calcAndroidScrollTimeout(e){let s=2e3;return e.step.isScrollToElement&&(s=4e3),e.step.events.length*s+5e3}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,s=e.step.type,n=3e4,o;return s==="sleep"?o=e.step.durationMS+t:s==="android-scroll"?o=Math.max(this.calcAndroidScrollTimeout(e),n):o=Math.max(this.getTotalStepTimeLeftToPlay(e),n),o}setStepPhaseTime(e){let t=Date.now(),s=t-this.lastUpdateTime;this.lastUpdateTime=t,this.currentRetryTimesReport[e]=s}reportGetTabTime(){this.setStepPhaseTime("tab")}reportGetFrameTime(){this.setStepPhaseTime("frame")}reportCalcConditionTime(){this.setStepPhaseTime("condition")}reportPreLocateActionsTime(){this.setStepPhaseTime("pre-locate")}reportFindElementsTime(){this.setStepPhaseTime("locate")}reportStepActionTime(){this.setStepPhaseTime("action")}}});var qu={};$(qu,{SeleniumTestPlayer:()=>_n});var _n,na=T(()=>{"use strict";j();In();V();Ou();ch();Fu();Uu();ph();ju();Ee();Gu();Vu();_n=class{constructor(e,t,s,n,o,i=void 0,a=void 0){this.id=e;this.playbackTimeoutCalculator=new Ps(Oi());let{sessionPlayer:c,commonConstants:l,stepActionFactory:m}=re();this.driver=o??new Pr;let d=new Ss(this.driver);this.stepActionFactory=new m(d),sa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ci(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let p=uh(this.driver);this.sessionPlayer=new c(e,this.tabService,new ws(this.driver),void 0,p,Ai,null,null,d,this.stepActionFactory,this.playbackTimeoutCalculator,null,n),this.sessionPlayer.setShouldMonitorPerformance(Boolean(s)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=a,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,s,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var s,n;let{commonConstants:e}=re(),t=1e3*60*2;try{await ne((s=this.driver)==null?void 0:s.end(),t)}catch(o){o instanceof te&&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 n=(await this.driver.getTabIds()).at(-1);return await this.tabService.addNewTab(this.id,n,e,t),this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},s=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(s);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(c=>a.url.includes(c))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Ey={};$(Ey,{buildCodeTests:()=>zu});async function MS(r,e,t,s,n){try{return await wy(r,e,t,s,n)}catch(o){if((o==null?void 0:o.code)==="ENOENT")return ar.compiler=null,ar.webpackConfig=null,s&&(s.data={}),await wy(r,e,t,s,n);throw o}}async function wy(r,e={mode:"development"},t=void 0,s=void 0,n=void 0){let o=await le("webpack"),i=cr.cloneDeep(e);e.externals={testim:"__testim"},e.devtool||(e.devtool="inline-source-map"),e.plugins||(e.plugins=[]),e.plugins.push(new o.DefinePlugin(FS(t)),new o.DefinePlugin({"process.argv":JSON.stringify(process.argv)})),r=r.map(f=>oa.resolve(f));let a=r.map(()=>J(30));if(e.optimization={minimize:!1},Number(process.versions.node.split(".")[0])>=17){let f=require("crypto"),h=f.createHash;f.createHash=(y,w)=>h(y==="md4"?"sha256":y,w)}e.entry=Object.fromEntries(cr.zip(r,a).map(([f,h])=>[h,f])),e.output=Object.assign({devtoolModuleFilenameTemplate:f=>`file:///${f.absoluteResourcePath}`,filename:"[name].bundle.js"},e.output);let l;s?(cr.isEqual(ar.webpackConfig,i)&&ar.compiler||(ar.webpackConfig=i,ar.compiler=o(e)),l=ar.compiler):l=o(e);let m=s||new vy.default;l.outputFileSystem=m;let d=it(f=>{n==null||n.addEventListener("abort",()=>{f(new Ie,void 0)})});try{let f=await Promise.race([it(h=>l.run(h)),d]);if(f!=null&&f.hasErrors()){let{errors:h}=f.toJson(),y=h.map(w=>`
|
|
411
|
+
${typeof w=="string"?w:w.message||"Unknown error"}`).join("");throw new Error(y)}}catch(f){let h=f.message.match(/Entry module not found: Error: Can't resolve '(.*)'/);throw h&&h.length===2?e.output&&e.output.library==="tdk"?new k(`Could not open dev-kit functions file in ${h[1]}`):new k(`Can't find test files in: '${h[1]}'`):new k(`Compilation Webpack Error in tests: ${f.message}`)}return{tests:[r.map((f,h)=>({code:m.readFileSync(oa.resolve("./dist",`${a[h]}.bundle.js`)),name:f})).map(({code:f,name:h})=>({code:f.toString(),baseUrl:"",name:oa.resolve(h),testConfig:{},testConfigId:null,testId:J(),resultId:J(),isTestsContainer:!0}))],runName:`Testim Dev Kit Run ${new Date().toLocaleString()}`}}function FS(r){let e=cr.fromPairs(Object.keys(process.env).filter(s=>/^TDK_/i.test(s)||s==="BASE_URL").map(s=>[s,process.env[s]])),t={BASE_URL:r==null?void 0:r.baseUrl};return{"process.env":US({...t,...e})}}function US(r){return Object.fromEntries(Object.entries(r).map(([e,t])=>[e,JSON.stringify(t)]))}var cr,oa,vy,ar,zu,Ku=T(()=>{"use strict";cr=E(require("lodash")),oa=E(require("path"));j();vy=E(require("memory-fs"));V();dt();ar={compiler:null,webpackConfig:null};zu=MS});var Iy={};$(Iy,{compileFunctionsLibrary:()=>Zu,findTestFolder:()=>Or,findTests:()=>Ju,getLocalLocatorContents:()=>Yu,getLocalLocators:()=>Ln,saveLocators:()=>Qu,saveTest:()=>Xu});async function Ln(){let r=await Or(process.cwd()),e=Xe.join(r,"locators","locators.js");function t(n){let o=n.toString().replace("module.exports =","return").replace(/require/g,"(x => /locator\\.(.*)\\.json/.exec(x)[1])");return new Function(o)()}let s=await st.promises.readFile(e).then(t,()=>({}));return Object.fromEntries(Object.keys(s).map(n=>[n.replace(/"/g,'\\"'),s[n]]))}async function Ju(r=process.cwd()){let e=await Or(r),t=await st.promises.readdir(e,{withFileTypes:!0}),s=["webpack.config.js","tsconfig.js",".DS_Store","functions.js"],n=[".html",".json"];return t.filter(o=>!s.includes(o.name)&&!n.some(i=>o.name.endsWith(i))&&o.isFile()&&!o.name.startsWith(".")).map(o=>o.name)}async function jS(r){let e=Object.entries(r),t=e.map(([,n])=>n),s=await Promise.all(t);for(let n=0;n<s.length;n++)e[n][1]=s[n];return Object.fromEntries(e)}async function Yu(r,e=!1,t=process.cwd()){let s={};if(e){let n=await Or(t);for(let o of Object.values(r))s[o]=st.promises.readFile(Xe.join(n,"locators",`locator.${o}.json`)).then(JSON.parse)}try{return await jS(s)}catch(n){return console.error(n),{}}}async function Xu({body:r,name:e,locators:t,language:s="javascript"}){let n=await Or(process.cwd()),o=Xe.join(n,"locators","locators.js"),i=Xe.join(n,e);if(!i.startsWith(n))throw new Error("A test name must be a valid file name and inside the tests directory");if(s==="javascript"?i.endsWith(".js")&&!i.endsWith(".test.js")?i=`${i.substr(0,i.length-3)}.test.js`:i.endsWith(".test.js")||(i+=".test.js"):i.endsWith(".ts")&&!i.endsWith(".test.ts")?i=`${i.substr(0,i.length-3)}.test.ts`:i.endsWith(".test.ts")||(i=`${i}.test.ts`),i.endsWith("locators/locators.js"))throw new Error("Cannot override locators file from the internet as it is evaluated by the runner");await st.promises.writeFile(i,r),await st.promises.mkdir(Xe.join(n,"locators")).catch(()=>null);for(let{id:l,body:m}of t)await st.promises.writeFile(Xe.join(n,"locators",`locator.${l}.json`),JSON.stringify(m));let a=Object.fromEntries(t.map(({name:l,id:m})=>[l,m])),c=await Ln();Object.assign(c,a),await Ry(o,c)}async function Ry(r,e){let t=`module.exports = {
|
|
412
412
|
`;for(let[s,n]of Object.entries(e))t+=` "${s}": require('./locator.${n}.json'),
|
|
413
|
-
`;t+="};",await st.promises.writeFile(r,t)}async function Xu(r,{mergeIntoExisting:e}={mergeIntoExisting:!1}){let t=await Or(process.cwd()),s=Xe.join(t,"locators","locators.js");await st.promises.mkdir(Xe.join(t,"locators")).catch(()=>null);for(let{name:o,id:i,elementLocator:a}of r)await st.promises.writeFile(Xe.join(t,"locators",`locator.${i}.json`),JSON.stringify({name:o,id:i,elementLocator:a}));let n=Object.fromEntries(r.map(({name:o,id:i})=>[o,i]));if(e){let o=await Ln();Object.assign(n,o)}await Ey(s,n)}async function Qu({fileSystem:r,bypassWebpack:e}={},t=void 0){let s=await Or(process.cwd());if(t!=null&&t.aborted)throw new Ie;let n=Xe.join(s,"functions.js");if(typeof e!="boolean"&&(e!=null&&e.testim)){let i=require("module"),a=i.prototype.require;i.prototype.require=function(l){return l==="testim"?e.testim:a.apply(this,arguments)};try{return delete require.cache[require.resolve(n)],require(n)}finally{i.prototype.require=a}}return(await qu([n],{output:{libraryTarget:"umd",library:"tdk",globalObject:"globalThis"},cache:{type:"memory"},mode:"development"},{},r,t)).tests[0][0].code}var vy,Xe,st,Or,Zu=T(()=>{"use strict";vy=E(require("lodash")),Xe=E(require("path")),st=require("fs");V();zu();Or=vy.memoize(async r=>(await st.promises.readdir(r)).includes("tests")&&(await st.promises.stat(Xe.join(r,"tests"))).isDirectory()?Xe.join(r,"tests"):r)});async function lr(r,e,t){let s=FS(r.parameterNames.map(n=>n.displayName),e.incomingParams.as);return await Promise.all(s.map(n=>typeof n=="object"&&n.locatedElement?t(n):n))}function FS(r,e){let t=[];for(let s of r){let n=e.functionParameters.indexOf(s);t.push(e.functionArguments[n])}return t}var Dn=T(()=>{"use strict"});var Ry={};$(Ry,{execute:()=>US});async function jS(r,e,t,s,n,o){var a;let i;try{let{WebDriver:c}=await le("selenium-webdriver");if(o.aborted)throw new Ie;let{Executor:l,HttpClient:p}=require("selenium-webdriver/http"),m=r.driver.client.options,d=m.path,f=`${m.protocol}://${m.hostname}:${m.port}`+d,h=new p(f),y=new c(r.getSessionId(),new l(h));await BS(y,r.driver);let S=await lr(t,s,v=>y.findElement({css:v.selector})),b=e.bind(null,y,...S);return i=function(){h.send=async function(){throw new Ie}},o.addEventListener("abort",i),await b(),{success:!0}}catch(c){return o.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,shouldRetry:!1,reason:(c==null?void 0:c.message)||c,extraInfo:(a=c==null?void 0:c.constructor)==null?void 0:a.name}}finally{i&&o.removeEventListener("abort",i)}}async function BS(r,e){if(e.cdpUrl){let t=await r.getAllWindowHandles();for(let s of t)if(await r.switchTo().window(s),await r.executeScript("return window.__isMainTestimTab"))break}}var US,Iy=T(()=>{"use strict";V();dt();Dn();US=jS});var xy={};$(xy,{execute:()=>$S});async function WS(r,e,t,s,n,o){var a;let i;try{let c=await le("puppeteer");if(o.aborted)throw new Ie;let l=await c.connect({browserWSEndpoint:r.driver.cdpUrl,defaultViewport:null,product:"chrome"});if(o.aborted)throw l.disconnect(),new Ie;i=function(){l.disconnect()},o.addEventListener("abort",i);let p=await l.pages(),m;for(let y of p)if(await y.evaluate(()=>window.__isMainTestimTab)){m=y;break}let d=m||p.at(-1),f=await lr(t,s,y=>d.$(y.selector));return await e.bind(null,d,...f)(),{success:!0}}catch(c){return o.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,shouldRetry:!1,reason:(c==null?void 0:c.message)||c,extraInfo:(a=c==null?void 0:c.constructor)==null?void 0:a.name}}finally{i&&o.removeEventListener("abort",i)}}var $S,ky=T(()=>{"use strict";V();dt();Dn();$S=WS});var Py={};$(Py,{execute:()=>HS});async function GS(r,e,t,s,n,o){var a;let i;try{let c=await le("playwright");if(o.aborted)throw new Ie;let l=await c.chromium.connect({wsEndpoint:r.driver.cdpUrl});if(o.aborted)throw l.disconnect(),new Ie;i=function(){l.disconnect()},o.addEventListener("abort",i);let d=(await(await l.newContext({viewport:null})).pages()).at(-1),f=await lr(t,s,y=>d.$(y.selector));return await e.bind(null,d,...f)(),{success:!0}}catch(c){return o.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,reason:(c==null?void 0:c.message)||c,extraInfo:(a=c==null?void 0:c.constructor)==null?void 0:a.name}}finally{i&&o.removeEventListener("abort",i)}}var HS,Cy=T(()=>{"use strict";V();dt();Dn();HS=GS});var Oy={};$(Oy,{execute:()=>VS});async function qS(r,e,t,s,n,o,i,a){function c(){r.sessionPlayer.stopPlaying()}a.addEventListener("abort",c);function l(C){if(o.parameterValues){let N=o.parameterValues.find(B=>B.type==="locate"&&B.id===C.locatorId);return{elementLocator:N.elementLocator,id:N.id,name:"Hybrid Step Locator"}}return C.locatedElement.shadowPath?C.locatedElement.shadowPath[0]:C}let p=await lr(o,t,l),m=e.bind(null,...p),d=J(),g=J(),f=t.testResultId,h=t.config.baseUrl,y=Ay.cloneDeep(t);Object.assign(y,{loginData:s});let S=re().manifestVersion||"runner",b=!1,v=null,I="master",A=`Execute TDK Function '${o.functionName}'`,_=!0,R={fn:m,bypassSetup:!0,isBeforeOrAfterTest:!0,name:A,sourceCode:m.toString(),sourceName:m.name,testId:d,resultId:J()},L=typeof e.results=="boolean"&&!e.results;try{O("tdkHybridStepPlayback before addAllTabs"),n?(Object.assign(r.sessionPlayer.playbackAutUtils,{frameManager:n}),Object.assign(r.sessionPlayer,{frameManager:n})):await r.addAllTabs(null,{loadInfo:!0,checkForMainTab:!0,takeScreenshots:!L},[r.driver.initialUrl]),r.sessionPlayer.playbackManager.dontAssociateChildResult=!0,r.sessionPlayer.playbackManager.onlyLocalReporting=L,O("tdkHybridStepPlayback before playTestByCode");let C=await new Promise((N,B)=>{i==="agent"&&zS(r,N);function K(){B(new Ie),a.removeEventListener("abort",K)}a.addEventListener("abort",K),r.sessionPlayer.playTestByCode(d,g,f,h,y,S,N,b,v,I,[R],A,_).catch(B)});return O("tdkHybridStepPlayback after playTestByCode"),{success:C.success,shouldRetry:!1,resultInfo:{testId:d,executionId:g,resultId:R.resultId}}}catch(C){return{success:!1,error:C,shouldRetry:!1}}finally{a.removeEventListener("abort",c)}}function zS(r,e){let{commonConstants:t}=re();r.sessionPlayer.playbackManager.on(t.playback.START,({testResult:s})=>{let n=s.runnerStatus;Object.defineProperty(s,"runnerStatus",{get(){return n},set(o){n=o,o==="FINISHED"&&e(s)}})})}var Ay,VS,_y=T(()=>{"use strict";Ay=E(require("lodash"));Le();j();V();Dn();Ee();VS=qS});var ia={};$(ia,{abort:()=>rp,execute:()=>Is,run:()=>YS});async function Is(r,e,t,s,n,o="cli"){let i=new AbortController,{signal:a}=i;tp.set(e.stepResultId,i);try{O("before seleniumTestPlayer require");let[{SeleniumTestPlayer:c},{compileFunctionsLibrary:l}]=await Promise.all([Promise.resolve().then(()=>(na(),Vu)),Promise.resolve().then(()=>(Zu(),Sy))]),{functionName:p=""}=r,m={},d=!1,g=new c(e.id,m,d,Lt.CODEFUL,t);ep=g.sessionPlayer.codeSessionPlayer.proxy;let f=r.bypassWebpack?{testim:ep.wrappedSteps()}:!1;O("before compileFunctionsLibrary",{bypassWebpack:Boolean(r.bypassWebpack)});let h;try{h=await l({fileSystem:KS,bypassWebpack:f},a)}catch(w){return{success:!1,shouldRetry:!1,reason:`Unable to compile functions library. ${w.message}`,extraInfo:w.stack}}let y;if(f?y=h[p]:(global.globalThis.__testim=ep.wrappedSteps(),(0,eval)(h),y=globalThis.tdk[p]),O("after hybridFunction obtain and eval"),!y)return{success:!1,shouldRetry:!1,reason:`Could not find function '${p}' locally. Please make sure you have a functions.js file with a '${p}' function defined`,extraInfo:Object.keys(globalThis.tdk)};if(y.type==="selenium"){let{execute:w}=await Promise.resolve().then(()=>(Iy(),Ry));return await w(g,y,r,e,o,a)}if(y.type==="puppeteer"){if(!g.driver.cdpUrl)return{success:!1,shouldRetry:!1,reason:"running puppeteer code requires the remote debugging protocol to be open. Please contact Testim support."};O("before puppeteerPlayback");let{execute:w}=await Promise.resolve().then(()=>(ky(),xy));try{return await w(g,y,r,e,o,a)}finally{O("after puppeteerPlayback")}}if(y.type==="playwright"){if(!g.driver.cdpUrl)return{success:!1,shouldRetry:!1,reason:"running playwright code requires the remote debugging protocol to be open. Please contact Testim support."};let{execute:w}=await Promise.resolve().then(()=>(Cy(),Py));return await w(g,y,r,e,o,a)}if(y.type==="tdk"||!y.type){let{execute:w}=await Promise.resolve().then(()=>(_y(),Oy));O("before tdkPlayback");try{return await w(g,y,e,s,n,r,o,a)}finally{O("after tdkPlayback")}}return{success:!1,shouldRetry:!1,reason:`unknown hybrid format ${y.type}`}}catch(c){JS.info("error running hybrid step",{err:c});return}finally{tp.delete(e.stepResultId)}}function rp(r){let e=tp.get(r);if(!e)throw new Error("No such stepResultId");e.abort()}var Ly,KS,JS,tp,ep,YS,Zi=T(()=>{"use strict";Ly=E(require("memory-fs"));Le();U();ie();KS=new Ly.default,JS=x("hybrid-step-playback"),tp=new Map,YS=(r,e,t,s)=>{let{step:n,context:o}=e.data;return Is(n,o,r,s.loginData)}});var sp={};$(sp,{run:()=>XS});var XS,Dy=T(()=>{"use strict";Cr();V();XS=async(r,e)=>{let{stepId:t,testResultId:s,retryIndex:n,stepResultId:o,packageData:i,timeout:a}=e.data;try{return{data:await ys(t,s,n,i,o,a),success:!0}}catch(c){if(c instanceof vt)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof te)return{success:!1,code:"timeout"};throw c}}});async function My(r,e,t,s){try{return await cl(r,e,t,s)}catch{aa.error("failed to report remote step state",{projectId:r,resultId:e,stepId:t});return}}async function ZS(r,e,t,s,n){return aa.info("finished to run remote step",{stepId:t,sessionId:n}),await My(r,e,t,{status:"completed",success:!0,failureReason:null,data:s})}async function Ny(r,e,t,s,n){return aa.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:s}),await My(r,e,t,{status:"completed",success:!1,failureReason:s})}async function Fy(r,e,t,s){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:o,userData:i}=r,a=t.type,c=e.getSessionId(),l=t.id;aa.info("start play remote step",{stepType:a,stepId:l,sessionId:c});let p=QS[a];if(!p)return await Ny(n,s,l,`Failed to find step type ${a}`,c);try{let m=await p.run(e,t,o,i);return await ZS(n,s,l,m,c)}catch(m){return await Ny(n,s,l,m.message,c)}}var aa,QS,Uy=T(()=>{"use strict";Xg();Zi();be();Dy();U();aa=x("step-playback"),QS={"cli-validation-code-step":nr,"cli-wait-for-code-step":nr,"cli-action-code-step":nr,"cli-api-code-step":nr,"cli-condition-step":nr,"cli-download-code-step":nr,"node-package":sp,"tdk-hybrid":ia}});var np,jy,_r,tR,op,$e,Nn=T(()=>{"use strict";j();Rt();np=E(require("ws")),jy=require("events");U();pe();_r=x("socket-ng-service"),tR=5e3,op=class extends jy.EventEmitter{constructor(){super(...arguments);this.clientId=J();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){_r.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),tR)}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(s){_r.error("failed to parse or trigger event",{err:s})}}connect(t){let s=this.formatUrl(zp);return Kt().then(n=>new Promise(o=>{let i={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new np.default(`${s}?projectId=${t}&clientId=${this.clientId}&token=${n}`,i),this.ws.on("open",()=>{var a;return _r.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),o()}),this.ws.on("close",a=>{_r.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===np.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{_r.info("websocket error",{event:a})}),this.ws.on("message",a=>{let c=this.parseEvent(a);c!=null&&c.type&&this.emit(c.type,c.data)})}))}sendMessage(t){if(!this.ws){_r.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(s){_r.error("failed to stringify message for sending",{err:s})}}listenOnce(t,s,n){let o=i=>{s(i)&&(n(i),this.removeListener(t,o))};this.on(t,o)}listenTo(t,s,n,o){function i(c){n(c)&&o(c)}(Array.isArray(s)?s:[s]).forEach(c=>{var p,m;(p=this.listeners)[m=`${t}:${c}`]||(p[m]=[]);let l=i.bind(this);this.listeners[`${t}:${c}`].push(l),this.on(c,l)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let s=this.filterMap[t];this.sendMessage({type:"add-filter",filter:s})})}addFilter(t,s,n,o=!1){return new Promise(i=>{let a=J(),c={query:s,id:a,type:n,fullDocument:o};this.listenOnce("add-filter:done",l=>l.id===a,i),this.sendMessage({type:"add-filter",filter:c}),this.filterMap[t]=c})}removeListeners(t,s){Object.keys(this.listeners).length!==0&&s.forEach(n=>{let o=this.listeners[`${t}:${n}`];o&&(delete this.listeners[`${t}:${n}`],o.forEach(i=>this.removeListener(n,i)))})}removeFilter(t,s){let n=this.filterMap[t];if(!n)return;let o=Array.isArray(s)?s:[s];this.removeListeners(t,o),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},$e=new op});var $y,ip,rR,sR,nR,By,ca,ur,la=T(()=>{"use strict";$y=E(require("p-retry")),ip=E(require("socket.io-client"));pe();j();U();rR=50,sR=10,nR=5e3,By=10*1e3,ca=x("base socket service"),ur=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);ca.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let s=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,s)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,s)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}ca.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${s==null?void 0:s.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===sR&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=rR)throw new Error(`Can't connect to Testim Servers.
|
|
414
|
-
Action required: Please allow opening a websockets connection to ${me} 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",()=>{ca.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let s={query:{projectId:e},requestTimeout:By,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=`${me}/${t}`,this._socket=ip.connect(this.url,s),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let s={query:{projectId:e},requestTimeout:By,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=`${me}/${t}`,this._socket=ip.connect(this.url,s),this.addSocketHandlers()}emitPromise(e,t){let s={},n=()=>new Promise((o,i)=>{this._socket.emit(e,t,a=>a!=null&&a.success?o():(s[e]=t,i(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,$y.default)(()=>ne(n(),nR),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(s).length>0&&ca.error("Bad acknowledge from socket emit",{errorneousEvents:s})}),this.emitPromiseQueue}}});var Wy={};$(Wy,{remoteStepServiceSocketIO:()=>oR});var ap,oR,Hy=T(()=>{"use strict";la();ap=class extends ur{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"remoteStep"),this.listerers={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,s){this.listerers[t]&&(this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&s(n.remoteStep)},this._socket.on("remoteStep:saved",this.listerers[t])}async unlistenToRemoteStep(t){this.listerers[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t],await this.emitLeaveRoom(t))}},oR=new ap});var Gy={};$(Gy,{remoteStepService:()=>Cs});var cp,Mn,lp,Cs,ua=T(()=>{"use strict";Nn();ie();Te();({REMOTE_STEP_SAVED:cp}=et),lp=class{async init(e){M.flags.useNewWSCLI.isEnabled()||(Mn=(await Promise.resolve().then(()=>(Hy(),Wy))).remoteStepServiceSocketIO,Mn.init(e))}joinToRemoteStep(e){return M.flags.useNewWSCLI.isEnabled()?$e.addFilter(`${e}:remoteStep`,{resultId:e},[cp]):Mn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(M.flags.useNewWSCLI.isEnabled()){$e.listenTo(`${e}:remoteStep`,[cp],s=>s.resultId===e&&s.remoteStep&&s.remoteStep.status==="pending",s=>t(s.remoteStep));return}Mn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return M.flags.useNewWSCLI.isEnabled()?($e.removeFilter(`${e}:remoteStep`,[cp]),Promise.resolve()):Mn.unlistenToRemoteStep(e)}},Cs=new lp});var up,Lr,Vy=T(()=>{"use strict";la();up=class extends ur{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"testResult"),this.listerers={}}listenToTestResult(t,s,n){this.listerers[t]&&(this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=o=>{o.resultId===t&&o.testId===s&&n(o.testResult)},this._socket.on("testResult:updated",this.listerers[t])}emitJoinRoom(t,s){return this.emitPromise("testResult:join",{resultId:t,testId:s})}async joinToTestResult(t,s){this.rooms[t]||this.joinRoom(t,s),await this.emitJoinRoom(t,s)}emitLeaveRoom(t,s){return this.emitPromise("testResult:leave",{resultId:t,testId:s})}leaveTestResult(t,s){return this.listerers[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t],this.emitLeaveRoom(t,s)):Promise.resolve()}getSocket(){return this._socket}},Lr=new up});var zy={};$(zy,{testResultService:()=>kt});var qy,pp,kt,pa=T(()=>{"use strict";qy=require("events");Nn();ie();Te();Vy();pp=class extends qy.EventEmitter{init(e){if(M.flags.useNewWSCLI.isEnabled()){$e.onConnect=()=>this.emit("socket-connected");return}Lr.init(e),Lr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return M.flags.useNewWSCLI.isEnabled()?$e.addFilter(`${e}:testResult`,{resultId:e,testId:t},[et.TEST_RESULT_UPDATED,et.TEST_RESULT_CREATED]):Lr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(M.flags.useNewWSCLI.isEnabled()){$e.removeFilter(`${e}:testResult`,[et.TEST_RESULT_UPDATED,et.TEST_RESULT_CREATED]);return}await Lr.leaveTestResult(e,t)}listenToTestResult(e,t,s){if(M.flags.useNewWSCLI.isEnabled()){$e.listenTo(`${e}:testResult`,[et.TEST_RESULT_UPDATED,et.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>s(n));return}Lr.listenToTestResult(e,t,s)}getSocket(){if(!M.flags.useNewWSCLI.isEnabled())return Lr.getSocket()}},kt=new pp});var Jy,Yy,Xy,we,iR,Qy,Ky,da,Zy=T(()=>{"use strict";Jy=E(require("lodash"));j();pe();Le();cs();Rt();be();Uy();Yy=E(require("p-retry")),Xy=require("url");U();Vo();fs();ie();ua();pa();Te();we=x("test-run-handler"),iR=3,Qy=20*1e3,Ky=r=>JSON.stringify(r).length<Qy,da=class{constructor(e,t,s,n,o,i){this._executionId=e;this._executionName=t;this._options=n;this._branch=o;this._testRunStatus=i;this.seleniumPerfStats=new Bt;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.clearTestResultFinished=Promise.resolve(void 0);var c,l;this._testStatus=s.testStatus,this._testId=s.testId,this._testName=s.name,this._testResultId=s.resultId,this._code=s.code,this._baseUrl=n.baseUrl||s.baseUrl||s.testConfig.baseUrl,this._nativeApp=s.nativeApp,this._overrideTestConfigId=(c=s.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((l=s.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?Js(n.browser,n.saucelabs,n.browserstack):s.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get automationMode(){return this._code?"codeful":"codeless"}get code(){return this._code}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}get browserStackAppPath(){var e;return this.isAppFromDevice?null:(e=this._nativeApp)==null?void 0:e.browserStackAppId}getSauceLabsAppPath(e){var t,s;return this.isAppFromDevice?null:e.includes("us-west-1")?(t=this._nativeApp)==null?void 0:t.usSauceLabsAppId:(s=this._nativeApp)==null?void 0:s.euSauceLabsAppId}get headspinAppPath(){var e;return this.isAppFromDevice?null:(e=this._nativeApp)==null?void 0:e.headSpinAppId}get androidActivityWait(){var n;let e=this._nativeApp&&"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp;if((n=e==null?void 0:e.activity)!=null&&n.includes(e.id))return`${e.id}.*`;let{activity:t}=e;if(!t)return null;let s=t.split(".").pop();return t.replace(s,"*")}get isFFAllowAppFromDeviceEnabled(){return M.flags.allowAppFromDeviceRuns.isEnabled()}get isAppFromDevice(){return qs(this._nativeApp)}get isAppForIosVirtualDevice(){return Jr(this._nativeApp)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?io.FROM_DEVICE:io.FROM_LIBRARY}get nativeAppLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${me}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}async getNativeAppData(){let{appId:e,baseUrl:t}=this._options;if(t&&!this._nativeApp&&!e){let s=t||this.baseUrl;if(!s)return null;let[n,o]=s.split(":");return{packageName:n,activity:o}}return this._nativeApp&&!e?"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 overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var s,n;let t={tokenV3:await Kt(),refreshToken:Po(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:Zp,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this.code&&{isCodeMode:!0,testName:this.testName},...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,onprem:this._options.company.onprem,storageBaseUrl:this._options.company.storageBaseUrl,storageType:this._options.company.storageType,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential}};if(this._options.disableMockNetwork&&ut("user-disable-mock"),t.lightweightMode&&((s=this._options.lightweightMode)!=null&&s.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=Ky(o);Object.assign(t.lightweightMode,{isRunDataSentInUrl:i});let a=JSON.stringify(o).length,c=this.testId;i?(Object.assign(t,{runData:o}),we.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):we.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${Qy} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let o=await dn(this._options);Object.assign(t,{preloadedTest:o[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return we.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var o;let e={...this.runData,...this.runMode===Y.EXTENSION&&{code:this.code},...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((o=this._options.lightweightMode)!=null&&o.disableResults&&!t&&Ky(e))return;let s=async()=>{try{return await ll(this._options.project,this._testId,this._testResultId,e)}catch(i){return we.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await s();return await this._testRunStatus.waitForExecutionStartedFinished(),al(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:i,runData:i?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){O("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},s=["Testim Editor","Tricentis Testim Editor"],{targetId:n}=t.find(i=>i.type==="background_page"&&s.includes(i.title))||{},{targetId:o}=t.find(i=>i.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!o)throw new Error("AUT target not found");try{O("before Target.attachToTarget");let[i,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=i||{};O("before Runtime.evaluate"),await(0,Yy.default)(async()=>{let{result:p}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);if(!p.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),O("after wait for runTestimTest function");let{result:l}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},c);if(l.subtype==="error")throw new Error(l.description);return O("after Runtime.evaluate"),l.value}catch(i){throw we.error("error running test using CDP",{err:i}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let s;try{s=new Xy.URL(e)}catch{return}let{username:n,password:o}=s;if(n||o)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let s=!1,n=o=>{if(!s){if(this.isRetryKeyMismatch(o)){we.warn(`ignoring result update for on started due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(o.status)&&(o.resultId=this.testResultId,o.status==="completed"&&(we.info("setting _wasCompletedOnStartedCheck to true",{testResult:o,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=o),s=!0,t(o))}};if(this._options.disableSockets){let o=Date.now()+e,i=async()=>{if(Date.now()>o)return;let{testId:a,testResultId:c,branch:l,_options:{project:p}}=this;try{let m=await Rr(a,c,p,l);n(m),s||setTimeout(i,3e3)}catch(m){we.error("failed to check if done",{err:m}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else kt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:s},branch:n}=this;try{let o=await Rr(e,t,s,n),i=["running","completed"];if(i.includes(o.status))return we.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw we.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Be.TEST_START_TIMEOUT_MSG)}catch(o){throw we.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error(Be.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(s=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){we.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),s(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||kt.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){we.warn(`ignoring result update for on completed due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}i.status==="completed"&&(i.resultId=this._testResultId,s(i))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),o=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Jy.debounce(async()=>{try{let i=await Rr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(we.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(i==null?void 0:i.status)==="completed"?(we.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),i.resultId=this._testResultId,s(i),!0):!1}catch(i){return we.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)kt.on("socket-connected",async()=>{try{await kt.joinToTestResult(this._testResultId,this.testId)}catch(i){we.error("failed joining to test result updates after socket reconnected",{error:i})}e==null||e()});else{let i=()=>{setTimeout(async()=>{try{let{isComplete:a}=await Xc(this._testResultId,this._options.project,this.retryKey);a?await e()||(we.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){we.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&kt.off("socket-connected",e)}}listenToRemoteStep(e){Cs.listenToRemoteStep(this.testResultId,t=>{Fy(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:iR;return this._timeoutRetryCount<e}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,s;return Boolean((s=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:s.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||(this._originalTestResultId=this._previousTestResultId),this._testResultId=J(),!((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 ma,eb=T(()=>{"use strict";Zy();ma=class{constructor(e,t,s,n,o,i){this._waitingTests=s.map(a=>new da(e,t,a,n,o,i))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var aR,cR,Fn,dp=T(()=>{"use strict";ds();U();aR=x("worker-utils"),cR=async(r,e,t)=>{e&&await ql(r,t)},Fn=async(r,e,t,s)=>{aR.info("releasing player",{hasPlayer:Boolean(s)});try{await(s==null?void 0:s.onDone())}finally{await cR(r,e,t)}}});function fR(r,e,t,s){return{testId:r,reason:s,name:e,resultId:t,success:!1}}var gp,nb,ob,fp,Pt,tb,rb,sb,Un,lR,mp,uR,Wt,pR,fa,dR,mR,gR,Ct,ga=T(()=>{"use strict";gp=E(require("ms")),nb=E(require("lodash")),ob=E(require("moment")),fp=E(require("p-retry"));j();Le();ds();be();U();dp();jt();Xo();Te();ua();pa();at();ie();V();Pt=x("base-worker"),{GET_BROWSER_TIMEOUT_MSG:tb,TEST_START_TIMEOUT_MSG:rb,TEST_COMPLETE_TIMEOUT_MSG:sb}=Be,{SETUP_TIMEOUT:Un,NETWORK_ERROR:lR,GRID_ERROR:mp,BROWSER_CLOSED:uR,SELENIUM_ERROR:Wt,UNKNOWN_ERROR:pR,MOBILE_SESSION_ERROR:fa}=Hs,dR=(0,gp.default)("1s"),mR=1;gR=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Ct=class{constructor(e,t,s,n,o,i,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=s;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.id=Ct.getWorkerId();this.lambdatestService=new Z;this.isCodeMode=t.files&&t.files.length>0,this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.isRegressionBaselineRun=t.isRegressionBaselineRun,this.userData=t.userData}static getWorkerId(){return mR++}async getGridSlot(e,t){let s=await Pf(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,s),s}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Us(!0)}async getBrowserOnce(e,t,s,n){throw new Us(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),Pt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!Ke({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var o;let t=!e.isFFAllowAppFromDeviceEnabled&&e.isAppFromDevice,s=e.isAppForIosVirtualDevice,n=((o=this.options.gridData)==null?void 0:o.type)===W.BROWSERSTACK&&!e.browserStackAppPath;if(t||s||n){let i={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:s,isMissingBrowserStackAppId:n}};return this.onTestIgnored(this.id,i),i}}setSessionTimeout(){return this.options.mode===Y.APPIUM?Math.max((0,gp.default)("180s"),this.options.getSessionTimeout):Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getTestPlayer(e,t){var o;let s=(o=this.userData)==null?void 0:o.projectId,n;try{O("before getSlotOnce retries");let i=0,a=await(0,fp.default)(async()=>{let p=Date.now();try{return await ne(this.getSlotOnce(e),this.options.getBrowserTimeout,Be.GET_BROWSER_TIMEOUT_MSG)}catch(m){let d={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw m instanceof Hr?Pt.info("could not get grid slot due to concurrency issue",d):Pt.error("error getting grid slot",{error:m,...d}),i++,await se(this.options.getBrowserTimeout-(Date.now()-p)),m}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1});O("after getSlotOnce retries"),O("before getBrowserOnce retries");let c=this.options.getBrowserRetries-i;if(!c)throw new Error("No free browser slots in desired grid");let l=0;n=await(0,fp.default)(async()=>{let p=Date.now(),m=this.initPlayer(e);try{a=await Cf(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1}),this.options.gridData.provider=a.provider,this.options.gridData.host=a.host,this.options.gridData.failedGetBrowserAttempts=l;let d=this.setSessionTimeout();O("before getBrowserOnce");let g=await ne(this.getBrowserOnce(e,t,m,a),d,Be.GET_BROWSER_TIMEOUT_MSG);return O("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,s),m||g}catch(d){let g={provider:a.provider,host:a.host,failedGetBrowserAttempts:l,id:this.options.gridData.gridId,type:a.type},f=this.options.mode===Y.APPIUM?"device":"browser";throw Pt.error(`error getting ${f} from grid`,{error:d,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:g}),Q.onGetBrowserFailure(this.id,s,++l),m.onDone(),!(d instanceof Tt)&&this.options.mode!==Y.APPIUM&&await se(this.options.getBrowserTimeout-(Date.now()-p)),d}},{retries:c-1,minTimeout:0,factor:1}),O("after getBrowserOnce retries")}catch(i){throw await Fn(this.id,this.releaseSlotOnTestFinished,s,n),i instanceof Tt?i:i instanceof wt?new fr(i,mp):new fr(i,Wt)}return n}async runTest(e,t,s){var p;O("inside runTest");let n=(p=this.userData)==null?void 0:p.projectId,o=this.handleQuarantine(e);if(o)return o;let i=Yr(this.options)&&this.handleMobileTest(e);if(i)return i;O("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,s,e.retryKey,a);e.baseUrl=c.config.baseUrl;let l=await this.getTestPlayer(e,t);try{return await this.runTestOnce(e,l)}finally{await Fn(this.id,this.releaseSlotOnTestFinished,n,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var d,g;let e=()=>process.nextTick(()=>this.run()),t=async(f,h,y)=>{var A,_;if(Ke(f,this.options)||!h.isFFAllowAppFromDeviceEnabled&&h.isAppFromDevice||h.isAppForIosVirtualDevice||Yr(this.options)&&((A=this.options.gridData)==null?void 0:A.type)===W.BROWSERSTACK&&!h.browserStackAppPath)return e();let w=h.sessionId,S=R=>y==null?void 0:y.message.includes(R),b=y&&y instanceof fr,v=y&&(S(rb)||S(sb)),I=!f.success&&(h.hasMoreRetries()&&!b&&!v||v&&h.hasMoreTimeoutRetries());try{let R=h.retryKey;f.testRetryKey=R;let L=h.getAppSource;return await this.onTestCompleted(this.id,this.testId,f,w,I,L),this.executionQueue.hasMoreTests()&&!((_=this.options.lightweightMode)!=null&&_.general)&&await se(dR),await this.runTestCleanup(),I?(v?await h.startNewTimeoutRetry():await h.startNewRetry(),Pt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:v,testRetryKey:R,totalRetries:h._totalRetryCount}),this.testResultId=h.testResultId,await p(h,I)):await e()}catch(R){if(R instanceof Gt)return;Pt.error("failed to process test result",{error:R}),e();return}},s=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
415
|
-
Please make sure the CLI has stable access to the internet. ${ac()?"(Internal: network connectivity test failed)":""}`,n=f=>{let{DEVICE_OS_VERSION_TOO_LOW:h,APP_NOT_EXIST_ON_DEVICE:y,APP_NEVER_STARTED:w}=gc,S=f instanceof Error?f.message:f;return S.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),S.includes(tb)?{errorType:Un,reason:"Test couldn't get device, time"}:S.includes(y)?{errorType:fa,reason:"app doesn't exist on device"}:S.includes(w)?{ErrorType:fa,reason:"app never started, check app permission or app activity"}:S.includes(h)?{ErrorType:fa,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:fa,reason:S}},o=(f,h)=>{let y=this.options.mode===Y.APPIUM?"device":"browser";if(!h&&M.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:lR,reason:s()};let w=f instanceof Error?f.message:f;if(w.includes(tb))return{errorType:Un,reason:`Test couldn't get ${y}`};if(w.includes(rb))return{errorType:Un,reason:"Test couldn't be started"};if(w.includes(sb)){if(!this.testRunTimeout)return{errorType:Un,reason:"Test timeout reached: test is too long"};let S=ob.default.duration(this.testRunTimeout,"milliseconds"),b=Math.floor(S.asMinutes()),v=S.seconds(),I=b>0?` ${b} min`:"",A=v>0?` ${v} sec`:"";return{errorType:Un,reason:`Test timeout reached (timeout:${I}${A}): test is too long`}}if(f instanceof fr&&f.type){if(f.type===mp)return{errorType:mp,reason:`Test couldn't get ${y} from grid - ${f.message}`};if(f.type===Wt)return{errorType:Wt,reason:`Failed to create new session - ${f.message}`}}return"type"in f&&f.type===uR?{errorType:Wt,reason:"Session terminated, it is possible that the cli could not connect to the grid to send keep-alive requests for a prolonged period"}:"failure"in f&&f.failure instanceof Wr?{errorType:Wt,reason:`Test couldn't get ${y} from grid - ${f.failure.message}`}:/SeleniumError: connect ECONNREFUSED/.test(f.message)||/Couldn't connect to selenium server/.test(f.message)?{errorType:Wt,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(f.message)?{errorType:Wt,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(f.message)?{errorType:Wt,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(f.message)?{errorType:Wt,reason:`Session could not be created, please check that the ${y} you requested is supported in your plan`}:{errorType:pR,reason:w}},i=async(f,h)=>{var v;let y=await ic();!y&&M.flags.warnOnBadNetwork.isEnabled()&&console.warn(s()),Pt.warn("error on run",{err:f});let w=(v=this.userData)==null?void 0:v.projectId,{errorType:S,reason:b}=this.options.mode===Y.APPIUM?n(f):o(f,y);il(w,this.testResultId,this.testId,{status:Ws.COMPLETED,success:!1,reason:b,errorType:S,testRetryKey:h.retryKey,setupStepResult:{status:Ws.COMPLETED,success:!1,reason:b,errorType:S}},h.remoteRunId),await t(fR(this.testId,this.testName,this.testResultId,b),h,f)},a=async(f,h)=>{var v;let y=this.testId,w=this.testResultId,S=(v=this.userData)==null?void 0:v.projectId,b=this.branch;if(!y||!w||!S||!b)return Pt.warn("Test failed. Not enough data to recover results via API",{err:f}),i(f,h);try{let I=await Rr(y,w,S,b);if(Pt.warn("Test failed. Got results via API",{err:f,testResult:nb.default.omit(I,gR)}),I&&I.status===Ws.COMPLETED)return await t(I,h);throw f}catch(I){return I!==f&&Pt.error("Failed to fetch test results from server",{testId:y,resultId:w,projectId:S,branch:b,err:I}),i(f,h)}},c=this.options.disableSockets||((d=this.options.lightweightMode)==null?void 0:d.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),l=this.options.disableSockets||((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep),p=async(f,h)=>{try{await Promise.all([!l&&Cs.joinToRemoteStep(this.testResultId),!c&&kt.joinToTestResult(this.testResultId,this.testId)]),f.validateRunConfig();let y=await this.runTest(f,this.customExtensionLocalLocation,h),w=await t(y,f);return O("After onRunComplete"),w}catch(y){return a(y,f)}finally{l||Cs.unlistenToRemoteStep(this.testResultId)}},m=this.executionQueue.getNext();return m?(this.testId=m.testId,this.testName=m.testName,this.testResultId=m.testResultId,this.overrideTestConfigId=m.overrideTestConfigId,this.testRunConfig=m.runConfig,this.branch=m.branch,p(m)):this.onQueueCompleted()}}});var ib={};$(ib,{WorkerSelenium:()=>hp});function yR(r){let{playback:e}=re().commonConstants;function t(s){r.playbackManager.on(s,()=>{O(`Got event ${s}`)})}Object.values(e).forEach(t)}var ha,hR,hp,ab=T(()=>{"use strict";j();Le();ga();U();jt();Vo();ie();_u();V();na();Ee();ha=x("worker-selenium"),hR=1e9,hp=class extends Ct{initPlayer(t){return new _n(this.id,t.runParams,this.options.shouldMonitorPerformance,t.automationMode,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,s,n,o){O("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new vs(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await i.init(this.options,this.testName,this.testRunConfig,o,s,this.executionId,this.testResultId,t.seleniumPerfStats,l,this.lambdatestService),O("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),O("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,hR),await this.windowUtils.validatePageIsAvailable(),O("in WorkerSelenium after navigate")}catch(l){let p=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=l.message&&l.message==="invalid argument";throw l instanceof Tt||p||m?new Tt(`Page '${c}' is not available`):(ha.error("failed to navigate to page",{baseUrl:c,err:l}),l)}}async runTestOnce(t,s){var p;let n=re(),{driver:o,sessionPlayer:i}=s,a=n.manifestVersion||"runner";Q.onWaitToTestComplete(this.id,this.isCodeMode),yR(i),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&i.setSfdcCredential(t.sfdcCredential),n.localAssetService&&n.localAssetService.initialize({serverUrl:this.options.localRCASaver});let c=null;(p=this.options.lightweightMode)!=null&&p.preloadTests&&(c=(await dn(this.options))[this.testId]);let l=async()=>{if(t.automationMode==="codeful"){i.callOrderScheduler?i.callOrderScheduler.schedule(()=>t.waitForExecutionStartedFinished(),{key:`test-result:${this.userData.projectId}:${this.testResultId}`}):await t.waitForExecutionStartedFinished(),O("right before playTestByCode");let d=new Promise((g,f)=>{i.playTestByCode(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,a,g,!1,this.overrideTestConfigId,this.branch,t.code,t.testName).catch(f)});return ne(d.then(g=>(O("right after playTestByCode"),g)),this.testRunTimeout,Be.TEST_COMPLETE_TIMEOUT_MSG).catch(g=>{var f;throw g instanceof te&&((f=i.stopPlayingOnTestTimeout)==null||f.call(i)),g}).then(g=>(g.resultId=this.testResultId,g))}let m=!1;return ne(new Promise((d,g)=>{i.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,a,d,!1,this.overrideTestConfigId,this.branch,m,t.remoteRunId,void 0,void 0,c).catch(g)}),this.testRunTimeout,Be.TEST_COMPLETE_TIMEOUT_MSG).catch(d=>{var g;throw d instanceof te&&((g=i.stopPlayingOnTestTimeout)==null||g.call(i)),d}).then(async d=>{n.localAssetService&&await n.localAssetService.drain(),d.stepsResults=null,d.resultId=this.testResultId,o.isAlive()||(ha.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),d.gridIssues="could not validate grid is alive");let g=o.maxKeepAliveGap();g>=3e4&&(ha.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),d.keepAliveIssue=g);let h={...d,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h})};o.start(),O("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,s),O("right after super.runTestOnce in workerSelenium");let m=await l();return O("right after runSeleniumTest"),m}catch(m){throw ha.error("failed to run test once",{err:m}),m}}}});var ya,cb=T(()=>{"use strict";ya=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 yp,ba,lb=T(()=>{"use strict";U();yp=x("mobile-frame-locator-mock"),ba=class{foundFrameCallback(){return yp.info("foundFrameCallback-mock invoked"),{}}locate(){return yp.info("locate-mock invoked"),{}}async findFrame(){return yp.info("findFrame-mock invoked"),{}}}});var bR,TR,Ta,ub=T(()=>{"use strict";bR=E(require("webdriverio"));cb();Mu();U();Fu();Uu();Ee();Hu();lb();Gu();TR=x("appium-test-player"),Ta=class{constructor(e,t,s,n,o=bR,i=void 0,a=void 0){this.id=e;this.driver=o;let{sessionPlayer:c,commonConstants:l,stepActionFactory:p,MobileLocateElementPlayer:m}=re(),d=new Ss(this.driver);this.stepActionFactory=new p(d),sa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Ps(Oi()),this.sessionPlayer=new c(e,new ya,null,null,ba,Ai,m,null,d,this.stepActionFactory,this.playbackTimeoutCalculator,null,n),this.sessionPlayer.setShouldMonitorPerformance(Boolean(s)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=a,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,s,n){}async onDone(){var e,t;try{await((t=(e=this.driver)==null?void 0:e.activeSession)==null?void 0:t.deleteSession())}catch(s){TR.error("error while deleting appium session",{error:s})}finally{let{commonConstants:s}=re();this.sessionPlayer.playbackManager.off(s.playback.RESULT),this.sessionPlayer=null,this.stepActionFactory=null,this.driver=null}}getSessionId(){var e,t;return(t=(e=this.driver)==null?void 0:e.activeSession)==null?void 0:t.sessionId}}});var db={};$(db,{WorkerAppium:()=>bp});var pb,jn,bp,mb=T(()=>{"use strict";pb=E(require("jsdom"));pe();be();wi();ga();U();jt();ub();Ee();yu();ie();jn=x("worker-appium"),bp=class extends Ct{initPlayer(e){return new Ta(this.id,e.runParams,this.options.shouldMonitorPerformance,e.automationMode,void 0,e.retryCount,e.previousTestResultId)}async getBrowserOnce(e,t,s,n){var h;Q.onGetSession(this.id,this.testName,e.runMode);let{driver:o}=s,i=this.options.projectData.type,a=await e.getNativeAppData(),c=i==="android"?e.androidActivityWait:null,l=e.nativeAppLink,{type:p,host:m}=this.options.gridData,d=!!(W.TESTIM_HEADSPIN===p&&e.headspinAppPath),g=!!(W.BROWSERSTACK===p&&e.browserStackAppPath),f=!!(W.SAUCELABS===p&&e.getSauceLabsAppPath(m));if(g&&(l=e.browserStackAppPath),d&&(l=e.headspinAppPath),f&&(l=e.getSauceLabsAppPath(m)),this.options.appId&&p!==W.BROWSERSTACK){let{project:y,appId:w}=this.options,S=await Jc({appId:w,projectId:y});if(!S)throw jn.error("mobile app not found",{appId:w,projectId:y}),new Error("mobile app not found");l=`${me}/storage${S.filePath}?access_token=${this.options.authData.token}`}try{let y={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(h=this.options.projectData)==null?void 0:h.name}-${this.options.project}`},w={projectType:i,nativeApp:a,appPath:l,androidActivityWait:c,sessionTags:y,gridInfo:n,options:this.options,testRunConfig:this.testRunConfig,isHSAppIdExists:d},S;if(this.options.skipLoadBalancer&&this.options.deviceUdid){this.options.lockDevice&&await hg(n,this.options.deviceUdid);let b=await Ag(w);S=await o.remote(b)}else{let b=Cg(w);S=await o.remote(b)}Object.assign(o,{activeSession:S}),await Tg(e,S,this.options),jn.info(`init new appium session testName: ${this.testName}`,{sessionId:S.sessionId,testResultId:this.testResultId,nativeApp:a})}catch(y){throw jn.error("failed to start application",{err:y}),y}}getServerAddressFromGrid(){let{host:e,port:t,accessToken:s,type:n}=this.options.gridData;return n===W.TESTIM_HEADSPIN?`https://${e}:${t}/v0/${s}/wd/hub`:`https://${e}:${t}/wd/hub`}getDirectAddressConnection(e){let{directConnectProtocol:t,directConnectHost:s,directConnectPort:n,directConnectPath:o}=e;if(t&&s&&n&&o)return`${t}://${s}:${n}${o}`}async runTestOnce(e,t){let s=re(),{sessionPlayer:n}=t,o=t.driver,i=s.manifestVersion||"runner";Q.onWaitToTestComplete(this.id,this.isCodeMode),n.playbackManager.executionId=e.executionId,n.playbackManager.executionName=e.executionName;let a;if(this.options.skipLoadBalancer){let{protocol:p,hostname:m,port:d,path:g}=await hu(this.options.gridData,this.options.deviceUdid);a=`${p}://${m}:${d}${g}`}else a=this.getDirectAddressConnection(o.activeSession.capabilities)||this.getServerAddressFromGrid();let c=new pb.JSDOM("").window.DOMParser;n.playbackManager.appiumSessionData={env:"remote",capabilities:o.activeSession.capabilities,sessionId:o.activeSession.sessionId},n.playbackManager.appiumApi=new s.AppiumApi(a,o.activeSession.sessionId,c),s.localAssetService&&s.localAssetService.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let m=await new Promise((g,f)=>n.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,i,g,!1,this.overrideTestConfigId,this.branch,!1,e.remoteRunId,void 0,void 0,void 0).catch(f));return s.localAssetService&&await s.localAssetService.drain(),m.stepsResults=null,m.resultId=this.testResultId,{...m,...e.seleniumPerfStats.getStats()}}catch(p){throw jn.error("error while running appium tests",{err:p}),p}};try{return await super.runTestOnce(e,t),await l.call(this)}catch(p){throw jn.error("failed to run test once",{err:p}),p}}}});var wa,fb=T(()=>{"use strict";j();In();V();wa=class{constructor(e){this.id=e;this.driver=new Pr}async onDone(){try{await ne(this.driver.end(),12e4)}catch(t){t instanceof te&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var gb,va,hb=T(()=>{"use strict";gb=E(require("ws"));j();va=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 gb.default(this._cdpUrl,{timeout:e}),s=it(o=>{t.once("open",o)}),n=it(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([s,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),s=this._cdpCallbacks.get(t.id);s&&(this._cdpCallbacks.delete(t.id),t.error?s.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?s.reject(new Error(t.result.exceptionDetails.exception.description)):s.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,s){let n=await this.initCDPWebsocket();this._lastWsId||(this._lastWsId=0);let o=this._lastWsId++,i=new Promise((c,l)=>{this._cdpCallbacks.set(o,{resolve:c,reject:l})}),a={method:e,params:t,id:o};return s&&Object.assign(a,{sessionId:s}),n.send(JSON.stringify(a)),i}}});var Sa,Tp,Ea,yb=T(()=>{"use strict";j();Sa=E(require("chrome-launcher"));wi();hb();ln();Tp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new va}async init(e,t,s,n,o,i,a,c,l,p){var f,h,y,w;let m=Ti(e,t,s,n,o,i,a),d=[...((f=m.desiredCapabilities)==null?void 0:f.chromeOptions.args)??[],...((w=(y=(h=m.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:w.args)??[],...Sa.Launcher.defaultFlags().filter(S=>S!=="--disable-extensions")];this.chrome=await Sa.launch({chromeFlags:d,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 g=await wr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(g),is(()=>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}},Ea=class{constructor(e){this.id=e;this.sessionId=J();this.driver=new Tp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var bb={};$(bb,{WorkerExtension:()=>Bn});var ht,Bn,wp=T(()=>{"use strict";Le();V();ga();j();U();jt();ie();fb();yb();ht=x("worker-ext"),Bn=class extends Ct{initPlayer(){return this.options.useChromeLauncher?new Ea(this.id):new wa(this.id)}async _getBrowserOnce(e,t,s,n){var i;let{driver:o}=s;try{return await o.init(this.options,this.testName,this.testRunConfig,n,t,this.executionId,this.testResultId,e.seleniumPerfStats,(i=this.options.lightweightMode)==null?void 0:i.general,this.lambdatestService)}catch(a){throw ht.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,s,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,s,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async runTestOnce(e,t){let{testResultId:s,executionId:n,testId:o}=this;O("WorkerExtension runTestOnce");let i=async p=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ne(e.runTestUsingCDP(p.cdpTestRunner),m,Be.TEST_START_TIMEOUT_MSG)}catch(d){if(!(d instanceof te))throw d;return ht.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:s}),await e.checkViaRestAPIIfTestStarted()}},a=async(p,m,d)=>{try{let g=await p.url(m);return d.driverUrlFinished=!0,g}catch(g){throw ht.error("error from driver.url",{err:g,testResultId:s,executionId:n,testId:o,url:m,urlLength:m.length}),g}},c=async p=>{let m=await e.onStarted(this.options.testStartTimeout);return p.testRunHandlerOnStartedHadFinished=!0,m},l=async()=>{var g;if(O("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id,this.isCodeMode);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(f){throw ht.warn("failed to run test via CDP",{err:f}),f}}let{driver:m}=t,d={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let f=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await ne(Promise.all([a(t.driver,f,d),c(d)]),this.options.testStartTimeout,Be.TEST_START_TIMEOUT_MSG)}catch(y){if(!(y instanceof te))throw y;ht.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:s,executionId:n,testId:o,...d}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id,this.isCodeMode);let h=y=>{throw e.onCompletedCleanup(),ht.warn("on browser closed error detected",{err:y,testResultId:s,executionId:n,testId:o}),m.unregisterToClosedBrowser(h),y.type=Hs.BROWSER_CLOSED,y};m.registerToClosedBrowser(h);try{let y=await ne(e.onCompleted(),this.testRunTimeout,Be.TEST_COMPLETE_TIMEOUT_MSG);m.unregisterToClosedBrowser(h),this.lambdatestService.isLambdatestRun()&&await m.executeJS(`lambda-status=${y.success?"passed":"failed"}`).catch(()=>{}),m.isAlive()||(ht.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),y.gridIssues="could not validate grid is alive");let w=m.maxKeepAliveGap();return w>=3e4&&(ht.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),y.keepAliveIssue=w),{...y,...e.seleniumPerfStats.getStats()}}catch(y){throw ht.warn("timeout wait until test completed",{err:y,testResultId:s,executionId:n,testId:o}),new Error(y)}finally{m.unregisterToClosedBrowser(h)}}catch(f){throw ht.warn("failed to start url",{err:f}),new Error(f)}};t.driver.start();try{return await super.runTestOnce(e,t),O("WorkerExtension super.runTestOnce"),await l()}catch(p){throw ht.error("failed to run test",{err:p,testId:e.testId,resultId:e.testResultId}),p}}}});var Tb={};$(Tb,{WorkerExtensionSingleBrowser:()=>vp});var wR,vR,vp,wb=T(()=>{"use strict";Le();j();U();dp();jt();wp();wR=x("base-worker"),vR=500,vp=class extends Bn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await Fn(this.id,this.releaseSlotOnTestFinished,t,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,s,n,o){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,s,n,o)}async getTestPlayer(t,s){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(wR.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,s)),this.testPlayer}async runTest(t,s,n){let o=this.handleQuarantine(t);if(o)return o;O("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,s);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 se(vR)}}});function ER(r,e){e===0?r():setTimeout(r,e*Xp)}var Ep,Ra,vb=T(()=>{"use strict";In();j();pe();Le();uu();Rt();Pu();V();U();ie();eb();Ep=x("parallel-worker-manager"),Ra=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e){case Y.SELENIUM:return(ab(),ve(ib)).WorkerSelenium;case Y.APPIUM:return(mb(),ve(db)).WorkerAppium;default:return Ii.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(wb(),ve(Tb)).WorkerExtensionSingleBrowser:(wp(),ve(bb)).WorkerExtension}}createWorkers(e,t,s,...n){let o=this.getWorkerType(s),i=()=>{try{return O("before new Worker",s),new o(t,...n)}finally{O("after new Worker",s)}};return Array.from(new Array(e),i)}async runTests(e,t,s,n,o,i,a,c,l){if(e&&e.length===0)return;let p=!1,m=0,d=g=>new Promise(f=>{var dr,At,Mr,P,D,F;let h=o.project,y=new ma(s,n,e,o,i,t),w={},S=e.length,b=(dr=o.company)==null?void 0:dr.companyId,v=(At=o.company)==null?void 0:At.name,I=o.source||"cli",A=o.user,_=(Mr=o.company)==null?void 0:Mr.planType,R=(P=o.company)==null?void 0:P.isStartUp,L=(D=o.projectData)==null?void 0:D.name,C=(F=o.projectData)==null?void 0:F.type,N=o.lightweightMode,B=yr(o),K=(G,ge,he,La,$n,Da)=>(m++,Gf({executionId:s,projectId:h,testId:ge,resultId:he,companyId:b,companyName:v,projectName:L,companyPlan:_,sessionType:B,source:I,user:A,lightweightMode:N,isStartUp:R,projectType:C,appSource:Da}),t.testStartAndReport(G,s,he,La,$n)),X=async(G,ge,he,La,$n,Da)=>{var Dp,Np,Mp;m--;let yt={...(N==null?void 0:N.onlyTestIdsNoSuite)&&{show:!0},...he.seleniumStats&&{seleniumStats:he.seleniumStats},...he.gridIssues&&{gridIssues:he.gridIssues},...he.keepAliveIssue&&{keepAliveIssue:he.keepAliveIssue},...o.host&&{gridHost:o.host}};if(he.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(he.seleniumPerfMarks),delete he.seleniumPerfMarks),o.grid||o.gridId?(yt.gridName=o.grid||((Dp=o.gridData)==null?void 0:Dp.name),yt.gridType=(Np=o.gridData)==null?void 0:Np.type,yt.gridProvider=(Mp=o.gridData)==null?void 0:Mp.provider):o.useLocalChromeDriver?(yt.gridName="local-chrome-driver-from-options",yt.gridType="local-chrome"):o.useChromeLauncher?(yt.gridName="chrome-launcher-from-options",yt.gridType="local-chrome"):o.browserstack?yt.gridName="browserstack-from-options":o.saucelabs&&(yt.gridName="saucelabs-from-options"),await t.testEndAndReport(G,he,s,La,$n,yt).catch(ST=>Ep.error("testEndAndReport threw an error",{err:ST})),$n)return;w[he.resultId]=he,Vf({executionId:s,projectId:h,testId:ge,resultId:he.resultId,result:he,companyId:b,companyName:v,projectName:L,companyPlan:_,sessionType:B,source:I,user:A,lightweightMode:N,logger:Ep,isStartUp:R,projectType:C,appSource:Da}),l&&!he.success&&(y.stop(),p=!0),(Object.keys(w).length===S||p&&m===0)&&f(w)},ee=(G,ge)=>{w[ge.resultId]=ge,t.onTestIgnored(G,ge.resultId),m--,(Object.keys(w).length===S||p&&m===0)&&f(w)},fe=(G,ge)=>t.onGridSlot(G,ge);o.userData={loginData:Object.assign({},Mt(),{refreshToken:Po(),authData:Mt(),token:g}),projectId:o.project,company:o.company,servicesUrl:me},O("in localStrategy before createWorker"),this.createWorkers(c,y,o.mode,o,this.customExtensionLocalLocation,s,K,X,fe,ee).forEach((G,ge)=>{O("before schedule worker.run after createWorkers"),ER(()=>{O("right before worker.run"),G.run()},ge)})});try{let g=await Kt(),f=await d(g);if(p)throw new Gt;return f}catch(g){throw Ep.error("failed running parallel workers",{executionId:s,err:g}),g}}}});var Ia,Eb=T(()=>{"use strict";la();Ia=class extends ur{init(e){return super.initNewSocket(e,"real-data")}emitJoinRoom(e,t){this._socket.emit("testResult:listen",{query:`projectId=${t}&runId=${e}`})}joinToTestResultsByRunId(e,t){this.joinRoom(e,t),this.emitJoinRoom(e,t)}stopListenToTestResultsByRunId(e){this.leaveRoom(e),this._socket.emit("testResult:listen:stop",{})}listenToTestResultsByRunId(e){function t(s){e(s.data)}this._socket.on("testResult:changes",t.bind(this))}}});var Sp,Rp,xa,Sb=T(()=>{"use strict";Nn();ie();Te();Eb();({TEST_RESULT_CREATED:Sp,TEST_RESULT_UPDATED:Rp}=et),xa=class{constructor(){M.flags.useNewWSCLI.isEnabled()||(this.realDataServiceSocketIO=new Ia)}init(e){return M.flags.useNewWSCLI.isEnabled()?Promise.resolve():this.realDataServiceSocketIO.init(e)}joinToTestResultsByRunId(e,t){if(M.flags.useNewWSCLI.isEnabled())return $e.addFilter(e,{runId:e},[Rp,Sp],!0);this.realDataServiceSocketIO.joinToTestResultsByRunId(e,t)}stopListenToTestResultsByRunId(e){if(M.flags.useNewWSCLI.isEnabled()){$e.removeFilter(e,[Rp,Sp]);return}this.realDataServiceSocketIO.stopListenToTestResultsByRunId(e)}listenToTestResultsByRunId(e,t){if(M.flags.useNewWSCLI.isEnabled()){$e.listenTo(e,[Rp,Sp],s=>s.runId===e,s=>t(s));return}this.realDataServiceSocketIO.listenToTestResultsByRunId(t)}}});async function xb(r,e){var t;if((t=r.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&r.testId)return{tests:[r.testId.map(n=>({testId:n,testConfig:{},resultId:J()}))]};if(r.files.length>0){let{buildCodeTests:s}=await Promise.resolve().then(()=>(zu(),wy)),n={};if(r.webpackConfig){let o=Ib.join(process.cwd(),r.webpackConfig);n=require(o)}return s(r.files,n,{baseUrl:r.baseUrl})}return await Kc({projectId:r.project,labels:r.label,testIds:r.testId,testNames:r.name,testConfigNames:r.testConfigNames,suiteNames:r.suites,suiteIds:r.suiteIds,branch:e,rerunFailedByRunId:r.rerunFailedByRunId,testConfigIds:r.testConfigIds,intersections:r.intersections})}function Ip(r){let e=Object.keys(r).length,t=Object.keys(r).reduce((s,n)=>s+(r[n].success===!0?1:0),0);return e===t}async function xp(r,e){let t=r.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],s=Rb.difference(Gs(r,e),t);if(s.length>0)throw ut("invalid-config-run",{browser:s.join(", "),mode:"runner"}),new k(`browser type <${s}> is not supported in ${r.mode} mode.`);return e}var Rb,Ib,kb=T(()=>{"use strict";Rb=E(require("lodash")),Ib=E(require("path"));j();cs();be();V()});var Dr,Pb,SR,ka,RR,Pa,Cb=T(()=>{"use strict";Dr=E(require("lodash"));j();U();pe();ie();Le();ds();zl();uu();be();Rt();jt();dg();V();vb();Sb();kb();({testRunStatus:Pb,CLI_MODE:SR}=Dt),ka=x("test-plan-runner"),RR=1e3*60*5,Pa=class{constructor(e){this.startTime=Date.now();this.workerManager=new Ra(e)}async runTestAllPhases(e,t,s,n,o,i,a,c){let l={},p=Mt(),m=async()=>{let y=o.beforeParallel||1,w=!0,S=await this.workerManager.runTests(e,c,i,a,o,n,p,y,w);Object.assign(l,S)},d=async()=>{let y=eo||o.parallel,w=!1;O("right before this.workerManager.runTests");let S=await this.workerManager.runTests(t,c,i,a,o,n,p,y,w);O("right after this.workerManager.runTests"),Object.assign(l,S)},g=async()=>{let y=o.afterParallel||1,w=!1,S=await this.workerManager.runTests(s,c,i,a,o,n,p,y,w);Object.assign(l,S)},f=yr(o);qf({executionId:i,projectId:o.project,sessionType:f}),O("right before runBeforeTests");try{return await m(),O("right before runTestPlanTests"),await d(),O("right after runTestPlanTests"),await g(),l}catch(y){if(ka.error("error running test plan",{err:y}),y instanceof Gt)return c.markAllQueuedTests(i,de.ABORTED,"aborted",!1);throw y}finally{await h()}async function h(){var w,S,b,v;if((w=o.lightweightMode)!=null&&w.disablePixelValidation)return;if(o.mode===SR.SELENIUM){let{EyeSdkBuilder:I}=(await Promise.resolve().then(()=>(Ee(),Ir))).getSessionPlayer();await I.closeBatch(i);return}let y;try{if(!((v=(b=(S=o.company)==null?void 0:S.activePlan)==null?void 0:b.premiumFeatures)!=null&&v.applitools)||(y=await pl(o.project),Dr.default.isEmpty(y)||!i))return;let{runKey:I,url:A}=y;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:A,apiKey:I}})}catch{}}}async initRealDataService(e){let t=new xa;return await t.init(e),t}async listenToTestCreatedInFile(e,t,s,n){let o={};e.joinToTestResultsByRunId(s,t);let i=!0;return await new Promise(c=>{let l=p=>{i=!1,c(p)};e.listenToTestResultsByRunId(s,p=>{let m=p.id;if(!n.getTestResult(m)){let f=o[m],h=Dr.default.merge({},f,p,{resultId:m});if(o[m]=h,!f||f.status!==p.status){let w=(n.getTestResult(h.parentResultId)||{workerId:1}).workerId;[Pb.RUNNING].includes(p.status)&&Q.onTestStarted(h,w),[Pb.COMPLETED].includes(p.status)&&(h.duration=h.endTime-h.startTime||0,Q.onTestFinished(h,w))}}let d=!Object.values(o).some(f=>["QUEUED","RUNNING"].includes(f.runnerStatus)),g=!Object.values(n.getAllTestResults()).some(f=>["QUEUED","RUNNING"].includes(f.status));if(d&&g)return l(Object.values(o));if(g&&!d)return se(1e4).then(()=>{i&&l(o)})})})}async initRealDataServiceAndListenToTestsCreatedInFile(e,t,s){let n=await this.initRealDataService(e);return this.listenToTestCreatedInFile(n,e,t,s)}async runTestPlan(e,t,s,n,o,i,a,c){var A,_,R;let l=J(),p=n.project;za(l),e.forEach(L=>Object.assign(L,{isBeforeTestPlan:!0})),s.forEach(L=>Object.assign(L,{isAfterTestPlan:!0}));let m=[...e,...t,...s],d=new bi(m,n,i,a),g=Dr.default.chain(m).map(L=>{var C;return((C=L.overrideTestConfig)==null?void 0:C.name)||""}).uniq().compact().value(),f=(g==null?void 0:g.length)===1?g[0]:null,h=n.files.length>0,y=(A=n.lightweightMode)!=null&&A.onlyTestIdsNoSuite?[]:m.map(L=>L.name),w=(_=n.lightweightMode)!=null&&_.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:s}:d.executionStart(l,p,this.startTime,o,y),S;h&&(S=this.initRealDataServiceAndListenToTestsCreatedInFile(p,l,d)),O("before testListInfoPromise");let b=await w;(R=n.lightweightMode)!=null&&R.onlyTestIdsNoSuite||Q.onTestPlanStarted(b.beforeTests,b.tests,b.afterTests,o,l,c,f,h),O("before runTestAllPhases");let v=await this.runTestAllPhases(b.beforeTests,b.tests,b.afterTests,a,n,l,o||"All Tests",d),I=await ne(S,RR).catch(async()=>{var C;ka.warn("timed out waiting for child results on websocket. using REST fallback",{projectId:p,executionId:l});let L=await on(p,"testResult",`runId=${l}&sort=runOrder`);return Dr.default.chain(((C=L==null?void 0:L.data)==null?void 0:C.docs)||[]).groupBy("parentResultId").omit("undefined").values().flatten().value()});return O("before executionEnd"),await d.executionEnd(l),O("after executionEnd"),{results:v,executionId:l,testPlanName:o,configName:f,childTestResults:I}}async runTestPlans(e,t){ka.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function s(p){return Dr.default.flattenDeep(Object.values(p)).reduce((m,d)=>m.concat(d.beforeTests,d.tests,d.afterTests),[])}let n={},o={},i=e.project,a=await zc(i,e.testPlan,e.testPlanIds,t,e.intersections),c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new k(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new k(`no test to run in test plan ${e.testPlan}`)}return await xp(e,s(l)),await ce(c,async p=>{let m=p.testPlanId;n[m]={};let d=Object.assign({},e);d.baseUrl=e.baseUrl||p.startUrl,d.host=e.host,d.port=e.port,d.gridId=e.gridId||p.gridId,e.grid&&delete d.gridId,d.gridData=await xf(e,p);let g=d.overrideExecutionName||p.name;return await ce(l[m],async f=>{let h=await this.runTestPlan(f.beforeTests,f.tests,f.afterTests,d,g,m,t),y=e.files.length>0;Q.onTestPlanFinished(h.results,p.name,this.startTime,h.executionId,!1,y,h.childTestResults),n[m][h.executionId]=h.results;let w=Object.keys(n[m]).map(I=>({executionId:I,status:Ip(n[m][I])})),S=Object.keys(n[m]).map(I=>n[m][I]).reduce((I,A)=>Object.assign(I,A),{}),b=Ip(S);Object.assign(o,S);let v=b?w[0].executionId:w.find(I=>!I.status).executionId;return await Gc(i,m,{success:b,executions:w,executionId:v}),h})})}async runAnonymousTestPlan(e,t){var a;ka.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),O("before getSuite");let s=await xb(e,t);if(O("after getSuite"),!((a=s==null?void 0:s.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new k("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new k("No tests to run")}t="branch"in s&&s.branch||t;let n=s;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new k("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;return O("Right before validateConfig + runAnonymousTestPlan tests map"),await ce(s.tests,async c=>{if(e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}await xp(e,c),O("right before runTestPlan");let l=await this.runTestPlan([],c,[],e,o,null,t,i);O("right after runTestPlan");let p=e.files.length>0;return await Q.onTestPlanFinished(l.results,o,this.startTime,l.executionId,i,p,l.childTestResults),l})}async run(e){let t=hn(),s=[];Vs(e)?s=await this.runTestPlans(e,t):s=await this.runAnonymousTestPlan(e,t);let n=Dr.default.flattenDeep(s);return O("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),O("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var Ob={};$(Ob,{init:()=>GR,run:()=>WR});function xR(r){if(!kp.get(r,"company.activePlan.premiumFeatures.allowCLI")){let t=r.project;as(r.authData.uid,"cli-not-supported",{projectId:t}),console.warn("Testim CLI is not supported in this plan")}}async function kR(r){let e=r.project,t=await Yc(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"),as(r.authData.uid,"execution-quota-surpassed",{projectId:e}),new Fs}function PR(r,e){var o,i,a,c;if(lo(e.activePlan)==="free"){let l=r.parallel||1,p=((i=(o=e.activePlan)==null?void 0:o.premiumFeatures)==null?void 0:i.concurrency)||1;if(l>p)throw new k(`Cannot run with parallel ${r.parallel}. Max parallel value is ${p}`)}let s=r.retentionDays;if(!s)return;let n=(c=(a=e.activePlan)==null?void 0:a.premiumFeatures)==null?void 0:c.resultRetention;if(s>n)throw new k(`Retention days (${s}) cannot be greater than the company's retention days (${n}). Run aborted`)}async function CR(r){var e;if(!((e=r.lightweightMode)!=null&&e.disableQuotaBlocking))try{await Promise.all([kR(r),xR(r)])}catch(t){if([k,Fs].some(s=>t instanceof s))throw t;IR.error("could not validate cli account",{err:t})}}function AR(r){let e=Mt();return Pm({userId:e.uid,name:e.uid,traits:{projectId:r,company:{id:r,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function OR(r,{disableResults:e=!1,disableRemoteStep:t=!1}){if(M.flags.useNewWSCLI.isEnabled()&&!e&&!t)return $e.connect(r);if(!t){let{remoteStepService:s}=await Promise.resolve().then(()=>(ua(),Gy));await s.init(r)}if(!e){let{testResultService:s}=await Promise.resolve().then(()=>(pa(),zy));s.init(r)}}function _R(r,e){let{branch:t,autoDetect:s}=r;if(Af(e,s),!e&&!s)throw new k(`branch ${t} does not exist, run aborted.`)}async function LR(r){let{project:e}=r,t=hn();kp.get(r,"company.activePlan.premiumFeatures.ttaForSalesforce")&&(r.sfdcCredential=await Wc({projectId:e,branch:t}))}function DR(r,e){let{onprem:t,id:s,storageBaseUrl:n,storageType:o,name:i,activePlan:a={}}=e;if(t){let{mode:m,extensionPath:d,ext:g,playerPath:f}=r;if([Y.SELENIUM].includes(m)&&!f)throw new k("in selenium on prem mode --player-path must be provided");if(m==="extension"&&!d&&!g)throw new k("In extension on prem mode --ext or --extension-path must be provided")}let c=Boolean(a.isPoc),l=Boolean(a.isStartUp),p=lo(a);p==="free"&&(r.newBrowserWaitTimeout=r.newBrowserWaitTimeout<Ab?Ab:r.newBrowserWaitTimeout),M.setCompanyId(s),M.setIsPOC(c),M.setIsStartUp(l),M.setPlanType(p),xt.setPlanType(p),r.company={companyId:s,onprem:t,storageBaseUrl:n,storageType:o,name:i,planType:p,isPOC:c,isStartUp:l,activePlan:a}}function NR(r,e){if(Ur){r.editorUrl=Ur;return}r.editorUrl=e.editorUrl}function MR(r,e){r.allGrids=e}function FR(r,e){r.authData=e}function UR(r,e){let{id:t,name:s,type:n,defaults:o}=e;M.setProjectId(t),M.setProjectType(n),r.projectData={projectId:t,type:n,name:s,defaults:o}}async function jR(r){r.gridData=await kf(r)}async function BR(r){let{project:e}=r,t={projectId:e};r.overrideMappingFile&&(ut("user-override-file",t),r.mockNetworkRules=await hm(r.overrideMappingFile))}async function $R(r,e){O("in runner.js runRunner");let{project:t,remoteRunId:s,useLocalChromeDriver:n,useChromeLauncher:o}=r;s||(r.source=n||o?"cli-local":"cli"),await tf(),O("in runner.js after checkNpmVersion"),await CR(r),O("in runRunner before tunnel.connect"),await Zo(r),O("in runRunner after tunnel.connect");let a=await new Pa(e).run(r);return O("before tunnel.disconnect"),await ei(r),await fn.end(t),O("after tunnel.disconnect and gridService.keepAlive.end"),a}function HR(r){var e;xt.shouldShowFreeGridRunWarning((e=r.gridData)==null?void 0:e.type)&&console.log(`
|
|
413
|
+
`;t+="};",await st.promises.writeFile(r,t)}async function Qu(r,{mergeIntoExisting:e}={mergeIntoExisting:!1}){let t=await Or(process.cwd()),s=Xe.join(t,"locators","locators.js");await st.promises.mkdir(Xe.join(t,"locators")).catch(()=>null);for(let{name:o,id:i,elementLocator:a}of r)await st.promises.writeFile(Xe.join(t,"locators",`locator.${i}.json`),JSON.stringify({name:o,id:i,elementLocator:a}));let n=Object.fromEntries(r.map(({name:o,id:i})=>[o,i]));if(e){let o=await Ln();Object.assign(n,o)}await Ry(s,n)}async function Zu({fileSystem:r,bypassWebpack:e}={},t=void 0){let s=await Or(process.cwd());if(t!=null&&t.aborted)throw new Ie;let n=Xe.join(s,"functions.js");if(typeof e!="boolean"&&(e!=null&&e.testim)){let i=require("module"),a=i.prototype.require;i.prototype.require=function(l){return l==="testim"?e.testim:a.apply(this,arguments)};try{return delete require.cache[require.resolve(n)],require(n)}finally{i.prototype.require=a}}return(await zu([n],{output:{libraryTarget:"umd",library:"tdk",globalObject:"globalThis"},cache:{type:"memory"},mode:"development"},{},r,t)).tests[0][0].code}var Sy,Xe,st,Or,ep=T(()=>{"use strict";Sy=E(require("lodash")),Xe=E(require("path")),st=require("fs");V();Ku();Or=Sy.memoize(async r=>(await st.promises.readdir(r)).includes("tests")&&(await st.promises.stat(Xe.join(r,"tests"))).isDirectory()?Xe.join(r,"tests"):r)});async function lr(r,e,t){let s=BS(r.parameterNames.map(n=>n.displayName),e.incomingParams.as);return await Promise.all(s.map(n=>typeof n=="object"&&n.locatedElement?t(n):n))}function BS(r,e){let t=[];for(let s of r){let n=e.functionParameters.indexOf(s);t.push(e.functionArguments[n])}return t}var Dn=T(()=>{"use strict"});var xy={};$(xy,{execute:()=>$S});async function WS(r,e,t,s,n,o){var a;let i;try{let{WebDriver:c}=await le("selenium-webdriver");if(o.aborted)throw new Ie;let{Executor:l,HttpClient:m}=require("selenium-webdriver/http"),d=r.driver.client.options,p=d.path,f=`${d.protocol}://${d.hostname}:${d.port}`+p,h=new m(f),y=new c(r.getSessionId(),new l(h));await HS(y,r.driver);let S=await lr(t,s,v=>y.findElement({css:v.selector})),b=e.bind(null,y,...S);return i=function(){h.send=async function(){throw new Ie}},o.addEventListener("abort",i),await b(),{success:!0}}catch(c){return o.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,shouldRetry:!1,reason:(c==null?void 0:c.message)||c,extraInfo:(a=c==null?void 0:c.constructor)==null?void 0:a.name}}finally{i&&o.removeEventListener("abort",i)}}async function HS(r,e){if(e.cdpUrl){let t=await r.getAllWindowHandles();for(let s of t)if(await r.switchTo().window(s),await r.executeScript("return window.__isMainTestimTab"))break}}var $S,ky=T(()=>{"use strict";V();dt();Dn();$S=WS});var Py={};$(Py,{execute:()=>GS});async function VS(r,e,t,s,n,o){var a;let i;try{let c=await le("puppeteer");if(o.aborted)throw new Ie;let l=await c.connect({browserWSEndpoint:r.driver.cdpUrl,defaultViewport:null,product:"chrome"});if(o.aborted)throw l.disconnect(),new Ie;i=function(){l.disconnect()},o.addEventListener("abort",i);let m=await l.pages(),d;for(let y of m)if(await y.evaluate(()=>window.__isMainTestimTab)){d=y;break}let p=d||m.at(-1),f=await lr(t,s,y=>p.$(y.selector));return await e.bind(null,p,...f)(),{success:!0}}catch(c){return o.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,shouldRetry:!1,reason:(c==null?void 0:c.message)||c,extraInfo:(a=c==null?void 0:c.constructor)==null?void 0:a.name}}finally{i&&o.removeEventListener("abort",i)}}var GS,Cy=T(()=>{"use strict";V();dt();Dn();GS=VS});var Ay={};$(Ay,{execute:()=>qS});async function zS(r,e,t,s,n,o){var a;let i;try{let c=await le("playwright");if(o.aborted)throw new Ie;let l=await c.chromium.connect({wsEndpoint:r.driver.cdpUrl});if(o.aborted)throw l.disconnect(),new Ie;i=function(){l.disconnect()},o.addEventListener("abort",i);let p=(await(await l.newContext({viewport:null})).pages()).at(-1),f=await lr(t,s,y=>p.$(y.selector));return await e.bind(null,p,...f)(),{success:!0}}catch(c){return o.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,reason:(c==null?void 0:c.message)||c,extraInfo:(a=c==null?void 0:c.constructor)==null?void 0:a.name}}finally{i&&o.removeEventListener("abort",i)}}var qS,Oy=T(()=>{"use strict";V();dt();Dn();qS=zS});var Ly={};$(Ly,{execute:()=>KS});async function JS(r,e,t,s,n,o,i,a){function c(){r.sessionPlayer.stopPlaying()}a.addEventListener("abort",c);function l(C){if(o.parameterValues){let N=o.parameterValues.find(B=>B.type==="locate"&&B.id===C.locatorId);return{elementLocator:N.elementLocator,id:N.id,name:"Hybrid Step Locator"}}return C.locatedElement.shadowPath?C.locatedElement.shadowPath[0]:C}let m=await lr(o,t,l),d=e.bind(null,...m),p=J(),g=J(),f=t.testResultId,h=t.config.baseUrl,y=_y.cloneDeep(t);Object.assign(y,{loginData:s});let S=re().manifestVersion||"runner",b=!1,v=null,I="master",A=`Execute TDK Function '${o.functionName}'`,_=!0,R={fn:d,bypassSetup:!0,isBeforeOrAfterTest:!0,name:A,sourceCode:d.toString(),sourceName:d.name,testId:p,resultId:J()},L=typeof e.results=="boolean"&&!e.results;try{O("tdkHybridStepPlayback before addAllTabs"),n?(Object.assign(r.sessionPlayer.playbackAutUtils,{frameManager:n}),Object.assign(r.sessionPlayer,{frameManager:n})):await r.addAllTabs(null,{loadInfo:!0,checkForMainTab:!0,takeScreenshots:!L},[r.driver.initialUrl]),r.sessionPlayer.playbackManager.dontAssociateChildResult=!0,r.sessionPlayer.playbackManager.onlyLocalReporting=L,O("tdkHybridStepPlayback before playTestByCode");let C=await new Promise((N,B)=>{i==="agent"&&YS(r,N);function K(){B(new Ie),a.removeEventListener("abort",K)}a.addEventListener("abort",K),r.sessionPlayer.playTestByCode(p,g,f,h,y,S,N,b,v,I,[R],A,_).catch(B)});return O("tdkHybridStepPlayback after playTestByCode"),{success:C.success,shouldRetry:!1,resultInfo:{testId:p,executionId:g,resultId:R.resultId}}}catch(C){return{success:!1,error:C,shouldRetry:!1}}finally{a.removeEventListener("abort",c)}}function YS(r,e){let{commonConstants:t}=re();r.sessionPlayer.playbackManager.on(t.playback.START,({testResult:s})=>{let n=s.runnerStatus;Object.defineProperty(s,"runnerStatus",{get(){return n},set(o){n=o,o==="FINISHED"&&e(s)}})})}var _y,KS,Dy=T(()=>{"use strict";_y=E(require("lodash"));Le();j();V();Dn();Ee();KS=JS});var ia={};$(ia,{abort:()=>sp,execute:()=>Is,run:()=>ZS});async function Is(r,e,t,s,n,o="cli"){let i=new AbortController,{signal:a}=i;rp.set(e.stepResultId,i);try{O("before seleniumTestPlayer require");let[{SeleniumTestPlayer:c},{compileFunctionsLibrary:l}]=await Promise.all([Promise.resolve().then(()=>(na(),qu)),Promise.resolve().then(()=>(ep(),Iy))]),{functionName:m=""}=r,d={},p=!1,g=new c(e.id,d,p,Lt.CODEFUL,t);tp=g.sessionPlayer.codeSessionPlayer.proxy;let f=r.bypassWebpack?{testim:tp.wrappedSteps()}:!1;O("before compileFunctionsLibrary",{bypassWebpack:Boolean(r.bypassWebpack)});let h;try{h=await l({fileSystem:XS,bypassWebpack:f},a)}catch(w){return{success:!1,shouldRetry:!1,reason:`Unable to compile functions library. ${w.message}`,extraInfo:w.stack}}let y;if(f?y=h[m]:(global.globalThis.__testim=tp.wrappedSteps(),(0,eval)(h),y=globalThis.tdk[m]),O("after hybridFunction obtain and eval"),!y)return{success:!1,shouldRetry:!1,reason:`Could not find function '${m}' locally. Please make sure you have a functions.js file with a '${m}' function defined`,extraInfo:Object.keys(globalThis.tdk)};if(y.type==="selenium"){let{execute:w}=await Promise.resolve().then(()=>(ky(),xy));return await w(g,y,r,e,o,a)}if(y.type==="puppeteer"){if(!g.driver.cdpUrl)return{success:!1,shouldRetry:!1,reason:"running puppeteer code requires the remote debugging protocol to be open. Please contact Testim support."};O("before puppeteerPlayback");let{execute:w}=await Promise.resolve().then(()=>(Cy(),Py));try{return await w(g,y,r,e,o,a)}finally{O("after puppeteerPlayback")}}if(y.type==="playwright"){if(!g.driver.cdpUrl)return{success:!1,shouldRetry:!1,reason:"running playwright code requires the remote debugging protocol to be open. Please contact Testim support."};let{execute:w}=await Promise.resolve().then(()=>(Oy(),Ay));return await w(g,y,r,e,o,a)}if(y.type==="tdk"||!y.type){let{execute:w}=await Promise.resolve().then(()=>(Dy(),Ly));O("before tdkPlayback");try{return await w(g,y,e,s,n,r,o,a)}finally{O("after tdkPlayback")}}return{success:!1,shouldRetry:!1,reason:`unknown hybrid format ${y.type}`}}catch(c){QS.info("error running hybrid step",{err:c});return}finally{rp.delete(e.stepResultId)}}function sp(r){let e=rp.get(r);if(!e)throw new Error("No such stepResultId");e.abort()}var Ny,XS,QS,rp,tp,ZS,Zi=T(()=>{"use strict";Ny=E(require("memory-fs"));Le();U();ie();XS=new Ny.default,QS=x("hybrid-step-playback"),rp=new Map,ZS=(r,e,t,s)=>{let{step:n,context:o}=e.data;return Is(n,o,r,s.loginData)}});var np={};$(np,{run:()=>eR});var eR,My=T(()=>{"use strict";Cr();V();eR=async(r,e)=>{let{stepId:t,testResultId:s,retryIndex:n,stepResultId:o,packageData:i,timeout:a}=e.data;try{return{data:await ys(t,s,n,i,o,a),success:!0}}catch(c){if(c instanceof vt)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof te)return{success:!1,code:"timeout"};throw c}}});async function Uy(r,e,t,s){try{return await ll(r,e,t,s)}catch{aa.error("failed to report remote step state",{projectId:r,resultId:e,stepId:t});return}}async function rR(r,e,t,s,n){return aa.info("finished to run remote step",{stepId:t,sessionId:n}),await Uy(r,e,t,{status:"completed",success:!0,failureReason:null,data:s})}async function Fy(r,e,t,s,n){return aa.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:s}),await Uy(r,e,t,{status:"completed",success:!1,failureReason:s})}async function jy(r,e,t,s){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:o,userData:i}=r,a=t.type,c=e.getSessionId(),l=t.id;aa.info("start play remote step",{stepType:a,stepId:l,sessionId:c});let m=tR[a];if(!m)return await Fy(n,s,l,`Failed to find step type ${a}`,c);try{let d=await m.run(e,t,o,i);return await rR(n,s,l,d,c)}catch(d){return await Fy(n,s,l,d.message,c)}}var aa,tR,By=T(()=>{"use strict";Zg();Zi();be();My();U();aa=x("step-playback"),tR={"cli-validation-code-step":nr,"cli-wait-for-code-step":nr,"cli-action-code-step":nr,"cli-api-code-step":nr,"cli-condition-step":nr,"cli-download-code-step":nr,"node-package":np,"tdk-hybrid":ia}});var op,$y,_r,nR,ip,$e,Nn=T(()=>{"use strict";j();Rt();op=E(require("ws")),$y=require("events");U();pe();_r=x("socket-ng-service"),nR=5e3,ip=class extends $y.EventEmitter{constructor(){super(...arguments);this.clientId=J();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){_r.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),nR)}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(s){_r.error("failed to parse or trigger event",{err:s})}}connect(t){let s=this.formatUrl(Kp);return Kt().then(n=>new Promise(o=>{let i={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new op.default(`${s}?projectId=${t}&clientId=${this.clientId}&token=${n}`,i),this.ws.on("open",()=>{var a;return _r.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),o()}),this.ws.on("close",a=>{_r.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===op.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{_r.info("websocket error",{event:a})}),this.ws.on("message",a=>{let c=this.parseEvent(a);c!=null&&c.type&&this.emit(c.type,c.data)})}))}sendMessage(t){if(!this.ws){_r.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(s){_r.error("failed to stringify message for sending",{err:s})}}listenOnce(t,s,n){let o=i=>{s(i)&&(n(i),this.removeListener(t,o))};this.on(t,o)}listenTo(t,s,n,o){function i(c){n(c)&&o(c)}(Array.isArray(s)?s:[s]).forEach(c=>{var m,d;(m=this.listeners)[d=`${t}:${c}`]||(m[d]=[]);let l=i.bind(this);this.listeners[`${t}:${c}`].push(l),this.on(c,l)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let s=this.filterMap[t];this.sendMessage({type:"add-filter",filter:s})})}addFilter(t,s,n,o=!1){return new Promise(i=>{let a=J(),c={query:s,id:a,type:n,fullDocument:o};this.listenOnce("add-filter:done",l=>l.id===a,i),this.sendMessage({type:"add-filter",filter:c}),this.filterMap[t]=c})}removeListeners(t,s){Object.keys(this.listeners).length!==0&&s.forEach(n=>{let o=this.listeners[`${t}:${n}`];o&&(delete this.listeners[`${t}:${n}`],o.forEach(i=>this.removeListener(n,i)))})}removeFilter(t,s){let n=this.filterMap[t];if(!n)return;let o=Array.isArray(s)?s:[s];this.removeListeners(t,o),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},$e=new ip});var Hy,ap,oR,iR,aR,Wy,ca,ur,la=T(()=>{"use strict";Hy=E(require("p-retry")),ap=E(require("socket.io-client"));pe();j();U();oR=50,iR=10,aR=5e3,Wy=10*1e3,ca=x("base socket service"),ur=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);ca.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let s=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,s)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,s)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}ca.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${s==null?void 0:s.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===iR&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=oR)throw new Error(`Can't connect to Testim Servers.
|
|
414
|
+
Action required: Please allow opening a websockets connection to ${me} 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",()=>{ca.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let s={query:{projectId:e},requestTimeout:Wy,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=`${me}/${t}`,this._socket=ap.connect(this.url,s),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let s={query:{projectId:e},requestTimeout:Wy,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=`${me}/${t}`,this._socket=ap.connect(this.url,s),this.addSocketHandlers()}emitPromise(e,t){let s={},n=()=>new Promise((o,i)=>{this._socket.emit(e,t,a=>a!=null&&a.success?o():(s[e]=t,i(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,Hy.default)(()=>ne(n(),aR),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(s).length>0&&ca.error("Bad acknowledge from socket emit",{errorneousEvents:s})}),this.emitPromiseQueue}}});var Gy={};$(Gy,{remoteStepServiceSocketIO:()=>cR});var cp,cR,Vy=T(()=>{"use strict";la();cp=class extends ur{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"remoteStep"),this.listerers={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,s){this.listerers[t]&&(this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&s(n.remoteStep)},this._socket.on("remoteStep:saved",this.listerers[t])}async unlistenToRemoteStep(t){this.listerers[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t],await this.emitLeaveRoom(t))}},cR=new cp});var qy={};$(qy,{remoteStepService:()=>Cs});var lp,Mn,up,Cs,ua=T(()=>{"use strict";Nn();ie();Te();({REMOTE_STEP_SAVED:lp}=et),up=class{async init(e){M.flags.useNewWSCLI.isEnabled()||(Mn=(await Promise.resolve().then(()=>(Vy(),Gy))).remoteStepServiceSocketIO,Mn.init(e))}joinToRemoteStep(e){return M.flags.useNewWSCLI.isEnabled()?$e.addFilter(`${e}:remoteStep`,{resultId:e},[lp]):Mn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(M.flags.useNewWSCLI.isEnabled()){$e.listenTo(`${e}:remoteStep`,[lp],s=>s.resultId===e&&s.remoteStep&&s.remoteStep.status==="pending",s=>t(s.remoteStep));return}Mn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return M.flags.useNewWSCLI.isEnabled()?($e.removeFilter(`${e}:remoteStep`,[lp]),Promise.resolve()):Mn.unlistenToRemoteStep(e)}},Cs=new up});var pp,Lr,zy=T(()=>{"use strict";la();pp=class extends ur{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"testResult"),this.listerers={}}listenToTestResult(t,s,n){this.listerers[t]&&(this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=o=>{o.resultId===t&&o.testId===s&&n(o.testResult)},this._socket.on("testResult:updated",this.listerers[t])}emitJoinRoom(t,s){return this.emitPromise("testResult:join",{resultId:t,testId:s})}async joinToTestResult(t,s){this.rooms[t]||this.joinRoom(t,s),await this.emitJoinRoom(t,s)}emitLeaveRoom(t,s){return this.emitPromise("testResult:leave",{resultId:t,testId:s})}leaveTestResult(t,s){return this.listerers[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t],this.emitLeaveRoom(t,s)):Promise.resolve()}getSocket(){return this._socket}},Lr=new pp});var Jy={};$(Jy,{testResultService:()=>kt});var Ky,dp,kt,pa=T(()=>{"use strict";Ky=require("events");Nn();ie();Te();zy();dp=class extends Ky.EventEmitter{init(e){if(M.flags.useNewWSCLI.isEnabled()){$e.onConnect=()=>this.emit("socket-connected");return}Lr.init(e),Lr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return M.flags.useNewWSCLI.isEnabled()?$e.addFilter(`${e}:testResult`,{resultId:e,testId:t},[et.TEST_RESULT_UPDATED,et.TEST_RESULT_CREATED]):Lr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(M.flags.useNewWSCLI.isEnabled()){$e.removeFilter(`${e}:testResult`,[et.TEST_RESULT_UPDATED,et.TEST_RESULT_CREATED]);return}await Lr.leaveTestResult(e,t)}listenToTestResult(e,t,s){if(M.flags.useNewWSCLI.isEnabled()){$e.listenTo(`${e}:testResult`,[et.TEST_RESULT_UPDATED,et.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>s(n));return}Lr.listenToTestResult(e,t,s)}getSocket(){if(!M.flags.useNewWSCLI.isEnabled())return Lr.getSocket()}},kt=new dp});var Xy,Qy,Zy,we,lR,eb,Yy,da,tb=T(()=>{"use strict";Xy=E(require("lodash"));j();pe();Le();cs();Rt();be();By();Qy=E(require("p-retry")),Zy=require("url");U();Vo();fs();ie();ua();pa();Te();we=x("test-run-handler"),lR=3,eb=20*1e3,Yy=r=>JSON.stringify(r).length<eb,da=class{constructor(e,t,s,n,o,i){this._executionId=e;this._executionName=t;this._options=n;this._branch=o;this._testRunStatus=i;this.seleniumPerfStats=new Bt;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.clearTestResultFinished=Promise.resolve(void 0);var c,l;this._testStatus=s.testStatus,this._testId=s.testId,this._testName=s.name,this._testResultId=s.resultId,this._code=s.code,this._baseUrl=n.baseUrl||s.baseUrl||s.testConfig.baseUrl,this._nativeApp=s.nativeApp,this._overrideTestConfigId=(c=s.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((l=s.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?Js(n.browser,n.saucelabs,n.browserstack):s.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get automationMode(){return this._code?"codeful":"codeless"}get code(){return this._code}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}get browserStackAppPath(){var e;return this.isAppFromDevice?null:(e=this._nativeApp)==null?void 0:e.browserStackAppId}getSauceLabsAppPath(e){var t,s;return this.isAppFromDevice?null:e.includes("us-west-1")?(t=this._nativeApp)==null?void 0:t.usSauceLabsAppId:(s=this._nativeApp)==null?void 0:s.euSauceLabsAppId}get headspinAppPath(){var e;return this.isAppFromDevice?null:(e=this._nativeApp)==null?void 0:e.headSpinAppId}get androidActivityWait(){var n;let e=this._nativeApp&&"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp;if((n=e==null?void 0:e.activity)!=null&&n.includes(e.id))return`${e.id}.*`;let{activity:t}=e;if(!t)return null;let s=t.split(".").pop();return t.replace(s,"*")}get isFFAllowAppFromDeviceEnabled(){return M.flags.allowAppFromDeviceRuns.isEnabled()}get isAppFromDevice(){return qs(this._nativeApp)}get isAppForIosVirtualDevice(){return Jr(this._nativeApp)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?io.FROM_DEVICE:io.FROM_LIBRARY}get nativeAppLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${me}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}async getNativeAppData(){let{appId:e,baseUrl:t}=this._options;if(t&&!this._nativeApp&&!e){let s=t||this.baseUrl;if(!s)return null;let[n,o]=s.split(":");return{packageName:n,activity:o}}return this._nativeApp&&!e?"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 overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var s,n;let t={tokenV3:await Kt(),refreshToken:Po(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:ed,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this.code&&{isCodeMode:!0,testName:this.testName},...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,onprem:this._options.company.onprem,storageBaseUrl:this._options.company.storageBaseUrl,storageType:this._options.company.storageType,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential}};if(this._options.disableMockNetwork&&ut("user-disable-mock"),t.lightweightMode&&((s=this._options.lightweightMode)!=null&&s.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=Yy(o);Object.assign(t.lightweightMode,{isRunDataSentInUrl:i});let a=JSON.stringify(o).length,c=this.testId;i?(Object.assign(t,{runData:o}),we.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):we.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${eb} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let o=await dn(this._options);Object.assign(t,{preloadedTest:o[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return we.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var o;let e={...this.runData,...this.runMode===Y.EXTENSION&&{code:this.code},...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((o=this._options.lightweightMode)!=null&&o.disableResults&&!t&&Yy(e))return;let s=async()=>{try{return await ul(this._options.project,this._testId,this._testResultId,e)}catch(i){return we.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await s();return await this._testRunStatus.waitForExecutionStartedFinished(),cl(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:i,runData:i?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){O("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},s=["Testim Editor","Tricentis Testim Editor"],{targetId:n}=t.find(i=>i.type==="background_page"&&s.includes(i.title))||{},{targetId:o}=t.find(i=>i.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!o)throw new Error("AUT target not found");try{O("before Target.attachToTarget");let[i,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=i||{};O("before Runtime.evaluate"),await(0,Qy.default)(async()=>{let{result:m}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);if(!m.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),O("after wait for runTestimTest function");let{result:l}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},c);if(l.subtype==="error")throw new Error(l.description);return O("after Runtime.evaluate"),l.value}catch(i){throw we.error("error running test using CDP",{err:i}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let s;try{s=new Zy.URL(e)}catch{return}let{username:n,password:o}=s;if(n||o)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let s=!1,n=o=>{if(!s){if(this.isRetryKeyMismatch(o)){we.warn(`ignoring result update for on started due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(o.status)&&(o.resultId=this.testResultId,o.status==="completed"&&(we.info("setting _wasCompletedOnStartedCheck to true",{testResult:o,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=o),s=!0,t(o))}};if(this._options.disableSockets){let o=Date.now()+e,i=async()=>{if(Date.now()>o)return;let{testId:a,testResultId:c,branch:l,_options:{project:m}}=this;try{let d=await Rr(a,c,m,l);n(d),s||setTimeout(i,3e3)}catch(d){we.error("failed to check if done",{err:d}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else kt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:s},branch:n}=this;try{let o=await Rr(e,t,s,n),i=["running","completed"];if(i.includes(o.status))return we.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw we.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Be.TEST_START_TIMEOUT_MSG)}catch(o){throw we.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error(Be.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(s=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){we.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),s(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||kt.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){we.warn(`ignoring result update for on completed due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}i.status==="completed"&&(i.resultId=this._testResultId,s(i))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),o=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Xy.debounce(async()=>{try{let i=await Rr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(we.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(i==null?void 0:i.status)==="completed"?(we.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),i.resultId=this._testResultId,s(i),!0):!1}catch(i){return we.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)kt.on("socket-connected",async()=>{try{await kt.joinToTestResult(this._testResultId,this.testId)}catch(i){we.error("failed joining to test result updates after socket reconnected",{error:i})}e==null||e()});else{let i=()=>{setTimeout(async()=>{try{let{isComplete:a}=await Qc(this._testResultId,this._options.project,this.retryKey);a?await e()||(we.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){we.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&kt.off("socket-connected",e)}}listenToRemoteStep(e){Cs.listenToRemoteStep(this.testResultId,t=>{jy(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:lR;return this._timeoutRetryCount<e}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,s;return Boolean((s=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:s.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||(this._originalTestResultId=this._previousTestResultId),this._testResultId=J(),!((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 ma,rb=T(()=>{"use strict";tb();ma=class{constructor(e,t,s,n,o,i){this._waitingTests=s.map(a=>new da(e,t,a,n,o,i))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var uR,pR,Fn,mp=T(()=>{"use strict";ds();U();uR=x("worker-utils"),pR=async(r,e,t)=>{e&&await zl(r,t)},Fn=async(r,e,t,s)=>{uR.info("releasing player",{hasPlayer:Boolean(s)});try{await(s==null?void 0:s.onDone())}finally{await pR(r,e,t)}}});function yR(r,e,t,s){return{testId:r,reason:s,name:e,resultId:t,success:!1}}var hp,ib,ab,gp,Pt,sb,nb,ob,Un,dR,fp,mR,Wt,fR,fa,gR,hR,bR,Ct,ga=T(()=>{"use strict";hp=E(require("ms")),ib=E(require("lodash")),ab=E(require("moment")),gp=E(require("p-retry"));j();Le();ds();be();U();mp();jt();Xo();Te();ua();pa();at();ie();V();Pt=x("base-worker"),{GET_BROWSER_TIMEOUT_MSG:sb,TEST_START_TIMEOUT_MSG:nb,TEST_COMPLETE_TIMEOUT_MSG:ob}=Be,{SETUP_TIMEOUT:Un,NETWORK_ERROR:dR,GRID_ERROR:fp,BROWSER_CLOSED:mR,SELENIUM_ERROR:Wt,UNKNOWN_ERROR:fR,MOBILE_SESSION_ERROR:fa}=Hs,gR=(0,hp.default)("1s"),hR=1;bR=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Ct=class{constructor(e,t,s,n,o,i,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=s;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.id=Ct.getWorkerId();this.lambdatestService=new Z;this.isCodeMode=t.files&&t.files.length>0,this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.isRegressionBaselineRun=t.isRegressionBaselineRun,this.userData=t.userData}static getWorkerId(){return hR++}async getGridSlot(e,t){let s=await Cf(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,s),s}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Us(!0)}async getBrowserOnce(e,t,s,n){throw new Us(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),Pt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!Ke({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var o;let t=!e.isFFAllowAppFromDeviceEnabled&&e.isAppFromDevice,s=e.isAppForIosVirtualDevice,n=((o=this.options.gridData)==null?void 0:o.type)===W.BROWSERSTACK&&!e.browserStackAppPath;if(t||s||n){let i={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:s,isMissingBrowserStackAppId:n}};return this.onTestIgnored(this.id,i),i}}setSessionTimeout(){return this.options.mode===Y.APPIUM?Math.max((0,hp.default)("180s"),this.options.getSessionTimeout):Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getTestPlayer(e,t){var o;let s=(o=this.userData)==null?void 0:o.projectId,n;try{O("before getSlotOnce retries");let i=0,a=await(0,gp.default)(async()=>{let m=Date.now();try{return await ne(this.getSlotOnce(e),this.options.getBrowserTimeout,Be.GET_BROWSER_TIMEOUT_MSG)}catch(d){let p={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw d instanceof Hr?Pt.info("could not get grid slot due to concurrency issue",p):Pt.error("error getting grid slot",{error:d,...p}),i++,await se(this.options.getBrowserTimeout-(Date.now()-m)),d}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1});O("after getSlotOnce retries"),O("before getBrowserOnce retries");let c=this.options.getBrowserRetries-i;if(!c)throw new Error("No free browser slots in desired grid");let l=0;n=await(0,gp.default)(async()=>{let m=Date.now(),d=this.initPlayer(e);try{a=await Af(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1}),this.options.gridData.provider=a.provider,this.options.gridData.host=a.host,this.options.gridData.failedGetBrowserAttempts=l;let p=this.setSessionTimeout();O("before getBrowserOnce");let g=await ne(this.getBrowserOnce(e,t,d,a),p,Be.GET_BROWSER_TIMEOUT_MSG);return O("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,s),d||g}catch(p){let g={provider:a.provider,host:a.host,failedGetBrowserAttempts:l,id:this.options.gridData.gridId,type:a.type},f=this.options.mode===Y.APPIUM?"device":"browser";throw Pt.error(`error getting ${f} from grid`,{error:p,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:g}),Q.onGetBrowserFailure(this.id,s,++l),d.onDone(),!(p instanceof Tt)&&this.options.mode!==Y.APPIUM&&await se(this.options.getBrowserTimeout-(Date.now()-m)),p}},{retries:c-1,minTimeout:0,factor:1}),O("after getBrowserOnce retries")}catch(i){throw await Fn(this.id,this.releaseSlotOnTestFinished,s,n),i instanceof Tt?i:i instanceof wt?new fr(i,fp):new fr(i,Wt)}return n}async runTest(e,t,s){var m;O("inside runTest");let n=(m=this.userData)==null?void 0:m.projectId,o=this.handleQuarantine(e);if(o)return o;let i=Yr(this.options)&&this.handleMobileTest(e);if(i)return i;O("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,s,e.retryKey,a);e.baseUrl=c.config.baseUrl;let l=await this.getTestPlayer(e,t);try{return await this.runTestOnce(e,l)}finally{await Fn(this.id,this.releaseSlotOnTestFinished,n,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var p,g;let e=()=>process.nextTick(()=>this.run()),t=async(f,h,y)=>{var A,_;if(Ke(f,this.options)||!h.isFFAllowAppFromDeviceEnabled&&h.isAppFromDevice||h.isAppForIosVirtualDevice||Yr(this.options)&&((A=this.options.gridData)==null?void 0:A.type)===W.BROWSERSTACK&&!h.browserStackAppPath)return e();let w=h.sessionId,S=R=>y==null?void 0:y.message.includes(R),b=y&&y instanceof fr,v=y&&(S(nb)||S(ob)),I=!f.success&&(h.hasMoreRetries()&&!b&&!v||v&&h.hasMoreTimeoutRetries());try{let R=h.retryKey;f.testRetryKey=R;let L=h.getAppSource;return await this.onTestCompleted(this.id,this.testId,f,w,I,L),this.executionQueue.hasMoreTests()&&!((_=this.options.lightweightMode)!=null&&_.general)&&await se(gR),await this.runTestCleanup(),I?(v?await h.startNewTimeoutRetry():await h.startNewRetry(),Pt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:v,testRetryKey:R,totalRetries:h._totalRetryCount}),this.testResultId=h.testResultId,await m(h,I)):await e()}catch(R){if(R instanceof Gt)return;Pt.error("failed to process test result",{error:R}),e();return}},s=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
415
|
+
Please make sure the CLI has stable access to the internet. ${cc()?"(Internal: network connectivity test failed)":""}`,n=f=>{let{DEVICE_OS_VERSION_TOO_LOW:h,APP_NOT_EXIST_ON_DEVICE:y,APP_NEVER_STARTED:w}=hc,S=f instanceof Error?f.message:f;return S.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),S.includes(sb)?{errorType:Un,reason:"Test couldn't get device, time"}:S.includes(y)?{errorType:fa,reason:"app doesn't exist on device"}:S.includes(w)?{ErrorType:fa,reason:"app never started, check app permission or app activity"}:S.includes(h)?{ErrorType:fa,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:fa,reason:S}},o=(f,h)=>{let y=this.options.mode===Y.APPIUM?"device":"browser";if(!h&&M.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:dR,reason:s()};let w=f instanceof Error?f.message:f;if(w.includes(sb))return{errorType:Un,reason:`Test couldn't get ${y}`};if(w.includes(nb))return{errorType:Un,reason:"Test couldn't be started"};if(w.includes(ob)){if(!this.testRunTimeout)return{errorType:Un,reason:"Test timeout reached: test is too long"};let S=ab.default.duration(this.testRunTimeout,"milliseconds"),b=Math.floor(S.asMinutes()),v=S.seconds(),I=b>0?` ${b} min`:"",A=v>0?` ${v} sec`:"";return{errorType:Un,reason:`Test timeout reached (timeout:${I}${A}): test is too long`}}if(f instanceof fr&&f.type){if(f.type===fp)return{errorType:fp,reason:`Test couldn't get ${y} from grid - ${f.message}`};if(f.type===Wt)return{errorType:Wt,reason:`Failed to create new session - ${f.message}`}}return"type"in f&&f.type===mR?{errorType:Wt,reason:"Session terminated, it is possible that the cli could not connect to the grid to send keep-alive requests for a prolonged period"}:"failure"in f&&f.failure instanceof Wr?{errorType:Wt,reason:`Test couldn't get ${y} from grid - ${f.failure.message}`}:/SeleniumError: connect ECONNREFUSED/.test(f.message)||/Couldn't connect to selenium server/.test(f.message)?{errorType:Wt,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(f.message)?{errorType:Wt,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(f.message)?{errorType:Wt,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(f.message)?{errorType:Wt,reason:`Session could not be created, please check that the ${y} you requested is supported in your plan`}:{errorType:fR,reason:w}},i=async(f,h)=>{var v;let y=await ac();!y&&M.flags.warnOnBadNetwork.isEnabled()&&console.warn(s()),Pt.warn("error on run",{err:f});let w=(v=this.userData)==null?void 0:v.projectId,{errorType:S,reason:b}=this.options.mode===Y.APPIUM?n(f):o(f,y);al(w,this.testResultId,this.testId,{status:Ws.COMPLETED,success:!1,reason:b,errorType:S,testRetryKey:h.retryKey,setupStepResult:{status:Ws.COMPLETED,success:!1,reason:b,errorType:S}},h.remoteRunId),await t(yR(this.testId,this.testName,this.testResultId,b),h,f)},a=async(f,h)=>{var v;let y=this.testId,w=this.testResultId,S=(v=this.userData)==null?void 0:v.projectId,b=this.branch;if(!y||!w||!S||!b)return Pt.warn("Test failed. Not enough data to recover results via API",{err:f}),i(f,h);try{let I=await Rr(y,w,S,b);if(Pt.warn("Test failed. Got results via API",{err:f,testResult:ib.default.omit(I,bR)}),I&&I.status===Ws.COMPLETED)return await t(I,h);throw f}catch(I){return I!==f&&Pt.error("Failed to fetch test results from server",{testId:y,resultId:w,projectId:S,branch:b,err:I}),i(f,h)}},c=this.options.disableSockets||((p=this.options.lightweightMode)==null?void 0:p.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),l=this.options.disableSockets||((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep),m=async(f,h)=>{try{await Promise.all([!l&&Cs.joinToRemoteStep(this.testResultId),!c&&kt.joinToTestResult(this.testResultId,this.testId)]),f.validateRunConfig();let y=await this.runTest(f,this.customExtensionLocalLocation,h),w=await t(y,f);return O("After onRunComplete"),w}catch(y){return a(y,f)}finally{l||Cs.unlistenToRemoteStep(this.testResultId)}},d=this.executionQueue.getNext();return d?(this.testId=d.testId,this.testName=d.testName,this.testResultId=d.testResultId,this.overrideTestConfigId=d.overrideTestConfigId,this.testRunConfig=d.runConfig,this.branch=d.branch,m(d)):this.onQueueCompleted()}}});var cb={};$(cb,{WorkerSelenium:()=>yp});function wR(r){let{playback:e}=re().commonConstants;function t(s){r.playbackManager.on(s,()=>{O(`Got event ${s}`)})}Object.values(e).forEach(t)}var ha,TR,yp,lb=T(()=>{"use strict";j();Le();ga();U();jt();Vo();ie();Lu();V();na();Ee();ha=x("worker-selenium"),TR=1e9,yp=class extends Ct{initPlayer(t){return new _n(this.id,t.runParams,this.options.shouldMonitorPerformance,t.automationMode,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,s,n,o){O("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new vs(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await i.init(this.options,this.testName,this.testRunConfig,o,s,this.executionId,this.testResultId,t.seleniumPerfStats,l,this.lambdatestService),O("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),O("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,TR),await this.windowUtils.validatePageIsAvailable(),O("in WorkerSelenium after navigate")}catch(l){let m=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",d=l.message&&l.message==="invalid argument";throw l instanceof Tt||m||d?new Tt(`Page '${c}' is not available`):(ha.error("failed to navigate to page",{baseUrl:c,err:l}),l)}}async runTestOnce(t,s){var m;let n=re(),{driver:o,sessionPlayer:i}=s,a=n.manifestVersion||"runner";Q.onWaitToTestComplete(this.id,this.isCodeMode),wR(i),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&i.setSfdcCredential(t.sfdcCredential),n.localAssetService&&n.localAssetService.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await dn(this.options))[this.testId]);let l=async()=>{if(t.automationMode==="codeful"){i.callOrderScheduler?i.callOrderScheduler.schedule(()=>t.waitForExecutionStartedFinished(),{key:`test-result:${this.userData.projectId}:${this.testResultId}`}):await t.waitForExecutionStartedFinished(),O("right before playTestByCode");let p=new Promise((g,f)=>{i.playTestByCode(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,a,g,!1,this.overrideTestConfigId,this.branch,t.code,t.testName).catch(f)});return ne(p.then(g=>(O("right after playTestByCode"),g)),this.testRunTimeout,Be.TEST_COMPLETE_TIMEOUT_MSG).catch(g=>{var f;throw g instanceof te&&((f=i.stopPlayingOnTestTimeout)==null||f.call(i)),g}).then(g=>(g.resultId=this.testResultId,g))}let d=!1;return ne(new Promise((p,g)=>{i.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,a,p,!1,this.overrideTestConfigId,this.branch,d,t.remoteRunId,void 0,void 0,c).catch(g)}),this.testRunTimeout,Be.TEST_COMPLETE_TIMEOUT_MSG).catch(p=>{var g;throw p instanceof te&&((g=i.stopPlayingOnTestTimeout)==null||g.call(i)),p}).then(async p=>{n.localAssetService&&await n.localAssetService.drain(),p.stepsResults=null,p.resultId=this.testResultId,o.isAlive()||(ha.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),p.gridIssues="could not validate grid is alive");let g=o.maxKeepAliveGap();g>=3e4&&(ha.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),p.keepAliveIssue=g);let h={...p,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h})};o.start(),O("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,s),O("right after super.runTestOnce in workerSelenium");let d=await l();return O("right after runSeleniumTest"),d}catch(d){throw ha.error("failed to run test once",{err:d}),d}}}});var ya,ub=T(()=>{"use strict";ya=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 bp,ba,pb=T(()=>{"use strict";U();bp=x("mobile-frame-locator-mock"),ba=class{foundFrameCallback(){return bp.info("foundFrameCallback-mock invoked"),{}}locate(){return bp.info("locate-mock invoked"),{}}async findFrame(){return bp.info("findFrame-mock invoked"),{}}}});var vR,ER,Ta,db=T(()=>{"use strict";vR=E(require("webdriverio"));ub();Fu();U();Uu();ju();Ee();Gu();pb();Vu();ER=x("appium-test-player"),Ta=class{constructor(e,t,s,n,o=vR,i=void 0,a=void 0){this.id=e;this.driver=o;let{sessionPlayer:c,commonConstants:l,stepActionFactory:m,MobileLocateElementPlayer:d}=re(),p=new Ss(this.driver);this.stepActionFactory=new m(p),sa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Ps(Oi()),this.sessionPlayer=new c(e,new ya,null,null,ba,Ai,d,null,p,this.stepActionFactory,this.playbackTimeoutCalculator,null,n),this.sessionPlayer.setShouldMonitorPerformance(Boolean(s)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=a,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,s,n){}async onDone(){var e,t;try{await((t=(e=this.driver)==null?void 0:e.activeSession)==null?void 0:t.deleteSession())}catch(s){ER.error("error while deleting appium session",{error:s})}finally{let{commonConstants:s}=re();this.sessionPlayer.playbackManager.off(s.playback.RESULT),this.sessionPlayer=null,this.stepActionFactory=null,this.driver=null}}getSessionId(){var e,t;return(t=(e=this.driver)==null?void 0:e.activeSession)==null?void 0:t.sessionId}}});var fb={};$(fb,{WorkerAppium:()=>Tp});var mb,jn,Tp,gb=T(()=>{"use strict";mb=E(require("jsdom"));pe();be();wi();ga();U();jt();db();Ee();bu();ie();jn=x("worker-appium"),Tp=class extends Ct{initPlayer(e){return new Ta(this.id,e.runParams,this.options.shouldMonitorPerformance,e.automationMode,void 0,e.retryCount,e.previousTestResultId)}async getBrowserOnce(e,t,s,n){var h;Q.onGetSession(this.id,this.testName,e.runMode);let{driver:o}=s,i=this.options.projectData.type,a=await e.getNativeAppData(),c=i==="android"?e.androidActivityWait:null,l=e.nativeAppLink,{type:m,host:d}=this.options.gridData,p=!!(W.TESTIM_HEADSPIN===m&&e.headspinAppPath),g=!!(W.BROWSERSTACK===m&&e.browserStackAppPath),f=!!(W.SAUCELABS===m&&e.getSauceLabsAppPath(d));if(g&&(l=e.browserStackAppPath),p&&(l=e.headspinAppPath),f&&(l=e.getSauceLabsAppPath(d)),this.options.appId&&m!==W.BROWSERSTACK){let{project:y,appId:w}=this.options,S=await Yc({appId:w,projectId:y});if(!S)throw jn.error("mobile app not found",{appId:w,projectId:y}),new Error("mobile app not found");l=`${me}/storage${S.filePath}?access_token=${this.options.authData.token}`}try{let y={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(h=this.options.projectData)==null?void 0:h.name}-${this.options.project}`},w={projectType:i,nativeApp:a,appPath:l,androidActivityWait:c,sessionTags:y,gridInfo:n,options:this.options,testRunConfig:this.testRunConfig,isHSAppIdExists:p},S;if(this.options.skipLoadBalancer&&this.options.deviceUdid){this.options.lockDevice&&await yg(n,this.options.deviceUdid);let b=await _g(w);S=await o.remote(b)}else{let b=Og(w);S=await o.remote(b)}Object.assign(o,{activeSession:S}),await wg(e,S,this.options),jn.info(`init new appium session testName: ${this.testName}`,{sessionId:S.sessionId,testResultId:this.testResultId,nativeApp:a})}catch(y){throw jn.error("failed to start application",{err:y}),y}}getServerAddressFromGrid(){let{host:e,port:t,accessToken:s,type:n}=this.options.gridData;return n===W.TESTIM_HEADSPIN?`https://${e}:${t}/v0/${s}/wd/hub`:`https://${e}:${t}/wd/hub`}getDirectAddressConnection(e){let{directConnectProtocol:t,directConnectHost:s,directConnectPort:n,directConnectPath:o}=e;if(t&&s&&n&&o)return`${t}://${s}:${n}${o}`}async runTestOnce(e,t){let s=re(),{sessionPlayer:n}=t,o=t.driver,i=s.manifestVersion||"runner";Q.onWaitToTestComplete(this.id,this.isCodeMode),n.playbackManager.executionId=e.executionId,n.playbackManager.executionName=e.executionName;let a;if(this.options.skipLoadBalancer){let{protocol:d,hostname:p,port:g,path:f}=await yu(this.options.gridData,this.options.deviceUdid);a=`${d}://${p}:${g}${f}`}else a=this.getDirectAddressConnection(o.activeSession.capabilities)||this.getServerAddressFromGrid();let c=new mb.JSDOM("").window.DOMParser,l=o.activeSession.capabilities;n.playbackManager.appiumSessionData={env:"remote",capabilities:l,sessionId:o.activeSession.sessionId,sessionToken:this.options.gridData.accessToken},n.playbackManager.appiumApi=new s.AppiumApi(a,o.activeSession.sessionId,c),s.localAssetService&&s.localAssetService.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let p=await new Promise((f,h)=>n.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,i,f,!1,this.overrideTestConfigId,this.branch,!1,e.remoteRunId,void 0,void 0,void 0).catch(h));return s.localAssetService&&await s.localAssetService.drain(),p.stepsResults=null,p.resultId=this.testResultId,{...p,...e.seleniumPerfStats.getStats()}}catch(d){throw jn.error("error while running appium tests",{err:d}),d}};try{return await super.runTestOnce(e,t),await m.call(this)}catch(d){throw jn.error("failed to run test once",{err:d}),d}}}});var wa,hb=T(()=>{"use strict";j();In();V();wa=class{constructor(e){this.id=e;this.driver=new Pr}async onDone(){try{await ne(this.driver.end(),12e4)}catch(t){t instanceof te&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var yb,va,bb=T(()=>{"use strict";yb=E(require("ws"));j();va=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new yb.default(this._cdpUrl,{timeout:e}),s=it(o=>{t.once("open",o)}),n=it(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([s,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),s=this._cdpCallbacks.get(t.id);s&&(this._cdpCallbacks.delete(t.id),t.error?s.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?s.reject(new Error(t.result.exceptionDetails.exception.description)):s.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,s){let n=await this.initCDPWebsocket();this._lastWsId||(this._lastWsId=0);let o=this._lastWsId++,i=new Promise((c,l)=>{this._cdpCallbacks.set(o,{resolve:c,reject:l})}),a={method:e,params:t,id:o};return s&&Object.assign(a,{sessionId:s}),n.send(JSON.stringify(a)),i}}});var Sa,wp,Ea,Tb=T(()=>{"use strict";j();Sa=E(require("chrome-launcher"));wi();bb();ln();wp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new va}async init(e,t,s,n,o,i,a,c,l,m){var f,h,y,w;let d=Ti(e,t,s,n,o,i,a),p=[...((f=d.desiredCapabilities)==null?void 0:f.chromeOptions.args)??[],...((w=(y=(h=d.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:w.args)??[],...Sa.Launcher.defaultFlags().filter(S=>S!=="--disable-extensions")];this.chrome=await Sa.launch({chromeFlags:p,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let g=await wr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(g),is(()=>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}},Ea=class{constructor(e){this.id=e;this.sessionId=J();this.driver=new wp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var vb={};$(vb,{WorkerExtension:()=>Bn});function SR(r){return r instanceof Error&&"type"in r&&typeof r.type=="string"}function wb(r){return SR(r)?r:new Error(r)}var ht,Bn,vp=T(()=>{"use strict";Le();V();ga();j();U();jt();ie();hb();Tb();ht=x("worker-ext"),Bn=class extends Ct{initPlayer(){return this.options.useChromeLauncher?new Ea(this.id):new wa(this.id)}async _getBrowserOnce(e,t,s,n){var i;let{driver:o}=s;try{return await o.init(this.options,this.testName,this.testRunConfig,n,t,this.executionId,this.testResultId,e.seleniumPerfStats,(i=this.options.lightweightMode)==null?void 0:i.general,this.lambdatestService)}catch(a){throw ht.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,s,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,s,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async runTestOnce(e,t){let{testResultId:s,executionId:n,testId:o}=this;O("WorkerExtension runTestOnce");let i=async m=>{let d=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ne(e.runTestUsingCDP(m.cdpTestRunner),d,Be.TEST_START_TIMEOUT_MSG)}catch(p){if(!(p instanceof te))throw p;return ht.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:s}),await e.checkViaRestAPIIfTestStarted()}},a=async(m,d,p)=>{try{let g=await m.url(d);return p.driverUrlFinished=!0,g}catch(g){throw ht.error("error from driver.url",{err:g,testResultId:s,executionId:n,testId:o,url:d,urlLength:d.length}),g}},c=async m=>{let d=await e.onStarted(this.options.testStartTimeout);return m.testRunHandlerOnStartedHadFinished=!0,d},l=async()=>{var g;if(O("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id,this.isCodeMode);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(f){throw ht.warn("failed to run test via CDP",{err:f}),f}}let{driver:d}=t,p={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let f=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await ne(Promise.all([a(t.driver,f,p),c(p)]),this.options.testStartTimeout,Be.TEST_START_TIMEOUT_MSG)}catch(w){if(!(w instanceof te))throw w;ht.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:s,executionId:n,testId:o,...p}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id,this.isCodeMode);let h=new AbortController,y=w=>{e.onCompletedCleanup(),ht.warn("on browser closed error detected",{err:w,testResultId:s,executionId:n,testId:o}),d.unregisterToClosedBrowser(y),w.type=Hs.BROWSER_CLOSED,h.abort(w)};d.registerToClosedBrowser(y);try{let w=ne(e.onCompleted(),this.testRunTimeout,Be.TEST_COMPLETE_TIMEOUT_MSG),S=await Za(w,h.signal);d.unregisterToClosedBrowser(y),this.lambdatestService.isLambdatestRun()&&await d.executeJS(`lambda-status=${S.success?"passed":"failed"}`).catch(()=>{}),d.isAlive()||(ht.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.gridIssues="could not validate grid is alive");let b=d.maxKeepAliveGap();return b>=3e4&&(ht.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.keepAliveIssue=b),{...S,...e.seleniumPerfStats.getStats()}}catch(w){throw ht.warn("timeout wait until test completed",{err:w,testResultId:s,executionId:n,testId:o}),wb(w)}finally{d.unregisterToClosedBrowser(y)}}catch(f){throw ht.warn("failed to start url",{err:f}),wb(f)}};t.driver.start();try{return await super.runTestOnce(e,t),O("WorkerExtension super.runTestOnce"),await l()}catch(m){throw ht.error("failed to run test",{err:m,testId:e.testId,resultId:e.testResultId}),m}}}});var Eb={};$(Eb,{WorkerExtensionSingleBrowser:()=>Ep});var RR,IR,Ep,Sb=T(()=>{"use strict";Le();j();U();mp();jt();vp();RR=x("base-worker"),IR=500,Ep=class extends Bn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await Fn(this.id,this.releaseSlotOnTestFinished,t,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,s,n,o){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,s,n,o)}async getTestPlayer(t,s){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(RR.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,s)),this.testPlayer}async runTest(t,s,n){let o=this.handleQuarantine(t);if(o)return o;O("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,s);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 se(IR)}}});function xR(r,e){e===0?r():setTimeout(r,e*Qp)}var Sp,Ra,Rb=T(()=>{"use strict";In();j();pe();Le();pu();Rt();Cu();V();U();ie();rb();Sp=x("parallel-worker-manager"),Ra=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e){case Y.SELENIUM:return(lb(),ve(cb)).WorkerSelenium;case Y.APPIUM:return(gb(),ve(fb)).WorkerAppium;default:return Ii.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Sb(),ve(Eb)).WorkerExtensionSingleBrowser:(vp(),ve(vb)).WorkerExtension}}createWorkers(e,t,s,...n){let o=this.getWorkerType(s),i=()=>{try{return O("before new Worker",s),new o(t,...n)}finally{O("after new Worker",s)}};return Array.from(new Array(e),i)}async runTests(e,t,s,n,o,i,a,c,l){if(e&&e.length===0)return;let m=!1,d=0,p=g=>new Promise(f=>{var dr,At,Mr,P,D,F;let h=o.project,y=new ma(s,n,e,o,i,t),w={},S=e.length,b=(dr=o.company)==null?void 0:dr.companyId,v=(At=o.company)==null?void 0:At.name,I=o.source||"cli",A=o.user,_=(Mr=o.company)==null?void 0:Mr.planType,R=(P=o.company)==null?void 0:P.isStartUp,L=(D=o.projectData)==null?void 0:D.name,C=(F=o.projectData)==null?void 0:F.type,N=o.lightweightMode,B=yr(o),K=(G,ge,he,La,$n,Da)=>(d++,Vf({executionId:s,projectId:h,testId:ge,resultId:he,companyId:b,companyName:v,projectName:L,companyPlan:_,sessionType:B,source:I,user:A,lightweightMode:N,isStartUp:R,projectType:C,appSource:Da}),t.testStartAndReport(G,s,he,La,$n)),X=async(G,ge,he,La,$n,Da)=>{var Np,Mp,Fp;d--;let yt={...(N==null?void 0:N.onlyTestIdsNoSuite)&&{show:!0},...he.seleniumStats&&{seleniumStats:he.seleniumStats},...he.gridIssues&&{gridIssues:he.gridIssues},...he.keepAliveIssue&&{keepAliveIssue:he.keepAliveIssue},...o.host&&{gridHost:o.host}};if(he.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(he.seleniumPerfMarks),delete he.seleniumPerfMarks),o.grid||o.gridId?(yt.gridName=o.grid||((Np=o.gridData)==null?void 0:Np.name),yt.gridType=(Mp=o.gridData)==null?void 0:Mp.type,yt.gridProvider=(Fp=o.gridData)==null?void 0:Fp.provider):o.useLocalChromeDriver?(yt.gridName="local-chrome-driver-from-options",yt.gridType="local-chrome"):o.useChromeLauncher?(yt.gridName="chrome-launcher-from-options",yt.gridType="local-chrome"):o.browserstack?yt.gridName="browserstack-from-options":o.saucelabs&&(yt.gridName="saucelabs-from-options"),await t.testEndAndReport(G,he,s,La,$n,yt).catch(xT=>Sp.error("testEndAndReport threw an error",{err:xT})),$n)return;w[he.resultId]=he,qf({executionId:s,projectId:h,testId:ge,resultId:he.resultId,result:he,companyId:b,companyName:v,projectName:L,companyPlan:_,sessionType:B,source:I,user:A,lightweightMode:N,logger:Sp,isStartUp:R,projectType:C,appSource:Da}),l&&!he.success&&(y.stop(),m=!0),(Object.keys(w).length===S||m&&d===0)&&f(w)},ee=(G,ge)=>{w[ge.resultId]=ge,t.onTestIgnored(G,ge.resultId),d--,(Object.keys(w).length===S||m&&d===0)&&f(w)},fe=(G,ge)=>t.onGridSlot(G,ge);o.userData={loginData:Object.assign({},Mt(),{refreshToken:Po(),authData:Mt(),token:g}),projectId:o.project,company:o.company,servicesUrl:me},O("in localStrategy before createWorker"),this.createWorkers(c,y,o.mode,o,this.customExtensionLocalLocation,s,K,X,fe,ee).forEach((G,ge)=>{O("before schedule worker.run after createWorkers"),xR(()=>{O("right before worker.run"),G.run()},ge)})});try{let g=await Kt(),f=await p(g);if(m)throw new Gt;return f}catch(g){throw Sp.error("failed running parallel workers",{executionId:s,err:g}),g}}}});var Ia,Ib=T(()=>{"use strict";la();Ia=class extends ur{init(e){return super.initNewSocket(e,"real-data")}emitJoinRoom(e,t){this._socket.emit("testResult:listen",{query:`projectId=${t}&runId=${e}`})}joinToTestResultsByRunId(e,t){this.joinRoom(e,t),this.emitJoinRoom(e,t)}stopListenToTestResultsByRunId(e){this.leaveRoom(e),this._socket.emit("testResult:listen:stop",{})}listenToTestResultsByRunId(e){function t(s){e(s.data)}this._socket.on("testResult:changes",t.bind(this))}}});var Rp,Ip,xa,xb=T(()=>{"use strict";Nn();ie();Te();Ib();({TEST_RESULT_CREATED:Rp,TEST_RESULT_UPDATED:Ip}=et),xa=class{constructor(){M.flags.useNewWSCLI.isEnabled()||(this.realDataServiceSocketIO=new Ia)}init(e){return M.flags.useNewWSCLI.isEnabled()?Promise.resolve():this.realDataServiceSocketIO.init(e)}joinToTestResultsByRunId(e,t){if(M.flags.useNewWSCLI.isEnabled())return $e.addFilter(e,{runId:e},[Ip,Rp],!0);this.realDataServiceSocketIO.joinToTestResultsByRunId(e,t)}stopListenToTestResultsByRunId(e){if(M.flags.useNewWSCLI.isEnabled()){$e.removeFilter(e,[Ip,Rp]);return}this.realDataServiceSocketIO.stopListenToTestResultsByRunId(e)}listenToTestResultsByRunId(e,t){if(M.flags.useNewWSCLI.isEnabled()){$e.listenTo(e,[Ip,Rp],s=>s.runId===e,s=>t(s));return}this.realDataServiceSocketIO.listenToTestResultsByRunId(t)}}});async function Cb(r,e){var t;if((t=r.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&r.testId)return{tests:[r.testId.map(n=>({testId:n,testConfig:{},resultId:J()}))]};if(r.files.length>0){let{buildCodeTests:s}=await Promise.resolve().then(()=>(Ku(),Ey)),n={};if(r.webpackConfig){let o=Pb.join(process.cwd(),r.webpackConfig);n=require(o)}return s(r.files,n,{baseUrl:r.baseUrl})}return await Jc({projectId:r.project,labels:r.label,testIds:r.testId,testNames:r.name,testConfigNames:r.testConfigNames,suiteNames:r.suites,suiteIds:r.suiteIds,branch:e,rerunFailedByRunId:r.rerunFailedByRunId,testConfigIds:r.testConfigIds,intersections:r.intersections})}function xp(r){let e=Object.keys(r).length,t=Object.keys(r).reduce((s,n)=>s+(r[n].success===!0?1:0),0);return e===t}async function kp(r,e){let t=r.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],s=kb.difference(Gs(r,e),t);if(s.length>0)throw ut("invalid-config-run",{browser:s.join(", "),mode:"runner"}),new k(`browser type <${s}> is not supported in ${r.mode} mode.`);return e}var kb,Pb,Ab=T(()=>{"use strict";kb=E(require("lodash")),Pb=E(require("path"));j();cs();be();V()});var Dr,Ob,kR,ka,PR,Pa,_b=T(()=>{"use strict";Dr=E(require("lodash"));j();U();pe();ie();Le();ds();Kl();pu();be();Rt();jt();mg();V();Rb();xb();Ab();({testRunStatus:Ob,CLI_MODE:kR}=Dt),ka=x("test-plan-runner"),PR=1e3*60*5,Pa=class{constructor(e){this.startTime=Date.now();this.workerManager=new Ra(e)}async runTestAllPhases(e,t,s,n,o,i,a,c){let l={},m=Mt(),d=async()=>{let y=o.beforeParallel||1,w=!0,S=await this.workerManager.runTests(e,c,i,a,o,n,m,y,w);Object.assign(l,S)},p=async()=>{let y=eo||o.parallel,w=!1;O("right before this.workerManager.runTests");let S=await this.workerManager.runTests(t,c,i,a,o,n,m,y,w);O("right after this.workerManager.runTests"),Object.assign(l,S)},g=async()=>{let y=o.afterParallel||1,w=!1,S=await this.workerManager.runTests(s,c,i,a,o,n,m,y,w);Object.assign(l,S)},f=yr(o);zf({executionId:i,projectId:o.project,sessionType:f}),O("right before runBeforeTests");try{return await d(),O("right before runTestPlanTests"),await p(),O("right after runTestPlanTests"),await g(),l}catch(y){if(ka.error("error running test plan",{err:y}),y instanceof Gt)return c.markAllQueuedTests(i,de.ABORTED,"aborted",!1);throw y}finally{await h()}async function h(){var w,S,b,v;if((w=o.lightweightMode)!=null&&w.disablePixelValidation)return;if(o.mode===kR.SELENIUM){let{EyeSdkBuilder:I}=(await Promise.resolve().then(()=>(Ee(),Ir))).getSessionPlayer();await I.closeBatch(i);return}let y;try{if(!((v=(b=(S=o.company)==null?void 0:S.activePlan)==null?void 0:b.premiumFeatures)!=null&&v.applitools)||(y=await dl(o.project),Dr.default.isEmpty(y)||!i))return;let{runKey:I,url:A}=y;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:A,apiKey:I}})}catch{}}}async initRealDataService(e){let t=new xa;return await t.init(e),t}async listenToTestCreatedInFile(e,t,s,n){let o={};e.joinToTestResultsByRunId(s,t);let i=!0;return await new Promise(c=>{let l=m=>{i=!1,c(m)};e.listenToTestResultsByRunId(s,m=>{let d=m.id;if(!n.getTestResult(d)){let f=o[d],h=Dr.default.merge({},f,m,{resultId:d});if(o[d]=h,!f||f.status!==m.status){let w=(n.getTestResult(h.parentResultId)||{workerId:1}).workerId;[Ob.RUNNING].includes(m.status)&&Q.onTestStarted(h,w),[Ob.COMPLETED].includes(m.status)&&(h.duration=h.endTime-h.startTime||0,Q.onTestFinished(h,w))}}let p=!Object.values(o).some(f=>["QUEUED","RUNNING"].includes(f.runnerStatus)),g=!Object.values(n.getAllTestResults()).some(f=>["QUEUED","RUNNING"].includes(f.status));if(p&&g)return l(Object.values(o));if(g&&!p)return se(1e4).then(()=>{i&&l(o)})})})}async initRealDataServiceAndListenToTestsCreatedInFile(e,t,s){let n=await this.initRealDataService(e);return this.listenToTestCreatedInFile(n,e,t,s)}async runTestPlan(e,t,s,n,o,i,a,c){var A,_,R;let l=J(),m=n.project;za(l),e.forEach(L=>Object.assign(L,{isBeforeTestPlan:!0})),s.forEach(L=>Object.assign(L,{isAfterTestPlan:!0}));let d=[...e,...t,...s],p=new bi(d,n,i,a),g=Dr.default.chain(d).map(L=>{var C;return((C=L.overrideTestConfig)==null?void 0:C.name)||""}).uniq().compact().value(),f=(g==null?void 0:g.length)===1?g[0]:null,h=n.files.length>0,y=(A=n.lightweightMode)!=null&&A.onlyTestIdsNoSuite?[]:d.map(L=>L.name),w=(_=n.lightweightMode)!=null&&_.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:s}:p.executionStart(l,m,this.startTime,o,y),S;h&&(S=this.initRealDataServiceAndListenToTestsCreatedInFile(m,l,p)),O("before testListInfoPromise");let b=await w;(R=n.lightweightMode)!=null&&R.onlyTestIdsNoSuite||Q.onTestPlanStarted(b.beforeTests,b.tests,b.afterTests,o,l,c,f,h),O("before runTestAllPhases");let v=await this.runTestAllPhases(b.beforeTests,b.tests,b.afterTests,a,n,l,o||"All Tests",p),I=await ne(S,PR).catch(async()=>{var C;ka.warn("timed out waiting for child results on websocket. using REST fallback",{projectId:m,executionId:l});let L=await on(m,"testResult",`runId=${l}&sort=runOrder`);return Dr.default.chain(((C=L==null?void 0:L.data)==null?void 0:C.docs)||[]).groupBy("parentResultId").omit("undefined").values().flatten().value()});return O("before executionEnd"),await p.executionEnd(l),O("after executionEnd"),{results:v,executionId:l,testPlanName:o,configName:f,childTestResults:I}}async runTestPlans(e,t){ka.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function s(m){return Dr.default.flattenDeep(Object.values(m)).reduce((d,p)=>d.concat(p.beforeTests,p.tests,p.afterTests),[])}let n={},o={},i=e.project,a=await Kc(i,e.testPlan,e.testPlanIds,t,e.intersections),c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new k(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new k(`no test to run in test plan ${e.testPlan}`)}return await kp(e,s(l)),await ce(c,async m=>{let d=m.testPlanId;n[d]={};let p=Object.assign({},e);p.baseUrl=e.baseUrl||m.startUrl,p.host=e.host,p.port=e.port,p.gridId=e.gridId||m.gridId,e.grid&&delete p.gridId,p.gridData=await kf(e,m);let g=p.overrideExecutionName||m.name;return await ce(l[d],async f=>{let h=await this.runTestPlan(f.beforeTests,f.tests,f.afterTests,p,g,d,t),y=e.files.length>0;Q.onTestPlanFinished(h.results,m.name,this.startTime,h.executionId,!1,y,h.childTestResults),n[d][h.executionId]=h.results;let w=Object.keys(n[d]).map(I=>({executionId:I,status:xp(n[d][I])})),S=Object.keys(n[d]).map(I=>n[d][I]).reduce((I,A)=>Object.assign(I,A),{}),b=xp(S);Object.assign(o,S);let v=b?w[0].executionId:w.find(I=>!I.status).executionId;return await Vc(i,d,{success:b,executions:w,executionId:v}),h})})}async runAnonymousTestPlan(e,t){var a;ka.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),O("before getSuite");let s=await Cb(e,t);if(O("after getSuite"),!((a=s==null?void 0:s.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new k("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new k("No tests to run")}t="branch"in s&&s.branch||t;let n=s;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new k("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;return O("Right before validateConfig + runAnonymousTestPlan tests map"),await ce(s.tests,async c=>{if(e.resultId){let d=c[0];d.resultId=e.resultId,c=[d]}await kp(e,c),O("right before runTestPlan");let l=await this.runTestPlan([],c,[],e,o,null,t,i);O("right after runTestPlan");let m=e.files.length>0;return await Q.onTestPlanFinished(l.results,o,this.startTime,l.executionId,i,m,l.childTestResults),l})}async run(e){let t=hn(),s=[];Vs(e)?s=await this.runTestPlans(e,t):s=await this.runAnonymousTestPlan(e,t);let n=Dr.default.flattenDeep(s);return O("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),O("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var Db={};$(Db,{init:()=>KR,run:()=>qR});function AR(r){if(!Pp.get(r,"company.activePlan.premiumFeatures.allowCLI")){let t=r.project;as(r.authData.uid,"cli-not-supported",{projectId:t}),console.warn("Testim CLI is not supported in this plan")}}async function OR(r){let e=r.project,t=await Xc(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"),as(r.authData.uid,"execution-quota-surpassed",{projectId:e}),new Fs}function _R(r,e){var o,i,a,c;if(lo(e.activePlan)==="free"){let l=r.parallel||1,m=((i=(o=e.activePlan)==null?void 0:o.premiumFeatures)==null?void 0:i.concurrency)||1;if(l>m)throw new k(`Cannot run with parallel ${r.parallel}. Max parallel value is ${m}`)}let s=r.retentionDays;if(!s)return;let n=(c=(a=e.activePlan)==null?void 0:a.premiumFeatures)==null?void 0:c.resultRetention;if(s>n)throw new k(`Retention days (${s}) cannot be greater than the company's retention days (${n}). Run aborted`)}async function LR(r){var e;if(!((e=r.lightweightMode)!=null&&e.disableQuotaBlocking))try{await Promise.all([OR(r),AR(r)])}catch(t){if([k,Fs].some(s=>t instanceof s))throw t;CR.error("could not validate cli account",{err:t})}}function DR(r){let e=Mt();return Cm({userId:e.uid,name:e.uid,traits:{projectId:r,company:{id:r,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function NR(r,{disableResults:e=!1,disableRemoteStep:t=!1}){if(M.flags.useNewWSCLI.isEnabled()&&!e&&!t)return $e.connect(r);if(!t){let{remoteStepService:s}=await Promise.resolve().then(()=>(ua(),qy));await s.init(r)}if(!e){let{testResultService:s}=await Promise.resolve().then(()=>(pa(),Jy));s.init(r)}}function MR(r,e){let{branch:t,autoDetect:s}=r;if(Of(e,s),!e&&!s)throw new k(`branch ${t} does not exist, run aborted.`)}async function FR(r){let{project:e}=r,t=hn();Pp.get(r,"company.activePlan.premiumFeatures.ttaForSalesforce")&&(r.sfdcCredential=await Hc({projectId:e,branch:t}))}function UR(r,e){let{onprem:t,id:s,storageBaseUrl:n,storageType:o,name:i,activePlan:a={}}=e;if(t){let{mode:d,extensionPath:p,ext:g,playerPath:f}=r;if([Y.SELENIUM].includes(d)&&!f)throw new k("in selenium on prem mode --player-path must be provided");if(d==="extension"&&!p&&!g)throw new k("In extension on prem mode --ext or --extension-path must be provided")}let c=Boolean(a.isPoc),l=Boolean(a.isStartUp),m=lo(a);m==="free"&&(r.newBrowserWaitTimeout=r.newBrowserWaitTimeout<Lb?Lb:r.newBrowserWaitTimeout),M.setCompanyId(s),M.setIsPOC(c),M.setIsStartUp(l),M.setPlanType(m),xt.setPlanType(m),r.company={companyId:s,onprem:t,storageBaseUrl:n,storageType:o,name:i,planType:m,isPOC:c,isStartUp:l,activePlan:a}}function jR(r,e){if(Ur){r.editorUrl=Ur;return}r.editorUrl=e.editorUrl}function BR(r,e){r.allGrids=e}function $R(r,e){r.authData=e}function WR(r,e){let{id:t,name:s,type:n,defaults:o}=e;M.setProjectId(t),M.setProjectType(n),r.projectData={projectId:t,type:n,name:s,defaults:o}}async function HR(r){r.gridData=await Pf(r)}async function GR(r){let{project:e}=r,t={projectId:e};r.overrideMappingFile&&(ut("user-override-file",t),r.mockNetworkRules=await ym(r.overrideMappingFile))}async function VR(r,e){O("in runner.js runRunner");let{project:t,remoteRunId:s,useLocalChromeDriver:n,useChromeLauncher:o}=r;s||(r.source=n||o?"cli-local":"cli"),await rf(),O("in runner.js after checkNpmVersion"),await LR(r),O("in runRunner before tunnel.connect"),await Zo(r),O("in runRunner after tunnel.connect");let a=await new Pa(e).run(r);return O("before tunnel.disconnect"),await ei(r),await fn.end(t),O("after tunnel.disconnect and gridService.keepAlive.end"),a}function zR(r){var e;xt.shouldShowFreeGridRunWarning((e=r.gridData)==null?void 0:e.type)&&console.log(`
|
|
416
416
|
\x1B[4m\x1B[36mOur Free grid offers basic service performance.
|
|
417
417
|
If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m
|
|
418
|
-
`)}async function
|
|
419
|
-
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`),fn.start(e),
|
|
418
|
+
`)}async function KR(r){var h,y,w;O("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:s,mode:n,disableSockets:o}=r,i=M.fetch(),a=NR(e,{disableResults:o||Boolean((t==null?void 0:t.disableResults)&&(s||n!=="extension")),disableRemoteStep:o||Boolean(t==null?void 0:t.disableRemoteStep)});i.catch(()=>{}),a.catch(()=>{});let{authData:c,editorConfig:l,companyByProjectId:m,projectById:d,branchName:p,allGrids:g}=await an(r);if(_R(r,m),await Promise.all([i,a]),r.browser&&M.flags.dec2022eolBrowsers.isEnabled()){let S=Ks(r.browser);if(S.eol)throw new k(`Unsupported browser: ${S.browserName}`)}O("after featureFlagsReady and socketConnected"),jR(r,l),UR(r,m),WR(r,d),MR(r,p),BR(r,g),$R(r,c),await FR(r),(h=r.lightweightMode)!=null&&h.disableLabs||await Ii.loadLabFeatures(d.id,m.activePlan),((y=r.lightweightMode)==null?void 0:y.type)==="turboMode"&&(M.flags.highSpeedMode.getValue()==="disabled"||r.company.planType==="free")&&delete r.lightweightMode,((w=r.lightweightMode)==null?void 0:w.type)==="turboMode"&&console.log(`
|
|
419
|
+
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`),fn.start(e),DR(e),await GR(r),await HR(r),zR(r);let f=hn();await Q.setOptions(r,f)}var Pp,Lb,CR,qR,Nb=T(()=>{"use strict";Pp=E(require("lodash"));j();jl();ql();Le();ds();cs();Kl();be();Rt();U();jt();pe();ie();V();_b();Nn();Cu();Te();bn();vl();Lb=30*60*1e3,CR=x("runner");qR=VR});function Mb(r){r.get("/",(e,t)=>{let s=Cp();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:s})}),r.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:Ul()})}),r.get("/loginInfo",(e,t)=>{try{let s=JSON.parse(Buffer.from(e.query.info,"base64").toString());Al({overwriteExisting:!1,projects:s}),t.status(200).end()}catch{t.status(400).end()}})}var Fb=T(()=>{"use strict";ls();Ap();jl()});function Bb(r){let e=(0,jb.Router)();return e.post("/run",async(t,s)=>{var a;if(!((a=t.body)!=null&&a.step)){s.status(400).send({error:"Missing step"});return}let{step:n,context:o,loginData:i}=t.body;if(!(r!=null&&r.webdriverApi)){s.status(503).send({success:!1,reason:"Testim Agent was not started with Testim Start."});return}t.setTimeout(0);try{let c=await Is(n,o,r.webdriverApi,i,void 0,"agent");s.status(200).send(c)}catch(c){Ub.error("failed to run hybrid code",{error:c}),s.status(500).send({success:!1,error:c})}}),e.post("/abort",(t,s)=>{var n;if(!((n=t.body)!=null&&n.stepResultId)){s.status(400).send({error:"missing stepResultId"});return}try{sp(t.body.stepResultId),s.status(204).end()}catch(o){let i="No such stepResultId";if((o==null?void 0:o.message)===i){s.status(400).send({error:i});return}Ub.error("hybrid code abort unexpected error",{e:o}),s.status(500).send({error:"unexpected error",info:`${o?o.message:"N/A"}`})}}),e}var jb,Ub,$b=T(()=>{"use strict";Zi();jb=require("express");U();Ub=x("hybrid-router")});var Wb,Nr,Hb,Gb=T(()=>{"use strict";Wb=require("express");U();ep();Nr=(0,Wb.Router)(),Hb=x("codim-router");Nr.get("/tests",async(r,e)=>{let t=await Ju();e.json({tests:t,success:!0})});Nr.get("/locators",async(r,e)=>{let t=await Ln(),s=await Yu(t,Boolean(r.query.full));e.json({locators:t,contents:s,success:!0})});Nr.post("/locators",async(r,e)=>{if(!r.body){e.status(400).send({success:!1,reason:"missing body"});return}if(!r.body.locators){e.status(400).send({success:!1,reason:"missing locators"});return}let{locators:t,mergeIntoExisting:s}=r.body;await Qu(t,{mergeIntoExisting:s||!1}),e.status(200).send({success:!0})});Nr.get("/compile",async(r,e)=>{try{let t=await Zu(r.body.name);e.send({success:!0,code:t})}catch(t){Hb.error(t),e.json({success:!1,reason:t.message})}});Nr.post("/saveTest",async(r,e)=>{if(!r.body){e.status(400).send({success:!1,reason:"missing body"});return}try{await Xu(r.body),e.send({success:!0})}catch(t){e.json({success:!1,reason:t.message}),Hb.error(t)}})});var Op,Vb,As,Ca,qb=T(()=>{"use strict";Op=E(require("chalk"));Cr();Vb=require("express");U();V();As=x("cli-router"),Ca=(0,Vb.Router)();Ca.post("/run",async(r,e)=>{let{code:t,stepId:s,incomingParams:n,context:o,testResultId:i,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:m}=r.body;if(typeof t!="string"||!s||!n||!o||!i||typeof a!="number"||!c||typeof l!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}try{let d=await bs(t,s,n,o,i,a,c,l,m);d.success||(console.log(Op.default.red(d.result.resultValue)),As.error("CLI Action Failure",{message:d.result.resultValue})),e.status(200).json({success:!0,data:d})}catch(d){As.error("failed to run cli code",{err:d}),console.log(Op.default.red("failed to run cli code",d)),e.status(500).json({success:!1,code:"internal-error"})}});Ca.post("/install",async(r,e)=>{let{stepId:t,testResultId:s,retryIndex:n,packageData:o,stepResultId:i,timeout:a}=r.body;if(!t||typeof o!="object"||!s||typeof n!="number"||!i||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}try{let c=await ys(t,s,n,o,i,a);As.info("installed packages successfully"),e.status(200).json({success:!0,data:c})}catch(c){if(c instanceof vt){As.error("failed to install node packages",{err:c}),e.status(200).json({success:!1,code:"invalid-node-package",message:c.message});return}if(c instanceof te){As.error("timeout installing node package"),e.status(200).json({success:!1,code:"timeout"});return}As.error("failed to install node packages",{err:c}),e.status(500).json({success:!1,code:"internal-error"})}})});var JR,zb=T(()=>{"use strict";Cr();U();qb();JR=x("cli-service");Qg().catch(r=>JR.warn("failed to clean local package folder",{err:r}))});async function YR(r,e,t="utf8"){let s=Yb.join(Jb.tmpdir(),r);return await Kb.promises.writeFile(s,e,t),s}async function QR(r){var t;let e=Date.now();try{let s=`
|
|
420
420
|
module.paths = ${JSON.stringify(module.paths)};
|
|
421
421
|
process.on('unhandledRejection', (error) => {
|
|
422
422
|
process.send({type: 'unhandledRejection', error: {message: error.message, stack: error.stack}});
|
|
@@ -427,12 +427,12 @@ Turbo mode will ignore step delays. Test artifacts like screenshots and logs wil
|
|
|
427
427
|
process.exit(1);
|
|
428
428
|
});
|
|
429
429
|
${r};
|
|
430
|
-
`,n=await
|
|
430
|
+
`,n=await YR(`tst-playground-${Date.now()}.js`,s),o=XR(n);Os[e]=o.child;let{error:i,exitCode:a}=await o;if(i)throw i;if(a!==0)throw new Error(`Process exited with exit code: ${a}`);return}finally{(t=Os[e])==null||t.kill(),delete Os[e]}}async function Qb({code:r,type:e}){if(_p.includes(e))return QR(r);throw new Gr}function Zb(){Object.keys(Os).forEach(r=>{Os[r].kill(),delete Os[r]})}var Kb,Jb,Yb,Xb,_p,Os,XR,eT=T(()=>{"use strict";Kb=E(require("fs")),Jb=E(require("os")),Yb=E(require("path")),Xb=require("child_process");V();_p=["playwright","selenium","puppeteer"],Os={};XR=r=>{let e,t=new Promise(n=>{e=n}),s=(0,Xb.fork)(r,{stdio:["inherit","inherit","inherit","ipc"]});return s.on("message",n=>{if(!n)return;let{type:o,error:i}=n;i&&["uncaughtException","unhandledRejection"].includes(o)&&e({error:new Vr(i.stack)})}),s.on("error",n=>{e({error:n})}),s.on("exit",n=>{e({exitCode:n})}),Object.assign(t,{child:s})}});var sT,Aa,nT,tT,rT,ZR,oT=T(()=>{"use strict";sT=require("express");U();V();pe();eT();Aa=(0,sT.Router)(),nT=x("playground-router"),tT=["localhost","app.testim.io","playground.testim.io","staging.testim.io","app.staging.testim.cc","tta-crm.tricentis.com"],rT=r=>{if(!r)return{};try{return new URL(r)}catch{return{}}},ZR=(r,e,t)=>{if(Xn)return t();let{referer:s,origin:n}=r.headers;if(!s&&!n)return e.status(400).send();let o=rT(s),i=rT(n);return!tT.includes(o.hostname)&&!tT.includes(i.hostname)?e.status(400).send():t()};Aa.post("/run",ZR,async(r,e)=>{let{code:t,type:s}=r.body;if(!t||!_p.includes(s)){e.status(400).send({success:!1,reason:"missing arguments"});return}try{await Qb({code:t,type:s}),e.send({success:!0})}catch(n){if(n instanceof Gr){e.status(404).send({success:!1});return}if(n instanceof Vr){e.json({success:!1,type:"playground-error",stack:n.innerStack});return}e.json({success:!1,reason:n.message}),nT.error(n)}});Aa.post("/stop",(r,e)=>{try{Zb(),e.send({success:!0})}catch(t){e.json({success:!1,reason:t.message}),nT.error(t)}})});function aT(r){let e=(0,iT.Router)();return e.get("/cdp-url",(t,s)=>{if(!r){s.status(503).send({error:"Testim standalone browser is not running"});return}s.status(200).send({url:r.webdriverApi.cdpUrl})}),e.get("/status",(t,s)=>{if(!r){s.status(503).send({ok:!1});return}s.status(200).send({ok:!0})}),e}var iT,cT=T(()=>{"use strict";iT=require("express")});var dT={};$(dT,{orchestrateRoutes:()=>eI});function eI(r,e){let t=(0,uT.default)();r(t),t.use(Lp.default.urlencoded({extended:!1,limit:"50mb"})),t.use((0,pT.default)()),t.use(Lp.default.json({limit:"50mb"}));let n={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:De||Xn?"*":["http://localhost:3000","https://app.testim.io","https://staging.testim.io","https://playground.testim.io","https://app.staging.testim.cc","chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia","https://tta-crm.tricentis.com"]};return t.use("*",(0,lT.default)(n)),Mb(t),t.use("/files",Nr),t.use("/playground",Aa),t.use("/cliJs",Ca),t.use("/standalone-browser",aT(e)),t.use("/hybrid",Bb(e)),t.use((o,i)=>{i.status(404).send("Endpoint Not Found")}),t}var lT,uT,Lp,pT,mT=T(()=>{"use strict";lT=E(require("cors")),uT=E(require("express")),Lp=E(require("body-parser")),pT=E(require("compression"));Fb();$b();Gb();zb();oT();cT();pe()});var gT={};$(gT,{init:()=>tI});async function tI({agentPort:r,agentBind:e,project:t,token:s,installPlaygroundPlaywrightDeps:n,installPlaygroundPuppeteerDeps:o,installPlaygroundSeleniumDeps:i},a){await sI({installPlaygroundPlaywrightDeps:n,installPlaygroundPuppeteerDeps:o,installPlaygroundSeleniumDeps:i,project:t}),await rI({agentPort:r,agentBind:e,project:t,token:s},a)}async function rI({agentPort:r,agentBind:e,project:t,token:s},n){let{orchestrateRoutes:o}=await Promise.resolve().then(()=>(mT(),dT));return new Promise((i,a)=>{let c=()=>{};t&&(cm(t,s),c=g=>{g.use((f,h,y)=>{Object.assign(f,{project:t}),y()})});let l=o(c,n),m=fT.createServer(l);m.listen(r,e),m.on("error",d),m.on("listening",p);function d(g){if(g.syscall!=="listen")return a(g);switch(g.code){case"EACCES":case"EPERM":return a(new k(`Port ${r} requires elevated privileges`));case"EADDRINUSE":return a(new k(`Port ${r} is already in use, is another Testim instance running?`));default:return a(g)}}function p(){let{port:g}=m.address();console.log(`Running on port: ${g}`),nI()}})}function sI({installPlaygroundPlaywrightDeps:r,installPlaygroundPuppeteerDeps:e,installPlaygroundSeleniumDeps:t,project:s}){let n=[];return r&&n.push(le("playwright")),e&&n.push(le("puppeteer")),t&&n.push(le("selenium-webdriver"),Er({projectId:s})),Promise.all(n)}async function nI(){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 fT,hT=T(()=>{"use strict";fT=E(require("http"));Rt();V();dt();rs()});var ST={};$(ST,{getStartedWithStart:()=>Cp,runAgentMode:()=>cI});async function cI(r){var s;let e;if(await Sr(r.playerLocation,r.canary),r.startTestimBrowser){await pI();try{e=await uI(r)}catch(n){throw(s=n==null?void 0:n.message)!=null&&s.includes("user data directory is already in use")?new k('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(hT(),gT));return e!=null&&e.webdriverApi&&setTimeout(async()=>{setTimeout(()=>(na(),ve(qu)));let o=["webpack"];for(let i of o)await le(i,{silent:!0}).catch(()=>null)},6e3),t.init(r,e)}function Cp(){return vT}function yT(r){try{return process.kill(r,0)}catch{return!1}}async function lI(r,e,t){let s=pr.join(Nt,`chrome-${tn}-process`),n=3e3,o=()=>{Ae.rmSync(s,{recursive:!0}),console.log(`
|
|
431
431
|
|
|
432
|
-
Browser session ended`),process.exit(0)};if(await ye(s)){let g=JSON.parse(Ae.readFileSync(s));if(
|
|
433
|
-
`).map(o=>o.trim()),s=Number.parseInt(e,10);if(!Number.isInteger(s)||s<1||s>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await wr(`localhost:${s}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:s,webSocketDebuggerUrl:n}}async function
|
|
434
|
-
`):""}overrideMimeType(t){if([Se.LOADING,Se.DONE].includes(this.readyState))throw new mr("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let s=new Ls("readystatechange");this.dispatchEvent(s)}_sendFile(){throw this._url.method!=="GET"?new zn("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||(t=""),this.upload._setData(t),this._finalizeHeaders(t),this._sendHxxpRequest(t)}_sendHxxpRequest(t){let s=this._url.protocol==="http:"?this.nodejsHttpAgent:this.nodejsHttpsAgent,o=(this._url.protocol==="http:"?Ns:Na).request({hostname:this._url.hostname,port:this._url.port,path:this._url.path,auth:this._url.auth,method:this._method,headers:this._headers,agent:s});typeof t=="object"&&t instanceof Hn.default&&t.pipe(o),this._request=o,this.timeout&&o.setTimeout(this.timeout,()=>this._onHttpTimeout(o)),o.on("response",i=>this._onHttpResponse(o,i)),o.on("error",()=>this._onHttpRequestError(o)),this.upload._startUpload(o),this._request===o&&this._dispatchProgress("loadstart")}_finalizeHeaders(t){typeof t=="object"&&t instanceof Hn.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,s){if(this._request!==t)return;if([301,302,303,307,308].includes(s.statusCode)){this._url=this._parseUrl(s.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=s,this._response.on("data",o=>this._onHttpResponseData(s,o)),this._response.on("end",()=>this._onHttpResponseEnd(s)),this._response.on("close",()=>this._onHttpResponseClose(s)),this.status=this._response.statusCode,this.statusText=Ns.STATUS_CODES[this.status],this._parseResponseHeaders(s);let n=this._responseHeaders["content-length"];n?(this._totalBytes=parseInt(n,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(Se.HEADERS_RECEIVED)}_onHttpResponseData(t,s){if(this._response===t)return this._responseParts.push(s),this._loadedBytes+=s.length,this.readyState!==Se.LOADING&&this._setReadyState(Se.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Se.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend")}_onHttpResponseClose(t){if(this._response!==t)return;let s=this._request;return this._setError(),s.abort(),this._setReadyState(Se.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Se.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Se.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let s=new Ls(t);s.lengthComputable=this._lengthComputable,s.loaded=this._loadedBytes,s.total=this._totalBytes,this.dispatchEvent(s)}_setError(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null}_parseUrl(t){let s,n,o,i=this.nodejsBaseUrl===null?t:Ds.resolve(this.nodejsBaseUrl,t),a=Ds.parse(i,!1,!0);return a.hash=null,a.auth&&(typeof o<"u"&&o!==null||typeof n<"u"&&n!==null)&&(s=a.auth.indexOf(":"),s===-1?o||(o=a.auth):(o||(o=a.substring(0,s)),n||(n=a.substring(s+1)))),(o||n)&&(a.auth=`${o}:${n}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([s,n])=>{let o=s.toLowerCase();this._privateHeaders[o]||(this._mimeOverride!==null&&o==="content-type"&&(n=this._mimeOverride),this._responseHeaders[o]=n)}),this._mimeOverride!==null&&!("content-type"in this._responseHeaders)&&(this._responseHeaders["content-type"]=this._mimeOverride)}_parseResponse(){let t=Buffer.concat(this._responseParts);switch(this._responseHeaders["content-encoding"]==="gzip"&&(t=require("zlib").gunzipSync(t)),this._responseParts=null,this.responseType){case"text":this._parseTextResponse(t);break;case"json":this.responseText=null;try{this.response=JSON.parse(t.toString("utf-8"))}catch{this.response=null}break;case"buffer":this.responseText=null,this.response=t;break;case"arraybuffer":{this.responseText=null;let s=new ArrayBuffer(t.length),n=new Uint8Array(s);for(let o=0;o<t.length;o++)n[o]=t[o];this.response=s;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"],s=/;\s*charset=(.*)$/.exec(t);return t&&s?s[1]:"utf-8"}},Oe=Se;Oe.SyntaxError=qn,Oe.ProgressEvent=Ls,Oe.SecurityError=Kn,Oe.XMLHttpRequest=Se,Oe.InvalidStateError=mr,Oe.XMLHttpRequestUpload=Vn,Oe.UNSENT=0,Oe.OPENED=1,Oe.HEADERS_RECEIVED=2,Oe.LOADING=3,Oe.DONE=4;Object.assign(global,{xhr2:Oe,XMLHttpRequest:Oe,performance:
|
|
432
|
+
Browser session ended`),process.exit(0)};if(await ye(s)){let g=JSON.parse(Ae.readFileSync(s));if(yT(g.pid)){let f=()=>yT(g.pid)?setTimeout(f,n):o();return f(),{webdriverApi:g}}}let i=await Io();await ye(_s)||await Ae.promises.mkdir(_s,{recursive:!0});let c=[...ET(_s,e,t,i).desiredCapabilities.chromeOptions.args,..._a.Launcher.defaultFlags().filter(g=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(g))],l={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},m=`${r.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`,d=await _a.launch({chromeFlags:c,startingUrl:m,ignoreDefaultFlags:!0,userDataDir:_s,chromePath:i,envVars:l}),p={port:d.port,pid:d.pid,cdpUrl:await wr(`localhost:${d.port}`)};return Ae.writeFileSync(s,JSON.stringify(p)),d.process.once("exit",o),d.process.once("close",o),{webdriverApi:p}}async function uI(r){let e=`${td}/extension/testim-full-master.zip`,t=pr.basename(e),s=pr.join(Nt,t),n=pr.join(Nt,`${t}__unzipped__`),o=!(r.ext||r.extensionPath);if(o&&await ye(s)){let g=await Ae.promises.stat(s);o=Date.now()-iI>g.mtimeMs}if(await Ae.promises.mkdir(Nt,{recursive:!0}),o){let g=(0,TT.default)("Downloading Testim Editor").start();await qe(e,s);try{await Ze(s,n)}catch{await Ae.promises.rm(s,{recursive:!0,force:!0}),await qe(e,s);try{await Ze(s,n)}catch{throw await Ae.promises.rm(s,{recursive:!0,force:!0}),g.fail("Failed to download Testim Editor"),new Error("Failed to download Testim Editor")}}finally{r.downloadBrowser||await Ae.promises.rm(n,{recursive:!0,force:!0})}g.succeed()}let i=r.extensionPath?null:(await Ae.promises.readFile(r.ext||s)).toString("base64");if(r.downloadBrowser)return await lI(r,i,n);await Er({projectId:r.project},{chromeBinaryLocation:r.chromeBinaryLocations});let a=ET(_s,i,r.extensionPath,r.chromeBinaryLocations),{WebDriver:c}=(In(),ve(Vg)),{SeleniumPerfStats:l}=(fs(),ve(ag)),m=new c;m.seleniumPerfStats=new l;let d=await m.initClient(a);vT=!0;let p=`${r.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`;await m.url(p),Object.assign(m,{initialUrl:p});try{m.cdpUrl=await wr(d.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:m}}function ET(r,e,t,s){let n=e?[e]:[],o=[`--user-data-dir=${r}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];return t&&o.push(`--load-extension=${t}`),{logLevel:oI,desiredCapabilities:{chromeOptions:{args:o,extensions:n,binary:s},browserName:"chrome"},host:"localhost",port:9515}}async function pI(){if(await ye(Oa))try{let{webSocketDebuggerUrl:r}=await dI();await mI(r),await Ae.promises.unlink(Oa)}catch(r){r&&r.message==="unable to connect to devtools http server"&&await Ae.promises.unlink(Oa)}}async function dI(){let r=await Ae.promises.readFile(Oa,{encoding:"utf8"}),[e,t]=r.split(`
|
|
433
|
+
`).map(o=>o.trim()),s=Number.parseInt(e,10);if(!Number.isInteger(s)||s<1||s>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await wr(`localhost:${s}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:s,webSocketDebuggerUrl:n}}async function mI(r,e=100){let t=await fI(r,e);return it(s=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),s)})}async function fI(r,e=100){let t=new wT.default(r,{timeout:e}),s=it(o=>{t.once("open",o)}).then(()=>{t.removeAllListeners()}),n=it(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return Promise.race([s,n]).then(()=>t)}var bT,TT,wT,Ae,pr,_a,oI,iI,_s,aI,Oa,vT,Ap=T(()=>{"use strict";bT=E(require("ms")),TT=E(require("ora")),wT=E(require("ws")),Ae=E(require("fs")),pr=E(require("path")),_a=E(require("chrome-launcher"));pe();rs();V();dt();Nc();j();oI=Zn?"verbose":"silent",iI=(0,bT.default)("1h"),_s=pr.join(Nt,"profile"),aI="DevToolsActivePort",Oa=pr.join(_s,aI);vT=!1});var YD=require("source-map-support/register");var jp;(jp=Array.prototype).at||(jp.at=function(r){let e=Number.isInteger(r)?r:0,t=e>=0?e:this.length+e;if(!(t<0||t>=this.length))return this[t]});var Bp=require("perf_hooks");var Jn=E(require("os")),Ds=E(require("url")),Ns=E(require("http")),Na=E(require("https")),Hn=E(require("form-data")),Gn=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){var s;e=e.toLowerCase(),(s=this._listeners)[e]||(s[e]=[]),this._listeners[e].push(t)}removeEventListener(e,t){let s;e=e.toLowerCase(),this._listeners[e]&&(s=this._listeners[e].indexOf(t),s!==-1&&this._listeners[e].splice(s,1))}dispatchEvent(e){var n;e.currentTarget=this,e.target=this;let t=e.type,s=this._listeners[t]||[];for(let o of s)o==null||o.call(this,e);(n=this[`on${t}`])==null||n.call(this,e)}},Vn=class extends Gn{constructor(t){super();this._request=t;this._contentType=null;this._body=null}_reset(){this._contentType=null,this._body=null}_setData(t){if(!(typeof t>"u"||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 s=Buffer.alloc(t.byteLength),n=new Uint8Array(t);for(let o=0;o<t.byteLength;o++)s[o]=n[o];this._body=s}else if("buffer"in t&&t.buffer instanceof ArrayBuffer){let s=Buffer.alloc(t.byteLength),n=t.byteOffset,o=new Uint8Array(t.buffer);for(let i=0;i<t.byteLength;i++)s[i]=o[i+n];this._body=s}else if(typeof t=="object"&&t instanceof Hn.default)this._body=null;else throw new Error(`Unsupported send() data ${t}`)}_finalizeHeaders(t,s){this._contentType&&!("content-type"in s)&&(t["Content-Type"]=this._contentType),this._body&&(t["Content-Length"]=this._body.length.toString())}_startUpload(t){this._body&&t.write(this._body),t.end()}},Ls=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}},qn=class extends Error{},zn=class extends Error{},Kn=class extends Error{},mr=class extends Error{},Se=class extends Gn{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=Ns.globalAgent;this.nodejsHttpsAgent=Na.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 (${Jn.type()} ${Jn.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=Se.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new Vn(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){Se.prototype.nodejsSet(t)}nodejsSet(t){if("httpAgent"in t&&(this.nodejsHttpAgent=t.httpAgent),"httpsAgent"in t&&(this.nodejsHttpsAgent=t.httpsAgent),"baseUrl"in t){let s=t.baseUrl;if(s!==null&&!Ds.parse(s,!1,!0).protocol)throw new qn("baseUrl must be an absolute URL");this.nodejsBaseUrl=s}}open(t,s,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new Kn(`HTTP method ${t} is not allowed in XHR`);let o=this._parseUrl(s);n===void 0&&(n=!0),this._method=t,this._url=o,this._sync=!n,this._headers={},this._loweredHeaders={},this._mimeOverride=null,this._setReadyState(Se.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,s){if(this.readyState!==Se.OPENED)throw new mr("XHR readyState must be OPENED");let n=t.toLowerCase();this._restrictedHeaders[n]||/^sec-/.test(n)||/^proxy-/.test(n)||(s=s.toString(),n in this._loweredHeaders?(t=this._loweredHeaders[n],this._headers[t]=`${this._headers[t]}, ${s}`):(this._loweredHeaders[n]=t,this._headers[t]=s))}send(t){if(this.readyState!==Se.OPENED)throw new mr("XHR readyState must be OPENED");if(this._request)throw new mr("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new zn(`Unsupported protocol ${this._url.protocol}`)}}abort(){this._request&&(this._request.abort(),this._setError(),this._dispatchProgress("abort"),this._dispatchProgress("loadend"))}getResponseHeader(t){var n;let s=t.toLowerCase();return((n=this._responseHeaders)==null?void 0:n[s])||null}getAllResponseHeaders(){return this._responseHeaders?Object.entries(this._responseHeaders).map(([t,s])=>`${t}: ${s}`).join(`\r
|
|
434
|
+
`):""}overrideMimeType(t){if([Se.LOADING,Se.DONE].includes(this.readyState))throw new mr("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let s=new Ls("readystatechange");this.dispatchEvent(s)}_sendFile(){throw this._url.method!=="GET"?new zn("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||(t=""),this.upload._setData(t),this._finalizeHeaders(t),this._sendHxxpRequest(t)}_sendHxxpRequest(t){let s=this._url.protocol==="http:"?this.nodejsHttpAgent:this.nodejsHttpsAgent,o=(this._url.protocol==="http:"?Ns:Na).request({hostname:this._url.hostname,port:this._url.port,path:this._url.path,auth:this._url.auth,method:this._method,headers:this._headers,agent:s});typeof t=="object"&&t instanceof Hn.default&&t.pipe(o),this._request=o,this.timeout&&o.setTimeout(this.timeout,()=>this._onHttpTimeout(o)),o.on("response",i=>this._onHttpResponse(o,i)),o.on("error",()=>this._onHttpRequestError(o)),this.upload._startUpload(o),this._request===o&&this._dispatchProgress("loadstart")}_finalizeHeaders(t){typeof t=="object"&&t instanceof Hn.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,s){if(this._request!==t)return;if([301,302,303,307,308].includes(s.statusCode)){this._url=this._parseUrl(s.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=s,this._response.on("data",o=>this._onHttpResponseData(s,o)),this._response.on("end",()=>this._onHttpResponseEnd(s)),this._response.on("close",()=>this._onHttpResponseClose(s)),this.status=this._response.statusCode,this.statusText=Ns.STATUS_CODES[this.status],this._parseResponseHeaders(s);let n=this._responseHeaders["content-length"];n?(this._totalBytes=parseInt(n,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(Se.HEADERS_RECEIVED)}_onHttpResponseData(t,s){if(this._response===t)return this._responseParts.push(s),this._loadedBytes+=s.length,this.readyState!==Se.LOADING&&this._setReadyState(Se.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Se.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend")}_onHttpResponseClose(t){if(this._response!==t)return;let s=this._request;return this._setError(),s.abort(),this._setReadyState(Se.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Se.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Se.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let s=new Ls(t);s.lengthComputable=this._lengthComputable,s.loaded=this._loadedBytes,s.total=this._totalBytes,this.dispatchEvent(s)}_setError(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null}_parseUrl(t){let s,n,o,i=this.nodejsBaseUrl===null?t:Ds.resolve(this.nodejsBaseUrl,t),a=Ds.parse(i,!1,!0);return a.hash=null,a.auth&&(typeof o<"u"&&o!==null||typeof n<"u"&&n!==null)&&(s=a.auth.indexOf(":"),s===-1?o||(o=a.auth):(o||(o=a.substring(0,s)),n||(n=a.substring(s+1)))),(o||n)&&(a.auth=`${o}:${n}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([s,n])=>{let o=s.toLowerCase();this._privateHeaders[o]||(this._mimeOverride!==null&&o==="content-type"&&(n=this._mimeOverride),this._responseHeaders[o]=n)}),this._mimeOverride!==null&&!("content-type"in this._responseHeaders)&&(this._responseHeaders["content-type"]=this._mimeOverride)}_parseResponse(){let t=Buffer.concat(this._responseParts);switch(this._responseHeaders["content-encoding"]==="gzip"&&(t=require("zlib").gunzipSync(t)),this._responseParts=null,this.responseType){case"text":this._parseTextResponse(t);break;case"json":this.responseText=null;try{this.response=JSON.parse(t.toString("utf-8"))}catch{this.response=null}break;case"buffer":this.responseText=null,this.response=t;break;case"arraybuffer":{this.responseText=null;let s=new ArrayBuffer(t.length),n=new Uint8Array(s);for(let o=0;o<t.length;o++)n[o]=t[o];this.response=s;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"],s=/;\s*charset=(.*)$/.exec(t);return t&&s?s[1]:"utf-8"}},Oe=Se;Oe.SyntaxError=qn,Oe.ProgressEvent=Ls,Oe.SecurityError=Kn,Oe.XMLHttpRequest=Se,Oe.InvalidStateError=mr,Oe.XMLHttpRequestUpload=Vn,Oe.UNSENT=0,Oe.OPENED=1,Oe.HEADERS_RECEIVED=2,Oe.LOADING=3,Oe.DONE=4;Object.assign(global,{xhr2:Oe,XMLHttpRequest:Oe,performance:Bp.performance,...typeof Blob>"u"&&{Blob:require("buffer").Blob}});var RT=E(require("semver"));Le();vl();qt();rs();var Dp=E(require("chalk")),IT=require("events");ie();ln();V();ie();Co();U();var wm=E(require("os")),El=E(require("path")),Sl=E(require("chalk")),Mo=require("fs");function vm(r){var e,t,s;if(!((e=r==null?void 0:r.message)!=null&&e.includes("SIGINT")))try{let n=wm.homedir();(0,Mo.mkdirSync)(El.resolve(n,".testim_logs"),{recursive:!0});let o=El.resolve(n,".testim_logs",`${new Date().toISOString().replace(/:|\./g,"_")}.log`);console.log("Oops :( The test runner has encountered an unexpected error. A complete log of this run can be found in:"),console.log(` ${o}`),(t=r==null?void 0:r.message)!=null&&t.includes("Unable to compile TypeScript")&&((s=r.stack)!=null&&s.includes("runner/src"))&&process.argv.some(i=>i.includes("player-require-path"))&&(console.log(Sl.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(Sl.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Mo.writeFileSync)(o,`${r}
|
|
435
435
|
${r==null?void 0:r.stack}
|
|
436
436
|
|
|
437
|
-
${JSON.stringify(r,Object.getOwnPropertyNames(r),2)}`)}catch{}}Xs();var
|
|
437
|
+
${JSON.stringify(r,Object.getOwnPropertyNames(r),2)}`)}catch{}}Xs();var Zw=x("process-handler"),Em=!1;function ev(r){return r instanceof Error?1:Em?0:(r||(r={}),Object.values(r).some(({runnerStatus:t,success:s,testStatus:n,status:o})=>[t,o].includes(de.SKIPPED)||[t,o].includes(de.FAILED)&&n===ze.EVALUATING?!1:s!==!0)?1:0)}function tv(){try{zt("chromedriver").stop()}catch{}}function Sm(){Em=!0}async function Rl(r){r!=null&&r.stack&&(ss?console.error(r,r.stack):vm(r)),tv(),await Zw.waitForFlush(),process.exit(ev(r))}be();U();var gI=x("cli-entry");function hI(r){if(!RT.satisfies(process.version,r))throw new k(`Testim.io CLI supports Node.js ${r}. This condition was not satisfied with current version: ${process.version}`);let e=16,t=18,s=Number(process.versions.node.split(".")[0]),n=new Date("2023-09-11T00:00:00.000Z"),o=n<=new Date,i=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(n);if(s<e)throw new k(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(s<t&&o)throw new k(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);s<t&&console.log(Dp.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${i}. please upgrade to a newer Node.js version.`))}async function yI(){console.log("Starting Testim.io CLI");let[r,e]=await Promise.all([Promise.resolve().then(()=>(j(),q)),Promise.resolve().then(()=>(Wm(),$m))]);O("Starting Testim.io CLI"),Tm(Rl);try{hI(r.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{let t=await e.process();if(O("in main, after options.process"),Ja(global.proxyUri),"parallel"in t&&t.parallel>5&&(IT.EventEmitter.defaultMaxListeners=t.parallel*2),Ka(t.project),jd("token"in t&&typeof t.token=="string"?t.token:"anonymous_encrypt_key"),r.isInstallLazyDepsMode(t)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:o}=await Promise.resolve().then(()=>(dt(),qm));return await o()}if(r.isInitCodimMode(t)){let{init:o}=await Promise.resolve().then(()=>(Xm(),Ym));return o(t.initTestProject)}if(r.isLoginMode(t))return;if(r.isCreatePrefetchedDataMode(t)){await Nd(),await an(t);let{preloadTests:o}=await Promise.resolve().then(()=>(Vo(),Zm));await o(t),!t.playerRequirePath&&t.mode!==Y.EXTENSION&&await Sr(t.playerLocation,t.canary);let i=await Fd();i.success?console.log(`created prefetched data at ${ho()}`):console.error("failed to create prefetch data",i.error);return}let s=await Promise.resolve().then(()=>(Nb(),Db));if(r.isTunnelOnlyMode(t)){await s.init(t);let{serveTunneling:o}=await Promise.resolve().then(()=>(ql(),Vl));await o(t);return}if(r.isAgentMode(t)){let{runAgentMode:o}=await Promise.resolve().then(()=>(Ap(),ST));return o(t)}if(t.saveRCALocally){let{initServer:o}=await Promise.resolve().then(()=>(gu(),pg)),{port:i}=await o(t);t.localRCASaver=`http://localhost:${i}`}t.exitCodeIgnoreFailingTests&&Sm(),O("right before testRunner.init/prepareRunner.prepare");let[n]=await Promise.all([hm(t),s.init(t)]);return O("right after testRunner.init/prepareRunner.prepare"),await s.run(t,n)}catch(t){if(t instanceof $r)return;let s=r.getArgsOnRemoteRunFailure();return s&&await hl({...s,error:t.message}).catch(()=>{}),t instanceof k?(console.log(Dp.default.red("Argument Error:",t.message)),t):t instanceof Wr?(console.log("Selenium Error:",t.message),t):(console.log("Error:",t.message),gI.error("runner ended with unexpected error",{err:t}),t)}}yI().then(r=>{Array.isArray(r)&&r.length===0&&console.log("No tests ran"),Rl(r)});
|
|
438
438
|
//# sourceMappingURL=cli.js.map
|