@testim/testim-cli 4.93.0 → 4.95.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 +6 -6
- package/cli.js.map +3 -3
- package/npm-shrinkwrap.json +33 -35
- package/package.json +3 -3
package/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#! /usr/bin/env node
|
|
2
|
-
"use strict";var _T=Object.create;var Hn=Object.defineProperty;var OT=Object.getOwnPropertyDescriptor;var LT=Object.getOwnPropertyNames;var DT=Object.getPrototypeOf,NT=Object.prototype.hasOwnProperty;var w=(s,e)=>()=>(s&&(e=s(s=0)),e);var G=(s,e)=>{for(var t in e)Hn(s,t,{get:e[t],enumerable:!0})},qp=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of LT(e))!NT.call(s,n)&&n!==t&&Hn(s,n,{get:()=>e[n],enumerable:!(r=OT(e,n))||r.enumerable});return s};var E=(s,e,t)=>(t=s!=null?_T(DT(s)):{},qp(e||!s||!s.__esModule?Hn(t,"default",{value:s,enumerable:!0}):t,s)),ye=s=>qp(Hn({},"__esModule",{value:!0}),s);var je={};G(je,{log:()=>M,measure:()=>UT});function M(...s){if(!Jp)return;let e=Date.now();console.log(`${e-MT} ${e-Kp} `,...s),Kp=e}function UT(s,e){if(!Jp)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var Jp,MT,Kp,$e=w(()=>{"use strict";Jp=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,MT=Date.now(),Kp=Date.now()});var zt,Wa,Nr=w(()=>{"use strict";zt="element-6066-11e4-a52e-4f735466cecf",Wa=79});function se(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function qe(s,e,t,r,n){let o="";return n=n?encodeURIComponent(n):"master",e&&t&&(o=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(o+=`?result-id=${r}`)),o}function Va(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function _e(s){let e=/^(https?:\/\/)/i,t=new RegExp("^(?:(?:(?:https?|ftp):)?\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u00a1-\\uffff][a-z0-9\\u00a1-\\uffff_-]{0,62})?[a-z0-9\\u00a1-\\uffff]\\.)+(?:[a-z\\u00a1-\\uffff]{2,}\\.?))(?::\\d{2,5})?(?:[/?#]\\S*)?$","i");return e.test(s)||t.test(s)}var Ga=w(()=>{"use strict"});var qa,Yp,Xp,Zn=w(()=>{qa={ngrok:"4.3.3","v8-to-istanbul":"9.1.0","istanbul-lib-coverage":"3.2.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"1.4.5-lts.1"},Yp={"@applitools/eyes-sdk-core":"13.11.32","@applitools/spec-driver-webdriverio":"1.4.29","@segment/analytics-node":"1.3.0","@types/unzip-stream":"0.3.2",ajv:"6.12.6","body-parser":"1.20.1",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4","coralogix-logger":"1.1.28",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",express:"4.19.2",fkill:"7.2.1","form-data":"3.0.0","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"0.22.10",jsonwebtoken:"9.0.0",linkedom:"0.
|
|
2
|
+
"use strict";var _T=Object.create;var Hn=Object.defineProperty;var OT=Object.getOwnPropertyDescriptor;var LT=Object.getOwnPropertyNames;var DT=Object.getPrototypeOf,NT=Object.prototype.hasOwnProperty;var w=(s,e)=>()=>(s&&(e=s(s=0)),e);var G=(s,e)=>{for(var t in e)Hn(s,t,{get:e[t],enumerable:!0})},qp=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of LT(e))!NT.call(s,n)&&n!==t&&Hn(s,n,{get:()=>e[n],enumerable:!(r=OT(e,n))||r.enumerable});return s};var E=(s,e,t)=>(t=s!=null?_T(DT(s)):{},qp(e||!s||!s.__esModule?Hn(t,"default",{value:s,enumerable:!0}):t,s)),ye=s=>qp(Hn({},"__esModule",{value:!0}),s);var je={};G(je,{log:()=>M,measure:()=>UT});function M(...s){if(!Jp)return;let e=Date.now();console.log(`${e-MT} ${e-Kp} `,...s),Kp=e}function UT(s,e){if(!Jp)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var Jp,MT,Kp,$e=w(()=>{"use strict";Jp=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,MT=Date.now(),Kp=Date.now()});var zt,Wa,Nr=w(()=>{"use strict";zt="element-6066-11e4-a52e-4f735466cecf",Wa=79});function se(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function qe(s,e,t,r,n){let o="";return n=n?encodeURIComponent(n):"master",e&&t&&(o=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(o+=`?result-id=${r}`)),o}function Va(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function _e(s){let e=/^(https?:\/\/)/i,t=new RegExp("^(?:(?:(?:https?|ftp):)?\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u00a1-\\uffff][a-z0-9\\u00a1-\\uffff_-]{0,62})?[a-z0-9\\u00a1-\\uffff]\\.)+(?:[a-z\\u00a1-\\uffff]{2,}\\.?))(?::\\d{2,5})?(?:[/?#]\\S*)?$","i");return e.test(s)||t.test(s)}var Ga=w(()=>{"use strict"});var qa,Yp,Xp,Zn=w(()=>{qa={ngrok:"4.3.3","v8-to-istanbul":"9.1.0","istanbul-lib-coverage":"3.2.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"1.4.5-lts.1"},Yp={"@applitools/eyes-sdk-core":"13.11.32","@applitools/spec-driver-webdriverio":"1.4.29","@segment/analytics-node":"1.3.0","@types/unzip-stream":"0.3.2",ajv:"6.12.6","body-parser":"1.20.1",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4","coralogix-logger":"1.1.28",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",express:"4.19.2",fkill:"7.2.1","form-data":"3.0.0","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"0.22.10",jsonwebtoken:"9.0.0",linkedom:"0.18.0",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2",npm:"10.5.0","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"6.3.1","rox-node":"4.9.18",semver:"7.6.0","serialize-error":"7.0.1","socket.io-client":"4.6.2","source-map-support":"0.5.19",superagent:"9.0.1","superagent-proxy":"3.0.0","test-exclude":"6.0.0","ua-parser-js":"0.7.33","unzip-stream":"0.3.1","validate-npm-package-name":"3.0.0",webdriverio:"7.24.0",winston:"3.11.0","winston-transport":"4.6.0",ws:"8.5.0",xml2js:"0.6.2",yaml:"2.2.2"},Xp={node:">= 18.0.0"}});var ks,Qp,Zp,ed,td,eo,_s,rd,fe,sd,nd,to,Oe,za,od,ro,id,RR,ad,AR,cd,ld,Mr,ud,pd,dd,md,fd,gd,hd,yd,bd,Td,wd,Os,vd,Ed,Sd,Ka,ue=w(()=>{"use strict";ks=process.env.SERVICES_HOST||"https://services.testim.io",Qp="https://testimstatic.blob.core.windows.net",Zp="https://tstresultfiles.azureedge.net";process.env.GATEWAY_URL&&(process.env.CORALOGIX_URL=`${process.env.GATEWAY_URL}/testim/coralogix/api/v1/logs`,process.env.SERVICES_HOST=`${process.env.GATEWAY_URL}/testim/services`,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:ks,ks=process.env.SERVICES_HOST);ed=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),td=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),eo=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),_s=process.env.EDITOR_URL,rd=process.env.WEBSOCKET_HOST||`${ks}/ws`,fe=ks,sd=parseInt(process.env.LOGGER_CONSOLE||"0",10),nd=parseInt(process.env.LOGGER_DEBUG||"0",10),to=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),Oe=parseInt(process.env.IS_ON_PREM||"0",10),za=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,od=parseInt(process.env.DEBUG_MODE||"0",10),ro=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,id=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",RR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),ad=parseInt(process.env.START_WORKER_DELAY_MS||"1500",10),AR=process.env.APPIUM_VERSION||"1.10.1",cd=process.env.GATEWAY_URL,ld=process.env.EXTENSION_SERVICES_HOST||ks,Mr=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:Qp,ud=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:Zp,pd=Qp,dd=Zp,md=5*60*1e3,fd=40,gd=process.env.TMA_BASE_API_URL||"http://127.0.0.1:8585/api",hd=process.env.HEADSPIN_MOBILE_DEVICES_API_URL||"https://api-dev.headspin.io/v0",yd=process.env.HEADSPIN_MOBILE_APPS_API_URL||"https://api-dev.headspin.io/v1",bd=process.env.TDC_MOBILE_DEVICES_API_URL||"https://api.tdc.tricentis-cloud.com/v0",Td=process.env.TDC_MOBILE_APPS_API_URL||"https://api.tdc.tricentis-cloud.com/v1",wd=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Os=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",vd=process.env.SAUCE_LABS_US_APPS_API_URL||"https://api.us-west-1.saucelabs.com/v1",Ed=process.env.SAUCE_LABS_EU_APPS_API_URL||"https://api.eu-central-1.saucelabs.com/v1",Sd=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||60,Ka=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung"});var Ja={};G(Ja,{CoralogixTransport:()=>Ur});var Re,Id,jT,$T,Ur,Ya=w(()=>{"use strict";Re=require("coralogix-logger"),Id=E(require("winston-transport")),jT={debug:Re.Severity.debug,silly:Re.Severity.verbose,verbose:Re.Severity.verbose,silent:Re.Severity.verbose,info:Re.Severity.info,http:Re.Severity.info,warn:Re.Severity.warning,warning:Re.Severity.warning,error:Re.Severity.error,critical:Re.Severity.critical,crit:Re.Severity.critical},$T=["err","error","reason","e"],Ur=class extends Id.default{constructor(t){t={...Ur.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,r){let{category:n,level:o,message:i,meta:a={},...l}=t,c={...a,...this.options.extraFields,...l},d=new Re.Log;d.severity=jT[o],d.text=i,d.category=n,c.className&&(d.className=c.className),c.methodName&&(d.methodName=c.methodName),c.threadId&&(d.threadId=c.threadId),delete c.className,delete c.methodName,delete c.threadId,delete c.category,delete c.level,delete c.message;let m=!1;a instanceof Error&&(m=!0,c.msg=a.message+a.stack,i&&(c.msg=`${i}
|
|
3
3
|
${c.msg}`));for(let u of $T)a[u]instanceof Error&&(c[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(c).length>0&&(i&&!m&&(c.msg=i),d.text=c),this.logger.addLog(d),r(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Re.CoralogixLogger.configure(t),Ur.options=t}}});var sc={};G(sc,{getLogger:()=>x,sessionPlayerLoggerFormatter:()=>Za,setExecutionId:()=>ec,setProjectId:()=>tc,setProxyUri:()=>rc});function GT(){let s=[],e=()=>Promise.resolve();if(!Oe){let{CoralogixTransport:t}=(Ya(),ye(Ja));t.configure(Pd);let r=new t({category:"ROOT"});s.push(r),e=()=>r.waitForFlush()}if(sd){let t={depth:5,colors:!0};s.push(new ft.transports.Console({format:ft.format.combine(ft.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),ft.format.timestamp({format:"HH:mm:ss:SSS"}),ft.format.printf(r=>`[${r.timestamp}] ${r.level} ${r.category}: ${r.message} ${no.inspect(r.meta,t)}`))}))}return[s,e]}function ec(s){Xa=s}function tc(s){kd=s}function rc(s){if(Oe||!s)return;let{CoralogixTransport:e}=(Ya(),ye(Ja));e.configure({...Pd,proxyUri:s})}function Ad(s){return{projectId:kd,time:new Date().toISOString(),...Xa&&!s&&{executionId:Xa}}}function x(s){return new Qa(JT.child({category:s}))}var xd,ft,no,so,Cd,WT,VT,Pd,Rd,Za,HT,qT,zT,KT,JT,Xa,kd,Qa,j=w(()=>{"use strict";xd=E(require("os")),ft=E(require("winston"));ue();no=E(require("util")),so=E(require("chalk")),Cd=E(require("dayjs"));B();WT=xd.hostname(),VT=gt(),Pd={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};Rd={depth:5,colors:!0},Za=(s,e,t)=>{let r=`[${(0,Cd.default)().format("HH:mm:ss:SSS")}]`,n=no.inspect(e,Rd),o=no.inspect(t,Rd);return`${so.default.white(r)} ${so.default.reset()}SessionPlayer-${so.default.red(s)} ${n} ${o}`},[HT,qT]=GT(),zT=nd?"debug":"info",KT={release:Boolean(!0),branch:"production"},JT=ft.createLogger({levels:ft.config.syslog.levels,level:zT,transports:HT,defaultMeta:{name:"runner",hostname:WT,nodeVersion:process.version,runnerVersion:VT,...KT}}),Xa=null,kd=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,r={}){let{executionId:n}=r;try{this._logger.log(e,{meta:r,message:t,...Ad(n)})}catch(o){try{this._logger.log("crit",{message:`failed to log message ${o.message}, ${o.stack}`,...Ad(n)})}catch{}}}waitForFlush(){return qT()}}});var co,Fr,P,Kt,fr,Rt,oo,Br,ne,Ls,ze,Jt,At,io,jr,ao,Ds,K=w(()=>{"use strict";co=require("p-retry"),Fr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},P=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Kt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},fr=class extends Error{constructor(t,r){super(t);this.type=r}},Rt=class extends co.AbortError{},oo=class extends co.AbortError{},Br=class extends co.AbortError{},ne=class extends Error{},Ls=class extends Error{},ze=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Jt=class extends ze{constructor(){super(...arguments);this.name="GridConcurrencyError"}},At=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},io=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},jr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},ao=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Ds=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function nc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function oe(s){return(0,Ld.setTimeout)(s)}function oc(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function ce(s,e,t="Timeout Error"){eo&&!_d&&(_d=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ne(t);return e=eo?Number(eo)||6e5:e,Promise.race([s,oe(e).then(()=>{throw r})])}async function ie(s,e,{concurrency:t}={}){if(t){Od||=(await import("p-limit")).default;let r=Od(t);return await Promise.all(Array.from(s,(n,o)=>r(()=>e(n,o))))}return await Promise.all(Array.from(s,e))}function Yt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var Ld,_d,Od,ic=w(()=>{"use strict";Ld=require("timers/promises");K();ue();_d=!1});var Ms,Dd,YT,Ns,Nd,XT,QT,Md,Ud=w(()=>{"use strict";Ms=E(require("lodash"));ue();Dd=require("dns");j();ic();YT=x("http-request-counters"),Ns=!1,Nd=async()=>{if(Oe)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ie(s,t=>Dd.promises.lookup(t)));return e||(Ns=!0),e}catch{return YT.error("network connectivity test failed"),Ns=!0,!1}},XT=Ms.throttle(Nd,10*1e3),QT=60*1e3*15,Md=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,o){let i=n.get(o)||0;n.set(o,i+1),setTimeout(()=>{let a=n.get(o)||1;n.set(o,a-1)},QT)}function t(n,o=n.name){return async function(...i){e(s.call,o);try{let a=await n.call(null,...i);return e(s.success,o),a}catch(a){throw e(s.fail,o),Ns||XT(),a}}}async function r(){if(Ns||!await Nd())return!1;let n=Ms.sum([...s.fail.values()]),o=Ms.sum([...s.call.values()]);return n<o*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>Ns,t}});var Ke={};G(Ke,{deleteFullRes:()=>sw,deleteReq:()=>Us,didNetworkConnectivityTestFail:()=>fc,download:()=>dc,get:()=>be,getFullRes:()=>ow,getText:()=>Bs,head:()=>iw,isNetworkHealthy:()=>mc,post:()=>Ve,postForm:()=>Fs,postFullRes:()=>nw,postText:()=>uc,put:()=>pc});function ew(){return global.caFileContent}function tw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function rw(){return!xt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(xt.default),global.proxyUri}function gr(s,e=!1){let t=ew();t&&s.ca(t);let r=!e&&rw();r&&s.proxy(r)}async function Fd(s,e={},t={},r=$r){let n=xt.default.delete(s).send(e).timeout(r).set(t);return gr(n),await n}async function cc(s,e,t={},r=$r,n=0){let o=xt.default.post(s).send(e).timeout(r).set(t);gr(o),n&&o.retry(n);try{return await o}catch(i){throw i.url=s,i.originalRequestTimeout=r,i.additionalSetHeaders=t,i}}async function lc(s,e,t={},r=$r,{isBinary:n=!1,skipProxy:o=!1}={}){let i=xt.default.get(s).query(e||{}).timeout(r).set(t);return n&&i.buffer(!0),gr(i,o),await i}var xt,ac,We,$r,ZT,Dt,Us,sw,Ve,nw,Fs,Bs,uc,be,ow,iw,pc,dc,mc,fc,Ge=w(()=>{"use strict";xt=E(require("superagent"));j();Ud();ac=x("http-request"),We=Md(),$r=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,ZT=6e4;Dt=(s,e,t)=>{throw ac.error(s,{...t,error:e}),e};Us=We(async(s,e,t,r)=>{try{let n=await Fd(s,e,t,r);return n.type==="text/plain"?n.text:n.body}catch(n){return Dt("failed to delete request",n,{url:s})}});sw=We(Fd),Ve=We(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let o=await cc(s,e,t,r,n);return o.type==="text/plain"?o.text:o.body}catch(o){return Dt("failed to post request",o,{url:s})}});nw=We(cc),Fs=We(async(s,e,t,r={},n=$r)=>{let o=xt.default.post(s).type("form").timeout(n).set(r);o.field(e),Object.entries(t).forEach(([i,a])=>{o.attach(i,a.buffer,a.fileName)}),gr(o);try{let i=await o;return i.type==="text/plain"?i.text:i.body}catch(i){return Dt("failed to post request",i,{url:s})}});Bs=We(async(s,e,t)=>{try{return(await lc(s,e,t)).text}catch(r){return Dt("failed to getText request",r,{url:s,query:e})}}),uc=We(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await cc(s,e,t,r,n)).text}catch(o){return Dt("failed to post request",o,{url:s})}}),be=We(async(s,e,t,r,n)=>{try{return(await lc(s,e,t,r,n)).body}catch(o){return Dt("failed to get request",o,{url:s,query:e})}}),ow=We((s,e,t,r)=>lc(s,e,t,r)),iw=We(async s=>{let e=xt.default.head(s).timeout($r);gr(e);try{return await e}catch(t){return Dt("failed to head request",t,{url:s})}}),pc=We(async(s,e,t={},r=$r)=>{let n=xt.default.put(s).send(e).timeout(r).set(t);gr(n);try{return(await n).body}catch(o){return Dt("failed to put request",o,{url:s})}}),dc=We(async s=>{ac.info("start to download",{url:s});let e=xt.default.get(s).timeout(ZT).buffer(!0).parse(tw);gr(e);try{let t=await e;return ac.info("finished to download",{url:s}),t}catch(t){return Dt("failed to download",t,{url:s})}}),mc=We.isNetworkHealthy,fc=We.didNetworkConnectivityTestFail});function ht(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Nt.resolve(__dirname,"../../"):s=Nt.resolve(__dirname,""),s):process.cwd()}function lo(s,e){return _e(s)?e||Nt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Nt.basename(s)}function gt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function cw(){try{return Xp.node}catch{return""}}async function $d(s,e,t=!0){let r=await tt.promises.readdir(s,{withFileTypes:!0});await tt.promises.mkdir(e,{recursive:t});for(let n of r){let o=Nt.join(s,n.name),i=Nt.join(e,n.name);n.isDirectory()?await $d(o,i):await tt.promises.copyFile(o,i)}}async function ge(s){try{return await tt.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Nt,Bd,jd,tt,aw,Mt,Je,uo,gc,rt,hc,Wd=w(()=>{"use strict";Nt=E(require("path"));Ga();Zn();Bd=E(require("unzip-stream")),jd=E(require("p-retry")),tt=require("fs"),aw=3;Mt=async s=>{let e=await Promise.resolve().then(()=>(Ge(),Ke));return(0,jd.default)(()=>e.download(s),{retries:aw,factor:1})},Je=async(s,e)=>{let t=await Mt(s);return tt.promises.writeFile(e,t.body)};uo=async(s,e)=>{let t=lo(s,e);return _e(s)?Je(s,t):tt.promises.copyFile(s,t)},gc=async s=>_e(s)?Mt(s):tt.promises.readFile(s),rt=async(s,e)=>await(0,tt.createReadStream)(s).pipe(Bd.Extract({path:e})),hc=s=>(0,tt.statSync)(s).size/1e6});var Ut={};G(Ut,{APPIUM_SESSION_MESSAGE:()=>vc,CLI_MODE:()=>Z,MOBILE_APP_SOURCE:()=>po,MOBILE_RUN_SKIP_REASON:()=>wc,gridMessages:()=>yt,gridTypes:()=>O,mobileWeb:()=>bc,runnerStatus:()=>yc,runnerTestStatus:()=>de,socketEventTypes:()=>Ct,stepResult:()=>$s,test:()=>Tc,testRunStatus:()=>js,testStatus:()=>Ye,timeoutMessages:()=>Ue});var Ue,js,yc,de,Ye,yt,bc,Tc,Ct,Z,O,$s,po,wc,vc,ae=w(()=>{"use strict";Ue={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},js={COMPLETED:"completed",RUNNING:"running"},yc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},de={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Ye={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},yt={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},bc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Tc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},Ct={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},Z={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},O={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},$s={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"},po={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},wc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},vc={APP_NOT_EXIST_ON_DEVICE:"used to start the app doesn't exist or cannot be launched",APP_NEVER_STARTED:"never started",DEVICE_OS_VERSION_TOO_LOW:"DeviceOSVersionTooLow",TIMEOUT_ERROR:"Timeout awaiting 'request'",SAUCELABS_APP_IS_NOT_INSTALLED:"Original error: 'app' option is required for reinstall"}});function Ws(s,e){var t,r,n;return((t=s.testConfigNames)!=null&&t.length||(r=s.testConfigIds)!=null&&r.length||s.testPlan.length||s.testPlanIds.length)&&!s.browser?[...new Set(e.map(o=>{var i;return(i=o.runConfig)==null?void 0:i.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function lw(){let{argv:s}=process;if(s.includes("--remoteRunId"))return{remoteRunId:s[s.indexOf("--remoteRunId")+1],projectId:s[s.indexOf("--project")+1],token:s[s.indexOf("--token")+1]}}var Vs,Vd,Xe,uw,pw,dw,mw,fw,Ec,Sc,Gd=w(()=>{"use strict";ae();Vs=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},Vd=s=>Boolean(s.resultId&&s.source==="remote-run"),Xe=(s,e)=>s.testStatus===Ye.QUARANTINE&&!Vd(e)&&!e.runQuarantinedTests;uw=s=>Boolean(s.loginMode),pw=s=>Boolean(s.tunnelOnlyMode),dw=s=>Boolean(s.createPrefechedData),mw=s=>Boolean(s.installLazyDepsMode),fw=s=>Boolean(s.agentMode),Ec=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Sc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function fo(s=0){return mo.default.duration(s).format("HH:mm:ss.SSS")}function Ic(s=0){return mo.default.duration(s).asSeconds()}var mo,Hd,qd=w(()=>{"use strict";mo=E(require("dayjs")),Hd=E(require("dayjs/plugin/duration"));mo.default.extend(Hd.default)});var Gs,Wr,Hs,zd,Vr,Kd=w(()=>{"use strict";ae();Gs=s=>!(!s||"fileName"in s),Wr=(s,e)=>{if(e===O.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},Hs=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},zd=s=>s===O.TESTIM_TVC,Vr=(s,e)=>zd(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Rc(s=4e3){let e=process.memoryUsage(),t=r=>Math.round(r/1024/1024*100)/100;return{isOverThreshold:t(e.rss)>s,rss:`${t(e.rss)} MB -> Resident Set Size - total memory allocated for the process execution`,heapTotal:`${t(e.heapTotal)} MB -> total size of the allocated heap`,heapUsed:`${t(e.heapUsed)} MB -> actual memory used during the execution`,external:`${t(e.external)} MB -> V8 external memory`}}var Jd=w(()=>{"use strict"});var J={};G(J,{OSS:()=>Gr,TESTIM_BROWSER_DIR:()=>Ft,buildBasicHeader:()=>Va,calcPercentile:()=>yo,copyDir:()=>$d,delay:()=>oe,doesPathExist:()=>ge,download:()=>Mt,downloadAndSave:()=>Je,extractElementId:()=>De,getArgsOnRemoteRunFailure:()=>lw,getBrowserInfo:()=>hw,getCdpAddressForHost:()=>yr,getCliLocation:()=>ht,getDuration:()=>fo,getDurationSec:()=>Ic,getEnginesVersion:()=>cw,getEnvironmentGitBranch:()=>hr,getLocalFileSizeInMB:()=>hc,getMemorySnapshot:()=>Rc,getPlanType:()=>ho,getRunConfigByBrowserName:()=>qs,getRunnerVersion:()=>gt,getSource:()=>uo,getSourceAsBuffer:()=>gc,getSourcePath:()=>lo,getTestUrl:()=>qe,getUniqBrowsers:()=>Ws,groupTestsByRetries:()=>xc,guid:()=>se,hasTestPlanFlag:()=>Vs,isAgentMode:()=>fw,isAppFromDevice:()=>Gs,isAppFromDeviceDisabled:()=>Vr,isCreatePrefetchedDataMode:()=>dw,isInstallLazyDepsMode:()=>mw,isLoginMode:()=>uw,isMobileProject:()=>Hs,isPromise:()=>nc,isQuarantineAndNotRemoteRun:()=>Xe,isRemoteRun:()=>Vd,isTestimVirtualGrid:()=>zd,isTunnelOnlyMode:()=>pw,isURL:()=>_e,promiseAbort:()=>oc,promiseFromCallback:()=>Yt,promiseMap:()=>ie,promiseTimeout:()=>ce,removePropertyFromObject:()=>go,replaceArgsWithNoDashes:()=>Ec,shouldBlockVirtualIosBuild:()=>Wr,spreadObjectToArgs:()=>Sc,unzipFile:()=>rt});function hw(s){return s=s.toLowerCase(),Ac.find(e=>e.browserValue===s)}function qs(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Ac.find(o=>o.browserName.toLowerCase()===s||s.includes(o.synonyms))||Ac[0],n=Gr.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=Gr.find(o=>o.sl.platform===e.platform):e.platformName&&(n=Gr.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=Gr.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=Gr.find(o=>o.bs.platform===t.platform))),Hr.merge(r,n)}function hr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function go(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&go(s[r],e,t))}function De(s){return s.ELEMENT||s[zt]}function ho(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function xc(s=[]){return Hr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((o,i)=>{let a=typeof o.retryCount=="number"?o.retryCount:1,l=typeof i.retryCount=="number"?i.retryCount:1;return a===l?o.startTime-i.startTime:(o.retryCount??0)-(i.retryCount??0)}),n=Hr.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}async function yr(s,e){let t=await Promise.resolve().then(()=>(Ge(),Ke));try{return(await t.get(`http://${s}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var Yd,Hr,Xd,gw,Ft,Gr,Ac,yo,B=w(()=>{"use strict";Yd=E(require("os")),Hr=E(require("lodash")),Xd=E(require("path"));Nr();Wd();Gd();qd();Ga();ic();Kd();Jd();gw=Yd.homedir(),Ft=Xd.join(gw,".testim-browser-profile"),Gr=[{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 Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17"},sl:{}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{platform:"macOS 10.15",safari_version:"latest"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{platform:"macOS 10.14",safari_version:"latest"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{platform:"macOS 10.13",safari_version:"latest"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{platform:"macOS 10.12",safari_version:"latest"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"latest"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"latest"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"latest"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"latest"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],Ac=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:"112"},sl:{browserName:"chrome",version:"94.0"},browserValue:"chrome"},{browserName:"Firefox",bs:{browser:"Firefox",browser_version:"89"},sl:{browserName:"firefox",version:"89.0"},browserValue:"firefox"},{browserName:"Safari",bs:{browser:"Safari"},sl:{browserName:"safari"},browserValue:"safari"},{browserName:"Edge Chromium",bs:{browser:"Edge",browser_version:"112"},sl:{browserName:"MicrosoftEdge",version:"94"},synonyms:["edge-chromium"],browserValue:"edge-chromium",seleniumName:"MicrosoftEdge"},{browserName:"Browser",bs:{},sl:{browserName:"Browser"},browserValue:"browser"},{browserName:"Android",bs:{browserName:"android"},sl:{},browserValue:"android"},{browserName:"iPad",bs:{browserName:"iPad"},sl:{},browserValue:"ipad"},{browserName:"iPhone",bs:{browserName:"iPhone"},sl:{},browserValue:"iphone"}];yo=(s,e)=>{if(s.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(s=[...s].sort((r,n)=>r-n),e<=0)return s[0];if(e>=100)return s.at(-1);let t=Math.ceil(s.length*(e/100))-1;return s[t]}});var Cc={};G(Cc,{$schema:()=>yw,default:()=>Ew,definitions:()=>bw,properties:()=>vw,required:()=>ww,type:()=>Tw});var yw,bw,Tw,ww,vw,Ew,Qd=w(()=>{yw="http://json-schema.org/draft-07/schema#",bw={request:{type:"object",required:["url"],additionalProperties:!1,properties:{url:{type:"string"},method:{type:"string",pattern:"^GET$|^HEAD$|^POST$|^PUT$|^DELETE$|^CONNECT$|^OPTIONS$|^TRACE$|^PATCH$"}}},header:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"}}},cookie:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"},path:{type:"string"},domain:{type:"string"},expires:{type:"string",format:"date-time"},httpOnly:{type:"boolean"},secure:{type:"boolean"}}},response:{type:"object",required:["status"],additionalProperties:!1,properties:{status:{type:"integer",minimum:100,exclusiveMaximum:600},headers:{type:"array",items:{$ref:"#/definitions/header"}},cookies:{type:"array",items:{$ref:"#/definitions/cookie"}},content:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}}},redirectResponse:{type:"object",required:["redirectUrl"],additionalProperties:!1,properties:{redirectUrl:{type:"string"}}},passthroughResponse:{type:"object",required:["passthrough"],additionalProperties:!1,properties:{passthrough:{type:"boolean",enum:[!0]}}},entry:{type:"object",required:["request","response"],additionalProperties:!1,properties:{request:{$ref:"#/definitions/request"},response:{oneOf:[{$ref:"#/definitions/response"},{$ref:"#/definitions/redirectResponse"},{$ref:"#/definitions/passthroughResponse"}]},maxHits:{type:"integer",minimum:1}}}},Tw="object",ww=["entries"],vw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},Ew={$schema:yw,definitions:bw,type:Tw,required:ww,properties:vw}});async function om(){try{return await ce(bo.promises.readFile(Eo()).then(async s=>{let e=await nm;return Rw(e,s)}),3e4)}catch{return{}}}function Rw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),o=zr.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),i=o.update(r);return JSON.parse(Buffer.concat([i,o.final()]))}function bt(s,e,t=Sw,r=void 0){return async()=>{if(!tm)return await s();let n=e;r&&(e+=JSON.stringify(r));let o=await Aw(e);if(o)return zs.debug("cache hit:",{fnName:e}),o;if(zs.debug("cache miss:",{fnName:e}),!rm)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let i=await s();return i&&await xw(e,i,t),i}}async function Aw(s){let t=(await So)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function xw(s,e,t){if(Pc)throw zs.error("calling set after waitForSave is not allowed",{key:s,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let r=await So;r[s]={value:e,expiry:Date.now()+t},sm=new Promise(n=>{vo=n}),Iw(r)}catch{zs.error("failed updating cache")}}async function Kr(){let s=await So;Object.keys(s).forEach(e=>{delete s[e]})}function im(s){tm=s}function Cw(s=!0){rm=s}async function am(){try{return Pc=!0,await sm}finally{Pc=!1}}function cm(s){wo=s,So=om()}var bo,To,zr,Zd,zs,wo,em,vo,tm,rm,Pc,sm,nm,Sw,Eo,So,Iw,lm,um,ZR,pm,Bt=w(()=>{"use strict";bo=E(require("fs")),To=E(require("path")),zr=E(require("crypto"));B();Zd=require("lodash");j();zs=x("local cache"),wo=To.resolve(ht(),"testim-cache"),tm=!0,rm=!0,Pc=!1,sm=new Promise(s=>{vo=s}),nm=new Promise(s=>{em=s}),Sw=1e3*60*60*3,Eo=()=>To.resolve(To.resolve(wo,"testim.cache"));So=om(),Iw=(0,Zd.debounce)(async s=>{let e;try{let t=await nm,r=zr.randomBytes(16),n=JSON.stringify(s),o=Buffer.from(t),i=zr.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),r),a=Buffer.concat([r,i.update(n),i.final()]);await ge(wo)||await bo.promises.mkdir(wo,{recursive:!0}),await bo.promises.writeFile(Eo(),a)}catch(t){zs.error("failed saving cache",{err:t}),e=t}vo(e?{success:!1,error:e}:{success:!0})},200);lm=em,um=im.bind(void 0,!1),ZR=im.bind(void 0,!0),pm=()=>Cw(!1)});function Io(){return{cliLocation:ht(),userInfo:Jr.userInfo(),platform:Jr.platform(),release:Jr.release()}}var Jr,kc=w(()=>{"use strict";Jr=E(require("os"));B()});function Pw(s){try{return Ro.resolve(Ro.dirname(require.resolve(`${s}/package.json`)),require(`${s}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(s);throw e}}function Qt(s){let e=Pw(s);return require(e)}var Ro,Ks=w(()=>{"use strict";Ro=E(require("path"))});function kw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function _w(s){return/The "to" argument must be of type string./.exec(s)}function gm(s,e,t){let r=kw(s),n=_w(s);return r||n?(fm.info("Failed to install package due to insufficient write access",{...Io(),package:t,path:r}),console.error(`
|
|
4
4
|
|
|
5
5
|
Testim failed installing the package ${t||""} due to insufficient permissions.
|
|
@@ -13,13 +13,13 @@ Testim had missing write access to ${r||e}
|
|
|
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 jw(){let s=`${Mr}/extension/sessionPlayer_LATEST_RELEASE`;return(await Mt(s)).body.toString("utf8")}async function $w(s,e){if(!_e(s)||_e(s)&&e||Oe)return s;let t=await jw();return`${s}-${t}`}function Bc(){let s=ht();return Xr.resolve(s,"testim-bin")}function Ww(){let s=Bc();return Xr.resolve(s,"sessionPlayer.zip")}async function Dm(s,e,t=!1){try{return await uo(s,e),await rt(e,Bc())}catch(r){if(t)throw r;return await Dm(s,e,!0)}}async function Tr(s,e){ko.info("prepare player",{location:s,canary:e});let t=Ww();return bt(async()=>{let r=await $w(s,e);return await Dm(r,t),{}},"preparePlayer",Lm,[s,e,t])()}var km,_m,Xr,Om,ko,Lm,Mc,Pm,Xs=w(()=>{"use strict";km=E(require("ms")),_m=E(require("fs")),Xr=E(require("path"));ue();Bt();Om=require("serialize-error");j();kc();K();B();ko=x("prepare runner and testim start"),Lm=(0,km.default)("0.5 day"),Mc=16,Pm=`The size of the custom extension is more than ${Mc}MB`});function Vw(){let s=Qs.type().toLowerCase();return s==="darwin"?Qs.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?Qs.arch()==="x64"?"win64":"win32":"linux"}async function Oo(){let s=Vw(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(s in t))throw new P(`Unsupported platform: ${s}`);let r=parseInt(Zs,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},o={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},i=`${e}/${t[s]}/${Zs}/${n[s]}.zip`,a=_o.join(jc,n[s]),l=`${a}.zip`,c=_o.join(a,o[s]);if(await ge(c))return c;if(!await ge(l)){let m=(0,$c.default)("Downloading Chromium").start();try{await Nm.promises.mkdir(jc),await Je(i,l)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,$c.default)("Extracting Chromium").start();try{await rt(l,jc)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),c}var Nm,Qs,_o,$c,Zs,jc,Wc=w(()=>{"use strict";Nm=E(require("fs")),Qs=E(require("os")),_o=E(require("path")),$c=E(require("ora"));K();B();Zs="1000968",jc=_o.join(Ft,`chrome-${Zs}`)});async function Bm(s,e){return wr=s,qc=e,await Vc()}function jm(s,e){wr=e.projectId,qc=e.token,en=e.userAccessKey,st=s.token,rn=zc(st),sn=s.refreshToken,Gc=s.ngrokToken,Hc=s.isNgrokWhitelisted,Mm=e.publicIp,Um=e.initializedFromCache}function Gw(s=wr,e=qc){return bt(()=>(tn.info("request to get cli token from server"),Ve({url:`${fe}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",Fm*10,{projectId:s,token:e})()}async function Hw(){tn.info("request to refresh JWT cli token from server");let s=await Ve({url:`${fe}/auth/refreshToken`,body:{token:st,refreshToken:sn}});return st=s.token,rn=zc(st),s.refreshToken&&(sn=s.refreshToken),st}async function Vc(){try{let s=await Gw();return tn.info("successfully get cli token from server"),st=s.token,rn=zc(st),sn=s.refreshToken,Gc=s.ngrokToken,Hc=s.isNgrokWhitelisted,st}catch(s){throw s.message.includes("Unauthorized")?new P("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(tn.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:wr}),new P(`While trying to retrieve CLI token, caught error: ${s}`))}}function zc(s){return require("jsonwebtoken").decode(s).exp*1e3}async function Zt(){if(!rn)return Vc();if(rn<Date.now()+4*Fm)try{return await Hw()}catch(s){return tn.error("failed to refresh token, executing fallback",s),Vc()}return st}function Lo(){return sn}function jt(){return st?{uid:require("jsonwebtoken").decode(st).id,ngrokToken:Gc,isNgrokWhitelisted:Hc}:{}}async function Do(){if(!en||!wr)return;if(await Kc({userAccessKey:en,projectId:wr}))return en;let e=`user access key "${en}" is invalid for project "${wr}"`;throw new P(e)}function No(){return Mm}function Mo(){return Um}var tn,st,rn,sn,Gc,Hc,wr,qc,en,Mm,Um,Fm,nt=w(()=>{"use strict";ue();Ge();Bt();K();j();he();tn=x("testim-custom-token"),wr=null,qc=null,Fm=5*60*1e3});var $m={};G($m,{isCi:()=>Qr});var Qr,Uo=w(()=>{"use strict";Qr=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var xe={};G(xe,{addTestRetry:()=>bl,clearTestResult:()=>gl,deleteCloudflareTunnel:()=>El,fetchLambdatestConfig:()=>dl,fixGridAppIDStructure:()=>Al,forceUpdateCloudflareTunnelRoutes:()=>vl,getAllGrids:()=>pl,getAppDetails:()=>an,getApplitoolsIntegrationData:()=>Tl,getBrowserStackSessionMetaData:()=>tv,getCloudflareTunnel:()=>wl,getEditorUrl:()=>Qw,getGridById:()=>Bo,getGridByName:()=>ll,getHybridGridProvider:()=>cl,getLabFeaturesByProjectId:()=>ml,getMobileDevicesFromGrid:()=>Il,getRealData:()=>fl,getS3Artifact:()=>on,getS3ArtifactText:()=>Yc,getSuiteTestList:()=>sl,getTestPlan:()=>Xw,getTestPlanTestList:()=>rl,getTestResults:()=>Er,getUsageForCurrentBillingPeriod:()=>nl,initializeUserWithAuth:()=>ul,isTestResultCompleted:()=>ol,keepAliveCompanySlots:()=>kl,keepAliveGrid:()=>il,loadSfdcCredential:()=>Xc,loadTest:()=>Qc,releaseCompanySlot:()=>Cl,releaseGridSlot:()=>al,reportExecutionFinished:()=>Fo,reportExecutionStarted:()=>tl,requestCompanySlot:()=>xl,saveRemoteStep:()=>hl,saveTestPlanResult:()=>Zc,updateCompanySlot:()=>Pl,updateExecutionTests:()=>el,updateRemoteRunFailure:()=>Sl,updateTestDataArtifact:()=>$o,updateTestResult:()=>jo,updateTestStatus:()=>vr,uploadAppToGrid:()=>Rl,uploadRunDataArtifact:()=>yl,validateUserAccessKey:()=>Kc});async function Zr(){let s=await Zt();if(!s)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${s}`}}async function Ae({url:s,body:e,headers:t={},timeout:r,retry:n}){let o=await Zr(),i={...t,...o};return Ve({url:`${fe}${s||""}`,body:e,headers:i,timeout:r,retry:n})}async function Kw(s,e,t,r={},n=void 0){let o=await Zr(),i={...r,...o};return await Fs(`${fe}${s||""}`,e,t,i,n)}async function nn(s,e){let t=await Zr();return await pc(`${fe}${s||""}`,e,t)}async function Jw(s,e){let t=await Zr();return await Us(`${fe}${s||""}`,e,t)}async function Yw(s,e){let t=await Zr();return await Bs(`${fe}${s||""}`,e||void 0,t)}async function Se(s,e,t,r){let n=await Zr();return await be(`${fe}${s||""}`,e||void 0,n,r,t)}function on(s,e){return(0,X.default)(()=>Se(`/storage${s}`,null,{isBinary:!0},e),{retries:ee,factor:1})}function Yc(s){return(0,X.default)(()=>Yw(`/storage${s}`))}async function Xw(s,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,X.default)(()=>Se("/testPlan",{projectId:s,name:e.join(",")}),{retries:ee,factor:1})).map(({testConfigIds:n,beforeAllLabels:o,testLabels:i,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(o),testLabels:t(i),afterAllLabels:t(a)}))}async function Xc({branch:s,projectId:e}){let t=await(0,X.default)(()=>Se(`/branch/branchData/${s}`,{projectId:e}),{retries:ee,factor:1});return t==null?void 0:t.sfdcCredential}function Qc({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,X.default)(()=>Se(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:ee,factor:1})}function Zc(s,e,t){return(0,X.default)(()=>Ae({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:ee,factor:1})}function vr(s,e,t,r,n,o,i=ee){return(0,X.default)(()=>nn("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:qw,...o}),{retries:i,factor:1})}function el(s,e,t,r,n,o,i,a){return(0,X.default)(()=>nn("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:o,endTime:i,projectId:a}),{retries:ee,factor:1})}async function tl({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:o,resultLabels:i,remoteRunId:a,localRunUserId:l,isLocalRun:c,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(Uo(),$m));return Ae({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:o,resultLabels:i,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function Fo(s,e,t,r,n={},o=void 0,i=void 0){let a=Date.now();return(0,X.default)(()=>nn("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:ee,factor:1})}async function rl(s,e,t,r,n){return(0,X.default)(()=>Ae({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:ee,factor:1})}function sl({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,X.default)(()=>Ae({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:ee,factor:1})}async function an({appId:s,projectId:e}){try{return await(0,X.default)(()=>Se(`/mobile-app/app/${s}?projectId=${e}`),{retries:ee,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function nl(s){try{return await(0,X.default)(()=>Se(`/plan/project/${s}/usage-current-billing-period`),{retries:ee,factor:1})}catch(e){Wt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function ol(s,e,t){return(0,X.default)(()=>Se(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:ee,factor:1})}function Er(s,e,t,r){return(0,X.default)(()=>Se(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:ee,factor:1})}function il(s,e){return Ae({url:`/grid/keep-alive?reqId=${se()}`,body:{projectId:s,slots:e},timeout:1e4})}function al(s,e,t,r,n){return Ae({url:`/grid/release?reqId=${se()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function cl(s){return Ae({url:"/grid/hybrid/provider",body:s})}function ll(s,e,t,r,n){return(0,X.default)(()=>Se("/grid/name",{companyId:s,projectId:e,name:t,browser:r,executionId:n,reqId:se()}),{retries:ee,factor:1})}function Bo(s,e,t,r,n){return(0,X.default)(()=>Se(`/grid/${t}`,{companyId:s,projectId:e,browser:r,executionId:n,reqId:se()}),{retries:ee,factor:1})}async function ul({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,gridId:o,grid:i}){var a,l;try{return await(0,X.default)(()=>Ve({url:`${fe}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,gridId:o,gridName:i}}),{retries:ee,factor:1})}catch(c){throw Wt.error("error initializing info from server",c),(a=c==null?void 0:c.message)!=null&&a.includes("Bad Request")?new P("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(l=c==null?void 0:c.code)!=null&&l.includes("ENOTFOUND")?new P("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):c}}async function Qw(){if(_s)return{editorUrl:_s};try{return await(0,X.default)(()=>Se("/system-info/editor-url"),{retries:ee,onFailedAttempt:s=>{if(s.attemptNumber>=ee)throw s},factor:1})}catch{return Wt.error("cannot retrieve editor-url from server"),{editorUrl:"https://app.testim.io"}}}function pl(s){return(0,X.default)(()=>Se("/grid",{companyId:s}),{retries:ee,factor:1})}function fl(s,e,t){return(0,X.default)(()=>Se(`/real-data/${e}?${t}&projectId=${s}`),{retries:ee,factor:1})}function jo(s,e,t,r,n){return(0,X.default)(()=>Ae({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:ee,factor:1})}function gl(s,e,t,r){return(0,X.default)(()=>Ae({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:ee,factor:1})}function hl(s,e,t,r){return(0,X.default)(()=>Ae({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:ee,factor:1})}function Zw(s){return s.startsWith("/")?s:`/${s}`}function ev(s,e,t){let r=Zw(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Vm(s,e,t,r,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${se()}${i||""}`,l=`${e}/${t}/${a}`,c=ev(l,"test-result-artifacts",s),d=Buffer.from(Wm.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,X.default)(()=>Kw(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:ee,factor:1}),c}function bl({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:o,testResult:i}){return(0,X.default)(()=>Ae({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:ee,factor:1})}async function Tl(s){try{return await Se(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Wt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function wl(s,e){try{return await nn("/tunnel",{companyId:s,routes:e})}catch(t){return Wt.warn("could'nt get tunnel.",{err:t}),{}}}async function vl(s,e){try{return await Ae({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}async function El(s,e){try{return await Jw(`/tunnel/${e}`,{companyId:s})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}function Sl(s){return Ve({url:`${fe}/result/remoteRunFailure`,body:s})}async function Il({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let o=`${zw}/mobileDevices/${t}/${r}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await(0,X.default)(()=>Se(o,{projectId:s}),{retries:ee,factor:1})}catch(i){return Wt.warn("could'nt get devices from headspin grid.",{err:i}),null}}async function Rl({projectId:s,gridId:e,app:t,timeout:r}){return(0,X.default)(()=>Ae({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:ee,factor:1})}async function Al(s){return(0,X.default)(()=>Ae({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:ee,factor:1})}async function xl(s,e){return(0,X.default)(()=>Ae({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:ee,factor:1})}async function Cl(s,e,t){return(0,X.default)(()=>Ae({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:ee,factor:1})}async function Pl(s,e,t){return(0,X.default)(()=>nn("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:ee,factor:1})}function kl(s,e,t){return Ae({url:`/slot-management/keep-alive?reqId=${se()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function tv(s,e){return await be(`${Os}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function Kc(s){try{return await Se("/v2/project/validateUserAccessKey",s),!0}catch(e){return Wt.error("error validating user access key",{error:e}),!1}}var er,Wm,X,Jc,qw,Wt,ee,zw,dl,ml,yl,$o,he=w(()=>{"use strict";er=E(require("lodash")),Wm=E(require("pako"));B();ue();ae();Ge();nt();X=E(require("p-retry")),Jc=E(require("object-hash"));K();j();qw=gt(),Wt=x("testim service api"),ee=3,zw="/grid";dl=async()=>(0,X.default)(()=>Se("/grid/lt/config"),{retries:ee,factor:1}),ml=async s=>(0,X.default)(()=>Se(`/labFeature/v2/project/${s}`),{retries:ee,factor:1});yl=er.memoize(async(s,e,t,r)=>{if(!er.isEmpty(r))return await Vm(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,Jc.default)(r)}:${e}:${t}`),$o=er.memoize(async(s,e,t,r,n)=>!r||er.isEmpty(r)?void 0:await Vm(s,e,t,JSON.stringify((()=>{let i=er.clone(r);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(l=>{i[l]&&Object.assign(i,{[l]:Tc.HIDDEN_PARAM})})}return i})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,Jc.default)(r)}:${e}:${t}`)});async function Gm(){return await Promise.any(rv.map(async s=>{try{let e=await be(s);return e==null?void 0:e.ip}catch{return null}}))}var rv,Hm=w(()=>{"use strict";Ge();rv=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"]});var tr={};G(tr,{getSessionPlayer:()=>te,options:()=>Ol});var Wo,Ol,_l,te,Te=w(()=>{"use strict";Wo=require("path");j();Ol={playerPath:void 0},te=()=>{if(_l)return _l;let s=($e(),ye(je));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(Xs(),ye(Ys)),t=e(),r=Ol.playerPath?(0,Wo.resolve)(Ol.playerPath,"src/background/sessionPlayerInit.ts"):(0,Wo.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),_l=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(Za),n}});function ov(s){process.nextTick(()=>{if([Z.SELENIUM,Z.APPIUM].includes(s))try{(Te(),ye(tr)).getSessionPlayer()}catch{}})}async function cn(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:o,useChromeLauncher:i,mode:a,gridId:l,grid:c}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(o||i),u=d?nv:sv,f=null;if(D.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{f=await Gm()}catch(y){qm.error("failed to get public ip",y)}let h=!0;M("before initializeUserWithAuth");let g=await bt(async()=>(ov(a),h=!1,await ul({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,gridId:l,grid:c})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:l,grid:c,publicIp:f})();return M("after initializeUserWithAuth"),f&&g.clientPublicIp&&g.clientPublicIp!==f&&qm.error("public ip mismatch",{publicIpFromExternalService:f,publicIpFromServices:g.clientPublicIp}),jm(g.authData,{projectId:e,token:t,userAccessKey:r,publicIp:g.clientPublicIp,initializedFromCache:h}),g}var qm,sv,nv,zm=w(()=>{"use strict";$e();he();Bt();nt();Hm();ae();j();pe();qm=x("initializeUserWithAuth"),sv=1e3*60*5,nv=1e3*60*60*10});async function Ym(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Oo():s.chromeBinaryLocation,e=Js({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==Z.EXTENSION&&await Tr(s.playerLocation,s.canary),s.mode===Z.EXTENSION&&!s.ext&&await Fc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await Uc(s.installCustomExtension,n)}return await e,t}async function Xm(s){var i;iv.info("prepare MockNetwork",{location:s});let e=await gc(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>Km*1e6)throw new Error(`${Ll} exceeded ${Km}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${Ll} cannot be parsed.${Vo.EOL}${a}`)}let n=new Jm.default;if(!n.validate(Cc,r)){let a=(i=n.errors)==null?void 0:i.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(Vo.EOL);throw new Error(`${Ll} is malformed.${Vo.EOL}${a}`)}return r.entries}var Vo,Jm,Km,Ll,iv,Dl=w(()=>{"use strict";Vo=E(require("os"));B();Qd();Xs();Jm=E(require("ajv"));ae();Wc();zm();Km=1,Ll="JSON file supplied to --mock-network-pattern",iv=(j(),ye(sc)).getLogger("prepare runner")});function Zm(s,e=process){async function t(r){await ce(ie(Qm,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{ln.error("Caught exception",{err:r}),console.log("Uncaught exception"),r.message&&console.log("Message =",r.message),r.reason&&console.log("Reason =",r.reason),await t(r)}),e.on("unhandledRejection",r=>{var n;if(ln.fatal("Caught unhandled promise rejection",r),!((n=r==null?void 0:r.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{ln.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw ln.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw ln.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function es(s){Qm.push(s)}var ln,Qm,un=w(()=>{"use strict";j();B();ln=x("process-handler"),Qm=[]});function Fl(s,e){let t=s.canary?"-master.zip":".zip",r=`${e?pd:Mr}/extension/testim-firefox-profile${t}`,n=`${e?dd:Mr}/extension/testim-headless${t}`;return{firefox:r,chrome:n,"edge-chromium":n}}function nf(s){let{chrome:e,firefox:t}=Fl(s,!1);return s.browser==="firefox"?t:s.browser==="chrome"?e:[e,t]}function Ho(s){let e=`${Mr}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var qo=w(()=>{"use strict";ue()});function uf(s){Oe||(s!=null&&s.userId||(s={anonymousId:lf}),cf.identify(s))}function Tt(s,e){return pn("ci",s,e)}function pn(s,e,t){if(Oe)return;let r=s?{userId:s}:{anonymousId:lf};cf.track(Object.assign(r,{event:e,properties:t}))}var af,cf,lf,ts=w(()=>{"use strict";ue();af=require("@segment/analytics-node"),cf=new af.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1}),lf=require("crypto").randomBytes(20).toString("hex")});function pf(s){return s.start&&pn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function df(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new P("Agent port is not number");let t=Ho(s);return console.log("Start Testim CLI on Agent mode"),{project:s.project,token:s.token,agentMode:!0,agentPort:s.agentPort,agentBind:s.agentBind,openEditor:s.openEditor,startTestimBrowser:e,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||t,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:Boolean(s.downloadBrowser)}}var mf=w(()=>{"use strict";qo();ts();K()});var ff,mv,fv,Bl,gf=w(()=>{"use strict";ff="TST_CREDS",mv=["username","password"],fv="$encrypted",Bl={get proxyPlaceholder(){return new Proxy({},{get(s,e){let t={};for(let r of mv)t[r]={[fv]:`${e}.${r}`};return t}})},containsEncryptedCredentials(s){return s.includes(ff)},injectProxyCredentialsStoreToGlobal(){Object.assign(globalThis,{[ff]:this.proxyPlaceholder})}}});function Ko(s){let{platform:e}=process;e==="win32"?(0,zo.exec)(`start chrome ${s}`):e==="darwin"?(0,zo.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,zo.exec)(`google-chrome ${s}`)}var zo,jl=w(()=>{"use strict";zo=require("child_process")});var Hl={};G(Hl,{doLogin:()=>Gl,getProjectId:()=>gv,getToken:()=>hv});async function gv(){return bf("projectId")}async function hv(){return bf("token")}function yf(s,e){return Promise.race([s,oe(e).then(()=>{throw new ne("timeout")})])}async function yv(){let s=(await import("express")).default(),e=async function(){return yf(new Promise(n=>{s.get("/loginInfo",(o,i)=>{n(JSON.parse(Buffer.from(o.query.info,"base64").toString())),i.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let o=s.listen(42543,i=>{i&&n(i),r(o.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(he(),xe)),{editorUrl:n}=await r();Ko(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function Gl({overwriteExisting:s=!0,projects:e=null}={}){let t=$l.homedir(),r=Wl.join(t,".testim");if(await ge(r)&&!s)return;let o={},[{default:i},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await yf(yv(),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,l.succeed(),await hf(r,o);return}if(e!=null&&e.length){l.succeed();let c=e.length===1?{project:e[0]}:await i({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});o.token=c.project.ci.token,o.projectId=c.project.id,await hf(r,o);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function hf(s,e){await Vl.promises.writeFile(s,Jo.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function bf(s){let e=$l.homedir(),t=Wl.join(e,".testim"),r=await ge(t),n={};if(r)try{n=Jo.parse((await Vl.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var $l,Wl,Jo,Vl,Yo=w(()=>{"use strict";$l=E(require("os")),Wl=E(require("path")),Jo=E(require("yaml"));B();Vl=require("fs");K();jl()});var Rf={};G(Rf,{process:()=>Rv});var zl,vf,Xo,Ef,Vt,Me,Sf,bv,Ne,Yl,Tv,wv,Tf,If,vv,Kl,Jl,Xl,ql,Pt,Ev,p,Sv,Iv,wf,Rv,Af=w(()=>{"use strict";zl=E(require("ms")),vf=E(require("chalk")),Xo=E(require("fs")),Ef=E(require("url")),Vt=E(require("lodash")),Me=E(require("path"));B();qo();mf();Bt();Sf=require("commander");ae();K();Nr();B();pe();gf();bv=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Ne=(s,e)=>(e.push(s),e),Yl=new Sf.Command,Tv=s=>s.split(","),wv=(s,e)=>!s||s.length===0?e:s,Tf=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],If=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function o(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function i(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function l(g){return g.includes("--save-rca-locally")}function c(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}Yl.help(g=>g.split(`
|
|
16
|
+
4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),i}}async function jw(){let s=`${Mr}/extension/sessionPlayer_LATEST_RELEASE`;return(await Mt(s)).body.toString("utf8")}async function $w(s,e){if(!_e(s)||_e(s)&&e||Oe)return s;let t=await jw();return`${s}-${t}`}function Bc(){let s=ht();return Xr.resolve(s,"testim-bin")}function Ww(){let s=Bc();return Xr.resolve(s,"sessionPlayer.zip")}async function Dm(s,e,t=!1){try{return await uo(s,e),await rt(e,Bc())}catch(r){if(t)throw r;return await Dm(s,e,!0)}}async function Tr(s,e){ko.info("prepare player",{location:s,canary:e});let t=Ww();return bt(async()=>{let r=await $w(s,e);return await Dm(r,t),{}},"preparePlayer",Lm,[s,e,t])()}var km,_m,Xr,Om,ko,Lm,Mc,Pm,Xs=w(()=>{"use strict";km=E(require("ms")),_m=E(require("fs")),Xr=E(require("path"));ue();Bt();Om=require("serialize-error");j();kc();K();B();ko=x("prepare runner and testim start"),Lm=(0,km.default)("0.5 day"),Mc=16,Pm=`The size of the custom extension is more than ${Mc}MB`});function Vw(){let s=Qs.type().toLowerCase();return s==="darwin"?Qs.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?Qs.arch()==="x64"?"win64":"win32":"linux"}async function Oo(){let s=Vw(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(s in t))throw new P(`Unsupported platform: ${s}`);let r=parseInt(Zs,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},o={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},i=`${e}/${t[s]}/${Zs}/${n[s]}.zip`,a=_o.join(jc,n[s]),l=`${a}.zip`,c=_o.join(a,o[s]);if(await ge(c))return c;if(!await ge(l)){let m=(0,$c.default)("Downloading Chromium").start();try{await Nm.promises.mkdir(jc),await Je(i,l)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,$c.default)("Extracting Chromium").start();try{await rt(l,jc)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),c}var Nm,Qs,_o,$c,Zs,jc,Wc=w(()=>{"use strict";Nm=E(require("fs")),Qs=E(require("os")),_o=E(require("path")),$c=E(require("ora"));K();B();Zs="1000968",jc=_o.join(Ft,`chrome-${Zs}`)});async function Bm(s,e){return wr=s,qc=e,await Vc()}function jm(s,e){wr=e.projectId,qc=e.token,en=e.userAccessKey,st=s.token,rn=zc(st),sn=s.refreshToken,Gc=s.ngrokToken,Hc=s.isNgrokWhitelisted,Mm=e.publicIp,Um=e.initializedFromCache}function Gw(s=wr,e=qc){return bt(()=>(tn.info("request to get cli token from server"),Ve({url:`${fe}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",Fm*10,{projectId:s,token:e})()}async function Hw(){tn.info("request to refresh JWT cli token from server");let s=await Ve({url:`${fe}/auth/refreshToken`,body:{token:st,refreshToken:sn}});return st=s.token,rn=zc(st),s.refreshToken&&(sn=s.refreshToken),st}async function Vc(){try{let s=await Gw();return tn.info("successfully get cli token from server"),st=s.token,rn=zc(st),sn=s.refreshToken,Gc=s.ngrokToken,Hc=s.isNgrokWhitelisted,st}catch(s){throw s.message.includes("Unauthorized")?new P("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(tn.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:wr}),new P(`While trying to retrieve CLI token, caught error: ${s}`))}}function zc(s){return require("jsonwebtoken").decode(s).exp*1e3}async function Zt(){if(!rn)return Vc();if(rn<Date.now()+4*Fm)try{return await Hw()}catch(s){return tn.error("failed to refresh token, executing fallback",s),Vc()}return st}function Lo(){return sn}function jt(){return st?{uid:require("jsonwebtoken").decode(st).id,ngrokToken:Gc,isNgrokWhitelisted:Hc}:{}}async function Do(){if(!en||!wr)return;if(await Kc({userAccessKey:en,projectId:wr}))return en;let e=`user access key "${en}" is invalid for project "${wr}"`;throw new P(e)}function No(){return Mm}function Mo(){return Um}var tn,st,rn,sn,Gc,Hc,wr,qc,en,Mm,Um,Fm,nt=w(()=>{"use strict";ue();Ge();Bt();K();j();he();tn=x("testim-custom-token"),wr=null,qc=null,Fm=5*60*1e3});var $m={};G($m,{isCi:()=>Qr});var Qr,Uo=w(()=>{"use strict";Qr=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var xe={};G(xe,{addTestRetry:()=>bl,clearTestResult:()=>gl,deleteCloudflareTunnel:()=>El,fetchLambdatestConfig:()=>dl,fixGridAppIDStructure:()=>Al,forceUpdateCloudflareTunnelRoutes:()=>vl,getAllGrids:()=>pl,getAppDetails:()=>an,getApplitoolsIntegrationData:()=>Tl,getBrowserStackSessionMetaData:()=>tv,getCloudflareTunnel:()=>wl,getEditorUrl:()=>Qw,getGridById:()=>Bo,getGridByName:()=>ll,getHybridGridProvider:()=>cl,getLabFeaturesByProjectId:()=>ml,getMobileDevicesFromGrid:()=>Il,getRealData:()=>fl,getS3Artifact:()=>on,getS3ArtifactText:()=>Yc,getSuiteTestList:()=>sl,getTestPlan:()=>Xw,getTestPlanTestList:()=>rl,getTestResults:()=>Er,getUsageForCurrentBillingPeriod:()=>nl,initializeUserWithAuth:()=>ul,isTestResultCompleted:()=>ol,keepAliveCompanySlots:()=>kl,keepAliveGrid:()=>il,loadSfdcCredential:()=>Xc,loadTest:()=>Qc,releaseCompanySlot:()=>Cl,releaseGridSlot:()=>al,reportExecutionFinished:()=>Fo,reportExecutionStarted:()=>tl,requestCompanySlot:()=>xl,saveRemoteStep:()=>hl,saveTestPlanResult:()=>Zc,updateCompanySlot:()=>Pl,updateExecutionTests:()=>el,updateRemoteRunFailure:()=>Sl,updateTestDataArtifact:()=>$o,updateTestResult:()=>jo,updateTestStatus:()=>vr,uploadAppToGrid:()=>Rl,uploadRunDataArtifact:()=>yl,validateUserAccessKey:()=>Kc});async function Zr(){let s=await Zt();if(!s)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${s}`}}async function Ae({url:s,body:e,headers:t={},timeout:r,retry:n}){let o=await Zr(),i={...t,...o};return Ve({url:`${fe}${s||""}`,body:e,headers:i,timeout:r,retry:n})}async function Kw(s,e,t,r={},n=void 0){let o=await Zr(),i={...r,...o};return await Fs(`${fe}${s||""}`,e,t,i,n)}async function nn(s,e){let t=await Zr();return await pc(`${fe}${s||""}`,e,t)}async function Jw(s,e){let t=await Zr();return await Us(`${fe}${s||""}`,e,t)}async function Yw(s,e){let t=await Zr();return await Bs(`${fe}${s||""}`,e||void 0,t)}async function Se(s,e,t,r){let n=await Zr();return await be(`${fe}${s||""}`,e||void 0,n,r,t)}function on(s,e){return(0,X.default)(()=>Se(`/storage${s}`,null,{isBinary:!0},e),{retries:ee,factor:1})}function Yc(s){return(0,X.default)(()=>Yw(`/storage${s}`))}async function Xw(s,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,X.default)(()=>Se("/testPlan",{projectId:s,name:e.join(",")}),{retries:ee,factor:1})).map(({testConfigIds:n,beforeAllLabels:o,testLabels:i,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(o),testLabels:t(i),afterAllLabels:t(a)}))}async function Xc({branch:s,projectId:e}){let t=await(0,X.default)(()=>Se(`/branch/branchData/${s}`,{projectId:e}),{retries:ee,factor:1});return t==null?void 0:t.sfdcCredential}function Qc({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,X.default)(()=>Se(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:ee,factor:1})}function Zc(s,e,t){return(0,X.default)(()=>Ae({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:ee,factor:1})}function vr(s,e,t,r,n,o,i=ee){return(0,X.default)(()=>nn("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:qw,...o}),{retries:i,factor:1})}function el(s,e,t,r,n,o,i,a){return(0,X.default)(()=>nn("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:o,endTime:i,projectId:a}),{retries:ee,factor:1})}async function tl({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:o,resultLabels:i,remoteRunId:a,localRunUserId:l,isLocalRun:c,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(Uo(),$m));return Ae({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:o,resultLabels:i,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function Fo(s,e,t,r,n={},o=void 0,i=void 0){let a=Date.now();return(0,X.default)(()=>nn("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:ee,factor:1})}async function rl(s,e,t,r,n){return(0,X.default)(()=>Ae({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:ee,factor:1})}function sl({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,X.default)(()=>Ae({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:ee,factor:1})}async function an({appId:s,projectId:e}){try{return await(0,X.default)(()=>Se(`/mobile-app/app/${s}?projectId=${e}`),{retries:ee,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function nl(s){try{return await(0,X.default)(()=>Se(`/plan/project/${s}/usage-current-billing-period`),{retries:ee,factor:1})}catch(e){Wt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function ol(s,e,t){return(0,X.default)(()=>Se(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:ee,factor:1})}function Er(s,e,t,r){return(0,X.default)(()=>Se(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:ee,factor:1})}function il(s,e){return Ae({url:`/grid/keep-alive?reqId=${se()}`,body:{projectId:s,slots:e},timeout:1e4})}function al(s,e,t,r,n){return Ae({url:`/grid/release?reqId=${se()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function cl(s){return Ae({url:"/grid/hybrid/provider",body:s})}function ll(s,e,t,r,n){return(0,X.default)(()=>Se("/grid/name",{companyId:s,projectId:e,name:t,browser:r,executionId:n,reqId:se()}),{retries:ee,factor:1})}function Bo(s,e,t,r,n){return(0,X.default)(()=>Se(`/grid/${t}`,{companyId:s,projectId:e,browser:r,executionId:n,reqId:se()}),{retries:ee,factor:1})}async function ul({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:o,gridId:i,grid:a}){var l,c;try{return await(0,X.default)(()=>Ve({url:`${fe}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:o,gridId:i,gridName:a}}),{retries:ee,factor:1})}catch(d){throw Wt.error("error initializing info from server",d),(l=d==null?void 0:d.message)!=null&&l.includes("Bad Request")?new P("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(c=d==null?void 0:d.code)!=null&&c.includes("ENOTFOUND")?new P("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):d}}async function Qw(){if(_s)return{editorUrl:_s};try{return await(0,X.default)(()=>Se("/system-info/editor-url"),{retries:ee,onFailedAttempt:s=>{if(s.attemptNumber>=ee)throw s},factor:1})}catch{return Wt.error("cannot retrieve editor-url from server"),{editorUrl:"https://app.testim.io"}}}function pl(s){return(0,X.default)(()=>Se("/grid",{companyId:s}),{retries:ee,factor:1})}function fl(s,e,t){return(0,X.default)(()=>Se(`/real-data/${e}?${t}&projectId=${s}`),{retries:ee,factor:1})}function jo(s,e,t,r,n){return(0,X.default)(()=>Ae({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:ee,factor:1})}function gl(s,e,t,r){return(0,X.default)(()=>Ae({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:ee,factor:1})}function hl(s,e,t,r){return(0,X.default)(()=>Ae({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:ee,factor:1})}function Zw(s){return s.startsWith("/")?s:`/${s}`}function ev(s,e,t){let r=Zw(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Vm(s,e,t,r,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${se()}${i||""}`,l=`${e}/${t}/${a}`,c=ev(l,"test-result-artifacts",s),d=Buffer.from(Wm.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,X.default)(()=>Kw(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:ee,factor:1}),c}function bl({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:o,testResult:i}){return(0,X.default)(()=>Ae({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:ee,factor:1})}async function Tl(s){try{return await Se(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Wt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function wl(s,e){try{return await nn("/tunnel",{companyId:s,routes:e})}catch(t){return Wt.warn("could'nt get tunnel.",{err:t}),{}}}async function vl(s,e){try{return await Ae({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}async function El(s,e){try{return await Jw(`/tunnel/${e}`,{companyId:s})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}function Sl(s){return Ve({url:`${fe}/result/remoteRunFailure`,body:s})}async function Il({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let o=`${zw}/mobileDevices/${t}/${r}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await(0,X.default)(()=>Se(o,{projectId:s}),{retries:ee,factor:1})}catch(i){return Wt.warn("could'nt get devices from headspin grid.",{err:i}),null}}async function Rl({projectId:s,gridId:e,app:t,timeout:r}){return(0,X.default)(()=>Ae({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:ee,factor:1})}async function Al(s){return(0,X.default)(()=>Ae({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:ee,factor:1})}async function xl(s,e){return(0,X.default)(()=>Ae({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:ee,factor:1})}async function Cl(s,e,t){return(0,X.default)(()=>Ae({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:ee,factor:1})}async function Pl(s,e,t){return(0,X.default)(()=>nn("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:ee,factor:1})}function kl(s,e,t){return Ae({url:`/slot-management/keep-alive?reqId=${se()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function tv(s,e){return await be(`${Os}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function Kc(s){try{return await Se("/v2/project/validateUserAccessKey",s),!0}catch(e){return Wt.error("error validating user access key",{error:e}),!1}}var er,Wm,X,Jc,qw,Wt,ee,zw,dl,ml,yl,$o,he=w(()=>{"use strict";er=E(require("lodash")),Wm=E(require("pako"));B();ue();ae();Ge();nt();X=E(require("p-retry")),Jc=E(require("object-hash"));K();j();qw=gt(),Wt=x("testim service api"),ee=3,zw="/grid";dl=async()=>(0,X.default)(()=>Se("/grid/lt/config"),{retries:ee,factor:1}),ml=async s=>(0,X.default)(()=>Se(`/labFeature/v2/project/${s}`),{retries:ee,factor:1});yl=er.memoize(async(s,e,t,r)=>{if(!er.isEmpty(r))return await Vm(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,Jc.default)(r)}:${e}:${t}`),$o=er.memoize(async(s,e,t,r,n)=>!r||er.isEmpty(r)?void 0:await Vm(s,e,t,JSON.stringify((()=>{let i=er.clone(r);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(l=>{i[l]&&Object.assign(i,{[l]:Tc.HIDDEN_PARAM})})}return i})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,Jc.default)(r)}:${e}:${t}`)});async function Gm(){let s=await Promise.any(rv.map(async e=>{try{return await be(e)}catch{return null}}));return s==null?void 0:s.ip}var rv,Hm=w(()=>{"use strict";Ge();rv=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"]});var tr={};G(tr,{getSessionPlayer:()=>te,options:()=>Ol});var Wo,Ol,_l,te,Te=w(()=>{"use strict";Wo=require("path");j();Ol={playerPath:void 0},te=()=>{if(_l)return _l;let s=($e(),ye(je));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(Xs(),ye(Ys)),t=e(),r=Ol.playerPath?(0,Wo.resolve)(Ol.playerPath,"src/background/sessionPlayerInit.ts"):(0,Wo.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),_l=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(Za),n}});function ov(s){process.nextTick(()=>{if([Z.SELENIUM,Z.APPIUM].includes(s))try{(Te(),ye(tr)).getSessionPlayer()}catch{}})}async function cn(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:o,useChromeLauncher:i,mode:a,gridId:l,grid:c}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(o||i),u=d?nv:sv,f=null;if(D.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{f=await Gm()}catch(y){qm.error("failed to get public ip",y)}let h=!0;M("before initializeUserWithAuth");let g=await bt(async()=>(ov(a),h=!1,await ul({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,publicIp:f,gridId:l,grid:c})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:l,grid:c,publicIp:f})();return s.publicIps=[g.clientPublicIp],M("after initializeUserWithAuth"),f&&g.clientPublicIp&&g.clientPublicIp!==f&&(qm.error("public ip mismatch",{publicIpFromExternalService:f,publicIpFromServices:g.clientPublicIp}),s.publicIps.push(f)),jm(g.authData,{projectId:e,token:t,userAccessKey:r,publicIp:g.clientPublicIp,initializedFromCache:h}),g}var qm,sv,nv,zm=w(()=>{"use strict";$e();he();Bt();nt();Hm();ae();j();pe();qm=x("initializeUserWithAuth"),sv=1e3*60*5,nv=1e3*60*60*10});async function Ym(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Oo():s.chromeBinaryLocation,e=Js({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==Z.EXTENSION&&await Tr(s.playerLocation,s.canary),s.mode===Z.EXTENSION&&!s.ext&&await Fc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await Uc(s.installCustomExtension,n)}return await e,t}async function Xm(s){var i;iv.info("prepare MockNetwork",{location:s});let e=await gc(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>Km*1e6)throw new Error(`${Ll} exceeded ${Km}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${Ll} cannot be parsed.${Vo.EOL}${a}`)}let n=new Jm.default;if(!n.validate(Cc,r)){let a=(i=n.errors)==null?void 0:i.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(Vo.EOL);throw new Error(`${Ll} is malformed.${Vo.EOL}${a}`)}return r.entries}var Vo,Jm,Km,Ll,iv,Dl=w(()=>{"use strict";Vo=E(require("os"));B();Qd();Xs();Jm=E(require("ajv"));ae();Wc();zm();Km=1,Ll="JSON file supplied to --mock-network-pattern",iv=(j(),ye(sc)).getLogger("prepare runner")});function Zm(s,e=process){async function t(r){await ce(ie(Qm,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{ln.error("Caught exception",{err:r}),console.log("Uncaught exception"),r.message&&console.log("Message =",r.message),r.reason&&console.log("Reason =",r.reason),await t(r)}),e.on("unhandledRejection",r=>{var n;if(ln.fatal("Caught unhandled promise rejection",r),!((n=r==null?void 0:r.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{ln.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw ln.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw ln.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function es(s){Qm.push(s)}var ln,Qm,un=w(()=>{"use strict";j();B();ln=x("process-handler"),Qm=[]});function Fl(s,e){let t=s.canary?"-master.zip":".zip",r=`${e?pd:Mr}/extension/testim-firefox-profile${t}`,n=`${e?dd:Mr}/extension/testim-headless${t}`;return{firefox:r,chrome:n,"edge-chromium":n}}function nf(s){let{chrome:e,firefox:t}=Fl(s,!1);return s.browser==="firefox"?t:s.browser==="chrome"?e:[e,t]}function Ho(s){let e=`${Mr}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var qo=w(()=>{"use strict";ue()});function uf(s){Oe||(s!=null&&s.userId||(s={anonymousId:lf}),cf.identify(s))}function Tt(s,e){return pn("ci",s,e)}function pn(s,e,t){if(Oe)return;let r=s?{userId:s}:{anonymousId:lf};cf.track(Object.assign(r,{event:e,properties:t}))}var af,cf,lf,ts=w(()=>{"use strict";ue();af=require("@segment/analytics-node"),cf=new af.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1}),lf=require("crypto").randomBytes(20).toString("hex")});function pf(s){return s.start&&pn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function df(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new P("Agent port is not number");let t=Ho(s);return console.log("Start Testim CLI on Agent mode"),{project:s.project,token:s.token,agentMode:!0,agentPort:s.agentPort,agentBind:s.agentBind,openEditor:s.openEditor,startTestimBrowser:e,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||t,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:Boolean(s.downloadBrowser)}}var mf=w(()=>{"use strict";qo();ts();K()});var ff,mv,fv,Bl,gf=w(()=>{"use strict";ff="TST_CREDS",mv=["username","password"],fv="$encrypted",Bl={get proxyPlaceholder(){return new Proxy({},{get(s,e){let t={};for(let r of mv)t[r]={[fv]:`${e}.${r}`};return t}})},containsEncryptedCredentials(s){return s.includes(ff)},injectProxyCredentialsStoreToGlobal(){Object.assign(globalThis,{[ff]:this.proxyPlaceholder})}}});function Ko(s){let{platform:e}=process;e==="win32"?(0,zo.exec)(`start chrome ${s}`):e==="darwin"?(0,zo.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,zo.exec)(`google-chrome ${s}`)}var zo,jl=w(()=>{"use strict";zo=require("child_process")});var Hl={};G(Hl,{doLogin:()=>Gl,getProjectId:()=>gv,getToken:()=>hv});async function gv(){return bf("projectId")}async function hv(){return bf("token")}function yf(s,e){return Promise.race([s,oe(e).then(()=>{throw new ne("timeout")})])}async function yv(){let s=(await import("express")).default(),e=async function(){return yf(new Promise(n=>{s.get("/loginInfo",(o,i)=>{n(JSON.parse(Buffer.from(o.query.info,"base64").toString())),i.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let o=s.listen(42543,i=>{i&&n(i),r(o.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(he(),xe)),{editorUrl:n}=await r();Ko(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function Gl({overwriteExisting:s=!0,projects:e=null}={}){let t=$l.homedir(),r=Wl.join(t,".testim");if(await ge(r)&&!s)return;let o={},[{default:i},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await yf(yv(),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,l.succeed(),await hf(r,o);return}if(e!=null&&e.length){l.succeed();let c=e.length===1?{project:e[0]}:await i({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});o.token=c.project.ci.token,o.projectId=c.project.id,await hf(r,o);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function hf(s,e){await Vl.promises.writeFile(s,Jo.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function bf(s){let e=$l.homedir(),t=Wl.join(e,".testim"),r=await ge(t),n={};if(r)try{n=Jo.parse((await Vl.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var $l,Wl,Jo,Vl,Yo=w(()=>{"use strict";$l=E(require("os")),Wl=E(require("path")),Jo=E(require("yaml"));B();Vl=require("fs");K();jl()});var Rf={};G(Rf,{process:()=>Rv});var zl,vf,Xo,Ef,Vt,Me,Sf,bv,Ne,Yl,Tv,wv,Tf,If,vv,Kl,Jl,Xl,ql,Pt,Ev,p,Sv,Iv,wf,Rv,Af=w(()=>{"use strict";zl=E(require("ms")),vf=E(require("chalk")),Xo=E(require("fs")),Ef=E(require("url")),Vt=E(require("lodash")),Me=E(require("path"));B();qo();mf();Bt();Sf=require("commander");ae();K();Nr();B();pe();gf();bv=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Ne=(s,e)=>(e.push(s),e),Yl=new Sf.Command,Tv=s=>s.split(","),wv=(s,e)=>!s||s.length===0?e:s,Tf=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],If=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function o(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function i(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function l(g){return g.includes("--save-rca-locally")}function c(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}Yl.help(g=>g.split(`
|
|
17
17
|
`).filter(T=>!t(T)&&!e(T)&&!s(T)&&!r(T)&&!n(T)&&!a(T)&&!i(T)&&!o(T)&&!l(T)&&!c(T)&&!d(T)&&!m(T)&&!u(T)&&!f(T)&&!h(T)).join(`
|
|
18
18
|
`))},vv=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(vf.default.yellow(`
|
|
19
19
|
WARNING: ${s} is deprecated. ${t}
|
|
20
20
|
`))},Kl=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:Jl,argv:Xl,exit:ql,cwd:Pt}=global.process,Ev=["trace","debug","info","warn","error","silent"];Ec(Xl,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));Yl.description("Testim.io CLI").option("-h --help","output usage information",If).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",Ne,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Ne,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Ne,[]).option("--test-id [test-id]","test ID to run",Ne,[]).option("-l, --label [label]","labels to search test by",Ne,[]).option("-n, --name [test-name]","test name to run",Ne,[]).option("--project [project-id]","project ID").option("-r, --report-file [report junit xml path]","where to save junit xml results file").option("--urls","add step urls to the junit report").option("--override-report-file-classname [override-report-file-classname]","custom junit class name for the junit reporter").option("--reporters [names]","report types",Tv).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",Ne,[]).option("--test-plan-id [test-plan-id]","test plan to run",Ne,[]).option("--suite [suite-name]","suite to run",Ne,[]).option("--suite-id [suite-id]","suite ID to run",Ne,[]).option("--rerun-failed-by-run-id [run-id]","allows re-running failed tests from a specific run ID").option("--disable-grid-check [boolean]","disable checking if selenium grid is available",!1).option("--disable-native-events [boolean]","pass nativeEvents=false capability to the selenium browser (in selenium mode)",!1).option("--disable-timeout-retry [boolean]","disable retry after test pass test timeout",!1).option("--ca-file [ca-file-location]","ca certificate file location").option("--proxy [proxy-url]","proxy url to all requests").option("--proxy-for-grid [proxy-for-grid]","used together with --proxy to also router grid traffic through a proxy").option("--result-label [result-label]","result label",Ne,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--user-access-key [user-access-key]","EXPERIMENTAL").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("--duration [duration]","The duration of the test run in minutes",Number).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--clear-file-cache","clear internal CLI file cache").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(Jl.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,zl.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,zl.default)("90s")).option("--driver-request-retries [driver-request-retries]","Retries for any WebDriver request to the grid server",Number,3).option("--local-tma-url [local-tma-url]","use a local TMA instance for appium session").option("--use-local-chrome-driver [use-local-chrome-driver]","use a local ChromeDriver instance instead of a selenium grid").option("--chrome-binary-location [chrome-binary-location]","Chrome binary location").option("--use-chrome-launcher","use a local Chrome installation without selenium").option("-mnh --mock-network-har","use the HAR file configured in the Testim editor to mock network traffic").option("-mnp --mock-network-pattern [local file location path]","use a JSON rule file to mock network traffic (Rule file schema: https://help.testim.io/page/mocking-network-traffic)").option("-omf --override-mapping-file [local file location path]","pass map file location to override mock network (see schema: https://help.testim.io/page/mocking-network-traffic)").option("-dmn --disable-mock-network","Disable mock mode for the entire CLI run").option("--run-quarantined-tests","Run quarantine tests").option("--collect-code-coverage","collect code coverage for all js files under base url").option("--code-coverage-url-filter [url pattern]","collect code coverage for all js files matching url filter (url including asterisk)").option("--code-coverage-report-path [path]","where to save coverage report (default ./coverage)").option("--code-coverage-source-map-path [path]","path of source code").option("--code-coverage-reporter [reporter]",`set code coverage reporter (default html and text), options: ${Kl.join("/")}`,Ne,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Ne,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",Ne,[]).option("--intersect-with-suite [suiteName]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite name)",Ne,[]).option("--intersect-with-suite-id [suiteId]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite ID)",Ne,[]).option("--apply-intersections-to-before-and-after-sections [boolean]","For a test plan's before/after tests, run tests that intersect with specified intersection flags",void 0).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).option("--print-grids","Print available grids and exit",!1).option("--print-final-caps","Print the final calculated capabilities",!1).parse(Xl);p=Yl.opts(),Sv=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},Iv=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},wf=s=>{var r;if(!D.flags.encryptedCredentials.isEnabled({projectId:p.project}))return;let t=Xo.readFileSync(s);(r=Bl)!=null&&r.containsEncryptedCredentials(t.toString())&&Bl.injectProxyCredentialsStoreToGlobal()},Rv=async()=>{var T,R,b,v,I,C,_,$;p.inspect&&require("inspector").open(p.inspect);let s={},e={},t=[],r={};if(!Xl.slice(2).length)throw If(),new Fr;if(p.version){let A="Testim CLI Version: ";Jl.npm_package_version&&(console.log(A,Jl.npm_package_version),ql(0));let S=gt();S&&(console.log(A,S),ql(0)),console.log("Could not find version, please check the package.json manually"),ql(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&um(),p.clearFileCache&&Kr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let A=Me.resolve(n);cm(A)}if(p.usePrefechedData&&pm(),p.playerRequirePath){let A=Me.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",A);let S=Me.join(A,"tsconfig.node.json"),U=require("ts-node").register({project:S,ignore:[/node_modules/,new RegExp(`^${Vt.escapeRegExp(Me.relative(Pt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:U.config.options.paths,baseUrl:U.config.options.baseUrl}),(Te(),ye(tr)).options.playerPath=A;let H=require("module"),Y=H.prototype.require;H.prototype.require=function(pt){return pt==="rox-alias"?Y.call(this,"rox-node"):pt==="canvas"?{}:Y.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=Xo.readFileSync(p.caFile)),p.proxy&&(global.proxyUri=p.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent").ProxyAgent,global.HttpsProxyAgent=require("https-proxy-agent").HttpsProxyAgent),p.proxyForGrid&&!p.proxy)throw new P("missing --proxy option");if(pf(p))return df(p);try{let A={};p.configFile?(wf(p.configFile),A=require(Me.join(Pt(),p.configFile)).config):p.optionsFile&&(A=require(Me.join(Pt(),p.optionsFile))),A&&typeof A.then=="function"&&(A=await A),Object.keys(A).forEach(S=>{let L=bv(S);p[L]=wv(p[L],A[S])})}catch(A){throw A.message=`Unable to read options file: ${A.message}`,A}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let o=((T=p.testConfig)==null?void 0:T.length)||((R=p.testConfigId)==null?void 0:R.length),i=((b=p.testPlan)==null?void 0:b.length)||((v=p.testPlanId)==null?void 0:v.length),a=((I=p.suite)==null?void 0:I.length)||((C=p.suiteId)==null?void 0:C.length);if(p.seleniumCapsFile)try{r=require(Me.join(Pt(),p.seleniumCapsFile))}catch(A){throw new P(`Failed to parse selenium caps file file error: ${A.message}`)}if((_=p.reporters)!=null&&_.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new P("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new P("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new P("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Me.join(Pt(),p.chromeExtraPrefs))}catch(A){throw new P(`Failed to read/open chrome extra prefs file error: ${A.message}`)}if(p.chromeExtraArgs){let A=p.chromeExtraArgs.split(",");for(let S of A){let[L]=S.split("=");Tf.includes(L)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(S),L==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${L}), allowed values: ${JSON.stringify(Tf)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&wf(p.paramsFile),s={...s,...require(Me.join(Pt(),p.paramsFile))}}catch(A){throw new P(`Failed to read/open params file error: ${A.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(A){throw new P(`Failed to parse params string error: ${A.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new P("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(Sv(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let A=require(Me.join(Pt(),p.sauceOptions)),S=A.platformName&&["ios","android"].includes(A.platformName.toLowerCase());if(A.browserName){let U=A.browserName.toLowerCase();switch(U){case"microsoftedge":p.browser="edge";break;default:p.browser=U}}p.browser==="edge"&&parseFloat(A.version)>=Wa&&(p.browser="edge-chromium");let L=parseFloat(A.version)<50&&!["dev","beta"].includes(A.version);if(!S&&p.browser==="chrome"&&L)throw new P("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...A}}catch(A){throw new P(`Failed to parse saucelabs options file error: ${A.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new P("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(Iv(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let A=require(Me.join(Pt(),p.browserstackOptions)),S=A.platform&&["mac","android"].includes(A.platform.toLowerCase());if(A.browserName&&(p.browser=A.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(A.browser_version)>=Wa&&(p.browser="edge-chromium"),!S&&parseFloat(A.browser_version)<50&&p.browser==="chrome")throw new P("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...A}}catch(A){throw new P(`Failed to parse browserstack options file error: ${A.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let A=require(Me.join(Pt(),p.perfectoOptions)),S={location:"US East",securityToken:p.perfectoToken};p.perfecto={...S,...A}}catch(A){throw new P(`Failed to parse perfecto options file error: ${A.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let A=require(Me.join(Pt(),p.testobjectOptions)),S={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...S,...A}}catch(A){throw new P(`Failed to parse test object options file error: ${A.message}`)}if(!p.project){let S=await(await Promise.resolve().then(()=>(Yo(),Hl))).getProjectId();if(S)p.project=S;else throw new P("missing project-id info, either --login to provide new credentials or use --project <project-id>")}D.flags.forceTurboModeIfNeeded.isEnabled({projectId:p.project})&&(p.turboMode=!0),p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),p.mode??="extension",p.retries=!p.retries||typeof p.retries=="boolean"?1:Number(p.retries)+1,p.browserTimeout=!p.browserTimeout||typeof p.browserTimeout=="boolean"?60*1e3:p.browserTimeout,p.newBrowserWaitTimeout=!p.newBrowserWaitTimeout||typeof p.newBrowserWaitTimeout=="boolean"?10*60*1e3:p.newBrowserWaitTimeout*60*1e3,p.getBrowserTimeout||(p.getBrowserTimeout=p.browserTimeout),p.getBrowserRetries||(p.getBrowserRetries=p.mode===Z.APPIUM?1:Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=p.browserTimeout<p.getSessionTimeout?p.getSessionTimeout:p.browserTimeout,p.driverRequestTimeout=p.browserTimeout<p.driverRequestTimeout?p.driverRequestTimeout:p.browserTimeout;let c=Boolean(p.timeout);if(p.timeout=!p.timeout||typeof p.timeout=="boolean"?10*60*1e3:p.timeout,p.beforeParallel=!p.beforeParallel||typeof p.beforeParallel=="boolean"?1:Number(p.beforeParallel),p.parallel=!p.parallel||typeof p.parallel=="boolean"?1:Number(p.parallel),p.afterParallel=!p.afterParallel||typeof p.afterParallel=="boolean"?1:Number(p.afterParallel),p.tunnelPort=!p.tunnelPort||typeof p.tunnelPort=="boolean"?"80":p.tunnelPort,p.port&&=Number(p.port),!p.token){let S=await(await Promise.resolve().then(()=>(Yo(),Hl))).getToken();if(S)p.token=S;else throw new P("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let d=A=>A<=0||!Number.isInteger(A);if(d(p.retries))throw new P("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new P("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(d(p.browserTimeout))throw new P("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d(p.newBrowserWaitTimeout))throw new P("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(d(p.timeout))throw new P("test run timeout could not be a negative number, --timeout <run-timeout>");if(d(p.beforeParallel))throw new P("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d(p.parallel))throw new P("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d(p.afterParallel))throw new P("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![Z.EXTENSION,Z.SELENIUM,Z.APPIUM].includes(p.mode))throw new P(`runner mode <${p.mode}> is not supported`);if(p.mode!==Z.SELENIUM&&p.disableNativeEvents)throw new P("disable-native-events is only applicable in selenium mode");if(!p.browser&&!o&&!i&&(p.browser="chrome"),p.appiumLogLevel||(p.appiumLogLevel="silent"),!Ev.includes(p.appiumLogLevel))throw new P(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData&&!p.printGrids)throw new P("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(p.testId.length||p.label.length||p.name.length||o||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new P("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --local-tma-url, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!i&&(p.beforeParallel!==1||p.afterParallel!==1))throw new P("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new P("please define exactly one of --grid or --grid-id or --host");if(($=p.host)!=null&&$.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=Ef.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(S=>S.trim()).filter(Boolean);let A=p.resultLabel.filter(S=>S.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&hr()&&p.resultLabel.unshift(hr()),A.length)throw new P("A result label cannot exceed 250 characters")}let u=nf(p),f=Ho(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new P("cannot set --w3c-capabilities and --old-capabilities options as false");if(p.protocol||=p.port===443?"https":"http",!["http","https"].includes(p.protocol))throw new P("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new P("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(p.rerunFailedByRunId&&(a||p.name.length||p.testId.length||p.label.length||i))throw new P("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(p.setRetention&&!Vt.inRange(Vt.parseInt(p.setRetention),1,11))throw new P("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");p.setRetention&&=Number(p.setRetention);let h="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new P(`--mock-network-har ${h}`);if(p.mockNetworkPattern)throw new P(`--mock-network-pattern ${h}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new P("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new P("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new P("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new P("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&Vt.difference(p.codeCoverageReporter,Kl).length){let A=Vt.difference(p.codeCoverageReporter,Kl);throw new P(`invalid --code-coverage-reporter parameters ${A.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let g={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},y=Object.keys(g).filter(A=>Boolean(p[A]));if(p.mode!==Z.EXTENSION&&y.length){let A=y.length>1?"are":"is";throw new P(`${y.map(S=>g[S]).join(" and ")} ${A} only applicable in extension mode`)}if(p.tmsFieldFile)try{let A=Xo.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(A)}catch(A){throw new P(`failed to parse field file error: ${A.message}`)}if(p.applyIntersectionsToBeforeAndAfterSections&&!p.intersectWithLabel&&!p.intersectWithSuite&&!p.intersectWithSuiteId)throw new P("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(p.highSpeed&&(vv("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new P("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new P("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(p.setNoReset&&p.fullReset)throw new P("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.lightweightMode)try{let A={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},S=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...A,...S}}catch(A){throw new P(`failed to parse lightweightMode settings error: ${A.message}`)}else p.turboMode&&p.mode===Z.EXTENSION?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&p.mode===Z.SELENIUM&&console.warn(`
|
|
21
21
|
When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they are not compatible concurrently`);if(typeof p.baseUrl=="boolean")throw new P("base url cannot be used as a flag, and must contain a string value");return{testId:[p.testId].flat(),name:[p.name].flat(),label:[p.label].flat(),suites:[p.suite].flat(),suiteIds:[p.suiteId].flat(),testPlan:[p.testPlan].flat(),testPlanIds:[p.testPlanId].flat(),reportFile:p.reportFile,urls:p.urls,reportFileClassname:p.overrideReportFileClassname,reporters:p.reporters,project:p.project,host:p.host,headless:p.headless,localTmaUrl:p.localTmaUrl,useLocalChromeDriver:p.useLocalChromeDriver,chromeBinaryLocation:p.chromeBinaryLocation,useChromeLauncher:p.useChromeLauncher,port:p.port,grid:p.grid,gridId:p.gridId,disableNativeEvents:p.disableNativeEvents,saucelabs:p.saucelabs,browserstack:p.browserstack,baseUrl:p.baseUrl,branch:(p.branch==="auto-detect"?hr():p.branch)||"master",autoDetect:p.branch==="auto-detect",token:p.token,userAccessKey:p.userAccessKey,userParamsData:s,mode:p.mode,browser:p.browser,beforeParallel:p.beforeParallel,parallel:p.parallel,afterParallel:p.afterParallel,canary:p.canary,rerunFailedByRunId:p.rerunFailedByRunId,disableGridCheck:p.disableGridCheck,disableTimeoutRetry:p.disableTimeoutRetry,resultLabels:p.resultLabel,path:p.path,protocol:p.protocol,perfecto:p.perfecto,experitestToken:p.experitestToken,testobjectSauce:p.testobjectSauce,gridUsername:p.gridUsername,gridPassword:p.gridPassword,overrideExecutionName:p.overrideExecutionName,tmsSuppressReporting:Boolean(p.suppressTmsReporting)||Boolean(p.tmsSuppressReporting),tmsRunId:p.tmsRunId,tmsCustomFields:p.tmsCustomFields,proxyForGrid:p.proxyForGrid,retentionDays:p.setRetention,passZeroTests:Boolean(p.passZeroTests),runQuarantinedTests:Boolean(p.runQuarantinedTests),deviceName:p.deviceName,deviceUdid:p.deviceUdid,customTag:p.customTag,osVersion:p.osVersion,duration:p.duration,skipLoadBalancer:p.skipLoadBalancer,lockDevice:p.lockDevice,appId:p.appId,appiumLogLevel:p.appiumLogLevel,setNoReset:p.setNoReset,fullReset:p.fullReset,ext:p.ext,extensionLocation:[p.extensionPath||u].flat(),extensionPath:p.extensionPath,playerLocation:p.playerPath||f,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:c,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0,applyIntersectionsToBeforeAndAfterSections:p.applyIntersectionsToBeforeAndAfterSections},downloadBrowser:p.downloadBrowser,slotService:"mongo",printGrids:p.printGrids,printFinalCaps:p.printFinalCaps}}});var kf={};G(kf,{installAllLazyDependencies:()=>Cv,lazyRequire:()=>ot});async function ot(s,e={}){let t=Lc(s);if(t)return t;let r;e.silent||(r=(0,xf.default)(`Installing ${s} before first usage...`).start());try{let n=await xv(s);return r&&r.succeed(),n}catch(n){Av.warn("failed to install dependency lazily",{dependency:s,err:n});let o=Pf(s),i=`${s}@${o}`,l=process.argv.includes("npx")?"":"-g ",c=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${l}${i}`;throw r&&r.fail(c),n}}async function xv(s){return rs.has(s)||(rs.set(s,Cf(s)),rs.get(s).catch(()=>{rs.delete(s)})),rs.get(s)}async function Cf(s){let e=Lc(s);if(e)return e;let t=Pf(s),r=`${s}@${t}`;return await xo(ht(),r),Qt(s)}async function Cv(){let s=Object.keys(qa);for(let e of s)await Cf(e)}function Pf(s){let e=Object.entries(qa).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var xf,Av,rs,mn=w(()=>{"use strict";xf=E(require("ora"));Yr();j();B();Zn();Ks();Av=x("lazy-require"),rs=new Map});var Of={};G(Of,{preloadTests:()=>fn});async function fn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await bt(async()=>{let t=await ie(s.testId,r=>Qc({...e,testId:r}),{concurrency:2});return _f.keyBy(t,"testData.id")},"loadTests",Pv,[e,s.testId])()}var _f,Pv,Qo=w(()=>{"use strict";_f=E(require("lodash"));Bt();he();B();Pv=1e3*60*60*10});function Ql(){return gt()}async function Nf(){if(!Oe)try{let s=await ce(_v(),5e3,"The API call to NPM timed out"),e=Ql();e&&Df.lt(e,s)&&console.log(Lf.default.yellow(`Warning: You are using version ${e}, a newer version is available. To update please run npm install (npm install -g @testim/testim-cli)`))}catch(s){kv.warn("Failed to get NPM version",{err:s})}}var Lf,Df,kv,_v,Zl=w(()=>{"use strict";Lf=E(require("chalk")),Df=E(require("semver"));B();ue();Yr();Bt();j();kv=x("npm-driver"),_v=bt(()=>hm("@testim/testim-cli"),"getNpmVersion")});var eu,Lv,ss,Mf,Uf,tu,Ff,Bf=w(()=>{"use strict";B();K();j();mn();eu=x("testimNgrok"),Lv=".whitelisted-ngrok.testim.io",ss="",Uf=async(s,e={})=>{if(!e.ngrokToken)throw new P("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${se()}-${s.projectData.projectId}${Lv}`);let r={proto:"http",addr:s.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};s.tunnelHostHeader&&(r.host_header=s.tunnelHostHeader),s.tunnelRegion&&(r.region=s.tunnelRegion);let o=await(await ot("ngrok")).connect(r);s.tunnelUseHttpAddress&&o.startsWith("https://")?(eu.info("replace https to http"),ss=o.replace("https://","http://")):ss=o,s.tunnelDiagnostics&&tu(),s.baseUrl=ss},tu=async(s=!0)=>{try{let t=(await ot("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(o=>o.public_url===ss);console.log("ngrok stats",n),eu.info("ngrok stats",{tunnel:n})}catch(e){eu.error("error collecting ngrok stats",{err:e})}s&&(Mf=setTimeout(()=>tu(),1e4))},Ff=async s=>{if(!ss)return;clearTimeout(Mf),s.tunnelDiagnostics&&await tu(!1),await(await ot("ngrok")).disconnect(ss)}});var rr,su,jf,Nv,Mv,ru,Zo,ti,ei,Uv,$f,Wf,Vf=w(()=>{"use strict";rr=E(require("os")),su=E(require("fs")),jf=E(require("child_process"));B();he();Nv="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",Mv={win32ia32:{path:"cloudflared-windows-386.exe"},win32x64:{path:"cloudflared-windows-amd64.exe"},darwinx64:{path:"cloudflared-darwin-amd64.tgz",extract:!0},linuxia32:{path:"cloudflared-linux-386"},linuxx64:{path:"cloudflared-linux-amd64"}},ru=rr.tmpdir(),Zo=`${ru}/cloudflared`,ti=null,ei=null,Uv=async()=>{if(await ge(Zo))return;let e=Mv[rr.platform()+rr.arch()];if(!e)throw new Error(`tunnel on ${rr.platform()+rr.arch()} platform is not supported.`);let t=e.extract?ru+e.path:Zo;await Je(`${Nv}/${e.path}`,t),e.extract&&await rt(t,ru),await su.promises.chmod(Zo,"755")},$f=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([wl(s.company.companyId,t),Uv()]);ti=r._id,ei=jf.spawn(Zo,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await vl(s.company.companyId,ti),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await su.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},Wf=async s=>{let e=[];return ti&&e.push(El(s.company.companyId,ti)),ei&&e.push(new Promise((t,r)=>{ei.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ei.kill()})),await Promise.all(e)}});function Gv(s){if(!(s!=null&&s.width)||!(s!=null&&s.height))return re.lambdatestConfig.RESOLUTION;let e=`${s.width}x${s.height}`;return Vv.includes(e)?e:(ri.warn("default resolution is used because the resolution is not supported by LT",{resolutionString:e}),re.lambdatestConfig.RESOLUTION)}var Gf,Hf,Gt,qf,zf,Kf,si,Jf,ri,Bv,jv,gn,$v,Wv,re,Vv,ni=w(()=>{"use strict";Gf=E(require("ms")),Hf=E(require("p-retry")),Gt=E(require("os")),qf=E(require("portfinder")),zf=E(require("child_process"));B();Ge();he();Kf=E(require("fs")),si=E(require("fs/promises")),Jf=require("path");K();j();qo();ae();pe();B();ri=x("lambdatestService"),Bv="https://downloads.lambdatest.com/tunnel/v3",jv={win32ia32:"windows/32bit/LT_Windows.zip",win32x64:"windows/64bit/LT_Windows.zip",darwinia32:"mac/32bit/LT_Mac.zip",darwinx64:"mac/64bit/LT_Mac.zip",darwinarm64:"mac/64bit/LT_Mac.zip",linuxia32:"linux/32bit/LT_Linux.zip",linuxx64:"linux/64bit/LT_Linux.zip",freebsdia32:"freebsd/32bit/LT_Freebsd.zip",freebsdx64:"freebsd/64bit/LT_Freebsd.zip"},gn=`${Gt.tmpdir()}/LT`,$v=`${gn}/LT`,Wv=(0,Gf.default)("15m"),re=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===O.LAMBDATEST||e.type===O.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){re.isLambdatestGrid(e)&&(re.lambdatestConfigPromise||=dl(),re.lambdatestConfig=await re.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?Wv:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ge($v))return;let t=jv[Gt.platform()+Gt.arch()];if(!t)throw new Error(`tunnel on ${Gt.platform()+Gt.arch()} platform is not supported.`);let r=`${gn}.zip`;await Je(`${Bv}/${t}`,r),await rt(r,gn)}static async chmodLtTunnel(e){if(!(Gt.platform()==="win32"||!await ge(e))){try{await si.access(e,Kf.constants.X_OK);return}catch{}try{await si.chmod(e,"777")}catch(r){throw ri.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await oe(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){re.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await qf.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:o,externalLambdatestNTLMTunnelUsername:i,externalLambdatestNTLMTunnelPassword:a}=e,l=global.proxyUri;re.tunnelName=se();let c=["--tunnelName",re.tunnelName,"--infoAPIPort",String(t)];if(D.flags.enableLambdaTestTunnelNTLM.isEnabled())if(c=[...c,"--ntlm"],i&&a)c=[...c,"--ntlm-username",i,"--ntlm-password",a];else{let u=JSON.parse(D.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(c=[...c,...Sc(u)])}if(D.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(c=[...c,"--skip-upgrade"]),e.externalLambdatestUseWss&&(c=[...c,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(c=[...c,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),r.tunnelUser&&r.tunnelKey)c=[...c,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&o)c=[...c,"--user",n,"--key",o];else throw new P("tunnel requires username and password");if(l)try{let u=new URL(l);c=[...c,"--proxy-host",u.hostname],u.port&&(c=[...c,"--proxy-port",u.port]),u.username&&u.password&&(c=[...c,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new P("proxy url is invalid")}e.externalLambdatestMitm&&(c=[...c,"--mitm"]),await re.delay(3e3),await re.chmodLtTunnel((0,Jf.join)(gn,"LT")),re.tunnel=zf.spawn("./LT",c,{cwd:gn});let d="",m="";re.tunnel.stdout.on("data",u=>{d+=u.toString()}),re.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,Hf.default)(()=>be(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});ri.info("LT tunnel info",u)}catch(u){throw ri.error("Failed to start LT tunnel",{err:u,stdoutResult:d,stderrResult:m}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!re.tunnel))return new Promise((t,r)=>{re.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),re.tunnel.kill()})}getCapabilities(e,t,r,n,o,i){if(!this.isActive)return{};let a=re.lambdatestConfig.CAPABILITIES[t]||{},l={...re.tunnelName&&{tunnel:!0,tunnelName:re.tunnelName}},c=[],{mode:d,canary:m,ext:u,extensionPath:f,installCustomExtension:h}=e,g=(i==null?void 0:i.os)==="Windows 11"?i.os:re.lambdatestConfig.PLATFORM;if(d===Z.EXTENSION&&!u){let y=Fl({canary:m},!0);!f&&y[t]&&(c=[...c,y[t]]),f&&_e(f)&&(c=[...c,f])}return h&&_e(h)&&(c=[...c,h]),{build:r,name:`${n} - ${o}`,platform:g,selenium_version:re.lambdatestConfig.SELENIUM_VERSION,resolution:Gv(i==null?void 0:i.resolution),timezone:re.lambdatestConfig.TIMEZONE,...a,loadExtension:c,...l,console:!0,queueTimeout:300,network:D.flags.LTNetworkCapabilities.isEnabled(),ntlm:D.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:D.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},Vv=["1024x768","1280x800","1280x1024","1366x768","1440x900","1680x1050","1600x1200","1920x1200","1920x1080","2048x1536","2560x1440"]});var nu={};G(nu,{connect:()=>ii,disconnect:()=>ai,serveTunneling:()=>qv});var oi,Yf,Xf,Hv,ii,ai,qv,ou=w(()=>{"use strict";Bf();un();Vf();nt();oi=E(require("ora"));j();ae();ni();Yf=x("tunnel"),Xf=s=>{var e;return[O.LAMBDATEST,O.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},Hv=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===O.HYBRID&&s.gridData.tunnel==="cloudflare"},ii=async s=>{if(!s.tunnel)return;let e=jt(),t;try{Xf(s)?(t=(0,oi.default)("Starting testim lambdatest tunnel...").start(),await re.connectTunnel(s)):Hv(s)?(t=(0,oi.default)("Starting testim cloudflare tunnel...").start(),await $f(s)):(t=(0,oi.default)("Starting testim ngrok tunnel...").start(),await Uf(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw Yf.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(n)}},ai=async s=>{if(s.tunnel)try{Xf(s)?await re.disconnectTunnel(s):"tunnelRoutes"in s?await Wf(s):await Ff(s)}catch(e){let t="catch error - failed to close tunnel";throw Yf.error(t,{err:e}),new Error(t)}},qv=async(s,e=new Promise(()=>{}))=>(await ii(s),es(()=>ai(s)),await e)});function zv(s){if(s.protocol)return s.protocol;if([O.TESTIM,O.BROWSERSTACK,O.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([O.TESTIM_ENTERPRISE,O.LAMBDATEST,O.DEVICE_FARM].includes(s.type)){let e=Qf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function Kv(s){let e=Qf.exec(s);return e==null?void 0:e[3]}function li(s){var R,b,v,I,C,_,$,A,S,L,U;let e=s&&Kv(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&zv(s),o=s==null?void 0:s.token,i=s==null?void 0:s.slotId,a=(R=s==null?void 0:s.hybrid)==null?void 0:R.tunnel,l=(b=s==null?void 0:s.external)==null?void 0:b.user,c=(v=s==null?void 0:s.external)==null?void 0:v.key,d=s==null?void 0:s.type,m=d===O.HYBRID?a&&((_=(C=(I=s.hybrid)==null?void 0:I.external)==null?void 0:C[s.hybrid.tunnel])==null?void 0:_.user):l,u=d===O.HYBRID?a&&((S=(A=($=s.hybrid)==null?void 0:$.external)==null?void 0:A[s.hybrid.tunnel])==null?void 0:S.key):c,f=s==null?void 0:s.name,h=s&&(s._id||s.gridId),g=s==null?void 0:s.provider,y=(L=s==null?void 0:s.mobileTokens)==null?void 0:L.androidToken,T=(U=s==null?void 0:s.mobileTokens)==null?void 0:U.iosToken;return{host:e,port:t,path:r,protocol:n,accessToken:o,slotId:i,gridId:h,tunnel:a,user:l,key:c,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:T}}async function eg(s,e,t,r,n){let o;try{o=await n()}catch(i){throw Qe.error("failed to get grid",{projectId:s,companyId:e,err:i}),new Error(yt.UNKNOWN)}if(Qe.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw Qe.error("invalid response - get grid",{res:o}),new Error(yt.UNKNOWN);if(o.status==="success"){let i=li(o.grid);return Jv(t,e,i.gridId,i.slotId,r),i}throw o.code==="not-found"?new ze(yt.NOT_FOUND):o.code==="no-available-slot"?new Jt(`Failed to run test on ${r} - concurrency limit reached`):(Qe.error("invalid code error response - get grid",{res:o}),new ze(yt.UNKNOWN))}function Yv(s,e,t,r,n,o){return eg(t,e,s,n,()=>Bo(e,t,r,n,o))}function Xv(s,e,t,r,n,o,i){return eg(t,e,s,n,()=>{var c;let l=(c=i.allGrids)==null?void 0:c.find(d=>(d.name||"").toLowerCase()===r.toLowerCase());return l!=null&&l._id?Bo(e,t,l._id,n,o):ll(e,t,r,n,o)})}function tg(s){return pl(s)}async function rg(s,e,t){let n=(t||await tg(s)).find(o=>o._id===e);if(!n)throw new P(`Failed to find grid id: ${e}`);return li(n)}async function Qv(s,e,t){let n=(t||await tg(s)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new P(`Failed to find grid name: ${e}`);return li(n)}async function iu(s,e){let t=hn[s];if(!t)return;let{slotId:r,gridId:n,browser:o,companyId:i}=t;if(delete hn[s],!r){Qe.warn("failed to find grid slot id",{projectId:e});return}Qe.info("release slot id",{projectId:e,companyId:i,slotId:r,gridId:n,browser:o});try{await al(i,e,r,n,o)}catch(a){Qe.error("failed to release slot",{projectId:e,err:a})}}async function Zv(s){let e=Object.values(hn).filter(Boolean);if(e.length!==0){Qe.info("keep alive worker slots",{projectId:s,slots:e});try{await il(s,e)}catch(t){Qe.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function eE(s){Zf=global.setInterval(Zv,1e4,s)}async function tE(s){let e=Object.keys(hn);if(e.length){Qe.warn("not all slots released before end runner flow",{projectId:s});try{await ie(e,t=>iu(Number(t),s))}catch(t){Qe.error("failed to release all slots",{err:t,projectId:s})}}}async function rE(s){await tE(s),clearInterval(Zf)}function sE(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function nE(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function sg(s){let t=(()=>ci.isEmpty(s.testobjectSauce)?ci.isEmpty(s.saucelabs)?ci.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:o,protocol:i}=s,a=sE(t,s),l=nE(t,s);return{host:r,port:n,path:o,protocol:i,type:t,user:l,key:a}}async function ng(s,e){let t=s.company.companyId;return await rg(t,e.gridId,s.allGrids)}async function og(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:o,useChromeLauncher:i,gridId:a,grid:l}=s;if(n||i||o)return{mode:"local"};if(r)return sg(s);let c=t==null?void 0:t.companyId;if(a)return rg(c,a,e);if(l)return Qv(c,l,e);if(Vs(s)||s.tunnelOnlyMode){Qe.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new ze("Missing host or grid configuration")}async function ig(s,e,t,r){let{host:n,project:o,grid:i,gridId:a,localTmaUrl:l,useLocalChromeDriver:c,useChromeLauncher:d,company:m}=t,u=m==null?void 0:m.companyId;if(c||d||l)return{mode:"local"};if(n)return sg(t);if(a)return Yv(r,u,o,a,s,e);if(i)return Xv(r,u,o,i,s,e,t);throw new ze("Missing host or grid configuration")}var ci,Qe,hn,Qf,Zf,Jv,yn,ag,ns=w(()=>{"use strict";ci=E(require("lodash"));he();j();B();ae();K();Qe=x("grid-service"),hn={},Qf=/(^(https?):\/{2})?(.*)/,Zf=null;Jv=(s,e,t,r,n)=>{hn[s]={gridId:t,companyId:e,slotId:r,browser:n}};yn={start:eE,end:rE};ag=async(s={},e={},t={},r={},n={})=>{var h,g,y;let{company:{companyId:o}={}}=s,{gridId:i,type:a}=e,l=s.browser||t.browserValue,c=Boolean(s.tunnel),{maxRetries:d,currentRetry:m}=n;if(!i||!a||(a===O.LAMBDATEST&&await((h=r.enableIfNeeded)==null?void 0:h.call(r,e)),a!==O.HYBRID||!o||!l||!d||!m))return e;let u=await cl({companyId:o,gridId:i,maxRetries:d,currentRetry:m,browser:l,usingTunnel:c});Qe.info("handling hybrid grid",{response:u,companyId:o});let f=li({...e,...u.connectionDetails,provider:u.provider});return u.provider!=="lambdatest"&&((g=r.disable)==null||g.call(r)),u.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,f)),f}});async function au(s,e,t){let r=os[s];if(!r)return;let{slotId:n}=r;if(delete os[s],!n){it.warn("failed to find slot slot id",{companyId:e,workerId:s});return}it.info("release slot id",{companyId:e,slotId:n});try{await Cl(e,t,n)}catch(o){it.error("failed to release slot",{companyId:e,err:o})}}async function oE(s,e){let t=Object.values(os).filter(Boolean);if(t.length!==0){it.info("keep alive worker slots",{companyId:s,slots:t});try{await kl(s,e,t)}catch(r){it.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function iE(s,e){cg=global.setInterval(()=>oE(s,e),1e4)}async function aE(s,e){let t=Object.keys(os);if(t.length){it.warn("not all slots released before end runner flow",{companyId:s});try{await ie(t,r=>au(Number(r),s,e))}catch(r){it.error("failed to release all slots",{err:r,companyId:s})}}}async function cE(s,e){await aE(s,e),clearInterval(cg)}async function ug(s,e,t){let r;try{r=await xl(s,e)}catch(n){throw it.error("failed to get slot",{companyId:s,err:n}),new Error(yt.UNKNOWN)}if(it.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw it.error("invalid response - get slot",{res:r}),new Error(yt.UNKNOWN);if(r.status==="success")return lg(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new ze(yt.NOT_FOUND):r.code==="no-available-slot"?new Jt("Failed to run test - concurrency limit reached"):(it.error("invalid code error response - get slot",{res:r}),new ze(yt.UNKNOWN))}async function pg(s,e,t,r){let n=os[r];if(!n)throw new Error("slot not found");Object.assign(n,t),lg(r,n),await Pl(s,e,n),it.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var it,os,cg,lg,Tn,is=w(()=>{"use strict";he();j();B();ae();K();it=x("slot-service"),os={},cg=null,lg=(s,e)=>{os[s]=e};Tn={start:iE,end:cE}});function vn(){return ui||"master"}function dg(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){ui="master";return}if(s!=null&&s.isArchived)throw new P(`Branch ${s.branch} is archived, run aborted.`);if(s){ui=s.branch||s;return}ui=e?"master":void 0}var ui,cu=w(()=>{"use strict";K()});var En,lu,lE,uu,uE,pi,di,mi,fi,gi,hi=w(()=>{"use strict";B();ae();En=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===de.FAILED},lu=s=>{let{status:e}=s;return e===de.ABORTED},lE=s=>{let{status:e}=s;return e===de.PASSED},uu=s=>s.runnerStatus===yc.SKIPPED,uE=s=>s.testStatus===Ye.EVALUATING,pi=(s,e)=>Object.values(s).filter(t=>{var r,n;return uu(t)&&(Xe(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,di=s=>Object.values(s).filter(e=>En(e)&&uE(e)).length,mi=s=>Object.values(s).filter(En),fi=s=>Object.values(s).filter(lE),gi=s=>Object.values(s).filter(lu)});function dE(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var pu,yi,pE,bi,fg=w(()=>{"use strict";pu=E(require("lodash"));j();hi();yi=x("debug-reporter"),pE=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],bi=class{constructor(e){this.options=e}onTestStarted(e,t){yi.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,o=r.host,i=r.gridId,a=r.type,l=r.failedGetBrowserAttempts;yi.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:o,failedGetBrowserAttempts:l,id:i,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...pu.default.omit(this.options,pE),company:pu.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,o,i,a){let l=dE(process.argv);yi.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:this.sanitizedOptionsForLogging,args:l})}onTestPlanFinished(e,t,r,n,o){let i=fi(e).length,a=Object.keys(e).length-i;yi.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:o,passed:i,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var du,kt,Sn=w(()=>{"use strict";ae();du=class{constructor(){this._planType="free"}setPlanType(e){this._planType=e}get isTestStatusEnabled(){return["pro","trial"].includes(this._planType)}shouldShowFreeGridRunWarning(e){return this._planType!=="pro"&&e===O.DEVICE_FARM}},kt=new du});var fu={};G(fu,{Reporter:()=>mE});var sr,In,Sr,Ti,gg,mu,mE,gu=w(()=>{"use strict";sr=E(require("chalk")),In=E(require("lodash"));B();ae();Sn();hi();Sr={success:sr.default.green,warn:sr.default.yellow,error:sr.default.red},{CLI_MODE:Ti}=Ut,gg="device",mu=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t){let r=`(${e.testId})`,n=`url: ${sr.default.underline(qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?de.PASSED:de.FAILED,n=`(${e.testId})`,o=Sr[e.success?"success":"error"];console.log(o(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${fo(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=qe(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(Sr.error("Failed runs are:")),console.log(Sr.error(t.join(`
|
|
22
|
-
\r`)))}onTestPlanFinished(e,t,r,n,o){let i=mi(e),a=fi(e),l=gi(e),c=a.length,d=l.length,m=i.length,u="",f="";if(kt.isTestStatusEnabled){let R=di(e);u=` FAILED-EVALUATING: ${R}`,m-=R,f=` SKIPPED: ${pi(e,this.options)}`}let h=this.buildTestPlanName(o,t),g,y=Sr[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${fo(r)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${T} (Execution ID: ${n})`:g=`Test plan${h} completed ${T} (${n})`,this.printWorkerDivider(),console.log(y(g)),this.printWorkerDivider(),this.printAllFailedTests(i)}buildTestPlanName(e,t){let r=In.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=In.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,o=In.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,i=In.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[o,n,r,i].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,o,i,a){let l=u=>{u.forEach((f,h)=>{var T;let g=(T=f.testData)!=null&&T.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`;console.log(" ",h+1,":",`${f.name}${Xe(f,this.options)?"-quarantine":""}`,y,g)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${m} (${o})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===Ti.APPIUM?gg:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${sr.default.underline(n)} slot from ${sr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===Ti.APPIUM?gg:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${sr.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,o=this.options.mode===Ti.APPIUM?"device":"browser";if(n)console.log(Sr.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(Sr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===Ti.APPIUM?"Appium":"Selenium";console.log(Sr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},mE=mu});var bu={};G(bu,{Reporter:()=>TE});function fE(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function gE(s){return s.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${s.visitedUrlsList||""}`}function hE(s){return`${s.visitedUrlsJson||""}`}async function yE(s,e,t,r,n,o){function i(u){let f=qe(s,t,u.testId,u.resultId,r),h={$:{name:fE(u),classname:n,time:Ic(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(En(u)||lu(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=En(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return uu(u)&&Xe(u,o)&&kt.isTestStatusEnabled&&(h.skipped={}),o.urls&&(h["visited-urls-list"]=gE(u),h["visited-urls-json"]=hE(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},R={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(kt.isTestStatusEnabled){R.skipped=pi(y,o);let b=di(y);R.failures-=b,R["failure-evaluating"]=b}return{$:R,testcase:Object.keys(y).map(b=>i(y[b]))}}function l(u){let f=Object.keys(u).map(g=>u[g].startTime),h=Math.min.apply(null,f);return h?new Date(h).toISOString():new Date().toISOString()}function c(u){return Object.keys(u).length}function d(u){return mi(u).length+gi(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new yu.Builder().buildObject(m)}catch(u){return bE(u)}}function bE(s){let e=new yu.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:s.message}}}}}};return e.buildObject(t)}var yu,hg,hu,TE,Tu=w(()=>{"use strict";yu=E(require("xml2js"));B();hg=require("fs");Sn();hi();hu=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,r=this.options.project,n=await yE(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await hg.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)}};TE=hu});var yg={};G(yg,{Reporter:()=>wE});function as(s){return s?s.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var wu,vu,wE,bg=w(()=>{"use strict";j();wu=x("team-city-reporter");vu=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${r}`;return as(n)}onTestStarted(e,t,r,n){if(r){wu.debug("skip report test started because is rerun");return}let o=this.getPrintName(e);console.log(`##teamcity[testStarted name='${o}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,o,i){if(o){wu.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${as(t)}' details='${as(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){wu.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${as(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${as(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${as(t)}']`)}},wE=vu});var Tg={};G(Tg,{Reporter:()=>vE});var Eu,vE,wg=w(()=>{"use strict";Eu=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,n,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},vE=Eu});var vg={};G(vg,{Reporter:()=>EE});var Su,EE,Eg=w(()=>{"use strict";B();jl();Su=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Ko(t)}},EE=Su});var Gx,Iu,Q,_t=w(()=>{"use strict";fg();j();Gx=x("reporter"),Iu=class{constructor(){this.reporters=[];this.onGetBrowserFailure=this.generateHook("onGetBrowserFailure");this.onGetBrowserSuccess=this.generateHook("onGetBrowserSuccess");this.onTestPlanStarted=this.generateHook("onTestPlanStarted");this.onGetSlot=this.generateHook("onGetSlot");this.onGetSession=this.generateHook("onGetSession");this.onTestFinished=this.generateHook("onTestFinished");this.onTestFailed=this.generateHook("onTestFailed");this.onTestPassed=this.generateHook("onTestPassed");this.onTestStarted=this.generateHook("onTestStarted");this.onTestIgnored=this.generateHook("onTestIgnored");this.onWaitToTestStart=this.generateHook("onWaitToTestStart");this.onWaitToTestComplete=this.generateHook("onWaitToTestComplete");this.onTestPlanFinished=this.generateHook("onTestPlanFinished",this.onTestPlanFinishedMutator);this.onAllTestPlansFinished=this.generateHook("onAllTestPlansFinished",this.onAllTestPlansFinishedMutator)}async setOptions(e,t){this.reporters=[];let r=e.reporters;if(this.reporters.push(new bi(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(gu(),fu));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(Tu(),bu));this.reporters.push(new o(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(bg(),yg)),r.includes("console")&&Promise.resolve().then(()=>(gu(),fu)),r.includes("junit")&&Promise.resolve().then(()=>(Tu(),bu)),r.includes("json")&&Promise.resolve().then(()=>(wg(),Tg)),r.includes("chrome")&&Promise.resolve().then(()=>(Eg(),vg))])).forEach(o=>{o&&this.reporters.push(new o.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,o){let i={};i=e;let a=Date.now()-(r||0);return[i,t,a,n,o]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var o;let n=t==null?void 0:t(...r);for(let i of this.reporters)await((o=i[e])==null?void 0:o.call(i,...n||r))}}},Q=new Iu});function Ig(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Rg({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:l,source:c,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=Ig({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:l,source:Sg(c,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);Tt("test-run-ci",y)}function Ag({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:o,companyId:i,companyName:a,projectName:l,companyPlan:c,source:d,user:m,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:T}){try{let R=Ig({executionId:s,projectId:e,testId:t,resultId:r,ucid:o,companyId:i,companyName:a,projectName:l,companyPlan:c,mockNetworkEnabled:n.wasMockNetworkActivated,source:Sg(d,m),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){Tt("test-run-ci-success",R);return}Tt("test-run-ci-fail",{...R,failureReason:n.failureReason})}catch(R){f.error("failed to update test end analytics",{err:R})}}function xg(s){Tt("batch-run-ci",s)}var Sg,Ru=w(()=>{"use strict";ts();Uo();Sg=(s,e)=>s!=="cli"&&s!=="cli-local"?s:Qr&&e?"ci-with-user":Qr?"ci":e?"cli-with-user":s});var Pg,wi,kg=w(()=>{"use strict";Pg=require("istanbul-lib-report"),wi=class extends Pg.ReportBase{constructor(t){super();t||={},this.appendToObject=t.appendToObject||{}}onStart(t){let r=t.getCoverageSummary(!1);this.appendToObject=Object.assign(this.appendToObject,r.toJSON())}}});var _g,Og,Lg,Rn,wt,Dg,vi,Au,Ng,SE,Mg,Ug,IE,RE,Fg,AE,xE,CE,PE,kE,Bg,jg=w(()=>{"use strict";_g=E(require("ora")),Og=E(require("dayjs")),Lg=E(require("test-exclude")),Rn=E(require("fs")),wt=E(require("path")),Dg=E(require("istanbul-reports")),vi=E(require("istanbul-lib-report"));he();K();B();j();mn();kg();Au=x("test-run-status"),Ng=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},SE=s=>!!Ng(s).search,Mg=s=>s?Ng(s).pathname.substring(1):"",Ug=(s,e)=>{let t=Mg(e);return!new Lg.default({relativePath:!1,include:s}).shouldInstrument(t)},IE=s=>s.substring(0,s.indexOf("?")),RE=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await ot("convert-source-map");if(t==="file"&&!e)throw new P("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Fg=(s,e)=>`${wt.resolve(s,Mg(e))}.js`,AE=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ie(Object.values(t),async n=>{if(!n)return;let o=n.toObject();await ie(o.sources,async(i,a)=>{if(Ug(r,i))return;let l=Fg(e,i);await Rn.promises.mkdir(wt.parse(l).dir,{recursive:!0}),await Rn.promises.writeFile(l,o.sourcesContent[a])})})},xE={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(SE(e)&&(e=IE(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=wt.dirname(this.getPath(s));return wt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},CE=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=vi.createContext({dir:t,coverageMap:e,watermarks:vi.getDefaultWatermarks(),sourceFinder:a=>{try{let l=Fg(r,a);return Rn.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new wi({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:xE}),Dg.create(a,l).execute(i)}),o},PE=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let i=(await ot("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Ug(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()},kE=async(s,e)=>{let{mergeProcessCovs:r}=await ot("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await fl(s,"testResult",`runId=${e}`)).data.docs;return await ie(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await on(l,9e4);await ie(c,async d=>{if(!o.has(d.url)){let m=d.text;d.sourceUrl&&(o.set(d.url,"TEMP"),m=await Yc(d.sourceUrl)),o.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:o,mergedCoverages:n}},Bg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Au.info("start js coverage process");let n=(0,_g.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=wt.resolve(s.codeCoverageReportPath||"./coverage"),i=wt.resolve(o,`.js/${(0,Og.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?wt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([ot("istanbul-lib-coverage"),kE(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Au.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await ie(c.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=d.get(h),R=await RE({sourceMapType:T,source:y,sourceMapDir:a});u[h]=R;let b=await PE(s,{source:y,sourceMap:R,functions:g});m.merge(b)}),await AE(s,i,u);let f=await CE(s,m,o,i);return n.succeed(),f}catch(l){let c="Failed to report coverage information";l instanceof P?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),Au.error(c,{err:l})}}});var $g={};G($g,{SELENIUM_PERF_MARKS:()=>Ce,SeleniumPerfStats:()=>Ir});var Ce,_E,Ir,cs=w(()=>{"use strict";B();Ce={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},_E=["ALL",...Object.values(Ce)],Ir=class{constructor(){this.marks=Object.fromEntries(_E.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=se();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,yo(r,50)],[`${t}_P95`,yo(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var Hg={};G(Hg,{initServer:()=>DE,mapFilesToLocalDrive:()=>Cu});function Cu(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,Ei[t.id]?{screenshot:Ei[t.id]}:{})),Object.keys(Si).forEach(t=>{s.assets||={},s.assets[Gg[t]]=Si[t]}),s.assets||={},s.assets.screenshots=Object.values(Ei)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function DE({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await ot("multer"),n=typeof t=="string"?t:OE;await xu.promises.mkdir(n,{recursive:!0});let o=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=An.join(n,m.testResultId);try{await xu.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(l,c,d){let{fileName:m}=l.body,u=JSON.parse(l.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=An.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),i=(0,Vg.default)();i.post("/",o.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(Ei[d.stepId]=l.file.path),d.testResultId&&LE.includes(d.subType)&&(Si[d.subType]||=[],Si[d.subType].push(l.file.path)),c.sendStatus(200)}),i.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(i);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new P(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new P(`Port ${s} is already in use`));default:return c(u)}}})}var xu,Wg,An,Vg,OE,Ei,Si,Gg,LE,Pu=w(()=>{"use strict";xu=E(require("fs")),Wg=E(require("os")),An=E(require("path")),Vg=E(require("express"));K();mn();OE=An.join(Wg.tmpdir(),"testim/rca/"),Ei={},Si={},Gg={"test-log":"consoleLogs","har-file":"networkLogs"},LE=Object.keys(Gg)});var nr,ku,Ii,qg=w(()=>{"use strict";nr=E(require("lodash"));B();j();ku=x("override-test-data-builder"),Ii=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return nr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!nr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):ku.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(nr.isObject(e.overrideAllTestsData)&&!nr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):ku.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:r}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}ku.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return nr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let o=r.map(d=>this.generateTestUniqId(d)),i=o.indexOf(n),a=o.lastIndexOf(n),l=r[i],c=this.createNewTestItems(l,t);return r.splice(i,a-i+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let o=se();return{...e,resultId:o,testData:{value:r,index:n+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function Ri(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Ze.warn("failed to run hook",{err:t}),new P(`failed to run hook promise ${t.message}`)}}var Rr,Ze,NE,ME,UE,FE,Ai,zg=w(()=>{"use strict";Rr=E(require("lodash"));B();ae();ns();is();he();K();j();_t();un();jg();cs();Pu();ue();pe();qg();Sn();Ze=x("test-run-status"),NE=hr(),ME=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,UE=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,FE=gt();Ai=class{constructor(e,t,r,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new Ir;var a,l,c,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let o=Ws(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:ro||t.parallel||1,browser:o,gitBranch:NE,gitCommit:ME,gitRepoUrl:UE,runnerVersion:FE,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:i,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:R}=a,b={originalTestResultId:t,previousTestResultId:r,config:Rr.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:i,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:R},bl({projectId:n,runId:o,testId:c,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let o=this.getTestResult(r);return o.workerId=e,Q.onTestStarted(o,e,n,r),o}async updateTestStatusRunning(e,t,r){var c;let{project:n,remoteRunId:o,projectData:i}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await $o(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(d){Ze.error("failed to upload test data artifact (runner)",{err:d})}let l=Rr.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,vr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(Xe(e,this.options))return;let n=this.exportsGlobal;try{let o=await Ri(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token);return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...this.beforeSuiteParams,...o},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(o){throw Ze.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,r,n,o){let i=this.testStart(e,t,r,n);return this.testStartReport(i,t,o)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo={...t,key:void 0,user:void 0},Ze.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:o,testId:i,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Ye.EVALUATING&&kt.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Ye.EVALUATING} status`);return}if(c){Q.onTestPassed(o);return}Q.onTestFailed(r,r.failureReason,qe(this.options.editorUrl,this.options.project,i,l,this.branchToUse),i,n,l)}calcResultText(e){return e.success?de.PASSED:de.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Ye.QUARANTINE}`)}monitorMemoryUsage(e){let t=Rc();t.isOverThreshold&&Ze.info("memoryUsage is over threshold",{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}testEnd(e,t,r,n,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&&Cu(i,Ze),i.resultUrl=qe(this.options.editorUrl,this.options.project,i.testId,i.resultId,this.branchToUse),i.status=this.calcResultText(t),t.status=i.status,t.name=i.name,t.testStatus=i.testStatus,t.testId||=i.testId,t.testCreatorName=i.testCreatorName,t.testCreatorEmail=i.testCreatorEmail,t.testOwnerName=i.testOwnerName,t.testOwnerEmail=i.testOwnerEmail,t.testData=i.config&&typeof i.config.testDataTotal=="number"?{total:i.config.testDataTotal,index:i.config.testDataIndex}:{},this.reportTestStatus(e,t,i,o),this.monitorMemoryUsage(i),Q.onTestFinished(i,e,o);let l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,i}async testEndReport(e,t,r,n){var i;let o=r.exportsGlobal;try{try{await Ri(this.options.afterTest,{...e,exportsGlobal:o,globalParameters:o},this.options.userData.loginData.token)}catch(a){Ze.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(i=this.options.lightweightMode)!=null&&i.onlyTestIdsNoSuite?void 0:await vr(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw Ze.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,o,i){let a=this.testEnd(e,t,r,n,o);return this.testEndReport(a,r,t,i)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:o,VIRTUAL_BUILD:i}=wc;return e&&(n=o),Wr(t,r)&&(n=i),n}calcTestRunStatus(){var i;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(i=e.gridData)==null?void 0:i.type,o=t.map(a=>{var f,h,g;let l=e.browser?qs(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=Vr(D,n)&&Gs(a.nativeApp)&&!e.appId,d=Hs(e)&&(Wr(a.nativeApp,n)||c),m=Xe(a,e)||d,u={testId:a.testId,status:m?de.SKIPPED:de.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Ye.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(c,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((h=a.testData)==null?void 0:h.total)||null,testDataIndex:((g=a.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:l.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(o)}async endKeepAlive(e,t,r){e==="redis"&&await Tn.end(r,t),e==="mongo"&&await yn.end(t)}async executionStart(e,t,r,n,o){Ze.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=i;es(()=>Promise.all([this.endKeepAlive(d,t,c),Fo("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,...D.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},u=await Ri(i.beforeSuite,m),f=new Ii(u,Rr.cloneDeep(this.testInfoList),t);this.testInfoList=f.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:h}=this,g=[],y=[],T=[];for(let b of h){if(b.isBeforeTestPlan){g.push(b);continue}if(b.isAfterTestPlan){T.push(b);continue}y.push(b)}let R=async()=>{let b=Rr.cloneDeep(this.testRunStatus);await ie(Object.keys(b),async _=>{var U;let $=b[_],A=(U=$.config)==null?void 0:U.testData,S=$.testId,L=await $o(t,S,_,A,l.defaults);L&&(delete $.config.testData,$.config.testDataUrl=L)});let v=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),I={executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:v,intersections:i.intersections},C=tl(I);return this.executionStartedPromise=C,C.catch(_=>Ze.error(_)),C};try{await R()}catch(b){Ze.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:y,afterTests:T}}concatSeleniumPerfMarks(e){Rr.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var d;let t=xc(this.testRunStatus),r=t.length,n=0,o=0,i=0;for(let{status:m,testStatus:u}of t)m===de.PASSED&&n++,m===de.SKIPPED&&o++,m===de.FAILED&&u===Ye.EVALUATING&&i++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await Ri(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:o})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Ze.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let c=await Bg(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Fo("FINISHED",e,this.options.project,r===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw Ze.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await el(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function jE(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Nu(s){return Yg.readFileSync(s,{encoding:"base64"})}function eh(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&_e(s))&&s){let r=Nu(s);ls.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${Du(r)} current extension count: ${e.length}`),e.push(r)}}function th(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;if(s.ext||r){let l=typeof s.ext=="string"?s.ext:`${__dirname}/..`,c=r||l,d=`--load-extension=${c}`;ls.info(`adding extension: testim unpacked , path: ${c}`),t.push(d);return}let o=s.canary?"-master.zip":".zip",i=Lu.join(process.cwd(),`testim-headless${o}`),a=Nu(i);ls.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${Du(a)} current extension count: ${e.length}`),e.push(a)}function $E(s,e,t,r,n,o,i){var h,g;let a=t.seleniumName||t.browserValue,l=[],c=[...Zg];e.headless&&c.push("--headless");let d={prefs:{"profile.default_content_setting_values.popups":_u.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":_u.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1},w3c:!0};Ou(n)&&(d.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),Ou(n)&&a==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(d.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(y=>c.push(`--${y}`)),e.chromeBlockLocation&&(d.prefs["profile.default_content_setting_values.geolocation"]=_u.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&c.push(`--user-data-dir=${e.chromeUserDataDir}`),(g=(h=e.projectData)==null?void 0:h.defaults)!=null&&g.disableChromiumGpu&&c.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:a});function m(){t.mobileEmulation&&(d.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+bc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}m(),eh(r,l,i),e.mode===Z.EXTENSION&&th(e,l,c,o,i),l.length>0&&(d.extensions=l),e.disableCookiesSameSiteNoneRequiresSecure&&(d.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),d.args=c;let u={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],f={MicrosoftEdge:"ms",chrome:"goog"}[a];return re.isLambdatestGrid(n)&&delete d.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(s.desiredCapabilities[u]=d),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${f}:${u}`]=d),s}function VE(s,e,t){let r={"pdfjs.disabled":!0};if(D.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":Jg.join(","),"browser.helperApps.neverAsk.openFile":Jg.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.mode===Z.EXTENSION)if(e.ext)s.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=Lu.join(process.cwd(),`testim-firefox-profile${n}`);s.desiredCapabilities.firefox_profile=Nu(o)}return e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function GE(s){return`${s.width}x${s.height}`}function HE(s,e,t,r){let{saucelabs:n}=s;if(n!=null&&n.browserVersion&&(n.version=n.browserVersion),n!=null&&n.username&&n.accessKey){let o={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=n.appiumVersion||t.sl.appiumVersion;let i=(0,Qg.cloneDeep)(t.sl);return(r!=null&&r.resolution||t.sl.screenResolution)&&(o["sauce:options"].screenResolution=GE(r.resolution||t.sl.screenResolution),delete i.screenResolution),at.merge(i,o,n)}return at.merge(o,n)}return{}}function qE(s,e,t){return at.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),{...t.bs,...s.browserstack,name:e}):{...s.browserstack,name:e}}function zE(s){return s.perfecto?s.perfecto:{}}function KE(s,e,t){if(s.experitestToken){let r=e==="safari";return{accessKey:s.experitestToken,browserVersion:"latest",platformName:r?"MAC":"WIN10",seleniumScreenshot:r,newSessionWaitTimeout:t}}return{}}function JE(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,o=r||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=Va(o,i)),a}function xi(s){var T,R,b,v;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,lambdatestService:c}=s;if(o.mode==="local"){let I=[],C=[...Zg],_={};return t.headless&&C.push("--headless"),t.silentDebuggerExtensionApi&&C.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&C.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach($=>C.push(`--${$}`)),t.chromeBinaryLocation&&(_.binary=t.chromeBinaryLocation),t.mode!=="selenium"&&th(t,I,C,null,c),eh(i,I,c),{logLevel:Kg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:C,extensions:I,..._},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:d,driverRequestRetries:m}=t,u=JE(t,o),f={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:Kg,connectionRetryTimeout:d,connectionRetryCount:m,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!at.isEmpty(u)&&{headers:u},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};Ou(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,f.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(f.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key);let h=Number(t.browserTimeout/1e3),g=t.browser||(n==null?void 0:n.browserValue);at.merge(f.desiredCapabilities,HE(t,r,n,e),qE(t,r,n),zE(t),KE(t,g,h),c==null?void 0:c.getCapabilities(t,g,a,l,r,e));let y=null;switch(!t.ext&&!t.extensionPath&&((T=o.host)!=null&&T.endsWith(".testim.io"))&&!t.canary&&t.mode===Z.EXTENSION&&(g==="chrome"||g==="edge-chromium"&&D.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(y="/opt/testim-headless"),g){case"chrome":case"edge-chromium":f=WE(f,t,n,i,o,y,c);break;case"firefox":f=VE(f,t,c);break;case"safari":case"safari technology preview":f=jE(f,g);break;default:break}at.merge(f.desiredCapabilities,t.seleniumCapsFileContent);try{let I={"hub.lambdatest.com":"lambdatest",[D.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},C=S=>S[o.provider]||S[f.host]||S[I[f.host]],_=S=>{var L,U;return C(S)||S[(L=f.desiredCapabilities)==null?void 0:L.browserName]||S[(U=f.desiredCapabilities)==null?void 0:U.version]||S||{}},$=JSON.parse(D.flags.addCustomCapabilities.getValue()||"{}"),A=_(_($));Object.keys(A).length&&(ls.info(`Adding custom capabilities: ${JSON.stringify(A)}`),Object.assign(f.desiredCapabilities,A))}catch(I){ls.error("Failed to load custom capabilities",{error:I,customCapabilities:D.flags.addCustomCapabilities.getValue()})}if(f.desiredCapabilities&&!f.capabilities&&(BE(f),f.capabilities={alwaysMatch:f.desiredCapabilities,firstMatch:[{}]},delete f.desiredCapabilities),f.hostname=f.host,s.printFinalCaps){let I=(R=f.capabilities)==null?void 0:R.alwaysMatch,C=JSON.parse(JSON.stringify(f)),_=(b=C==null?void 0:C.capabilities)==null?void 0:b.alwaysMatch,$=S=>S.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(S=>{var L,U;_!=null&&_[S]&&(_[S].extensions=(U=(L=I==null?void 0:I[S])==null?void 0:L.extensions)==null?void 0:U.map($))}),_!=null&&_.loadExtension&&(_.loadExtension=(v=I==null?void 0:I.loadExtension)==null?void 0:v.map($));let A=require("util");console.log(A.inspect(C,{showHidden:!1,depth:null,colors:!0}))}return f}var Yg,Lu,Xg,at,Qg,ls,Kg,_u,Zg,Du,Ou,BE,WE,Jg,Mu=w(()=>{"use strict";Yg=E(require("fs")),Lu=E(require("path")),Xg=E(require("crypto")),at=E(require("lodash"));B();ue();j();pe();ae();ni();Qg=require("lodash"),ls=x("testim-desired-capabilities-builder"),Kg=to?"debug":"silent",_u={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Zg=["--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"],Du=(...s)=>Xg.createHash("sha256").update(s.join("")).digest("hex"),Ou=s=>s.type===O.DEVICE_FARM||s.type===O.HYBRID&&s.provider==="devicefarm",BE=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=D.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(o=>{delete e[o]})}catch{ls.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};WE=at.memoize($E,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(at.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return Du(i,a,l,r,c,o)}),Jg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Fe(s){var e,t,r,n,o,i,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=s.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function sh(s,e,t){if(!e||!s)return s;if(s.includes("%"))return s.replace(/ /g,"%20");try{return decodeURI(s)!==s?s:encodeURI(s)}catch(r){return t&&t.warn("tried to encode url but failed",{err:r,url:s}),s}}var Uu=w(()=>{"use strict"});function Fu(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let h=u;h&&h!==u.ownerDocument;h=h.parentNode)if(f(h))return h;return null}function n(u,f){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(f(h))return h;return null}function o(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let g=window.getComputedStyle(u).getPropertyValue(f);if(g&&g!=="inherit")return g;let y=t(u);return o(y,f)}function i(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let g=o(u,"stroke-width");return!!g&&parseInt(g,10)>0}return o(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?i(g):!1)}function a(u){return o(u,"overflow")==="hidden"}function l(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!i(f)?!0:l(f))}function c(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:c(u.parentNode):!1}if(!s||!c(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return Fu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(o(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(o(u,"opacity"))===0),m=!!n(s,u=>o(u,"display")==="none");return!(d||m||!i(s)||l(s))}var nh=w(()=>{"use strict"});var oh,ih,Ht,YE,XE,Ci,ah=w(()=>{"use strict";oh=E(require("promise-queue")),ih=E(require("webdriverio"));ue();$e();B();j();Nr();nh();Uu();cs();Ht=x("WebDriverApi"),YE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},XE={implicit:0,pageLoad:1,script:2},Ci=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}async rejectWithLog(e,t){let{testName:r,testResultId:n}=this,o=t?t.toString().substr(0,2e3):"";throw Ht.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),za!==void 0&&(e=za);let t=1/0;this.queue=new oh.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(o){return this.rejectWithLog(o,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,i;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),M("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(Ce.GET_BROWSER);try{await this.addToQueue(async()=>{Ht.info("requesting browser",{testResultId:r,testName:t}),M("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await ih.remote(e),this.logGridStatus(r)}),M("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,Ce.GET_BROWSER)}}async logGridStatus(e){var i;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",o;try{o=await this.client.status();for(let a of o.nodes||[])for(let l of a.slots||[])if(((i=l==null?void 0:l.session)==null?void 0:i.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){Ht.info("grid status is not supported by the grid",{testResultId:e});return}Ht.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Ht.info("grid status",{gridStatusMsg:o.message,ready:o.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},o=()=>this.client.execute(e,t).catch(n),i=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return o();t=t.map(a=>{if(a===null){Ht.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await i()}catch(a){if(Fe(a))return this.unsupportedActions.add("execute"),o();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),o=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await o()}catch(i){if(Fe(i))return this.unsupportedActions.add("executeAsync"),n();throw i}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Ce.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,Ce.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Ce.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(De(e)))}finally{this.seleniumPerfStats.markEnd(t,Ce.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(Fu,{ELEMENT:e,[zt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Fe(n))return this.unsupportedActions.add("elementIdDisplayed"),r();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(sh(e,this.isSafari(),Ht))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let r=()=>{let o=[];return o[XE[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(o){if(Fe(o))return this.unsupportedActions.add("timeouts"),n();throw o}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,o){window.scrollTo(n,o)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(De(e)),await this.elementIdValue(De(e),t)}async getViewportSize(e){let t=await this.execute(YE);if(typeof e=="string"&&e.match(/(width|height)/)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(De(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let o=Math.abs(e.width),i=Math.abs(e.height);r=async()=>await this.client.setWindowSize(o,i),n=async()=>await this.client._setWindowSize(o,i)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(o){if(Fe(o))return this.unsupportedActions.add("windowHandleSize"),r();throw o}})}}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>{var l;return(l=this.client)==null?void 0:l.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){Ht.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return Ht.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var ch={};G(ch,{doubleClick:()=>QE});var QE,lh=w(()=>{"use strict";QE=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(u){function f(R,b,v){return v>R&&v<b}let h=u.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&f(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,T=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:T}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},c=function(u,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=i(u),h=u.event;return t.includes(h)?l(h,f.x,f.y):c(h,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var xn={};G(xn,{dispatchFocus:()=>ZE});function ZE(s,e){function t(o){let i=document.createEvent("HTMLEvents");return i.initEvent(o,!0,!1),i}function r(){var i;let o=document.activeElement;for(;(i=o.shadowRoot)!=null&&i.activeElement;)o=o.shadowRoot.activeElement;return o}function n(o,i){i&&(i.dispatchEvent(t("focusout")),i.dispatchEvent(t("blur"))),o.dispatchEvent(t("focusin")),o.dispatchEvent(t("focus")),typeof o.focus=="function"&&o.focus();let a=r();i&&a===i&&typeof i.blur=="function"&&i.blur()}if(s){let o=getLocatedElement(s);if(o&&o!==e)try{n(o,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var Cn=w(()=>{"use strict"});var fh={};G(fh,{WebDriver:()=>xr});async function sS(s){var e,t;try{let r=(t=(e=s==null?void 0:s.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return r?await tS(r):void 0}catch(r){Be.info("Error getting cdpAddress",r);return}}var us,dh,mh,Be,or,eS,uh,tS,ir,rS,ph,Ar,xr,Pn=w(()=>{"use strict";us=E(require("lodash"));B();$e();Mu();dh=E(require("p-retry")),mh=E(require("ua-parser-js"));Nr();j();Uu();ah();K();pe();cs();Be=x("webdriver"),[or,eS]=[0,2],{extractElementId:uh,getCdpAddressForHost:tS}=J,ir=()=>(Te(),ye(tr)).getSessionPlayer().codeSnippets,rS=()=>(Te(),ye(tr)).getSessionPlayer().locatorBuilderUtils,ph=()=>(Te(),ye(tr)).getSessionPlayer().utils,Ar=()=>(Te(),ye(tr)).getSessionPlayer().positionUtils;xr=class extends Ci{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var R,b,v,I,C,_,$,A;let{overrideConfiguration:r,browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f,printFinalCaps:h}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((v=(b=(R=n==null?void 0:n.company)==null?void 0:R.activePlan)==null?void 0:b.premiumFeatures)==null?void 0:v.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let g=xi({browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r,printFinalCaps:h});g.desiredCapabilities&&delete g.desiredCapabilities.marionette,g.capabilities&&delete g.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let y=u?0:1500,T=u?()=>null:()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let S=await this.initClient(g,o,d);M("after initResult before getCdpAddress in init"),this.cdpUrl=await sS(S),M("after getCdpAddress in webdriver.js init"),Be.info(`init new session testName: ${o}`,{sessionId:this.getSessionId(),testResultId:d}),await oe(y),D.flags.dontFocusOnInit.isEnabled()||await T(),M("after focus and delay in webdriver.js init")}catch(S){let L=JSON.stringify(us.omit(g,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Be.error("failed to init webdriver",{err:S,capabilitiesAsString:L});let U=((C=(I=n==null?void 0:n.company)==null?void 0:I.activePlan)==null?void 0:C.plan)==="free";throw(_=S.stack)!=null&&_.includes("at startWebDriverSession")&&(($=S.message)!=null&&$.startsWith("Failed to create session"))&&((A=S.message)!=null&&A.includes("Timeout awaiting 'request'"))&&U?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):S.message.match(/Invalid username or password/)?new Br(S.message):S.message.match(/capabilit(y|ies)/)?new oo(S.message):S.message.match(/403 Forbidden/)?new Error("Grid Access Denied"):S.message.match(/Browser_Version not supported/)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${S.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>us.zip(o.slice(0,-1),o.slice(1)),r=this._keepAliveRequests.map(({start:o})=>o).filter(Boolean),n=t(r).map(([o,i])=>i-o);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function o(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let i=se();r(i);try{await this.executeJS(o),this._isAlive=!0,n("end",i),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",i),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Be.warn("close unexpected alert open"),await this.alertAccept().catch(l=>Be.warn("failed to click on alert",{err:l}));return}if(Be.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;Be.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:l,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=l&&this.browserClosedCallbacks.forEach(c=>{try{c(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=uh(r.value);return await this.switchToFrame({ELEMENT:n,[zt]:n}),r}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new io:r}}async getElement(t){var o;let r=this.seleniumPerfStats.markStart(Ce.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,Ce.GET_ELEMENT)}if(((o=t==null?void 0:t.shadowPath)==null?void 0:o.length)||D.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
22
|
+
\r`)))}onTestPlanFinished(e,t,r,n,o){let i=mi(e),a=fi(e),l=gi(e),c=a.length,d=l.length,m=i.length,u="",f="";if(kt.isTestStatusEnabled){let R=di(e);u=` FAILED-EVALUATING: ${R}`,m-=R,f=` SKIPPED: ${pi(e,this.options)}`}let h=this.buildTestPlanName(o,t),g,y=Sr[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${fo(r)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${T} (Execution ID: ${n})`:g=`Test plan${h} completed ${T} (${n})`,this.printWorkerDivider(),console.log(y(g)),this.printWorkerDivider(),this.printAllFailedTests(i)}buildTestPlanName(e,t){let r=In.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=In.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,o=In.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,i=In.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[o,n,r,i].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,o,i,a){let l=u=>{u.forEach((f,h)=>{var T;let g=(T=f.testData)!=null&&T.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`;console.log(" ",h+1,":",`${f.name}${Xe(f,this.options)?"-quarantine":""}`,y,g)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${m} (${o})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===Ti.APPIUM?gg:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${sr.default.underline(n)} slot from ${sr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===Ti.APPIUM?gg:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${sr.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,o=this.options.mode===Ti.APPIUM?"device":"browser";if(n)console.log(Sr.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(Sr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===Ti.APPIUM?"Appium":"Selenium";console.log(Sr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},mE=mu});var bu={};G(bu,{Reporter:()=>TE});function fE(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function gE(s){return s.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${s.visitedUrlsList||""}`}function hE(s){return`${s.visitedUrlsJson||""}`}async function yE(s,e,t,r,n,o){function i(u){let f=qe(s,t,u.testId,u.resultId,r),h={$:{name:fE(u),classname:n,time:Ic(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(En(u)||lu(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=En(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return uu(u)&&Xe(u,o)&&kt.isTestStatusEnabled&&(h.skipped={}),o.urls&&(h["visited-urls-list"]=gE(u),h["visited-urls-json"]=hE(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},R={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(kt.isTestStatusEnabled){R.skipped=pi(y,o);let b=di(y);R.failures-=b,R["failure-evaluating"]=b}return{$:R,testcase:Object.keys(y).map(b=>i(y[b]))}}function l(u){let f=Object.keys(u).map(g=>u[g].startTime),h=Math.min.apply(null,f);return h?new Date(h).toISOString():new Date().toISOString()}function c(u){return Object.keys(u).length}function d(u){return mi(u).length+gi(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new yu.Builder().buildObject(m)}catch(u){return bE(u)}}function bE(s){let e=new yu.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:s.message}}}}}};return e.buildObject(t)}var yu,hg,hu,TE,Tu=w(()=>{"use strict";yu=E(require("xml2js"));B();hg=require("fs");Sn();hi();hu=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,r=this.options.project,n=await yE(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await hg.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)}};TE=hu});var yg={};G(yg,{Reporter:()=>wE});function as(s){return s?s.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var wu,vu,wE,bg=w(()=>{"use strict";j();wu=x("team-city-reporter");vu=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${r}`;return as(n)}onTestStarted(e,t,r,n){if(r){wu.debug("skip report test started because is rerun");return}let o=this.getPrintName(e);console.log(`##teamcity[testStarted name='${o}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,o,i){if(o){wu.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${as(t)}' details='${as(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){wu.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${as(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${as(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${as(t)}']`)}},wE=vu});var Tg={};G(Tg,{Reporter:()=>vE});var Eu,vE,wg=w(()=>{"use strict";Eu=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,n,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},vE=Eu});var vg={};G(vg,{Reporter:()=>EE});var Su,EE,Eg=w(()=>{"use strict";B();jl();Su=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Ko(t)}},EE=Su});var Gx,Iu,Q,_t=w(()=>{"use strict";fg();j();Gx=x("reporter"),Iu=class{constructor(){this.reporters=[];this.onGetBrowserFailure=this.generateHook("onGetBrowserFailure");this.onGetBrowserSuccess=this.generateHook("onGetBrowserSuccess");this.onTestPlanStarted=this.generateHook("onTestPlanStarted");this.onGetSlot=this.generateHook("onGetSlot");this.onGetSession=this.generateHook("onGetSession");this.onTestFinished=this.generateHook("onTestFinished");this.onTestFailed=this.generateHook("onTestFailed");this.onTestPassed=this.generateHook("onTestPassed");this.onTestStarted=this.generateHook("onTestStarted");this.onTestIgnored=this.generateHook("onTestIgnored");this.onWaitToTestStart=this.generateHook("onWaitToTestStart");this.onWaitToTestComplete=this.generateHook("onWaitToTestComplete");this.onTestPlanFinished=this.generateHook("onTestPlanFinished",this.onTestPlanFinishedMutator);this.onAllTestPlansFinished=this.generateHook("onAllTestPlansFinished",this.onAllTestPlansFinishedMutator)}async setOptions(e,t){this.reporters=[];let r=e.reporters;if(this.reporters.push(new bi(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(gu(),fu));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(Tu(),bu));this.reporters.push(new o(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(bg(),yg)),r.includes("console")&&Promise.resolve().then(()=>(gu(),fu)),r.includes("junit")&&Promise.resolve().then(()=>(Tu(),bu)),r.includes("json")&&Promise.resolve().then(()=>(wg(),Tg)),r.includes("chrome")&&Promise.resolve().then(()=>(Eg(),vg))])).forEach(o=>{o&&this.reporters.push(new o.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,o){let i={};i=e;let a=Date.now()-(r||0);return[i,t,a,n,o]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var o;let n=t==null?void 0:t(...r);for(let i of this.reporters)await((o=i[e])==null?void 0:o.call(i,...n||r))}}},Q=new Iu});function Ig(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Rg({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:l,source:c,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=Ig({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:l,source:Sg(c,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);Tt("test-run-ci",y)}function Ag({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:o,companyId:i,companyName:a,projectName:l,companyPlan:c,source:d,user:m,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:T}){try{let R=Ig({executionId:s,projectId:e,testId:t,resultId:r,ucid:o,companyId:i,companyName:a,projectName:l,companyPlan:c,mockNetworkEnabled:n.wasMockNetworkActivated,source:Sg(d,m),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){Tt("test-run-ci-success",R);return}Tt("test-run-ci-fail",{...R,failureReason:n.failureReason})}catch(R){f.error("failed to update test end analytics",{err:R})}}function xg(s){Tt("batch-run-ci",s)}var Sg,Ru=w(()=>{"use strict";ts();Uo();Sg=(s,e)=>s!=="cli"&&s!=="cli-local"?s:Qr&&e?"ci-with-user":Qr?"ci":e?"cli-with-user":s});var Pg,wi,kg=w(()=>{"use strict";Pg=require("istanbul-lib-report"),wi=class extends Pg.ReportBase{constructor(t){super();t||={},this.appendToObject=t.appendToObject||{}}onStart(t){let r=t.getCoverageSummary(!1);this.appendToObject=Object.assign(this.appendToObject,r.toJSON())}}});var _g,Og,Lg,Rn,wt,Dg,vi,Au,Ng,SE,Mg,Ug,IE,RE,Fg,AE,xE,CE,PE,kE,Bg,jg=w(()=>{"use strict";_g=E(require("ora")),Og=E(require("dayjs")),Lg=E(require("test-exclude")),Rn=E(require("fs")),wt=E(require("path")),Dg=E(require("istanbul-reports")),vi=E(require("istanbul-lib-report"));he();K();B();j();mn();kg();Au=x("test-run-status"),Ng=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},SE=s=>!!Ng(s).search,Mg=s=>s?Ng(s).pathname.substring(1):"",Ug=(s,e)=>{let t=Mg(e);return!new Lg.default({relativePath:!1,include:s}).shouldInstrument(t)},IE=s=>s.substring(0,s.indexOf("?")),RE=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await ot("convert-source-map");if(t==="file"&&!e)throw new P("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Fg=(s,e)=>`${wt.resolve(s,Mg(e))}.js`,AE=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ie(Object.values(t),async n=>{if(!n)return;let o=n.toObject();await ie(o.sources,async(i,a)=>{if(Ug(r,i))return;let l=Fg(e,i);await Rn.promises.mkdir(wt.parse(l).dir,{recursive:!0}),await Rn.promises.writeFile(l,o.sourcesContent[a])})})},xE={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(SE(e)&&(e=IE(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=wt.dirname(this.getPath(s));return wt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},CE=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=vi.createContext({dir:t,coverageMap:e,watermarks:vi.getDefaultWatermarks(),sourceFinder:a=>{try{let l=Fg(r,a);return Rn.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new wi({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:xE}),Dg.create(a,l).execute(i)}),o},PE=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let i=(await ot("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Ug(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()},kE=async(s,e)=>{let{mergeProcessCovs:r}=await ot("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await fl(s,"testResult",`runId=${e}`)).data.docs;return await ie(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await on(l,9e4);await ie(c,async d=>{if(!o.has(d.url)){let m=d.text;d.sourceUrl&&(o.set(d.url,"TEMP"),m=await Yc(d.sourceUrl)),o.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:o,mergedCoverages:n}},Bg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Au.info("start js coverage process");let n=(0,_g.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=wt.resolve(s.codeCoverageReportPath||"./coverage"),i=wt.resolve(o,`.js/${(0,Og.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?wt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([ot("istanbul-lib-coverage"),kE(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Au.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await ie(c.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=d.get(h),R=await RE({sourceMapType:T,source:y,sourceMapDir:a});u[h]=R;let b=await PE(s,{source:y,sourceMap:R,functions:g});m.merge(b)}),await AE(s,i,u);let f=await CE(s,m,o,i);return n.succeed(),f}catch(l){let c="Failed to report coverage information";l instanceof P?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),Au.error(c,{err:l})}}});var $g={};G($g,{SELENIUM_PERF_MARKS:()=>Ce,SeleniumPerfStats:()=>Ir});var Ce,_E,Ir,cs=w(()=>{"use strict";B();Ce={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},_E=["ALL",...Object.values(Ce)],Ir=class{constructor(){this.marks=Object.fromEntries(_E.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=se();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,yo(r,50)],[`${t}_P95`,yo(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var Hg={};G(Hg,{initServer:()=>DE,mapFilesToLocalDrive:()=>Cu});function Cu(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,Ei[t.id]?{screenshot:Ei[t.id]}:{})),Object.keys(Si).forEach(t=>{s.assets||={},s.assets[Gg[t]]=Si[t]}),s.assets||={},s.assets.screenshots=Object.values(Ei)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function DE({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await ot("multer"),n=typeof t=="string"?t:OE;await xu.promises.mkdir(n,{recursive:!0});let o=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=An.join(n,m.testResultId);try{await xu.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(l,c,d){let{fileName:m}=l.body,u=JSON.parse(l.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=An.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),i=(0,Vg.default)();i.post("/",o.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(Ei[d.stepId]=l.file.path),d.testResultId&&LE.includes(d.subType)&&(Si[d.subType]||=[],Si[d.subType].push(l.file.path)),c.sendStatus(200)}),i.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(i);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new P(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new P(`Port ${s} is already in use`));default:return c(u)}}})}var xu,Wg,An,Vg,OE,Ei,Si,Gg,LE,Pu=w(()=>{"use strict";xu=E(require("fs")),Wg=E(require("os")),An=E(require("path")),Vg=E(require("express"));K();mn();OE=An.join(Wg.tmpdir(),"testim/rca/"),Ei={},Si={},Gg={"test-log":"consoleLogs","har-file":"networkLogs"},LE=Object.keys(Gg)});var nr,ku,Ii,qg=w(()=>{"use strict";nr=E(require("lodash"));B();j();ku=x("override-test-data-builder"),Ii=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return nr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!nr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):ku.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(nr.isObject(e.overrideAllTestsData)&&!nr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):ku.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:r}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}ku.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return nr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let o=r.map(d=>this.generateTestUniqId(d)),i=o.indexOf(n),a=o.lastIndexOf(n),l=r[i],c=this.createNewTestItems(l,t);return r.splice(i,a-i+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let o=se();return{...e,resultId:o,testData:{value:r,index:n+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function Ri(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Ze.warn("failed to run hook",{err:t}),new P(`failed to run hook promise ${t.message}`)}}var Rr,Ze,NE,ME,UE,FE,Ai,zg=w(()=>{"use strict";Rr=E(require("lodash"));B();ae();ns();is();he();K();j();_t();un();jg();cs();Pu();ue();pe();qg();Sn();Ze=x("test-run-status"),NE=hr(),ME=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,UE=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,FE=gt();Ai=class{constructor(e,t,r,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new Ir;var a,l,c,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let o=Ws(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:ro||t.parallel||1,browser:o,gitBranch:NE,gitCommit:ME,gitRepoUrl:UE,runnerVersion:FE,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:i,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:R}=a,b={originalTestResultId:t,previousTestResultId:r,config:Rr.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:i,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:R},bl({projectId:n,runId:o,testId:c,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let o=this.getTestResult(r);return o.workerId=e,Q.onTestStarted(o,e,n,r),o}async updateTestStatusRunning(e,t,r){var c;let{project:n,remoteRunId:o,projectData:i}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await $o(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(d){Ze.error("failed to upload test data artifact (runner)",{err:d})}let l=Rr.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,vr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(Xe(e,this.options))return;let n=this.exportsGlobal;try{let o=await Ri(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token);return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...this.beforeSuiteParams,...o},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(o){throw Ze.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,r,n,o){let i=this.testStart(e,t,r,n);return this.testStartReport(i,t,o)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo={...t,key:void 0,user:void 0},Ze.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:o,testId:i,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Ye.EVALUATING&&kt.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Ye.EVALUATING} status`);return}if(c){Q.onTestPassed(o);return}Q.onTestFailed(r,r.failureReason,qe(this.options.editorUrl,this.options.project,i,l,this.branchToUse),i,n,l)}calcResultText(e){return e.success?de.PASSED:de.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Ye.QUARANTINE}`)}monitorMemoryUsage(e){let t=Rc();t.isOverThreshold&&Ze.info("memoryUsage is over threshold",{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}testEnd(e,t,r,n,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&&Cu(i,Ze),i.resultUrl=qe(this.options.editorUrl,this.options.project,i.testId,i.resultId,this.branchToUse),i.status=this.calcResultText(t),t.status=i.status,t.name=i.name,t.testStatus=i.testStatus,t.testId||=i.testId,t.testCreatorName=i.testCreatorName,t.testCreatorEmail=i.testCreatorEmail,t.testOwnerName=i.testOwnerName,t.testOwnerEmail=i.testOwnerEmail,t.testData=i.config&&typeof i.config.testDataTotal=="number"?{total:i.config.testDataTotal,index:i.config.testDataIndex}:{},this.reportTestStatus(e,t,i,o),this.monitorMemoryUsage(i),Q.onTestFinished(i,e,o);let l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,i}async testEndReport(e,t,r,n){var i;let o=r.exportsGlobal;try{try{await Ri(this.options.afterTest,{...e,exportsGlobal:o,globalParameters:o},this.options.userData.loginData.token)}catch(a){Ze.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(i=this.options.lightweightMode)!=null&&i.onlyTestIdsNoSuite?void 0:await vr(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw Ze.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,o,i){let a=this.testEnd(e,t,r,n,o);return this.testEndReport(a,r,t,i)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:o,VIRTUAL_BUILD:i}=wc;return e&&(n=o),Wr(t,r)&&(n=i),n}calcTestRunStatus(){var i;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(i=e.gridData)==null?void 0:i.type,o=t.map(a=>{var f,h,g;let l=e.browser?qs(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=Vr(D,n)&&Gs(a.nativeApp)&&!e.appId,d=Hs(e)&&(Wr(a.nativeApp,n)||c),m=Xe(a,e)||d,u={testId:a.testId,status:m?de.SKIPPED:de.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Ye.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(c,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((h=a.testData)==null?void 0:h.total)||null,testDataIndex:((g=a.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:l.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(o)}async endKeepAlive(e,t,r){e==="redis"&&await Tn.end(r,t),e==="mongo"&&await yn.end(t)}async executionStart(e,t,r,n,o){Ze.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=i;es(()=>Promise.all([this.endKeepAlive(d,t,c),Fo("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,...D.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},u=await Ri(i.beforeSuite,m),f=new Ii(u,Rr.cloneDeep(this.testInfoList),t);this.testInfoList=f.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:h}=this,g=[],y=[],T=[];for(let b of h){if(b.isBeforeTestPlan){g.push(b);continue}if(b.isAfterTestPlan){T.push(b);continue}y.push(b)}let R=async()=>{let b=Rr.cloneDeep(this.testRunStatus);await ie(Object.keys(b),async C=>{var L;let _=b[C],$=(L=_.config)==null?void 0:L.testData,A=_.testId,S=await $o(t,A,C,$,l.defaults);S&&(delete _.config.testData,_.config.testDataUrl=S)});let v=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),I=tl({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:v,intersections:i.intersections});return this.executionStartedPromise=I,I.catch(C=>Ze.error(C)),I};try{await R()}catch(b){Ze.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:y,afterTests:T}}concatSeleniumPerfMarks(e){Rr.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var d;let t=xc(this.testRunStatus),r=t.length,n=0,o=0,i=0;for(let{status:m,testStatus:u}of t)m===de.PASSED&&n++,m===de.SKIPPED&&o++,m===de.FAILED&&u===Ye.EVALUATING&&i++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await Ri(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:o})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Ze.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let c=await Bg(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Fo("FINISHED",e,this.options.project,r===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw Ze.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await el(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function jE(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Nu(s){return Yg.readFileSync(s,{encoding:"base64"})}function eh(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&_e(s))&&s){let r=Nu(s);ls.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${Du(r)} current extension count: ${e.length}`),e.push(r)}}function th(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;if(s.ext||r){let l=typeof s.ext=="string"?s.ext:`${__dirname}/..`,c=r||l,d=`--load-extension=${c}`;ls.info(`adding extension: testim unpacked , path: ${c}`),t.push(d);return}let o=s.canary?"-master.zip":".zip",i=Lu.join(process.cwd(),`testim-headless${o}`),a=Nu(i);ls.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${Du(a)} current extension count: ${e.length}`),e.push(a)}function $E(s,e,t,r,n,o,i){var h,g;let a=t.seleniumName||t.browserValue,l=[],c=[...Zg];e.headless&&c.push("--headless");let d={prefs:{"profile.default_content_setting_values.popups":_u.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":_u.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1},w3c:!0};Ou(n)&&(d.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),Ou(n)&&a==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(d.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(y=>c.push(`--${y}`)),e.chromeBlockLocation&&(d.prefs["profile.default_content_setting_values.geolocation"]=_u.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&c.push(`--user-data-dir=${e.chromeUserDataDir}`),(g=(h=e.projectData)==null?void 0:h.defaults)!=null&&g.disableChromiumGpu&&c.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:a});function m(){t.mobileEmulation&&(d.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+bc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}m(),eh(r,l,i),e.mode===Z.EXTENSION&&th(e,l,c,o,i),l.length>0&&(d.extensions=l),e.disableCookiesSameSiteNoneRequiresSecure&&(d.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),d.args=c;let u={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],f={MicrosoftEdge:"ms",chrome:"goog"}[a];return re.isLambdatestGrid(n)&&delete d.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(s.desiredCapabilities[u]=d),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${f}:${u}`]=d),s}function VE(s,e,t){let r={"pdfjs.disabled":!0};if(D.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":Jg.join(","),"browser.helperApps.neverAsk.openFile":Jg.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.mode===Z.EXTENSION)if(e.ext)s.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=Lu.join(process.cwd(),`testim-firefox-profile${n}`);s.desiredCapabilities.firefox_profile=Nu(o)}return e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function GE(s){return`${s.width}x${s.height}`}function HE(s,e,t,r){let{saucelabs:n}=s;if(n!=null&&n.browserVersion&&(n.version=n.browserVersion),n!=null&&n.username&&n.accessKey){let o={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=n.appiumVersion||t.sl.appiumVersion;let i=(0,Qg.cloneDeep)(t.sl);return(r!=null&&r.resolution||t.sl.screenResolution)&&(o["sauce:options"].screenResolution=GE(r.resolution||t.sl.screenResolution),delete i.screenResolution),at.merge(i,o,n)}return at.merge(o,n)}return{}}function qE(s,e,t){return at.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),{...t.bs,...s.browserstack,name:e}):{...s.browserstack,name:e}}function zE(s){return s.perfecto?s.perfecto:{}}function KE(s,e,t){if(s.experitestToken){let r=e==="safari";return{accessKey:s.experitestToken,browserVersion:"latest",platformName:r?"MAC":"WIN10",seleniumScreenshot:r,newSessionWaitTimeout:t}}return{}}function JE(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,o=r||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=Va(o,i)),a}function xi(s){var T,R,b,v;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,lambdatestService:c}=s;if(o.mode==="local"){let I=[],C=[...Zg],_={};return t.headless&&C.push("--headless"),t.silentDebuggerExtensionApi&&C.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&C.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach($=>C.push(`--${$}`)),t.chromeBinaryLocation&&(_.binary=t.chromeBinaryLocation),t.mode!=="selenium"&&th(t,I,C,null,c),eh(i,I,c),{logLevel:Kg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:C,extensions:I,..._},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:d,driverRequestRetries:m}=t,u=JE(t,o),f={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:Kg,connectionRetryTimeout:d,connectionRetryCount:m,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!at.isEmpty(u)&&{headers:u},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};Ou(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,f.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(f.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key);let h=Number(t.browserTimeout/1e3),g=t.browser||(n==null?void 0:n.browserValue);at.merge(f.desiredCapabilities,HE(t,r,n,e),qE(t,r,n),zE(t),KE(t,g,h),c==null?void 0:c.getCapabilities(t,g,a,l,r,e));let y=null;switch(!t.ext&&!t.extensionPath&&((T=o.host)!=null&&T.endsWith(".testim.io"))&&!t.canary&&t.mode===Z.EXTENSION&&(g==="chrome"||g==="edge-chromium"&&D.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(y="/opt/testim-headless"),g){case"chrome":case"edge-chromium":f=WE(f,t,n,i,o,y,c);break;case"firefox":f=VE(f,t,c);break;case"safari":case"safari technology preview":f=jE(f,g);break;default:break}at.merge(f.desiredCapabilities,t.seleniumCapsFileContent);try{let I={"hub.lambdatest.com":"lambdatest",[D.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},C=S=>S[o.provider]||S[f.host]||S[I[f.host]],_=S=>{var L,U;return C(S)||S[(L=f.desiredCapabilities)==null?void 0:L.browserName]||S[(U=f.desiredCapabilities)==null?void 0:U.version]||S||{}},$=JSON.parse(D.flags.addCustomCapabilities.getValue()||"{}"),A=_(_($));Object.keys(A).length&&(ls.info(`Adding custom capabilities: ${JSON.stringify(A)}`),Object.assign(f.desiredCapabilities,A))}catch(I){ls.error("Failed to load custom capabilities",{error:I,customCapabilities:D.flags.addCustomCapabilities.getValue()})}if(f.desiredCapabilities&&!f.capabilities&&(BE(f),f.capabilities={alwaysMatch:f.desiredCapabilities,firstMatch:[{}]},delete f.desiredCapabilities),f.hostname=f.host,s.printFinalCaps){let I=(R=f.capabilities)==null?void 0:R.alwaysMatch,C=JSON.parse(JSON.stringify(f)),_=(b=C==null?void 0:C.capabilities)==null?void 0:b.alwaysMatch,$=S=>S.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(S=>{var L,U;_!=null&&_[S]&&(_[S].extensions=(U=(L=I==null?void 0:I[S])==null?void 0:L.extensions)==null?void 0:U.map($))}),_!=null&&_.loadExtension&&(_.loadExtension=(v=I==null?void 0:I.loadExtension)==null?void 0:v.map($));let A=require("util");console.log(A.inspect(C,{showHidden:!1,depth:null,colors:!0}))}return f}var Yg,Lu,Xg,at,Qg,ls,Kg,_u,Zg,Du,Ou,BE,WE,Jg,Mu=w(()=>{"use strict";Yg=E(require("fs")),Lu=E(require("path")),Xg=E(require("crypto")),at=E(require("lodash"));B();ue();j();pe();ae();ni();Qg=require("lodash"),ls=x("testim-desired-capabilities-builder"),Kg=to?"debug":"silent",_u={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Zg=["--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"],Du=(...s)=>Xg.createHash("sha256").update(s.join("")).digest("hex"),Ou=s=>s.type===O.DEVICE_FARM||s.type===O.HYBRID&&s.provider==="devicefarm",BE=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=D.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(o=>{delete e[o]})}catch{ls.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};WE=at.memoize($E,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(at.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return Du(i,a,l,r,c,o)}),Jg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Fe(s){var e,t,r,n,o,i,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=s.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function sh(s,e,t){if(!e||!s)return s;if(s.includes("%"))return s.replace(/ /g,"%20");try{return decodeURI(s)!==s?s:encodeURI(s)}catch(r){return t&&t.warn("tried to encode url but failed",{err:r,url:s}),s}}var Uu=w(()=>{"use strict"});function Fu(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let h=u;h&&h!==u.ownerDocument;h=h.parentNode)if(f(h))return h;return null}function n(u,f){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(f(h))return h;return null}function o(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let g=window.getComputedStyle(u).getPropertyValue(f);if(g&&g!=="inherit")return g;let y=t(u);return o(y,f)}function i(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let g=o(u,"stroke-width");return!!g&&parseInt(g,10)>0}return o(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?i(g):!1)}function a(u){return o(u,"overflow")==="hidden"}function l(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!i(f)?!0:l(f))}function c(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:c(u.parentNode):!1}if(!s||!c(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return Fu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(o(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(o(u,"opacity"))===0),m=!!n(s,u=>o(u,"display")==="none");return!(d||m||!i(s)||l(s))}var nh=w(()=>{"use strict"});var oh,ih,Ht,YE,XE,Ci,ah=w(()=>{"use strict";oh=E(require("promise-queue")),ih=E(require("webdriverio"));ue();$e();B();j();Nr();nh();Uu();cs();Ht=x("WebDriverApi"),YE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},XE={implicit:0,pageLoad:1,script:2},Ci=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}async rejectWithLog(e,t){let{testName:r,testResultId:n}=this,o=t?t.toString().substr(0,2e3):"";throw Ht.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),za!==void 0&&(e=za);let t=1/0;this.queue=new oh.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(o){return this.rejectWithLog(o,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,i;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),M("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(Ce.GET_BROWSER);try{await this.addToQueue(async()=>{Ht.info("requesting browser",{testResultId:r,testName:t}),M("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await ih.remote(e),this.logGridStatus(r)}),M("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,Ce.GET_BROWSER)}}async logGridStatus(e){var i;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",o;try{o=await this.client.status();for(let a of o.nodes||[])for(let l of a.slots||[])if(((i=l==null?void 0:l.session)==null?void 0:i.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){Ht.info("grid status is not supported by the grid",{testResultId:e});return}Ht.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Ht.info("grid status",{gridStatusMsg:o.message,ready:o.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},o=()=>this.client.execute(e,t).catch(n),i=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return o();t=t.map(a=>{if(a===null){Ht.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await i()}catch(a){if(Fe(a))return this.unsupportedActions.add("execute"),o();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),o=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await o()}catch(i){if(Fe(i))return this.unsupportedActions.add("executeAsync"),n();throw i}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Ce.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,Ce.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Ce.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(De(e)))}finally{this.seleniumPerfStats.markEnd(t,Ce.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(Fu,{ELEMENT:e,[zt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Fe(n))return this.unsupportedActions.add("elementIdDisplayed"),r();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(sh(e,this.isSafari(),Ht))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let r=()=>{let o=[];return o[XE[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(o){if(Fe(o))return this.unsupportedActions.add("timeouts"),n();throw o}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,o){window.scrollTo(n,o)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(De(e)),await this.elementIdValue(De(e),t)}async getViewportSize(e){let t=await this.execute(YE);if(typeof e=="string"&&e.match(/(width|height)/)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(De(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let o=Math.abs(e.width),i=Math.abs(e.height);r=async()=>await this.client.setWindowSize(o,i),n=async()=>await this.client._setWindowSize(o,i)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(o){if(Fe(o))return this.unsupportedActions.add("windowHandleSize"),r();throw o}})}}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>{var l;return(l=this.client)==null?void 0:l.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){Ht.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return Ht.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var ch={};G(ch,{doubleClick:()=>QE});var QE,lh=w(()=>{"use strict";QE=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(u){function f(R,b,v){return v>R&&v<b}let h=u.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&f(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,T=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:T}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},c=function(u,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=i(u),h=u.event;return t.includes(h)?l(h,f.x,f.y):c(h,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var xn={};G(xn,{dispatchFocus:()=>ZE});function ZE(s,e){function t(o){let i=document.createEvent("HTMLEvents");return i.initEvent(o,!0,!1),i}function r(){var i;let o=document.activeElement;for(;(i=o.shadowRoot)!=null&&i.activeElement;)o=o.shadowRoot.activeElement;return o}function n(o,i){i&&(i.dispatchEvent(t("focusout")),i.dispatchEvent(t("blur"))),o.dispatchEvent(t("focusin")),o.dispatchEvent(t("focus")),typeof o.focus=="function"&&o.focus();let a=r();i&&a===i&&typeof i.blur=="function"&&i.blur()}if(s){let o=getLocatedElement(s);if(o&&o!==e)try{n(o,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var Cn=w(()=>{"use strict"});var fh={};G(fh,{WebDriver:()=>xr});async function sS(s){var e,t;try{let r=(t=(e=s==null?void 0:s.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return r?await tS(r):void 0}catch(r){Be.info("Error getting cdpAddress",r);return}}var us,dh,mh,Be,or,eS,uh,tS,ir,rS,ph,Ar,xr,Pn=w(()=>{"use strict";us=E(require("lodash"));B();$e();Mu();dh=E(require("p-retry")),mh=E(require("ua-parser-js"));Nr();j();Uu();ah();K();pe();cs();Be=x("webdriver"),[or,eS]=[0,2],{extractElementId:uh,getCdpAddressForHost:tS}=J,ir=()=>(Te(),ye(tr)).getSessionPlayer().codeSnippets,rS=()=>(Te(),ye(tr)).getSessionPlayer().locatorBuilderUtils,ph=()=>(Te(),ye(tr)).getSessionPlayer().utils,Ar=()=>(Te(),ye(tr)).getSessionPlayer().positionUtils;xr=class extends Ci{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var R,b,v,I,C,_,$,A;let{overrideConfiguration:r,browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f,printFinalCaps:h}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((v=(b=(R=n==null?void 0:n.company)==null?void 0:R.activePlan)==null?void 0:b.premiumFeatures)==null?void 0:v.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let g=xi({browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r,printFinalCaps:h});g.desiredCapabilities&&delete g.desiredCapabilities.marionette,g.capabilities&&delete g.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let y=u?0:1500,T=u?()=>null:()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let S=await this.initClient(g,o,d);M("after initResult before getCdpAddress in init"),this.cdpUrl=await sS(S),M("after getCdpAddress in webdriver.js init"),Be.info(`init new session testName: ${o}`,{sessionId:this.getSessionId(),testResultId:d}),await oe(y),D.flags.dontFocusOnInit.isEnabled()||await T(),M("after focus and delay in webdriver.js init")}catch(S){let L=JSON.stringify(us.omit(g,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Be.error("failed to init webdriver",{err:S,capabilitiesAsString:L});let U=((C=(I=n==null?void 0:n.company)==null?void 0:I.activePlan)==null?void 0:C.plan)==="free";throw(_=S.stack)!=null&&_.includes("at startWebDriverSession")&&(($=S.message)!=null&&$.startsWith("Failed to create session"))&&((A=S.message)!=null&&A.includes("Timeout awaiting 'request'"))&&U?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):S.message.match(/Invalid username or password/)?new Br(S.message):S.message.match(/capabilit(y|ies)/)?new oo(S.message):S.message.match(/403 Forbidden/)?new Error("Grid Access Denied"):S.message.match(/Browser_Version not supported/)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${S.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>us.zip(o.slice(0,-1),o.slice(1)),r=this._keepAliveRequests.map(({start:o})=>o).filter(Boolean),n=t(r).map(([o,i])=>i-o);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function o(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let i=se();r(i);try{await this.executeJS(o),this._isAlive=!0,n("end",i),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",i),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Be.warn("close unexpected alert open"),await this.alertAccept().catch(l=>Be.warn("failed to click on alert",{err:l}));return}if(Be.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;Be.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:l,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=l&&this.browserClosedCallbacks.forEach(c=>{try{c(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=uh(r.value);return await this.switchToFrame({ELEMENT:n,[zt]:n}),r}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new io:r}}async getElement(t){var o;let r=this.seleniumPerfStats.markStart(Ce.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,Ce.GET_ELEMENT)}if(((o=t==null?void 0:t.shadowPath)==null?void 0:o.length)||D.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
23
23
|
var fn = ${ir().getLocatedElementCode};
|
|
24
24
|
return fn.apply(null, arguments);
|
|
25
25
|
`,t)}finally{this.seleniumPerfStats.markEnd(r,Ce.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(r,Ce.GET_ELEMENT)}}executeJS(t,...r){return this.execute(t,...r)}async executeCodeAsync(t,r,...n){return await this.timeouts("script",r),await this.executeAsync(t,...n)}async markDynamicParent(t,r){function n({attributeName:o,attributeValue:i,locatedElement:a}){let l=getLocatedElement(a);if(!l)throw new Error("could not find dynamic parent");l.setAttribute(o,i)}await this.executeJS(`
|
|
@@ -214,7 +214,7 @@ When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they
|
|
|
214
214
|
});
|
|
215
215
|
})();
|
|
216
216
|
`,u=[],f=new bh.Worker(m,{eval:!0});try{return await ce(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:y}=g,T={...y,tstConsoleLogs:u};ct.debug("Run code worker response",{messageWithLogs:T,transactionId:s}),h(T)}else g.action==="progress"&&u.push(g.data)}).on("error",g=>{g.message==="malformed data: URI"?ct.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:i}):ct.error("Run code worker error",{err:g,transactionId:s}),h({tstConsoleLogs:u,status:"failed",result:{resultValue:g==null?void 0:g.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{ct.debug("Run code worker has been terminated",{transactionId:s})}),f.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),o)}catch(h){if(!(h instanceof ne))throw h;return ct.warn("timeout to run code",{transactionId:s,err:h}),{tstConsoleLogs:u,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{f==null||f.terminate()}}async function cS(s){try{await gh.promises.rm(s,{recursive:!0,force:!0})}catch(e){ct.warn("failed to remove install npm packages folder",{err:e})}}function Th(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function ds(s,e,t,r,n,o){let i=Th(n,e,s,t),{data:a}=await lS(i,r,o);return a}async function ms(s,e,t,r,n,o,i,a,l,c){var g;let d=r.computePackagePathFromPackageJsonExports||D.flags.computePackagePathFromPackageJsonExports.isEnabled(),m=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(d){let T=Tm(y.testimPackageLocalLocation);return[y.paramName,ps.join(y.testimPackageLocalLocation,T)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=Th(i,n,e,o);if(c){let y=await on(c);y&&(l=y)}Buffer.isBuffer(l)&&(ct.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:l}),l=l.toString());let f="data:,";return l==="data:"&&(ct.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:l}),l=f),{...await aS(u,t,r,s,m,a,l),nodeVersion:process.version}}async function lS(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=wh(),i=D.flags.reuseCliPkgInstallFolder.isEnabled()?n:ps.join(n,`/${s}`),a=global.proxyUri;async function l(){let c="";try{if(c=await wm(i,r,a,t),ct.info("npm package install finished",{transactionId:s,output:c,timeout:t}),Number(c.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(m=>{let u=ym(i,m.packageName);return{...m,packageFullName:`${m.packageName}@${u}`,packageLocalLocation:ps.resolve(i,"node_modules",m.packageName)}}),installFolder:i}}catch(d){throw ct.warn("npm package install failed",{transactionId:s,err:d}),d}}try{return await ce(l(),t)}catch(c){throw c instanceof ne&&ct.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function wh(){return ps.join(hh.tmpdir(),"/testim_local_packages")}function uS(){let s=wh();return cS(s)}var gh,hh,ps,yh,bh,ct,fs=w(()=>{"use strict";gh=E(require("fs")),hh=E(require("os")),ps=E(require("path"));B();Yr();yh=E(require("data-uri-to-buffer")),bh=require("worker_threads");K();j();he();Yr();pe();ct=x("cli-service");uS().catch(s=>ct.warn("failed to clean local package folder",{err:s}))});var ar={};G(ar,{run:()=>dS});function pS(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=D.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var dS,vh=w(()=>{"use strict";fs();K();pe();dS=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:o,context:i,testResultId:a,retryIndex:l,stepResultId:c,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let f=await ms(r,n,o,i,a,l,c,d,m,u);return f&&pS({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof ne?new Error("Timeout while running action"):f}}});var Wu={};G(Wu,{run:()=>mS});var mS,Eh=w(()=>{"use strict";fs();K();mS=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:o,packageData:i,timeout:a}=e.data;try{return{data:await ds(t,r,n,i,o,a),success:!0}}catch(l){if(l instanceof At)return{success:!1,code:"invalid-node-package",message:l.message};if(l instanceof ne)return{success:!1,code:"timeout"};throw l}}});async function Ih(s,e,t,r){try{return await hl(s,e,t,r)}catch{ki.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function gS(s,e,t,r,n){return ki.info("finished to run remote step",{stepId:t,sessionId:n}),await Ih(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function Sh(s,e,t,r,n){return ki.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await Ih(s,e,t,{status:"completed",success:!1,failureReason:r})}async function Rh(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:o}=s,i=t.type,a=e.getSessionId(),l=t.id;ki.info("start play remote step",{stepType:i,stepId:l,sessionId:a});let c=fS[i];if(!c)return await Sh(n,r,l,`Failed to find step type ${i}`,a);try{let d=await c.run(e,t,o);return await gS(n,r,l,d,a)}catch(d){return await Sh(n,r,l,d.message,a)}}var ki,fS,Ah=w(()=>{"use strict";vh();he();Eh();j();ki=x("step-playback"),fS={"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":ar,"cli-download-code-step":ar,"node-package":Wu}});var Vu,xh,Cr,yS,Gu,vt,_i=w(()=>{"use strict";B();nt();Vu=E(require("ws")),xh=require("events");j();ue();Cr=x("socket-service"),yS=5e3,Gu=class extends xh.EventEmitter{constructor(){super(...arguments);this.clientId=se();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Cr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),yS)}formatUrl(t){return t.startsWith("http://")?t.replace("http://","ws://"):t.startsWith("https://")?t.replace("https://","wss://"):t}parseEvent(t){try{return JSON.parse(t)}catch(r){Cr.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(rd);return Zt().then(n=>new Promise(o=>{let i={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new Vu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,i),this.ws.on("open",()=>{var a;return Cr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),o()}),this.ws.on("close",a=>{Cr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===Vu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Cr.info("websocket error",{event:a})}),this.ws.on("message",a=>{let l=this.parseEvent(a);l!=null&&l.type&&this.emit(l.type,l.data)})}))}sendMessage(t){if(!this.ws){Cr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Cr.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,n){let o=i=>{r(i)&&(n(i),this.removeListener(t,o))};this.on(t,o)}listenTo(t,r,n,o){function i(l){n(l)&&o(l)}(Array.isArray(r)?r:[r]).forEach(l=>{this.listeners[`${t}:${l}`]||=[];let c=i.bind(this);this.listeners[`${t}:${l}`].push(c),this.on(l,c)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,o=!1){return new Promise(i=>{let a=se(),l={query:r,id:a,type:n,fullDocument:o};this.listenOnce("add-filter:done",c=>c.id===a,i),this.sendMessage({type:"add-filter",filter:l}),this.filterMap[t]=l})}removeListeners(t,r){Object.keys(this.listeners).length!==0&&r.forEach(n=>{let o=this.listeners[`${t}:${n}`];o&&(delete this.listeners[`${t}:${n}`],o.forEach(i=>this.removeListener(n,i)))})}removeFilter(t,r){let n=this.filterMap[t];if(!n)return;let o=Array.isArray(r)?r:[r];this.removeListeners(t,o),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},vt=new Gu});var Ph,Hu,bS,TS,wS,Ch,Oi,gs,qu=w(()=>{"use strict";Ph=E(require("p-retry")),Hu=E(require("socket.io-client"));ue();B();j();bS=50,TS=10,wS=5e3,Ch=10*1e3,Oi=x("base socket service"),gs=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Oi.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let r=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,r)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,r)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}Oi.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${r==null?void 0:r.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===TS&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=bS)throw new Error(`Can't connect to Testim Servers.
|
|
217
|
-
Action required: Please allow opening a websockets connection to ${fe} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{Oi.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let r={query:{projectId:e},requestTimeout:Ch,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${fe}/${t}`,this._socket=Hu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:Ch,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${fe}/${t}`,this._socket=Hu.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((o,i)=>{this._socket.emit(e,t,a=>a!=null&&a.success?o():(r[e]=t,i(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,Ph.default)(()=>ce(n(),wS),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Oi.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var kh={};G(kh,{remoteStepServiceSocketIO:()=>vS});var zu,vS,_h=w(()=>{"use strict";qu();zu=class extends gs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},vS=new zu});var Oh={};G(Oh,{remoteStepService:()=>hs});var Ku,_n,Ju,hs,Li=w(()=>{"use strict";_i();ae();pe();({REMOTE_STEP_SAVED:Ku}=Ct),Ju=class{async init(e){D.flags.useNewWSCLI.isEnabled()||(_n=(await Promise.resolve().then(()=>(_h(),kh))).remoteStepServiceSocketIO,_n.init(e))}joinToRemoteStep(e){return D.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:remoteStep`,{resultId:e},[Ku]):_n.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(D.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:remoteStep`,[Ku],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}_n.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return D.flags.useNewWSCLI.isEnabled()?(vt.removeFilter(`${e}:remoteStep`,[Ku]),Promise.resolve()):_n.unlistenToRemoteStep(e)}},hs=new Ju});var Yu,Pr,Lh=w(()=>{"use strict";qu();Yu=class extends gs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=o=>{o.resultId===t&&o.testId===r&&n(o.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Pr=new Yu});var Nh={};G(Nh,{testResultService:()=>Ot});var Dh,Xu,Ot,Di=w(()=>{"use strict";Dh=require("events");_i();ae();pe();Lh();Xu=class extends Dh.EventEmitter{init(e){if(D.flags.useNewWSCLI.isEnabled()){vt.onConnect=()=>this.emit("socket-connected");return}Pr.init(e),Pr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return D.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED]):Pr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(D.flags.useNewWSCLI.isEnabled()){vt.removeFilter(`${e}:testResult`,[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED]);return}await Pr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(D.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:testResult`,[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Pr.listenToTestResult(e,t,r)}getSocket(){if(!D.flags.useNewWSCLI.isEnabled())return Pr.getSocket()}},Ot=new Xu});var Uh,Fh,Bh,Ee,ES,jh,Mh,Ni,$h=w(()=>{"use strict";Uh=E(require("lodash"));B();ue();$e();ts();nt();he();Ah();Fh=E(require("p-retry")),Bh=require("url");j();Qo();cs();ae();Li();Di();Ee=x("test-run-handler"),ES=3,jh=20*1e3,Mh=s=>JSON.stringify(s).length<jh,Ni=class{constructor(e,t,r,n,o,i){this._executionId=e;this._executionName=t;this._options=n;this._branch=o;this._testRunStatus=i;this.seleniumPerfStats=new Ir;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this._seleniumHubRetryCount=2;this.clearTestResultFinished=Promise.resolve(void 0);var l,c;this._testStatus=r.testStatus,this._testId=r.testId,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(l=r.overrideTestConfig)==null?void 0:l.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((c=r.runConfig)!=null&&c.isMobileWeb)&&n.browser;this._runConfig=a?qs(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,o,i,a;return this.isAppFromDevice?null:r?(o=(n=r.gridData)==null?void 0:n[e])==null?void 0:o[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(i=this._nativeApp.gridData)==null?void 0:i[e])==null?void 0:a[t]:null}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return Gs(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Wr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?po.FROM_DEVICE:po.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${fe}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}set nativeApp(e){this._nativeApp=e}get nativeAppMetadata(){return this._nativeApp?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var r,n;let t={tokenV3:await Zt(),refreshToken:Lo(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:ld,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,storageBaseUrl:this._options.company.storageBaseUrl,storageType:this._options.company.storageType,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential},userAccessKey:await Do()};if(this._options.disableMockNetwork&&Tt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=Mh(o);Object.assign(t.lightweightMode,{isRunDataSentInUrl:i});let a=JSON.stringify(o).length,l=this.testId;i?(Object.assign(t,{runData:o}),Ee.info(`Run data sent as URL param, test id: ${l} run data length: ${a}`)):Ee.warn(`Run data is too big to be sent as a URL param. Test id: ${l}, run data size: ${a} (limit: ${jh} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let o=await fn(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 Ee.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var o;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((o=this._options.lightweightMode)!=null&&o.disableResults&&!t&&Mh(e))return;let r=async()=>{try{return await yl(this._options.project,this._testId,this._testResultId,e)}catch(i){return Ee.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),gl(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:i,runData:i?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}decreaseSeleniumHubRetry(){this._seleniumHubRetryCount-=1}get ignoreSeleniumHubError(){return this._seleniumHubRetryCount===0}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){M("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=["Testim Editor","Tricentis Testim Editor"],{targetId:n}=t.find(i=>i.type==="background_page"&&r.includes(i.title))||{},{targetId:o}=t.find(i=>i.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!o)throw new Error("AUT target not found");try{M("before Target.attachToTarget");let[i,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:l}=i||{};M("before Runtime.evaluate"),await(0,Fh.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},l);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),M("after wait for runTestimTest function");let{result:c}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},l);if(c.subtype==="error")throw new Error(c.description);return M("after Runtime.evaluate"),c.value}catch(i){throw Ee.error("error running test using CDP",{err:i}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new Bh.URL(e)}catch{return}let{username:n,password:o}=r;if(n||o)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=o=>{if(!r){if(this.isRetryKeyMismatch(o)){Ee.warn(`ignoring result update for on started due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(o.status)&&(o.resultId=this.testResultId,o.status==="completed"&&!this.isSeleniumHubNoMatchSessionError(o.reason)&&(Ee.info("setting _wasCompletedOnStartedCheck to true",{testResult:o,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=o),r=!0,t(o))}};if(this._options.disableSockets){let o=Date.now()+e,i=async()=>{if(Date.now()>o)return;let{testId:a,testResultId:l,branch:c,_options:{project:d}}=this;try{let m=await Er(a,l,d,c);n(m),r||setTimeout(i,3e3)}catch(m){Ee.error("failed to check if done",{err:m}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else Ot.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let o=await Er(e,t,r,n),i=["running","completed"];if(i.includes(o.status))return Ee.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw Ee.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}catch(o){throw Ee.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Ot.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Ee.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Ot.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){Ee.warn(`ignoring result update for on completed due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}i.status==="completed"&&(i.resultId=this._testResultId,r(i))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),o=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Uh.debounce(async()=>{try{let i=await Er(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(Ee.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"?(Ee.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),i.resultId=this._testResultId,r(i),!0):!1}catch(i){return Ee.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)Ot.on("socket-connected",async()=>{try{await Ot.joinToTestResult(this._testResultId,this.testId)}catch(i){Ee.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 ol(this._testResultId,this._options.project,this.retryKey);a?await e()||(Ee.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){Ee.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Ot.off("socket-connected",e)}}listenToRemoteStep(e){hs.listenToRemoteStep(this.testResultId,t=>{Rh(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:ES;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=se(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Mi,Wh=w(()=>{"use strict";$h();Mi=class{constructor(e,t,r,n,o,i){this.pendingAppUploads=new Map;let a=new Set(r.map(l=>{var c;return(c=l.nativeApp)==null?void 0:c.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(l=>{this.pendingAppUploads.set(l,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(l=>new Ni(e,t,l,n,o,i))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var SS,IS,RS,On,Qu=w(()=>{"use strict";ns();is();j();SS=x("worker-utils"),IS=async(s,e,t)=>{e&&await iu(s,t)},RS=async(s,e,t)=>{await au(s,e,t)},On=async(s,e,t,r,n,o)=>{SS.info("releasing player",{hasPlayer:Boolean(o)});try{await(o==null?void 0:o.onDone())}finally{n==="mongo"&&await IS(s,e,t),n==="redis"&&await RS(s,r,t)}}});function _S(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Bi,Hh,Fi,tp,qh,Et,Vh,Gh,Zu,Ln,AS,ep,xS,cr,CS,Ui,PS,kS,OS,lt,Dn=w(()=>{"use strict";Bi=E(require("ms")),Hh=E(require("lodash")),Fi=E(require("p-retry")),tp=E(require("dayjs")),qh=E(require("dayjs/plugin/duration"));B();$e();ns();is();he();j();Qu();_t();ni();pe();Li();Di();Ge();ae();K();tp.default.extend(qh.default);Et=x("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Vh,TEST_START_TIMEOUT_MSG:Gh,TEST_COMPLETE_TIMEOUT_MSG:Zu}=Ue,{SETUP_TIMEOUT:Ln,NETWORK_ERROR:AS,GRID_ERROR:ep,BROWSER_CLOSED:xS,SELENIUM_ERROR:cr,UNKNOWN_ERROR:CS,MOBILE_SESSION_ERROR:Ui}=$s,PS=(0,Bi.default)("1s"),kS=1;OS=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],lt=class{constructor(e,t,r,n,o,i,a,l,c=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=l;this.releaseSlotOnTestFinished=c;this.id=lt.getWorkerId();this.lambdatestService=new re;this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}static getWorkerId(){return kS++}async getGridSlot(e,t){let r=await ig(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Ds(!0)}async getBrowserOnce(e,t,r,n){throw new Ds(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),Et.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!Xe({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,o;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Vr(D,(o=this.options.gridData)==null?void 0:o.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let i={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,i),i}}setSessionTimeout(){var e;return this.options.mode===Z.APPIUM?((e=this.options.gridData)==null?void 0:e.type)===O.BROWSERSTACK?Math.max((0,Bi.default)("600s"),this.options.getSessionTimeout):Math.max((0,Bi.default)("180s"),this.options.getSessionTimeout):Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,Fi.default)(async()=>{let n=Date.now();try{return await ce(this.getSlotOnce(e),this.options.getBrowserTimeout,Ue.GET_BROWSER_TIMEOUT_MSG)}catch(o){return t++,await this.handleGetSlotError(o,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,Fi.default)(async()=>{var n,o;let r=Date.now();try{let i=(n=this.options.company)==null?void 0:n.companyId,a=(o=this.options.projectData)==null?void 0:o.projectId;return await ce(ug(i,a,this.id),this.options.getBrowserTimeout,Ue.GET_BROWSER_TIMEOUT_MSG)}catch(i){return e++,await this.handleGetSlotError(i,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof Jt?Et.info("could not get grid slot due to concurrency issue",r):Et.error("error getting grid slot",{error:e,...r}),await oe(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var o;let r=(o=this.userData)==null?void 0:o.projectId,n;try{M("before getSlotOnce retries");let{failedAttemptsCount:i,gridInfo:a={}}=await this.handleGetSlot(e);M("before getBrowserOnce retries");let l=this.options.getBrowserRetries-i;if(!l)throw new Error("No free browser slots in desired grid");let c=0;n=await(0,Fi.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await ag(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:l,currentRetry:c+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=c;let f=this.setSessionTimeout();M("before getBrowserOnce");let h=await ce(this.getBrowserOnce(e,t,m,u),f,Ue.GET_BROWSER_TIMEOUT_MSG);return M("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),m||h}catch(u){let f={...a,failedGetBrowserAttempts:c,id:this.options.gridData.gridId},h=this.options.mode===Z.APPIUM?"device":"browser";throw Et.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f}),Q.onGetBrowserFailure(this.id,r,++c),m.onDone(),!(u instanceof Rt)&&this.options.mode!==Z.APPIUM&&await oe(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:l-1,minTimeout:0,factor:1}),M("after getBrowserOnce retries")}catch(i){throw await On(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[Rt,Br].some(a=>i instanceof a)?i:i instanceof ze?new fr(i,ep):new fr(i,cr)}return n}async runTest(e,t,r){var d;M("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,o=this.handleQuarantine(e);if(o)return o;let i=Hs(this.options)&&this.handleMobileTest(e);if(i)return i;M("before runTest onTestStarted");let a=e.getAppSource,l=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=l.config.baseUrl;let c=await this.getTestPlayer(e,t);try{return await this.runTestOnce(e,c)}finally{await On(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,c)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var u,f;let e=()=>process.nextTick(()=>this.run()),t=async(h,g,y)=>{var L,U,q;if(Xe(h,this.options)||Vr(D,(L=this.options.gridData)==null?void 0:L.type)&&g.isAppFromDevice&&!this.options.appId||g.isAppForIosVirtualDevice)return e();let T=g.sessionId,R=H=>y==null?void 0:y.message.includes(H),b=y&&y instanceof fr,v=y&&(R(Gh)||R(Zu)),_=D.flags.retryOnSeleniumHubError.isEnabled()&&!!h.reason&&g.isSeleniumHubNoMatchSessionError(h.reason)&&!g.ignoreSeleniumHubError,$=v&&g.hasMoreTimeoutRetries(),A=g.hasMoreRetries()&&!b&&!v,S=!h.success&&(A||$||_);try{let H=g.retryKey;h.testRetryKey=H;let Y=g.getAppSource;if(await this.onTestCompleted(this.id,this.testId,h,T,S,Y),this.executionQueue.hasMoreTests()&&!((U=this.options.lightweightMode)!=null&&U.general)&&await oe(PS),await this.runTestCleanup(),S){if($&&await g.startNewTimeoutRetry(),_){Et.info(`retry test id: ${this.testId} name: ${this.testName} again due to selenium hub error`,{testId:g.testId,retryReason:h.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId});let me=(q=this.options.projectData)==null?void 0:q.projectId,pt=g.testResultId,It=g.testId;await jo(me,pt,It,{show:!1}),g.decreaseSeleniumHubRetry(),g.decreaseRetryCount(),await g.startNewRetry()}return A&&!_&&!$&&await g.startNewRetry(),Et.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:v,testRetryKey:H,totalRetries:g._totalRetryCount}),this.testResultId=g.testResultId,await d(g,S)}return await e()}catch(H){if(H instanceof Kt)return;Et.error("failed to process test result",{error:H}),e();return}},r=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
217
|
+
Action required: Please allow opening a websockets connection to ${fe} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{Oi.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let r={query:{projectId:e},requestTimeout:Ch,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${fe}/${t}`,this._socket=Hu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:Ch,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${fe}/${t}`,this._socket=Hu.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((o,i)=>{this._socket.emit(e,t,a=>a!=null&&a.success?o():(r[e]=t,i(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,Ph.default)(()=>ce(n(),wS),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Oi.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var kh={};G(kh,{remoteStepServiceSocketIO:()=>vS});var zu,vS,_h=w(()=>{"use strict";qu();zu=class extends gs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},vS=new zu});var Oh={};G(Oh,{remoteStepService:()=>hs});var Ku,_n,Ju,hs,Li=w(()=>{"use strict";_i();ae();pe();({REMOTE_STEP_SAVED:Ku}=Ct),Ju=class{async init(e){D.flags.useNewWSCLI.isEnabled()||(_n=(await Promise.resolve().then(()=>(_h(),kh))).remoteStepServiceSocketIO,_n.init(e))}joinToRemoteStep(e){return D.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:remoteStep`,{resultId:e},[Ku]):_n.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(D.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:remoteStep`,[Ku],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}_n.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return D.flags.useNewWSCLI.isEnabled()?(vt.removeFilter(`${e}:remoteStep`,[Ku]),Promise.resolve()):_n.unlistenToRemoteStep(e)}},hs=new Ju});var Yu,Pr,Lh=w(()=>{"use strict";qu();Yu=class extends gs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=o=>{o.resultId===t&&o.testId===r&&n(o.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Pr=new Yu});var Nh={};G(Nh,{testResultService:()=>Ot});var Dh,Xu,Ot,Di=w(()=>{"use strict";Dh=require("events");_i();ae();pe();Lh();Xu=class extends Dh.EventEmitter{init(e){if(D.flags.useNewWSCLI.isEnabled()){vt.onConnect=()=>this.emit("socket-connected");return}Pr.init(e),Pr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return D.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED]):Pr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(D.flags.useNewWSCLI.isEnabled()){vt.removeFilter(`${e}:testResult`,[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED]);return}await Pr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(D.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:testResult`,[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Pr.listenToTestResult(e,t,r)}getSocket(){if(!D.flags.useNewWSCLI.isEnabled())return Pr.getSocket()}},Ot=new Xu});var Uh,Fh,Bh,Ee,ES,jh,Mh,Ni,$h=w(()=>{"use strict";Uh=E(require("lodash"));B();ue();$e();ts();nt();he();Ah();Fh=E(require("p-retry")),Bh=require("url");j();Qo();cs();ae();Li();Di();Ee=x("test-run-handler"),ES=3,jh=20*1e3,Mh=s=>JSON.stringify(s).length<jh,Ni=class{constructor(e,t,r,n,o,i){this._executionId=e;this._executionName=t;this._options=n;this._branch=o;this._testRunStatus=i;this.seleniumPerfStats=new Ir;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this._seleniumHubRetryCount=2;this.clearTestResultFinished=Promise.resolve(void 0);var l,c;this._testStatus=r.testStatus,this._testId=r.testId,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(l=r.overrideTestConfig)==null?void 0:l.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((c=r.runConfig)!=null&&c.isMobileWeb)&&n.browser;this._runConfig=a?qs(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,o,i,a;return this.isAppFromDevice?null:r?(o=(n=r.gridData)==null?void 0:n[e])==null?void 0:o[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(i=this._nativeApp.gridData)==null?void 0:i[e])==null?void 0:a[t]:null}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return Gs(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Wr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?po.FROM_DEVICE:po.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${fe}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}set nativeApp(e){this._nativeApp=e}get nativeAppMetadata(){return this._nativeApp?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var r,n;let t={tokenV3:await Zt(),refreshToken:Lo(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:ld,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,storageBaseUrl:this._options.company.storageBaseUrl,storageType:this._options.company.storageType,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential},userAccessKey:await Do()};if(this._options.disableMockNetwork&&Tt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=Mh(o);Object.assign(t.lightweightMode,{isRunDataSentInUrl:i});let a=JSON.stringify(o).length,l=this.testId;i?(Object.assign(t,{runData:o}),Ee.info(`Run data sent as URL param, test id: ${l} run data length: ${a}`)):Ee.warn(`Run data is too big to be sent as a URL param. Test id: ${l}, run data size: ${a} (limit: ${jh} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let o=await fn(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 Ee.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var o;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((o=this._options.lightweightMode)!=null&&o.disableResults&&!t&&Mh(e))return;let r=async()=>{try{return await yl(this._options.project,this._testId,this._testResultId,e)}catch(i){return Ee.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),gl(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:i,runData:i?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}decreaseSeleniumHubRetry(){this._seleniumHubRetryCount-=1}get ignoreSeleniumHubError(){return this._seleniumHubRetryCount===0}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){M("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=["Testim Editor","Tricentis Testim Editor"],{targetId:n}=t.find(i=>i.type==="background_page"&&r.includes(i.title))||{},{targetId:o}=t.find(i=>i.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!o)throw new Error("AUT target not found");try{M("before Target.attachToTarget");let[i,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:l}=i||{};M("before Runtime.evaluate"),await(0,Fh.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},l);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),M("after wait for runTestimTest function");let{result:c}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},l);if(c.subtype==="error")throw new Error(c.description);return M("after Runtime.evaluate"),c.value}catch(i){throw Ee.error("error running test using CDP",{err:i}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new Bh.URL(e)}catch{return}let{username:n,password:o}=r;if(n||o)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=o=>{if(!r){if(this.isRetryKeyMismatch(o)){Ee.warn(`ignoring result update for on started due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(o.status)&&(o.resultId=this.testResultId,o.status==="completed"&&!this.isSeleniumHubNoMatchSessionError(o.reason)&&(Ee.info("setting _wasCompletedOnStartedCheck to true",{testResult:o,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=o),r=!0,t(o))}};if(this._options.disableSockets){let o=Date.now()+e,i=async()=>{if(Date.now()>o)return;let{testId:a,testResultId:l,branch:c,_options:{project:d}}=this;try{let m=await Er(a,l,d,c);n(m),r||setTimeout(i,3e3)}catch(m){Ee.error("failed to check if done",{err:m}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else Ot.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let o=await Er(e,t,r,n),i=["running","completed"];if(i.includes(o.status))return Ee.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw Ee.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}catch(o){throw Ee.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Ot.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Ee.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Ot.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){Ee.warn(`ignoring result update for on completed due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}i.status==="completed"&&(i.resultId=this._testResultId,r(i))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),o=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Uh.debounce(async()=>{try{let i=await Er(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(Ee.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"?(Ee.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),i.resultId=this._testResultId,r(i),!0):!1}catch(i){return Ee.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)Ot.on("socket-connected",async()=>{try{await Ot.joinToTestResult(this._testResultId,this.testId)}catch(i){Ee.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 ol(this._testResultId,this._options.project,this.retryKey);a?await e()||(Ee.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){Ee.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Ot.off("socket-connected",e)}}listenToRemoteStep(e){hs.listenToRemoteStep(this.testResultId,t=>{Rh(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:ES;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=se(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Mi,Wh=w(()=>{"use strict";$h();Mi=class{constructor(e,t,r,n,o,i){this.pendingAppUploads=new Map;let a=new Set(r.map(l=>{var c;return(c=l.nativeApp)==null?void 0:c.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(l=>{this.pendingAppUploads.set(l,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(l=>new Ni(e,t,l,n,o,i))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var SS,IS,RS,On,Qu=w(()=>{"use strict";ns();is();j();SS=x("worker-utils"),IS=async(s,e,t)=>{e&&await iu(s,t)},RS=async(s,e,t)=>{await au(s,e,t)},On=async(s,e,t,r,n,o)=>{SS.info("releasing player",{hasPlayer:Boolean(o)});try{await(o==null?void 0:o.onDone())}finally{n==="mongo"&&await IS(s,e,t),n==="redis"&&await RS(s,r,t)}}});function _S(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Bi,Hh,Fi,tp,qh,Et,Vh,Gh,Zu,Ln,AS,ep,xS,cr,CS,Ui,PS,kS,OS,lt,Dn=w(()=>{"use strict";Bi=E(require("ms")),Hh=E(require("lodash")),Fi=E(require("p-retry")),tp=E(require("dayjs")),qh=E(require("dayjs/plugin/duration"));B();$e();ns();is();he();j();Qu();_t();ni();pe();Li();Di();Ge();ae();K();tp.default.extend(qh.default);Et=x("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Vh,TEST_START_TIMEOUT_MSG:Gh,TEST_COMPLETE_TIMEOUT_MSG:Zu}=Ue,{SETUP_TIMEOUT:Ln,NETWORK_ERROR:AS,GRID_ERROR:ep,BROWSER_CLOSED:xS,SELENIUM_ERROR:cr,UNKNOWN_ERROR:CS,MOBILE_SESSION_ERROR:Ui}=$s,PS=(0,Bi.default)("1s"),kS=1;OS=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],lt=class{constructor(e,t,r,n,o,i,a,l,c=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=l;this.releaseSlotOnTestFinished=c;this.id=lt.getWorkerId();this.lambdatestService=new re;this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}static getWorkerId(){return kS++}async getGridSlot(e,t){let r=await ig(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Ds(!0)}async getBrowserOnce(e,t,r,n){throw new Ds(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),Et.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!Xe({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,o;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Vr(D,(o=this.options.gridData)==null?void 0:o.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let i={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,i),i}}setSessionTimeout(){var e;return this.options.mode===Z.APPIUM?((e=this.options.gridData)==null?void 0:e.type)===O.BROWSERSTACK?Math.max((0,Bi.default)("600s"),this.options.getSessionTimeout):Math.max((0,Bi.default)("180s"),this.options.getSessionTimeout):Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,Fi.default)(async()=>{let n=Date.now();try{return await ce(this.getSlotOnce(e),this.options.getBrowserTimeout,Ue.GET_BROWSER_TIMEOUT_MSG)}catch(o){return t++,await this.handleGetSlotError(o,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,Fi.default)(async()=>{var n,o;let r=Date.now();try{let i=(n=this.options.company)==null?void 0:n.companyId,a=(o=this.options.projectData)==null?void 0:o.projectId;return await ce(ug(i,a,this.id),this.options.getBrowserTimeout,Ue.GET_BROWSER_TIMEOUT_MSG)}catch(i){return e++,await this.handleGetSlotError(i,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof Jt?Et.info("could not get grid slot due to concurrency issue",r):Et.error("error getting grid slot",{error:e,...r}),await oe(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var o;let r=(o=this.userData)==null?void 0:o.projectId,n;try{M("before getSlotOnce retries");let{failedAttemptsCount:i,gridInfo:a={}}=await this.handleGetSlot(e);M("before getBrowserOnce retries");let l=this.options.getBrowserRetries-i;if(!l)throw new Error("No free browser slots in desired grid");let c=0;n=await(0,Fi.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await ag(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:l,currentRetry:c+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=c;let f=this.setSessionTimeout();M("before getBrowserOnce");let h=await ce(this.getBrowserOnce(e,t,m,u),f,Ue.GET_BROWSER_TIMEOUT_MSG);return M("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),m||h}catch(u){let f={...a,failedGetBrowserAttempts:c,id:this.options.gridData.gridId},h=this.options.mode===Z.APPIUM?"device":"browser";throw Et.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Q.onGetBrowserFailure(this.id,r,++c),m.onDone(),!(u instanceof Rt)&&this.options.mode!==Z.APPIUM&&await oe(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:l-1,minTimeout:0,factor:1}),M("after getBrowserOnce retries")}catch(i){throw await On(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[Rt,Br].some(a=>i instanceof a)?i:i instanceof ze?new fr(i,ep):new fr(i,cr)}return n}async runTest(e,t,r){var d;M("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,o=this.handleQuarantine(e);if(o)return o;let i=Hs(this.options)&&this.handleMobileTest(e);if(i)return i;M("before runTest onTestStarted");let a=e.getAppSource,l=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=l.config.baseUrl;let c=await this.getTestPlayer(e,t);try{return await this.runTestOnce(e,c)}finally{await On(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,c)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var u,f;let e=()=>process.nextTick(()=>this.run()),t=async(h,g,y)=>{var L,U,q;if(Xe(h,this.options)||Vr(D,(L=this.options.gridData)==null?void 0:L.type)&&g.isAppFromDevice&&!this.options.appId||g.isAppForIosVirtualDevice)return e();let T=g.sessionId,R=H=>y==null?void 0:y.message.includes(H),b=y&&y instanceof fr,v=y&&(R(Gh)||R(Zu)),_=D.flags.retryOnSeleniumHubError.isEnabled()&&!!h.reason&&g.isSeleniumHubNoMatchSessionError(h.reason)&&!g.ignoreSeleniumHubError,$=v&&g.hasMoreTimeoutRetries(),A=g.hasMoreRetries()&&!b&&!v,S=!h.success&&(A||$||_);try{let H=g.retryKey;h.testRetryKey=H;let Y=g.getAppSource;if(await this.onTestCompleted(this.id,this.testId,h,T,S,Y),this.executionQueue.hasMoreTests()&&!((U=this.options.lightweightMode)!=null&&U.general)&&await oe(PS),await this.runTestCleanup(),S){if($&&await g.startNewTimeoutRetry(),_){Et.info(`retry test id: ${this.testId} name: ${this.testName} again due to selenium hub error`,{testId:g.testId,retryReason:h.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId});let me=(q=this.options.projectData)==null?void 0:q.projectId,pt=g.testResultId,It=g.testId;await jo(me,pt,It,{show:!1}),g.decreaseSeleniumHubRetry(),g.decreaseRetryCount(),await g.startNewRetry()}return A&&!_&&!$&&await g.startNewRetry(),Et.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:v,testRetryKey:H,totalRetries:g._totalRetryCount}),this.testResultId=g.testResultId,await d(g,S)}return await e()}catch(H){if(H instanceof Kt)return;Et.error("failed to process test result",{error:H}),e();return}},r=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
218
218
|
Please make sure the CLI has stable access to the internet. ${fc()?"(Internal: network connectivity test failed)":""}`,n=h=>{let{DEVICE_OS_VERSION_TOO_LOW:g,APP_NOT_EXIST_ON_DEVICE:y,APP_NEVER_STARTED:T,TIMEOUT_ERROR:R,SAUCELABS_APP_IS_NOT_INSTALLED:b}=vc,v=h instanceof Error?h.message:h;return v.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),v.includes(Vh)||v.includes(R)?{errorType:Ln,reason:"timeout while getting device"}:v.includes(y)||v.includes(b)?{errorType:Ui,reason:"app doesn't exist on device"}:v.includes(T)?{errorType:Ui,reason:"app never started, check app permission or app activity"}:v.includes(g)?{errorType:Ui,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Ui,reason:v}},o=(h,g)=>{let y=this.options.mode===Z.APPIUM?"device":"browser";if(!g&&D.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:AS,reason:r()};let T=h instanceof Error?h.message:h;if(T.includes(Vh))return{errorType:Ln,reason:`Test couldn't get ${y}`};if(T.includes(Gh))return{errorType:Ln,reason:"Test couldn't be started"};if(T.includes(Zu)){if(!this.testRunTimeout)return{errorType:Ln,reason:"Test timeout reached: test is too long"};let R=tp.default.duration({milliseconds:this.testRunTimeout}),b=Math.floor(R.asMinutes()),v=R.asSeconds(),I=b>0?` ${b} min`:"",C=v>0?` ${v} sec`:"";return{errorType:Ln,reason:`Test timeout reached (timeout:${I}${C}): test is too long`}}if(h instanceof fr&&h.type){if(h.type===ep)return{errorType:ep,reason:`Test couldn't get ${y} from grid - ${h.message}`};if(h.type===cr)return{errorType:cr,reason:`Failed to create new session - ${h.message}`}}return"type"in h&&h.type===xS?{errorType:cr,reason:`Session terminated, this is often caused to connection
|
|
219
219
|
problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(h.message)||/Couldn't connect to selenium server/.test(h.message)?{errorType:cr,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(h.message)?{errorType:cr,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(h.message)?{errorType:cr,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(h.message)?{errorType:cr,reason:`Session could not be created, please check that the ${y} you requested is supported in your plan`}:{errorType:CS,reason:T}},i=async(h,g)=>{var v;let y=await mc();!y&&D.flags.warnOnBadNetwork.isEnabled()&&console.warn(r()),Et.warn("error on run",{err:h});let T=(v=this.userData)==null?void 0:v.projectId,{errorType:R,reason:b}=this.options.mode===Z.APPIUM?n(h):o(h,y);jo(T,this.testResultId,this.testId,{status:js.COMPLETED,success:!1,reason:b,errorType:R,testRetryKey:g.retryKey,setupStepResult:{status:js.COMPLETED,success:!1,reason:b,errorType:R}},g.remoteRunId),await t(_S(this.testId,this.testName,this.testResultId,b),g,h)},a=async(h,g)=>{var v;let y=this.testId,T=this.testResultId,R=(v=this.userData)==null?void 0:v.projectId,b=this.branch;if(!y||!T||!R||!b)return Et.warn("Test failed. Not enough data to recover results via API",{err:h}),i(h,g);try{let I=await Er(y,T,R,b);if(Et.warn("Test failed. Got results via API",{err:h,testResult:Hh.default.omit(I,OS),resultId:T}),I&&I.status===js.COMPLETED&&!h.message.includes(Zu))return await t(I,g);throw h}catch(I){return I!==h&&Et.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:R,branch:b,err:I}),i(h,g)}},l=this.options.disableSockets||((u=this.options.lightweightMode)==null?void 0:u.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),c=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep),d=async(h,g)=>{try{await Promise.all([!c&&hs.joinToRemoteStep(this.testResultId),!l&&Ot.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==Z.APPIUM&&h.validateRunConfig();let y=await this.runTest(h,this.customExtensionLocalLocation,g),T=await t(y,h);return M("After onRunComplete"),T}catch(y){return a(y,h)}finally{c||hs.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,d(m)):this.onQueueCompleted()}}});var rp,zh,ys,sp=w(()=>{"use strict";B();rp=E(require("p-retry"));B();j();K();zh=x("window-utils"),ys=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(o,i){let a=document.elementFromPoint(o,i);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(o){let i=o.message.includes("method IWebBrowser2::Navigate2() failed");if(o.seleniumStack&&i&&n>0)return zh.warn("selenium navigation failed. retrying to navigate",{err:o}),await oe(1500),r(n-1);throw!o.seleniumStack&&i&&zh.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:o}),o}};return Promise.race([r(),oe(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),oe(e)])}async getZoom(){function e(){return{zoomLevel:window.outerWidth/window.innerWidth}}let{value:t}=await this.driver.executeJS(e);return t}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let r=document.body,n=document.documentElement,o=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),i=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:o,width:i}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await oe(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let r;if(typeof location<"u")r=location;else if(typeof window<"u"&&window.location!==void 0)r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&r.href.indexOf("res://ieframe.dll/http_404.htm")!==0&&r.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new Rt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,rp.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,rp.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var np,bs,op=w(()=>{"use strict";j();np=x("cookies-utils"),bs=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(r){throw np.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw np.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw np.error("failed to remove cookie",{err:t}),t}}}});var ip,ji,Kh=w(()=>{"use strict";ip=E(require("p-retry")),ji=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[o,i]=await(0,ip.default)(n,{retries:e,minTimeout:t,factor:1}),a=i?i.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),o=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[i,a]=await(0,ip.default)(o,{retries:t,minTimeout:r,factor:1}),l=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(l.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function Jh(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let o=s.offset||{top:0,left:0};if(o.top*=r,o.left*=r,!s.elementRect)return LS.warn("missing elementRect",Xh.omit(s,"image")),{};let{elementRect:i}=s,a=await Ts.default.read(Buffer.from(n[1],"base64")),l=i.left*r+o.left*r,c=i.top*r+o.top*r,d=i.width*r,m=i.height*r;l<0&&(d+=l,d=d<0?0:d,l=0),c<0&&(m+=c,m=m<0?0:m,c=0);let u=a.bitmap.width,f=a.bitmap.height;if(l+d>u&&(d=u-l),c+m>f&&(m=f-c),m<=0||d<=0)throw new ap("height or width is equal or lower than zero");return{elementImage:await a.crop(l,c,d,m).getBase64Async(Ts.default.MIME_PNG)}}async function DS(s,e){let t=await Ts.default.read(s.width,s.height);for(let n of e){let o=n.image.match(/^data:[^;]*;base64,(.*)$/),i=await Ts.default.read(Buffer.from(o[1],"base64"));await new Promise((a,l)=>{t.composite(i,n.position.left,n.position.top,c=>{if(c){l(c);return}a()})})}return await t.getBase64Async(Ts.default.MIME_PNG)}function NS(s,e){return DS(s,e)}async function MS(){}async function US(s){function e(o){let i=s[o];return typeof i=="string"&&i.startsWith("data")}async function t(o){let i=await MS(s[o]);return{key:o,url:i}}let r=await ie(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(o=>[o.key,o.url]));return Object.assign(s,n)}function Yh(s,e){return e||=1,s||={left:0,top:0,width:0,height:0},{left:e*Math.round(s.left),top:e*Math.round(s.top),width:e*Math.round(s.width),height:e*Math.round(s.height),pixelRatio:e}}var Xh,Ts,LS,ap,$i,Qh=w(()=>{"use strict";Xh=E(require("lodash"));B();Ts=E(require("jimp"));j();LS=x("image-capture-utils"),ap=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};$i=class{constructor(e,t,r){this.windowUtils=t;this.screenshotUtils=r}async takeViewPortImage(){let e=await this.screenshotUtils.takeScreenshot();return typeof e=="string"?e:e.image}takeImageForComparison(){return this.takeViewPortImage()}async takeAreaDataUrl(e){let t=await this.screenshotUtils.takeScreenshot(),r=await Jh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:Yh(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 US({screenImage:t.image,absoluteScreenHighlight:Yh(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>oe(250),o=Boolean(e);async function i(u,f){o?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await Jh({elementRect:f},h);return{position:{left:u.x+f.left,top:u.y+f.top},size:{width:f.width,height:f.height},image:g.elementImage}}async function a(u){let f=[];for(let h of u){let g=await i(h.scrollPos,h.cropData);f.push(g)}return f}function l(u,f){let h=Math.max(u.width,f.width),g=f.width,y=Math.max(u.height,f.height),T=f.height,R=Array.from({length:Math.ceil(h/g)},(v,I)=>({scrollX:Math.min(I*g,h-g),cropX:I*g-Math.min(I*g,h-g),cropW:g-(I*g-Math.min(I*g,h-g))})),b=Array.from({length:Math.ceil(y/T)},(v,I)=>({scrollY:Math.min(I*T,y-T),cropY:I*T-Math.min(I*T,y-T),cropH:T-(I*T-Math.min(I*T,y-T))}));return R.flatMap(v=>b.map(I=>({scrollPos:{x:v.scrollX,y:I.scrollY},cropData:{top:I.cropY,left:v.cropX,width:v.cropW,height:I.cropH}})))}async function c(u,f){let h=await t.getCurrentScrollPosition(),g=l(u,f),y=await a(g);return await t.scrollToPosition(h),NS(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await c(d,m)}}});var Zh,ey,Wi,Vi,ty=w(()=>{"use strict";Zh=E(require("p-retry")),ey=E(require("semver"));B();j();sp();Kh();Qh();Te();Wi=x("tab-service"),Vi=class{constructor(e){this.driver=e;this.sessionTabs={};this._utils={};this.pendingTabs={};this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(r=>!t[r].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={pendingInfos:{},tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(r=>{let n=this.getTabInfo(e,r);return`tabId=${r}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,r,n){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),Wi.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,o={}){let i=await this.getTabDetails(t,e,o),a=se();function l(c){return o.checkForMainTab?i.isMainTab:!i.isMainTab||i.isMainTab==="unknown"?!c.getMainTabInfo(e):i.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:i.url,title:i.title,favIconUrl:i.favIconUrl,order:r,from:this.getTabInfo(e,i.openerTabId),isMain:l(this),openerStepId:n},a}async addTab(e,t,r,n,o={}){let i=await this.buildTabInfo(e,t,r,n,o),a=new ys(t,this.driver);this._utils[i]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new $i(t,a,new ji(t,this.driver,{takeScreenshots:o.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(i=>r[i]).filter(i=>!i.isMain);if(n.length===1)return this._utils[n[0].infoId];let o=Object.keys(e).map(i=>e[i]).filter(i=>this.isSameTab(e,t,i));return o.length>0?this._utils[o[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(o=>o===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:o}=te(),i=o.urlBreaker(e.url||e.currentUrl),a=o.urlBreaker(t.url||t.currentUrl),l=n(i),c=n(a),d=r.map(m=>o.urlBreaker(m)).map(m=>n(m)).filter(m=>m===l);return l===c&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=te();if(n){let c=this.getAllTabInfos(e),d=Object.keys(c).map(m=>c[m]);return n.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let o=this.getAllTabInfos(e),i=Object.keys(o).map(c=>o[c].url);if(this.exactUrlMatch(t,r,i))return!0;let a=c=>`${c.domain}/${c.path.join("/")}`;if(this.singleExactMatchForParts(t,r,i,a))return!0;let l=c=>`${c.domain}/${c.path.join("/")}#${c.hash}`;return!!(this.singleExactMatchForParts(t,r,i,l)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(o=>o.value));try{let[o,i,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:o,url:i,isMainTab:a}}catch(o){Wi.error("failed to get url or title",{err:o})}}catch(n){Wi.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await oe(500),await this.waitForTabToOpen(e))}async tryToAddTab(e){if(this.pendingTabs[e])return;let t=await this.getUnregisteredTabId(e);t&&(await this.addNewTab(e,t),await this.addFrameHandler(t),Object.assign(this.sessionTabs[e],{currentTab:null}))}async addNewPopup(e,t){let r=this.getAllTabInfos(e);if(Object.keys(r).find(i=>r[i].openerStepId===t))return;if(this.pendingTabs[e]){Wi.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,Zh.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=ey.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(o=>o.type==="locate"&&!o.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var a,l;let{tabMatcher:r,commonConstants:n}=te();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 c=await this.driver.getCurrentTabId();if(c)return c;let d=this.getMainTabId(e);if(d)return d;throw new Error("Current tab not found")}let o=(l=t.tabInfo)==null?void 0:l.openerStepId;await this.waitToPendingTabs(e,o);let i;if(r){let c=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed);i=r.matchTabs(t,c)}else{let c=t.tabInfo;c?i=this.getAllTabIds(e).find(d=>{let m=this.getTabInfo(e,d);return this.isSameTab(e,m,c)}):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(c){let d=["no such window","no window found","the window could not be found"];if(c.message&&d.some(m=>c.message.toLowerCase().includes(m)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[i].isClosed=!0,this.getTabIdByTabInfo(e,t);throw c}}}});var cp,Gi,lp=w(()=>{"use strict";cp=class{select(){return console.log(`
|
|
220
220
|
internal error - cant use port selector in selenium!!!!
|
|
@@ -405,8 +405,8 @@ Please make sure the CLI has stable access to the internet. ${fc()?"(Internal: n
|
|
|
405
405
|
`;return this.driver.executeJS(n,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(n){throw aa.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(n){let o="The element is not editable",i="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",l="element not interactable",c="element is not pointer- or keyboard interactable",d="invalid element state: Element is not currently interactable and may not be manipulated",m="Element must not be hidden, disabled or read-only",u="is not reachable by keyboard",f=n?n.message:"";if(f===d||f.startsWith(m)||f.startsWith(o)||f.startsWith(i)||f.startsWith(a)||f.includes(u)||f.includes(l)||f.includes(c)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw aa.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(De(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=D.flags.overrideAzureStorageUrl.isEnabled(),n=D.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:o,context:i,step:a,stepActionUtils:l,driver:c}=this,d=await o.utils.addTokenToFileUrls(i.project.id,a.fileUrls,l.testimServicesApi,r,aa);if(d.length===0)throw new Error("No files urls to upload");if(n&&(d=await Promise.all(d.map(async({name:u,url:f})=>{let h=await Mt(f);return{name:u,url:`data:${h.type};base64,${Buffer.from(h.body).toString("base64")}`}}))),c.isSafari()||c.isFirefox()||c.isEdgeChromium()){await this.driver.executeJS(`
|
|
406
406
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
407
407
|
const downloadAndUploadFile = ${oI()};
|
|
408
|
-
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Hy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var la,ua,Ky=w(()=>{"use strict";la=require("url");le();ua=class extends V{async updateBaseUrl(e){let t=new la.URL(e),r=new la.URL(this.context.recordedBaseUrl),n=new la.URL(this.context.baseUrl);return t.host===r.host&&r.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var pa,Jy=w(()=>{"use strict";le();B();pa=class extends V{async performAction(){await oe(this.step.durationMS||0)}}});var da,Yy=w(()=>{"use strict";le();da=class extends V{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Bn,Xy=w(()=>{"use strict";le();Bn=class extends V{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(r,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t,apiCallAsync:r}=this.sessionPlayerInit;return typeof r=="function"&&r.length===2?r(t,e):new Promise(n=>{t(e,n)})}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},o=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),i=o.result||{},a={method:t.method,status:i.status,url:t.url};return o.success?i.status===0?{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:i,resultInfo:a,shouldRetry:!1,success:!0}:{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:i.error||e.error.REQUEST_TIMED_OUT,errorType:i.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var ma,Qy=w(()=>{"use strict";le();ma=class extends V{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var Zy,dp,mp,eb=w(()=>{"use strict";Zy=E(require("@applitools/spec-driver-webdriverio"));Zn();Te();dp=class{constructor(){let{EyeSdkBuilder:e}=te(),t=Yp["@applitools/eyes-sdk-core"]||"N/A",{makeSDK:r}=require("@applitools/eyes-sdk-core");this.sdk=r({name:"Testim.io",version:`4.0.1/eyes-sdk-core/${t}`,spec:Zy.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=te(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},mp=new dp});var rb,tb,jn,sb=w(()=>{"use strict";rb=E(require("lodash"));le();j();eb();tb=x("pixel-validation-step-action"),jn=class extends V{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||o,l=await mp.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},d;try{let f=await l.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};rb.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(g,i.applitoolsStepSettings),tb.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){tb.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await mp.handleApplitoolsSdkResult(this.context,d,this.step)}}});var vs,fp=w(()=>{"use strict";fs();K();Zi();vs=class extends lr{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o="",id:i=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await ms(o,i,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ne?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ur,nb=w(()=>{"use strict";fp();ur=class extends vs{isFailedResult(e){return e===!1}}});var fa,ob=w(()=>{"use strict";fp();fa=class extends vs{isFailedResult(e){return!e}}});var ga,ib=w(()=>{"use strict";fs();le();K();ga=class extends V{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await ds(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof At?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ne?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var _r,ab=w(()=>{"use strict";le();_r=class extends V{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var we,cb=w(()=>{"use strict";le();we=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var ha,lb=w(()=>{"use strict";le();ha=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var ya,ub=w(()=>{"use strict";le();ya=class extends V{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function iI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function ba(s,e){iI(aI,e),e.registerLocateStepActionUtils(Mn.getUtils(s))}var aI,gp=w(()=>{"use strict";iy();ly();by();Ty();vy();Iy();xy();Cy();Py();ky();Ly();Dy();Ny();Fy();$y();zy();Ky();Jy();Yy();Xy();Qy();sb();nb();ob();ib();ab();cb();lb();ub();aI={locate:Mn,scroll:Ki,mouse:Ji,submit:sa,text:Xi,"special-key":ea,"user-code":qt,"validation-code-step":qt,"wait-for-code-step":qt,"action-code-step":qt,"condition-step":ws,"skip-code-step":ws,"element-code-step":ws,"evaluate-expression":Yi,"text-validation":Fn,"wait-for-text-validation":Fn,"select-option":ra,"drop-file":ia,"input-file":ca,hover:na,navigation:ua,wheel:oa,sleep:pa,refresh:da,"keyboard-shortcut-step":ta,"api-validation":Bn,"api-action":Bn,"api-code-step":qt,"extract-text":ma,"simple-ui-verification":jn,"wait-for-simple-ui-verification":jn,"cli-validation-download-file":_r,"cli-wait-for-download-file":_r,"network-validation-step":_r,"cli-validation-code-step":ur,"cli-wait-for-code-step":ur,"cli-action-code-step":ur,"cli-api-code-step":ur,"cli-condition-step":fa,"node-package":ga,"email-code-step":qt,"cli-email-code-step":ur,"sfdc-internal-test-step":ya,"sfdc-recorded-step":ha,"sfdc-step-login":we,"sfdc-step-loginas":we,"sfdc-step-logout":we,"sfdc-step-sobjectcreate":we,"sfdc-step-sobjectdelete":we,"sfdc-step-findrecord":we,"sfdc-step-quickaction":we,"sfdc-step-sobjectedit":we,"sfdc-step-sobjectvalidate":we,"sfdc-step-launchapp":we,"sfdc-step-wait-for-page-load":we,"sfdc-step-closeconsoletabs":we,"sfdc-step-relatedlistaction":we,"sfdc-step-permission-validation":we,"sfdc-step-convert-lead-to-opportunity":we,"sfdc-step-quotelineeditor":we,"sfdc-document-validation":_r,"sfdc-step-sobjectverifyoptions":we}});var pb,cI,Es,hp=w(()=>{"use strict";pb=["simple-ui-verification","wait-for-simple-ui-verification"],cI=[...pb,"custom-validation","sfdc-internal-test-step","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-wait-for-page-load","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation","sfdc-step-convert-lead-to-opportunity","sfdc-step-quotelineeditor","sfdc-document-validation","sfdc-step-sobjectverifyoptions"],Es=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=cI.includes(e.stepType)?[r]:t(r);this.resetStepVariables(r,n),e.context.data.maxTotalStepTime=r}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let r=e.context.config.stepTimeout;return pb.includes(e.stepType)&&(r=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(r=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:r}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let r=Date.now()-e.startTimestamp;return t-r}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+1e3}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,r=e.step.type,n=3e4;return r==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),n)}}});var mb={};G(mb,{SeleniumTestPlayer:()=>$n});var db,lI,$n,yp=w(()=>{"use strict";B();db=require("@applitools/eyes-sdk-core");Pn();K();j();op();ty();lp();qi();ny();up();Te();gp();hp();lI=x("SeleniumTestPlayer"),$n=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new Es(zi());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=te();this.driver=n??new xr;let d=new Hi(this.driver);this.stepActionFactory=new c(d),ba(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Vi(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=sy(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new bs(this.driver),FrameLocator:m,portSelector:Gi,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:db.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=te(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(o){o instanceof ne&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){lI.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(r);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var fb={};G(fb,{WorkerSelenium:()=>bp});function pI(s){let{playback:e}=te().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>M(`Got event ${t}`))}var Ta,uI,bp,gb=w(()=>{"use strict";B();$e();Dn();j();_t();Qo();ae();sp();K();yp();Te();nt();Ta=x("worker-selenium"),uI=1e9,bp=class extends lt{initPlayer(t){return new $n(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){M("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ys(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await i.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:o,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps}),M("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),M("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,uI),await this.windowUtils.validatePageIsAvailable(),M("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof Rt||d||m?new Rt(`Page '${l}' is not available`):(Ta.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:No(),initializedFromCache:Mo()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:o}=te(),{driver:i,sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),pI(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),o.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await fn(this.options))[this.testId]);let d=async()=>ce(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(f)}),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof ne&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await o.drain(),u.stepsResults=null,u.resultId=this.testResultId,i.isAlive()||(Ta.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=i.maxKeepAliveGap();f>=3e4&&(Ta.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});i.start(),M("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),M("right after super.runTestOnce in workerSelenium");let u=await d();return M("right after runSeleniumTest"),u}catch(u){throw Ta.error("failed to run test once",{err:u}),u}}}});var hb,yb,He,dI,mI,Tp,St,wa=w(()=>{"use strict";hb=E(require("ora")),yb=E(require("jimp"));ue();Ge();he();j();ae();Te();pe();He=x("mobile-grid-service"),dI="https://tdc.tricentis-cloud.com",mI="https://ui.headspin.io",Tp=class{constructor(){this.gridsAppIdGetter={[O.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[O.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[O.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[O.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[O.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[O.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===O.TESTIM_TDC||e===O.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e)?`${t}/lock`:""}getBaseApiUrl(e){return e===O.TESTIM_HEADSPIN?`${hd}/devices`:e===O.TESTIM_TDC?`${bd}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e.type),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await Ve({url:r,headers:n,body:o})}catch(i){throw He.debug(`error while locking device ${t}`,{error:i}),i.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):i}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e.type)}/device_id:${t}/automation-config`;try{let o=await be(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw He.error("error while getting automation config for device",{error:o,deviceId:t}),o}}async getPCloudyAuthToken(e,t,r){let n=await Bs(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,o=new URL(n);return{hostname:o.hostname,port:Number(o.port),protocol:o.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){if(this.isTdcOrHeadSpinGrid(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:`/v0/${e.accessToken}/wd/hub`};if(e.type===O.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===O.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([O.BROWSERSTACK,O.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:o,gridId:i}){var a,l,c;if(t===O.TESTIM_HEADSPIN||t===O.TESTIM_TDC){let d=await Il({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===O.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===O.SAUCELABS)return e.testobject_device_name;if(t===O.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n){let{executionId:o,testId:i,testResultId:a}=e,{project:l,projectData:{type:c}={},company:{companyId:d=""}={},gridData:{gridId:m="",type:u=""}={}}=n,f=t.capabilities,h=f.platformName,g;if(u===O.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:T}=te();g=T(t.capabilities)}else g=await this.getDeviceFromAppiumCapabilities(f,t,r,h,u,l,c,d,m);let y=await this.buildRemoteResultLink(n.gridData,t.sessionId,f);return await vr(l,o,i,a,"RUNNING",{device:g,...y&&{remoteResultLink:y}}),He.info("device details updated on testResult",{testResultId:a,executionId:o,testId:i,device:g,remoteResultLink:y,gridType:u}),g}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===O.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),i=Number(o[0]),a=Number(o[1]);return{scaleFactor:e.pixelRatio,width:i,height:a}}try{let{AppiumApi:o}=te(),i=new o(t,r.sessionId,null),[a,l]=await Promise.all([i.getScreenshot(),i.getDeviceSize()]),c=Buffer.from(a,"base64"),d=await yb.default.read(c),m=d.getWidth(),u=d.getHeight();return{scaleFactor:m/l.width,width:m,height:u}}catch(o){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,o,i,a,l,c){let[d,m]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:o,projectId:i,projectType:a,companyId:l,gridId:c})]),u=this.getOsVersion(e,o);return{name:m??"",model:e.deviceModel,udid:e.udid,osVersion:u,osType:n,isVirtual:!1,...d}}async buildRemoteResultLink(e,t,r){return e.type===O.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Os}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===O.SAUCELABS?r.testobject_test_report_url:e.type===O.TESTIM_TVC?r.replayUrl:e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC?`${e.type===O.TESTIM_HEADSPIN?mI:dI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let r=(await be(`${gd}/devices`)).find(n=>n.udid===e);if(!r)throw new Error(`device ${e} not found`);return{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,geo:"local",osVersion:r.osVersion,osType:r.deviceType.toLowerCase(),scaleFactor:r.scaleFactor??0,isVirtual:r.virtual??!1,minApiVersion:r.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:o,testResultId:i}=r,a=await this.getTmaDeviceDetails(e),{project:l}=t;return await vr(l,n,o,i,"RUNNING",{device:a}),He.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,o=t.mobileApp,i=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:o,gridHost:e.host});return i?(D.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:i,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Al({gridAppId:i,gridId:e.gridId,projectId:r,gridType:n,appId:o.appId,gridHost:e.host})),i):t.getAppPathByGridType(n,e.gridId,o)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r,executionId:n,testResultId:o}){let i=await an({appId:e,projectId:t});return{appUrl:`${fe}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(fd*60))+1)*60*1e3,Math.max(md,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let a={[O.BROWSERSTACK]:{name:"Browserstack"},[O.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[O.P_CLOUDY]:{name:"pCloudy"}}[o].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,hb.default)(`uploading app to ${a} please wait..`).start();try{He.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await Rl({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),He.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:o,mobileAppId:i}){let a=t.get(i);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:o});return t.set(i,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",o,{executionId:i,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){He.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:i});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d,executionId:i,testResultId:a});n=T.appUrl,o=T.mobileApp,e.nativeApp=o}else He.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:i}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===O.BROWSERSTACK||f===O.TESTIM_TVC||f===O.P_CLOUDY;if(g){let T=t.projectData.type,R=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});R&&(He.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=g),!R&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!R&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:i})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var c,d;let{accessToken:n,user:o,host:i,key:a,type:l}=t;if(l===O.BROWSERSTACK){let m=`${Os}/recent_apps`,u=await this.fetchWithUserAndPasswordAuth({url:m,user:o,key:a});return Array.isArray(u)?u.some(f=>f.app_url===e):!1}if(l===O.SAUCELABS){let u=`${i.includes("eu-central-1")?Ed:vd}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:o,key:a})).items.some(h=>h.id===e)}if(l===O.TESTIM_HEADSPIN||l===O.TESTIM_TDC){let m=l===O.TESTIM_HEADSPIN?`${yd}/apps`:`${Td}/apps`;return(await this.fetchWithTokenAuth({url:m,accessToken:n,authType:"Bearer"})).apps.some(f=>f.app_id===e)}if(l===O.TESTIM_TVC){let m=`${wd}/versions/${e}/info`,u=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:m,accessToken:u,authType:"Upload-Token"}),!0}catch(f){return f.status!==404&&He.error("error while verifying app exists on TVC",{error:f}),!1}}if(l===O.P_CLOUDY){let m=await this.getPCloudyAuthToken(i,o,a),u=`https://${i}/api/drive`,f=await uc({url:u,body:{token:m,filter:"all"},headers:{contentType:null}});return(d=(c=JSON.parse(f).result)==null?void 0:c.files)==null?void 0:d.some(g=>g.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await be(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r}){let n={Authorization:`${r} ${t}`};return await be(e,void 0,n)}},St=new Tp});function bb({nativeAppMetadata:s,appPath:e,gridInfo:t}){if(!s&&!e||!s)throw Error("Application not specified. Please provide the required application for execution and try again.");if(!s.id&&!s.activity&&!s.packageName)throw Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");if(t.mode!=="local"&&!fI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function gI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==O.TESTIM_TDC&&e.type!==O.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function hI(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,o=[{executionId:t},{testResultId:r}];return e&&o.push({testName:e}),n&&o.push({customTag:n}),o}function yI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===O.TESTIM_TDC,a=s===O.TESTIM_HEADSPIN,l=i?"tdc":"headspin",c=a&&D.flags.enableBatchHeadSpin.isEnabled(),d=i&&(D.flags.enableBatchTDC.isEnabled()||D.flags.headSpinTdcEnableFlagCapability.isEnabled());return{[`${l}:capture`]:!0,...D.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...o&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:hI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n}}}function va(s){return"id"in s?s.id:s.packageName}function bI(s,e){return{[`${e===O.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function TI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:o}){let{fullReset:i,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=bI(n,t.gridData.type));let m=()=>i===void 0&&n?!0:typeof i=="string"?i!=="false":i;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":va(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!i,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...o&&{"appium:appWaitActivity":`${o}, *`},...r&&{"appium:appPackage":va(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Lr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:o=""}){switch(s){case"ios":return{platformName:"iOS",[`${o}autoAcceptAlerts`]:!0,[`${o}automationName`]:"XCUITest",[`${o}fullReset`]:!0,...t&&{[`${o}bundleId`]:va(t)},...r&&{[`${o}app`]:r},...e};case"android":return{platformName:"Android",[`${o}autoGrantPermissions`]:!0,[`${o}automationName`]:"UiAutomator2",...n&&{[`${o}appWaitActivity`]:`${n}, *`},...t&&{[`${o}appPackage`]:va(t),[`${o}appActivity`]:t.activity??".*"},...r&&{[`${o}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Tb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=yI(i.type,o,n);return TI({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Sa({osVersion:s,mobileConfig:e}){let{staticAllocation:t,dynamicAllocation:r}=e;return s||(t!=null&&t.osVersion?t==null?void 0:t.osVersion:r!=null&&r.osVersionRegex?r==null?void 0:r.osVersionRegex:".*")}function Ia({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o}=e,i=r===O.P_CLOUDY;return s||(n!=null&&n.deviceName?i?n.deviceUdid:n.deviceName:o!=null&&o.deviceNameRegex?t==="android"&&o.deviceNameRegex===".*"&&i?Ka:o.deviceNameRegex:t==="ios"&&r===O.BROWSERSTACK?"iPhone.*":i?t==="ios"?"apple":Ka:".*")}function wI(s,e){let{androidToken:t,iosToken:r}=s,n=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(n&&!r)throw Error("missing ios token for testim virtual cloud");if(!n&&!t)throw Error("missing android token for testim virtual cloud");return n?r:t}function vI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Ea(s,Ss)}}function wb(s,e,t){return s?Object.entries(s).reduce((r,[n,o])=>{if(e(n)){if(!t)return r[n]=o,r;let i=n.replace(t,"");r[i]=o}return r},{}):{}}function EI(s){return wb(s,e=>e.startsWith("browserstack."),"browserstack.")}function SI(s){return wb(s,e=>!e.startsWith("browserstack."))}function vb(s){return!s||!Eb(s)?"2.0.0":s}function Eb(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Sb({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,o=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,i=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&o.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&i.test(s),d=l||c;if(t){let m=Eb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Ea(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let o=`${e}${r}`;t[o]=n}),t}function II({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=wI(o,s),f=Sa({osVersion:l,mobileConfig:d}),h=Ia({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),g=qe(n.editorUrl,n.project,i.testId,i.testResultId,i.branch),y={device:h,os_version:f,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:externalUrl":g,"waldo:options":{token:u}};return Lr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function RI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=o,h=D.flags.enableAppium2pCloudy.isEnabled(),g=Sa({osVersion:l,mobileConfig:d}),y=Ia({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),R={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:i.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...R,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Sd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=vI(b)),t="",Lr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Ss}})}function AI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=Sa({osVersion:l,mobileConfig:d}),f=Ia({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Or.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],Sb({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},R={user:o.user,key:o.key,name:i.testResultId,build:i.executionId,appiumVersion:vb(g.appiumVersion),deviceName:f,tags:Object.values(i)},b={"appium:platformVersion":u,"appium:deviceName":f,...Ea(h,Ss),"sauce:options":{...T,...R,...(0,Or.omit)(g,"appiumVersion")}};return Lr({projectType:s,sessionCaps:b,appiumPrefix:Ss,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":o.user,"saucelabs.key":o.key,platformVersion:u,deviceName:f,tags:Object.values(i),name:i.testResultId,build:i.executionId,...h,...g};return Lr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function xI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=Sa({osVersion:l,mobileConfig:d}),f=Ia({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=EI(n.browserstack),g=(0,Or.omit)(SI(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:R}=n.browserstack||{};if(Sb({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let v={userName:o.user,accessKey:o.key,appiumVersion:vb(h.appiumVersion),projectName:y||i.project,buildName:T||i.executionId,debug:!0,networkLogs:!0},I={"appium:platformVersion":u,"appium:deviceName":f,...Ea(g,Ss),"bstack:options":{...v,...(0,Or.omit)(h,"appiumVersion")}};return Lr({projectType:s,sessionCaps:I,appiumPrefix:Ss,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let b={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:R||i.testResultId,project:y||i.project,build:T||i.executionId,buildTags:Object.values(i).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,...Ea(h,"browserstack.")};return Lr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function CI(s){if(O.TESTIM_TDC===s.gridInfo.type||O.TESTIM_HEADSPIN===s.gridInfo.type)return Tb(s);if(O.TESTIM_TVC===s.gridInfo.type)return II(s);if(O.P_CLOUDY===s.gridInfo.type)return RI(s);if(O.SAUCELABS===s.gridInfo.type)return AI(s);if(O.BROWSERSTACK===s.gridInfo.type)return xI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function PI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:o,osVersion:i,deviceUdid:a}=s,l={};return n==="dynamic"&&(!o&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!i&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),o&&(l.manufacturer=o),i&&(l.os_version=i),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}function Ib(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:o}=s,{selectedGrid:i}=(o==null?void 0:o.mobile)||{};if(o!=null&&o.mobile&&(i==null?void 0:i.type)!==e.type)throw Error(`selected grid type ${i.type} is not equal to grid type ${e.type}`);bb({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=St.getGridConnection(e),l=CI(s);if(e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC){let d=e.type===O.TESTIM_HEADSPIN?"headspin":"tdc",m=PI(r,o==null?void 0:o.mobile);if(!(0,Or.isEmpty)(m)){let u=Object.entries(m).map(([f,h])=>h.split(",").map(g=>g===".*"||g==="="?"":`${f}:${g}`).join(",")).join(" ").trim();l[`${d}:selector`]=u}}let c=e.type===O.TESTIM_TVC?{alwaysMatch:l}:l;return{...a,desiredCapabilities:l,capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function Rb(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;bb({nativeAppMetadata:r,appPath:o,gridInfo:t}),gI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((g=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await St.getGridDirectConnection(t,d),f=Tb({projectType:e,nativeAppMetadata:r,appPath:o,androidActivityWait:i,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Ab(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s;return Lr({projectType:e,sessionCaps:{},nativeAppMetadata:t,appPath:r,androidActivityWait:n})}function xb(s){var t,r;let e={...s};return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],(t=e.capabilities["sauce:options"])==null||delete t.user,(r=e.capabilities["sauce:options"])==null||delete r.key,delete e.capabilities.key,delete e.capabilities.user,e}var Or,Ss,fI,wp=w(()=>{"use strict";pe();ae();wa();Or=require("lodash");B();ue();Ss="appium:",fI=[O.BROWSERSTACK,O.SAUCELABS,O.TESTIM_HEADSPIN,O.TESTIM_TDC,O.TESTIM_TVC,O.P_CLOUDY]});var Ra,Pb=w(()=>{"use strict";Ra=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 _b,kb,Aa,Ob=w(()=>{"use strict";_b=require("linkedom"),kb=new _b.DOMParser,Aa=class{constructor(e){this.driver=e;this._abortedSteps=[]}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}unescapeHTML(e){return kb.parseFromString(`<html><body>${e}</body></html>`,"text/html").documentElement.textContent}getLinksFromUnescapeHTML(e){return[...kb.parseFromString(`<html><body>${e}</body></html>`,"text/html").getElementsByTagName("a")].map(r=>r.href).filter(Boolean)}}});var vp,xa,Lb=w(()=>{"use strict";j();vp=x("mobile-frame-locator-mock"),xa=class{foundFrameCallback(){return vp.info("foundFrameCallback-mock invoked"),{}}locate(){return vp.info("locate-mock invoked"),{}}async findFrame(){return vp.info("findFrame-mock invoked"),{}}}});var kI,Nb,Db,Is,Ep=w(()=>{"use strict";kI=E(require("webdriverio")),Nb=require("@applitools/eyes-sdk-core");Pb();lp();j();Ob();up();Te();gp();Lb();hp();Db=x("appium-test-player"),Is=class{constructor(e,t,r,n=kI,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=te(),m=new Aa(this.driver);this.stepActionFactory=new c(m),ba(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Es(zi()),this.sessionPlayer=new a(e,{tabService:new Ra,cookieUtils:void 0,FrameLocator:xa,portSelector:Gi,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Nb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,o={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Db.info("appium session deleted",{...o}))}catch(i){Db.error("error while deleting appium session",{...o,error:i})}finally{let{commonConstants:i}=te();e.off(i.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function _I(s){return await be(`${s}/api/status`)}async function Mb(s,e){return await be(`${s}/api/devices/${e}/status`)}async function Ub(s){if((await _I(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Fb=w(()=>{"use strict";Ge()});var Bb={};G(Bb,{WorkerLocalTma:()=>Ap});var Ca,Sp,Ip,Rp,Ap,jb=w(()=>{"use strict";Ge();wp();Dn();B();j();_t();Ep();Te();Fb();wa();Ca=x("worker-appium"),Sp=class extends Error{},Ip=class extends Error{},Rp=class extends Error{},Ap=class extends lt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=te(),{DOMParser:n}=await import("linkedom"),o=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=o,o}async getBrowserOnce(t,r,n,o){var I;if(Q.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:i,deviceUdid:a,projectData:l}=this.options;await Ub(i);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{executionId:C,testResultId:_}=t,{mobileApp:$}=await St.getMobileAppDataByAppId({appId:f,projectId:c,token:d,executionId:C,testResultId:_});t.nativeApp=$}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:R,version:b},v]=await Promise.all([this.getAppStateFromDevice(i,a,T),Mb(i,a)]).catch(C=>{throw this.handleDeviceNotFoundError(C),C});if(!R&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!R&&y&&await this.installApp(i,a,y);try{let C={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(I=this.options.projectData)==null?void 0:I.name}-${this.options.project}`},_=Ab({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:C,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),$={capabilities:{udid:a,..._}},A=await this.requestNewAppiumSessionFromTma(i,$,g);this.sessionData=A;let S=await m.attach({sessionId:A.sessionId,capabilities:_});this.device=await St.updateTmaDeviceDetails(a,this.options,t),Ca.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:S.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:S.capabilities})}catch(C){throw Ca.error("failed to start application",{err:C}),C}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await Ve({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new Rp(l):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,l=(await be(i)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var o,i;try{let a=await Mt(n);await Fs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new Ip(c,{cause:a})}}handleDeviceNotFoundError(t){var n,o;let r=(o=(n=t.response)==null?void 0:n.body)==null?void 0:o.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Sp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=te(),{sessionPlayer:i}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),o.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{i.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await o.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Ca.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Ca.error("failed to run test once",{err:c}),c}}}});var Wb={};G(Wb,{WorkerAppium:()=>xp});var $b,Dr,xp,Vb=w(()=>{"use strict";wp();$b=require("linkedom");Dn();j();_t();Ep();Te();wa();ae();is();Dr=x("worker-appium"),xp=class extends lt{initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,l=await St.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),c=a==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let m={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.id}`},u={projectType:a,nativeAppMetadata:d,appPath:l,androidActivityWait:c,sessionTags:m,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig},f;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await St.lockDevice(o,this.options.deviceUdid),f=await Rb(u)):f=Ib(u),Dr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:xb(f)});let h=this.getServerAddressFromGrid();this.activeSession=await i.remote(f),this.device=await St.updateDeviceOnRemoteTestResult(t,this.activeSession,h,this.options);let g=`${h}/session/${this.activeSession.sessionId}`;this.updateSlotData(g),Dr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Dr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}async startKeepAlive(t){let r=async()=>{try{await(t==null?void 0:t.getOrientation())}catch(n){Dr.error("failed to keep appium session alive",{err:n})}};this.keepAliveIndex=setInterval(r,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&pg(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:t},this.id)}catch(r){Dr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===O.TESTIM_HEADSPIN||o===O.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:o===O.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:o,directConnectPath:i}=t;if(r&&n&&o&&i)return`${r}://${n}:${o}${i}`}async runTestOnce(t,r){var u,f;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=te(),{sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let c;if(this.options.skipLoadBalancer){let h=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:g,hostname:y,port:T,path:R}=await St.getHeadSpinDeviceConnection(this.options.gridData,h);c=`${g}://${y}:${T}${R}`}else c=this.getDirectAddressConnection(this.activeSession.capabilities)||this.getServerAddressFromGrid();let d=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:d,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(f=this.options.company)==null?void 0:f.companyId,device:this.device},a.playbackManager.appiumApi=new o(c,this.activeSession.sessionId,$b.DOMParser),this.startKeepAlive(a.playbackManager.appiumApi),i.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let h=await new Promise((y,T)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:y,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(T)});return this.stopKeepAlive(),await i.drain(),h.stepsResults=null,h.resultId=this.testResultId,{...h,...t.seleniumPerfStats.getStats()}}catch(h){throw Dr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:h}),this.stopKeepAlive(),h}};try{return await super.runTestOnce(t,r),await m()}catch(h){throw Dr.error("failed to run test once",{err:h}),h}}}});var Pa,Gb=w(()=>{"use strict";B();Pn();K();Pa=class{constructor(e){this.id=e;this.driver=new xr}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof ne&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Hb,ka,qb=w(()=>{"use strict";Hb=E(require("ws"));B();ka=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 Hb.default(this._cdpUrl,{timeout:e}),r=Yt(o=>{t.once("open",o)}),n=Yt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let o=this._lastWsId++,i=new Promise((l,c)=>{this._cdpCallbacks.set(o,{resolve:l,reject:c})}),a={method:e,params:t,id:o};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),i}}});var Oa,Cp,_a,zb=w(()=>{"use strict";B();Oa=E(require("chrome-launcher"));Mu();qb();un();Cp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new ka}async init(e){var f,h,g,y;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c}=e,d=xi({browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c}),m=[...((f=d.desiredCapabilities)==null?void 0:f.chromeOptions.args)??[],...((y=(g=(h=d.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:g["goog:chromeOptions"])==null?void 0:y.args)??[],...Oa.Launcher.defaultFlags().filter(T=>T!=="--disable-extensions")];this.chrome=await Oa.launch({chromeFlags:m,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 u=await yr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(u),es(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},_a=class{constructor(e){this.id=e;this.sessionId=se();this.driver=new Cp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Jb={};G(Jb,{WorkerExtension:()=>Wn});function OI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Kb(s){return OI(s)?s:new Error(s)}var ut,Wn,Pp=w(()=>{"use strict";$e();K();Dn();B();j();_t();ae();Gb();zb();nt();ut=x("worker-ext"),Wn=class extends lt{initPlayer(){return this.options.useChromeLauncher?new _a(this.id):new Pa(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(i=this.options.lightweightMode)==null?void 0:i.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps})}catch(a){throw ut.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:No(),initializedFromCache:Mo(),testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var o;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((o=this.options.browserstack)!=null&&o["browserstack.user"])){let i={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(i)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:o}=this;M("WorkerExtension runTestOnce");let i=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ce(e.runTestUsingCDP(d.cdpTestRunner),m,Ue.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ne))throw u;return ut.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw ut.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:o,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(M("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw ut.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Ue.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof ne))throw T;ut.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),ut.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),T.type=$s.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=ce(e.onCompleted(),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG),R=await oc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(R.success),R.reason)}catch(I){ut.error("Could not update the grid about the test status",{err:I})}m.isAlive()||(ut.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),R.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(ut.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),R.keepAliveIssue=b),{...R,...e.seleniumPerfStats.getStats()}}catch(T){throw ut.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:o}),Kb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw ut.warn("failed to start url",{err:h}),Kb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),M("WorkerExtension super.runTestOnce"),await c()}catch(d){throw ut.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Yb={};G(Yb,{WorkerExtensionSingleBrowser:()=>kp});var LI,DI,kp,Xb=w(()=>{"use strict";$e();B();j();Qu();_t();Pp();LI=x("base-worker"),DI=500,kp=class extends Wn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await On(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,o){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,o)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(LI.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let o=this.handleQuarantine(t);if(o)return o;M("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await oe(DI)}}});function NI(s,e){e===0?s():setTimeout(s,e*ad)}var _p,La,Qb=w(()=>{"use strict";Pn();ue();$e();Ru();nt();$u();K();j();ae();Wh();_p=x("parallel-worker-manager"),La=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Z.SELENIUM:return(gb(),ye(fb)).WorkerSelenium;case Z.APPIUM:return e.localTmaUrl?(jb(),ye(Bb)).WorkerLocalTma:(Vb(),ye(Wb)).WorkerAppium;default:return Pi.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Xb(),ye(Yb)).WorkerExtensionSingleBrowser:(Pp(),ye(Jb)).WorkerExtension}}createWorkers(e,t,...r){let n=r[0],o=this.getWorkerType(n),i=()=>{try{return M("before new Worker",n.mode),new o(t,...r)}finally{M("after new Worker",n.mode)}};return Array.from(new Array(e),i)}async runTests(e,t,r,n,o,i,a,l,c){if(e&&e.length===0)return;let d=!1,m=0,u=(f,h)=>new Promise(g=>{var dr,k,N,F,z,dt,Fa,Wp;let y=o.project,T=new Mi(r,n,e,o,i,t),R={},b=e.length,v=((dr=o.company)==null?void 0:dr.ucid)||"",I=(k=o.company)==null?void 0:k.companyId,C=(N=o.company)==null?void 0:N.name,_=o.source||"cli",$=o.user,A=(F=o.company)==null?void 0:F.planType,S=(z=o.company)==null?void 0:z.isStartUp,L=(dt=o.projectData)==null?void 0:dt.name,U=(Fa=o.projectData)==null?void 0:Fa.type,q=o.lightweightMode,H=(Wp=o.gridData)==null?void 0:Wp.type,Y=(Lt,mt,ve,Ba,Gn,ja)=>(m++,Rg({executionId:r,projectId:y,testId:mt,resultId:ve,ucid:v,companyId:I,companyName:C,projectName:L,companyPlan:A,source:_,user:$,lightweightMode:q,isStartUp:S,projectType:U,appSource:ja,gridType:H}),t.testStartAndReport(Lt,r,ve,Ba,Gn)),me=async(Lt,mt,ve,Ba,Gn,ja)=>{var Vp,Gp,Hp;m--;let et={...(q==null?void 0:q.onlyTestIdsNoSuite)&&{show:!0},...ve.seleniumStats&&{seleniumStats:ve.seleniumStats},...ve.gridIssues&&{gridIssues:ve.gridIssues},...ve.keepAliveIssue&&{keepAliveIssue:ve.keepAliveIssue},...o.host&&{gridHost:o.host}};if(ve.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ve.seleniumPerfMarks),delete ve.seleniumPerfMarks),o.grid||o.gridId?(et.gridName=o.grid||((Vp=o.gridData)==null?void 0:Vp.name),et.gridType=(Gp=o.gridData)==null?void 0:Gp.type,et.gridProvider=(Hp=o.gridData)==null?void 0:Hp.provider):o.localTmaUrl?(et.gridName="local-tma-from-options",et.gridType="local-tma"):o.useLocalChromeDriver?(et.gridName="local-chrome-driver-from-options",et.gridType="local-chrome"):o.useChromeLauncher?(et.gridName="chrome-launcher-from-options",et.gridType="local-chrome"):o.browserstack?et.gridName="browserstack-from-options":o.saucelabs&&(et.gridName="saucelabs-from-options"),await t.testEndAndReport(Lt,ve,r,Ba,Gn,et).catch(kT=>_p.error("testEndAndReport threw an error",{err:kT})),Gn)return;R[ve.resultId]=ve,Ag({executionId:r,projectId:y,testId:mt,resultId:ve.resultId,result:ve,ucid:v,companyId:I,companyName:C,projectName:L,companyPlan:A,source:_,user:$,lightweightMode:q,logger:_p,isStartUp:S,projectType:U,appSource:ja}),c&&!ve.success&&(T.stop(),d=!0),(Object.keys(R).length===b||d&&m===0)&&g(R)},pt=(Lt,mt)=>{R[mt.resultId]=mt,t.onTestIgnored(Lt,mt.resultId),m--,(Object.keys(R).length===b||d&&m===0)&&g(R)},It=(Lt,mt)=>t.onGridSlot(Lt,mt);o.userData={loginData:{...jt(),refreshToken:Lo(),authData:jt(),token:f,userAccessKey:h},projectId:o.project,company:o.company,servicesUrl:fe},M("in localStrategy before createWorker"),this.createWorkers(l,T,o,this.customExtensionLocalLocation,r,Y,me,It,pt).forEach((Lt,mt)=>{M("before schedule worker.run after createWorkers"),NI(()=>{M("right before worker.run"),Lt.run()},mt)})});try{let f=await Zt(),h=await Do(),g=await u(f,h);if(d)throw new Kt;return g}catch(f){throw _p.error("failed running parallel workers",{executionId:r,err:f}),f}}}});async function eT(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:se()}))]}:await sl({projectId:s.project,labels:s.label,testIds:s.testId,testNames:s.name,testConfigNames:s.testConfigNames,suiteNames:s.suites,suiteIds:s.suiteIds,branch:e,rerunFailedByRunId:s.rerunFailedByRunId,testConfigIds:s.testConfigIds,intersections:s.intersections})}function Op(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function Lp(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=Zb.difference(Ws(s,e),t);if(r.length>0)throw Tt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new P(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Zb,tT=w(()=>{"use strict";Zb=E(require("lodash"));B();ts();he();K()});var Vn,fD,Dp,Np,Da,rT=w(()=>{"use strict";Vn=E(require("lodash"));B();j();ue();ae();$e();ns();cu();Ru();he();nt();_t();zg();K();Qb();tT();({testRunStatus:fD,CLI_MODE:Dp}=Ut),Np=x("test-plan-runner"),Da=class{constructor(e){this.startTime=Date.now();this.workerManager=new La(e)}async runTestAllPhases(e,t,r,n,o,i,a,l){let c={},d=jt(),m=async()=>{let g=o.beforeParallel||1,y=!0,T=await this.workerManager.runTests(e,l,i,a,o,n,d,g,y);Object.assign(c,T)},u=async()=>{let g=ro||o.parallel,y=!1;M("right before this.workerManager.runTests");let T=await this.workerManager.runTests(t,l,i,a,o,n,d,g,y);M("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=o.afterParallel||1,y=!1,T=await this.workerManager.runTests(r,l,i,a,o,n,d,g,y);Object.assign(c,T)};xg({executionId:i,projectId:o.project}),M("right before runBeforeTests");try{return await m(),M("right before runTestPlanTests"),await u(),M("right after runTestPlanTests"),await f(),c}catch(g){if(Np.error("error running test plan",{err:g}),g instanceof Kt)return l.markAllQueuedTests(i,de.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,R,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===Dp.SELENIUM){let[{getSessionPlayer:v},{makeSDK:I}]=await Promise.all([Promise.resolve().then(()=>(Te(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:C}=v();await C.closeBatch(i,I);return}let g;try{if(!((b=(R=(T=o.company)==null?void 0:T.activePlan)==null?void 0:R.premiumFeatures)!=null&&b.applitools)||(g=await Tl(o.project),Vn.default.isEmpty(g)||!i))return;let{runKey:v,url:I}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:I,apiKey:v}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,l){var b,v,I;let c=se(),d=n.project;ec(c),e.forEach(C=>Object.assign(C,{isBeforeTestPlan:!0})),r.forEach(C=>Object.assign(C,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Ai(m,n,i,a),f=Vn.default.chain(m).map(C=>{var _;return((_=C.overrideTestConfig)==null?void 0:_.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(C=>C.name),y=(v=n.lightweightMode)!=null&&v.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,o,g);M("before testListInfoPromise");let T=await y;(I=n.lightweightMode)!=null&&I.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,o,c,l,h),M("before runTestAllPhases");let R=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,o||"All Tests",u);return M("before executionEnd"),await u.executionEnd(c),M("after executionEnd"),{results:R,executionId:c,testPlanName:o,configName:h}}async runTestPlans(e,t){Np.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return Vn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await rl(i,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Dp.APPIUM&&await Lp(e,r(c)),await ie(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await ng(e,d);let f=u.overrideExecutionName||d.name;return await ie(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(I=>({executionId:I,status:Op(n[m][I])})),R=Object.keys(n[m]).map(I=>n[m][I]).reduce((I,C)=>Object.assign(I,C),{}),b=Op(R);Object.assign(o,R);let v=b?T[0].executionId:T.find(I=>!I.status).executionId;return await Zc(i,m,{success:b,executions:T,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var l;Np.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),M("before getSuite");let r=await eT(e,t);if(M("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new P("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new P("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new P("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;M("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode==="appium"&&(a=await an({appId:e.appId,projectId:e.project})),await ie(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==Dp.APPIUM&&await Lp(e,c),M("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,o,null,t,i);return M("right after runTestPlan"),await Q.onTestPlanFinished(d.results,o,this.startTime,d.executionId,i),d})}async run(e){let t=vn(),r=[];Vs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Vn.default.flattenDeep(r);return M("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),M("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var iT={};G(iT,{init:()=>rR,run:()=>XI});async function MI(s){let e=s.project,t=await nl(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"),pn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ls}function UI(s,e){var i,a,l,c,d,m,u,f;let t=ho(e.activePlan),r=s.parallel;if(t==="free"&&r>nT)throw new P(`The free plan allows only ${nT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let h=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!h)throw new P("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let g=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.runInTurboMode;s.lightweightMode&&!g&&(console.warn(`
|
|
409
|
-
Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((d=s.gridData)==null?void 0:d.type)===O.TESTIM_TVC){let h=e.tvcLicense.expireAt||1;if(Date.now()>h)throw new P("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let g=Number(e.tvcLicense.maxParallel);if(r>g)throw new P(`Your license allows only ${g} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((m=s.gridData)==null?void 0:m.type)===O.TESTIM_TDC){let h=e.tdcLicense.expireAt||1;if(Date.now()>h)throw new P("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted")}let n=s.retentionDays;if(!n)return;let o=(f=(u=e.activePlan)==null?void 0:u.premiumFeatures)==null?void 0:f.resultRetention;if(n>o)throw new P(`Retention days (${n}) cannot be greater than the company's retention days (${o}). Run aborted`)}async function FI(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await MI(s)}catch(t){if([P,Ls].some(r=>t instanceof r))throw t;Mp.error("could not validate cli account",{err:t})}}function BI(s){let e=jt();return uf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function jI(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(D.flags.useNewWSCLI.isEnabled()&&!e&&!t)return vt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(Li(),Oh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(Di(),Nh));r.init(s)}}function $I(s,e){let{branch:t,autoDetect:r}=s;if(dg(e,r),!e&&!r)throw new P(`branch ${t} does not exist, run aborted.`)}async function WI(s,e){let{id:t,type:r}=e,o=oT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&D.flags.sfdcHybridCompany.isEnabled(),i=vn();o&&(s.sfdcCredential=await Xc({projectId:t,branch:i}))}function VI(s,e){let{id:t,storageBaseUrl:r,storageType:n,name:o,activePlan:i={}}=e,a=Boolean(i.isPoc),l=Boolean(i.isStartUp),c=ho(i);c==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<sT?sT:s.newBrowserWaitTimeout),D.setCompanyId(t),D.setIsPOC(a),D.setIsStartUp(l),D.setPlanType(c),kt.setPlanType(c),s.company={ucid:"",companyId:t,storageBaseUrl:r,storageType:n,name:o,planType:c,isPOC:a,isStartUp:l,activePlan:i}}function GI(s,e){s.editorUrl=_s||e.editorUrl}function HI(s,e){s.allGrids=e}function qI(s,e){s.authData=e}function zI(s,e){let{id:t,name:r,type:n,defaults:o}=e;D.setProjectId(t),D.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:o}}async function KI(s){s.gridData=await og(s)}async function JI(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(Tt("user-override-file",t),s.mockNetworkRules=await Xm(s.overrideMappingFile))}async function YI(s,e){M("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:o}=s;r||(s.source=n||o?"cli-local":"cli"),await Nf(),M("in runner.js after checkNpmVersion"),await FI(s),M("in runRunner before tunnel.connect"),await ii(s),M("in runRunner after tunnel.connect");let a=await new Da(e).run(s);return M("before tunnel.disconnect"),await ai(s),await eR(s.slotService,t,s.company.companyId),M("after tunnel.disconnect and gridService.keepAlive.end"),a}function QI(s){var e;kt.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
|
|
408
|
+
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Hy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var la,ua,Ky=w(()=>{"use strict";la=require("url");le();ua=class extends V{async updateBaseUrl(e){let t=new la.URL(e),r=new la.URL(this.context.recordedBaseUrl),n=new la.URL(this.context.baseUrl);return t.host===r.host&&r.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var pa,Jy=w(()=>{"use strict";le();B();pa=class extends V{async performAction(){await oe(this.step.durationMS||0)}}});var da,Yy=w(()=>{"use strict";le();da=class extends V{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Bn,Xy=w(()=>{"use strict";le();Bn=class extends V{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(r,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t,apiCallAsync:r}=this.sessionPlayerInit;return typeof r=="function"&&r.length===2?r(t,e):new Promise(n=>{t(e,n)})}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},o=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),i=o.result||{},a={method:t.method,status:i.status,url:t.url};return o.success?i.status===0?{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:i,resultInfo:a,shouldRetry:!1,success:!0}:{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:i.error||e.error.REQUEST_TIMED_OUT,errorType:i.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var ma,Qy=w(()=>{"use strict";le();ma=class extends V{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var Zy,dp,mp,eb=w(()=>{"use strict";Zy=E(require("@applitools/spec-driver-webdriverio"));Zn();Te();dp=class{constructor(){let{EyeSdkBuilder:e}=te(),t=Yp["@applitools/eyes-sdk-core"]||"N/A",{makeSDK:r}=require("@applitools/eyes-sdk-core");this.sdk=r({name:"Testim.io",version:`4.0.1/eyes-sdk-core/${t}`,spec:Zy.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=te(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},mp=new dp});var rb,tb,jn,sb=w(()=>{"use strict";rb=E(require("lodash"));le();j();eb();tb=x("pixel-validation-step-action"),jn=class extends V{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||o,l=await mp.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},d;try{let f=await l.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};rb.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(g,i.applitoolsStepSettings),tb.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){tb.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await mp.handleApplitoolsSdkResult(this.context,d,this.step)}}});var vs,fp=w(()=>{"use strict";fs();K();Zi();vs=class extends lr{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o="",id:i=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await ms(o,i,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ne?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ur,nb=w(()=>{"use strict";fp();ur=class extends vs{isFailedResult(e){return e===!1}}});var fa,ob=w(()=>{"use strict";fp();fa=class extends vs{isFailedResult(e){return!e}}});var ga,ib=w(()=>{"use strict";fs();le();K();ga=class extends V{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await ds(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof At?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ne?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var _r,ab=w(()=>{"use strict";le();_r=class extends V{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var we,cb=w(()=>{"use strict";le();we=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var ha,lb=w(()=>{"use strict";le();ha=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var ya,ub=w(()=>{"use strict";le();ya=class extends V{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function iI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function ba(s,e){iI(aI,e),e.registerLocateStepActionUtils(Mn.getUtils(s))}var aI,gp=w(()=>{"use strict";iy();ly();by();Ty();vy();Iy();xy();Cy();Py();ky();Ly();Dy();Ny();Fy();$y();zy();Ky();Jy();Yy();Xy();Qy();sb();nb();ob();ib();ab();cb();lb();ub();aI={locate:Mn,scroll:Ki,mouse:Ji,submit:sa,text:Xi,"special-key":ea,"user-code":qt,"validation-code-step":qt,"wait-for-code-step":qt,"action-code-step":qt,"condition-step":ws,"skip-code-step":ws,"element-code-step":ws,"evaluate-expression":Yi,"text-validation":Fn,"wait-for-text-validation":Fn,"select-option":ra,"drop-file":ia,"input-file":ca,hover:na,navigation:ua,wheel:oa,sleep:pa,refresh:da,"keyboard-shortcut-step":ta,"api-validation":Bn,"api-action":Bn,"api-code-step":qt,"extract-text":ma,"simple-ui-verification":jn,"wait-for-simple-ui-verification":jn,"cli-validation-download-file":_r,"cli-wait-for-download-file":_r,"network-validation-step":_r,"cli-validation-code-step":ur,"cli-wait-for-code-step":ur,"cli-action-code-step":ur,"cli-api-code-step":ur,"cli-condition-step":fa,"node-package":ga,"email-code-step":qt,"cli-email-code-step":ur,"sfdc-internal-test-step":ya,"sfdc-recorded-step":ha,"sfdc-step-login":we,"sfdc-step-loginas":we,"sfdc-step-logout":we,"sfdc-step-sobjectcreate":we,"sfdc-step-sobjectdelete":we,"sfdc-step-findrecord":we,"sfdc-step-quickaction":we,"sfdc-step-sobjectedit":we,"sfdc-step-sobjectvalidate":we,"sfdc-step-launchapp":we,"sfdc-step-wait-for-page-load":we,"sfdc-step-closeconsoletabs":we,"sfdc-step-relatedlistaction":we,"sfdc-step-permission-validation":we,"sfdc-step-convert-lead-to-opportunity":we,"sfdc-step-quotelineeditor":we,"sfdc-document-validation":_r,"sfdc-step-sobjectverifyoptions":we}});var pb,cI,Es,hp=w(()=>{"use strict";pb=["simple-ui-verification","wait-for-simple-ui-verification"],cI=[...pb,"custom-validation","sfdc-internal-test-step","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-wait-for-page-load","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation","sfdc-step-convert-lead-to-opportunity","sfdc-step-quotelineeditor","sfdc-document-validation","sfdc-step-sobjectverifyoptions"],Es=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=cI.includes(e.stepType)?[r]:t(r);this.resetStepVariables(r,n),e.context.data.maxTotalStepTime=r}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let r=e.context.config.stepTimeout;return pb.includes(e.stepType)&&(r=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(r=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:r}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let r=Date.now()-e.startTimestamp;return t-r}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+1e3}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,r=e.step.type,n=3e4;return r==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),n)}}});var mb={};G(mb,{SeleniumTestPlayer:()=>$n});var db,lI,$n,yp=w(()=>{"use strict";B();db=require("@applitools/eyes-sdk-core");Pn();K();j();op();ty();lp();qi();ny();up();Te();gp();hp();lI=x("SeleniumTestPlayer"),$n=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new Es(zi());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=te();this.driver=n??new xr;let d=new Hi(this.driver);this.stepActionFactory=new c(d),ba(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Vi(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=sy(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new bs(this.driver),FrameLocator:m,portSelector:Gi,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:db.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=te(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(o){o instanceof ne&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){lI.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(r);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var fb={};G(fb,{WorkerSelenium:()=>bp});function pI(s){let{playback:e}=te().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>M(`Got event ${t}`))}var Ta,uI,bp,gb=w(()=>{"use strict";B();$e();Dn();j();_t();Qo();ae();sp();K();yp();Te();nt();Ta=x("worker-selenium"),uI=1e9,bp=class extends lt{initPlayer(t){return new $n(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){M("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ys(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await i.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:o,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps}),M("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),M("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,uI),await this.windowUtils.validatePageIsAvailable(),M("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof Rt||d||m?new Rt(`Page '${l}' is not available`):(Ta.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:No(),initializedFromCache:Mo()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:o}=te(),{driver:i,sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),pI(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),o.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await fn(this.options))[this.testId]);let d=async()=>ce(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(f)}),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof ne&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await o.drain(),u.stepsResults=null,u.resultId=this.testResultId,i.isAlive()||(Ta.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=i.maxKeepAliveGap();f>=3e4&&(Ta.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});i.start(),M("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),M("right after super.runTestOnce in workerSelenium");let u=await d();return M("right after runSeleniumTest"),u}catch(u){throw Ta.error("failed to run test once",{err:u}),u}}}});var hb,yb,He,dI,mI,Tp,St,wa=w(()=>{"use strict";hb=E(require("ora")),yb=E(require("jimp"));ue();Ge();he();j();ae();Te();pe();He=x("mobile-grid-service"),dI="https://tdc.tricentis-cloud.com",mI="https://ui.headspin.io",Tp=class{constructor(){this.gridsAppIdGetter={[O.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[O.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[O.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[O.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[O.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[O.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===O.TESTIM_TDC||e===O.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e)?`${t}/lock`:""}getBaseApiUrl(e){return e===O.TESTIM_HEADSPIN?`${hd}/devices`:e===O.TESTIM_TDC?`${bd}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e.type),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await Ve({url:r,headers:n,body:o})}catch(i){throw He.debug(`error while locking device ${t}`,{error:i}),i.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):i}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e.type)}/device_id:${t}/automation-config`;try{let o=await be(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw He.error("error while getting automation config for device",{error:o,deviceId:t}),o}}async getPCloudyAuthToken(e,t,r){let n=await Bs(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,o=new URL(n);return{hostname:o.hostname,port:Number(o.port),protocol:o.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===O.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===O.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([O.BROWSERSTACK,O.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:o,gridId:i}){var a,l,c;if(t===O.TESTIM_HEADSPIN||t===O.TESTIM_TDC){let d=await Il({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===O.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===O.SAUCELABS)return e.testobject_device_name;if(t===O.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n){let{executionId:o,testId:i,testResultId:a}=e,{project:l,projectData:{type:c}={},company:{companyId:d=""}={},gridData:{gridId:m="",type:u=""}={}}=n,f=t.capabilities,h=f.platformName,g;if(u===O.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:T}=te();g=T(t.capabilities)}else g=await this.getDeviceFromAppiumCapabilities(f,t,r,h,u,l,c,d,m);let y=await this.buildRemoteResultLink(n.gridData,t.sessionId,f);return await vr(l,o,i,a,"RUNNING",{device:g,...y&&{remoteResultLink:y}}),He.info("device details updated on testResult",{testResultId:a,executionId:o,testId:i,device:g,remoteResultLink:y,gridType:u}),g}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===O.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),i=Number(o[0]),a=Number(o[1]);return{scaleFactor:e.pixelRatio,width:i,height:a}}try{let{AppiumApi:o}=te(),i=new o(t,r.sessionId,null),[a,l]=await Promise.all([i.getScreenshot(),i.getDeviceSize()]),c=Buffer.from(a,"base64"),d=await yb.default.read(c),m=d.getWidth(),u=d.getHeight();return{scaleFactor:m/l.width,width:m,height:u}}catch(o){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,o,i,a,l,c){let[d,m]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:o,projectId:i,projectType:a,companyId:l,gridId:c})]),u=this.getOsVersion(e,o);return{name:m??"",model:e.deviceModel,udid:e.udid,osVersion:u,osType:n,isVirtual:!1,...d}}async buildRemoteResultLink(e,t,r){return e.type===O.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Os}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===O.SAUCELABS?r.testobject_test_report_url:e.type===O.TESTIM_TVC?r.replayUrl:e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC?`${e.type===O.TESTIM_HEADSPIN?mI:dI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let r=(await be(`${gd}/devices`)).find(n=>n.udid===e);if(!r)throw new Error(`device ${e} not found`);return{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,geo:"local",osVersion:r.osVersion,osType:r.deviceType.toLowerCase(),scaleFactor:r.scaleFactor??0,isVirtual:r.virtual??!1,minApiVersion:r.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:o,testResultId:i}=r,a=await this.getTmaDeviceDetails(e),{project:l}=t;return await vr(l,n,o,i,"RUNNING",{device:a}),He.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,o=t.mobileApp,i=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:o,gridHost:e.host});return i?(D.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:i,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Al({gridAppId:i,gridId:e.gridId,projectId:r,gridType:n,appId:o.appId,gridHost:e.host})),i):t.getAppPathByGridType(n,e.gridId,o)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r,executionId:n,testResultId:o}){let i=await an({appId:e,projectId:t});return{appUrl:`${fe}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(fd*60))+1)*60*1e3,Math.max(md,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let a={[O.BROWSERSTACK]:{name:"Browserstack"},[O.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[O.P_CLOUDY]:{name:"pCloudy"}}[o].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,hb.default)(`uploading app to ${a} please wait..`).start();try{He.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await Rl({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),He.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:o,mobileAppId:i}){let a=t.get(i);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:o});return t.set(i,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",o,{executionId:i,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){He.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:i});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d,executionId:i,testResultId:a});n=T.appUrl,o=T.mobileApp,e.nativeApp=o}else He.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:i}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===O.BROWSERSTACK||f===O.TESTIM_TVC||f===O.P_CLOUDY;if(g){let T=t.projectData.type,R=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});R&&(He.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=g),!R&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!R&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:i})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var c,d;let{accessToken:n,user:o,host:i,key:a,type:l}=t;if(l===O.BROWSERSTACK){let m=`${Os}/recent_apps`,u=await this.fetchWithUserAndPasswordAuth({url:m,user:o,key:a});return Array.isArray(u)?u.some(f=>f.app_url===e):!1}if(l===O.SAUCELABS){let u=`${i.includes("eu-central-1")?Ed:vd}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:o,key:a})).items.some(h=>h.id===e)}if(l===O.TESTIM_HEADSPIN||l===O.TESTIM_TDC){let m=l===O.TESTIM_HEADSPIN?`${yd}/apps`:`${Td}/apps`;return(await this.fetchWithTokenAuth({url:m,accessToken:n,authType:"Bearer"})).apps.some(f=>f.app_id===e)}if(l===O.TESTIM_TVC){let m=`${wd}/versions/${e}/info`,u=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:m,accessToken:u,authType:"Upload-Token"}),!0}catch(f){return f.status!==404&&He.error("error while verifying app exists on TVC",{error:f}),!1}}if(l===O.P_CLOUDY){let m=await this.getPCloudyAuthToken(i,o,a),u=`https://${i}/api/drive`,f=await uc({url:u,body:{token:m,filter:"all"},headers:{contentType:null}});return(d=(c=JSON.parse(f).result)==null?void 0:c.files)==null?void 0:d.some(g=>g.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await be(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r}){let n={Authorization:`${r} ${t}`};return await be(e,void 0,n)}},St=new Tp});function bb({nativeAppMetadata:s,appPath:e,gridInfo:t}){if(!s&&!e||!s)throw Error("Application not specified. Please provide the required application for execution and try again.");if(!s.id&&!s.activity&&!s.packageName)throw Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");if(t.mode!=="local"&&!fI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function gI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==O.TESTIM_TDC&&e.type!==O.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function hI(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,o=[{executionId:t},{testResultId:r}];return e&&o.push({testName:e}),n&&o.push({customTag:n}),o}function yI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===O.TESTIM_TDC,a=s===O.TESTIM_HEADSPIN,l=i?"tdc":"headspin",c=a&&D.flags.enableBatchHeadSpin.isEnabled(),d=i&&(D.flags.enableBatchTDC.isEnabled()||D.flags.headSpinTdcEnableFlagCapability.isEnabled());return{[`${l}:capture`]:!0,...D.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...o&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:hI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n}}}function va(s){return"id"in s?s.id:s.packageName}function bI(s,e){return{[`${e===O.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function TI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:o}){let{fullReset:i,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=bI(n,t.gridData.type));let m=()=>i===void 0&&n?!0:typeof i=="string"?i!=="false":i;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":va(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!i,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...o&&{"appium:appWaitActivity":`${o}, *`},...r&&{"appium:appPackage":va(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Lr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:o=""}){switch(s){case"ios":return{platformName:"iOS",[`${o}autoAcceptAlerts`]:!0,[`${o}automationName`]:"XCUITest",[`${o}fullReset`]:!0,...t&&{[`${o}bundleId`]:va(t)},...r&&{[`${o}app`]:r},...e};case"android":return{platformName:"Android",[`${o}autoGrantPermissions`]:!0,[`${o}automationName`]:"UiAutomator2",...n&&{[`${o}appWaitActivity`]:`${n}, *`},...t&&{[`${o}appPackage`]:va(t),[`${o}appActivity`]:t.activity??".*"},...r&&{[`${o}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Tb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=yI(i.type,o,n);return TI({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Sa({osVersion:s,mobileConfig:e}){let{staticAllocation:t,dynamicAllocation:r}=e;return s||(t!=null&&t.osVersion?t==null?void 0:t.osVersion:r!=null&&r.osVersionRegex?r==null?void 0:r.osVersionRegex:".*")}function Ia({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o}=e,i=r===O.P_CLOUDY;return s||(n!=null&&n.deviceName?i?n.deviceUdid:n.deviceName:o!=null&&o.deviceNameRegex?t==="android"&&o.deviceNameRegex===".*"&&i?Ka:o.deviceNameRegex:t==="ios"&&r===O.BROWSERSTACK?"iPhone.*":i?t==="ios"?"apple":Ka:".*")}function wI(s,e){let{androidToken:t,iosToken:r}=s,n=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(n&&!r)throw Error("missing ios token for testim virtual cloud");if(!n&&!t)throw Error("missing android token for testim virtual cloud");return n?r:t}function vI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Ea(s,Ss)}}function wb(s,e,t){return s?Object.entries(s).reduce((r,[n,o])=>{if(e(n)){if(!t)return r[n]=o,r;let i=n.replace(t,"");r[i]=o}return r},{}):{}}function EI(s){return wb(s,e=>e.startsWith("browserstack."),"browserstack.")}function SI(s){return wb(s,e=>!e.startsWith("browserstack."))}function vb(s){return!s||!Eb(s)?"2.0.0":s}function Eb(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Sb({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,o=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,i=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&o.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&i.test(s),d=l||c;if(t){let m=Eb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Ea(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let o=`${e}${r}`;t[o]=n}),t}function II({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=wI(o,s),f=Sa({osVersion:l,mobileConfig:d}),h=Ia({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),g=qe(n.editorUrl,n.project,i.testId,i.testResultId,i.branch),y={device:h,os_version:f,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:externalUrl":g,"waldo:options":{token:u}};return Lr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function RI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=o,h=D.flags.enableAppium2pCloudy.isEnabled(),g=Sa({osVersion:l,mobileConfig:d}),y=Ia({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),R={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:i.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...R,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Sd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=vI(b)),t="",Lr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Ss}})}function AI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=Sa({osVersion:l,mobileConfig:d}),f=Ia({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Or.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],Sb({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},R={user:o.user,key:o.key,name:i.testResultId,build:i.executionId,appiumVersion:vb(g.appiumVersion),deviceName:f,tags:Object.values(i)},b={"appium:platformVersion":u,"appium:deviceName":f,...Ea(h,Ss),"sauce:options":{...T,...R,...(0,Or.omit)(g,"appiumVersion")}};return Lr({projectType:s,sessionCaps:b,appiumPrefix:Ss,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":o.user,"saucelabs.key":o.key,platformVersion:u,deviceName:f,tags:Object.values(i),name:i.testResultId,build:i.executionId,...h,...g};return Lr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function xI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=Sa({osVersion:l,mobileConfig:d}),f=Ia({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=EI(n.browserstack),g=(0,Or.omit)(SI(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:R}=n.browserstack||{};if(Sb({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let v={userName:o.user,accessKey:o.key,appiumVersion:vb(h.appiumVersion),projectName:y||i.project,buildName:T||i.executionId,debug:!0,networkLogs:!0},I={"appium:platformVersion":u,"appium:deviceName":f,...Ea(g,Ss),"bstack:options":{...v,...(0,Or.omit)(h,"appiumVersion")}};return Lr({projectType:s,sessionCaps:I,appiumPrefix:Ss,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let b={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:R||i.testResultId,project:y||i.project,build:T||i.executionId,buildTags:Object.values(i).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,...Ea(h,"browserstack.")};return Lr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function CI(s){if(O.TESTIM_TDC===s.gridInfo.type||O.TESTIM_HEADSPIN===s.gridInfo.type)return Tb(s);if(O.TESTIM_TVC===s.gridInfo.type)return II(s);if(O.P_CLOUDY===s.gridInfo.type)return RI(s);if(O.SAUCELABS===s.gridInfo.type)return AI(s);if(O.BROWSERSTACK===s.gridInfo.type)return xI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function PI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:o,osVersion:i,deviceUdid:a}=s,l={};return n==="dynamic"&&(!o&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!i&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),o&&(l.manufacturer=o),i&&(l.os_version=i),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}function Ib(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:o}=s,{selectedGrid:i}=(o==null?void 0:o.mobile)||{};if(o!=null&&o.mobile&&(i==null?void 0:i.type)!==e.type)throw Error(`selected grid type ${i.type} is not equal to grid type ${e.type}`);bb({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=St.getGridConnection(e),l=CI(s);if(e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC){let d=e.type===O.TESTIM_HEADSPIN?"headspin":"tdc",m=PI(r,o==null?void 0:o.mobile);if(!(0,Or.isEmpty)(m)){let u=Object.entries(m).map(([f,h])=>h.split(",").map(g=>g===".*"||g==="="?"":`${f}:${g}`).join(",")).join(" ").trim();l[`${d}:selector`]=u}}let c=e.type===O.TESTIM_TVC?{alwaysMatch:l}:l;return{...a,desiredCapabilities:l,capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function Rb(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;bb({nativeAppMetadata:r,appPath:o,gridInfo:t}),gI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((g=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await St.getGridDirectConnection(t,d),f=Tb({projectType:e,nativeAppMetadata:r,appPath:o,androidActivityWait:i,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Ab(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s;return Lr({projectType:e,sessionCaps:{},nativeAppMetadata:t,appPath:r,androidActivityWait:n})}function xb(s){var t,r;let e={...s};return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],(t=e.capabilities["sauce:options"])==null||delete t.user,(r=e.capabilities["sauce:options"])==null||delete r.key,delete e.capabilities.key,delete e.capabilities.user,e}var Or,Ss,fI,wp=w(()=>{"use strict";pe();ae();wa();Or=require("lodash");B();ue();Ss="appium:",fI=[O.BROWSERSTACK,O.SAUCELABS,O.TESTIM_HEADSPIN,O.TESTIM_TDC,O.TESTIM_TVC,O.P_CLOUDY]});var Ra,Pb=w(()=>{"use strict";Ra=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 _b,kb,Aa,Ob=w(()=>{"use strict";_b=require("linkedom"),kb=new _b.DOMParser,Aa=class{constructor(e){this.driver=e;this._abortedSteps=[]}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}unescapeHTML(e){return kb.parseFromString(`<html><body>${e}</body></html>`,"text/html").documentElement.textContent}getLinksFromUnescapeHTML(e){return[...kb.parseFromString(`<html><body>${e}</body></html>`,"text/html").getElementsByTagName("a")].map(r=>r.href).filter(Boolean)}}});var vp,xa,Lb=w(()=>{"use strict";j();vp=x("mobile-frame-locator-mock"),xa=class{foundFrameCallback(){return vp.info("foundFrameCallback-mock invoked"),{}}locate(){return vp.info("locate-mock invoked"),{}}async findFrame(){return vp.info("findFrame-mock invoked"),{}}}});var kI,Nb,Db,Is,Ep=w(()=>{"use strict";kI=E(require("webdriverio")),Nb=require("@applitools/eyes-sdk-core");Pb();lp();j();Ob();up();Te();gp();Lb();hp();Db=x("appium-test-player"),Is=class{constructor(e,t,r,n=kI,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=te(),m=new Aa(this.driver);this.stepActionFactory=new c(m),ba(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Es(zi()),this.sessionPlayer=new a(e,{tabService:new Ra,cookieUtils:void 0,FrameLocator:xa,portSelector:Gi,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Nb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,o={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Db.info("appium session deleted",{...o}))}catch(i){Db.error("error while deleting appium session",{...o,error:i})}finally{let{commonConstants:i}=te();e.off(i.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function _I(s){return await be(`${s}/api/status`)}async function Mb(s,e){return await be(`${s}/api/devices/${e}/status`)}async function Ub(s){if((await _I(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Fb=w(()=>{"use strict";Ge()});var Bb={};G(Bb,{WorkerLocalTma:()=>Ap});var Ca,Sp,Ip,Rp,Ap,jb=w(()=>{"use strict";Ge();wp();Dn();B();j();_t();Ep();Te();Fb();wa();Ca=x("worker-appium"),Sp=class extends Error{},Ip=class extends Error{},Rp=class extends Error{},Ap=class extends lt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=te(),{DOMParser:n}=await import("linkedom"),o=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=o,o}async getBrowserOnce(t,r,n,o){var I;if(Q.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:i,deviceUdid:a,projectData:l}=this.options;await Ub(i);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{executionId:C,testResultId:_}=t,{mobileApp:$}=await St.getMobileAppDataByAppId({appId:f,projectId:c,token:d,executionId:C,testResultId:_});t.nativeApp=$}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:R,version:b},v]=await Promise.all([this.getAppStateFromDevice(i,a,T),Mb(i,a)]).catch(C=>{throw this.handleDeviceNotFoundError(C),C});if(!R&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!R&&y&&await this.installApp(i,a,y);try{let C={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(I=this.options.projectData)==null?void 0:I.name}-${this.options.project}`},_=Ab({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:C,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),$={capabilities:{udid:a,..._}},A=await this.requestNewAppiumSessionFromTma(i,$,g);this.sessionData=A;let S=await m.attach({sessionId:A.sessionId,capabilities:_});this.device=await St.updateTmaDeviceDetails(a,this.options,t),Ca.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:S.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:S.capabilities})}catch(C){throw Ca.error("failed to start application",{err:C}),C}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await Ve({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new Rp(l):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,l=(await be(i)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var o,i;try{let a=await Mt(n);await Fs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new Ip(c,{cause:a})}}handleDeviceNotFoundError(t){var n,o;let r=(o=(n=t.response)==null?void 0:n.body)==null?void 0:o.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Sp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=te(),{sessionPlayer:i}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),o.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{i.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await o.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Ca.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Ca.error("failed to run test once",{err:c}),c}}}});var Wb={};G(Wb,{WorkerAppium:()=>xp});var $b,Dr,xp,Vb=w(()=>{"use strict";wp();$b=require("linkedom");Dn();j();_t();Ep();Te();wa();ae();is();Dr=x("worker-appium"),xp=class extends lt{initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,l=await St.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),c=a==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let m={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.id}`},u={projectType:a,nativeAppMetadata:d,appPath:l,androidActivityWait:c,sessionTags:m,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig},f;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await St.lockDevice(o,this.options.deviceUdid),f=await Rb(u)):f=Ib(u),Dr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:xb(f)});let h=this.getServerAddressFromGrid();this.activeSession=await i.remote(f),this.device=await St.updateDeviceOnRemoteTestResult(t,this.activeSession,h,this.options);let g=`${h}/session/${this.activeSession.sessionId}`;this.updateSlotData(g),Dr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Dr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}async startKeepAlive(t){let r=async()=>{try{await(t==null?void 0:t.getOrientation())}catch(n){Dr.error("failed to keep appium session alive",{err:n})}};this.keepAliveIndex=setInterval(r,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&pg(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:t},this.id)}catch(r){Dr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===O.TESTIM_HEADSPIN||o===O.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:o===O.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:o,directConnectPath:i}=t;if(r&&n&&o&&i)return`${r}://${n}:${o}${i}`}async runTestOnce(t,r){var u,f;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=te(),{sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let c;if(this.options.skipLoadBalancer){let h=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:g,hostname:y,port:T,path:R}=await St.getHeadSpinDeviceConnection(this.options.gridData,h);c=`${g}://${y}:${T}${R}`}else c=this.getDirectAddressConnection(this.activeSession.capabilities)||this.getServerAddressFromGrid();let d=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:d,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(f=this.options.company)==null?void 0:f.companyId,device:this.device},a.playbackManager.appiumApi=new o(c,this.activeSession.sessionId,$b.DOMParser),this.startKeepAlive(a.playbackManager.appiumApi),i.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let h=await new Promise((y,T)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:y,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(T)});return this.stopKeepAlive(),await i.drain(),h.stepsResults=null,h.resultId=this.testResultId,{...h,...t.seleniumPerfStats.getStats()}}catch(h){throw Dr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:h}),this.stopKeepAlive(),h}};try{return await super.runTestOnce(t,r),await m()}catch(h){throw Dr.error("failed to run test once",{err:h}),h}}}});var Pa,Gb=w(()=>{"use strict";B();Pn();K();Pa=class{constructor(e){this.id=e;this.driver=new xr}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof ne&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Hb,ka,qb=w(()=>{"use strict";Hb=E(require("ws"));B();ka=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 Hb.default(this._cdpUrl,{timeout:e}),r=Yt(o=>{t.once("open",o)}),n=Yt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let o=this._lastWsId++,i=new Promise((l,c)=>{this._cdpCallbacks.set(o,{resolve:l,reject:c})}),a={method:e,params:t,id:o};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),i}}});var Oa,Cp,_a,zb=w(()=>{"use strict";B();Oa=E(require("chrome-launcher"));Mu();qb();un();Cp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new ka}async init(e){var f,h,g,y;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c}=e,d=xi({browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c}),m=[...((f=d.desiredCapabilities)==null?void 0:f.chromeOptions.args)??[],...((y=(g=(h=d.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:g["goog:chromeOptions"])==null?void 0:y.args)??[],...Oa.Launcher.defaultFlags().filter(T=>T!=="--disable-extensions")];this.chrome=await Oa.launch({chromeFlags:m,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 u=await yr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(u),es(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},_a=class{constructor(e){this.id=e;this.sessionId=se();this.driver=new Cp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Jb={};G(Jb,{WorkerExtension:()=>Wn});function OI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Kb(s){return OI(s)?s:new Error(s)}var ut,Wn,Pp=w(()=>{"use strict";$e();K();Dn();B();j();_t();ae();Gb();zb();nt();ut=x("worker-ext"),Wn=class extends lt{initPlayer(){return this.options.useChromeLauncher?new _a(this.id):new Pa(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(i=this.options.lightweightMode)==null?void 0:i.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps})}catch(a){throw ut.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:No(),initializedFromCache:Mo(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var o;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((o=this.options.browserstack)!=null&&o["browserstack.user"])){let i={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(i)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:o}=this;M("WorkerExtension runTestOnce");let i=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ce(e.runTestUsingCDP(d.cdpTestRunner),m,Ue.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ne))throw u;return ut.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw ut.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:o,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(M("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw ut.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Ue.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof ne))throw T;ut.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),ut.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),T.type=$s.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=ce(e.onCompleted(),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG),R=await oc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(R.success),R.reason)}catch(I){ut.error("Could not update the grid about the test status",{err:I})}m.isAlive()||(ut.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),R.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(ut.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),R.keepAliveIssue=b),{...R,...e.seleniumPerfStats.getStats()}}catch(T){throw ut.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:o}),Kb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw ut.warn("failed to start url",{err:h}),Kb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),M("WorkerExtension super.runTestOnce"),await c()}catch(d){throw ut.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Yb={};G(Yb,{WorkerExtensionSingleBrowser:()=>kp});var LI,DI,kp,Xb=w(()=>{"use strict";$e();B();j();Qu();_t();Pp();LI=x("base-worker"),DI=500,kp=class extends Wn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await On(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,o){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,o)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(LI.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let o=this.handleQuarantine(t);if(o)return o;M("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await oe(DI)}}});function NI(s,e){e===0?s():setTimeout(s,e*ad)}var _p,La,Qb=w(()=>{"use strict";Pn();ue();$e();Ru();nt();$u();K();j();ae();Wh();_p=x("parallel-worker-manager"),La=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Z.SELENIUM:return(gb(),ye(fb)).WorkerSelenium;case Z.APPIUM:return e.localTmaUrl?(jb(),ye(Bb)).WorkerLocalTma:(Vb(),ye(Wb)).WorkerAppium;default:return Pi.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Xb(),ye(Yb)).WorkerExtensionSingleBrowser:(Pp(),ye(Jb)).WorkerExtension}}createWorkers(e,t,...r){let n=r[0],o=this.getWorkerType(n),i=()=>{try{return M("before new Worker",n.mode),new o(t,...r)}finally{M("after new Worker",n.mode)}};return Array.from(new Array(e),i)}async runTests(e,t,r,n,o,i,a,l,c){if(e&&e.length===0)return;let d=!1,m=0,u=(f,h)=>new Promise(g=>{var dr,k,N,F,z,dt,Fa,Wp;let y=o.project,T=new Mi(r,n,e,o,i,t),R={},b=e.length,v=((dr=o.company)==null?void 0:dr.ucid)||"",I=(k=o.company)==null?void 0:k.companyId,C=(N=o.company)==null?void 0:N.name,_=o.source||"cli",$=o.user,A=(F=o.company)==null?void 0:F.planType,S=(z=o.company)==null?void 0:z.isStartUp,L=(dt=o.projectData)==null?void 0:dt.name,U=(Fa=o.projectData)==null?void 0:Fa.type,q=o.lightweightMode,H=(Wp=o.gridData)==null?void 0:Wp.type,Y=(Lt,mt,ve,Ba,Gn,ja)=>(m++,Rg({executionId:r,projectId:y,testId:mt,resultId:ve,ucid:v,companyId:I,companyName:C,projectName:L,companyPlan:A,source:_,user:$,lightweightMode:q,isStartUp:S,projectType:U,appSource:ja,gridType:H}),t.testStartAndReport(Lt,r,ve,Ba,Gn)),me=async(Lt,mt,ve,Ba,Gn,ja)=>{var Vp,Gp,Hp;m--;let et={...(q==null?void 0:q.onlyTestIdsNoSuite)&&{show:!0},...ve.seleniumStats&&{seleniumStats:ve.seleniumStats},...ve.gridIssues&&{gridIssues:ve.gridIssues},...ve.keepAliveIssue&&{keepAliveIssue:ve.keepAliveIssue},...o.host&&{gridHost:o.host}};if(ve.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ve.seleniumPerfMarks),delete ve.seleniumPerfMarks),o.grid||o.gridId?(et.gridName=o.grid||((Vp=o.gridData)==null?void 0:Vp.name),et.gridType=(Gp=o.gridData)==null?void 0:Gp.type,et.gridProvider=(Hp=o.gridData)==null?void 0:Hp.provider):o.localTmaUrl?(et.gridName="local-tma-from-options",et.gridType="local-tma"):o.useLocalChromeDriver?(et.gridName="local-chrome-driver-from-options",et.gridType="local-chrome"):o.useChromeLauncher?(et.gridName="chrome-launcher-from-options",et.gridType="local-chrome"):o.browserstack?et.gridName="browserstack-from-options":o.saucelabs&&(et.gridName="saucelabs-from-options"),await t.testEndAndReport(Lt,ve,r,Ba,Gn,et).catch(kT=>_p.error("testEndAndReport threw an error",{err:kT})),Gn)return;R[ve.resultId]=ve,Ag({executionId:r,projectId:y,testId:mt,resultId:ve.resultId,result:ve,ucid:v,companyId:I,companyName:C,projectName:L,companyPlan:A,source:_,user:$,lightweightMode:q,logger:_p,isStartUp:S,projectType:U,appSource:ja}),c&&!ve.success&&(T.stop(),d=!0),(Object.keys(R).length===b||d&&m===0)&&g(R)},pt=(Lt,mt)=>{R[mt.resultId]=mt,t.onTestIgnored(Lt,mt.resultId),m--,(Object.keys(R).length===b||d&&m===0)&&g(R)},It=(Lt,mt)=>t.onGridSlot(Lt,mt);o.userData={loginData:{...jt(),refreshToken:Lo(),authData:jt(),token:f,userAccessKey:h},projectId:o.project,company:o.company,servicesUrl:fe},M("in localStrategy before createWorker"),this.createWorkers(l,T,o,this.customExtensionLocalLocation,r,Y,me,It,pt).forEach((Lt,mt)=>{M("before schedule worker.run after createWorkers"),NI(()=>{M("right before worker.run"),Lt.run()},mt)})});try{let f=await Zt(),h=await Do(),g=await u(f,h);if(d)throw new Kt;return g}catch(f){throw _p.error("failed running parallel workers",{executionId:r,err:f}),f}}}});async function eT(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:se()}))]}:await sl({projectId:s.project,labels:s.label,testIds:s.testId,testNames:s.name,testConfigNames:s.testConfigNames,suiteNames:s.suites,suiteIds:s.suiteIds,branch:e,rerunFailedByRunId:s.rerunFailedByRunId,testConfigIds:s.testConfigIds,intersections:s.intersections})}function Op(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function Lp(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=Zb.difference(Ws(s,e),t);if(r.length>0)throw Tt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new P(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Zb,tT=w(()=>{"use strict";Zb=E(require("lodash"));B();ts();he();K()});var Vn,fD,Dp,Np,Da,rT=w(()=>{"use strict";Vn=E(require("lodash"));B();j();ue();ae();$e();ns();cu();Ru();he();nt();_t();zg();K();Qb();tT();({testRunStatus:fD,CLI_MODE:Dp}=Ut),Np=x("test-plan-runner"),Da=class{constructor(e){this.startTime=Date.now();this.workerManager=new La(e)}async runTestAllPhases(e,t,r,n,o,i,a,l){let c={},d=jt(),m=async()=>{let g=o.beforeParallel||1,y=!0,T=await this.workerManager.runTests(e,l,i,a,o,n,d,g,y);Object.assign(c,T)},u=async()=>{let g=ro||o.parallel,y=!1;M("right before this.workerManager.runTests");let T=await this.workerManager.runTests(t,l,i,a,o,n,d,g,y);M("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=o.afterParallel||1,y=!1,T=await this.workerManager.runTests(r,l,i,a,o,n,d,g,y);Object.assign(c,T)};xg({executionId:i,projectId:o.project}),M("right before runBeforeTests");try{return await m(),M("right before runTestPlanTests"),await u(),M("right after runTestPlanTests"),await f(),c}catch(g){if(Np.error("error running test plan",{err:g}),g instanceof Kt)return l.markAllQueuedTests(i,de.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,R,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===Dp.SELENIUM){let[{getSessionPlayer:v},{makeSDK:I}]=await Promise.all([Promise.resolve().then(()=>(Te(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:C}=v();await C.closeBatch(i,I);return}let g;try{if(!((b=(R=(T=o.company)==null?void 0:T.activePlan)==null?void 0:R.premiumFeatures)!=null&&b.applitools)||(g=await Tl(o.project),Vn.default.isEmpty(g)||!i))return;let{runKey:v,url:I}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:I,apiKey:v}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,l){var b,v,I;let c=se(),d=n.project;ec(c),e.forEach(C=>Object.assign(C,{isBeforeTestPlan:!0})),r.forEach(C=>Object.assign(C,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Ai(m,n,i,a),f=Vn.default.chain(m).map(C=>{var _;return((_=C.overrideTestConfig)==null?void 0:_.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(C=>C.name),y=(v=n.lightweightMode)!=null&&v.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,o,g);M("before testListInfoPromise");let T=await y;(I=n.lightweightMode)!=null&&I.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,o,c,l,h),M("before runTestAllPhases");let R=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,o||"All Tests",u);return M("before executionEnd"),await u.executionEnd(c),M("after executionEnd"),{results:R,executionId:c,testPlanName:o,configName:h}}async runTestPlans(e,t){Np.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return Vn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await rl(i,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Dp.APPIUM&&await Lp(e,r(c)),await ie(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await ng(e,d);let f=u.overrideExecutionName||d.name;return await ie(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(I=>({executionId:I,status:Op(n[m][I])})),R=Object.keys(n[m]).map(I=>n[m][I]).reduce((I,C)=>Object.assign(I,C),{}),b=Op(R);Object.assign(o,R);let v=b?T[0].executionId:T.find(I=>!I.status).executionId;return await Zc(i,m,{success:b,executions:T,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var l;Np.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),M("before getSuite");let r=await eT(e,t);if(M("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new P("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new P("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new P("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;M("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode==="appium"&&(a=await an({appId:e.appId,projectId:e.project})),await ie(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==Dp.APPIUM&&await Lp(e,c),M("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,o,null,t,i);return M("right after runTestPlan"),await Q.onTestPlanFinished(d.results,o,this.startTime,d.executionId,i),d})}async run(e){let t=vn(),r=[];Vs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Vn.default.flattenDeep(r);return M("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),M("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var iT={};G(iT,{init:()=>rR,run:()=>XI});async function MI(s){let e=s.project,t=await nl(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"),pn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ls}function UI(s,e){var i,a,l,c,d,m,u,f;let t=ho(e.activePlan),r=s.parallel;if(t==="free"&&r>nT)throw new P(`The free plan allows only ${nT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let h=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!h)throw new P("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let g=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.runInTurboMode;s.lightweightMode&&!g&&(console.warn(`
|
|
409
|
+
Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((d=s.gridData)==null?void 0:d.type)===O.TESTIM_TVC){let h=e.tvcLicense.expireAt||1;if(Date.now()>h)throw new P("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let g=Number(e.tvcLicense.maxParallel);if(r>g)throw new P(`Your license allows only ${g} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((m=s.gridData)==null?void 0:m.type)===O.TESTIM_TDC){let h=e.tdcLicense.expireAt||1;if(Date.now()>h)throw new P("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted")}let n=s.retentionDays;if(!n)return;let o=(f=(u=e.activePlan)==null?void 0:u.premiumFeatures)==null?void 0:f.resultRetention;if(n>o)throw new P(`Retention days (${n}) cannot be greater than the company's retention days (${o}). Run aborted`)}async function FI(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await MI(s)}catch(t){if([P,Ls].some(r=>t instanceof r))throw t;Mp.error("could not validate cli account",{err:t})}}function BI(s){let e=jt();return uf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function jI(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(D.flags.useNewWSCLI.isEnabled()&&!e&&!t)return vt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(Li(),Oh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(Di(),Nh));r.init(s)}}function $I(s,e){let{branch:t,autoDetect:r}=s;if(dg(e,r),!e&&!r)throw new P(`branch ${t} does not exist, run aborted.`)}async function WI(s,e){let{id:t,type:r}=e,o=oT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&D.flags.sfdcHybridCompany.isEnabled(),i=vn();o&&(s.sfdcCredential=await Xc({projectId:t,branch:i}))}function VI(s,e){let{id:t,storageBaseUrl:r,storageType:n,name:o,activePlan:i={}}=e,a=Boolean(i.isPoc),l=Boolean(i.isStartUp),c=ho(i);c==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<sT?sT:s.newBrowserWaitTimeout),D.setCompanyId(t),D.setIsPOC(a),D.setIsStartUp(l),D.setPlanType(c),kt.setPlanType(c),s.company={ucid:"",companyId:t,storageBaseUrl:r,storageType:n,name:o,planType:c,isPOC:a,isStartUp:l,activePlan:i}}function GI(s,e){s.editorUrl=_s||e.editorUrl}function HI(s,e){s.allGrids=e}function qI(s,e){s.authData=e}function zI(s,e){let{id:t,name:r,type:n,defaults:o}=e;D.setProjectId(t),D.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:o}}async function KI(s){var e;s.gridData=await og(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}async function JI(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(Tt("user-override-file",t),s.mockNetworkRules=await Xm(s.overrideMappingFile))}async function YI(s,e){M("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:o}=s;r||(s.source=n||o?"cli-local":"cli"),await Nf(),M("in runner.js after checkNpmVersion"),await FI(s),M("in runRunner before tunnel.connect"),await ii(s),M("in runRunner after tunnel.connect");let a=await new Da(e).run(s);return M("before tunnel.disconnect"),await ai(s),await eR(s.slotService,t,s.company.companyId),M("after tunnel.disconnect and gridService.keepAlive.end"),a}function QI(s){var e;kt.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
|
|
410
410
|
\x1B[4m\x1B[36mOur Free grid offers basic service performance.
|
|
411
411
|
If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m
|
|
412
412
|
`)}function ZI(s,e,t){s==="redis"&&Tn.start(t,e),s==="mongo"&&yn.start(e)}async function eR(s,e,t){s==="redis"&&await Tn.end(t,e),s==="mongo"&&await yn.end(e)}function tR(s,e){var o,i,a,l,c,d;let t=D.flags.redisSlotManager.isEnabled(),r=((o=s.projectData)==null?void 0:o.type)==="ios"||((i=s.projectData)==null?void 0:i.type)==="android",n=t&&r;if(e.followL2CPlan){let m=(l=(a=e.l2cLicense)==null?void 0:a.shadowCatalogId)==null?void 0:l.includes("testim_mobile"),u=!!((c=e.tvcLicense)!=null&&c.maxParallel);n&&u&&m&&(s.slotService="redis")}!e.followL2CPlan&&n&&((d=e.mobile)!=null&&d.maxParallel)&&(s.slotService="redis")}async function rR(s){var h,g,y;M("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:o}=s,i=jI(e,{disableResults:o||Boolean((t==null?void 0:t.disableResults)&&(r||n!=="extension")),disableRemoteStep:o||Boolean(t==null?void 0:t.disableRemoteStep)});i.catch(()=>{});let{authData:a,editorConfig:l,companyByProjectId:c,projectById:d,branchName:m,allGrids:u}=await cn(s);if(s.printGrids){let T=u.sort((R,b)=>R.type.localeCompare(b.type));console.table(T.reduce((R,b)=>{class v{constructor(_,$){this.Type=_,this.Browsers=$}}let I=Object.entries(b.browsers||{"N/A":""}).map(C=>C.join(":")).join(", ");return R[b.name]=new v(b.type,I),R},{})),process.exit(0)}if(await i,M("after featureFlagsReady and socketConnected"),GI(s,l),VI(s,c),zI(s,d),$I(s,m),HI(s,u),qI(s,a),await WI(s,d),await KI(s),UI(s,c),tR(s,c),D.flags.clearRunnerFileCache.isEnabled())try{await Kr(),Mp.info("runner file cache cleared")}catch(T){Mp.error("failed to clear runner file cache",{err:T})}(h=s.lightweightMode)!=null&&h.disableLabs||await Pi.loadLabFeatures(d.id,c.activePlan),((g=s.lightweightMode)==null?void 0:g.type)==="turboMode"&&(D.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&console.log(`
|