@testim/testim-cli 4.82.0 → 4.84.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 +2 -2
- package/npm-shrinkwrap.json +215 -240
- package/package.json +13 -9
package/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#! /usr/bin/env node
|
|
2
|
-
"use strict";var qT=Object.create;var Kn=Object.defineProperty;var zT=Object.getOwnPropertyDescriptor;var KT=Object.getOwnPropertyNames;var JT=Object.getPrototypeOf,YT=Object.prototype.hasOwnProperty;var T=(s,e)=>()=>(s&&(e=s(s=0)),e);var G=(s,e)=>{for(var t in e)Kn(s,t,{get:e[t],enumerable:!0})},Jp=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of KT(e))!YT.call(s,n)&&n!==t&&Kn(s,n,{get:()=>e[n],enumerable:!(r=zT(e,n))||r.enumerable});return s};var E=(s,e,t)=>(t=s!=null?qT(JT(s)):{},Jp(e||!s||!s.__esModule?Kn(t,"default",{value:s,enumerable:!0}):t,s)),ye=s=>Jp(Kn({},"__esModule",{value:!0}),s);var We={};G(We,{log:()=>M,measure:()=>QT});function M(...s){if(!Qp)return;let e=Date.now();console.log(`${e-XT} ${e-Xp} `,...s),Xp=e}function QT(s,e){if(!Qp)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var Qp,XT,Xp,Ve=T(()=>{"use strict";Qp=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,XT=Date.now(),Xp=Date.now()});var Ga,zt,Ha,Mr=T(()=>{"use strict";Ga={NULL:"\uE000",Unidentified:"\uE000",Cancel:"\uE001",Help:"\uE002","Back space":"\uE003",Backspace:"\uE003",Tab:"\uE004",Clear:"\uE005",Return:"\uE006",Enter:"\uE007",Shift:"\uE008",Control:"\uE009",Alt:"\uE00A",Pause:"\uE00B",Escape:"\uE00C",Space:"\uE00D"," ":"\uE00D",Pageup:"\uE00E",PageUp:"\uE00E",Page_Up:"\uE00E",Pagedown:"\uE00F",PageDown:"\uE00F",Page_Down:"\uE00F",End:"\uE010",Home:"\uE011","Left arrow":"\uE012",Arrow_Left:"\uE012",ArrowLeft:"\uE012","Up arrow":"\uE013",Arrow_Up:"\uE013",ArrowUp:"\uE013","Right arrow":"\uE014",Arrow_Right:"\uE014",ArrowRight:"\uE014","Down arrow":"\uE015",Arrow_Down:"\uE015",ArrowDown:"\uE015",Insert:"\uE016",Delete:"\uE017",Semicolon:"\uE018",Equals:"\uE019","Numpad 0":"\uE01A","Numpad 1":"\uE01B","Numpad 2":"\uE01C","Numpad 3":"\uE01D","Numpad 4":"\uE01E","Numpad 5":"\uE01F","Numpad 6":"\uE020","Numpad 7":"\uE021","Numpad 8":"\uE022","Numpad 9":"\uE023",Multiply:"\uE024",Add:"\uE025",Separator:"\uE026",Subtract:"\uE027",Decimal:"\uE028",Divide:"\uE029",F1:"\uE031",F2:"\uE032",F3:"\uE033",F4:"\uE034",F5:"\uE035",F6:"\uE036",F7:"\uE037",F8:"\uE038",F9:"\uE039",F10:"\uE03A",F11:"\uE03B",F12:"\uE03C",Command:"\uE03D",Meta:"\uE03D",Zenkaku_Hankaku:"\uE040",ZenkakuHankaku:"\uE040"},zt="element-6066-11e4-a52e-4f735466cecf",Ha=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 ze(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 qa(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function Oe(s){let e=/^(https?:\/\/)/i,t=new RegExp("^(?:(?:(?:https?|ftp):)?\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u00a1-\\uffff][a-z0-9\\u00a1-\\uffff_-]{0,62})?[a-z0-9\\u00a1-\\uffff]\\.)+(?:[a-z\\u00a1-\\uffff]{2,}\\.?))(?::\\d{2,5})?(?:[/?#]\\S*)?$","i");return e.test(s)||t.test(s)}var za=T(()=>{"use strict"});var Ja,Zp,ed,ro=T(()=>{Ja={ngrok:"4.3.3",webpack:"5.74.0",playwright:"0.12.1",puppeteer:"2.1.1","selenium-webdriver":"3.6.0","v8-to-istanbul":"9.1.0","istanbul-lib-coverage":"3.2.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"1.4.5-lts.1"},Zp={"@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.17.3",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:"
|
|
2
|
+
"use strict";var qT=Object.create;var Kn=Object.defineProperty;var zT=Object.getOwnPropertyDescriptor;var KT=Object.getOwnPropertyNames;var JT=Object.getPrototypeOf,YT=Object.prototype.hasOwnProperty;var T=(s,e)=>()=>(s&&(e=s(s=0)),e);var G=(s,e)=>{for(var t in e)Kn(s,t,{get:e[t],enumerable:!0})},Jp=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of KT(e))!YT.call(s,n)&&n!==t&&Kn(s,n,{get:()=>e[n],enumerable:!(r=zT(e,n))||r.enumerable});return s};var E=(s,e,t)=>(t=s!=null?qT(JT(s)):{},Jp(e||!s||!s.__esModule?Kn(t,"default",{value:s,enumerable:!0}):t,s)),ye=s=>Jp(Kn({},"__esModule",{value:!0}),s);var We={};G(We,{log:()=>M,measure:()=>QT});function M(...s){if(!Qp)return;let e=Date.now();console.log(`${e-XT} ${e-Xp} `,...s),Xp=e}function QT(s,e){if(!Qp)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var Qp,XT,Xp,Ve=T(()=>{"use strict";Qp=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,XT=Date.now(),Xp=Date.now()});var Ga,zt,Ha,Mr=T(()=>{"use strict";Ga={NULL:"\uE000",Unidentified:"\uE000",Cancel:"\uE001",Help:"\uE002","Back space":"\uE003",Backspace:"\uE003",Tab:"\uE004",Clear:"\uE005",Return:"\uE006",Enter:"\uE007",Shift:"\uE008",Control:"\uE009",Alt:"\uE00A",Pause:"\uE00B",Escape:"\uE00C",Space:"\uE00D"," ":"\uE00D",Pageup:"\uE00E",PageUp:"\uE00E",Page_Up:"\uE00E",Pagedown:"\uE00F",PageDown:"\uE00F",Page_Down:"\uE00F",End:"\uE010",Home:"\uE011","Left arrow":"\uE012",Arrow_Left:"\uE012",ArrowLeft:"\uE012","Up arrow":"\uE013",Arrow_Up:"\uE013",ArrowUp:"\uE013","Right arrow":"\uE014",Arrow_Right:"\uE014",ArrowRight:"\uE014","Down arrow":"\uE015",Arrow_Down:"\uE015",ArrowDown:"\uE015",Insert:"\uE016",Delete:"\uE017",Semicolon:"\uE018",Equals:"\uE019","Numpad 0":"\uE01A","Numpad 1":"\uE01B","Numpad 2":"\uE01C","Numpad 3":"\uE01D","Numpad 4":"\uE01E","Numpad 5":"\uE01F","Numpad 6":"\uE020","Numpad 7":"\uE021","Numpad 8":"\uE022","Numpad 9":"\uE023",Multiply:"\uE024",Add:"\uE025",Separator:"\uE026",Subtract:"\uE027",Decimal:"\uE028",Divide:"\uE029",F1:"\uE031",F2:"\uE032",F3:"\uE033",F4:"\uE034",F5:"\uE035",F6:"\uE036",F7:"\uE037",F8:"\uE038",F9:"\uE039",F10:"\uE03A",F11:"\uE03B",F12:"\uE03C",Command:"\uE03D",Meta:"\uE03D",Zenkaku_Hankaku:"\uE040",ZenkakuHankaku:"\uE040"},zt="element-6066-11e4-a52e-4f735466cecf",Ha=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 ze(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 qa(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function Oe(s){let e=/^(https?:\/\/)/i,t=new RegExp("^(?:(?:(?:https?|ftp):)?\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u00a1-\\uffff][a-z0-9\\u00a1-\\uffff_-]{0,62})?[a-z0-9\\u00a1-\\uffff]\\.)+(?:[a-z\\u00a1-\\uffff]{2,}\\.?))(?::\\d{2,5})?(?:[/?#]\\S*)?$","i");return e.test(s)||t.test(s)}var za=T(()=>{"use strict"});var Ja,Zp,ed,ro=T(()=>{Ja={ngrok:"4.3.3",webpack:"5.74.0",playwright:"0.12.1",puppeteer:"2.1.1","selenium-webdriver":"3.6.0","v8-to-istanbul":"9.1.0","istanbul-lib-coverage":"3.2.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"1.4.5-lts.1"},Zp={"@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.17.3",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:"git+https://github.com/omril1/linkedom.git#cd031e9b299ef58ffdaaf6d9a60490bb843c8afa",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:"8.1.2","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"},ed={node:">= 18.0.0"}});var Us,td,rd,so,sd,no,Fs,nd,fe,od,id,oo,_e,Ya,ad,io,cd,qR,ld,zR,ud,pd,Ur,dd,md,fd,gd,hd,yd,bd,Td,wd,vd,Ed,Bs,Sd,Id,Rd,Xa,le=T(()=>{"use strict";Us=process.env.SERVICES_HOST||"https://services.testim.io",td="https://testimstatic.blob.core.windows.net",rd="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:Us,Us=process.env.SERVICES_HOST);so=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),sd=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),no=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),Fs=process.env.EDITOR_URL,nd=process.env.WEBSOCKET_HOST||`${Us}/ws`,fe=Us,od=parseInt(process.env.LOGGER_CONSOLE||"0",10),id=parseInt(process.env.LOGGER_DEBUG||"0",10),oo=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),_e=parseInt(process.env.IS_ON_PREM||"0",10),Ya=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,ad=parseInt(process.env.DEBUG_MODE||"0",10),io=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,cd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",qR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),ld=parseInt(process.env.START_WORKER_DELAY_MS||"1500",10),zR=process.env.APPIUM_VERSION||"1.10.1",ud=process.env.GATEWAY_URL,pd=process.env.EXTENSION_SERVICES_HOST||Us,Ur=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:td,dd=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:rd,md=td,fd=rd,gd=5*60*1e3,hd=40,yd=process.env.TMA_BASE_API_URL||"http://127.0.0.1:8585/api",bd=process.env.HEADSPIN_MOBILE_DEVICES_API_URL||"https://api-dev.headspin.io/v0",Td=process.env.HEADSPIN_MOBILE_APPS_API_URL||"https://api-dev.headspin.io/v1",wd=process.env.TDC_MOBILE_DEVICES_API_URL||"https://api.tdc.tricentis-cloud.com/v0",vd=process.env.TDC_MOBILE_APPS_API_URL||"https://api.tdc.tricentis-cloud.com/v1",Ed=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Bs=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Sd=process.env.SAUCE_LABS_US_APPS_API_URL||"https://api.us-west-1.saucelabs.com/v1",Id=process.env.SAUCE_LABS_EU_APPS_API_URL||"https://api.eu-central-1.saucelabs.com/v1",Rd=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||60,Xa=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung"});var Qa={};G(Qa,{CoralogixTransport:()=>Fr});var Ae,Ad,tw,rw,Fr,Za=T(()=>{"use strict";Ae=require("coralogix-logger"),Ad=E(require("winston-transport")),tw={debug:Ae.Severity.debug,silly:Ae.Severity.verbose,verbose:Ae.Severity.verbose,silent:Ae.Severity.verbose,info:Ae.Severity.info,http:Ae.Severity.info,warn:Ae.Severity.warning,warning:Ae.Severity.warning,error:Ae.Severity.error,critical:Ae.Severity.critical,crit:Ae.Severity.critical},rw=["err","error","reason","e"],Fr=class extends Ad.default{constructor(t){t=Object.assign({},Fr.options,t);super(t);this.options=t,this.logger=new Ae.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=Object.assign({},a,this.options.extraFields,l),d=new Ae.Log;d.severity=tw[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 rw)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){Ae.CoralogixLogger.configure(t),Fr.options=t}}});var ic={};G(ic,{getLogger:()=>x,sessionPlayerLoggerFormatter:()=>rc,setExecutionId:()=>sc,setProjectId:()=>nc,setProxyUri:()=>oc});function ow(){let s=[],e=()=>Promise.resolve();if(!_e){let{CoralogixTransport:t}=(Za(),ye(Qa));t.configure(Od);let r=new t({category:"ROOT"});s.push(r),e=()=>r.waitForFlush()}if(od){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} ${co.inspect(r.meta,t)}`))}))}return[s,e]}function sc(s){ec=s}function nc(s){_d=s}function oc(s){if(_e||!s)return;let{CoralogixTransport:e}=(Za(),ye(Qa));e.configure({...Od,proxyUri:s})}function Cd(s){return{projectId:_d,time:new Date().toISOString(),...ec&&!s&&{executionId:ec}}}function x(s){return new tc(uw.child({category:s}))}var Pd,ft,co,ao,kd,sw,nw,Od,xd,rc,iw,aw,cw,lw,uw,ec,_d,tc,j=T(()=>{"use strict";Pd=E(require("os")),ft=E(require("winston"));le();co=E(require("util")),ao=E(require("chalk")),kd=E(require("dayjs"));B();sw=Pd.hostname(),nw=gt(),Od={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};xd={depth:5,colors:!0},rc=(s,e,t)=>{let r=`[${(0,kd.default)().format("HH:mm:ss:SSS")}]`,n=co.inspect(e,xd),o=co.inspect(t,xd);return`${ao.default.white(r)} ${ao.default.reset()}SessionPlayer-${ao.default.red(s)} ${n} ${o}`},[iw,aw]=ow(),cw=id?"debug":"info",lw={release:Boolean(!0),branch:"production"},uw=ft.createLogger({levels:ft.config.syslog.levels,level:cw,transports:iw,defaultMeta:{name:"runner",hostname:sw,nodeVersion:process.version,runnerVersion:nw,...lw}}),ec=null,_d=null;tc=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,Object.assign({meta:r,message:t},Cd(n)))}catch(o){try{this._logger.log("crit",Object.assign({message:`failed to log message ${o.message}, ${o.stack}`},Cd(n)))}catch{}}}waitForFlush(){return aw()}}});var mo,Br,P,Kt,fr,Rt,lo,jr,ne,js,Ke,Jt,At,uo,$r,Wr,Vr,po,$s,z=T(()=>{"use strict";mo=require("p-retry"),Br=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 mo.AbortError{},lo=class extends mo.AbortError{},jr=class extends mo.AbortError{},ne=class extends Error{},js=class extends Error{},Ke=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Jt=class extends Ke{constructor(){super(...arguments);this.name="GridConcurrencyError"}},At=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},uo=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},$r=class extends Error{},Wr=class extends Error{constructor(t){super();this.innerStack=t}},Vr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},po=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},$s=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function ac(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function oe(s){return(0,Nd.setTimeout)(s)}function cc(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"){no&&!Ld&&(Ld=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ne(t);return e=no?Number(no)||6e5:e,Promise.race([s,oe(e).then(()=>{throw r})])}async function ie(s,e,{concurrency:t}={}){if(t){Dd||=(await import("p-limit")).default;let r=Dd(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 Nd,Ld,Dd,lc=T(()=>{"use strict";Nd=require("timers/promises");z();le();Ld=!1});var Vs,Md,pw,Ws,Ud,dw,mw,Fd,Bd=T(()=>{"use strict";Vs=E(require("lodash"));le();Md=require("dns");j();lc();pw=x("http-request-counters"),Ws=!1,Ud=async()=>{if(_e)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ie(s,t=>Md.promises.lookup(t)));return e||(Ws=!0),e}catch{return pw.error("network connectivity test failed"),Ws=!0,!1}},dw=Vs.throttle(Ud,10*1e3),mw=60*1e3*15,Fd=()=>{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)},mw)}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),Ws||dw(),a}}}async function r(){if(Ws||!await Ud())return!1;let n=Vs.sum([...s.fail.values()]),o=Vs.sum([...s.call.values()]);return n<o*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>Ws,t}});var Je={};G(Je,{deleteFullRes:()=>bw,deleteReq:()=>Gs,didNetworkConnectivityTestFail:()=>yc,download:()=>gc,get:()=>be,getFullRes:()=>ww,getText:()=>qs,head:()=>vw,isNetworkHealthy:()=>hc,post:()=>He,postForm:()=>Hs,postFullRes:()=>Tw,postText:()=>mc,put:()=>fc});function gw(){return global.caFileContent}function hw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function yw(){return!xt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(xt.default),global.proxyUri}function gr(s,e=!1){let t=gw();t&&s.ca(t);let r=!e&&yw();r&&s.proxy(r)}async function jd(s,e={},t={},r=Gr){let n=xt.default.delete(s).send(e).timeout(r).set(t);return gr(n),await n}async function pc(s,e,t={},r=Gr,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 dc(s,e,t={},r=Gr,{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,uc,Ge,Gr,fw,Nt,Gs,bw,He,Tw,Hs,qs,mc,be,ww,vw,fc,gc,hc,yc,qe=T(()=>{"use strict";xt=E(require("superagent"));j();Bd();uc=x("http-request"),Ge=Fd(),Gr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,fw=6e4;Nt=(s,e,t)=>{throw uc.error(s,{...t,error:e}),e};Gs=Ge(async(s,e,t,r)=>{try{let n=await jd(s,e,t,r);return n.type==="text/plain"?n.text:n.body}catch(n){return Nt("failed to delete request",n,{url:s})}});bw=Ge(jd),He=Ge(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let o=await pc(s,e,t,r,n);return o.type==="text/plain"?o.text:o.body}catch(o){return Nt("failed to post request",o,{url:s})}});Tw=Ge(pc),Hs=Ge(async(s,e,t,r={},n=Gr)=>{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 Nt("failed to post request",i,{url:s})}});qs=Ge(async(s,e,t)=>{try{return(await dc(s,e,t)).text}catch(r){return Nt("failed to getText request",r,{url:s,query:e})}}),mc=Ge(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await pc(s,e,t,r,n)).text}catch(o){return Nt("failed to post request",o,{url:s})}}),be=Ge(async(s,e,t,r,n)=>{try{return(await dc(s,e,t,r,n)).body}catch(o){return Nt("failed to get request",o,{url:s,query:e})}}),ww=Ge((s,e,t,r)=>dc(s,e,t,r)),vw=Ge(async s=>{let e=xt.default.head(s).timeout(Gr);gr(e);try{return await e}catch(t){return Nt("failed to head request",t,{url:s})}}),fc=Ge(async(s,e,t={},r=Gr)=>{let n=xt.default.put(s).send(e).timeout(r).set(t);gr(n);try{return(await n).body}catch(o){return Nt("failed to put request",o,{url:s})}}),gc=Ge(async s=>{uc.info("start to download",{url:s});let e=xt.default.get(s).timeout(fw).buffer(!0).parse(hw);gr(e);try{let t=await e;return uc.info("finished to download",{url:s}),t}catch(t){return Nt("failed to download",t,{url:s})}}),hc=Ge.isNetworkHealthy,yc=Ge.didNetworkConnectivityTestFail});function ht(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Mt.resolve(__dirname,"../../"):s=Mt.resolve(__dirname,""),s):process.cwd()}function fo(s,e){return Oe(s)?e||Mt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Mt.basename(s)}function gt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function Sw(){try{return ed.node}catch{return""}}async function Vd(s,e,t=!0){let r=await rt.promises.readdir(s,{withFileTypes:!0});await rt.promises.mkdir(e,{recursive:t});for(let n of r){let o=Mt.join(s,n.name),i=Mt.join(e,n.name);n.isDirectory()?await Vd(o,i):await rt.promises.copyFile(o,i)}}async function ge(s){try{return await rt.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Mt,$d,Wd,rt,Ew,Ut,Ye,go,bc,st,Tc,Gd=T(()=>{"use strict";Mt=E(require("path"));za();ro();$d=E(require("unzip-stream")),Wd=E(require("p-retry")),rt=require("fs"),Ew=3;Ut=async s=>{let e=await Promise.resolve().then(()=>(qe(),Je));return(0,Wd.default)(()=>e.download(s),{retries:Ew,factor:1})},Ye=async(s,e)=>{let t=await Ut(s);return rt.promises.writeFile(e,t.body)};go=async(s,e)=>{let t=fo(s,e);return Oe(s)?Ye(s,t):rt.promises.copyFile(s,t)},bc=async s=>Oe(s)?Ut(s):rt.promises.readFile(s),st=async(s,e)=>await(0,rt.createReadStream)(s).pipe($d.Extract({path:e})),Tc=s=>(0,rt.statSync)(s).size/1e6});var Ft={};G(Ft,{APPIUM_SESSION_MESSAGE:()=>Ic,CLI_MODE:()=>Q,MOBILE_APP_SOURCE:()=>ho,MOBILE_RUN_SKIP_REASON:()=>Sc,gridMessages:()=>yt,gridTypes:()=>_,mobileWeb:()=>vc,runnerStatus:()=>wc,runnerTestStatus:()=>pe,socketEventTypes:()=>Ct,stepResult:()=>Ks,test:()=>Ec,testRunStatus:()=>zs,testStatus:()=>Xe,timeoutMessages:()=>Be});var Be,zs,wc,pe,Xe,yt,vc,Ec,Ct,Q,_,Ks,ho,Sc,Ic,ae=T(()=>{"use strict";Be={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},zs={COMPLETED:"completed",RUNNING:"running"},wc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},pe={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Xe={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"},vc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Ec={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},Ct={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},Q={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},_={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"},Ks={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"},ho={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},Sc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Ic={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 Js(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 Iw(){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 Ys,Hd,Qe,Rw,Aw,xw,Cw,Pw,Rc,Ac,qd=T(()=>{"use strict";ae();Ys=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},Hd=s=>Boolean(s.resultId&&s.source==="remote-run"),Qe=(s,e)=>s.testStatus===Xe.QUARANTINE&&!Hd(e)&&!e.runQuarantinedTests;Rw=s=>Boolean(s.loginMode),Aw=s=>Boolean(s.tunnelOnlyMode),xw=s=>Boolean(s.createPrefechedData),Cw=s=>Boolean(s.installLazyDepsMode),Pw=s=>Boolean(s.agentMode),Rc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Ac=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function bo(s=0){return yo.default.duration(s).format("HH:mm:ss.SSS")}function xc(s=0){return yo.default.duration(s).asSeconds()}var yo,zd,Kd=T(()=>{"use strict";yo=E(require("dayjs")),zd=E(require("dayjs/plugin/duration"));yo.default.extend(zd.default)});var Xs,Hr,Qs,Jd,qr,Yd=T(()=>{"use strict";ae();Xs=s=>!(!s||"fileName"in s),Hr=(s,e)=>e===_.TESTIM_TVC?!1:s&&"fileName"in s?s.fileName.endsWith(".app"):!1,Qs=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},Jd=s=>s===_.TESTIM_TVC,qr=(s,e)=>Jd(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Cc(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 Xd=T(()=>{"use strict"});var J={};G(J,{OSS:()=>zr,TESTIM_BROWSER_DIR:()=>Bt,buildBasicHeader:()=>qa,calcPercentile:()=>vo,copyDir:()=>Vd,delay:()=>oe,doesPathExist:()=>ge,download:()=>Ut,downloadAndSave:()=>Ye,extractElementId:()=>De,getArgsOnRemoteRunFailure:()=>Iw,getBrowserInfo:()=>Ow,getCdpAddressForHost:()=>yr,getCliLocation:()=>ht,getDuration:()=>bo,getDurationSec:()=>xc,getEnginesVersion:()=>Sw,getEnvironmentGitBranch:()=>hr,getLocalFileSizeInMB:()=>Tc,getMemorySnapshot:()=>Cc,getPlanType:()=>wo,getRunConfigByBrowserName:()=>Zs,getRunnerVersion:()=>gt,getSource:()=>go,getSourceAsBuffer:()=>bc,getSourcePath:()=>fo,getTestUrl:()=>ze,getUniqBrowsers:()=>Js,groupTestsByRetries:()=>kc,guid:()=>se,hasTestPlanFlag:()=>Ys,isAgentMode:()=>Pw,isAppFromDevice:()=>Xs,isAppFromDeviceDisabled:()=>qr,isCreatePrefetchedDataMode:()=>xw,isInstallLazyDepsMode:()=>Cw,isLoginMode:()=>Rw,isMobileProject:()=>Qs,isPromise:()=>ac,isQuarantineAndNotRemoteRun:()=>Qe,isRemoteRun:()=>Hd,isTestimVirtualGrid:()=>Jd,isTunnelOnlyMode:()=>Aw,isURL:()=>Oe,promiseAbort:()=>cc,promiseFromCallback:()=>Yt,promiseMap:()=>ie,promiseTimeout:()=>ce,removePropertyFromObject:()=>To,replaceArgsWithNoDashes:()=>Rc,shouldBlockVirtualIosBuild:()=>Hr,spreadObjectToArgs:()=>Ac,unzipFile:()=>st});function Ow(s){return s=s.toLowerCase(),Pc.find(e=>e.browserValue===s)}function Zs(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Pc.find(o=>o.browserName.toLowerCase()===s||s.includes(o.synonyms))||Pc[0],n=zr.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=zr.find(o=>o.sl.platform===e.platform):e.platformName&&(n=zr.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=zr.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=zr.find(o=>o.bs.platform===t.platform))),Kr.merge(r,n)}function hr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function To(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&To(s[r],e,t))}function De(s){return s.ELEMENT||s[zt]}function wo(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function kc(s=[]){return Kr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((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=Kr.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(()=>(qe(),Je));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 Qd,Kr,Zd,kw,Bt,zr,Pc,vo,B=T(()=>{"use strict";Qd=E(require("os")),Kr=E(require("lodash")),Zd=E(require("path"));Mr();Gd();qd();Kd();za();lc();Yd();Xd();kw=Qd.homedir(),Bt=Zd.join(kw,".testim-browser-profile"),zr=[{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"}}],Pc=[{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"}];vo=(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 Oc={};G(Oc,{$schema:()=>_w,default:()=>Uw,definitions:()=>Lw,properties:()=>Mw,required:()=>Nw,type:()=>Dw});var _w,Lw,Dw,Nw,Mw,Uw,em=T(()=>{_w="http://json-schema.org/draft-07/schema#",Lw={request:{type:"object",required:["url"],additionalProperties:!1,properties:{url:{type:"string"},method:{type:"string",pattern:"^GET$|^HEAD$|^POST$|^PUT$|^DELETE$|^CONNECT$|^OPTIONS$|^TRACE$|^PATCH$"}}},header:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"}}},cookie:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"},path:{type:"string"},domain:{type:"string"},expires:{type:"string",format:"date-time"},httpOnly:{type:"boolean"},secure:{type:"boolean"}}},response:{type:"object",required:["status"],additionalProperties:!1,properties:{status:{type:"integer",minimum:100,exclusiveMaximum:600},headers:{type:"array",items:{$ref:"#/definitions/header"}},cookies:{type:"array",items:{$ref:"#/definitions/cookie"}},content:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}}},redirectResponse:{type:"object",required:["redirectUrl"],additionalProperties:!1,properties:{redirectUrl:{type:"string"}}},passthroughResponse:{type:"object",required:["passthrough"],additionalProperties:!1,properties:{passthrough:{type:"boolean",enum:[!0]}}},entry:{type:"object",required:["request","response"],additionalProperties:!1,properties:{request:{$ref:"#/definitions/request"},response:{oneOf:[{$ref:"#/definitions/response"},{$ref:"#/definitions/redirectResponse"},{$ref:"#/definitions/passthroughResponse"}]},maxHits:{type:"integer",minimum:1}}}},Dw="object",Nw=["entries"],Mw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},Uw={$schema:_w,definitions:Lw,type:Dw,required:Nw,properties:Mw}});async function am(){try{return await ce(Eo.promises.readFile(Ao()).then(async s=>{let e=await im;return jw(e,s)}),3e4)}catch{return{}}}function jw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),o=Yr.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=Fw,r=void 0){return async()=>{if(!sm)return await s();let n=e;r&&(e+=JSON.stringify(r));let o=await $w(e);if(o)return en.debug("cache hit:",{fnName:e}),o;if(en.debug("cache miss:",{fnName:e}),!nm)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 Ww(e,i,t),i}}async function $w(s){let t=(await xo)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function Ww(s,e,t){if(_c)throw en.error("calling set after waitForSave is not allowed",{key:s,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let r=await xo;r[s]={value:e,expiry:Date.now()+t},om=new Promise(n=>{Ro=n}),Bw(r)}catch{en.error("failed updating cache")}}async function Xr(){let s=await xo;Object.keys(s).forEach(e=>{delete s[e]})}function cm(s){sm=s}function Vw(s=!0){nm=s}async function lm(){try{return _c=!0,await om}finally{_c=!1}}function um(s){Io=s,xo=am()}var Eo,So,Yr,tm,en,Io,rm,Ro,sm,nm,_c,om,im,Fw,Ao,xo,Bw,pm,dm,wA,mm,jt=T(()=>{"use strict";Eo=E(require("fs")),So=E(require("path")),Yr=E(require("crypto"));B();tm=require("lodash");j();en=x("local cache"),Io=So.resolve(ht(),"testim-cache"),sm=!0,nm=!0,_c=!1,om=new Promise(s=>{Ro=s}),im=new Promise(s=>{rm=s}),Fw=1e3*60*60*3,Ao=()=>So.resolve(So.resolve(Io,"testim.cache"));xo=am(),Bw=(0,tm.debounce)(async s=>{let e;try{let t=await im,r=Yr.randomBytes(16),n=JSON.stringify(s),o=Buffer.from(t),i=Yr.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),r),a=Buffer.concat([r,i.update(n),i.final()]);await ge(Io)||await Eo.promises.mkdir(Io,{recursive:!0}),await Eo.promises.writeFile(Ao(),a)}catch(t){en.error("failed saving cache",{err:t}),e=t}Ro(e?{success:!1,error:e}:{success:!0})},200);pm=rm,dm=cm.bind(void 0,!1),wA=cm.bind(void 0,!0),mm=()=>Vw(!1)});function Co(){return{cliLocation:ht(),userInfo:Qr.userInfo(),platform:Qr.platform(),release:Qr.release()}}var Qr,Lc=T(()=>{"use strict";Qr=E(require("os"));B()});function Gw(s){try{return Po.resolve(Po.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=Gw(s);return require(e)}var Po,tn=T(()=>{"use strict";Po=E(require("path"))});function Hw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function qw(s){return/The "to" argument must be of type string./.exec(s)}function ym(s,e,t){let r=Hw(s),n=qw(s);return r||n?(hm.info("Failed to install package due to insufficient write access",{...Co(),package:t,path:r}),console.error(`
|
|
4
4
|
|
|
5
5
|
Testim failed installing the package ${t||""} due to insufficient permissions.
|
|
@@ -406,7 +406,7 @@ Please make sure the CLI has stable access to the internet. ${yc()?"(Internal: n
|
|
|
406
406
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
407
407
|
const downloadAndUploadFile = ${vI()};
|
|
408
408
|
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await zy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ua,pa,Yy=T(()=>{"use strict";ua=require("url");ue();pa=class extends V{async updateBaseUrl(e){let t=new ua.URL(e),r=new ua.URL(this.context.recordedBaseUrl),n=new ua.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 da,Xy=T(()=>{"use strict";ue();B();da=class extends V{async performAction(){await oe(this.step.durationMS||0)}}});var ma,Qy=T(()=>{"use strict";ue();ma=class extends V{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Wn,Zy=T(()=>{"use strict";ue();Wn=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,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 fa,eb=T(()=>{"use strict";ue();fa=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 tb,fp,gp,rb=T(()=>{"use strict";tb=E(require("@applitools/spec-driver-webdriverio"));ro();Te();fp=class{constructor(){let{EyeSdkBuilder:e}=ee(),t=Zp["@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:tb.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=ee(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},gp=new fp});var nb,sb,Vn,ob=T(()=>{"use strict";nb=E(require("lodash"));ue();j();rb();sb=x("pixel-validation-step-action"),Vn=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 gp.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"};nb.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(g,i.applitoolsStepSettings),sb.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){sb.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await gp.handleApplitoolsSdkResult(this.context,d,this.step)}}});var As,hp=T(()=>{"use strict";Ts();z();ta();As=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 bs(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,ib=T(()=>{"use strict";hp();ur=class extends As{isFailedResult(e){return e===!1}}});var ga,ab=T(()=>{"use strict";hp();ga=class extends As{isFailedResult(e){return!e}}});var ha,cb=T(()=>{"use strict";Ts();ue();z();ha=class extends V{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await ys(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 Lr,lb=T(()=>{"use strict";ue();Lr=class extends V{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var Ee,ub=T(()=>{"use strict";ue();Ee=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 ya,pb=T(()=>{"use strict";ue();ya=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 ba,db=T(()=>{"use strict";ue();ba=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 EI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Ta(s,e){EI(SI,e),e.registerLocateStepActionUtils(Bn.getUtils(s))}var SI,yp=T(()=>{"use strict";ly();dy();vy();Ey();Iy();xy();ky();Oy();_y();Ny();My();Uy();jy();Vy();Jy();Yy();Xy();Qy();Zy();eb();ob();ib();ab();cb();lb();ub();pb();db();SI={locate:Bn,scroll:Yi,mouse:Xi,submit:na,text:Zi,"special-key":ra,"user-code":qt,"validation-code-step":qt,"wait-for-code-step":qt,"action-code-step":qt,"condition-step":Rs,"skip-code-step":Rs,"element-code-step":Rs,"evaluate-expression":Qi,"text-validation":$n,"wait-for-text-validation":$n,"select-option":sa,"drop-file":aa,"input-file":la,hover:oa,navigation:pa,wheel:ia,sleep:da,refresh:ma,"api-validation":Wn,"api-action":Wn,"api-code-step":qt,"extract-text":fa,"simple-ui-verification":Vn,"wait-for-simple-ui-verification":Vn,"cli-validation-download-file":Lr,"cli-wait-for-download-file":Lr,"network-validation-step":Lr,"cli-validation-code-step":ur,"cli-wait-for-code-step":ur,"cli-action-code-step":ur,"cli-api-code-step":ur,"cli-condition-step":ga,"node-package":ha,"email-code-step":qt,"cli-email-code-step":ur,"sfdc-internal-test-step":ba,"sfdc-recorded-step":ya,"sfdc-step-login":Ee,"sfdc-step-loginas":Ee,"sfdc-step-logout":Ee,"sfdc-step-sobjectcreate":Ee,"sfdc-step-sobjectdelete":Ee,"sfdc-step-findrecord":Ee,"sfdc-step-quickaction":Ee,"sfdc-step-sobjectedit":Ee,"sfdc-step-sobjectvalidate":Ee,"sfdc-step-launchapp":Ee,"sfdc-step-wait-for-page-load":Ee,"sfdc-step-closeconsoletabs":Ee,"sfdc-step-relatedlistaction":Ee,"sfdc-step-permission-validation":Ee,"sfdc-step-convert-lead-to-opportunity":Ee,"sfdc-step-quotelineeditor":Ee,"sfdc-document-validation":Lr}});var mb,II,xs,bp=T(()=>{"use strict";mb=["simple-ui-verification","wait-for-simple-ui-verification"],II=[...mb,"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"],xs=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=II.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 mb.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 gb={};G(gb,{SeleniumTestPlayer:()=>Gn});var fb,Gn,Tp=T(()=>{"use strict";B();fb=require("@applitools/eyes-sdk-core");Ln();z();ap();sy();pp();ny();ay();dp();Te();yp();bp();Gn=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new xs(Ji());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=ee();this.driver=n??new Pr;let d=new Ki(this.driver);this.stepActionFactory=new c(d),Ta(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new qi(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=iy(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new Ss(this.driver),FrameLocator:m,portSelector:zi,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:fb.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}=ee(),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 n=(await this.driver.getTabIds()||[]).at(-1);return await this.tabService.addNewTab(this.id,n,e,t),this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},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 hb={};G(hb,{WorkerSelenium:()=>wp});function AI(s){let{playback:e}=ee().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>M(`Got event ${t}`))}var wa,RI,wp,yb=T(()=>{"use strict";B();Ve();Fn();j();_t();ti();ae();op();z();Tp();Te();ot();wa=x("worker-selenium"),RI=1e9,wp=class extends lt{initPlayer(t){return new Gn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){M("in WorkerSelenium getBrowserOnce"),X.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new Es(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,RI),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`):(wa.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Bo(),initializedFromCache:jo()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:o}=ee(),{driver:i,sessionPlayer:a}=r,l=n||"runner";X.onWaitToTestComplete(this.id),AI(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 bn(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,Be.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()||(wa.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&&(wa.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 wa.error("failed to run test once",{err:u}),u}}}});var bb,Tb,$e,xI,CI,vp,St,va=T(()=>{"use strict";bb=E(require("ora")),Tb=E(require("jimp"));le();qe();he();j();ae();Te();$e=x("mobile-grid-service"),xI="https://tdc.tricentis-cloud.com",CI="https://ui.headspin.io",vp=class{constructor(){this.gridsAppIdGetter={[_.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[_.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[_.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[_.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[_.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[_.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===_.TESTIM_TDC||e===_.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e)?`${t}/lock`:""}getBaseApiUrl(e){return e===_.TESTIM_HEADSPIN?`${bd}/devices`:e===_.TESTIM_TDC?`${wd}/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 He({url:r,headers:n,body:o})}catch(i){throw $e.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 $e.error("error while getting automation config for device",{error:o,deviceId:t}),o}}async getPCloudyAuthToken(e,t,r){let n=await qs(`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===_.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===_.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([_.BROWSERSTACK,_.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===_.TESTIM_HEADSPIN||t===_.TESTIM_TDC){let d=await Cl({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===_.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===_.SAUCELABS)return e.testobject_device_name;if(t===_.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;u===_.TESTIM_TVC?g=this.getDeviceFromTvcCapabilities(t.capabilities):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 Er(l,o,i,a,"RUNNING",{device:g,...y&&{remoteResultLink:y}}),$e.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===_.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}=ee(),i=new o(t,r.sessionId,null),[a,l]=await Promise.all([i.getScreenshot(),i.getDeviceSize()]),c=Buffer.from(a,"base64"),d=await Tb.default.read(c),m=d.getWidth(),u=d.getHeight();return{scaleFactor:m/l.width,width:m,height:u}}catch(o){return $e.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}}getDeviceFromTvcCapabilities(e){let{getTvcDeviceInfoFromSessionCaps:t}=ee();return t?t(e):{model:e.device,height:e.screen.height,width:e.screen.width,scaleFactor:e.screen.scale??1,isVirtual:!0,osType:e.platformName.toLowerCase(),osVersion:e.os_version,name:e.device}}async buildRemoteResultLink(e,t,r){return e.type===_.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Bs}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===_.SAUCELABS?r.testobject_test_report_url:e.type===_.TESTIM_TVC?r.replayUrl:e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC?`${e.type===_.TESTIM_HEADSPIN?CI:xI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let r=(await be(`${yd}/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 Er(l,n,o,i,"RUNNING",{device:a}),$e.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getMobileAppDataByAppId({appId:e,projectId:t,token:r,executionId:n,testResultId:o}){try{let i=await al({appId:e,projectId:t});if(!i)throw $e.error("mobile app not found",{appId:e,projectId:t,executionId:n,testResultId:o}),new Error("mobile app not found");return{appUrl:`${fe}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}catch(i){throw $e.error("error while getting app details",{error:i,appId:e,projectId:t,executionId:n,testResultId:o}),i}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(hd*60))+1)*60*1e3,Math.max(gd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let i={[_.BROWSERSTACK]:{name:"Browserstack",appPath:"browserStackAppId"},[_.TESTIM_TVC]:{name:"Mobile Virtual Grid",appPath:"testimTvcAppId"},[_.P_CLOUDY]:{name:"pCloudy",appPath:"pCloudyAppId"}},a=i[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,bb.default)(`uploading app to ${a} please wait..`).start();try{$e.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await Pl({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});c.succeed(`app uploaded successfully to ${a}`);let m=i[o].appPath;return d[m]}catch(d){throw c.fail(`failed to upload app to ${a}`),$e.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&&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="",host:h=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){$e.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:i});let R=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d,executionId:i,testResultId:a});n=R.appUrl,o=R.mobileApp,e.nativeApp=o}else $e.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:i}),n=e.downloadableAppPublicLink||"";let g=l||e.mobileApp.appId,y=this.gridsAppIdGetter[f]({testRunHandler:e,mobileApp:o,gridHost:h}),w=f===_.BROWSERSTACK||f===_.TESTIM_TVC||f===_.P_CLOUDY;if(y){let R=t.projectData.type,b=await this.verifyAppStillExistsOnGrid({gridAppId:y,gridData:m,projectType:R});b&&($e.info("app exists on grid, using gridAppId",{gridAppId:y,projectId:c,testResultId:a,executionId:i,mobileAppId:g}),n=y),!b&&w&&($e.info("app not exists on grid, uploading it",{gridAppId:y,projectId:c,testResultId:a,executionId:i,mobileAppId:g}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:g})),!b&&!w&&$e.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:i})}return!y&&w&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:g})),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===_.BROWSERSTACK){let m=`${Bs}/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===_.SAUCELABS){let u=`${i.includes("eu-central-1")?Id:Sd}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:o,key:a})).items.some(h=>h.id===e)}if(l===_.TESTIM_HEADSPIN||l===_.TESTIM_TDC){let m=l===_.TESTIM_HEADSPIN?`${Td}/apps`:`${vd}/apps`;return(await this.fetchWithTokenAuth({url:m,accessToken:n,authType:"Bearer"})).apps.some(f=>f.app_id===e)}if(l===_.TESTIM_TVC){let m=`${Ed}/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&&$e.error("error while verifying app exists on TVC",{error:f}),!1}}if(l===_.P_CLOUDY){let m=await this.getPCloudyAuthToken(i,o,a),u=`https://${i}/api/drive`,f=await mc({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 vp});function wb({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"&&!PI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function kI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==_.TESTIM_TDC&&e.type!==_.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 OI(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 _I(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===_.TESTIM_TDC,a=s===_.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`]:OI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n}}}function Ea(s){return"id"in s?s.id:s.packageName}function LI(s,e){return{[`${e===_.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function DI({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=LI(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":Ea(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":Ea(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Nr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:o=""}){switch(s){case"ios":return{platformName:"iOS",[`${o}autoAcceptAlerts`]:!0,[`${o}automationName`]:"XCUITest",[`${o}fullReset`]:!0,...t&&{[`${o}bundleId`]:Ea(t)},...r&&{[`${o}app`]:r},...e};case"android":return{platformName:"Android",[`${o}autoGrantPermissions`]:!0,[`${o}automationName`]:"UiAutomator2",...n&&{[`${o}appWaitActivity`]:`${n}, *`},...t&&{[`${o}appPackage`]:Ea(t),[`${o}appActivity`]:t.activity??".*"},...r&&{[`${o}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function vb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=_I(i.type,o,n);return DI({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Ia({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 Ra({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o}=e,i=r===_.P_CLOUDY;return s||(n!=null&&n.deviceName?i?n.deviceUdid:n.deviceName:o!=null&&o.deviceNameRegex?t==="android"&&o.deviceNameRegex===".*"&&i?Xa:o.deviceNameRegex:t==="ios"&&r===_.BROWSERSTACK?"iPhone.*":i?t==="ios"?"apple":Xa:".*")}function NI(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 MI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Sa(s,Cs)}}function Eb(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 UI(s){return Eb(s,e=>e.startsWith("browserstack."),"browserstack.")}function FI(s){return Eb(s,e=>!e.startsWith("browserstack."))}function Sb(s){return!s||!Ib(s)?"2.0.0":s}function Ib(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Rb({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=Ib(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Sa(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let o=`${e}${r}`;t[o]=n}),t}function BI({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=NI(o,s),f=Ia({osVersion:l,mobileConfig:d}),h=Ra({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),g=ze(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 Nr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function jI({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=Ia({osVersion:l,mobileConfig:d}),y=Ra({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),w=/^[a-zA-Z]+$/.test(y),R={...g!==".*"&&{pCloudy_DeviceVersion:g},...w&&{pCloudy_DeviceManufacturer:y},...!w&&{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(Rd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=MI(b)),t="",Nr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Cs}})}function $I({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=Ia({osVersion:l,mobileConfig:d}),f=Ra({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Dr.omit)(Object.assign({},n.saucelabs),["automationName","platformName"]),g=Object.assign({},h["sauce:options"]);if(delete h["sauce:options"],Rb({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let w={debug:!0,networkLogs:!0},R={user:o.user,key:o.key,name:i.testResultId,build:i.executionId,appiumVersion:Sb(g.appiumVersion),deviceName:f,tags:Object.values(i)},b={"appium:platformVersion":u,"appium:deviceName":f,...Sa(h,Cs),"sauce:options":{...w,...R,...(0,Dr.omit)(g,"appiumVersion")}};return Nr({projectType:s,sessionCaps:b,appiumPrefix:Cs,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 Nr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function WI({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=Ia({osVersion:l,mobileConfig:d}),f=Ra({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=UI(n.browserstack),g=(0,Dr.omit)(FI(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:w,name:R}=n.browserstack||{};if(Rb({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let v={userName:o.user,accessKey:o.key,appiumVersion:Sb(h.appiumVersion),projectName:y||i.project,buildName:w||i.executionId,debug:!0,networkLogs:!0},I={"appium:platformVersion":u,"appium:deviceName":f,...Sa(g,Cs),"bstack:options":{...v,...(0,Dr.omit)(h,"appiumVersion")}};return Nr({projectType:s,sessionCaps:I,appiumPrefix:Cs,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:w||i.executionId,buildTags:Object.values(i).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,...Sa(h,"browserstack.")};return Nr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function VI(s){if(_.TESTIM_TDC===s.gridInfo.type||_.TESTIM_HEADSPIN===s.gridInfo.type)return vb(s);if(_.TESTIM_TVC===s.gridInfo.type)return BI(s);if(_.P_CLOUDY===s.gridInfo.type)return jI(s);if(_.SAUCELABS===s.gridInfo.type)return $I(s);if(_.BROWSERSTACK===s.gridInfo.type)return WI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function GI(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 Ab(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}`);wb({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=St.getGridConnection(e),l=VI(s);if(e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC){let d=e.type===_.TESTIM_HEADSPIN?"headspin":"tdc",m=GI(r,o==null?void 0:o.mobile);if(!(0,Dr.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===_.TESTIM_TVC?{alwaysMatch:l}:l;return{...a,desiredCapabilities:l,capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function xb(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;wb({nativeAppMetadata:r,appPath:o,gridInfo:t}),kI({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=vb({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 Cb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s;return Nr({projectType:e,sessionCaps:{},nativeAppMetadata:t,appPath:r,androidActivityWait:n})}function Pb(s){var t,r;let e=Object.assign({},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 Dr,Cs,PI,Ep=T(()=>{"use strict";de();ae();va();Dr=require("lodash");B();le();Cs="appium:",PI=[_.BROWSERSTACK,_.SAUCELABS,_.TESTIM_HEADSPIN,_.TESTIM_TDC,_.TESTIM_TVC,_.P_CLOUDY]});var Aa,Ob=T(()=>{"use strict";Aa=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 xa,_b=T(()=>{"use strict";xa=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)")}}});var Sp,Ca,Lb=T(()=>{"use strict";j();Sp=x("mobile-frame-locator-mock"),Ca=class{foundFrameCallback(){return Sp.info("foundFrameCallback-mock invoked"),{}}locate(){return Sp.info("locate-mock invoked"),{}}async findFrame(){return Sp.info("findFrame-mock invoked"),{}}}});var HI,Nb,Db,Ps,Ip=T(()=>{"use strict";HI=E(require("webdriverio")),Nb=require("@applitools/eyes-sdk-core");Ob();pp();j();_b();dp();Te();yp();Lb();bp();Db=x("appium-test-player"),Ps=class{constructor(e,t,r,n=HI,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=ee(),m=new xa(this.driver);this.stepActionFactory=new c(m),Ta(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new xs(Ji()),this.sessionPlayer=new a(e,{tabService:new Aa,cookieUtils:void 0,FrameLocator:Ca,portSelector:zi,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}=ee();e.off(i.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function qI(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 qI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Fb=T(()=>{"use strict";qe()});var Bb={};G(Bb,{WorkerLocalTma:()=>Cp});var Pa,Rp,Ap,xp,Cp,jb=T(()=>{"use strict";qe();Ep();Fn();B();j();_t();Ip();Te();Fb();va();Pa=x("worker-appium"),Rp=class extends Error{},Ap=class extends Error{},xp=class extends Error{},Cp=class extends lt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Ps(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}=ee(),{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(X.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:O}=t,{mobileApp:$}=await St.getMobileAppDataByAppId({appId:f,projectId:c,token:d,executionId:C,testResultId:O});t.nativeApp=$}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,w=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!w)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,w),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}`},O=Cb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:C,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),$={capabilities:{udid:a,...O}},A=await this.requestNewAppiumSessionFromTma(i,$,g);this.sessionData=A;let S=await m.attach({sessionId:A.sessionId,capabilities:O});this.device=await St.updateTmaDeviceDetails(a,this.options,t),Pa.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 Pa.error("failed to start application",{err:C}),C}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await He({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 xp(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 Ut(n);await Hs(`${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 Ap(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 Rp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=ee(),{sessionPlayer:i}=r,a=n||"runner";X.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 Pa.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Pa.error("failed to run test once",{err:c}),c}}}});var Wb={};G(Wb,{WorkerAppium:()=>Pp});var $b,ks,Pp,Vb=T(()=>{"use strict";Ep();$b=require("linkedom");Fn();j();_t();Ip();Te();va();ae();ps();ks=x("worker-appium"),Pp=class extends lt{initPlayer(t){return new Ps(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){X.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 xb(u)):f=Ab(u),ks.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:Pb(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),ks.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw ks.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}updateSlotData(t){try{this.options.slotService==="redis"&&mg(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){ks.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===_.TESTIM_HEADSPIN||o===_.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:o===_.TESTIM_TVC?`https://${t}/wd/hub`: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}=ee(),{sessionPlayer:a}=r,l=n||"runner";X.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:w,path:R}=await St.getHeadSpinDeviceConnection(this.options.gridData,h);c=`${g}://${y}:${w}${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),i.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let h=await new Promise((y,w)=>{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(w)});return await i.drain(),h.stepsResults=null,h.resultId=this.testResultId,{...h,...t.seleniumPerfStats.getStats()}}catch(h){throw ks.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:h}),h}};try{return await super.runTestOnce(t,r),await m()}catch(h){throw ks.error("failed to run test once",{err:h}),h}}}});var ka,Gb=T(()=>{"use strict";B();Ln();z();ka=class{constructor(e){this.id=e;this.driver=new Pr}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,Oa,qb=T(()=>{"use strict";Hb=E(require("ws"));B();Oa=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 La,kp,_a,zb=T(()=>{"use strict";B();La=E(require("chrome-launcher"));Fu();qb();fn();kp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Oa}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=ki({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)??[],...La.Launcher.defaultFlags().filter(w=>w!=="--disable-extensions")];this.chrome=await La.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),ns(()=>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 kp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Jb={};G(Jb,{WorkerExtension:()=>Hn});function zI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Kb(s){return zI(s)?s:new Error(s)}var ut,Hn,Op=T(()=>{"use strict";Ve();z();Fn();B();j();_t();ae();Gb();zb();ot();ut=x("worker-ext"),Hn=class extends lt{initPlayer(){return this.options.useChromeLauncher?new _a(this.id):new ka(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:Bo(),initializedFromCache:jo(),testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,r,n){return X.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,Be.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)){X.onWaitToTestStart(this.id),X.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();X.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Be.TEST_START_TIMEOUT_MSG)}catch(w){if(!(w instanceof ne))throw w;ut.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}X.onWaitToTestComplete(this.id);let g=new AbortController,y=w=>{e.onCompletedCleanup(),ut.warn("on browser closed error detected",{err:w,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),w.type=Ks.BROWSER_CLOSED,g.abort(w)};m.registerToClosedBrowser(y);try{let w=ce(e.onCompleted(),this.testRunTimeout,Be.TEST_COMPLETE_TIMEOUT_MSG),R=await cc(w,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(w){throw ut.warn("timeout wait until test completed",{err:w,testResultId:r,executionId:n,testId:o}),Kb(w)}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:()=>_p});var KI,JI,_p,Xb=T(()=>{"use strict";Ve();B();j();ep();_t();Op();KI=x("base-worker"),JI=500,_p=class extends Hn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await Mn(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 X.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()&&(KI.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(JI)}}});function YI(s,e){e===0?s():setTimeout(s,e*ld)}var Lp,Da,Qb=T(()=>{"use strict";Ln();le();Ve();xu();ot();Vu();z();j();ae();Gh();Lp=x("parallel-worker-manager"),Da=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Q.SELENIUM:return(yb(),ye(hb)).WorkerSelenium;case Q.APPIUM:return e.localTmaUrl?(jb(),ye(Bb)).WorkerLocalTma:(Vb(),ye(Wb)).WorkerAppium;default:return _i.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Xb(),ye(Yb)).WorkerExtensionSingleBrowser:(Op(),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,K,dt,ja,Hp;let y=o.project,w=new Bi(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=o.source||"cli",$=o.user,A=(F=o.company)==null?void 0:F.planType,S=(K=o.company)==null?void 0:K.isStartUp,L=(dt=o.projectData)==null?void 0:dt.name,U=(ja=o.projectData)==null?void 0:ja.type,q=o.lightweightMode,H=(Hp=o.gridData)==null?void 0:Hp.type,Y=(Dt,mt,we,$a,zn,Wa)=>(m++,xg({executionId:r,projectId:y,testId:mt,resultId:we,ucid:v,companyId:I,companyName:C,projectName:L,companyPlan:A,source:O,user:$,lightweightMode:q,isStartUp:S,projectType:U,appSource:Wa,gridType:H}),t.testStartAndReport(Dt,r,we,$a,zn)),me=async(Dt,mt,we,$a,zn,Wa)=>{var qp,zp,Kp;m--;let tt={...(q==null?void 0:q.onlyTestIdsNoSuite)&&{show:!0},...we.seleniumStats&&{seleniumStats:we.seleniumStats},...we.gridIssues&&{gridIssues:we.gridIssues},...we.keepAliveIssue&&{keepAliveIssue:we.keepAliveIssue},...o.host&&{gridHost:o.host}};if(we.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(we.seleniumPerfMarks),delete we.seleniumPerfMarks),o.grid||o.gridId?(tt.gridName=o.grid||((qp=o.gridData)==null?void 0:qp.name),tt.gridType=(zp=o.gridData)==null?void 0:zp.type,tt.gridProvider=(Kp=o.gridData)==null?void 0:Kp.provider):o.localTmaUrl?(tt.gridName="local-tma-from-options",tt.gridType="local-tma"):o.useLocalChromeDriver?(tt.gridName="local-chrome-driver-from-options",tt.gridType="local-chrome"):o.useChromeLauncher?(tt.gridName="chrome-launcher-from-options",tt.gridType="local-chrome"):o.browserstack?tt.gridName="browserstack-from-options":o.saucelabs&&(tt.gridName="saucelabs-from-options"),await t.testEndAndReport(Dt,we,r,$a,zn,tt).catch(HT=>Lp.error("testEndAndReport threw an error",{err:HT})),zn)return;R[we.resultId]=we,Cg({executionId:r,projectId:y,testId:mt,resultId:we.resultId,result:we,ucid:v,companyId:I,companyName:C,projectName:L,companyPlan:A,source:O,user:$,lightweightMode:q,logger:Lp,isStartUp:S,projectType:U,appSource:Wa}),c&&!we.success&&(w.stop(),d=!0),(Object.keys(R).length===b||d&&m===0)&&g(R)},pt=(Dt,mt)=>{R[mt.resultId]=mt,t.onTestIgnored(Dt,mt.resultId),m--,(Object.keys(R).length===b||d&&m===0)&&g(R)},It=(Dt,mt)=>t.onGridSlot(Dt,mt);o.userData={loginData:Object.assign({},$t(),{refreshToken:Uo(),authData:$t(),token:f,userAccessKey:h}),projectId:o.project,company:o.company,servicesUrl:fe},M("in localStrategy before createWorker"),this.createWorkers(l,w,o,this.customExtensionLocalLocation,r,Y,me,It,pt).forEach((Dt,mt)=>{M("before schedule worker.run after createWorkers"),YI(()=>{M("right before worker.run"),Dt.run()},mt)})});try{let f=await Zt(),h=await Fo(),g=await u(f,h);if(d)throw new Kt;return g}catch(f){throw Lp.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 il({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 Dp(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 Np(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(Js(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=T(()=>{"use strict";Zb=E(require("lodash"));B();os();he();z()});var qn,xD,Mp,Up,Na,rT=T(()=>{"use strict";qn=E(require("lodash"));B();j();le();ae();Ve();ls();uu();xu();he();ot();_t();Jg();z();Qb();tT();({testRunStatus:xD,CLI_MODE:Mp}=Ft),Up=x("test-plan-runner"),Na=class{constructor(e){this.startTime=Date.now();this.workerManager=new Da(e)}async runTestAllPhases(e,t,r,n,o,i,a,l){let c={},d=$t(),m=async()=>{let g=o.beforeParallel||1,y=!0,w=await this.workerManager.runTests(e,l,i,a,o,n,d,g,y);Object.assign(c,w)},u=async()=>{let g=io||o.parallel,y=!1;M("right before this.workerManager.runTests");let w=await this.workerManager.runTests(t,l,i,a,o,n,d,g,y);M("right after this.workerManager.runTests"),Object.assign(c,w)},f=async()=>{let g=o.afterParallel||1,y=!1,w=await this.workerManager.runTests(r,l,i,a,o,n,d,g,y);Object.assign(c,w)};Pg({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(Up.error("error running test plan",{err:g}),g instanceof Kt)return l.markAllQueuedTests(i,pe.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,w,R,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===Mp.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=(w=o.company)==null?void 0:w.activePlan)==null?void 0:R.premiumFeatures)!=null&&b.applitools)||(g=await Sl(o.project),qn.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;sc(c),e.forEach(C=>Object.assign(C,{isBeforeTestPlan:!0})),r.forEach(C=>Object.assign(C,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Pi(m,n,i,a),f=qn.default.chain(m).map(C=>{var O;return((O=C.overrideTestConfig)==null?void 0:O.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 w=await y;(I=n.lightweightMode)!=null&&I.onlyTestIdsNoSuite||X.onTestPlanStarted(w.beforeTests,w.tests,w.afterTests,o,c,l,h),M("before runTestAllPhases");let R=await this.runTestAllPhases(w.beforeTests,w.tests,w.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){Up.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function r(d){return qn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await ol(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!==Mp.APPIUM&&await Np(e,r(c)),await ie(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u=Object.assign({},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 ig(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);X.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let w=Object.keys(n[m]).map(I=>({executionId:I,status:Dp(n[m][I])})),R=Object.keys(n[m]).map(I=>n[m][I]).reduce((I,C)=>Object.assign(I,C),{}),b=Dp(R);Object.assign(o,R);let v=b?w[0].executionId:w.find(I=>!I.status).executionId;return await rl(i,m,{success:b,executions:w,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var a;Up.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),M("before getSuite");let r=await eT(e,t);if(M("after getSuite"),!((a=r==null?void 0:r.tests[0])!=null&&a.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;return M("Right before validateConfig + runAnonymousTestPlan tests map"),await ie(r.tests,async l=>{if(e.resultId){let d=l[0];d.resultId=e.resultId,l=[d]}e.mode!==Mp.APPIUM&&await Np(e,l),M("right before runTestPlan");let c=await this.runTestPlan([],l,[],e,o,null,t,i);return M("right after runTestPlan"),await X.onTestPlanFinished(c.results,o,this.startTime,c.executionId,i),c})}async run(e){let t=Rn(),r=[];Ys(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=qn.default.flattenDeep(r);return M("right before onAllTestPlansFinished"),await X.onAllTestPlansFinished(n),M("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var iT={};G(iT,{init:()=>yR,run:()=>dR});async function XI(s){let e=s.project,t=await cl(e);if(t!=null&&t.isExecutionBlocked)throw console.error("You have reached the limit of runs for the billing month, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli"),gn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new js}function QI(s,e){var i,a,l,c,d,m,u,f;let t=wo(e.activePlan),r=s.parallel;if(t==="free"&&r>nT)throw new P(`The free plan allows only ${nT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let h=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!h)throw new P("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let g=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.runInTurboMode;s.lightweightMode&&!g&&(console.warn(`
|
|
409
|
-
Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((d=s.gridData)==null?void 0:d.type)===_.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)===_.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 ZI(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await XI(s)}catch(t){if([P,js].some(r=>t instanceof r))throw t;Fp.error("could not validate cli account",{err:t})}}function eR(s){let e=$t();return df({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function tR(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(D.flags.useNewWSCLI.isEnabled()&&!e&&!t)return vt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(Mi(),Dh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(Ui(),Uh));r.init(s)}}function rR(s,e){let{branch:t,autoDetect:r}=s;if(fg(e,r),!e&&!r)throw new P(`branch ${t} does not exist, run aborted.`)}async function sR(s,e){let{id:t,type:r}=e,o=oT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||D.flags.sfdcHybridCompany.isEnabled()
|
|
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)===_.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)===_.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 ZI(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await XI(s)}catch(t){if([P,js].some(r=>t instanceof r))throw t;Fp.error("could not validate cli account",{err:t})}}function eR(s){let e=$t();return df({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function tR(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(D.flags.useNewWSCLI.isEnabled()&&!e&&!t)return vt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(Mi(),Dh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(Ui(),Uh));r.init(s)}}function rR(s,e){let{branch:t,autoDetect:r}=s;if(fg(e,r),!e&&!r)throw new P(`branch ${t} does not exist, run aborted.`)}async function sR(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=Rn();o&&(s.sfdcCredential=await el({projectId:t,branch:i}))}function nR(s,e){let{id:t,storageBaseUrl:r,storageType:n,name:o,activePlan:i={}}=e,a=Boolean(i.isPoc),l=Boolean(i.isStartUp),c=wo(i);c==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<sT?sT:s.newBrowserWaitTimeout),D.setCompanyId(t),D.setIsPOC(a),D.setIsStartUp(l),D.setPlanType(c),Ot.setPlanType(c),s.company={ucid:"",companyId:t,storageBaseUrl:r,storageType:n,name:o,planType:c,isPOC:a,isStartUp:l,activePlan:i}}function oR(s,e){s.editorUrl=Fs||e.editorUrl}function iR(s,e){s.allGrids=e}function aR(s,e){s.authData=e}function cR(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 lR(s){s.gridData=await ag(s)}async function uR(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(Tt("user-override-file",t),s.mockNetworkRules=await Zm(s.overrideMappingFile))}async function pR(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 Uf(),M("in runner.js after checkNpmVersion"),await ZI(s),M("in runRunner before tunnel.connect"),await li(s),M("in runRunner after tunnel.connect");let a=await new Na(e).run(s);return M("before tunnel.disconnect"),await ui(s),await gR(s.slotService,t,s.company.companyId),M("after tunnel.disconnect and gridService.keepAlive.end"),a}function mR(s){var e;Ot.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
|
|
410
410
|
\x1B[4m\x1B[36mOur Free grid offers basic service performance.
|
|
411
411
|
If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m
|
|
412
412
|
`)}function fR(s,e,t){s==="redis"&&Sn.start(t,e),s==="mongo"&&vn.start(e)}async function gR(s,e,t){s==="redis"&&await Sn.end(t,e),s==="mongo"&&await vn.end(e)}function hR(s,e){var o,i,a,l,c,d;let t=D.flags.redisSlotManager.isEnabled(),r=((o=s.projectData)==null?void 0:o.type)==="ios"||((i=s.projectData)==null?void 0:i.type)==="android",n=t&&r;if(e.followL2CPlan){let m=(l=(a=e.l2cLicense)==null?void 0:a.shadowCatalogId)==null?void 0:l.includes("testim_mobile"),u=!!((c=e.tvcLicense)!=null&&c.maxParallel);n&&u&&m&&(s.slotService="redis")}!e.followL2CPlan&&n&&((d=e.mobile)!=null&&d.maxParallel)&&(s.slotService="redis")}async function yR(s){var h,g,y;M("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:o}=s,i=tR(e,{disableResults:o||Boolean((t==null?void 0:t.disableResults)&&(r||n!=="extension")),disableRemoteStep:o||Boolean(t==null?void 0:t.disableRemoteStep)});i.catch(()=>{});let{authData:a,editorConfig:l,companyByProjectId:c,projectById:d,branchName:m,allGrids:u}=await dn(s);if(s.printGrids){let w=u.sort((R,b)=>R.type.localeCompare(b.type));console.table(w.reduce((R,b)=>{class v{constructor(O,$){this.Type=O,this.Browsers=$}}let I=Object.entries(b.browsers||{"N/A":""}).map(C=>C.join(":")).join(", ");return R[b.name]=new v(b.type,I),R},{})),process.exit(0)}if(await i,M("after featureFlagsReady and socketConnected"),oR(s,l),nR(s,c),cR(s,d),rR(s,m),iR(s,u),aR(s,a),await sR(s,d),await lR(s),QI(s,c),hR(s,c),D.flags.clearRunnerFileCache.isEnabled())try{await Xr(),Fp.info("runner file cache cleared")}catch(w){Fp.error("failed to clear runner file cache",{err:w})}(h=s.lightweightMode)!=null&&h.disableLabs||await _i.loadLabFeatures(d.id,c.activePlan),((g=s.lightweightMode)==null?void 0:g.type)==="turboMode"&&(D.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&console.log(`
|
|
@@ -424,9 +424,9 @@ Turbo mode will ignore step delays. Test artifacts like screenshots and logs wil
|
|
|
424
424
|
`,n=await bR(`tst-playground-${Date.now()}.js`,r),o=TR(n);_s[e]=o.child;let{error:i,exitCode:a}=await o;if(i)throw i;if(a!==0)throw new Error(`Process exited with exit code: ${a}`);return}finally{(t=_s[e])==null||t.kill(),delete _s[e]}}async function yT({code:s,type:e}){if(Wp.includes(e))return wR(s);throw new $r}function bT(){Object.keys(_s).forEach(s=>{_s[s].kill(),delete _s[s]})}var mT,fT,gT,hT,Wp,_s,TR,TT=T(()=>{"use strict";mT=E(require("fs")),fT=E(require("os")),gT=E(require("path")),hT=require("child_process");z();Wp=["playwright","selenium","puppeteer"],_s={};TR=s=>{let e,t=new Promise(n=>{e=n}),r=(0,hT.fork)(s,{stdio:["inherit","inherit","inherit","ipc"]});return r.on("message",n=>{if(!n)return;let{type:o,error:i}=n;i&&["uncaughtException","unhandledRejection"].includes(o)&&e({error:new Wr(i.stack)})}),r.on("error",n=>{e({error:n})}),r.on("exit",n=>{e({exitCode:n})}),Object.assign(t,{child:r})}});var ET,Ua,ST,wT,vT,vR,IT=T(()=>{"use strict";ET=require("express");j();z();le();TT();Ua=(0,ET.Router)(),ST=x("playground-router"),wT=["localhost","app.testim.io","playground.testim.io","staging.testim.io","app.staging.testim.cc","tta-crm.tricentis.com"],vT=s=>{if(!s)return{};try{return new URL(s)}catch{return{}}},vR=(s,e,t)=>{if(so)return t();let{referer:r,origin:n}=s.headers;if(!r&&!n)return e.status(400).send();let o=vT(r),i=vT(n);return!wT.includes(o.hostname)&&!wT.includes(i.hostname)?e.status(400).send():t()};Ua.post("/run",vR,async(s,e)=>{let{code:t,type:r}=s.body;if(!t||!Wp.includes(r)){e.status(400).send({success:!1,reason:"missing arguments"});return}try{await yT({code:t,type:r}),e.send({success:!0})}catch(n){if(n instanceof $r){e.status(404).send({success:!1});return}if(n instanceof Wr){e.json({success:!1,type:"playground-error",stack:n.innerStack});return}e.json({success:!1,reason:n.message}),ST.error(n)}});Ua.post("/stop",(s,e)=>{try{bT(),e.send({success:!0})}catch(t){e.json({success:!1,reason:t.message}),ST.error(t)}})});function AT(s){let e=(0,RT.Router)();return e.get("/cdp-url",(t,r)=>{if(!s){r.status(503).send({error:"Testim standalone browser is not running"});return}r.status(200).send({url:s.webdriverApi.cdpUrl})}),e.get("/status",(t,r)=>{if(!s){r.status(503).send({ok:!1});return}r.status(200).send({ok:!0})}),e}var RT,xT=T(()=>{"use strict";RT=require("express")});var OT={};G(OT,{orchestrateRoutes:()=>ER});function ER(s,e){let t=(0,PT.default)();s(t),t.use(Vp.default.urlencoded({extended:!1,limit:"50mb"})),t.use((0,kT.default)()),t.use(Vp.default.json({limit:"50mb"}));let n={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:_e||so?"*":["http://localhost:3000","https://app.testim.io","https://staging.testim.io","https://playground.testim.io","https://app.staging.testim.cc","chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia","https://tta-crm.tricentis.com"]};return t.use("*",(0,CT.default)(n)),cT(t),t.use("/playground",Ua),t.use("/cliJs",Ma),t.use("/standalone-browser",AT(e)),t.use((o,i)=>{i.status(404).send("Endpoint Not Found")}),t}var CT,PT,Vp,kT,_T=T(()=>{"use strict";CT=E(require("cors")),PT=E(require("express")),Vp=E(require("body-parser")),kT=E(require("compression"));lT();dT();IT();xT();le()});var DT={};G(DT,{init:()=>SR});async function SR({agentPort:s,agentBind:e,project:t,token:r,installPlaygroundPlaywrightDeps:n,installPlaygroundPuppeteerDeps:o,installPlaygroundSeleniumDeps:i},a){await RR({installPlaygroundPlaywrightDeps:n,installPlaygroundPuppeteerDeps:o,installPlaygroundSeleniumDeps:i,project:t}),await IR({agentPort:s,agentBind:e,project:t,token:r},a)}async function IR({agentPort:s,agentBind:e,project:t,token:r},n){let{orchestrateRoutes:o}=await Promise.resolve().then(()=>(_T(),OT));return new Promise((i,a)=>{let l=()=>{};t&&($m(t,r),l=f=>{f.use((h,g,y)=>{Object.assign(h,{project:t}),y()})});let c=o(l,n),d=LT.createServer(c);d.listen(s,e),d.on("error",m),d.on("listening",u);function m(f){if(f.syscall!=="listen")return a(f);switch(f.code){case"EACCES":case"EPERM":return a(new P(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return a(new P(`Port ${s} is already in use, is another Testim instance running?`));default:return a(f)}}function u(){let{port:f}=d.address();console.log(`Running on port: ${f}`),AR()}})}function RR({installPlaygroundPlaywrightDeps:s,installPlaygroundPuppeteerDeps:e,installPlaygroundSeleniumDeps:t,project:r}){let n=[];return s&&n.push(Ie("playwright")),e&&n.push(Ie("puppeteer")),t&&n.push(Ie("selenium-webdriver"),Tr({projectId:r})),Promise.all(n)}async function AR(){await require("prompts")({name:"",type:"text",message:'Type the word "stop" or Press Ctrl + C.',validate:t=>t.toUpperCase().trim()==="STOP"}),console.log("Exiting Testim CLI"),process.exit(0)}var LT,NT=T(()=>{"use strict";LT=E(require("http"));ot();z();Ir();ts()});var WT={};G(WT,{getStartedWithStart:()=>Bp,runAgentMode:()=>kR});async function kR(s){var r;let e;if(await wr(s.playerLocation,s.canary),s.startTestimBrowser){await LR();try{e=await _R(s)}catch(n){throw(r=n==null?void 0:n.message)!=null&&r.includes("user data directory is already in use")?new P('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(NT(),DT));return e!=null&&e.webdriverApi&&setTimeout(async()=>{setTimeout(()=>(Tp(),ye(gb)));let o=["webpack"];for(let i of o)await Ie(i,{silent:!0}).catch(()=>null)},6e3),t.init(s,e)}function Bp(){return jT}function MT(s){try{return process.kill(s,0)}catch{return!1}}async function OR(s,e,t){let r=pr.join(Bt,`chrome-${nn}-process`),n=3e3,o=()=>{Pe.rmSync(r,{recursive:!0}),console.log(`
|
|
425
425
|
|
|
426
426
|
Browser session ended`),process.exit(0)};if(await ge(r)){let f=JSON.parse(Pe.readFileSync(r));if(MT(f.pid)){let h=()=>MT(f.pid)?setTimeout(h,n):o();return h(),{webdriverApi:f}}}let i=await Mo();await ge(Ls)||await Pe.promises.mkdir(Ls,{recursive:!0});let l=[...$T(Ls,e,t,i).desiredCapabilities.chromeOptions.args,...Ba.Launcher.defaultFlags().filter(f=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(f))],c={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},d=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`,m=await Ba.launch({chromeFlags:l,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:Ls,chromePath:i,envVars:c}),u={port:m.port,pid:m.pid,cdpUrl:await yr(`localhost:${m.port}`)};return Pe.writeFileSync(r,JSON.stringify(u)),m.process.once("exit",o),m.process.once("close",o),{webdriverApi:u}}async function _R(s){let e=`${dd}/extension/testim-full-master.zip`,t=pr.basename(e),r=pr.join(Bt,t),n=pr.join(Bt,`${t}__unzipped__`),o=!(s.ext||s.extensionPath);if(o&&await ge(r)){let f=await Pe.promises.stat(r);o=Date.now()-CR>f.mtimeMs}if(await Pe.promises.mkdir(Bt,{recursive:!0}),o){let f=(0,FT.default)("Downloading Testim Editor").start();await Ye(e,r);try{await st(r,n)}catch{await Pe.promises.rm(r,{recursive:!0,force:!0}),await Ye(e,r);try{await st(r,n)}catch{throw await Pe.promises.rm(r,{recursive:!0,force:!0}),f.fail("Failed to download Testim Editor"),new Error("Failed to download Testim Editor")}}finally{s.downloadBrowser||await Pe.promises.rm(n,{recursive:!0,force:!0})}f.succeed()}let i=s.extensionPath?null:(await Pe.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await OR(s,i,n);await Tr({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=$T(Ls,i,s.extensionPath,s.chromeBinaryLocations),{WebDriver:l}=(Ln(),ye(hh)),{SeleniumPerfStats:c}=(ms(),ye(Vg)),d=new l;d.seleniumPerfStats=new c;let m=await d.initClient(a);jT=!0;let u=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`;await d.url(u),Object.assign(d,{initialUrl:u});try{d.cdpUrl=await yr(m.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:d}}function $T(s,e,t,r){let n=e?[e]:[],o=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];return t&&o.push(`--load-extension=${t}`),{logLevel:xR,desiredCapabilities:{chromeOptions:{args:o,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function LR(){if(await ge(Fa))try{let{webSocketDebuggerUrl:s}=await DR();await NR(s),await Pe.promises.unlink(Fa)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Pe.promises.unlink(Fa)}}async function DR(){let s=await Pe.promises.readFile(Fa,{encoding:"utf8"}),[e,t]=s.split(`
|
|
427
|
-
`).map(o=>o.trim()),r=Number.parseInt(e,10);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await yr(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function NR(s,e=100){let t=await MR(s,e);return Yt(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function MR(s,e=100){let t=new BT.default(s,{timeout:e}),r=Yt(o=>{t.once("open",o)}).then(()=>{t.removeAllListeners()}),n=Yt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return Promise.race([r,n]).then(()=>t)}var UT,FT,BT,Pe,pr,Ba,xR,CR,Ls,PR,Fa,jT,jp=T(()=>{"use strict";UT=E(require("ms")),FT=E(require("ora")),BT=E(require("ws")),Pe=E(require("fs")),pr=E(require("path")),Ba=E(require("chrome-launcher"));le();ts();z();Ir();Hc();B();xR=oo?"verbose":"silent",CR=(0,UT.default)("1h"),Ls=pr.join(Bt,"profile"),PR="DevToolsActivePort",Fa=pr.join(Ls,PR);jT=!1});var
|
|
427
|
+
`).map(o=>o.trim()),r=Number.parseInt(e,10);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await yr(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function NR(s,e=100){let t=await MR(s,e);return Yt(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function MR(s,e=100){let t=new BT.default(s,{timeout:e}),r=Yt(o=>{t.once("open",o)}).then(()=>{t.removeAllListeners()}),n=Yt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return Promise.race([r,n]).then(()=>t)}var UT,FT,BT,Pe,pr,Ba,xR,CR,Ls,PR,Fa,jT,jp=T(()=>{"use strict";UT=E(require("ms")),FT=E(require("ora")),BT=E(require("ws")),Pe=E(require("fs")),pr=E(require("path")),Ba=E(require("chrome-launcher"));le();ts();z();Ir();Hc();B();xR=oo?"verbose":"silent",CR=(0,UT.default)("1h"),Ls=pr.join(Bt,"profile"),PR="DevToolsActivePort",Fa=pr.join(Ls,PR);jT=!1});var gN=require("source-map-support/register");Array.prototype.at||=function(s){let e=Number.isInteger(s)?s:0,t=e>=0?e:this.length+e;if(!(t<0||t>=this.length))return this[t]};var Yp=require("perf_hooks");var to=E(require("os")),Ns=E(require("url")),Ms=E(require("http")),Va=E(require("https")),Jn=E(require("form-data")),Yn=class{constructor(){this.onloadstart=null;this.onprogress=null;this.onabort=null;this.onerror=null;this.onload=null;this.ontimeout=null;this.onloadend=null;this._listeners={}}addEventListener(e,t){e=e.toLowerCase(),this._listeners[e]||=[],this._listeners[e].push(t)}removeEventListener(e,t){let r;e=e.toLowerCase(),this._listeners[e]&&(r=this._listeners[e].indexOf(t),r!==-1&&this._listeners[e].splice(r,1))}dispatchEvent(e){var n;e.currentTarget=this,e.target=this;let t=e.type,r=this._listeners[t]||[];for(let o of r)o==null||o.call(this,e);(n=this[`on${t}`])==null||n.call(this,e)}},Xn=class extends Yn{constructor(t){super();this._request=t;this._contentType=null;this._body=null}_reset(){this._contentType=null,this._body=null}_setData(t){if(t!=null)if(typeof t=="string")t.length!==0&&(this._contentType="text/plain;charset=UTF-8"),this._body=Buffer.from(t,"utf8");else if(Buffer.isBuffer(t))this._body=t;else if(t instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=new Uint8Array(t);for(let o=0;o<t.byteLength;o++)r[o]=n[o];this._body=r}else if("buffer"in t&&t.buffer instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=t.byteOffset,o=new Uint8Array(t.buffer);for(let i=0;i<t.byteLength;i++)r[i]=o[i+n];this._body=r}else if(typeof t=="object"&&t instanceof Jn.default)this._body=null;else throw new Error(`Unsupported send() data ${t}`)}_finalizeHeaders(t,r){this._contentType&&!("content-type"in r)&&(t["Content-Type"]=this._contentType),this._body&&(t["Content-Length"]=this._body.length.toString())}_startUpload(t){this._body&&t.write(this._body),t.end()}},Ds=class{constructor(e){this.type=e;this.target=null;this.currentTarget=null;this.lengthComputable=!1;this.loaded=0;this.total=0;this.bubbles=!1;this.cancelable=!1}},Qn=class extends Error{},Zn=class extends Error{},eo=class extends Error{},mr=class extends Error{},Re=class extends Yn{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=Ms.globalAgent;this.nodejsHttpsAgent=Va.globalAgent;this.nodejsBaseUrl=null;this._restrictedMethods={CONNECT:!0,TRACE:!0,TRACK:!0};this._restrictedHeaders={"accept-charset":!0,"accept-encoding":!0,"access-control-request-headers":!0,"access-control-request-method":!0,connection:!0,"content-length":!0,cookie:!0,cookie2:!0,date:!0,dnt:!0,expect:!0,host:!0,"keep-alive":!0,origin:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,via:!0};this._privateHeaders={"set-cookie":!1,"set-cookie2":!1};this._userAgent=`Mozilla/5.0 (${to.type()} ${to.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=Re.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new Xn(this);this._method=null;this._url=null;this._sync=!1;this._headers=null;this._loweredHeaders=null;this._mimeOverride=null;this._request=null;this._response=null;this._responseParts=null;this._responseHeaders=null;this._aborting=null;this._error=null;this._loadedBytes=0;this._totalBytes=0;this._lengthComputable=!1;this._anonymous=t==null?void 0:t.anon}static nodejsSet(t){Re.prototype.nodejsSet(t)}nodejsSet(t){if("httpAgent"in t&&(this.nodejsHttpAgent=t.httpAgent),"httpsAgent"in t&&(this.nodejsHttpsAgent=t.httpsAgent),"baseUrl"in t){let r=t.baseUrl;if(r!==null&&!Ns.parse(r,!1,!0).protocol)throw new Qn("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new eo(`HTTP method ${t} is not allowed in XHR`);let o=this._parseUrl(r);n===void 0&&(n=!0),this._method=t,this._url=o,this._sync=!n,this._headers={},this._loweredHeaders={},this._mimeOverride=null,this._setReadyState(Re.OPENED),this._request=null,this._response=null,this.status=0,this.statusText="",this._responseParts=[],this._responseHeaders=null,this._loadedBytes=0,this._totalBytes=0,this._lengthComputable=!1}setRequestHeader(t,r){if(this.readyState!==Re.OPENED)throw new mr("XHR readyState must be OPENED");let n=t.toLowerCase();this._restrictedHeaders[n]||/^sec-/.test(n)||/^proxy-/.test(n)||(r=r.toString(),n in this._loweredHeaders?(t=this._loweredHeaders[n],this._headers[t]=`${this._headers[t]}, ${r}`):(this._loweredHeaders[n]=t,this._headers[t]=r))}send(t){if(this.readyState!==Re.OPENED)throw new mr("XHR readyState must be OPENED");if(this._request)throw new mr("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new Zn(`Unsupported protocol ${this._url.protocol}`)}}abort(){this._request&&(this._request.abort(),this._setError(),this._dispatchProgress("abort"),this._dispatchProgress("loadend"))}getResponseHeader(t){var n;let r=t.toLowerCase();return((n=this._responseHeaders)==null?void 0:n[r])||null}getAllResponseHeaders(){return this._responseHeaders?Object.entries(this._responseHeaders).map(([t,r])=>`${t}: ${r}`).join(`\r
|
|
428
428
|
`):""}overrideMimeType(t){if([Re.LOADING,Re.DONE].includes(this.readyState))throw new mr("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new Ds("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new Zn("The file protocol only supports GET"):new Error("Protocol file: not implemented")}_sendHttp(t){if(this._sync)throw new Error("Synchronous XHR processing not implemented");t!=null&&(this._method==="GET"||this._method==="HEAD")?t=null:t||="",this.upload._setData(t),this._finalizeHeaders(t),this._sendHxxpRequest(t)}_sendHxxpRequest(t){let r=this._url.protocol==="http:"?this.nodejsHttpAgent:this.nodejsHttpsAgent,o=(this._url.protocol==="http:"?Ms:Va).request({hostname:this._url.hostname,port:this._url.port,path:this._url.path,auth:this._url.auth,method:this._method,headers:this._headers,agent:r});typeof t=="object"&&t instanceof Jn.default&&t.pipe(o),this._request=o,this.timeout&&o.setTimeout(this.timeout,()=>this._onHttpTimeout(o)),o.on("response",i=>this._onHttpResponse(o,i)),o.on("error",()=>this._onHttpRequestError(o)),this.upload._startUpload(o),this._request===o&&this._dispatchProgress("loadstart")}_finalizeHeaders(t){typeof t=="object"&&t instanceof Jn.default&&Object.assign(this._headers,t.getHeaders()),this._headers.Connection="keep-alive",this._headers.Host=this._url.host,this._anonymous&&(this._headers.Referer="about:blank"),this._headers["User-Agent"]=this._userAgent,this.upload._finalizeHeaders(this._headers,this._loweredHeaders)}_onHttpResponse(t,r){if(this._request!==t)return;if([301,302,303,307,308].includes(r.statusCode)){this._url=this._parseUrl(r.headers.location),this._method="GET","content-type"in this._loweredHeaders&&(delete this._headers[this._loweredHeaders["content-type"]],delete this._loweredHeaders["content-type"]),"Content-Type"in this._headers&&delete this._headers["Content-Type"],delete this._headers["Content-Length"],this.upload._reset(),this._finalizeHeaders(),this._sendHxxpRequest();return}this._response=r,this._response.on("data",o=>this._onHttpResponseData(r,o)),this._response.on("end",()=>this._onHttpResponseEnd(r)),this._response.on("close",()=>this._onHttpResponseClose(r)),this.status=this._response.statusCode,this.statusText=Ms.STATUS_CODES[this.status],this._parseResponseHeaders(r);let n=this._responseHeaders["content-length"];n?(this._totalBytes=parseInt(n,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(Re.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==Re.LOADING&&this._setReadyState(Re.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Re.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend")}_onHttpResponseClose(t){if(this._response!==t)return;let r=this._request;return this._setError(),r.abort(),this._setReadyState(Re.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Re.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Re.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let r=new Ds(t);r.lengthComputable=this._lengthComputable,r.loaded=this._loadedBytes,r.total=this._totalBytes,this.dispatchEvent(r)}_setError(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null}_parseUrl(t){let r,n,o,i=this.nodejsBaseUrl===null?t:Ns.resolve(this.nodejsBaseUrl,t),a=Ns.parse(i,!1,!0);return a.hash=null,a.auth&&(o!=null||n!=null)&&(r=a.auth.indexOf(":"),r===-1?o||(o=a.auth):(o||(o=a.substring(0,r)),n||(n=a.substring(r+1)))),(o||n)&&(a.auth=`${o}:${n}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([r,n])=>{let o=r.toLowerCase();this._privateHeaders[o]||(this._mimeOverride!==null&&o==="content-type"&&(n=this._mimeOverride),this._responseHeaders[o]=n)}),this._mimeOverride!==null&&!("content-type"in this._responseHeaders)&&(this._responseHeaders["content-type"]=this._mimeOverride)}_parseResponse(){let t=Buffer.concat(this._responseParts);switch(this._responseHeaders["content-encoding"]==="gzip"&&(t=require("zlib").gunzipSync(t)),this._responseParts=null,this.responseType){case"text":this._parseTextResponse(t);break;case"json":this.responseText=null;try{this.response=JSON.parse(t.toString("utf-8"))}catch{this.response=null}break;case"buffer":this.responseText=null,this.response=t;break;case"arraybuffer":{this.responseText=null;let r=new ArrayBuffer(t.length),n=new Uint8Array(r);for(let o=0;o<t.length;o++)n[o]=t[o];this.response=r;break}default:this._parseTextResponse(t)}}_parseTextResponse(t){try{this.responseText=t.toString(this._parseResponseEncoding())}catch{this.responseText=t.toString("binary")}this.response=this.responseText}_parseResponseEncoding(){let t=this._responseHeaders["content-type"],r=/;\s*charset=(.*)$/.exec(t);return t&&r?r[1]:"utf-8"}},ke=Re;ke.SyntaxError=Qn,ke.ProgressEvent=Ds,ke.SecurityError=eo,ke.XMLHttpRequest=Re,ke.InvalidStateError=mr,ke.XMLHttpRequestUpload=Xn,ke.UNSENT=0,ke.OPENED=1,ke.HEADERS_RECEIVED=2,ke.LOADING=3,ke.DONE=4;Object.assign(global,{xhr2:ke,XMLHttpRequest:ke,performance:Yp.performance,...typeof Blob>"u"&&{Blob:require("buffer").Blob}});var VT=E(require("semver"));Ve();Ul();jt();ts();var Gp=E(require("chalk")),GT=require("events");ae();fn();z();ae();$o();j();var rf=E(require("os")),Fl=E(require("path")),Bl=E(require("chalk")),Ko=require("fs");le();function sf(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=rf.homedir();(0,Ko.mkdirSync)(Fl.resolve(n,".testim_logs"),{recursive:!0});let o=Fl.resolve(n,".testim_logs",`${new Date().toISOString().replace(/:|\./g,"_")}.log`);console.log("Oops :( The test runner has encountered an unexpected error. A complete log of this run can be found in:"),console.log(` ${o}`),ad&&console.log(`Call stack: ${s==null?void 0:s.stack}`),(t=s==null?void 0:s.message)!=null&&t.includes("Unable to compile TypeScript")&&((r=s.stack)!=null&&r.includes("runner/src"))&&process.argv.some(i=>i.includes("player-require-path"))&&(console.log(Bl.default.red("Looks like you got a TypeScript compile error champ - but it's not a very good one because we use TypeScript in transpile-only mode")),console.log(Bl.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Ko.writeFileSync)(o,`${s}
|
|
429
429
|
${s==null?void 0:s.stack}
|
|
430
430
|
|
|
431
|
-
${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}tn();var Iv=x("process-handler"),nf=!1;function Rv(s){return s instanceof Error?1:nf?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:o})=>[t,o].includes(pe.SKIPPED)||[t,o].includes(pe.FAILED)&&n===Xe.EVALUATING?!1:r!==!0)?1:0)}function Av(){try{Qt("chromedriver").stop()}catch{}}function of(){nf=!0}async function jl(s){s!=null&&s.stack&&(rs?console.error(s,s.stack):sf(s)),Av(),await Iv.waitForFlush(),process.exit(Rv(s))}he();j();de();var UR=x("cli-entry");function FR(s){if(!VT.satisfies(process.version,s))throw new P(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=
|
|
431
|
+
${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}tn();var Iv=x("process-handler"),nf=!1;function Rv(s){return s instanceof Error?1:nf?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:o})=>[t,o].includes(pe.SKIPPED)||[t,o].includes(pe.FAILED)&&n===Xe.EVALUATING?!1:r!==!0)?1:0)}function Av(){try{Qt("chromedriver").stop()}catch{}}function of(){nf=!0}async function jl(s){s!=null&&s.stack&&(rs?console.error(s,s.stack):sf(s)),Av(),await Iv.waitForFlush(),process.exit(Rv(s))}he();j();de();var UR=x("cli-entry");function FR(s){if(!VT.satisfies(process.version,s))throw new P(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=18,t=20,r=Number(process.versions.node.split(".")[0]),n=new Date("2025-04-30T00:00:00.000Z"),o=n<=new Date,i=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(n);if(r<e)throw new P(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&o)throw new P(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(Gp.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${i}. please upgrade to a newer Node.js version.`))}async function BR(){console.log("Starting Testim.io CLI");let[s,e]=await Promise.all([Promise.resolve().then(()=>(B(),J)),Promise.resolve().then(()=>(Cf(),xf))]);M("Starting Testim.io CLI"),tf(jl);try{FR(s.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{await D.fetch();let t=await e.process();if(M("in main, after options.process"),oc(global.proxyUri),GT.EventEmitter.defaultMaxListeners="parallel"in t&&t.parallel>10?t.parallel*3:30,nc(t.project),pm("token"in t&&typeof t.token=="string"?t.token:"anonymous_encrypt_key"),s.isInstallLazyDepsMode(t)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:o}=await Promise.resolve().then(()=>(Ir(),_f));return await o()}if(s.isLoginMode(t))return;if(s.isCreatePrefetchedDataMode(t)){await Xr(),await dn(t);let{preloadTests:o}=await Promise.resolve().then(()=>(ti(),Df));await o(t),!t.playerRequirePath&&t.mode!==Q.EXTENSION&&await wr(t.playerLocation,t.canary);let i=await lm();i.success?console.log(`created prefetched data at ${Ao()}`):console.error("failed to create prefetch data",i.error);return}let r=await Promise.resolve().then(()=>(aT(),iT));if(s.isTunnelOnlyMode(t)){await r.init(t);let{serveTunneling:o}=await Promise.resolve().then(()=>(au(),iu));await o(t);return}if(s.isAgentMode(t)){let{runAgentMode:o}=await Promise.resolve().then(()=>(jp(),WT));return o(t)}if(t.saveRCALocally){let{initServer:o}=await Promise.resolve().then(()=>(Ou(),zg)),{port:i}=await o(t);t.localRCASaver=`http://localhost:${i}`}t.exitCodeIgnoreFailingTests&&of(),M("right before testRunner.init/prepareRunner.prepare");let[n]=await Promise.all([Qm(t),r.init(t)]);return M("right after testRunner.init/prepareRunner.prepare"),await r.run(t,n)}catch(t){if(t instanceof Br)return;let r=s.getArgsOnRemoteRunFailure();return r&&await xl({...r,error:t.message}).catch(()=>{}),t instanceof P?(console.log(Gp.default.red("Argument Error:",t.message)),t):(console.log("Error:",t.message),UR.error("runner ended with unexpected error",{err:t}),t)}}BR().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),jl(s)});
|
|
432
432
|
//# sourceMappingURL=cli.js.map
|