@testim/testim-cli 4.92.0 → 4.94.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 +4 -4
- package/cli.js.map +3 -3
- package/npm-shrinkwrap.json +26 -374
- 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.16.10",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:"
|
|
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.16.10",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,7 +13,7 @@ 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}
|
|
@@ -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,7 +405,7 @@ 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(`
|
|
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
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(`
|
|
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
|