@testim/testim-cli 4.63.0 → 4.64.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 +12 -12
- package/cli.js.map +3 -3
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#! /usr/bin/env node
|
|
2
|
-
"use strict";var ET=Object.create;var Vn=Object.defineProperty;var ST=Object.getOwnPropertyDescriptor;var IT=Object.getOwnPropertyNames;var RT=Object.getPrototypeOf,xT=Object.prototype.hasOwnProperty;var T=(s,e)=>()=>(s&&(e=s(s=0)),e);var V=(s,e)=>{for(var t in e)Vn(s,t,{get:e[t],enumerable:!0})},Fp=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of IT(e))!xT.call(s,n)&&n!==t&&Vn(s,n,{get:()=>e[n],enumerable:!(r=ST(e,n))||r.enumerable});return s};var v=(s,e,t)=>(t=s!=null?ET(RT(s)):{},Fp(e||!s||!s.__esModule?Vn(t,"default",{value:s,enumerable:!0}):t,s)),he=s=>Fp(Vn({},"__esModule",{value:!0}),s);var je={};V(je,{log:()=>N,measure:()=>CT});function N(...s){if(!$p)return;let e=Date.now();console.log(`${e-AT} ${e-jp} `,...s),jp=e}function CT(s,e){if(!$p)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var $p,AT,jp,$e=T(()=>{"use strict";$p=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,AT=Date.now(),jp=Date.now()});var _a,zt,La,Mr=T(()=>{"use strict";_a={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",La=79});function re(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function qe(s,e,t,r,n){let o="";return n=n?encodeURIComponent(n):"master",e&&t&&(o=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(o+=`?result-id=${r}`)),o}function Da(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function We(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 Ma=T(()=>{"use strict"});var Ua,Wp,Vp,Xn=T(()=>{Ua={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"},Wp={"@applitools/eyes-sdk-core":"13.11.32","@applitools/spec-driver-webdriverio":"1.4.29","coralogix-logger":"1.1.28","@types/unzip-stream":"0.3.2",ajv:"6.12.6","analytics-node":"5.0.0","body-parser":"1.20.1",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4",cors:"2.8.5","data-uri-to-buffer":"2.0.2",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:"0.15.3",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2",npm:"8.19.2","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"6.3.1","rox-node":"4.9.18",semver:"7.5.4","serialize-error":"7.0.1","socket.io-client":"4.6.2","source-map-support":"0.5.19",superagent:"3.8.3","superagent-proxy":"3.0.0","test-exclude":"6.0.0","ua-parser-js":"0.7.33","unzip-stream":"0.3.1","validate-npm-package-name":"3.0.0",webdriverio:"7.24.0",winston:"3.6.0","winston-transport":"4.5.0",ws:"8.5.0",xml2js:"0.6.2",yaml:"2.2.2"},Vp={node:">= 16.0.0"}});var Ds,Gp,Hp,Qn,qp,Zn,Ms,zp,me,Kp,Jp,eo,Oe,Fa,Yp,to,Xp,
|
|
3
|
-
${c.msg}`));for(let u of _T)a[u]instanceof Error&&(c[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(c).length>0&&(i&&!m&&(c.msg=i),d.text=c),this.logger.addLog(d),r(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Re.CoralogixLogger.configure(t),Ur.options=t}}});var Ka={};V(Ka,{getLogger:()=>x,setExecutionId:()=>Ha,setProjectId:()=>qa,setProxyUri:()=>za});function MT(){let s=[],e=()=>Promise.resolve();if(!Oe){let{CoralogixTransport:t}=(Wa(),he($a));t.configure(bd);let r=new t({category:"ROOT"});s.push(r),e=()=>r.waitForFlush()}return Kp&&s.push(new St.transports.Console({format:St.format.combine(St.format.colorize(),St.format.simple())})),[s,e]}function Ha(s){Va=s}function qa(s){Td=s}function za(s){if(Oe||!s)return;let{CoralogixTransport:e}=(Wa(),he($a));e.configure({...bd,proxyUri:s})}function hd(s){return{projectId:Td,time:new Date().toISOString(),...Va&&!s&&{executionId:Va}}}function x(s){return new Ga(jT.child({category:s}))}var yd,St,LT,DT,bd,NT,UT,FT,BT,jT,Va,Td,Ga,j=T(()=>{"use strict";yd=v(require("os")),St=v(require("winston"));le();B();LT=yd.hostname(),DT=dt(),bd={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};[NT,UT]=MT(),FT=Jp?"debug":"info",BT={release:Boolean(!0),branch:"production"},jT=St.createLogger({levels:St.config.syslog.levels,level:FT,transports:NT,defaultMeta:{name:"runner",hostname:LT,nodeVersion:process.version,runnerVersion:DT,...BT}}),Va=null,Td=null;Ga=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},hd(n)))}catch(o){try{this._logger.log("crit",Object.assign({message:`failed to log message ${o.message}, ${o.stack}`},hd(n)))}catch{}}}waitForFlush(){return UT()}}});var oo,Fr,C,Kt,fr,It,ro,Br,ne,Us,ze,Jt,Rt,so,jr,$r,Wr,no,Fs,q=T(()=>{"use strict";oo=require("p-retry"),Fr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},C=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}},It=class extends oo.AbortError{},ro=class extends oo.AbortError{},Br=class extends oo.AbortError{},ne=class extends Error{},Us=class extends Error{},ze=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Jt=class extends ze{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Rt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},so=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},jr=class extends Error{},$r=class extends Error{constructor(t){super();this.innerStack=t}},Wr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},no=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Fs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Ja(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function oe(s){return(0,Ed.setTimeout)(s)}function Ya(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"){Zn&&!wd&&(wd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ne(t);return e=Zn?Number(Zn)||6e5:e,Promise.race([s,oe(e).then(()=>{throw r})])}async function ie(s,e,{concurrency:t}={}){if(t){vd||=(await import("p-limit")).default;let r=vd(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 Ed,wd,vd,Xa=T(()=>{"use strict";Ed=require("timers/promises");q();le();wd=!1});var js,Sd,$T,Bs,Id,WT,VT,Rd,xd=T(()=>{"use strict";js=v(require("lodash"));le();Sd=require("dns");j();Xa();$T=x("http-request-counters"),Bs=!1,Id=async()=>{if(Oe)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ie(s,t=>Sd.promises.lookup(t)));return e||(Bs=!0),e}catch{return $T.error("network connectivity test failed"),Bs=!0,!1}},WT=js.throttle(Id,10*1e3),VT=60*1e3*15,Rd=()=>{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)},VT)}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),Bs||WT(),a}}}async function r(){if(Bs||!await Id())return!1;let n=js.sum([...s.fail.values()]),o=js.sum([...s.call.values()]);return n<o*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>Bs,t}});var tt={};V(tt,{deleteFullRes:()=>KT,deleteReq:()=>$s,didNetworkConnectivityTestFail:()=>oc,download:()=>sc,get:()=>Ee,getFullRes:()=>YT,getText:()=>Vs,head:()=>XT,isNetworkHealthy:()=>nc,post:()=>Ge,postForm:()=>Ws,postFullRes:()=>JT,postText:()=>tc,put:()=>rc});function HT(){return global.caFileContent}function qT(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function zT(){return!xt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(xt.default),global.proxyUri}function gr(s,e=!1){let t=HT();t&&s.ca(t);let r=!e&&zT();r&&s.proxy(r)}async function Ad(s,e={},t={},r=Vr){let n=xt.default.delete(s).send(e).timeout(r).set(t);return gr(n),await n}async function Za(s,e,t={},r=Vr,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 ec(s,e,t={},r=Vr,{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,Qa,Ve,Vr,GT,Dt,$s,KT,Ge,JT,Ws,Vs,tc,Ee,YT,XT,rc,sc,nc,oc,Ke=T(()=>{"use strict";xt=v(require("superagent"));j();xd();Qa=x("http-request"),Ve=Rd(),Vr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,GT=6e4;Dt=(s,e,t)=>{throw Qa.error(s,{...t,error:e}),e};$s=Ve(async(s,e,t,r)=>{try{let n=await Ad(s,e,t,r);return n.type==="text/plain"?n.text:n.body}catch(n){return Dt("failed to delete request",n,{url:s})}});KT=Ve(Ad),Ge=Ve(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let o=await Za(s,e,t,r,n);return o.type==="text/plain"?o.text:o.body}catch(o){return Dt("failed to post request",o,{url:s})}});JT=Ve(Za),Ws=Ve(async(s,e,t,r={},n=Vr)=>{let o=xt.default.post(s).type("form").timeout(n).set(r);o.field(e),Object.entries(t).forEach(([i,a])=>{o.attach(i,a.buffer,a.fileName)}),gr(o);try{let i=await o;return i.type==="text/plain"?i.text:i.body}catch(i){return Dt("failed to post request",i,{url:s})}});Vs=Ve(async(s,e,t)=>{try{return(await ec(s,e,t)).text}catch(r){return Dt("failed to getText request",r,{url:s,query:e})}}),tc=Ve(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await Za(s,e,t,r,n)).text}catch(o){return Dt("failed to post request",o,{url:s})}}),Ee=Ve(async(s,e,t,r,n)=>{try{return(await ec(s,e,t,r,n)).body}catch(o){return Dt("failed to get request",o,{url:s,query:e})}}),YT=Ve((s,e,t,r)=>ec(s,e,t,r)),XT=Ve(async s=>{let e=xt.default.head(s).timeout(Vr);gr(e);try{return await e}catch(t){return Dt("failed to head request",t,{url:s})}}),rc=Ve(async(s,e,t={},r=Vr)=>{let n=xt.default.put(s).send(e).timeout(r).set(t);gr(n);try{return(await n).body}catch(o){return Dt("failed to put request",o,{url:s})}}),sc=Ve(async s=>{Qa.info("start to download",{url:s});let e=xt.default.get(s).timeout(GT).buffer(!0).parse(qT);gr(e);try{let t=await e;return Qa.info("finished to download",{url:s}),t}catch(t){return Dt("failed to download",t,{url:s})}}),nc=Ve.isNetworkHealthy,oc=Ve.didNetworkConnectivityTestFail});function mt(){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 io(s,e){return We(s)?e||Mt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Mt.basename(s)}function dt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function ZT(){try{return Vp.node}catch{return""}}async function kd(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 kd(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,Cd,Pd,rt,QT,Nt,Je,ao,ic,st,ac,Od=T(()=>{"use strict";Mt=v(require("path"));Ma();Xn();Cd=v(require("unzip-stream")),Pd=v(require("p-retry")),rt=require("fs"),QT=3;Nt=async s=>{let e=await Promise.resolve().then(()=>(Ke(),tt));return(0,Pd.default)(()=>e.download(s),{retries:QT,factor:1})},Je=async(s,e)=>{let t=await Nt(s);return rt.promises.writeFile(e,t.body)};ao=async(s,e)=>{let t=io(s,e);return We(s)?Je(s,t):rt.promises.copyFile(s,t)},ic=async s=>We(s)?Nt(s):rt.promises.readFile(s),st=async(s,e)=>await(0,rt.createReadStream)(s).pipe(Cd.Extract({path:e})),ac=s=>(0,rt.statSync)(s).size/1e6});var Ut={};V(Ut,{APPIUM_SESSION_MESSAGE:()=>dc,CLI_MODE:()=>Y,MOBILE_APP_SOURCE:()=>co,MOBILE_RUN_SKIP_REASON:()=>pc,gridMessages:()=>ft,gridTypes:()=>O,mobileWeb:()=>lc,runnerStatus:()=>cc,runnerTestStatus:()=>pe,socketEventTypes:()=>At,stepResult:()=>Hs,test:()=>uc,testRunStatus:()=>Gs,testStatus:()=>Ye,timeoutMessages:()=>Fe});var Fe,Gs,cc,pe,Ye,ft,lc,uc,At,Y,O,Hs,co,pc,dc,ae=T(()=>{"use strict";Fe={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Gs={COMPLETED:"completed",RUNNING:"running"},cc={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"},Ye={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},ft={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},lc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},uc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},At={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},Y={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},O={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},Hs={SETUP_TIMEOUT:"setup-timeout",NETWORK_ERROR:"network-error",GRID_ERROR:"grid-error",SELENIUM_ERROR:"selenium-error",BROWSER_CLOSED:"browser-closed",MOBILE_SESSION_ERROR:"mobile-session-error",UNKNOWN_ERROR:"unknown-error"},co={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},pc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},dc={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 qs(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 ew(){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 zs,_d,Xe,tw,rw,sw,nw,ow,mc,fc,Ld=T(()=>{"use strict";ae();zs=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},_d=s=>Boolean(s.resultId&&s.source==="remote-run"),Xe=(s,e)=>s.testStatus===Ye.QUARANTINE&&!_d(e)&&!e.runQuarantinedTests;tw=s=>Boolean(s.loginMode),rw=s=>Boolean(s.tunnelOnlyMode),sw=s=>Boolean(s.createPrefechedData),nw=s=>Boolean(s.installLazyDepsMode),ow=s=>Boolean(s.agentMode),mc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},fc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function uo(s=0){return lo.default.duration(s).format("HH:mm:ss.SSS")}function gc(s=0){return lo.default.duration(s).asSeconds()}var lo,Dd,Md=T(()=>{"use strict";lo=v(require("dayjs")),Dd=v(require("dayjs/plugin/duration"));lo.default.extend(Dd.default)});var Ks,Gr,Js,Nd,Hr,Ud=T(()=>{"use strict";ae();Ks=s=>!(!s||"fileName"in s),Gr=(s,e)=>e===O.TESTIM_TVC?!1:s&&"fileName"in s?s.fileName.endsWith(".app"):!1,Js=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},Nd=s=>s===O.TESTIM_TVC,Hr=(s,e)=>Nd(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function hc(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 Fd=T(()=>{"use strict"});var K={};V(K,{OSS:()=>qr,TESTIM_BROWSER_DIR:()=>Ft,buildBasicHeader:()=>Da,calcPercentile:()=>fo,copyDir:()=>kd,delay:()=>oe,doesPathExist:()=>ge,download:()=>Nt,downloadAndSave:()=>Je,extractElementId:()=>Le,getArgsOnRemoteRunFailure:()=>ew,getBrowserInfo:()=>aw,getCdpAddressForHost:()=>br,getCliLocation:()=>mt,getDuration:()=>uo,getDurationSec:()=>gc,getEnginesVersion:()=>ZT,getEnvironmentGitBranch:()=>yr,getLocalFileSizeInMB:()=>ac,getMemorySnapshot:()=>hc,getPlanType:()=>mo,getRunConfigByBrowserName:()=>Ys,getRunnerVersion:()=>dt,getSource:()=>ao,getSourceAsBuffer:()=>ic,getSourcePath:()=>io,getTestUrl:()=>qe,getUniqBrowsers:()=>qs,groupTestsByRetries:()=>bc,guid:()=>re,hasTestPlanFlag:()=>zs,isAgentMode:()=>ow,isAppFromDevice:()=>Ks,isAppFromDeviceDisabled:()=>Hr,isCreatePrefetchedDataMode:()=>sw,isInstallLazyDepsMode:()=>nw,isLoginMode:()=>tw,isMobileProject:()=>Js,isPromise:()=>Ja,isQuarantineAndNotRemoteRun:()=>Xe,isRemoteRun:()=>_d,isTestimVirtualGrid:()=>Nd,isTunnelOnlyMode:()=>rw,isURL:()=>We,promiseAbort:()=>Ya,promiseFromCallback:()=>Yt,promiseMap:()=>ie,promiseTimeout:()=>ce,removePropertyFromObject:()=>po,replaceArgsWithNoDashes:()=>mc,shouldBlockVirtualIosBuild:()=>Gr,spreadObjectToArgs:()=>fc,unzipFile:()=>st});function aw(s){return s=s.toLowerCase(),yc.find(e=>e.browserValue===s)}function Ys(s,e,t){s=s==null?void 0:s.toLowerCase();let r=yc.find(o=>o.browserName.toLowerCase()===s||s.includes(o.synonyms))||yc[0],n=qr.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=qr.find(o=>o.sl.platform===e.platform):e.platformName&&(n=qr.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=qr.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=qr.find(o=>o.bs.platform===t.platform))),hr.merge(r,n)}function yr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function po(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&po(s[r],e,t))}function Le(s){return s.ELEMENT||s[zt]}function mo(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function bc(s=[]){return hr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=hr.orderBy(t,o=>typeof o.retryCount=="number"?o.retryCount:1),n=hr.chain(r).last().cloneDeep().value();return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}async function br(s,e){let t=await Promise.resolve().then(()=>(Ke(),tt));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 Bd,hr,jd,iw,Ft,qr,yc,fo,B=T(()=>{"use strict";Bd=v(require("os")),hr=v(require("lodash")),jd=v(require("path"));Mr();Od();Ld();Md();Ma();Xa();Ud();Fd();iw=Bd.homedir(),Ft=jd.join(iw,".testim-browser-profile"),qr=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14"},sl:{platform:"macOS 11",safari_version:"14"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13"},sl:{platform:"macOS 10.15",safari_version:"13"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12"},sl:{platform:"macOS 10.14",safari_version:"12"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11"},sl:{platform:"macOS 10.13",safari_version:"11"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10"},sl:{platform:"macOS 10.12",safari_version:"10.0"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"9.0"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"8.0"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"7.0"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"6.0"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],yc=[{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"}];fo=(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 Tc={};V(Tc,{$schema:()=>cw,default:()=>mw,definitions:()=>lw,properties:()=>dw,required:()=>pw,type:()=>uw});var cw,lw,uw,pw,dw,mw,$d=T(()=>{cw="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}}}},uw="object",pw=["entries"],dw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},mw={$schema:cw,definitions:lw,type:uw,required:pw,properties:dw}});async function Kd(){try{return await ce(go.promises.readFile(To()).then(async s=>{let e=await zd;return hw(e,s)}),3e4)}catch{return{}}}function hw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),o=Kr.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 gt(s,e,t=fw,r=void 0){return async()=>{if(!Gd)return await s();let n=e;r&&(e+=JSON.stringify(r));let o=await yw(e);if(o)return Xs.debug("cache hit:",{fnName:e}),o;if(Xs.debug("cache miss:",{fnName:e}),!Hd)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 bw(e,i,t),i}}async function yw(s){let t=(await wo)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function bw(s,e,t){if(wc)throw Xs.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 wo;r[s]={value:e,expiry:Date.now()+t},qd=new Promise(n=>{bo=n}),gw(r)}catch{Xs.error("failed updating cache")}}async function Jr(){let s=await wo;Object.keys(s).forEach(e=>{delete s[e]})}function Jd(s){Gd=s}function Tw(s=!0){Hd=s}async function Yd(){try{return wc=!0,await qd}finally{wc=!1}}function Xd(s){yo=s,wo=Kd()}var go,ho,Kr,Wd,Xs,yo,Vd,bo,Gd,Hd,wc,qd,zd,fw,To,wo,gw,Qd,Zd,WR,em,Bt=T(()=>{"use strict";go=v(require("fs")),ho=v(require("path")),Kr=v(require("crypto"));B();Wd=require("lodash");j();Xs=x("local cache"),yo=ho.resolve(mt(),"testim-cache"),Gd=!0,Hd=!0,wc=!1,qd=new Promise(s=>{bo=s}),zd=new Promise(s=>{Vd=s}),fw=1e3*60*60*3,To=()=>ho.resolve(ho.resolve(yo,"testim.cache"));wo=Kd(),gw=(0,Wd.debounce)(async s=>{let e;try{let t=await zd,r=Kr.randomBytes(16),n=JSON.stringify(s),o=Buffer.from(t),i=Kr.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),r),a=Buffer.concat([r,i.update(n),i.final()]);await ge(yo)||await go.promises.mkdir(yo,{recursive:!0}),await go.promises.writeFile(To(),a)}catch(t){Xs.error("failed saving cache",{err:t}),e=t}bo(e?{success:!1,error:e}:{success:!0})},200);Qd=Vd,Zd=Jd.bind(void 0,!1),WR=Jd.bind(void 0,!0),em=()=>Tw(!1)});function vo(){return{cliLocation:mt(),userInfo:Yr.userInfo(),platform:Yr.platform(),release:Yr.release()}}var Yr,vc=T(()=>{"use strict";Yr=v(require("os"));B()});function ww(s){try{return Eo.resolve(Eo.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=ww(s);return require(e)}var Eo,Qs=T(()=>{"use strict";Eo=v(require("path"))});function vw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Ew(s){return/The "to" argument must be of type string./.exec(s)}function nm(s,e,t){let r=vw(s),n=Ew(s);return r||n?(sm.info("Failed to install package due to insufficient write access",{...vo(),package:t,path:r}),console.error(`
|
|
2
|
+
"use strict";var ET=Object.create;var Vn=Object.defineProperty;var ST=Object.getOwnPropertyDescriptor;var IT=Object.getOwnPropertyNames;var RT=Object.getPrototypeOf,xT=Object.prototype.hasOwnProperty;var T=(s,e)=>()=>(s&&(e=s(s=0)),e);var V=(s,e)=>{for(var t in e)Vn(s,t,{get:e[t],enumerable:!0})},Fp=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of IT(e))!xT.call(s,n)&&n!==t&&Vn(s,n,{get:()=>e[n],enumerable:!(r=ST(e,n))||r.enumerable});return s};var v=(s,e,t)=>(t=s!=null?ET(RT(s)):{},Fp(e||!s||!s.__esModule?Vn(t,"default",{value:s,enumerable:!0}):t,s)),he=s=>Fp(Vn({},"__esModule",{value:!0}),s);var je={};V(je,{log:()=>N,measure:()=>CT});function N(...s){if(!$p)return;let e=Date.now();console.log(`${e-AT} ${e-jp} `,...s),jp=e}function CT(s,e){if(!$p)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var $p,AT,jp,$e=T(()=>{"use strict";$p=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,AT=Date.now(),jp=Date.now()});var _a,zt,La,Mr=T(()=>{"use strict";_a={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",La=79});function re(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function qe(s,e,t,r,n){let o="";return n=n?encodeURIComponent(n):"master",e&&t&&(o=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(o+=`?result-id=${r}`)),o}function Da(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function We(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 Ma=T(()=>{"use strict"});var Ua,Wp,Vp,Xn=T(()=>{Ua={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"},Wp={"@applitools/eyes-sdk-core":"13.11.32","@applitools/spec-driver-webdriverio":"1.4.29","coralogix-logger":"1.1.28","@types/unzip-stream":"0.3.2",ajv:"6.12.6","analytics-node":"5.0.0","body-parser":"1.20.1",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4",cors:"2.8.5","data-uri-to-buffer":"2.0.2",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:"0.15.3",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2",npm:"8.19.2","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"6.3.1","rox-node":"4.9.18",semver:"7.5.4","serialize-error":"7.0.1","socket.io-client":"4.6.2","source-map-support":"0.5.19",superagent:"3.8.3","superagent-proxy":"3.0.0","test-exclude":"6.0.0","ua-parser-js":"0.7.33","unzip-stream":"0.3.1","validate-npm-package-name":"3.0.0",webdriverio:"7.24.0",winston:"3.6.0","winston-transport":"4.5.0",ws:"8.5.0",xml2js:"0.6.2",yaml:"2.2.2"},Vp={node:">= 16.0.0"}});var Ds,Gp,Hp,Qn,qp,Zn,Ms,zp,me,Kp,Jp,eo,Oe,Fa,Yp,to,Xp,gR,Qp,hR,Zp,ed,Nr,td,rd,sd,nd,od,id,ad,cd,ld,ud,Ns,pd,dd,Ba,md,fd,ja,le=T(()=>{"use strict";Ds=process.env.SERVICES_HOST||"https://services.testim.io",Gp="https://testimstatic.blob.core.windows.net",Hp="https://tstresultfiles.azureedge.net";process.env.GATEWAY_URL&&(process.env.CORALOGIX_URL=`${process.env.GATEWAY_URL}/testim/coralogix/api/v1/logs`,process.env.SERVICES_HOST=`${process.env.GATEWAY_URL}/testim/services`,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:Ds,Ds=process.env.SERVICES_HOST);Qn=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),qp=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),Zn=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),Ms=process.env.EDITOR_URL,zp=process.env.WEBSOCKET_HOST||`${Ds}/ws`,me=Ds,Kp=parseInt(process.env.LOGGER_CONSOLE||"0",10),Jp=parseInt(process.env.LOGGER_DEBUG||"0",10),eo=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),Oe=parseInt(process.env.IS_ON_PREM||"0",10),Fa=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,Yp=parseInt(process.env.DEBUG_MODE||"0",10),to=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,Xp=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",gR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),Qp=parseInt(process.env.START_WORKER_DELAY_MS||"1500",10),hR=process.env.APPIUM_VERSION||"1.10.1",Zp=process.env.GATEWAY_URL,ed=process.env.EXTENSION_SERVICES_HOST||Ds,Nr=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:Gp,td=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:Hp,rd=Gp,sd=Hp,nd=5*60*1e3,od=40,id=process.env.HEADSPIN_MOBILE_DEVICES_API_URL||"https://api-dev.headspin.io/v0",ad=process.env.HEADSPIN_MOBILE_APPS_API_URL||"https://api-dev.headspin.io/v1",cd=process.env.TDC_MOBILE_DEVICES_API_URL||"https://api.tdc.tricentis-cloud.com/v0",ld=process.env.TDC_MOBILE_APPS_API_URL||"https://api.tdc.tricentis-cloud.com/v1",ud=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Ns=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",pd=process.env.SAUCE_LABS_US_APPS_API_URL||"https://api.us-west-1.saucelabs.com/v1",dd=process.env.SAUCE_LABS_EU_APPS_API_URL||"https://api.eu-central-1.saucelabs.com/v1",Ba=process.env.P_CLOUDY_MOBILE_API_URL||"https://device.pcloudy.com/api",md=process.env.TMA_BASE_API_URL||"http://127.0.0.1:8585/api",fd=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||5,ja=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung"});var $a={};V($a,{CoralogixTransport:()=>Ur});var Re,gd,OT,_T,Ur,Wa=T(()=>{"use strict";Re=require("coralogix-logger"),gd=v(require("winston-transport")),OT={debug:Re.Severity.debug,silly:Re.Severity.verbose,verbose:Re.Severity.verbose,silent:Re.Severity.verbose,info:Re.Severity.info,http:Re.Severity.info,warn:Re.Severity.warning,warning:Re.Severity.warning,error:Re.Severity.error,critical:Re.Severity.critical,crit:Re.Severity.critical},_T=["err","error","reason","e"],Ur=class extends gd.default{constructor(t){t=Object.assign({},Ur.options,t);super(t);this.options=t,this.logger=new Re.CoralogixLogger(t.category||""),this.name="Coralogix Transport",t.timestamp&&(this.timestamp=t.timestamp)}log(t,r){let{category:n,level:o,message:i,meta:a={},...l}=t,c=Object.assign({},a,this.options.extraFields,l),d=new Re.Log;d.severity=OT[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
|
+
${c.msg}`));for(let u of _T)a[u]instanceof Error&&(c[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(c).length>0&&(i&&!m&&(c.msg=i),d.text=c),this.logger.addLog(d),r(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Re.CoralogixLogger.configure(t),Ur.options=t}}});var Ka={};V(Ka,{getLogger:()=>x,setExecutionId:()=>Ha,setProjectId:()=>qa,setProxyUri:()=>za});function MT(){let s=[],e=()=>Promise.resolve();if(!Oe){let{CoralogixTransport:t}=(Wa(),he($a));t.configure(bd);let r=new t({category:"ROOT"});s.push(r),e=()=>r.waitForFlush()}return Kp&&s.push(new St.transports.Console({format:St.format.combine(St.format.colorize(),St.format.simple())})),[s,e]}function Ha(s){Va=s}function qa(s){Td=s}function za(s){if(Oe||!s)return;let{CoralogixTransport:e}=(Wa(),he($a));e.configure({...bd,proxyUri:s})}function hd(s){return{projectId:Td,time:new Date().toISOString(),...Va&&!s&&{executionId:Va}}}function x(s){return new Ga(jT.child({category:s}))}var yd,St,LT,DT,bd,NT,UT,FT,BT,jT,Va,Td,Ga,j=T(()=>{"use strict";yd=v(require("os")),St=v(require("winston"));le();B();LT=yd.hostname(),DT=dt(),bd={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};[NT,UT]=MT(),FT=Jp?"debug":"info",BT={release:Boolean(!0),branch:"production"},jT=St.createLogger({levels:St.config.syslog.levels,level:FT,transports:NT,defaultMeta:{name:"runner",hostname:LT,nodeVersion:process.version,runnerVersion:DT,...BT}}),Va=null,Td=null;Ga=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},hd(n)))}catch(o){try{this._logger.log("crit",Object.assign({message:`failed to log message ${o.message}, ${o.stack}`},hd(n)))}catch{}}}waitForFlush(){return UT()}}});var oo,Fr,C,Kt,fr,It,ro,Br,ne,Us,ze,Jt,Rt,so,jr,$r,Wr,no,Fs,q=T(()=>{"use strict";oo=require("p-retry"),Fr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},C=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}},It=class extends oo.AbortError{},ro=class extends oo.AbortError{},Br=class extends oo.AbortError{},ne=class extends Error{},Us=class extends Error{},ze=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Jt=class extends ze{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Rt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},so=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},jr=class extends Error{},$r=class extends Error{constructor(t){super();this.innerStack=t}},Wr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},no=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Fs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Ja(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function oe(s){return(0,Ed.setTimeout)(s)}function Ya(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"){Zn&&!wd&&(wd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ne(t);return e=Zn?Number(Zn)||6e5:e,Promise.race([s,oe(e).then(()=>{throw r})])}async function ie(s,e,{concurrency:t}={}){if(t){vd||=(await import("p-limit")).default;let r=vd(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 Ed,wd,vd,Xa=T(()=>{"use strict";Ed=require("timers/promises");q();le();wd=!1});var js,Sd,$T,Bs,Id,WT,VT,Rd,xd=T(()=>{"use strict";js=v(require("lodash"));le();Sd=require("dns");j();Xa();$T=x("http-request-counters"),Bs=!1,Id=async()=>{if(Oe)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ie(s,t=>Sd.promises.lookup(t)));return e||(Bs=!0),e}catch{return $T.error("network connectivity test failed"),Bs=!0,!1}},WT=js.throttle(Id,10*1e3),VT=60*1e3*15,Rd=()=>{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)},VT)}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),Bs||WT(),a}}}async function r(){if(Bs||!await Id())return!1;let n=js.sum([...s.fail.values()]),o=js.sum([...s.call.values()]);return n<o*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>Bs,t}});var tt={};V(tt,{deleteFullRes:()=>KT,deleteReq:()=>$s,didNetworkConnectivityTestFail:()=>oc,download:()=>sc,get:()=>Ee,getFullRes:()=>YT,getText:()=>Vs,head:()=>XT,isNetworkHealthy:()=>nc,post:()=>Ge,postForm:()=>Ws,postFullRes:()=>JT,postText:()=>tc,put:()=>rc});function HT(){return global.caFileContent}function qT(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function zT(){return!xt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(xt.default),global.proxyUri}function gr(s,e=!1){let t=HT();t&&s.ca(t);let r=!e&&zT();r&&s.proxy(r)}async function Ad(s,e={},t={},r=Vr){let n=xt.default.delete(s).send(e).timeout(r).set(t);return gr(n),await n}async function Za(s,e,t={},r=Vr,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 ec(s,e,t={},r=Vr,{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,Qa,Ve,Vr,GT,Dt,$s,KT,Ge,JT,Ws,Vs,tc,Ee,YT,XT,rc,sc,nc,oc,Ke=T(()=>{"use strict";xt=v(require("superagent"));j();xd();Qa=x("http-request"),Ve=Rd(),Vr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,GT=6e4;Dt=(s,e,t)=>{throw Qa.error(s,{...t,error:e}),e};$s=Ve(async(s,e,t,r)=>{try{let n=await Ad(s,e,t,r);return n.type==="text/plain"?n.text:n.body}catch(n){return Dt("failed to delete request",n,{url:s})}});KT=Ve(Ad),Ge=Ve(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let o=await Za(s,e,t,r,n);return o.type==="text/plain"?o.text:o.body}catch(o){return Dt("failed to post request",o,{url:s})}});JT=Ve(Za),Ws=Ve(async(s,e,t,r={},n=Vr)=>{let o=xt.default.post(s).type("form").timeout(n).set(r);o.field(e),Object.entries(t).forEach(([i,a])=>{o.attach(i,a.buffer,a.fileName)}),gr(o);try{let i=await o;return i.type==="text/plain"?i.text:i.body}catch(i){return Dt("failed to post request",i,{url:s})}});Vs=Ve(async(s,e,t)=>{try{return(await ec(s,e,t)).text}catch(r){return Dt("failed to getText request",r,{url:s,query:e})}}),tc=Ve(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await Za(s,e,t,r,n)).text}catch(o){return Dt("failed to post request",o,{url:s})}}),Ee=Ve(async(s,e,t,r,n)=>{try{return(await ec(s,e,t,r,n)).body}catch(o){return Dt("failed to get request",o,{url:s,query:e})}}),YT=Ve((s,e,t,r)=>ec(s,e,t,r)),XT=Ve(async s=>{let e=xt.default.head(s).timeout(Vr);gr(e);try{return await e}catch(t){return Dt("failed to head request",t,{url:s})}}),rc=Ve(async(s,e,t={},r=Vr)=>{let n=xt.default.put(s).send(e).timeout(r).set(t);gr(n);try{return(await n).body}catch(o){return Dt("failed to put request",o,{url:s})}}),sc=Ve(async s=>{Qa.info("start to download",{url:s});let e=xt.default.get(s).timeout(GT).buffer(!0).parse(qT);gr(e);try{let t=await e;return Qa.info("finished to download",{url:s}),t}catch(t){return Dt("failed to download",t,{url:s})}}),nc=Ve.isNetworkHealthy,oc=Ve.didNetworkConnectivityTestFail});function mt(){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 io(s,e){return We(s)?e||Mt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Mt.basename(s)}function dt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function ZT(){try{return Vp.node}catch{return""}}async function kd(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 kd(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,Cd,Pd,rt,QT,Nt,Je,ao,ic,st,ac,Od=T(()=>{"use strict";Mt=v(require("path"));Ma();Xn();Cd=v(require("unzip-stream")),Pd=v(require("p-retry")),rt=require("fs"),QT=3;Nt=async s=>{let e=await Promise.resolve().then(()=>(Ke(),tt));return(0,Pd.default)(()=>e.download(s),{retries:QT,factor:1})},Je=async(s,e)=>{let t=await Nt(s);return rt.promises.writeFile(e,t.body)};ao=async(s,e)=>{let t=io(s,e);return We(s)?Je(s,t):rt.promises.copyFile(s,t)},ic=async s=>We(s)?Nt(s):rt.promises.readFile(s),st=async(s,e)=>await(0,rt.createReadStream)(s).pipe(Cd.Extract({path:e})),ac=s=>(0,rt.statSync)(s).size/1e6});var Ut={};V(Ut,{APPIUM_SESSION_MESSAGE:()=>dc,CLI_MODE:()=>Y,MOBILE_APP_SOURCE:()=>co,MOBILE_RUN_SKIP_REASON:()=>pc,gridMessages:()=>ft,gridTypes:()=>O,mobileWeb:()=>lc,runnerStatus:()=>cc,runnerTestStatus:()=>pe,socketEventTypes:()=>At,stepResult:()=>Hs,test:()=>uc,testRunStatus:()=>Gs,testStatus:()=>Ye,timeoutMessages:()=>Fe});var Fe,Gs,cc,pe,Ye,ft,lc,uc,At,Y,O,Hs,co,pc,dc,ae=T(()=>{"use strict";Fe={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Gs={COMPLETED:"completed",RUNNING:"running"},cc={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"},Ye={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},ft={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},lc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},uc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},At={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},Y={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},O={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},Hs={SETUP_TIMEOUT:"setup-timeout",NETWORK_ERROR:"network-error",GRID_ERROR:"grid-error",SELENIUM_ERROR:"selenium-error",BROWSER_CLOSED:"browser-closed",MOBILE_SESSION_ERROR:"mobile-session-error",UNKNOWN_ERROR:"unknown-error"},co={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},pc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},dc={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 qs(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 ew(){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 zs,_d,Xe,tw,rw,sw,nw,ow,mc,fc,Ld=T(()=>{"use strict";ae();zs=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},_d=s=>Boolean(s.resultId&&s.source==="remote-run"),Xe=(s,e)=>s.testStatus===Ye.QUARANTINE&&!_d(e)&&!e.runQuarantinedTests;tw=s=>Boolean(s.loginMode),rw=s=>Boolean(s.tunnelOnlyMode),sw=s=>Boolean(s.createPrefechedData),nw=s=>Boolean(s.installLazyDepsMode),ow=s=>Boolean(s.agentMode),mc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},fc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function uo(s=0){return lo.default.duration(s).format("HH:mm:ss.SSS")}function gc(s=0){return lo.default.duration(s).asSeconds()}var lo,Dd,Md=T(()=>{"use strict";lo=v(require("dayjs")),Dd=v(require("dayjs/plugin/duration"));lo.default.extend(Dd.default)});var Ks,Gr,Js,Nd,Hr,Ud=T(()=>{"use strict";ae();Ks=s=>!(!s||"fileName"in s),Gr=(s,e)=>e===O.TESTIM_TVC?!1:s&&"fileName"in s?s.fileName.endsWith(".app"):!1,Js=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},Nd=s=>s===O.TESTIM_TVC,Hr=(s,e)=>Nd(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function hc(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 Fd=T(()=>{"use strict"});var K={};V(K,{OSS:()=>qr,TESTIM_BROWSER_DIR:()=>Ft,buildBasicHeader:()=>Da,calcPercentile:()=>fo,copyDir:()=>kd,delay:()=>oe,doesPathExist:()=>ge,download:()=>Nt,downloadAndSave:()=>Je,extractElementId:()=>Le,getArgsOnRemoteRunFailure:()=>ew,getBrowserInfo:()=>aw,getCdpAddressForHost:()=>br,getCliLocation:()=>mt,getDuration:()=>uo,getDurationSec:()=>gc,getEnginesVersion:()=>ZT,getEnvironmentGitBranch:()=>yr,getLocalFileSizeInMB:()=>ac,getMemorySnapshot:()=>hc,getPlanType:()=>mo,getRunConfigByBrowserName:()=>Ys,getRunnerVersion:()=>dt,getSource:()=>ao,getSourceAsBuffer:()=>ic,getSourcePath:()=>io,getTestUrl:()=>qe,getUniqBrowsers:()=>qs,groupTestsByRetries:()=>bc,guid:()=>re,hasTestPlanFlag:()=>zs,isAgentMode:()=>ow,isAppFromDevice:()=>Ks,isAppFromDeviceDisabled:()=>Hr,isCreatePrefetchedDataMode:()=>sw,isInstallLazyDepsMode:()=>nw,isLoginMode:()=>tw,isMobileProject:()=>Js,isPromise:()=>Ja,isQuarantineAndNotRemoteRun:()=>Xe,isRemoteRun:()=>_d,isTestimVirtualGrid:()=>Nd,isTunnelOnlyMode:()=>rw,isURL:()=>We,promiseAbort:()=>Ya,promiseFromCallback:()=>Yt,promiseMap:()=>ie,promiseTimeout:()=>ce,removePropertyFromObject:()=>po,replaceArgsWithNoDashes:()=>mc,shouldBlockVirtualIosBuild:()=>Gr,spreadObjectToArgs:()=>fc,unzipFile:()=>st});function aw(s){return s=s.toLowerCase(),yc.find(e=>e.browserValue===s)}function Ys(s,e,t){s=s==null?void 0:s.toLowerCase();let r=yc.find(o=>o.browserName.toLowerCase()===s||s.includes(o.synonyms))||yc[0],n=qr.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=qr.find(o=>o.sl.platform===e.platform):e.platformName&&(n=qr.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=qr.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=qr.find(o=>o.bs.platform===t.platform))),hr.merge(r,n)}function yr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function po(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&po(s[r],e,t))}function Le(s){return s.ELEMENT||s[zt]}function mo(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function bc(s=[]){return hr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=hr.orderBy(t,o=>typeof o.retryCount=="number"?o.retryCount:1),n=hr.chain(r).last().cloneDeep().value();return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}async function br(s,e){let t=await Promise.resolve().then(()=>(Ke(),tt));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 Bd,hr,jd,iw,Ft,qr,yc,fo,B=T(()=>{"use strict";Bd=v(require("os")),hr=v(require("lodash")),jd=v(require("path"));Mr();Od();Ld();Md();Ma();Xa();Ud();Fd();iw=Bd.homedir(),Ft=jd.join(iw,".testim-browser-profile"),qr=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14"},sl:{platform:"macOS 11",safari_version:"14"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13"},sl:{platform:"macOS 10.15",safari_version:"13"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12"},sl:{platform:"macOS 10.14",safari_version:"12"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11"},sl:{platform:"macOS 10.13",safari_version:"11"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10"},sl:{platform:"macOS 10.12",safari_version:"10.0"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"9.0"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"8.0"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"7.0"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"6.0"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],yc=[{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"}];fo=(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 Tc={};V(Tc,{$schema:()=>cw,default:()=>mw,definitions:()=>lw,properties:()=>dw,required:()=>pw,type:()=>uw});var cw,lw,uw,pw,dw,mw,$d=T(()=>{cw="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}}}},uw="object",pw=["entries"],dw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},mw={$schema:cw,definitions:lw,type:uw,required:pw,properties:dw}});async function Kd(){try{return await ce(go.promises.readFile(To()).then(async s=>{let e=await zd;return hw(e,s)}),3e4)}catch{return{}}}function hw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),o=Kr.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 gt(s,e,t=fw,r=void 0){return async()=>{if(!Gd)return await s();let n=e;r&&(e+=JSON.stringify(r));let o=await yw(e);if(o)return Xs.debug("cache hit:",{fnName:e}),o;if(Xs.debug("cache miss:",{fnName:e}),!Hd)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 bw(e,i,t),i}}async function yw(s){let t=(await wo)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function bw(s,e,t){if(wc)throw Xs.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 wo;r[s]={value:e,expiry:Date.now()+t},qd=new Promise(n=>{bo=n}),gw(r)}catch{Xs.error("failed updating cache")}}async function Jr(){let s=await wo;Object.keys(s).forEach(e=>{delete s[e]})}function Jd(s){Gd=s}function Tw(s=!0){Hd=s}async function Yd(){try{return wc=!0,await qd}finally{wc=!1}}function Xd(s){yo=s,wo=Kd()}var go,ho,Kr,Wd,Xs,yo,Vd,bo,Gd,Hd,wc,qd,zd,fw,To,wo,gw,Qd,Zd,VR,em,Bt=T(()=>{"use strict";go=v(require("fs")),ho=v(require("path")),Kr=v(require("crypto"));B();Wd=require("lodash");j();Xs=x("local cache"),yo=ho.resolve(mt(),"testim-cache"),Gd=!0,Hd=!0,wc=!1,qd=new Promise(s=>{bo=s}),zd=new Promise(s=>{Vd=s}),fw=1e3*60*60*3,To=()=>ho.resolve(ho.resolve(yo,"testim.cache"));wo=Kd(),gw=(0,Wd.debounce)(async s=>{let e;try{let t=await zd,r=Kr.randomBytes(16),n=JSON.stringify(s),o=Buffer.from(t),i=Kr.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),r),a=Buffer.concat([r,i.update(n),i.final()]);await ge(yo)||await go.promises.mkdir(yo,{recursive:!0}),await go.promises.writeFile(To(),a)}catch(t){Xs.error("failed saving cache",{err:t}),e=t}bo(e?{success:!1,error:e}:{success:!0})},200);Qd=Vd,Zd=Jd.bind(void 0,!1),VR=Jd.bind(void 0,!0),em=()=>Tw(!1)});function vo(){return{cliLocation:mt(),userInfo:Yr.userInfo(),platform:Yr.platform(),release:Yr.release()}}var Yr,vc=T(()=>{"use strict";Yr=v(require("os"));B()});function ww(s){try{return Eo.resolve(Eo.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=ww(s);return require(e)}var Eo,Qs=T(()=>{"use strict";Eo=v(require("path"))});function vw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Ew(s){return/The "to" argument must be of type string./.exec(s)}function nm(s,e,t){let r=vw(s),n=Ew(s);return r||n?(sm.info("Failed to install package due to insufficient write access",{...vo(),package:t,path:r}),console.error(`
|
|
4
4
|
|
|
5
5
|
Testim failed installing the package ${t||""} due to insufficient permissions.
|
|
6
6
|
This is probably due to an installation of @testim/testim-cli with sudo, and running it without sudo.
|
|
@@ -13,13 +13,13 @@ Testim had missing write access to ${r||e}
|
|
|
13
13
|
- installed where chromedriver expects it (see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver#requirements).
|
|
14
14
|
- exists in your PATH environment variables.
|
|
15
15
|
3. Try adding --chrome-binary-location flag to Testim CLI specifying the exact location of chrome binary in your computer (e.g on Windows "C:/Program Files/Google/Chrome/Application/chrome.exe").
|
|
16
|
-
4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),i}}async function Cw(){let s=`${Nr}/extension/sessionPlayer_LATEST_RELEASE`;return(await Nt(s)).body.toString("utf8")}async function Pw(s,e){if(!We(s)||We(s)&&e||Oe)return s;let t=await Cw();return`${s}-${t}`}function Pc(){let s=mt();return Qr.resolve(s,"testim-bin")}function kw(){let s=Pc();return Qr.resolve(s,"sessionPlayer.zip")}async function vm(s,e,t=!1){try{return await ao(s,e),await st(e,Pc())}catch(r){if(t)throw r;return await vm(s,e,!0)}}async function vr(s,e){xo.info("prepare player",{location:s,canary:e});let t=kw();return gt(async()=>{let r=await Pw(s,e);return await vm(r,t),{}},"preparePlayer",wm,[s,e,t])()}var ym,bm,Qr,Tm,xo,wm,xc,hm,Zr=T(()=>{"use strict";ym=v(require("ms")),bm=v(require("fs")),Qr=v(require("path"));le();Bt();Tm=require("serialize-error");j();vc();q();B();xo=x("prepare runner and testim start"),wm=(0,ym.default)("0.5 day"),xc=16,hm=`The size of the custom extension is more than ${xc}MB`});function Ow(){let s=en.type().toLowerCase();return s==="darwin"?en.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?en.arch()==="x64"?"win64":"win32":"linux"}async function Co(){let s=Ow(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(s in t))throw new C(`Unsupported platform: ${s}`);let r=parseInt(tn,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},o={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},i=`${e}/${t[s]}/${tn}/${n[s]}.zip`,a=Ao.join(kc,n[s]),l=`${a}.zip`,c=Ao.join(a,o[s]);if(await ge(c))return c;if(!await ge(l)){let m=(0,Oc.default)("Downloading Chromium").start();try{await Em.promises.mkdir(kc),await Je(i,l)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,Oc.default)("Extracting Chromium").start();try{await st(l,kc)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),c}var Em,en,Ao,Oc,tn,kc,_c=T(()=>{"use strict";Em=v(require("fs")),en=v(require("os")),Ao=v(require("path")),Oc=v(require("ora"));q();B();tn="1000968",kc=Ao.join(Ft,`chrome-${tn}`)});async function Im(s,e){return Po=s,Nc=e,await Lc()}function Rm(s,e,t){nt=s.token,Po=e,Nc=t,sn=Uc(nt),nn=s.refreshToken,Dc=s.ngrokToken,Mc=s.isNgrokWhitelisted}function _w(s=Po,e=Nc){return gt(()=>(rn.info("request to get cli token from server"),Ge({url:`${me}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",Sm*10,{projectId:s,token:e})()}async function Lw(){rn.info("request to refresh JWT cli token from server");let s=await Ge({url:`${me}/auth/refreshToken`,body:{token:nt,refreshToken:nn}});return nt=s.token,sn=Uc(nt),s.refreshToken&&(nn=s.refreshToken),nt}async function Lc(){try{let s=await _w();return rn.info("successfully get cli token from server"),nt=s.token,sn=Uc(nt),nn=s.refreshToken,Dc=s.ngrokToken,Mc=s.isNgrokWhitelisted,nt}catch(s){throw s.message.includes("Unauthorized")?new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(rn.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Po}),new C(`While trying to retrieve CLI token, caught error: ${s}`))}}function Uc(s){return require("jsonwebtoken").decode(s).exp*1e3}async function Zt(){if(!sn)return Lc();if(sn<Date.now()+4*Sm)try{return await Lw()}catch(s){return rn.error("failed to refresh token, executing fallback",s),Lc()}return nt}function ko(){return nn}function jt(){return nt?{uid:require("jsonwebtoken").decode(nt).id,ngrokToken:Dc,isNgrokWhitelisted:Mc}:{}}var rn,nt,sn,nn,Dc,Mc,Po,Nc,Sm,Ct=T(()=>{"use strict";le();Ke();Bt();q();j();rn=x("testim-custom-token"),Po=null,Nc=null,Sm=5*60*1e3});var xm={};V(xm,{isCi:()=>es});var es,Oo=T(()=>{"use strict";es=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var Ae={};V(Ae,{addTestRetry:()=>cl,clearTestResult:()=>ol,deleteCloudflareTunnel:()=>dl,fetchLambdatestConfig:()=>rl,forceUpdateCloudflareTunnelRoutes:()=>pl,getAllGrids:()=>tl,getAppDetails:()=>zc,getApplitoolsIntegrationData:()=>ll,getBrowserStackSessionMetaData:()=>Vw,getCloudflareTunnel:()=>ul,getEditorUrl:()=>jw,getGridById:()=>Lo,getGridByName:()=>Zc,getHybridGridProvider:()=>Qc,getLabFeaturesByProjectId:()=>sl,getMobileDevicesFromGrid:()=>fl,getRealData:()=>nl,getS3Artifact:()=>an,getS3ArtifactText:()=>Bc,getSuiteTestList:()=>qc,getTestPlan:()=>Bw,getTestPlanTestList:()=>Hc,getTestResults:()=>Sr,getUsageForCurrentBillingPeriod:()=>Kc,initializeUserWithAuth:()=>el,isTestResultCompleted:()=>Jc,keepAliveCompanySlots:()=>Tl,keepAliveGrid:()=>Yc,loadSfdcCredential:()=>jc,loadTest:()=>$c,releaseCompanySlot:()=>yl,releaseGridSlot:()=>Xc,reportExecutionFinished:()=>_o,reportExecutionStarted:()=>Gc,requestCompanySlot:()=>hl,saveRemoteStep:()=>il,saveTestPlanResult:()=>Wc,updateCompanySlot:()=>bl,updateExecutionTests:()=>Vc,updateRemoteRunFailure:()=>ml,updateTestDataArtifact:()=>Mo,updateTestResult:()=>Do,updateTestStatus:()=>Er,uploadAppToGrid:()=>gl,uploadRunDataArtifact:()=>al});async function ts(){let s=await Zt();if(!s)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${s}`}}async function De({url:s,body:e,headers:t={},timeout:r,retry:n}){let o=await ts(),i=Object.assign({},t,o);return Ge({url:`${me}${s||""}`,body:e,headers:i,timeout:r,retry:n})}async function Nw(s,e,t,r={},n=void 0){let o=await ts(),i=Object.assign({},r,o);return await Ws(`${me}${s||""}`,e,t,i,n)}async function on(s,e){let t=await ts();return await rc(`${me}${s||""}`,e,t)}async function Uw(s,e){let t=await ts();return await $s(`${me}${s||""}`,e,t)}async function Fw(s,e){let t=await ts();return await Vs(`${me}${s||""}`,e||void 0,t)}async function xe(s,e,t,r){let n=await ts();return await Ee(`${me}${s||""}`,e||void 0,n,r,t)}function an(s,e){return(0,Z.default)(()=>xe(`/storage${s}`,null,{isBinary:!0},e),{retries:ee,factor:1})}function Bc(s){return(0,Z.default)(()=>Fw(`/storage${s}`))}async function Bw(s,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,Z.default)(()=>xe("/testPlan",{projectId:s,name:e.join(",")}),{retries:ee,factor:1})).map(({testConfigIds:n,beforeAllLabels:o,testLabels:i,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(o),testLabels:t(i),afterAllLabels:t(a)}))}async function jc({branch:s,projectId:e}){let t=await(0,Z.default)(()=>xe(`/branch/branchData/${s}`,{projectId:e}),{retries:ee,factor:1});return t==null?void 0:t.sfdcCredential}function $c({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,Z.default)(()=>xe(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:ee,factor:1})}function Wc(s,e,t){return(0,Z.default)(()=>De({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:ee,factor:1})}function Er(s,e,t,r,n,o,i=ee){return(0,Z.default)(()=>on("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:Dw,...o}),{retries:i,factor:1})}function Vc(s,e,t,r,n,o,i,a){return(0,Z.default)(()=>on("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:o,endTime:i,projectId:a}),{retries:ee,factor:1})}async function Gc({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:o,resultLabels:i,remoteRunId:a,localRunUserId:l,isLocalRun:c,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(Oo(),xm));return De({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:o,resultLabels:i,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function _o(s,e,t,r,n={},o=void 0,i=void 0){let a=Date.now();return(0,Z.default)(()=>on("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:ee,factor:1})}async function Hc(s,e,t,r,n){return(0,Z.default)(()=>De({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:ee,factor:1})}function qc({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,Z.default)(()=>De({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:ee,factor:1})}async function zc({appId:s,projectId:e}){try{return await(0,Z.default)(()=>xe(`/mobile-app/app/${s}?projectId=${e}`),{retries:ee,factor:1})}catch(t){Wt.error("failed getting application details",{appId:s,error:t});return}}async function Kc(s){try{return await(0,Z.default)(()=>xe(`/plan/project/${s}/usage-current-billing-period`),{retries:ee,factor:1})}catch(e){Wt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function Jc(s,e,t){return(0,Z.default)(()=>xe(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:ee,factor:1})}function Sr(s,e,t,r){return(0,Z.default)(()=>xe(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:ee,factor:1})}function Yc(s,e){return De({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function Xc(s,e,t,r,n){return De({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function Qc(s){return De({url:"/grid/hybrid/provider",body:s})}function Zc(s,e,t,r,n){return(0,Z.default)(()=>xe("/grid/name",{companyId:s,projectId:e,name:t,browser:r,executionId:n,reqId:re()}),{retries:ee,factor:1})}function Lo(s,e,t,r,n){return(0,Z.default)(()=>xe(`/grid/${t}`,{companyId:s,projectId:e,browser:r,executionId:n,reqId:re()}),{retries:ee,factor:1})}async function el({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,gridId:o,grid:i}){var a,l;try{return await(0,Z.default)(()=>Ge({url:`${me}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,gridId:o,gridName:i}}),{retries:ee,factor:1})}catch(c){throw Wt.error("error initializing info from server",c),(a=c==null?void 0:c.message)!=null&&a.includes("Bad Request")?new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(l=c==null?void 0:c.code)!=null&&l.includes("ENOTFOUND")?new C("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):c}}async function jw(){if(Ms)return{editorUrl:Ms};try{return await(0,Z.default)(()=>xe("/system-info/editor-url"),{retries:ee,onFailedAttempt:s=>{if(s.attemptNumber>=ee)throw s},factor:1})}catch{return Wt.error("cannot retrieve editor-url from server"),{editorUrl:"https://app.testim.io"}}}function tl(s){return(0,Z.default)(()=>xe("/grid",{companyId:s}),{retries:ee,factor:1})}function nl(s,e,t){return(0,Z.default)(()=>xe(`/real-data/${e}?${t}&projectId=${s}`),{retries:ee,factor:1})}function Do(s,e,t,r,n){return(0,Z.default)(()=>De({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:ee,factor:1})}function ol(s,e,t,r){return(0,Z.default)(()=>De({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:ee,factor:1})}function il(s,e,t,r){return(0,Z.default)(()=>De({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:ee,factor:1})}function $w(s){return s.startsWith("/")?s:`/${s}`}function Ww(s,e,t){let r=$w(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Cm(s,e,t,r,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${re()}${i||""}`,l=`${e}/${t}/${a}`,c=Ww(l,"test-result-artifacts",s),d=Buffer.from(Am.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,Z.default)(()=>Nw(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:ee,factor:1}),c}function cl({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:o,testResult:i}){return(0,Z.default)(()=>De({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:ee,factor:1})}async function ll(s){try{return await xe(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Wt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function ul(s,e){try{return await on("/tunnel",{companyId:s,routes:e})}catch(t){return Wt.warn("could'nt get tunnel.",{err:t}),{}}}async function pl(s,e){try{return await De({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}async function dl(s,e){try{return await Uw(`/tunnel/${e}`,{companyId:s})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}function ml(s){return Ge({url:`${me}/result/remoteRunFailure`,body:s})}async function fl({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let o=`${Mw}/mobileDevices/${t}/${r}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await(0,Z.default)(()=>xe(o,{projectId:s}),{retries:ee,factor:1})}catch(i){return Wt.warn("could'nt get devices from headspin grid.",{err:i}),null}}async function gl({projectId:s,gridId:e,app:t,timeout:r}){return(0,Z.default)(()=>De({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:ee,factor:1})}async function hl(s,e){return(0,Z.default)(()=>De({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:ee,factor:1})}async function yl(s,e,t){return(0,Z.default)(()=>De({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:ee,factor:1})}async function bl(s,e,t){return(0,Z.default)(()=>on("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:ee,factor:1})}function Tl(s,e,t){return De({url:`/slot-management/keep-alive?reqId=${re()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function Vw(s,e){return await Ee(`${Ns}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}var er,Am,Z,Fc,Dw,Wt,ee,Mw,rl,sl,al,Mo,ye=T(()=>{"use strict";er=v(require("lodash")),Am=v(require("pako"));B();le();ae();Ke();Ct();Z=v(require("p-retry")),Fc=v(require("object-hash"));q();j();Dw=dt(),Wt=x("testim service api"),ee=3,Mw="/grid";rl=async()=>(0,Z.default)(()=>xe("/grid/lt/config"),{retries:ee,factor:1}),sl=async s=>(0,Z.default)(()=>xe(`/labFeature/v2/project/${s}`),{retries:ee,factor:1});al=er.memoize(async(s,e,t,r)=>{if(!er.isEmpty(r))return await Cm(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,Fc.default)(r)}:${e}:${t}`),Mo=er.memoize(async(s,e,t,r,n)=>!r||er.isEmpty(r)?void 0:await Cm(s,e,t,JSON.stringify((()=>{let i=er.clone(r);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(l=>{i[l]&&Object.assign(i,{[l]:uc.HIDDEN_PARAM})})}return i})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,Fc.default)(r)}:${e}:${t}`)});var tr={};V(tr,{getSessionPlayer:()=>se,options:()=>vl});var No,vl,wl,se,Te=T(()=>{"use strict";No=require("path"),vl={playerPath:void 0},se=()=>{if(wl)return wl;let s=($e(),he(je));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(Zr(),he(Zs)),t=e(),r=vl.playerPath?(0,No.resolve)(vl.playerPath,"src/background/sessionPlayerInit.ts"):(0,No.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),wl=n,n}});function qw(s){process.nextTick(()=>{if([Y.SELENIUM,Y.APPIUM].includes(s))try{(Te(),he(tr)).getSessionPlayer()}catch{}})}async function cn(s){let{project:e,token:t,lightweightMode:r,useLocalChromeDriver:n,useChromeLauncher:o,mode:i,gridId:a,grid:l}=s,c=Boolean(r==null?void 0:r.general),d=Boolean(n||o),m=c?Hw:Gw;N("before initializeUserWithAuth");let u=await gt(async()=>(qw(i),await el({projectId:e,token:t,branchName:s.branch,lightweightMode:r,localGrid:d,gridId:a,grid:l})),"initializeUserWithAuth",m,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:c,localGrid:d,gridId:a,grid:l})();return N("after initializeUserWithAuth"),Rm(u.authData,s.project,s.token),u}var Gw,Hw,Pm=T(()=>{"use strict";$e();ye();Bt();Ct();ae();Gw=1e3*60*5,Hw=1e3*60*60*10});async function _m(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Co():s.chromeBinaryLocation,e=wr({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==Y.EXTENSION&&await vr(s.playerLocation,s.canary),s.mode===Y.EXTENSION&&!s.ext&&await Cc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await Ac(s.installCustomExtension,n)}return await e,t}async function Lm(s){var i;zw.info("prepare MockNetwork",{location:s});let e=await ic(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>km*1e6)throw new Error(`${El} exceeded ${km}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${El} cannot be parsed.${Uo.EOL}${a}`)}let n=new Om.default;if(!n.validate(Tc,r)){let a=(i=n.errors)==null?void 0:i.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(Uo.EOL);throw new Error(`${El} is malformed.${Uo.EOL}${a}`)}return r.entries}var Uo,Om,km,El,zw,Sl=T(()=>{"use strict";Uo=v(require("os"));B();$d();Zr();Om=v(require("ajv"));ae();_c();Pm();km=1,El="JSON file supplied to --mock-network-pattern",zw=(j(),he(Ka)).getLogger("prepare runner")});function Mm(s,e=process){async function t(r){await ce(ie(Dm,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{ln.error("Caught exception",{err:r}),console.log("Uncaught exception"),r.message&&console.log("Message =",r.message),r.reason&&console.log("Reason =",r.reason),await t(r)}),e.on("unhandledRejection",r=>{var n;if(ln.fatal("Caught unhandled promise rejection",r),!((n=r==null?void 0:r.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{ln.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw ln.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw ln.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function rs(s){Dm.push(s)}var ln,Dm,un=T(()=>{"use strict";j();B();ln=x("process-handler"),Dm=[]});var G,$m,Zw,ev,tv,jm,Bo,Al,M,fe=T(()=>{"use strict";G=v(require("rox-node"));j();B();le();$m=x("FeatureFlagsService"),Zw=!Oe&&!0&&!Zp,ev=2e4,tv=60*60*24,jm=["labs","disabled","enabled"],Bo=class extends G.default.Variant{constructor(e="disabled"){super(e,jm)}getValue(){let e=super.getValue();return jm.includes(e)?e:($m.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},Al=class{constructor(){this.flags={useNewWSCLI:new G.default.Flag,useSafariWebdriverVisibilityChecks:new G.default.Flag,useClickimVisibilityChecks:new G.default.Flag,runGetElementCodeInAut:new G.default.Flag,enableFrameSwitchOptimization:new G.default.Flag,maximumJsResultSize:new G.default.Configuration(2e3*1024),skipFileInputClicks:new G.default.Flag,errorMessageOnBadNetwork:new G.default.Flag(!0),warnOnBadNetwork:new G.default.Flag(!1),overrideAzureStorageUrl:new G.default.Flag,autoSaveDownloadFileFireFox:new G.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new G.default.Flag(!0),experimentalPreCodeCompilation:new G.default.Flag(!0),experimentalAsyncCustomCode:new G.default.Flag,useSameBrowserForMultiTests:new Bo("labs"),highSpeedMode:new Bo,usePortedHtml5DragDrop:new G.default.Flag,testNamesToBeforeSuiteHook:new G.default.Flag,addCustomCapabilities:new G.default.Variant("{}"),addCustomLTtunnelNTLMOptions:new G.default.Variant("{}"),LTNetworkCapabilities:new G.default.Flag,downloadToBase64:new G.default.Flag,publicGridURL:new G.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new G.default.Flag(!0),unsupportedCapsFields:new G.default.Variant("[]"),useLinkedomToParseHtml:new G.default.Flag,dontFocusOnInit:new G.default.Flag,retryOnSeleniumHubError:new G.default.Flag,enableLambdaTestTunnelNTLM:new G.default.Flag,enableLambdaTestTunnelSkipUpgrade:new G.default.Flag,tdcHsPreventNetworkCapture:new G.default.Flag,headSpinTdcEnableFlagCapability:new G.default.Flag,enableBatchTDC:new G.default.Flag,enableBatchHeadSpin:new G.default.Flag,clearRunnerFileCache:new G.default.Flag,forceTurboModeIfNeeded:new G.default.Flag,redisSlotManager:new G.default.Flag,tunnelBinaryNewVersion:new G.default.Flag(!1),computePackagePathFromPackageJsonExports:new G.default.Flag},G.default.register("default",this.flags)}setProjectId(e){G.default.setCustomStringProperty("projectId",e)}setProjectType(e){G.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){G.default.setCustomStringProperty("productType",e)}setCompanyId(e){G.default.setCustomStringProperty("companyId",e)}setPlanType(e){G.default.setCustomStringProperty("planType",e)}setIsPOC(e){G.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){G.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){G.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!Zw)return;let e={fetchIntervalInSec:tv,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return ce(G.default.setup(Xp,e),ev).catch(t=>$m.error("failed to get feature flag status",t))}},M=new Al});function Cl(s,e){let t=s.canary?"-master.zip":".zip",r=`${e?rd:Nr}/extension/testim-firefox-profile${t}`,n=`${e?sd:Nr}/extension/testim-headless${t}`;return{firefox:r,chrome:n,"edge-chromium":n}}function Wm(s){let{chrome:e,firefox:t}=Cl(s,!1);return s.browser==="firefox"?t:s.browser==="chrome"?e:[e,t]}function jo(s){let e=`${Nr}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var $o=T(()=>{"use strict";le()});function zm(s){Oe||(s!=null&&s.userId||(s={anonymousId:qm}),Hm.identify(s))}function ht(s,e){return pn("ci",s,e)}function pn(s,e,t){if(Oe)return;let r=s?{userId:s}:{anonymousId:qm};Hm.track(Object.assign(r,{event:e,properties:t}))}var Gm,Hm,qm,ss=T(()=>{"use strict";le();Gm=v(require("analytics-node")),Hm=new Gm.default("sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",{flushAt:1}),qm=require("crypto").randomBytes(20).toString("hex")});function Km(s){return s.start&&pn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function Jm(s){let e=["playground-playwright","playground-puppeteer","playground-selenium"],t=!1,r=!1,n=!1,o=!1;if(s.start&&(o=!0),Number.isNaN(s.agentPort))throw new C("Agent port is not number");if(typeof s.agent=="string"&&e.some(a=>s.agent.includes(a))){let a=s.agent.split(",").map(l=>l.trim());a.includes("playground-playwright")&&(t=!0),a.includes("playground-puppeteer")&&(r=!0),a.includes("playground-selenium")&&(n=!0)}let i=jo(s);return console.log("Start Testim CLI on Agent mode"),{project:s.project,token:s.token,agentMode:!0,agentPort:s.agentPort,agentBind:s.agentBind,openEditor:s.openEditor,installPlaygroundPlaywrightDeps:t,installPlaygroundPuppeteerDeps:r,installPlaygroundSeleniumDeps:n,startTestimBrowser:o,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||i,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:Boolean(s.downloadBrowser)}}var Ym=T(()=>{"use strict";$o();ss();q()});function Vo(s){let{platform:e}=process;e==="win32"?(0,Wo.exec)(`start chrome ${s}`):e==="darwin"?(0,Wo.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,Wo.exec)(`google-chrome ${s}`)}var Wo,Pl=T(()=>{"use strict";Wo=require("child_process")});var mn={};V(mn,{doLogin:()=>Ll,getProjectId:()=>sv,getToken:()=>nv});async function sv(){return Zm("projectId")}async function nv(){return Zm("token")}function Qm(s,e){return Promise.race([s,oe(e).then(()=>{throw new ne("timeout")})])}async function ov(){let s=(await import("express")).default(),e=async function(){return Qm(new Promise(n=>{s.get("/loginInfo",(o,i)=>{n(JSON.parse(Buffer.from(o.query.info,"base64").toString())),i.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let o=s.listen(42543,i=>{i&&n(i),r(o.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ye(),Ae)),{editorUrl:n}=await r();Vo(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function Ll({overwriteExisting:s=!0,projects:e=null}={}){let t=kl.homedir(),r=Ol.join(t,".testim");if(await ge(r)&&!s)return;let o={},[{default:i},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await Qm(ov(),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,l.succeed(),await Xm(r,o);return}if(e!=null&&e.length){l.succeed();let c=e.length===1?{project:e[0]}:await i({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});o.token=c.project.ci.token,o.projectId=c.project.id,await Xm(r,o);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Xm(s,e){await _l.promises.writeFile(s,Go.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function Zm(s){let e=kl.homedir(),t=Ol.join(e,".testim"),r=await ge(t),n={};if(r)try{n=Go.parse((await _l.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var kl,Ol,Go,_l,ns=T(()=>{"use strict";kl=v(require("os")),Ol=v(require("path")),Go=v(require("yaml"));B();_l=require("fs");q();Pl()});var of={};V(of,{process:()=>mv});var Ml,tf,Nl,rf,Vt,Ne,sf,iv,Me,Bl,av,cv,ef,nf,lv,Ul,Fl,jl,Dl,Pt,uv,p,pv,dv,mv,af=T(()=>{"use strict";Ml=v(require("ms")),tf=v(require("chalk")),Nl=v(require("fs")),rf=v(require("url")),Vt=v(require("lodash")),Ne=v(require("path"));B();$o();Ym();Bt();sf=require("commander");ae();q();Mr();B();fe();iv=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Me=(s,e)=>(e.push(s),e),Bl=new sf.Command,av=s=>s.split(","),cv=(s,e)=>!s||s.length===0?e:s,ef=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],nf=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function o(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function i(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function l(g){return g.includes("--save-rca-locally")}function c(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}Bl.help(g=>g.split(`
|
|
16
|
+
4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),i}}async function Cw(){let s=`${Nr}/extension/sessionPlayer_LATEST_RELEASE`;return(await Nt(s)).body.toString("utf8")}async function Pw(s,e){if(!We(s)||We(s)&&e||Oe)return s;let t=await Cw();return`${s}-${t}`}function Pc(){let s=mt();return Qr.resolve(s,"testim-bin")}function kw(){let s=Pc();return Qr.resolve(s,"sessionPlayer.zip")}async function vm(s,e,t=!1){try{return await ao(s,e),await st(e,Pc())}catch(r){if(t)throw r;return await vm(s,e,!0)}}async function vr(s,e){xo.info("prepare player",{location:s,canary:e});let t=kw();return gt(async()=>{let r=await Pw(s,e);return await vm(r,t),{}},"preparePlayer",wm,[s,e,t])()}var ym,bm,Qr,Tm,xo,wm,xc,hm,Zr=T(()=>{"use strict";ym=v(require("ms")),bm=v(require("fs")),Qr=v(require("path"));le();Bt();Tm=require("serialize-error");j();vc();q();B();xo=x("prepare runner and testim start"),wm=(0,ym.default)("0.5 day"),xc=16,hm=`The size of the custom extension is more than ${xc}MB`});function Ow(){let s=en.type().toLowerCase();return s==="darwin"?en.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?en.arch()==="x64"?"win64":"win32":"linux"}async function Co(){let s=Ow(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(s in t))throw new C(`Unsupported platform: ${s}`);let r=parseInt(tn,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},o={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},i=`${e}/${t[s]}/${tn}/${n[s]}.zip`,a=Ao.join(kc,n[s]),l=`${a}.zip`,c=Ao.join(a,o[s]);if(await ge(c))return c;if(!await ge(l)){let m=(0,Oc.default)("Downloading Chromium").start();try{await Em.promises.mkdir(kc),await Je(i,l)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,Oc.default)("Extracting Chromium").start();try{await st(l,kc)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),c}var Em,en,Ao,Oc,tn,kc,_c=T(()=>{"use strict";Em=v(require("fs")),en=v(require("os")),Ao=v(require("path")),Oc=v(require("ora"));q();B();tn="1000968",kc=Ao.join(Ft,`chrome-${tn}`)});async function Im(s,e){return Po=s,Nc=e,await Lc()}function Rm(s,e,t){nt=s.token,Po=e,Nc=t,sn=Uc(nt),nn=s.refreshToken,Dc=s.ngrokToken,Mc=s.isNgrokWhitelisted}function _w(s=Po,e=Nc){return gt(()=>(rn.info("request to get cli token from server"),Ge({url:`${me}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",Sm*10,{projectId:s,token:e})()}async function Lw(){rn.info("request to refresh JWT cli token from server");let s=await Ge({url:`${me}/auth/refreshToken`,body:{token:nt,refreshToken:nn}});return nt=s.token,sn=Uc(nt),s.refreshToken&&(nn=s.refreshToken),nt}async function Lc(){try{let s=await _w();return rn.info("successfully get cli token from server"),nt=s.token,sn=Uc(nt),nn=s.refreshToken,Dc=s.ngrokToken,Mc=s.isNgrokWhitelisted,nt}catch(s){throw s.message.includes("Unauthorized")?new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(rn.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Po}),new C(`While trying to retrieve CLI token, caught error: ${s}`))}}function Uc(s){return require("jsonwebtoken").decode(s).exp*1e3}async function Zt(){if(!sn)return Lc();if(sn<Date.now()+4*Sm)try{return await Lw()}catch(s){return rn.error("failed to refresh token, executing fallback",s),Lc()}return nt}function ko(){return nn}function jt(){return nt?{uid:require("jsonwebtoken").decode(nt).id,ngrokToken:Dc,isNgrokWhitelisted:Mc}:{}}var rn,nt,sn,nn,Dc,Mc,Po,Nc,Sm,Ct=T(()=>{"use strict";le();Ke();Bt();q();j();rn=x("testim-custom-token"),Po=null,Nc=null,Sm=5*60*1e3});var xm={};V(xm,{isCi:()=>es});var es,Oo=T(()=>{"use strict";es=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var Ae={};V(Ae,{addTestRetry:()=>cl,clearTestResult:()=>ol,deleteCloudflareTunnel:()=>dl,fetchLambdatestConfig:()=>rl,forceUpdateCloudflareTunnelRoutes:()=>pl,getAllGrids:()=>tl,getAppDetails:()=>zc,getApplitoolsIntegrationData:()=>ll,getBrowserStackSessionMetaData:()=>Vw,getCloudflareTunnel:()=>ul,getEditorUrl:()=>jw,getGridById:()=>Lo,getGridByName:()=>Zc,getHybridGridProvider:()=>Qc,getLabFeaturesByProjectId:()=>sl,getMobileDevicesFromGrid:()=>fl,getRealData:()=>nl,getS3Artifact:()=>an,getS3ArtifactText:()=>Bc,getSuiteTestList:()=>qc,getTestPlan:()=>Bw,getTestPlanTestList:()=>Hc,getTestResults:()=>Sr,getUsageForCurrentBillingPeriod:()=>Kc,initializeUserWithAuth:()=>el,isTestResultCompleted:()=>Jc,keepAliveCompanySlots:()=>Tl,keepAliveGrid:()=>Yc,loadSfdcCredential:()=>jc,loadTest:()=>$c,releaseCompanySlot:()=>yl,releaseGridSlot:()=>Xc,reportExecutionFinished:()=>_o,reportExecutionStarted:()=>Gc,requestCompanySlot:()=>hl,saveRemoteStep:()=>il,saveTestPlanResult:()=>Wc,updateCompanySlot:()=>bl,updateExecutionTests:()=>Vc,updateRemoteRunFailure:()=>ml,updateTestDataArtifact:()=>Mo,updateTestResult:()=>Do,updateTestStatus:()=>Er,uploadAppToGrid:()=>gl,uploadRunDataArtifact:()=>al});async function ts(){let s=await Zt();if(!s)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${s}`}}async function De({url:s,body:e,headers:t={},timeout:r,retry:n}){let o=await ts(),i=Object.assign({},t,o);return Ge({url:`${me}${s||""}`,body:e,headers:i,timeout:r,retry:n})}async function Nw(s,e,t,r={},n=void 0){let o=await ts(),i=Object.assign({},r,o);return await Ws(`${me}${s||""}`,e,t,i,n)}async function on(s,e){let t=await ts();return await rc(`${me}${s||""}`,e,t)}async function Uw(s,e){let t=await ts();return await $s(`${me}${s||""}`,e,t)}async function Fw(s,e){let t=await ts();return await Vs(`${me}${s||""}`,e||void 0,t)}async function xe(s,e,t,r){let n=await ts();return await Ee(`${me}${s||""}`,e||void 0,n,r,t)}function an(s,e){return(0,Z.default)(()=>xe(`/storage${s}`,null,{isBinary:!0},e),{retries:ee,factor:1})}function Bc(s){return(0,Z.default)(()=>Fw(`/storage${s}`))}async function Bw(s,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,Z.default)(()=>xe("/testPlan",{projectId:s,name:e.join(",")}),{retries:ee,factor:1})).map(({testConfigIds:n,beforeAllLabels:o,testLabels:i,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(o),testLabels:t(i),afterAllLabels:t(a)}))}async function jc({branch:s,projectId:e}){let t=await(0,Z.default)(()=>xe(`/branch/branchData/${s}`,{projectId:e}),{retries:ee,factor:1});return t==null?void 0:t.sfdcCredential}function $c({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,Z.default)(()=>xe(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:ee,factor:1})}function Wc(s,e,t){return(0,Z.default)(()=>De({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:ee,factor:1})}function Er(s,e,t,r,n,o,i=ee){return(0,Z.default)(()=>on("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:Dw,...o}),{retries:i,factor:1})}function Vc(s,e,t,r,n,o,i,a){return(0,Z.default)(()=>on("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:o,endTime:i,projectId:a}),{retries:ee,factor:1})}async function Gc({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:o,resultLabels:i,remoteRunId:a,localRunUserId:l,isLocalRun:c,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(Oo(),xm));return De({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:o,resultLabels:i,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function _o(s,e,t,r,n={},o=void 0,i=void 0){let a=Date.now();return(0,Z.default)(()=>on("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:ee,factor:1})}async function Hc(s,e,t,r,n){return(0,Z.default)(()=>De({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:ee,factor:1})}function qc({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,Z.default)(()=>De({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:ee,factor:1})}async function zc({appId:s,projectId:e}){try{return await(0,Z.default)(()=>xe(`/mobile-app/app/${s}?projectId=${e}`),{retries:ee,factor:1})}catch(t){Wt.error("failed getting application details",{appId:s,error:t});return}}async function Kc(s){try{return await(0,Z.default)(()=>xe(`/plan/project/${s}/usage-current-billing-period`),{retries:ee,factor:1})}catch(e){Wt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function Jc(s,e,t){return(0,Z.default)(()=>xe(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:ee,factor:1})}function Sr(s,e,t,r){return(0,Z.default)(()=>xe(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:ee,factor:1})}function Yc(s,e){return De({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function Xc(s,e,t,r,n){return De({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function Qc(s){return De({url:"/grid/hybrid/provider",body:s})}function Zc(s,e,t,r,n){return(0,Z.default)(()=>xe("/grid/name",{companyId:s,projectId:e,name:t,browser:r,executionId:n,reqId:re()}),{retries:ee,factor:1})}function Lo(s,e,t,r,n){return(0,Z.default)(()=>xe(`/grid/${t}`,{companyId:s,projectId:e,browser:r,executionId:n,reqId:re()}),{retries:ee,factor:1})}async function el({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,gridId:o,grid:i}){var a,l;try{return await(0,Z.default)(()=>Ge({url:`${me}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,gridId:o,gridName:i}}),{retries:ee,factor:1})}catch(c){throw Wt.error("error initializing info from server",c),(a=c==null?void 0:c.message)!=null&&a.includes("Bad Request")?new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(l=c==null?void 0:c.code)!=null&&l.includes("ENOTFOUND")?new C("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):c}}async function jw(){if(Ms)return{editorUrl:Ms};try{return await(0,Z.default)(()=>xe("/system-info/editor-url"),{retries:ee,onFailedAttempt:s=>{if(s.attemptNumber>=ee)throw s},factor:1})}catch{return Wt.error("cannot retrieve editor-url from server"),{editorUrl:"https://app.testim.io"}}}function tl(s){return(0,Z.default)(()=>xe("/grid",{companyId:s}),{retries:ee,factor:1})}function nl(s,e,t){return(0,Z.default)(()=>xe(`/real-data/${e}?${t}&projectId=${s}`),{retries:ee,factor:1})}function Do(s,e,t,r,n){return(0,Z.default)(()=>De({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:ee,factor:1})}function ol(s,e,t,r){return(0,Z.default)(()=>De({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:ee,factor:1})}function il(s,e,t,r){return(0,Z.default)(()=>De({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:ee,factor:1})}function $w(s){return s.startsWith("/")?s:`/${s}`}function Ww(s,e,t){let r=$w(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Cm(s,e,t,r,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${re()}${i||""}`,l=`${e}/${t}/${a}`,c=Ww(l,"test-result-artifacts",s),d=Buffer.from(Am.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,Z.default)(()=>Nw(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:ee,factor:1}),c}function cl({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:o,testResult:i}){return(0,Z.default)(()=>De({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:ee,factor:1})}async function ll(s){try{return await xe(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Wt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function ul(s,e){try{return await on("/tunnel",{companyId:s,routes:e})}catch(t){return Wt.warn("could'nt get tunnel.",{err:t}),{}}}async function pl(s,e){try{return await De({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}async function dl(s,e){try{return await Uw(`/tunnel/${e}`,{companyId:s})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}function ml(s){return Ge({url:`${me}/result/remoteRunFailure`,body:s})}async function fl({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let o=`${Mw}/mobileDevices/${t}/${r}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await(0,Z.default)(()=>xe(o,{projectId:s}),{retries:ee,factor:1})}catch(i){return Wt.warn("could'nt get devices from headspin grid.",{err:i}),null}}async function gl({projectId:s,gridId:e,app:t,timeout:r}){return(0,Z.default)(()=>De({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:ee,factor:1})}async function hl(s,e){return(0,Z.default)(()=>De({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:ee,factor:1})}async function yl(s,e,t){return(0,Z.default)(()=>De({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:ee,factor:1})}async function bl(s,e,t){return(0,Z.default)(()=>on("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:ee,factor:1})}function Tl(s,e,t){return De({url:`/slot-management/keep-alive?reqId=${re()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function Vw(s,e){return await Ee(`${Ns}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}var er,Am,Z,Fc,Dw,Wt,ee,Mw,rl,sl,al,Mo,ye=T(()=>{"use strict";er=v(require("lodash")),Am=v(require("pako"));B();le();ae();Ke();Ct();Z=v(require("p-retry")),Fc=v(require("object-hash"));q();j();Dw=dt(),Wt=x("testim service api"),ee=3,Mw="/grid";rl=async()=>(0,Z.default)(()=>xe("/grid/lt/config"),{retries:ee,factor:1}),sl=async s=>(0,Z.default)(()=>xe(`/labFeature/v2/project/${s}`),{retries:ee,factor:1});al=er.memoize(async(s,e,t,r)=>{if(!er.isEmpty(r))return await Cm(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,Fc.default)(r)}:${e}:${t}`),Mo=er.memoize(async(s,e,t,r,n)=>!r||er.isEmpty(r)?void 0:await Cm(s,e,t,JSON.stringify((()=>{let i=er.clone(r);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(l=>{i[l]&&Object.assign(i,{[l]:uc.HIDDEN_PARAM})})}return i})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,Fc.default)(r)}:${e}:${t}`)});var tr={};V(tr,{getSessionPlayer:()=>se,options:()=>vl});var No,vl,wl,se,Te=T(()=>{"use strict";No=require("path"),vl={playerPath:void 0},se=()=>{if(wl)return wl;let s=($e(),he(je));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(Zr(),he(Zs)),t=e(),r=vl.playerPath?(0,No.resolve)(vl.playerPath,"src/background/sessionPlayerInit.ts"):(0,No.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),wl=n,n}});function qw(s){process.nextTick(()=>{if([Y.SELENIUM,Y.APPIUM].includes(s))try{(Te(),he(tr)).getSessionPlayer()}catch{}})}async function cn(s){let{project:e,token:t,lightweightMode:r,useLocalChromeDriver:n,useChromeLauncher:o,mode:i,gridId:a,grid:l}=s,c=Boolean(r==null?void 0:r.general),d=Boolean(n||o),m=c?Hw:Gw;N("before initializeUserWithAuth");let u=await gt(async()=>(qw(i),await el({projectId:e,token:t,branchName:s.branch,lightweightMode:r,localGrid:d,gridId:a,grid:l})),"initializeUserWithAuth",m,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:c,localGrid:d,gridId:a,grid:l})();return N("after initializeUserWithAuth"),Rm(u.authData,s.project,s.token),u}var Gw,Hw,Pm=T(()=>{"use strict";$e();ye();Bt();Ct();ae();Gw=1e3*60*5,Hw=1e3*60*60*10});async function _m(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Co():s.chromeBinaryLocation,e=wr({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==Y.EXTENSION&&await vr(s.playerLocation,s.canary),s.mode===Y.EXTENSION&&!s.ext&&await Cc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await Ac(s.installCustomExtension,n)}return await e,t}async function Lm(s){var i;zw.info("prepare MockNetwork",{location:s});let e=await ic(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>km*1e6)throw new Error(`${El} exceeded ${km}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${El} cannot be parsed.${Uo.EOL}${a}`)}let n=new Om.default;if(!n.validate(Tc,r)){let a=(i=n.errors)==null?void 0:i.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(Uo.EOL);throw new Error(`${El} is malformed.${Uo.EOL}${a}`)}return r.entries}var Uo,Om,km,El,zw,Sl=T(()=>{"use strict";Uo=v(require("os"));B();$d();Zr();Om=v(require("ajv"));ae();_c();Pm();km=1,El="JSON file supplied to --mock-network-pattern",zw=(j(),he(Ka)).getLogger("prepare runner")});function Mm(s,e=process){async function t(r){await ce(ie(Dm,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{ln.error("Caught exception",{err:r}),console.log("Uncaught exception"),r.message&&console.log("Message =",r.message),r.reason&&console.log("Reason =",r.reason),await t(r)}),e.on("unhandledRejection",r=>{var n;if(ln.fatal("Caught unhandled promise rejection",r),!((n=r==null?void 0:r.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{ln.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw ln.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw ln.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function rs(s){Dm.push(s)}var ln,Dm,un=T(()=>{"use strict";j();B();ln=x("process-handler"),Dm=[]});var G,$m,Zw,ev,tv,jm,Bo,Al,M,fe=T(()=>{"use strict";G=v(require("rox-node"));j();B();le();$m=x("FeatureFlagsService"),Zw=!Oe&&!0&&!Zp,ev=2e4,tv=60*60*24,jm=["labs","disabled","enabled"],Bo=class extends G.default.Variant{constructor(e="disabled"){super(e,jm)}getValue(){let e=super.getValue();return jm.includes(e)?e:($m.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},Al=class{constructor(){this.flags={useNewWSCLI:new G.default.Flag,useSafariWebdriverVisibilityChecks:new G.default.Flag,useClickimVisibilityChecks:new G.default.Flag,runGetElementCodeInAut:new G.default.Flag,enableFrameSwitchOptimization:new G.default.Flag,maximumJsResultSize:new G.default.Configuration(2e3*1024),skipFileInputClicks:new G.default.Flag,errorMessageOnBadNetwork:new G.default.Flag(!0),warnOnBadNetwork:new G.default.Flag(!1),overrideAzureStorageUrl:new G.default.Flag,autoSaveDownloadFileFireFox:new G.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new G.default.Flag(!0),experimentalPreCodeCompilation:new G.default.Flag(!0),experimentalAsyncCustomCode:new G.default.Flag,useSameBrowserForMultiTests:new Bo("labs"),highSpeedMode:new Bo,usePortedHtml5DragDrop:new G.default.Flag,testNamesToBeforeSuiteHook:new G.default.Flag,addCustomCapabilities:new G.default.Variant("{}"),addCustomLTtunnelNTLMOptions:new G.default.Variant("{}"),LTNetworkCapabilities:new G.default.Flag,downloadToBase64:new G.default.Flag,publicGridURL:new G.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new G.default.Flag(!0),unsupportedCapsFields:new G.default.Variant("[]"),dontFocusOnInit:new G.default.Flag,retryOnSeleniumHubError:new G.default.Flag,enableLambdaTestTunnelNTLM:new G.default.Flag,enableLambdaTestTunnelSkipUpgrade:new G.default.Flag,tdcHsPreventNetworkCapture:new G.default.Flag,headSpinTdcEnableFlagCapability:new G.default.Flag,enableBatchTDC:new G.default.Flag,enableBatchHeadSpin:new G.default.Flag,clearRunnerFileCache:new G.default.Flag,forceTurboModeIfNeeded:new G.default.Flag,redisSlotManager:new G.default.Flag,tunnelBinaryNewVersion:new G.default.Flag(!1),computePackagePathFromPackageJsonExports:new G.default.Flag,sendExtensionOnEdgeNonLinux:new G.default.Flag},G.default.register("default",this.flags)}setProjectId(e){G.default.setCustomStringProperty("projectId",e)}setProjectType(e){G.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){G.default.setCustomStringProperty("productType",e)}setCompanyId(e){G.default.setCustomStringProperty("companyId",e)}setPlanType(e){G.default.setCustomStringProperty("planType",e)}setIsPOC(e){G.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){G.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){G.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!Zw)return;let e={fetchIntervalInSec:tv,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return ce(G.default.setup(Xp,e),ev).catch(t=>$m.error("failed to get feature flag status",t))}},M=new Al});function Cl(s,e){let t=s.canary?"-master.zip":".zip",r=`${e?rd:Nr}/extension/testim-firefox-profile${t}`,n=`${e?sd:Nr}/extension/testim-headless${t}`;return{firefox:r,chrome:n,"edge-chromium":n}}function Wm(s){let{chrome:e,firefox:t}=Cl(s,!1);return s.browser==="firefox"?t:s.browser==="chrome"?e:[e,t]}function jo(s){let e=`${Nr}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var $o=T(()=>{"use strict";le()});function zm(s){Oe||(s!=null&&s.userId||(s={anonymousId:qm}),Hm.identify(s))}function ht(s,e){return pn("ci",s,e)}function pn(s,e,t){if(Oe)return;let r=s?{userId:s}:{anonymousId:qm};Hm.track(Object.assign(r,{event:e,properties:t}))}var Gm,Hm,qm,ss=T(()=>{"use strict";le();Gm=v(require("analytics-node")),Hm=new Gm.default("sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",{flushAt:1}),qm=require("crypto").randomBytes(20).toString("hex")});function Km(s){return s.start&&pn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function Jm(s){let e=["playground-playwright","playground-puppeteer","playground-selenium"],t=!1,r=!1,n=!1,o=!1;if(s.start&&(o=!0),Number.isNaN(s.agentPort))throw new C("Agent port is not number");if(typeof s.agent=="string"&&e.some(a=>s.agent.includes(a))){let a=s.agent.split(",").map(l=>l.trim());a.includes("playground-playwright")&&(t=!0),a.includes("playground-puppeteer")&&(r=!0),a.includes("playground-selenium")&&(n=!0)}let i=jo(s);return console.log("Start Testim CLI on Agent mode"),{project:s.project,token:s.token,agentMode:!0,agentPort:s.agentPort,agentBind:s.agentBind,openEditor:s.openEditor,installPlaygroundPlaywrightDeps:t,installPlaygroundPuppeteerDeps:r,installPlaygroundSeleniumDeps:n,startTestimBrowser:o,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||i,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:Boolean(s.downloadBrowser)}}var Ym=T(()=>{"use strict";$o();ss();q()});function Vo(s){let{platform:e}=process;e==="win32"?(0,Wo.exec)(`start chrome ${s}`):e==="darwin"?(0,Wo.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,Wo.exec)(`google-chrome ${s}`)}var Wo,Pl=T(()=>{"use strict";Wo=require("child_process")});var mn={};V(mn,{doLogin:()=>Ll,getProjectId:()=>sv,getToken:()=>nv});async function sv(){return Zm("projectId")}async function nv(){return Zm("token")}function Qm(s,e){return Promise.race([s,oe(e).then(()=>{throw new ne("timeout")})])}async function ov(){let s=(await import("express")).default(),e=async function(){return Qm(new Promise(n=>{s.get("/loginInfo",(o,i)=>{n(JSON.parse(Buffer.from(o.query.info,"base64").toString())),i.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let o=s.listen(42543,i=>{i&&n(i),r(o.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ye(),Ae)),{editorUrl:n}=await r();Vo(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function Ll({overwriteExisting:s=!0,projects:e=null}={}){let t=kl.homedir(),r=Ol.join(t,".testim");if(await ge(r)&&!s)return;let o={},[{default:i},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await Qm(ov(),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,l.succeed(),await Xm(r,o);return}if(e!=null&&e.length){l.succeed();let c=e.length===1?{project:e[0]}:await i({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});o.token=c.project.ci.token,o.projectId=c.project.id,await Xm(r,o);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Xm(s,e){await _l.promises.writeFile(s,Go.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function Zm(s){let e=kl.homedir(),t=Ol.join(e,".testim"),r=await ge(t),n={};if(r)try{n=Go.parse((await _l.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var kl,Ol,Go,_l,ns=T(()=>{"use strict";kl=v(require("os")),Ol=v(require("path")),Go=v(require("yaml"));B();_l=require("fs");q();Pl()});var of={};V(of,{process:()=>mv});var Ml,tf,Nl,rf,Vt,Ne,sf,iv,Me,Bl,av,cv,ef,nf,lv,Ul,Fl,jl,Dl,Pt,uv,p,pv,dv,mv,af=T(()=>{"use strict";Ml=v(require("ms")),tf=v(require("chalk")),Nl=v(require("fs")),rf=v(require("url")),Vt=v(require("lodash")),Ne=v(require("path"));B();$o();Ym();Bt();sf=require("commander");ae();q();Mr();B();fe();iv=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Me=(s,e)=>(e.push(s),e),Bl=new sf.Command,av=s=>s.split(","),cv=(s,e)=>!s||s.length===0?e:s,ef=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],nf=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function o(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function i(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function l(g){return g.includes("--save-rca-locally")}function c(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}Bl.help(g=>g.split(`
|
|
17
17
|
`).filter(y=>!t(y)&&!e(y)&&!s(y)&&!r(y)&&!n(y)&&!a(y)&&!i(y)&&!o(y)&&!l(y)&&!c(y)&&!d(y)&&!m(y)&&!u(y)&&!f(y)).join(`
|
|
18
18
|
`))},lv=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(tf.default.yellow(`
|
|
19
19
|
WARNING: ${s} is deprecated. ${t}
|
|
20
20
|
`))},Ul=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:Fl,argv:jl,exit:Dl,cwd:Pt}=global.process,uv=["trace","debug","info","warn","error","silent"];mc(jl,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));Bl.description("Testim.io CLI").option("-h --help","output usage information",nf).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-config [test-config]","test config name to override for all tests in current execution",Me,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Me,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Me,[]).option("-w, --webpackConfig [webpack-configuration]","webpack configuration used to build the code based project").option("--test-id [test-id]","test ID to run",Me,[]).option("-l, --label [label]","labels to search test by",Me,[]).option("-n, --name [test-name]","test name to run",Me,[]).option("--project [project-id]","project ID").option("-r, --report-file [report junit xml path]","where to save junit xml results file").option("--urls","add step urls to the junit report").option("--override-report-file-classname [override-report-file-classname]","custom junit class name for the junit reporter").option("--reporters [names]","report types",av).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",Me,[]).option("--test-plan-id [test-plan-id]","test plan to run",Me,[]).option("--suite [suite-name]","suite to run",Me,[]).option("--suite-id [suite-id]","suite ID to run",Me,[]).option("--rerun-failed-by-run-id [run-id]","allows re-running failed tests from a specific run ID").option("--disable-grid-check [boolean]","disable checking if selenium grid is available",!1).option("--disable-native-events [boolean]","pass nativeEvents=false capability to the selenium browser (in selenium mode)",!1).option("--disable-timeout-retry [boolean]","disable retry after test pass test timeout",!1).option("--ca-file [ca-file-location]","ca certificate file location").option("--proxy [proxy-url]","proxy url to all requests").option("--proxy-for-grid [proxy-for-grid]","used together with --proxy to also router grid traffic through a proxy").option("--result-label [result-label]","result label",Me,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("--duration [duration]","The duration of the test run in minutes",Number).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--clear-file-cache","clear internal CLI file cache").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(Fl.TESTIM_TEST_START_TIMEOUT)||2*60*1e3).option("--timeout [test-timeout]","Test run timeout in milliseconds",Number).option("--browser-timeout [open-browser-timeout]","Get browser from grid timeout in milliseconds",Number).option("--new-browser-wait-timeout [max-wait-to-browser]","Maximum get browser wait in minutes",Number).option("--get-browser-timeout [get-browser-timeout]","Timeout for a single attempt to get browser from the grid configured in the project's plan",Number).option("--get-browser-retries [get-browser-retries]","Number of attempts to get browser from the grid configured in the project's plan",Number).option("--get-session-timeout [get-session-timeout]",'Timeout for "/session" request to the selenium server',Number,(0,Ml.default)("90s")).option("--get-session-retries [get-session-retries]",'Retries for "/session" request to the selenium server',Number,3).option("--driver-request-timeout [driver-request-timeout]","Timeout for any WebDriver request to the grid server",Number,(0,Ml.default)("90s")).option("--driver-request-retries [driver-request-retries]","Retries for any WebDriver request to the grid server",Number,3).option("--local-tma-url [local-tma-url]","use a local TMA instance for appium session").option("--use-local-chrome-driver [use-local-chrome-driver]","use a local ChromeDriver instance instead of a selenium grid").option("--chrome-binary-location [chrome-binary-location]","Chrome binary location").option("--use-chrome-launcher","use a local Chrome installation without selenium").option("-mnh --mock-network-har","use the HAR file configured in the Testim editor to mock network traffic").option("-mnp --mock-network-pattern [local file location path]","use a JSON rule file to mock network traffic (Rule file schema: https://help.testim.io/page/mocking-network-traffic)").option("-omf --override-mapping-file [local file location path]","pass map file location to override mock network (see schema: https://help.testim.io/page/mocking-network-traffic)").option("-dmn --disable-mock-network","Disable mock mode for the entire CLI run").option("--run-quarantined-tests","Run quarantine tests").option("--collect-code-coverage","collect code coverage for all js files under base url").option("--code-coverage-url-filter [url pattern]","collect code coverage for all js files matching url filter (url including asterisk)").option("--code-coverage-report-path [path]","where to save coverage report (default ./coverage)").option("--code-coverage-source-map-path [path]","path of source code").option("--code-coverage-reporter [reporter]",`set code coverage reporter (default html and text), options: ${Ul.join("/")}`,Me,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Me,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--login","Log in to Testim").option("--require-credentials","Log in to Testim if not already logged in").option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",Me,[]).option("--intersect-with-suite [suiteName]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite name)",Me,[]).option("--intersect-with-suite-id [suiteId]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite ID)",Me,[]).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).parse(jl);p=Bl.opts(),pv=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},dv=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},mv=async()=>{var E,I,b,w,R,k,_,$;p.inspect&&require("inspector").open(p.inspect);let s={},e={},t=[],r={};if(!jl.slice(2).length)throw nf(),new Fr;if(p.requireCredentials){let S=await Promise.resolve().then(()=>(ns(),mn)),A=await S.getProjectId(),L=await S.getToken();(!A||!L)&&await S.doLogin()}if(p.login)return await(await Promise.resolve().then(()=>(ns(),mn))).doLogin(),{loginMode:!0};if(p.version){let S="Testim CLI Version: ";Fl.npm_package_version&&(console.log(S,Fl.npm_package_version),Dl(0));let A=dt();A&&(console.log(S,A),Dl(0)),console.log("Could not find version, please check the package.json manually"),Dl(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Zd(),p.clearFileCache&&Jr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let S=Ne.resolve(n);Xd(S)}if(p.usePrefechedData&&em(),p.playerRequirePath){let S=Ne.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",S);let A=Ne.join(S,"tsconfig.node.json"),U=require("ts-node").register({project:A,ignore:[/node_modules/,new RegExp(`^${Vt.escapeRegExp(Ne.relative(Pt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:U.config.options.paths,baseUrl:U.config.options.baseUrl}),(Te(),he(tr)).options.playerPath=S;let H=require("module"),X=H.prototype.require;H.prototype.require=function(Et){return Et==="rox-alias"?X.call(this,"rox-node"):X.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=Nl.readFileSync(p.caFile)),p.proxy&&(global.proxyUri=p.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent").ProxyAgent,global.HttpsProxyAgent=require("https-proxy-agent").HttpsProxyAgent),p.proxyForGrid&&!p.proxy)throw new C("missing --proxy option");if(Km(p))return Jm(p);try{let S={};p.configFile?S=require(Ne.join(Pt(),p.configFile)).config:p.optionsFile&&(S=require(Ne.join(Pt(),p.optionsFile))),S&&typeof S.then=="function"&&(S=await S),Object.keys(S).forEach(A=>{let L=iv(A);p[L]=cv(p[L],S[A])})}catch(S){throw S.message=`Unable to read options file: ${S.message}`,S}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let o=((E=p.testConfig)==null?void 0:E.length)||((I=p.testConfigId)==null?void 0:I.length),i=((b=p.testPlan)==null?void 0:b.length)||((w=p.testPlanId)==null?void 0:w.length),a=((R=p.suite)==null?void 0:R.length)||((k=p.suiteId)==null?void 0:k.length);if(p.seleniumCapsFile)try{r=require(Ne.join(Pt(),p.seleniumCapsFile))}catch(S){throw new C(`Failed to parse selenium caps file file error: ${S.message}`)}if((_=p.reporters)!=null&&_.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new C("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new C("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new C("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Ne.join(Pt(),p.chromeExtraPrefs))}catch(S){throw new C(`Failed to read/open chrome extra prefs file error: ${S.message}`)}if(p.chromeExtraArgs){let S=p.chromeExtraArgs.split(",");for(let A of S){let[L]=A.split("=");ef.includes(L)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(A),L==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${L}), allowed values: ${JSON.stringify(ef)}`)}}if(p.paramsFile)try{s=Object.assign({},s,require(Ne.join(Pt(),p.paramsFile)))}catch(S){throw new C(`Failed to read/open params file error: ${S.message}`)}if(p.params)try{s=Object.assign({},s,JSON.parse(p.params))}catch(S){throw new C(`Failed to parse params string error: ${S.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new C("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(pv(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let S=require(Ne.join(Pt(),p.sauceOptions)),A=S.platformName&&["ios","android"].includes(S.platformName.toLowerCase());if(S.browserName){let U=S.browserName.toLowerCase();switch(U){case"microsoftedge":p.browser="edge";break;default:p.browser=U}}p.browser==="edge"&&parseFloat(S.version)>=La&&(p.browser="edge-chromium");let L=parseFloat(S.version)<50&&!["dev","beta"].includes(S.version);if(!A&&p.browser==="chrome"&&L)throw new C("The minimum chrome supported version is 50.0");p.saucelabs=Object.assign({},p.saucelabs,S)}catch(S){throw new C(`Failed to parse saucelabs options file error: ${S.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new C("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(dv(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let S=require(Ne.join(Pt(),p.browserstackOptions)),A=S.platform&&["mac","android"].includes(S.platform.toLowerCase());if(S.browserName&&(p.browser=S.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(S.browser_version)>=La&&(p.browser="edge-chromium"),!A&&parseFloat(S.browser_version)<50&&p.browser==="chrome")throw new C("The minimum chrome supported version is 50.0");p.browserstack=Object.assign({},p.browserstack,S)}catch(S){throw new C(`Failed to parse browserstack options file error: ${S.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let S=require(Ne.join(Pt(),p.perfectoOptions)),A={location:"US East",securityToken:p.perfectoToken};p.perfecto=Object.assign({},A,S)}catch(S){throw new C(`Failed to parse perfecto options file error: ${S.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let S=require(Ne.join(Pt(),p.testobjectOptions)),A={testobjectApiKey:p.testobjectKey};p.testobjectSauce=Object.assign({},A,S)}catch(S){throw new C(`Failed to parse test object options file error: ${S.message}`)}if(!p.project){let A=await(await Promise.resolve().then(()=>(ns(),mn))).getProjectId();if(A)p.project=A;else throw new C("missing project-id info, either --login to provide new credentials or use --project <project-id>")}M.flags.forceTurboModeIfNeeded.isEnabled({projectId:p.project})&&(p.turboMode=!0),p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),p.mode??="extension",p.retries=!p.retries||typeof p.retries=="boolean"?1:Number(p.retries)+1,p.browserTimeout=!p.browserTimeout||typeof p.browserTimeout=="boolean"?60*1e3:p.browserTimeout,p.newBrowserWaitTimeout=!p.newBrowserWaitTimeout||typeof p.newBrowserWaitTimeout=="boolean"?10*60*1e3:p.newBrowserWaitTimeout*60*1e3,p.getBrowserTimeout||(p.getBrowserTimeout=p.browserTimeout),p.getBrowserRetries||(p.getBrowserRetries=p.mode===Y.APPIUM?1:Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=p.browserTimeout<p.getSessionTimeout?p.getSessionTimeout:p.browserTimeout,p.driverRequestTimeout=p.browserTimeout<p.driverRequestTimeout?p.driverRequestTimeout:p.browserTimeout;let c=Boolean(p.timeout);if(p.timeout=!p.timeout||typeof p.timeout=="boolean"?10*60*1e3:p.timeout,p.beforeParallel=!p.beforeParallel||typeof p.beforeParallel=="boolean"?1:Number(p.beforeParallel),p.parallel=!p.parallel||typeof p.parallel=="boolean"?1:Number(p.parallel),p.afterParallel=!p.afterParallel||typeof p.afterParallel=="boolean"?1:Number(p.afterParallel),p.tunnelPort=!p.tunnelPort||typeof p.tunnelPort=="boolean"?"80":p.tunnelPort,p.port&&=Number(p.port),!p.token){let A=await(await Promise.resolve().then(()=>(ns(),mn))).getToken();if(A)p.token=A;else throw new C("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let d=S=>S<=0||!Number.isInteger(S);if(d(p.retries))throw new C("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new C("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(d(p.browserTimeout))throw new C("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d(p.newBrowserWaitTimeout))throw new C("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(d(p.timeout))throw new C("test run timeout could not be a negative number, --timeout <run-timeout>");if(d(p.beforeParallel))throw new C("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d(p.parallel))throw new C("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d(p.afterParallel))throw new C("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![Y.EXTENSION,Y.SELENIUM,Y.APPIUM].includes(p.mode))throw new C(`runner mode <${p.mode}> is not supported`);if(p.mode!==Y.SELENIUM&&p.disableNativeEvents)throw new C("disable-native-events is only applicable in selenium mode");if(!p.browser&&!o&&!i&&(p.browser="chrome"),p.appiumLogLevel||(p.appiumLogLevel="silent"),!uv.includes(p.appiumLogLevel))throw new C(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData)throw new C("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(p.testId.length||p.label.length||p.name.length||o||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new C("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --local-tma-url, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!i&&(p.beforeParallel!==1||p.afterParallel!==1))throw new C("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new C("please define exactly one of --grid or --grid-id or --host");if(($=p.host)!=null&&$.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=rf.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(A=>A.trim()).filter(Boolean);let S=p.resultLabel.filter(A=>A.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&yr()&&p.resultLabel.unshift(yr()),S.length)throw new C("A result label cannot exceed 250 characters")}let u=Wm(p),f=jo(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new C("cannot set --w3c-capabilities and --old-capabilities options as false");if(p.protocol||=p.port===443?"https":"http",!["http","https"].includes(p.protocol))throw new C("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new C("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(p.rerunFailedByRunId&&(a||p.name.length||p.testId.length||p.label.length||i))throw new C("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(p.setRetention&&!Vt.inRange(Vt.parseInt(p.setRetention),1,11))throw new C("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");p.setRetention&&=Number(p.setRetention);let g="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new C(`--mock-network-har ${g}`);if(p.mockNetworkPattern)throw new C(`--mock-network-pattern ${g}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new C("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new C("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new C("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new C("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&Vt.difference(p.codeCoverageReporter,Ul).length){let S=Vt.difference(p.codeCoverageReporter,Ul);throw new C(`invalid --code-coverage-reporter parameters ${S.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let h={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},y=Object.keys(h).filter(S=>Boolean(p[S]));if(p.mode!==Y.EXTENSION&&y.length){let S=y.length>1?"are":"is";throw new C(`${y.map(A=>h[A]).join(" and ")} ${S} only applicable in extension mode`)}if(p.tmsFieldFile)try{let S=Nl.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(S)}catch(S){throw new C(`failed to parse field file error: ${S.message}`)}if(p.highSpeed&&(lv("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new C("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new C("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(p.setNoReset&&p.fullReset)throw new C("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.lightweightMode)try{let S={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},A=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode=Object.assign({},S,A)}catch(S){throw new C(`failed to parse lightweightMode settings error: ${S.message}`)}else p.turboMode&&p.mode===Y.EXTENSION?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&p.mode===Y.SELENIUM&&console.warn(`
|
|
21
21
|
When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they are not compatible concurrently`);if(typeof p.baseUrl=="boolean")throw new C("base url cannot be used as a flag, and must contain a string value");return{testId:[p.testId].flat(),name:[p.name].flat(),label:[p.label].flat(),suites:[p.suite].flat(),suiteIds:[p.suiteId].flat(),testPlan:[p.testPlan].flat(),testPlanIds:[p.testPlanId].flat(),webpackConfig:p.webpackConfig,reportFile:p.reportFile,urls:p.urls,reportFileClassname:p.overrideReportFileClassname,reporters:p.reporters,project:p.project,host:p.host,headless:p.headless,localTmaUrl:p.localTmaUrl,useLocalChromeDriver:p.useLocalChromeDriver,chromeBinaryLocation:p.chromeBinaryLocation,useChromeLauncher:p.useChromeLauncher,port:p.port,grid:p.grid,gridId:p.gridId,disableNativeEvents:p.disableNativeEvents,saucelabs:p.saucelabs,browserstack:p.browserstack,baseUrl:p.baseUrl,branch:(p.branch==="auto-detect"?yr():p.branch)||"master",autoDetect:p.branch==="auto-detect",token:p.token,userParamsData:s,mode:p.mode,browser:p.browser,beforeParallel:p.beforeParallel,parallel:p.parallel,afterParallel:p.afterParallel,canary:p.canary,rerunFailedByRunId:p.rerunFailedByRunId,disableGridCheck:p.disableGridCheck,disableTimeoutRetry:p.disableTimeoutRetry,resultLabels:p.resultLabel,path:p.path,protocol:p.protocol,perfecto:p.perfecto,experitestToken:p.experitestToken,testobjectSauce:p.testobjectSauce,gridUsername:p.gridUsername,gridPassword:p.gridPassword,overrideExecutionName:p.overrideExecutionName,tmsSuppressReporting:Boolean(p.suppressTmsReporting)||Boolean(p.tmsSuppressReporting),tmsRunId:p.tmsRunId,tmsCustomFields:p.tmsCustomFields,proxyForGrid:p.proxyForGrid,retentionDays:p.setRetention,passZeroTests:Boolean(p.passZeroTests),runQuarantinedTests:Boolean(p.runQuarantinedTests),deviceName:p.deviceName,deviceUdid:p.deviceUdid,customTag:p.customTag,osVersion:p.osVersion,duration:p.duration,skipLoadBalancer:p.skipLoadBalancer,lockDevice:p.lockDevice,appId:p.appId,appiumLogLevel:p.appiumLogLevel,setNoReset:p.setNoReset,fullReset:p.fullReset,ext:p.ext,extensionLocation:[p.extensionPath||u].flat(),extensionPath:p.extensionPath,playerLocation:p.playerPath||f,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:c,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0},downloadBrowser:p.downloadBrowser,slotService:"mongo"}}});var pf={};V(pf,{installAllLazyDependencies:()=>hv,lazyRequire:()=>Se});async function Se(s,e={}){let t=Ic(s);if(t)return t;let r;e.silent||(r=(0,cf.default)(`Installing ${s} before first usage...`).start());try{let n=await gv(s);return r&&r.succeed(),n}catch(n){fv.warn("failed to install dependency lazily",{dependency:s,err:n});let o=uf(s),i=`${s}@${o}`,l=process.argv.includes("npx")?"":"-g ",c=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${l}${i}`;throw r&&r.fail(c),n}}async function gv(s){return os.has(s)||(os.set(s,lf(s)),os.get(s).catch(()=>{os.delete(s)})),os.get(s)}async function lf(s){let e=Ic(s);if(e)return e;let t=uf(s),r=`${s}@${t}`;return await Io(mt(),r),Qt(s)}async function hv(){let s=Object.keys(Ua);for(let e of s)await lf(e)}function uf(s){let e=Object.entries(Ua).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var cf,fv,os,Ir=T(()=>{"use strict";cf=v(require("ora"));Xr();j();B();Xn();Qs();fv=x("lazy-require"),os=new Map});var mf={};V(mf,{preloadTests:()=>fn});async function fn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await gt(async()=>{let t=await ie(s.testId,r=>$c({...e,testId:r}),{concurrency:2});return df.keyBy(t,"testData.id")},"loadTests",yv,[e,s.testId])()}var df,yv,Ho=T(()=>{"use strict";df=v(require("lodash"));Bt();ye();B();yv=1e3*60*60*10});function $l(){return dt()}async function hf(){if(!Oe)try{let s=await ce(Tv(),5e3,"The API call to NPM timed out"),e=$l();e&&gf.lt(e,s)&&console.log(ff.default.yellow(`Warning: You are using version ${e}, a newer version is available. To update please run npm install (npm install -g @testim/testim-cli)`))}catch(s){bv.warn("Failed to get NPM version",{err:s})}}var ff,gf,bv,Tv,Wl=T(()=>{"use strict";ff=v(require("chalk")),gf=v(require("semver"));B();le();Xr();Bt();j();bv=x("npm-driver"),Tv=gt(()=>om("@testim/testim-cli"),"getNpmVersion")});var Vl,vv,is,yf,bf,Gl,Tf,wf=T(()=>{"use strict";B();q();j();Ir();Vl=x("testimNgrok"),vv=".whitelisted-ngrok.testim.io",is="",bf=async(s,e={})=>{if(!e.ngrokToken)throw new C("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${re()}-${s.projectData.projectId}${vv}`);let r={proto:"http",addr:s.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};s.tunnelHostHeader&&(r.host_header=s.tunnelHostHeader),s.tunnelRegion&&(r.region=s.tunnelRegion);let o=await(await Se("ngrok")).connect(r);s.tunnelUseHttpAddress&&o.startsWith("https://")?(Vl.info("replace https to http"),is=o.replace("https://","http://")):is=o,s.tunnelDiagnostics&&Gl(),s.baseUrl=is},Gl=async(s=!0)=>{try{let t=(await Se("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(o=>o.public_url===is);console.log("ngrok stats",n),Vl.info("ngrok stats",{tunnel:n})}catch(e){Vl.error("error collecting ngrok stats",{err:e})}s&&(yf=setTimeout(()=>Gl(),1e4))},Tf=async s=>{if(!is)return;clearTimeout(yf),s.tunnelDiagnostics&&await Gl(!1),await(await Se("ngrok")).disconnect(is)}});var rr,ql,vf,Sv,Iv,Hl,qo,Ko,zo,Rv,Ef,Sf,If=T(()=>{"use strict";rr=v(require("os")),ql=v(require("fs")),vf=v(require("child_process"));B();ye();Sv="https://github.com/cloudflare/cloudflared/releases/download/2023.10.0/",Iv={win32ia32:{path:"cloudflared-windows-386.exe"},win32x64:{path:"cloudflared-windows-amd64.exe"},darwinx64:{path:"cloudflared-darwin-amd64.tgz",extract:!0},linuxia32:{path:"cloudflared-linux-386"},linuxx64:{path:"cloudflared-linux-amd64"}},Hl=rr.tmpdir(),qo=`${Hl}/cloudflared`,Ko=null,zo=null,Rv=async()=>{if(await ge(qo))return;let e=Iv[rr.platform()+rr.arch()];if(!e)throw new Error(`tunnel on ${rr.platform()+rr.arch()} platform is not supported.`);let t=e.extract?Hl+e.path:qo;await Je(`${Sv}/${e.path}`,t),e.extract&&await st(t,Hl),await ql.promises.chmod(qo,"755")},Ef=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([ul(s.company.companyId,t),Rv()]);Ko=r._id,zo=vf.spawn(qo,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await pl(s.company.companyId,Ko),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await ql.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},Sf=async s=>{let e=[];return Ko&&e.push(dl(s.company.companyId,Ko)),zo&&e.push(new Promise((t,r)=>{zo.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),zo.kill()})),await Promise.all(e)}});function _v(s){if(!(s!=null&&s.width)||!(s!=null&&s.height))return te.lambdatestConfig.RESOLUTION;let e=`${s.width}x${s.height}`;return Ov.includes(e)?e:(Jo.warn("default resolution is used because the resolution is not supported by LT",{resolutionString:e}),te.lambdatestConfig.RESOLUTION)}var Rf,xf,Gt,Af,Cf,Pf,Yo,kf,Jo,Av,Cv,gn,Pv,kv,te,Ov,Xo=T(()=>{"use strict";Rf=v(require("ms")),xf=v(require("p-retry")),Gt=v(require("os")),Af=v(require("portfinder")),Cf=v(require("child_process"));B();Ke();ye();Pf=v(require("fs")),Yo=v(require("fs/promises")),kf=require("path");q();j();$o();ae();fe();B();Jo=x("lambdatestService"),Av="https://downloads.lambdatest.com/tunnel/v3",Cv={win32ia32:"windows/32bit/LT_Windows.zip",win32x64:"windows/64bit/LT_Windows.zip",darwinia32:"mac/32bit/LT_Mac.zip",darwinx64:"mac/64bit/LT_Mac.zip",darwinarm64:"mac/64bit/LT_Mac.zip",linuxia32:"linux/32bit/LT_Linux.zip",linuxx64:"linux/64bit/LT_Linux.zip",freebsdia32:"freebsd/32bit/LT_Freebsd.zip",freebsdx64:"freebsd/64bit/LT_Freebsd.zip"},gn=`${Gt.tmpdir()}/LT`,Pv=`${gn}/LT`,kv=(0,Rf.default)("15m"),te=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===O.LAMBDATEST||e.type===O.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){te.isLambdatestGrid(e)&&(te.lambdatestConfigPromise||=rl(),te.lambdatestConfig=await te.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?kv:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ge(Pv))return;let t=Cv[Gt.platform()+Gt.arch()];if(!t)throw new Error(`tunnel on ${Gt.platform()+Gt.arch()} platform is not supported.`);let r=`${gn}.zip`;await Je(`${Av}/${t}`,r),await st(r,gn)}static async chmodLtTunnel(e){if(!(Gt.platform()==="win32"||!await ge(e))){try{await Yo.access(e,Pf.constants.X_OK);return}catch{}try{await Yo.chmod(e,"777")}catch(r){throw Jo.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await oe(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){te.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await Af.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:o,externalLambdatestNTLMTunnelUsername:i,externalLambdatestNTLMTunnelPassword:a}=e,l=global.proxyUri;te.tunnelName=re();let c=["--tunnelName",te.tunnelName,"--infoAPIPort",String(t)];if(M.flags.enableLambdaTestTunnelNTLM.isEnabled())if(c=[...c,"--ntlm"],i&&a)c=[...c,"--ntlm-username",i,"--ntlm-password",a];else{let u=JSON.parse(M.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(c=[...c,...fc(u)])}if(M.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(c=[...c,"--skip-upgrade"]),e.externalLambdatestUseWss&&(c=[...c,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(c=[...c,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),r.tunnelUser&&r.tunnelKey)c=[...c,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&o)c=[...c,"--user",n,"--key",o];else throw new C("tunnel requires username and password");if(l)try{let u=new URL(l);c=[...c,"--proxy-host",u.hostname],u.port&&(c=[...c,"--proxy-port",u.port]),u.username&&u.password&&(c=[...c,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new C("proxy url is invalid")}e.externalLambdatestMitm&&(c=[...c,"--mitm"]),await te.delay(3e3),await te.chmodLtTunnel((0,kf.join)(gn,"LT")),te.tunnel=Cf.spawn("./LT",c,{cwd:gn});let d="",m="";te.tunnel.stdout.on("data",u=>{d+=u.toString()}),te.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,xf.default)(()=>Ee(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});Jo.info("LT tunnel info",u)}catch(u){throw Jo.error("Failed to start LT tunnel",{err:u,stdoutResult:d,stderrResult:m}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!te.tunnel))return new Promise((t,r)=>{te.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),te.tunnel.kill()})}getCapabilities(e,t,r,n,o,i){if(!this.isActive)return{};let a=te.lambdatestConfig.CAPABILITIES[t]||{},l={...te.tunnelName&&{tunnel:!0,tunnelName:te.tunnelName}},c=[],{mode:d,canary:m,ext:u,extensionPath:f,installCustomExtension:g}=e,h=(i==null?void 0:i.os)==="Windows 11"?i.os:te.lambdatestConfig.PLATFORM;if(d===Y.EXTENSION&&!u){let y=Cl({canary:m},!0);!f&&y[t]&&(c=[...c,y[t]]),f&&We(f)&&(c=[...c,f])}return g&&We(g)&&(c=[...c,g]),{build:r,name:`${n} - ${o}`,platform:h,selenium_version:te.lambdatestConfig.SELENIUM_VERSION,resolution:_v(i==null?void 0:i.resolution),timezone:te.lambdatestConfig.TIMEZONE,...a,loadExtension:c,...l,console:!0,queueTimeout:300,network:M.flags.LTNetworkCapabilities.isEnabled(),ntlm:M.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:M.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},Ov=["1024x768","1280x800","1280x1024","1366x768","1440x900","1680x1050","1600x1200","1920x1200","1920x1080","2048x1536","2560x1440"]});var zl={};V(zl,{connect:()=>Zo,disconnect:()=>ei,serveTunneling:()=>Dv});var Qo,Of,_f,Lv,Zo,ei,Dv,Kl=T(()=>{"use strict";wf();un();If();Ct();Qo=v(require("ora"));j();ae();Xo();Of=x("tunnel"),_f=s=>{var e;return[O.LAMBDATEST,O.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},Lv=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===O.HYBRID&&s.gridData.tunnel==="cloudflare"},Zo=async s=>{if(!s.tunnel)return;let e=jt(),t;try{_f(s)?(t=(0,Qo.default)("Starting testim lambdatest tunnel...").start(),await te.connectTunnel(s)):Lv(s)?(t=(0,Qo.default)("Starting testim cloudflare tunnel...").start(),await Ef(s)):(t=(0,Qo.default)("Starting testim ngrok tunnel...").start(),await bf(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw Of.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(n)}},ei=async s=>{if(s.tunnel)try{_f(s)?await te.disconnectTunnel(s):"tunnelRoutes"in s?await Sf(s):await Tf(s)}catch(e){let t="catch error - failed to close tunnel";throw Of.error(t,{err:e}),new Error(t)}},Dv=async(s,e=new Promise(()=>{}))=>(await Zo(s),rs(()=>ei(s)),await e)});function Mv(s){if(s.protocol)return s.protocol;if([O.TESTIM,O.BROWSERSTACK,O.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([O.TESTIM_ENTERPRISE,O.LAMBDATEST,O.DEVICE_FARM].includes(s.type)){let e=Lf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function Nv(s){let e=Lf.exec(s);return e==null?void 0:e[3]}function ri(s){var I,b,w,R,k,_,$,S,A,L,U;let e=s&&Nv(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&Mv(s),o=s==null?void 0:s.token,i=s==null?void 0:s.slotId,a=(I=s==null?void 0:s.hybrid)==null?void 0:I.tunnel,l=(b=s==null?void 0:s.external)==null?void 0:b.user,c=(w=s==null?void 0:s.external)==null?void 0:w.key,d=s==null?void 0:s.type,m=d===O.HYBRID?a&&((_=(k=(R=s.hybrid)==null?void 0:R.external)==null?void 0:k[s.hybrid.tunnel])==null?void 0:_.user):l,u=d===O.HYBRID?a&&((A=(S=($=s.hybrid)==null?void 0:$.external)==null?void 0:S[s.hybrid.tunnel])==null?void 0:A.key):c,f=s==null?void 0:s.name,g=s&&(s._id||s.gridId),h=s==null?void 0:s.provider,y=(L=s==null?void 0:s.mobileTokens)==null?void 0:L.androidToken,E=(U=s==null?void 0:s.mobileTokens)==null?void 0:U.iosToken;return{host:e,port:t,path:r,protocol:n,accessToken:o,slotId:i,gridId:g,tunnel:a,user:l,key:c,type:d,name:f,provider:h,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:E}}async function Mf(s,e,t,r,n){let o;try{o=await n()}catch(i){throw Qe.error("failed to get grid",{projectId:s,companyId:e,err:i}),new Error(ft.UNKNOWN)}if(Qe.info("get grid info",Object.assign({},o,{projectId:s,companyId:e})),!o||!["success","error"].includes(o.status))throw Qe.error("invalid response - get grid",{res:o}),new Error(ft.UNKNOWN);if(o.status==="success"){let i=ri(o.grid);return Uv(t,e,i.gridId,i.slotId,r),i}throw o.code==="not-found"?new ze(ft.NOT_FOUND):o.code==="no-available-slot"?new Jt(`Failed to run test on ${r} - concurrency limit reached`):(Qe.error("invalid code error response - get grid",{res:o}),new ze(ft.UNKNOWN))}function Fv(s,e,t,r,n,o){return Mf(t,e,s,n,()=>Lo(e,t,r,n,o))}function Bv(s,e,t,r,n,o,i){return Mf(t,e,s,n,()=>{var c;let l=(c=i.allGrids)==null?void 0:c.find(d=>(d.name||"").toLowerCase()===r.toLowerCase());return l!=null&&l._id?Lo(e,t,l._id,n,o):Zc(e,t,r,n,o)})}function Nf(s){return tl(s)}async function Uf(s,e,t){let n=(t||await Nf(s)).find(o=>o._id===e);if(!n)throw new C(`Failed to find grid id: ${e}`);return ri(n)}async function jv(s,e,t){let n=(t||await Nf(s)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new C(`Failed to find grid name: ${e}`);return ri(n)}async function Jl(s,e){let t=hn[s];if(!t)return;let{slotId:r,gridId:n,browser:o,companyId:i}=t;if(delete hn[s],!r){Qe.warn("failed to find grid slot id",{projectId:e});return}Qe.info("release slot id",{projectId:e,companyId:i,slotId:r,gridId:n,browser:o});try{await Xc(i,e,r,n,o)}catch(a){Qe.error("failed to release slot",{projectId:e,err:a})}}async function $v(s){let e=Object.values(hn).filter(Boolean);if(e.length!==0){Qe.info("keep alive worker slots",{projectId:s,slots:e});try{await Yc(s,e)}catch(t){Qe.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function Wv(s){Df=global.setInterval($v,1e4,s)}async function Vv(s){let e=Object.keys(hn);if(e.length){Qe.warn("not all slots released before end runner flow",{projectId:s});try{await ie(e,t=>Jl(Number(t),s))}catch(t){Qe.error("failed to release all slots",{err:t,projectId:s})}}}async function Gv(s){await Vv(s),clearInterval(Df)}function Hv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function qv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function Ff(s){let t=(()=>ti.isEmpty(s.testobjectSauce)?ti.isEmpty(s.saucelabs)?ti.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:o,protocol:i}=s,a=Hv(t,s),l=qv(t,s);return{host:r,port:n,path:o,protocol:i,type:t,user:l,key:a}}async function Bf(s,e){let t=s.company.companyId;return await Uf(t,e.gridId,s.allGrids)}async function jf(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:o,useChromeLauncher:i,gridId:a,grid:l}=s;if(n||i||o)return{mode:"local"};if(r)return Ff(s);let c=t==null?void 0:t.companyId;if(a)return Uf(c,a,e);if(l)return jv(c,l,e);if(zs(s)||s.tunnelOnlyMode){Qe.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new ze("Missing host or grid configuration")}async function $f(s,e,t,r){let{host:n,project:o,grid:i,gridId:a,localTmaUrl:l,useLocalChromeDriver:c,useChromeLauncher:d,company:m}=t,u=m==null?void 0:m.companyId;if(c||d||l)return{mode:"local"};if(n)return Ff(t);if(a)return Fv(r,u,o,a,s,e);if(i)return Bv(r,u,o,i,s,e,t);throw new ze("Missing host or grid configuration")}var ti,Qe,hn,Lf,Df,Uv,yn,Wf,as=T(()=>{"use strict";ti=v(require("lodash"));ye();j();B();ae();q();Qe=x("grid-service"),hn={},Lf=/(^(https?):\/{2})?(.*)/,Df=null;Uv=(s,e,t,r,n)=>{hn[s]={gridId:t,companyId:e,slotId:r,browser:n}};yn={start:Wv,end:Gv};Wf=async(s={},e={},t={},r={},n={})=>{var g,h,y;let{company:{companyId:o}={}}=s,{gridId:i,type:a}=e,l=s.browser||t.browserValue,c=Boolean(s.tunnel),{maxRetries:d,currentRetry:m}=n;if(!i||!a||(a===O.LAMBDATEST&&await((g=r.enableIfNeeded)==null?void 0:g.call(r,e)),a!==O.HYBRID||!o||!l||!d||!m))return e;let u=await Qc({companyId:o,gridId:i,maxRetries:d,currentRetry:m,browser:l,usingTunnel:c});Qe.info("handling hybrid grid",{response:u,companyId:o});let f=ri({...e,...u.connectionDetails,provider:u.provider});return u.provider!=="lambdatest"&&((h=r.disable)==null||h.call(r)),u.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,f)),f}});async function Yl(s,e,t){let r=cs[s];if(!r)return;let{slotId:n}=r;if(delete cs[s],!n){ot.warn("failed to find slot slot id",{companyId:e,workerId:s});return}ot.info("release slot id",{companyId:e,slotId:n});try{await yl(e,t,n)}catch(o){ot.error("failed to release slot",{companyId:e,err:o})}}async function zv(s,e){let t=Object.values(cs).filter(Boolean);if(t.length!==0){ot.info("keep alive worker slots",{companyId:s,slots:t});try{await Tl(s,e,t)}catch(r){ot.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function Kv(s,e){Vf=global.setInterval(()=>zv(s,e),1e4)}async function Jv(s,e){let t=Object.keys(cs);if(t.length){ot.warn("not all slots released before end runner flow",{companyId:s});try{await ie(t,r=>Yl(Number(r),s,e))}catch(r){ot.error("failed to release all slots",{err:r,companyId:s})}}}async function Yv(s,e){await Jv(s,e),clearInterval(Vf)}async function Hf(s,e,t){let r;try{r=await hl(s,e)}catch(n){throw ot.error("failed to get slot",{companyId:s,err:n}),new Error(ft.UNKNOWN)}if(ot.info("get slot info",Object.assign({},r,{companyId:s})),!r||!["success","error"].includes(r.status))throw ot.error("invalid response - get slot",{res:r}),new Error(ft.UNKNOWN);if(r.status==="success")return Gf(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new ze(ft.NOT_FOUND):r.code==="no-available-slot"?new Jt("Failed to run test - concurrency limit reached"):(ot.error("invalid code error response - get slot",{res:r}),new ze(ft.UNKNOWN))}async function qf(s,e,t,r){let n=cs[r];if(!n)throw new Error("slot not found");Object.assign(n,t),Gf(r,n),await bl(s,e,n),ot.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var ot,cs,Vf,Gf,Tn,ls=T(()=>{"use strict";ye();j();B();ae();q();ot=x("slot-service"),cs={},Vf=null,Gf=(s,e)=>{cs[s]=e};Tn={start:Kv,end:Yv}});function vn(){return si||"master"}function zf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){si="master";return}if(s!=null&&s.isArchived)throw new C(`Branch ${s.branch} is archived, run aborted.`);if(s){si=s.branch||s;return}si=e?"master":void 0}var si,Xl=T(()=>{"use strict";q()});var En,Ql,Xv,Zl,Qv,ni,oi,ii,ai,ci,li=T(()=>{"use strict";B();ae();En=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===pe.FAILED},Ql=s=>{let{status:e}=s;return e===pe.ABORTED},Xv=s=>{let{status:e}=s;return e===pe.PASSED},Zl=s=>s.runnerStatus===cc.SKIPPED,Qv=s=>s.testStatus===Ye.EVALUATING,ni=(s,e)=>Object.values(s).filter(t=>{var r,n;return Zl(t)&&(Xe(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,oi=s=>Object.values(s).filter(e=>En(e)&&Qv(e)).length,ii=s=>Object.values(s).filter(En),ai=s=>Object.values(s).filter(Xv),ci=s=>Object.values(s).filter(Ql)});function eE(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var eu,ui,Zv,pi,Jf=T(()=>{"use strict";eu=v(require("lodash"));j();li();ui=x("debug-reporter"),Zv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],pi=class{constructor(e){this.options=e}onTestStarted(e,t){ui.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,o=r.host,i=r.gridId,a=r.type,l=r.failedGetBrowserAttempts;ui.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:o,failedGetBrowserAttempts:l,id:i,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...eu.default.omit(this.options,Zv),company:eu.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,o,i,a){let l=eE(process.argv);ui.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:this.sanitizedOptionsForLogging,args:l})}onTestPlanFinished(e,t,r,n,o){let i=ai(e).length,a=Object.keys(e).length-i;ui.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:o,passed:i,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var tu,kt,Sn=T(()=>{"use strict";ae();tu=class{constructor(){this._planType="free"}setPlanType(e){this._planType=e}get isTestStatusEnabled(){return["pro","trial"].includes(this._planType)}shouldShowFreeGridRunWarning(e){return this._planType!=="pro"&&e===O.DEVICE_FARM}},kt=new tu});var su={};V(su,{Reporter:()=>tE});var sr,In,Rr,di,Yf,ru,tE,nu=T(()=>{"use strict";sr=v(require("chalk")),In=v(require("lodash"));B();ae();Sn();li();Rr={success:sr.default.green,warn:sr.default.yellow,error:sr.default.red},{CLI_MODE:di}=Ut,Yf="device",ru=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t){let r=`(${e.testId})`,n=`url: ${sr.default.underline(qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?pe.PASSED:pe.FAILED,n=`(${e.testId})`,o=Rr[e.success?"success":"error"];console.log(o(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${uo(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=qe(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(Rr.error("Failed runs are:")),console.log(Rr.error(t.join(`
|
|
22
|
-
\r`)))}onTestPlanFinished(e,t,r,n,o){let i=ii(e),a=ai(e),l=ci(e),c=a.length,d=l.length,m=i.length,u="",f="";if(kt.isTestStatusEnabled){let I=oi(e);u=` FAILED-EVALUATING: ${I}`,m-=I,f=` SKIPPED: ${ni(e,this.options)}`}let g=this.buildTestPlanName(o,t),h,y=Rr[m?"error":"success"],E=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${uo(r)}`;g.trim()===""||g.trim()==="Anonymous"?h=`Tests completed. ${E} (Execution ID: ${n})`:h=`Test plan${g} completed ${E} (${n})`,this.printWorkerDivider(),console.log(y(h)),this.printWorkerDivider(),this.printAllFailedTests(i)}buildTestPlanName(e,t){let r=In.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=In.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,o=In.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,i=In.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[o,n,r,i].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,o,i,a){let l=u=>{u.forEach((f,g)=>{var E;let h=(E=f.testData)!=null&&E.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`;console.log(" ",g+1,":",`${f.name}${Xe(f,this.options)?"-quarantine":""}`,y,h)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${m} (${o})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===di.APPIUM?Yf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${sr.default.underline(n)} slot from ${sr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===di.APPIUM?Yf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${sr.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,o=this.options.mode===di.APPIUM?"device":"browser";if(n)console.log(Rr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${o} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(Rr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===di.APPIUM?"Appium":"Selenium";console.log(Rr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},tE=ru});var au={};V(au,{Reporter:()=>aE});function rE(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function sE(s){return s.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${s.visitedUrlsList||""}`}function nE(s){return`${s.visitedUrlsJson||""}`}async function oE(s,e,t,r,n,o){function i(u){let f=qe(s,t,u.testId,u.resultId,r),g={$:{name:rE(u),classname:n,time:gc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(En(u)||Ql(u)){let h=`Step Failed: ${u.failureReason||u.reason}`,y=En(u)?`${h} More info at: ${f}`:h;g.failure={$:{message:y}}}return Zl(u)&&Xe(u,o)&&kt.isTestStatusEnabled&&(g.skipped={}),o.urls&&(g["visited-urls-list"]=sE(u),g["visited-urls-json"]=nE(u)),g}function a(u){let{results:f,testPlanName:g,configName:h}=u,y=f||{},I={name:(h&&g?`${g} with config '${h}'`:g)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(kt.isTestStatusEnabled){I.skipped=ni(y,o);let b=oi(y);I.failures-=b,I["failure-evaluating"]=b}return{$:I,testcase:Object.keys(y).map(b=>i(y[b]))}}function l(u){let f=Object.keys(u).map(h=>u[h].startTime),g=Math.min.apply(null,f);return g?new Date(g).toISOString():new Date().toISOString()}function c(u){return Object.keys(u).length}function d(u){return ii(u).length+ci(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new iu.Builder().buildObject(m)}catch(u){return iE(u)}}function iE(s){let e=new iu.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:s.message}}}}}};return e.buildObject(t)}var iu,Xf,ou,aE,cu=T(()=>{"use strict";iu=v(require("xml2js"));B();Xf=require("fs");Sn();li();ou=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,r=this.options.project,n=await oE(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Xf.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(o){return console.error("could not save report file",t,o),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};aE=ou});var Qf={};V(Qf,{Reporter:()=>cE});function us(s){return s?s.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var lu,uu,cE,Zf=T(()=>{"use strict";j();lu=x("team-city-reporter");uu=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${r}`;return us(n)}onTestStarted(e,t,r,n){if(r){lu.debug("skip report test started because is rerun");return}let o=this.getPrintName(e);console.log(`##teamcity[testStarted name='${o}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,o,i){if(o){lu.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${us(t)}' details='${us(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){lu.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${us(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${us(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${us(t)}']`)}},cE=uu});var eg={};V(eg,{Reporter:()=>lE});var pu,lE,tg=T(()=>{"use strict";pu=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,n,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},lE=pu});var rg={};V(rg,{Reporter:()=>uE});var du,uE,sg=T(()=>{"use strict";B();Pl();du=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Vo(t)}},uE=du});var IA,mu,Q,Ot=T(()=>{"use strict";Jf();j();IA=x("reporter"),mu=class{constructor(){this.reporters=[];this.onGetBrowserFailure=this.generateHook("onGetBrowserFailure");this.onGetBrowserSuccess=this.generateHook("onGetBrowserSuccess");this.onTestPlanStarted=this.generateHook("onTestPlanStarted");this.onGetSlot=this.generateHook("onGetSlot");this.onGetSession=this.generateHook("onGetSession");this.onTestFinished=this.generateHook("onTestFinished");this.onTestFailed=this.generateHook("onTestFailed");this.onTestPassed=this.generateHook("onTestPassed");this.onTestStarted=this.generateHook("onTestStarted");this.onTestIgnored=this.generateHook("onTestIgnored");this.onWaitToTestStart=this.generateHook("onWaitToTestStart");this.onWaitToTestComplete=this.generateHook("onWaitToTestComplete");this.onTestPlanFinished=this.generateHook("onTestPlanFinished",this.onTestPlanFinishedMutator);this.onAllTestPlansFinished=this.generateHook("onAllTestPlansFinished",this.onAllTestPlansFinishedMutator)}async setOptions(e,t){this.reporters=[];let r=e.reporters;if(this.reporters.push(new pi(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(nu(),su));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(cu(),au));this.reporters.push(new o(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Zf(),Qf)),r.includes("console")&&Promise.resolve().then(()=>(nu(),su)),r.includes("junit")&&Promise.resolve().then(()=>(cu(),au)),r.includes("json")&&Promise.resolve().then(()=>(tg(),eg)),r.includes("chrome")&&Promise.resolve().then(()=>(sg(),rg))])).forEach(o=>{o&&this.reporters.push(new o.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,o){let i={};i=e;let a=Date.now()-(r||0);return[i,t,a,n,o]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var o;let n=t==null?void 0:t(...r);for(let i of this.reporters)await((o=i[e])==null?void 0:o.call(i,...n||r))}}},Q=new mu});function og(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function ig({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:l,source:c,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:g,gridType:h}){let y=og({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:l,source:ng(c,d),isStartUp:u,projectType:f,gridType:h,...["android","ios"].includes(f)&&g&&{appSource:g}},m);ht("test-run-ci",y)}function ag({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:o,companyId:i,companyName:a,projectName:l,companyPlan:c,source:d,user:m,lightweightMode:u,logger:f,isStartUp:g,projectType:h,appSource:y,gridType:E}){try{let I=og({executionId:s,projectId:e,testId:t,resultId:r,ucid:o,companyId:i,companyName:a,projectName:l,companyPlan:c,mockNetworkEnabled:n.wasMockNetworkActivated,source:ng(d,m),isStartUp:g,projectType:h,gridType:E,...["android","ios"].includes(h)&&y&&{appSource:y}},u);if(n.success){ht("test-run-ci-success",I);return}ht("test-run-ci-fail",Object.assign({},I,{failureReason:n.failureReason}))}catch(I){f.error("failed to update test end analytics",{err:I})}}function cg(s){ht("batch-run-ci",s)}var ng,fu=T(()=>{"use strict";ss();Oo();ng=(s,e)=>s!=="cli"&&s!=="cli-local"?s:es&&e?"ci-with-user":es?"ci":e?"cli-with-user":s});var ug,mi,pg=T(()=>{"use strict";ug=require("istanbul-lib-report"),mi=class extends ug.ReportBase{constructor(t){super();t||={},this.appendToObject=t.appendToObject||{}}onStart(t){let r=t.getCoverageSummary(!1);this.appendToObject=Object.assign(this.appendToObject,r.toJSON())}}});var dg,mg,fg,Rn,yt,gg,fi,gu,hg,pE,yg,bg,dE,mE,Tg,fE,gE,hE,yE,bE,wg,vg=T(()=>{"use strict";dg=v(require("ora")),mg=v(require("dayjs")),fg=v(require("test-exclude")),Rn=v(require("fs")),yt=v(require("path")),gg=v(require("istanbul-reports")),fi=v(require("istanbul-lib-report"));ye();q();B();j();Ir();pg();gu=x("test-run-status"),hg=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},pE=s=>!!hg(s).search,yg=s=>s?hg(s).pathname.substring(1):"",bg=(s,e)=>{let t=yg(e);return!new fg.default({relativePath:!1,include:s}).shouldInstrument(t)},dE=s=>s.substring(0,s.indexOf("?")),mE=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await Se("convert-source-map");if(t==="file"&&!e)throw new C("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Tg=(s,e)=>`${yt.resolve(s,yg(e))}.js`,fE=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ie(Object.values(t),async n=>{if(!n)return;let o=n.toObject();await ie(o.sources,async(i,a)=>{if(bg(r,i))return;let l=Tg(e,i);await Rn.promises.mkdir(yt.parse(l).dir,{recursive:!0}),await Rn.promises.writeFile(l,o.sourcesContent[a])})})},gE={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(pE(e)&&(e=dE(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=yt.dirname(this.getPath(s));return yt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},hE=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=fi.createContext({dir:t,coverageMap:e,watermarks:fi.getDefaultWatermarks(),sourceFinder:a=>{try{let l=Tg(r,a);return Rn.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new mi({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:gE}),gg.create(a,l).execute(i)}),o},yE=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let i=(await Se("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>bg(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()},bE=async(s,e)=>{let{mergeProcessCovs:r}=await Se("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await nl(s,"testResult",`runId=${e}`)).data.docs;return await ie(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await an(l,9e4);await ie(c,async d=>{if(!o.has(d.url)){let m=d.text;d.sourceUrl&&(o.set(d.url,"TEMP"),m=await Bc(d.sourceUrl)),o.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:o,mergedCoverages:n}},wg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;gu.info("start js coverage process");let n=(0,dg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=yt.resolve(s.codeCoverageReportPath||"./coverage"),i=yt.resolve(o,`.js/${(0,mg.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?yt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([Se("istanbul-lib-coverage"),bE(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}gu.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await ie(c.result,async({url:g,functions:h})=>{let{text:y,sourceMapType:E}=d.get(g),I=await mE({sourceMapType:E,source:y,sourceMapDir:a});u[g]=I;let b=await yE(s,{source:y,sourceMap:I,functions:h});m.merge(b)}),await fE(s,i,u);let f=await hE(s,m,o,i);return n.succeed(),f}catch(l){let c="Failed to report coverage information";l instanceof C?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),gu.error(c,{err:l})}}});var Eg={};V(Eg,{SELENIUM_PERF_MARKS:()=>Ce,SeleniumPerfStats:()=>xr});var Ce,TE,xr,ps=T(()=>{"use strict";B();Ce={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},TE=["ALL",...Object.values(Ce)],xr=class{constructor(){this.marks=Object.fromEntries(TE.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=re();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,fo(r,50)],[`${t}_P95`,fo(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var xg={};V(xg,{initServer:()=>EE,mapFilesToLocalDrive:()=>yu});function yu(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,gi[t.id]?{screenshot:gi[t.id]}:{})),Object.keys(hi).forEach(t=>{s.assets||={},s.assets[Rg[t]]=hi[t]}),s.assets||={},s.assets.screenshots=Object.values(gi)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function EE({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await Se("multer"),n=typeof t=="string"?t:wE;await hu.promises.mkdir(n,{recursive:!0});let o=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=xn.join(n,m.testResultId);try{await hu.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(l,c,d){let{fileName:m}=l.body,u=JSON.parse(l.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=xn.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),i=(0,Ig.default)();i.post("/",o.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(gi[d.stepId]=l.file.path),d.testResultId&&vE.includes(d.subType)&&(hi[d.subType]||=[],hi[d.subType].push(l.file.path)),c.sendStatus(200)}),i.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(i);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new C(`Port ${s} is already in use`));default:return c(u)}}})}var hu,Sg,xn,Ig,wE,gi,hi,Rg,vE,bu=T(()=>{"use strict";hu=v(require("fs")),Sg=v(require("os")),xn=v(require("path")),Ig=v(require("express"));q();Ir();wE=xn.join(Sg.tmpdir(),"testim/rca/"),gi={},hi={},Rg={"test-log":"consoleLogs","har-file":"networkLogs"},vE=Object.keys(Rg)});var nr,Tu,yi,Ag=T(()=>{"use strict";nr=v(require("lodash"));B();j();Tu=x("override-test-data-builder"),yi=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return nr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!nr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Tu.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(nr.isObject(e.overrideAllTestsData)&&!nr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Tu.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:r}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}Tu.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return nr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let o=r.map(d=>this.generateTestUniqId(d)),i=o.indexOf(n),a=o.lastIndexOf(n),l=r[i],c=this.createNewTestItems(l,t);return r.splice(i,a-i+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let o=re();return Object.assign({},e,{resultId:o,testData:{value:r,index:n+1,total:t.length||1}})})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function bi(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Ze.warn("failed to run hook",{err:t}),new C(`failed to run hook promise ${t.message}`)}}var Ar,Ze,SE,IE,RE,xE,Ti,Cg=T(()=>{"use strict";Ar=v(require("lodash"));B();ae();as();ls();ye();q();j();Ot();un();vg();ps();bu();le();fe();Ag();Sn();Ze=x("test-run-status"),SE=yr(),IE=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,RE=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,xE=dt();Ti=class{constructor(e,t,r,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new xr;var a,l,c,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let o=qs(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:to||t.parallel||1,browser:o,gitBranch:SE,gitCommit:IE,gitRepoUrl:RE,runnerVersion:xE,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:i,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:g,testOwnerEmail:h,testLabels:y,testSuites:E,allLabels:I}=a,b={originalTestResultId:t,previousTestResultId:r,config:Ar.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:i,testStatus:m};return this.testRunStatus[e]=Object.assign({},b,{testCreatorName:u,testCreatorEmail:f,testOwnerName:g,testOwnerEmail:h,testLabels:y,testSuites:E,allLabels:I}),cl({projectId:n,runId:o,testId:c,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let o=this.getTestResult(r);return o.workerId=e,Q.onTestStarted(o,e,n,r),o}async updateTestStatusRunning(e,t,r){var c;let{project:n,remoteRunId:o,projectData:i}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Mo(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(d){Ze.error("failed to upload test data artifact (runner)",{err:d})}let l=Ar.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,Er(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(Xe(e,this.options))return;let n=this.exportsGlobal;try{let o=await bi(this.options.beforeTest,Object.assign({},e,{exportsGlobal:n,globalParameters:n}),this.options.userData.loginData.token);return e.config.testData=Object.assign({},e.config.testData,this.exportsGlobal,this.fileUserParamsData,this.beforeSuiteParams,o),this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(o){throw Ze.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,r,n,o){let i=this.testStart(e,t,r,n);return this.testStartReport(i,t,o)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo=Object.assign({},t,{key:void 0,user:void 0}),Ze.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:o,testId:i,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Ye.EVALUATING&&kt.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Ye.EVALUATING} status`);return}if(c){Q.onTestPassed(o);return}Q.onTestFailed(r,r.failureReason,qe(this.options.editorUrl,this.options.project,i,l,this.branchToUse),i,n,l)}calcResultText(e){return e.success?pe.PASSED:pe.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Ye.QUARANTINE}`)}monitorMemoryUsage(e){let t=hc();if(t.isOverThreshold){let r=M.flags.useLinkedomToParseHtml.isEnabled()?"linkedom":"jsdom";Ze.info(`using ${r} to parse html`,{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}}testEnd(e,t,r,n,o){let i=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;i.sessionId=n,i.startTime=t.startTime||i.startTime||Date.now(),i.duration=a,t.duration=a,i.failureReason=t.failureReason||t.reason,t.failureReason=i.failureReason,i.failurePath=t.failurePath,i.resultId=t.resultId,i.success=t.success,this.options.saveRCALocally&&yu(i,Ze),i.resultUrl=qe(this.options.editorUrl,this.options.project,i.testId,i.resultId,this.branchToUse),i.status=this.calcResultText(t),t.status=i.status,t.name=i.name,t.testStatus=i.testStatus,t.testId||=i.testId,t.testCreatorName=i.testCreatorName,t.testCreatorEmail=i.testCreatorEmail,t.testOwnerName=i.testOwnerName,t.testOwnerEmail=i.testOwnerEmail,t.testData=i.config&&typeof i.config.testDataTotal=="number"?{total:i.config.testDataTotal,index:i.config.testDataIndex}:{},this.reportTestStatus(e,t,i,o),this.monitorMemoryUsage(i),Q.onTestFinished(i,e,o);let l=Object.assign({},this.exportsGlobal,t.exportsGlobal);return this.exportsGlobal=l,i}async testEndReport(e,t,r,n){var i;let o=r.exportsGlobal;try{try{await bi(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){Ze.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(i=this.options.lightweightMode)!=null&&i.onlyTestIdsNoSuite?void 0:await Er(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw Ze.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,o,i){let a=this.testEnd(e,t,r,n,o);return this.testEndReport(a,r,t,i)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:o,VIRTUAL_BUILD:i}=pc;return e&&(n=o),Gr(t,r)&&(n=i),n}calcTestRunStatus(){var i;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(i=e.gridData)==null?void 0:i.type,o=t.map(a=>{var f,g,h;let l=e.browser?Ys(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=Hr(M,n)&&Ks(a.nativeApp)&&!e.appId,d=Js(e)&&(Gr(a.nativeApp,n)||c),m=Xe(a,e)||d,u={testId:a.testId,status:m?pe.SKIPPED:pe.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Ye.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(c,a.nativeApp,n)},config:Object.assign({},this.execConfig,{companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((g=a.testData)==null?void 0:g.total)||null,testDataIndex:((h=a.testData)==null?void 0:h.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:l.browserValue.toLowerCase()})};return[a.resultId,u]});return Object.fromEntries(o)}async endKeepAlive(e,t,r){e==="redis"&&await Tn.end(r,t),e==="mongo"&&await yn.end(t)}async executionStart(e,t,r,n,o){Ze.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=i;rs(()=>Promise.all([this.endKeepAlive(d,t,c),_o("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,...M.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},u=await bi(i.beforeSuite,m),f=new yi(u,Ar.cloneDeep(this.testInfoList),t);this.testInfoList=f.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:g}=this,h=[],y=[],E=[];for(let b of g){if(b.isBeforeTestPlan){h.push(b);continue}if(b.isAfterTestPlan){E.push(b);continue}y.push(b)}let I=async()=>{let b=Ar.cloneDeep(this.testRunStatus);await ie(Object.keys(b),async _=>{var U;let $=b[_],S=(U=$.config)==null?void 0:U.testData,A=$.testId,L=await Mo(t,A,_,S,l.defaults);L&&(delete $.config.testData,$.config.testDataUrl=L)});let w=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),R={executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:w,intersections:i.intersections},k=Gc(R);return this.executionStartedPromise=k,k.catch(_=>Ze.error(_)),k};try{await I()}catch(b){Ze.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:h,tests:y,afterTests:E}}concatSeleniumPerfMarks(e){Ar.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var d;let t=bc(this.testRunStatus),r=t.length,n=0,o=0,i=0;for(let{status:m,testStatus:u}of t)m===pe.PASSED&&n++,m===pe.SKIPPED&&o++,m===pe.FAILED&&u===Ye.EVALUATING&&i++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await bi(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:o})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Ze.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let c=await wg(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await _o("FINISHED",e,this.options.project,r===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw Ze.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await Vc(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function CE(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Iu(s){return Og.readFileSync(s,{encoding:"base64"})}function Mg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&We(s))&&s){let r=Iu(s);ds.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${Su(r)} current extension count: ${e.length}`),e.push(r)}}function Ng(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;if(s.ext||r){let l=typeof s.ext=="string"?s.ext:`${__dirname}/..`,c=r||l,d=`--load-extension=${c}`;ds.info(`adding extension: testim unpacked , path: ${c}`),t.push(d);return}let o=s.canary?"-master.zip":".zip",i=Eu.join(process.cwd(),`testim-headless${o}`),a=Iu(i);ds.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${Su(a)} current extension count: ${e.length}`),e.push(a)}function PE(s,e,t,r,n,o,i){var g,h;let a=t.seleniumName||t.browserValue,l=[],c=[...Dg];e.headless&&c.push("--headless");let d={prefs:{"profile.default_content_setting_values.popups":wu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":wu.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1},w3c:!0};vu(n)&&(d.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),vu(n)&&a==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(d.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(y=>c.push(`--${y}`)),e.chromeBlockLocation&&(d.prefs["profile.default_content_setting_values.geolocation"]=wu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&c.push(`--user-data-dir=${e.chromeUserDataDir}`),(h=(g=e.projectData)==null?void 0:g.defaults)!=null&&h.disableChromiumGpu&&c.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:a});function m(){t.mobileEmulation&&(d.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+lc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}m(),Mg(r,l,i),e.mode===Y.EXTENSION&&Ng(e,l,c,o,i),l.length>0&&(d.extensions=l),e.disableCookiesSameSiteNoneRequiresSecure&&(d.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),d.args=c;let u={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],f={MicrosoftEdge:"ms",chrome:"goog"}[a];return te.isLambdatestGrid(n)&&delete d.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(s.desiredCapabilities[u]=d),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${f}:${u}`]=d),s}function OE(s,e,t){let r={"pdfjs.disabled":!0};if(M.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":kg.join(","),"browser.helperApps.neverAsk.openFile":kg.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.mode===Y.EXTENSION)if(e.ext)s.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=Eu.join(process.cwd(),`testim-firefox-profile${n}`);s.desiredCapabilities.firefox_profile=Iu(o)}return e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function _E(s){return`${s.width}x${s.height}`}function LE(s,e,t,r){let{saucelabs:n}=s;if(n!=null&&n.browserVersion&&(n.version=n.browserVersion),n!=null&&n.username&&n.accessKey){let o={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=n.appiumVersion||t.sl.appiumVersion;let i=(0,Lg.cloneDeep)(t.sl);return(r!=null&&r.resolution||t.sl.screenResolution)&&(o["sauce:options"].screenResolution=_E(r.resolution||t.sl.screenResolution),delete i.screenResolution),it.merge(i,o,n)}return it.merge(o,n)}return{}}function DE(s,e,t){return it.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),Object.assign({},t.bs,s.browserstack,{name:e})):Object.assign({},s.browserstack,{name:e})}function ME(s){return s.perfecto?s.perfecto:{}}function NE(s,e,t){if(s.experitestToken){let r=e==="safari";return{accessKey:s.experitestToken,browserVersion:"latest",platformName:r?"MAC":"WIN10",seleniumScreenshot:r,newSessionWaitTimeout:t}}return{}}function UE(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,o=r||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=Da(o,i)),a}function wi(s){var E;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,lambdatestService:c}=s;if(o.mode==="local"){let I=[],b=[...Dg],w={};return t.headless&&b.push("--headless"),t.silentDebuggerExtensionApi&&b.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&b.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach(R=>b.push(`--${R}`)),t.chromeBinaryLocation&&(w.binary=t.chromeBinaryLocation),t.mode!=="selenium"&&Ng(t,I,b,null,c),Mg(i,I,c),{logLevel:Pg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:b,extensions:I,...w},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:d,driverRequestRetries:m}=t,u=UE(t,o),f={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:Pg,connectionRetryTimeout:d,connectionRetryCount:m,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!it.isEmpty(u)&&{headers:u},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};vu(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,f.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(f.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key);let g=Number(t.browserTimeout/1e3),h=t.browser||(n==null?void 0:n.browserValue);it.merge(f.desiredCapabilities,LE(t,r,n,e),DE(t,r,n),ME(t),NE(t,h,g),c==null?void 0:c.getCapabilities(t,h,a,l,r,e));let y=null;switch(!t.ext&&!t.extensionPath&&((E=o.host)!=null&&E.endsWith(".testim.io"))&&!t.canary&&t.mode===Y.EXTENSION&&(y="/opt/testim-headless"),h){case"chrome":case"edge-chromium":f=kE(f,t,n,i,o,y,c);break;case"firefox":f=OE(f,t,c);break;case"safari":case"safari technology preview":f=CE(f,h);break;default:break}it.merge(f.desiredCapabilities,t.seleniumCapsFileContent);try{let I={"hub.lambdatest.com":"lambdatest",[M.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},b=_=>_[o.provider]||_[f.host]||_[I[f.host]],w=_=>{var $,S;return b(_)||_[($=f.desiredCapabilities)==null?void 0:$.browserName]||_[(S=f.desiredCapabilities)==null?void 0:S.version]||_||{}},R=JSON.parse(M.flags.addCustomCapabilities.getValue()||"{}"),k=w(w(R));Object.keys(k).length&&(ds.info(`Adding custom capabilities: ${JSON.stringify(k)}`),Object.assign(f.desiredCapabilities,k))}catch(I){ds.error("Failed to load custom capabilities",{error:I,customCapabilities:M.flags.addCustomCapabilities.getValue()})}return f.desiredCapabilities&&!f.capabilities&&(AE(f),f.capabilities={alwaysMatch:f.desiredCapabilities,firstMatch:[{}]},delete f.desiredCapabilities),f.hostname=f.host,f}var Og,Eu,_g,it,Lg,ds,Pg,wu,Dg,Su,vu,AE,kE,kg,Ru=T(()=>{"use strict";Og=v(require("fs")),Eu=v(require("path")),_g=v(require("crypto")),it=v(require("lodash"));B();le();j();fe();ae();Xo();Lg=require("lodash"),ds=x("testim-desired-capabilities-builder"),Pg=eo?"debug":"silent",wu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Dg=["--disable-popup-blocking","--ignore-gpu-blacklist","--auto-select-desktop-capture-source=Entire screen","--ignore-certificate-errors","--disable-features=TranslateUI","--disable-background-networking","--disable-sync","--metrics-recording-only","--disable-default-apps","--mute-audio","--no-first-run","--disable-back-forward-cache"],Su=(...s)=>_g.createHash("sha256").update(s.join("")).digest("hex"),vu=s=>s.type===O.DEVICE_FARM||s.type===O.HYBRID&&s.provider==="devicefarm",AE=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=M.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(o=>{delete e[o]})}catch{ds.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};kE=it.memoize(PE,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(it.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return Su(i,a,l,r,c,o)}),kg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Ue(s){var e,t,r,n,o,i,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=s.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function Fg(s,e,t){if(!e||!s)return s;if(s.includes("%"))return s.replace(/ /g,"%20");try{return decodeURI(s)!==s?s:encodeURI(s)}catch(r){return t&&t.warn("tried to encode url but failed",{err:r,url:s}),s}}var xu=T(()=>{"use strict"});function Au(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let g=u;g&&g!==u.ownerDocument;g=g.parentNode)if(f(g))return g;return null}function n(u,f){for(let g=u;g&&g!==u.ownerDocument;g=t(g))if(f(g))return g;return null}function o(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let h=window.getComputedStyle(u).getPropertyValue(f);if(h&&h!=="inherit")return h;let y=t(u);return o(y,f)}function i(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let h=o(u,"stroke-width");return!!h&&parseInt(h,10)>0}return o(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(h=>h.nodeType===Node.TEXT_NODE?!0:e(h)?i(h):!1)}function a(u){return o(u,"overflow")==="hidden"}function l(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!i(f)?!0:l(f))}function c(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:c(u.parentNode):!1}if(!s||!c(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,g=>g.tagName.toUpperCase()==="SELECT");return Au(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(o(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(o(u,"opacity"))===0),m=!!n(s,u=>o(u,"display")==="none");return!(d||m||!i(s)||l(s))}var Bg=T(()=>{"use strict"});var jg,$g,Ht,FE,BE,vi,Wg=T(()=>{"use strict";jg=v(require("promise-queue")),$g=v(require("webdriverio"));le();$e();B();j();Mr();Bg();xu();ps();Ht=x("WebDriverApi"),FE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},BE={implicit:0,pageLoad:1,script:2},vi=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}async rejectWithLog(e,t){let{testName:r,testResultId:n}=this,o=t?t.toString().substr(0,2e3):"";throw Ht.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),Fa!==void 0&&(e=Fa);let t=1/0;this.queue=new jg.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(o){return this.rejectWithLog(o,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,i;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),N("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(Ce.GET_BROWSER);try{await this.addToQueue(async()=>{Ht.info("requesting browser",{testResultId:r,testName:t}),N("before this.client.init"),this.client=await $g.remote(e),this.logGridStatus(r)}),N("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,Ce.GET_BROWSER)}}async logGridStatus(e){var i;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",o;try{o=await this.client.status();for(let a of o.nodes||[])for(let l of a.slots||[])if(((i=l==null?void 0:l.session)==null?void 0:i.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){Ht.info("grid status is not supported by the grid",{testResultId:e});return}Ht.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Ht.info("grid status",{gridStatusMsg:o.message,ready:o.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},o=()=>this.client.execute(e,t).catch(n),i=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return o();t=t.map(a=>{if(a===null){Ht.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await i()}catch(a){if(Ue(a))return this.unsupportedActions.add("execute"),o();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),o=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await o()}catch(i){if(Ue(i))return this.unsupportedActions.add("executeAsync"),n();throw i}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Ce.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,Ce.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Ce.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Le(e)))}finally{this.seleniumPerfStats.markEnd(t,Ce.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(Au,{ELEMENT:e,[zt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Ue(n))return this.unsupportedActions.add("elementIdDisplayed"),r();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(Fg(e,this.isSafari(),Ht))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let r=()=>{let o=[];return o[BE[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(o){if(Ue(o))return this.unsupportedActions.add("timeouts"),n();throw o}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,o){window.scrollTo(n,o)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(Le(e)),await this.elementIdValue(Le(e),t)}async getViewportSize(e){let t=await this.execute(FE);if(typeof e=="string"&&e.match(/(width|height)/)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async keys(e){let t=i=>Object.hasOwn(_a,i)?[_a[i]]:i.split(""),r=[];if(typeof e=="string")r=t(e);else if(Array.isArray(e))for(let i of e)r=r.concat(t(i));else throw new Error("number or type of arguments don't agree with keys protocol command");let n=()=>{var i;return(i=this.client)==null?void 0:i.requestHandler.create("/session/:sessionId/keys",{value:r})},o=()=>{let i=r.map(l=>({type:"keyDown",value:l})),a=r.map(l=>({type:"keyUp",value:l}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};if(this.unsupportedActions.has("keys"))return o();try{return await this.addToQueue(()=>n())}catch(i){if(Ue(i))return this.unsupportedActions.add("keys"),o();throw i}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(Le(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let o=Math.abs(e.width),i=Math.abs(e.height);r=async()=>await this.client.setWindowSize(o,i),n=async()=>await this.client._setWindowSize(o,i)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(o){if(Ue(o))return this.unsupportedActions.add("windowHandleSize"),r();throw o}})}}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>{var l;return(l=this.client)==null?void 0:l.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){Ht.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return Ht.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var Vg={};V(Vg,{doubleClick:()=>jE});var jE,Gg=T(()=>{"use strict";jE=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(u){function f(I,b,w){return w>I&&w<b}let g=u.pointerPosition||{},h=r.getBoundingClientRect(),y=g.originX&&f(h.left,h.left+h.width,g.originX)?g.originX:h.left+h.width/2,E=g.originY&&f(h.top,h.top+h.height,g.originY)?g.originY:h.top+h.height/2;return{x:y,y:E}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,f,g){if(!window.PointerEvent)return;let h=a(f,g);return new window.PointerEvent(u,h)},c=function(u,f,g){let h=document.createEvent("MouseEvents");return h.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,g,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),h},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=i(u),g=u.event;return t.includes(g)?l(g,f.x,f.y):c(g,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var An={};V(An,{dispatchFocus:()=>$E});function $E(s,e){function t(o){let i=document.createEvent("HTMLEvents");return i.initEvent(o,!0,!1),i}function r(){var i;let o=document.activeElement;for(;(i=o.shadowRoot)!=null&&i.activeElement;)o=o.shadowRoot.activeElement;return o}function n(o,i){i&&(i.dispatchEvent(t("focusout")),i.dispatchEvent(t("blur"))),o.dispatchEvent(t("focusin")),o.dispatchEvent(t("focus")),typeof o.focus=="function"&&o.focus();let a=r();i&&a===i&&typeof i.blur=="function"&&i.blur()}if(s){let o=getLocatedElement(s);if(o&&o!==e)try{n(o,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var Cn=T(()=>{"use strict"});var Jg={};V(Jg,{WebDriver:()=>Pr});async function HE(s){var e,t;try{let r=(t=(e=s==null?void 0:s.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return r?await VE(r):void 0}catch(r){Be.info("Error getting cdpAddress",r);return}}var ms,zg,Kg,Be,or,WE,Hg,VE,ir,GE,qg,Cr,Pr,Pn=T(()=>{"use strict";ms=v(require("lodash"));B();$e();Ru();zg=v(require("p-retry")),Kg=v(require("ua-parser-js"));Mr();j();xu();Wg();q();fe();ps();Be=x("webdriver"),[or,WE]=[0,2],{extractElementId:Hg,getCdpAddressForHost:VE}=K,ir=()=>(Te(),he(tr)).getSessionPlayer().codeSnippets,GE=()=>(Te(),he(tr)).getSessionPlayer().locatorBuilderUtils,qg=()=>(Te(),he(tr)).getSessionPlayer().utils,Cr=()=>(Te(),he(tr)).getSessionPlayer().positionUtils;Pr=class extends vi{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var E,I,b,w,R,k,_,$;let{overrideConfiguration:r,browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((b=(I=(E=n==null?void 0:n.company)==null?void 0:E.activePlan)==null?void 0:I.premiumFeatures)==null?void 0:b.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let g=wi({browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r});g.desiredCapabilities&&delete g.desiredCapabilities.marionette,g.capabilities&&delete g.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let h=u?0:1500,y=u?()=>null:()=>this.executeJS("window.focus()");try{N("before initClient in webdriver.js init");let S=await this.initClient(g,o,d);N("after initResult before getCdpAddress in init"),this.cdpUrl=await HE(S),N("after getCdpAddress in webdriver.js init"),Be.info(`init new session testName: ${o}`,{sessionId:this.getSessionId(),testResultId:d}),await oe(h),M.flags.dontFocusOnInit.isEnabled()||await y(),N("after focus and delay in webdriver.js init")}catch(S){let A=JSON.stringify(ms.omit(g,"capabilities.extensions","capabilities.capabilities.extensions"));Be.error("failed to init webdriver",{err:S,capabilitiesAsString:A});let L=((R=(w=n==null?void 0:n.company)==null?void 0:w.activePlan)==null?void 0:R.plan)==="free";throw(k=S.stack)!=null&&k.includes("at startWebDriverSession")&&((_=S.message)!=null&&_.startsWith("Failed to create session"))&&(($=S.message)!=null&&$.includes("Timeout awaiting 'request'"))&&L?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):S.message.match(/Invalid username or password/)?new Br(S.message):S.message.match(/capabilit(y|ies)/)?new ro(S.message):new Error("failed to init client driver")}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>ms.zip(o.slice(0,-1),o.slice(1)),r=this._keepAliveRequests.map(({start:o})=>o).filter(Boolean),n=t(r).map(([o,i])=>i-o);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function o(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let i=re();r(i);try{await this.executeJS(o),this._isAlive=!0,n("end",i),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",i),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Be.warn("close unexpected alert open"),await this.alertAccept().catch(l=>Be.warn("failed to click on alert",{err:l}));return}if(Be.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;Be.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:l,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=l&&this.browserClosedCallbacks.forEach(c=>{try{c(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=Hg(r.value);return await this.switchToFrame({ELEMENT:n,[zt]:n}),r}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new so:r}}async getElement(t){var o;let r=this.seleniumPerfStats.markStart(Ce.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,Ce.GET_ELEMENT)}if(((o=t==null?void 0:t.shadowPath)==null?void 0:o.length)||M.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
22
|
+
\r`)))}onTestPlanFinished(e,t,r,n,o){let i=ii(e),a=ai(e),l=ci(e),c=a.length,d=l.length,m=i.length,u="",f="";if(kt.isTestStatusEnabled){let I=oi(e);u=` FAILED-EVALUATING: ${I}`,m-=I,f=` SKIPPED: ${ni(e,this.options)}`}let g=this.buildTestPlanName(o,t),h,y=Rr[m?"error":"success"],E=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${uo(r)}`;g.trim()===""||g.trim()==="Anonymous"?h=`Tests completed. ${E} (Execution ID: ${n})`:h=`Test plan${g} completed ${E} (${n})`,this.printWorkerDivider(),console.log(y(h)),this.printWorkerDivider(),this.printAllFailedTests(i)}buildTestPlanName(e,t){let r=In.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=In.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,o=In.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,i=In.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[o,n,r,i].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,o,i,a){let l=u=>{u.forEach((f,g)=>{var E;let h=(E=f.testData)!=null&&E.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`;console.log(" ",g+1,":",`${f.name}${Xe(f,this.options)?"-quarantine":""}`,y,h)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${m} (${o})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===di.APPIUM?Yf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${sr.default.underline(n)} slot from ${sr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===di.APPIUM?Yf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${sr.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,o=this.options.mode===di.APPIUM?"device":"browser";if(n)console.log(Rr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${o} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(Rr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===di.APPIUM?"Appium":"Selenium";console.log(Rr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},tE=ru});var au={};V(au,{Reporter:()=>aE});function rE(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function sE(s){return s.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${s.visitedUrlsList||""}`}function nE(s){return`${s.visitedUrlsJson||""}`}async function oE(s,e,t,r,n,o){function i(u){let f=qe(s,t,u.testId,u.resultId,r),g={$:{name:rE(u),classname:n,time:gc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(En(u)||Ql(u)){let h=`Step Failed: ${u.failureReason||u.reason}`,y=En(u)?`${h} More info at: ${f}`:h;g.failure={$:{message:y}}}return Zl(u)&&Xe(u,o)&&kt.isTestStatusEnabled&&(g.skipped={}),o.urls&&(g["visited-urls-list"]=sE(u),g["visited-urls-json"]=nE(u)),g}function a(u){let{results:f,testPlanName:g,configName:h}=u,y=f||{},I={name:(h&&g?`${g} with config '${h}'`:g)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(kt.isTestStatusEnabled){I.skipped=ni(y,o);let b=oi(y);I.failures-=b,I["failure-evaluating"]=b}return{$:I,testcase:Object.keys(y).map(b=>i(y[b]))}}function l(u){let f=Object.keys(u).map(h=>u[h].startTime),g=Math.min.apply(null,f);return g?new Date(g).toISOString():new Date().toISOString()}function c(u){return Object.keys(u).length}function d(u){return ii(u).length+ci(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new iu.Builder().buildObject(m)}catch(u){return iE(u)}}function iE(s){let e=new iu.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:s.message}}}}}};return e.buildObject(t)}var iu,Xf,ou,aE,cu=T(()=>{"use strict";iu=v(require("xml2js"));B();Xf=require("fs");Sn();li();ou=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,r=this.options.project,n=await oE(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Xf.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(o){return console.error("could not save report file",t,o),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};aE=ou});var Qf={};V(Qf,{Reporter:()=>cE});function us(s){return s?s.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var lu,uu,cE,Zf=T(()=>{"use strict";j();lu=x("team-city-reporter");uu=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${r}`;return us(n)}onTestStarted(e,t,r,n){if(r){lu.debug("skip report test started because is rerun");return}let o=this.getPrintName(e);console.log(`##teamcity[testStarted name='${o}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,o,i){if(o){lu.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${us(t)}' details='${us(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){lu.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${us(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${us(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${us(t)}']`)}},cE=uu});var eg={};V(eg,{Reporter:()=>lE});var pu,lE,tg=T(()=>{"use strict";pu=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,n,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},lE=pu});var rg={};V(rg,{Reporter:()=>uE});var du,uE,sg=T(()=>{"use strict";B();Pl();du=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Vo(t)}},uE=du});var RA,mu,Q,Ot=T(()=>{"use strict";Jf();j();RA=x("reporter"),mu=class{constructor(){this.reporters=[];this.onGetBrowserFailure=this.generateHook("onGetBrowserFailure");this.onGetBrowserSuccess=this.generateHook("onGetBrowserSuccess");this.onTestPlanStarted=this.generateHook("onTestPlanStarted");this.onGetSlot=this.generateHook("onGetSlot");this.onGetSession=this.generateHook("onGetSession");this.onTestFinished=this.generateHook("onTestFinished");this.onTestFailed=this.generateHook("onTestFailed");this.onTestPassed=this.generateHook("onTestPassed");this.onTestStarted=this.generateHook("onTestStarted");this.onTestIgnored=this.generateHook("onTestIgnored");this.onWaitToTestStart=this.generateHook("onWaitToTestStart");this.onWaitToTestComplete=this.generateHook("onWaitToTestComplete");this.onTestPlanFinished=this.generateHook("onTestPlanFinished",this.onTestPlanFinishedMutator);this.onAllTestPlansFinished=this.generateHook("onAllTestPlansFinished",this.onAllTestPlansFinishedMutator)}async setOptions(e,t){this.reporters=[];let r=e.reporters;if(this.reporters.push(new pi(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(nu(),su));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(cu(),au));this.reporters.push(new o(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Zf(),Qf)),r.includes("console")&&Promise.resolve().then(()=>(nu(),su)),r.includes("junit")&&Promise.resolve().then(()=>(cu(),au)),r.includes("json")&&Promise.resolve().then(()=>(tg(),eg)),r.includes("chrome")&&Promise.resolve().then(()=>(sg(),rg))])).forEach(o=>{o&&this.reporters.push(new o.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,o){let i={};i=e;let a=Date.now()-(r||0);return[i,t,a,n,o]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var o;let n=t==null?void 0:t(...r);for(let i of this.reporters)await((o=i[e])==null?void 0:o.call(i,...n||r))}}},Q=new mu});function og(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function ig({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:l,source:c,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:g,gridType:h}){let y=og({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:l,source:ng(c,d),isStartUp:u,projectType:f,gridType:h,...["android","ios"].includes(f)&&g&&{appSource:g}},m);ht("test-run-ci",y)}function ag({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:o,companyId:i,companyName:a,projectName:l,companyPlan:c,source:d,user:m,lightweightMode:u,logger:f,isStartUp:g,projectType:h,appSource:y,gridType:E}){try{let I=og({executionId:s,projectId:e,testId:t,resultId:r,ucid:o,companyId:i,companyName:a,projectName:l,companyPlan:c,mockNetworkEnabled:n.wasMockNetworkActivated,source:ng(d,m),isStartUp:g,projectType:h,gridType:E,...["android","ios"].includes(h)&&y&&{appSource:y}},u);if(n.success){ht("test-run-ci-success",I);return}ht("test-run-ci-fail",Object.assign({},I,{failureReason:n.failureReason}))}catch(I){f.error("failed to update test end analytics",{err:I})}}function cg(s){ht("batch-run-ci",s)}var ng,fu=T(()=>{"use strict";ss();Oo();ng=(s,e)=>s!=="cli"&&s!=="cli-local"?s:es&&e?"ci-with-user":es?"ci":e?"cli-with-user":s});var ug,mi,pg=T(()=>{"use strict";ug=require("istanbul-lib-report"),mi=class extends ug.ReportBase{constructor(t){super();t||={},this.appendToObject=t.appendToObject||{}}onStart(t){let r=t.getCoverageSummary(!1);this.appendToObject=Object.assign(this.appendToObject,r.toJSON())}}});var dg,mg,fg,Rn,yt,gg,fi,gu,hg,pE,yg,bg,dE,mE,Tg,fE,gE,hE,yE,bE,wg,vg=T(()=>{"use strict";dg=v(require("ora")),mg=v(require("dayjs")),fg=v(require("test-exclude")),Rn=v(require("fs")),yt=v(require("path")),gg=v(require("istanbul-reports")),fi=v(require("istanbul-lib-report"));ye();q();B();j();Ir();pg();gu=x("test-run-status"),hg=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},pE=s=>!!hg(s).search,yg=s=>s?hg(s).pathname.substring(1):"",bg=(s,e)=>{let t=yg(e);return!new fg.default({relativePath:!1,include:s}).shouldInstrument(t)},dE=s=>s.substring(0,s.indexOf("?")),mE=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await Se("convert-source-map");if(t==="file"&&!e)throw new C("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Tg=(s,e)=>`${yt.resolve(s,yg(e))}.js`,fE=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ie(Object.values(t),async n=>{if(!n)return;let o=n.toObject();await ie(o.sources,async(i,a)=>{if(bg(r,i))return;let l=Tg(e,i);await Rn.promises.mkdir(yt.parse(l).dir,{recursive:!0}),await Rn.promises.writeFile(l,o.sourcesContent[a])})})},gE={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(pE(e)&&(e=dE(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=yt.dirname(this.getPath(s));return yt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},hE=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=fi.createContext({dir:t,coverageMap:e,watermarks:fi.getDefaultWatermarks(),sourceFinder:a=>{try{let l=Tg(r,a);return Rn.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new mi({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:gE}),gg.create(a,l).execute(i)}),o},yE=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let i=(await Se("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>bg(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()},bE=async(s,e)=>{let{mergeProcessCovs:r}=await Se("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await nl(s,"testResult",`runId=${e}`)).data.docs;return await ie(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await an(l,9e4);await ie(c,async d=>{if(!o.has(d.url)){let m=d.text;d.sourceUrl&&(o.set(d.url,"TEMP"),m=await Bc(d.sourceUrl)),o.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:o,mergedCoverages:n}},wg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;gu.info("start js coverage process");let n=(0,dg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=yt.resolve(s.codeCoverageReportPath||"./coverage"),i=yt.resolve(o,`.js/${(0,mg.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?yt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([Se("istanbul-lib-coverage"),bE(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}gu.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await ie(c.result,async({url:g,functions:h})=>{let{text:y,sourceMapType:E}=d.get(g),I=await mE({sourceMapType:E,source:y,sourceMapDir:a});u[g]=I;let b=await yE(s,{source:y,sourceMap:I,functions:h});m.merge(b)}),await fE(s,i,u);let f=await hE(s,m,o,i);return n.succeed(),f}catch(l){let c="Failed to report coverage information";l instanceof C?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),gu.error(c,{err:l})}}});var Eg={};V(Eg,{SELENIUM_PERF_MARKS:()=>Ce,SeleniumPerfStats:()=>xr});var Ce,TE,xr,ps=T(()=>{"use strict";B();Ce={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},TE=["ALL",...Object.values(Ce)],xr=class{constructor(){this.marks=Object.fromEntries(TE.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=re();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,fo(r,50)],[`${t}_P95`,fo(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var xg={};V(xg,{initServer:()=>EE,mapFilesToLocalDrive:()=>yu});function yu(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,gi[t.id]?{screenshot:gi[t.id]}:{})),Object.keys(hi).forEach(t=>{s.assets||={},s.assets[Rg[t]]=hi[t]}),s.assets||={},s.assets.screenshots=Object.values(gi)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function EE({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await Se("multer"),n=typeof t=="string"?t:wE;await hu.promises.mkdir(n,{recursive:!0});let o=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=xn.join(n,m.testResultId);try{await hu.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(l,c,d){let{fileName:m}=l.body,u=JSON.parse(l.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=xn.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),i=(0,Ig.default)();i.post("/",o.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(gi[d.stepId]=l.file.path),d.testResultId&&vE.includes(d.subType)&&(hi[d.subType]||=[],hi[d.subType].push(l.file.path)),c.sendStatus(200)}),i.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(i);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new C(`Port ${s} is already in use`));default:return c(u)}}})}var hu,Sg,xn,Ig,wE,gi,hi,Rg,vE,bu=T(()=>{"use strict";hu=v(require("fs")),Sg=v(require("os")),xn=v(require("path")),Ig=v(require("express"));q();Ir();wE=xn.join(Sg.tmpdir(),"testim/rca/"),gi={},hi={},Rg={"test-log":"consoleLogs","har-file":"networkLogs"},vE=Object.keys(Rg)});var nr,Tu,yi,Ag=T(()=>{"use strict";nr=v(require("lodash"));B();j();Tu=x("override-test-data-builder"),yi=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return nr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!nr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Tu.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(nr.isObject(e.overrideAllTestsData)&&!nr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Tu.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:r}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}Tu.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return nr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let o=r.map(d=>this.generateTestUniqId(d)),i=o.indexOf(n),a=o.lastIndexOf(n),l=r[i],c=this.createNewTestItems(l,t);return r.splice(i,a-i+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let o=re();return Object.assign({},e,{resultId:o,testData:{value:r,index:n+1,total:t.length||1}})})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function bi(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Ze.warn("failed to run hook",{err:t}),new C(`failed to run hook promise ${t.message}`)}}var Ar,Ze,SE,IE,RE,xE,Ti,Cg=T(()=>{"use strict";Ar=v(require("lodash"));B();ae();as();ls();ye();q();j();Ot();un();vg();ps();bu();le();fe();Ag();Sn();Ze=x("test-run-status"),SE=yr(),IE=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,RE=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,xE=dt();Ti=class{constructor(e,t,r,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new xr;var a,l,c,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let o=qs(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:to||t.parallel||1,browser:o,gitBranch:SE,gitCommit:IE,gitRepoUrl:RE,runnerVersion:xE,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:i,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:g,testOwnerEmail:h,testLabels:y,testSuites:E,allLabels:I}=a,b={originalTestResultId:t,previousTestResultId:r,config:Ar.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:i,testStatus:m};return this.testRunStatus[e]=Object.assign({},b,{testCreatorName:u,testCreatorEmail:f,testOwnerName:g,testOwnerEmail:h,testLabels:y,testSuites:E,allLabels:I}),cl({projectId:n,runId:o,testId:c,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let o=this.getTestResult(r);return o.workerId=e,Q.onTestStarted(o,e,n,r),o}async updateTestStatusRunning(e,t,r){var c;let{project:n,remoteRunId:o,projectData:i}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Mo(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(d){Ze.error("failed to upload test data artifact (runner)",{err:d})}let l=Ar.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,Er(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(Xe(e,this.options))return;let n=this.exportsGlobal;try{let o=await bi(this.options.beforeTest,Object.assign({},e,{exportsGlobal:n,globalParameters:n}),this.options.userData.loginData.token);return e.config.testData=Object.assign({},e.config.testData,this.exportsGlobal,this.fileUserParamsData,this.beforeSuiteParams,o),this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(o){throw Ze.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,r,n,o){let i=this.testStart(e,t,r,n);return this.testStartReport(i,t,o)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo=Object.assign({},t,{key:void 0,user:void 0}),Ze.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:o,testId:i,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Ye.EVALUATING&&kt.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Ye.EVALUATING} status`);return}if(c){Q.onTestPassed(o);return}Q.onTestFailed(r,r.failureReason,qe(this.options.editorUrl,this.options.project,i,l,this.branchToUse),i,n,l)}calcResultText(e){return e.success?pe.PASSED:pe.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Ye.QUARANTINE}`)}monitorMemoryUsage(e){let t=hc();t.isOverThreshold&&Ze.info("memoryUsage is over threshold",{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}testEnd(e,t,r,n,o){let i=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;i.sessionId=n,i.startTime=t.startTime||i.startTime||Date.now(),i.duration=a,t.duration=a,i.failureReason=t.failureReason||t.reason,t.failureReason=i.failureReason,i.failurePath=t.failurePath,i.resultId=t.resultId,i.success=t.success,this.options.saveRCALocally&&yu(i,Ze),i.resultUrl=qe(this.options.editorUrl,this.options.project,i.testId,i.resultId,this.branchToUse),i.status=this.calcResultText(t),t.status=i.status,t.name=i.name,t.testStatus=i.testStatus,t.testId||=i.testId,t.testCreatorName=i.testCreatorName,t.testCreatorEmail=i.testCreatorEmail,t.testOwnerName=i.testOwnerName,t.testOwnerEmail=i.testOwnerEmail,t.testData=i.config&&typeof i.config.testDataTotal=="number"?{total:i.config.testDataTotal,index:i.config.testDataIndex}:{},this.reportTestStatus(e,t,i,o),this.monitorMemoryUsage(i),Q.onTestFinished(i,e,o);let l=Object.assign({},this.exportsGlobal,t.exportsGlobal);return this.exportsGlobal=l,i}async testEndReport(e,t,r,n){var i;let o=r.exportsGlobal;try{try{await bi(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){Ze.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(i=this.options.lightweightMode)!=null&&i.onlyTestIdsNoSuite?void 0:await Er(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw Ze.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,o,i){let a=this.testEnd(e,t,r,n,o);return this.testEndReport(a,r,t,i)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:o,VIRTUAL_BUILD:i}=pc;return e&&(n=o),Gr(t,r)&&(n=i),n}calcTestRunStatus(){var i;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(i=e.gridData)==null?void 0:i.type,o=t.map(a=>{var f,g,h;let l=e.browser?Ys(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=Hr(M,n)&&Ks(a.nativeApp)&&!e.appId,d=Js(e)&&(Gr(a.nativeApp,n)||c),m=Xe(a,e)||d,u={testId:a.testId,status:m?pe.SKIPPED:pe.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Ye.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(c,a.nativeApp,n)},config:Object.assign({},this.execConfig,{companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((g=a.testData)==null?void 0:g.total)||null,testDataIndex:((h=a.testData)==null?void 0:h.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:l.browserValue.toLowerCase()})};return[a.resultId,u]});return Object.fromEntries(o)}async endKeepAlive(e,t,r){e==="redis"&&await Tn.end(r,t),e==="mongo"&&await yn.end(t)}async executionStart(e,t,r,n,o){Ze.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=i;rs(()=>Promise.all([this.endKeepAlive(d,t,c),_o("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,...M.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},u=await bi(i.beforeSuite,m),f=new yi(u,Ar.cloneDeep(this.testInfoList),t);this.testInfoList=f.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:g}=this,h=[],y=[],E=[];for(let b of g){if(b.isBeforeTestPlan){h.push(b);continue}if(b.isAfterTestPlan){E.push(b);continue}y.push(b)}let I=async()=>{let b=Ar.cloneDeep(this.testRunStatus);await ie(Object.keys(b),async _=>{var U;let $=b[_],S=(U=$.config)==null?void 0:U.testData,A=$.testId,L=await Mo(t,A,_,S,l.defaults);L&&(delete $.config.testData,$.config.testDataUrl=L)});let w=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),R={executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:w,intersections:i.intersections},k=Gc(R);return this.executionStartedPromise=k,k.catch(_=>Ze.error(_)),k};try{await I()}catch(b){Ze.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:h,tests:y,afterTests:E}}concatSeleniumPerfMarks(e){Ar.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var d;let t=bc(this.testRunStatus),r=t.length,n=0,o=0,i=0;for(let{status:m,testStatus:u}of t)m===pe.PASSED&&n++,m===pe.SKIPPED&&o++,m===pe.FAILED&&u===Ye.EVALUATING&&i++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await bi(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:o})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Ze.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let c=await wg(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await _o("FINISHED",e,this.options.project,r===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw Ze.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await Vc(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function CE(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Iu(s){return Og.readFileSync(s,{encoding:"base64"})}function Mg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&We(s))&&s){let r=Iu(s);ds.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${Su(r)} current extension count: ${e.length}`),e.push(r)}}function Ng(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;if(s.ext||r){let l=typeof s.ext=="string"?s.ext:`${__dirname}/..`,c=r||l,d=`--load-extension=${c}`;ds.info(`adding extension: testim unpacked , path: ${c}`),t.push(d);return}let o=s.canary?"-master.zip":".zip",i=Eu.join(process.cwd(),`testim-headless${o}`),a=Iu(i);ds.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${Su(a)} current extension count: ${e.length}`),e.push(a)}function PE(s,e,t,r,n,o,i){var g,h;let a=t.seleniumName||t.browserValue,l=[],c=[...Dg];e.headless&&c.push("--headless");let d={prefs:{"profile.default_content_setting_values.popups":wu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":wu.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1},w3c:!0};vu(n)&&(d.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),vu(n)&&a==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(d.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(y=>c.push(`--${y}`)),e.chromeBlockLocation&&(d.prefs["profile.default_content_setting_values.geolocation"]=wu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&c.push(`--user-data-dir=${e.chromeUserDataDir}`),(h=(g=e.projectData)==null?void 0:g.defaults)!=null&&h.disableChromiumGpu&&c.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:a});function m(){t.mobileEmulation&&(d.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+lc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}m(),Mg(r,l,i),e.mode===Y.EXTENSION&&Ng(e,l,c,o,i),l.length>0&&(d.extensions=l),e.disableCookiesSameSiteNoneRequiresSecure&&(d.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),d.args=c;let u={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],f={MicrosoftEdge:"ms",chrome:"goog"}[a];return te.isLambdatestGrid(n)&&delete d.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(s.desiredCapabilities[u]=d),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${f}:${u}`]=d),s}function OE(s,e,t){let r={"pdfjs.disabled":!0};if(M.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":kg.join(","),"browser.helperApps.neverAsk.openFile":kg.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.mode===Y.EXTENSION)if(e.ext)s.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=Eu.join(process.cwd(),`testim-firefox-profile${n}`);s.desiredCapabilities.firefox_profile=Iu(o)}return e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function _E(s){return`${s.width}x${s.height}`}function LE(s,e,t,r){let{saucelabs:n}=s;if(n!=null&&n.browserVersion&&(n.version=n.browserVersion),n!=null&&n.username&&n.accessKey){let o={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=n.appiumVersion||t.sl.appiumVersion;let i=(0,Lg.cloneDeep)(t.sl);return(r!=null&&r.resolution||t.sl.screenResolution)&&(o["sauce:options"].screenResolution=_E(r.resolution||t.sl.screenResolution),delete i.screenResolution),it.merge(i,o,n)}return it.merge(o,n)}return{}}function DE(s,e,t){return it.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),Object.assign({},t.bs,s.browserstack,{name:e})):Object.assign({},s.browserstack,{name:e})}function ME(s){return s.perfecto?s.perfecto:{}}function NE(s,e,t){if(s.experitestToken){let r=e==="safari";return{accessKey:s.experitestToken,browserVersion:"latest",platformName:r?"MAC":"WIN10",seleniumScreenshot:r,newSessionWaitTimeout:t}}return{}}function UE(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,o=r||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=Da(o,i)),a}function wi(s){var E;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,lambdatestService:c}=s;if(o.mode==="local"){let I=[],b=[...Dg],w={};return t.headless&&b.push("--headless"),t.silentDebuggerExtensionApi&&b.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&b.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach(R=>b.push(`--${R}`)),t.chromeBinaryLocation&&(w.binary=t.chromeBinaryLocation),t.mode!=="selenium"&&Ng(t,I,b,null,c),Mg(i,I,c),{logLevel:Pg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:b,extensions:I,...w},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:d,driverRequestRetries:m}=t,u=UE(t,o),f={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:Pg,connectionRetryTimeout:d,connectionRetryCount:m,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!it.isEmpty(u)&&{headers:u},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};vu(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,f.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(f.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key);let g=Number(t.browserTimeout/1e3),h=t.browser||(n==null?void 0:n.browserValue);it.merge(f.desiredCapabilities,LE(t,r,n,e),DE(t,r,n),ME(t),NE(t,h,g),c==null?void 0:c.getCapabilities(t,h,a,l,r,e));let y=null;switch(!t.ext&&!t.extensionPath&&((E=o.host)!=null&&E.endsWith(".testim.io"))&&!t.canary&&t.mode===Y.EXTENSION&&(h==="chrome"||h==="edge-chromium"&&M.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(y="/opt/testim-headless"),h){case"chrome":case"edge-chromium":f=kE(f,t,n,i,o,y,c);break;case"firefox":f=OE(f,t,c);break;case"safari":case"safari technology preview":f=CE(f,h);break;default:break}it.merge(f.desiredCapabilities,t.seleniumCapsFileContent);try{let I={"hub.lambdatest.com":"lambdatest",[M.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},b=_=>_[o.provider]||_[f.host]||_[I[f.host]],w=_=>{var $,S;return b(_)||_[($=f.desiredCapabilities)==null?void 0:$.browserName]||_[(S=f.desiredCapabilities)==null?void 0:S.version]||_||{}},R=JSON.parse(M.flags.addCustomCapabilities.getValue()||"{}"),k=w(w(R));Object.keys(k).length&&(ds.info(`Adding custom capabilities: ${JSON.stringify(k)}`),Object.assign(f.desiredCapabilities,k))}catch(I){ds.error("Failed to load custom capabilities",{error:I,customCapabilities:M.flags.addCustomCapabilities.getValue()})}return f.desiredCapabilities&&!f.capabilities&&(AE(f),f.capabilities={alwaysMatch:f.desiredCapabilities,firstMatch:[{}]},delete f.desiredCapabilities),f.hostname=f.host,f}var Og,Eu,_g,it,Lg,ds,Pg,wu,Dg,Su,vu,AE,kE,kg,Ru=T(()=>{"use strict";Og=v(require("fs")),Eu=v(require("path")),_g=v(require("crypto")),it=v(require("lodash"));B();le();j();fe();ae();Xo();Lg=require("lodash"),ds=x("testim-desired-capabilities-builder"),Pg=eo?"debug":"silent",wu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Dg=["--disable-popup-blocking","--ignore-gpu-blacklist","--auto-select-desktop-capture-source=Entire screen","--ignore-certificate-errors","--disable-features=TranslateUI","--disable-background-networking","--disable-sync","--metrics-recording-only","--disable-default-apps","--mute-audio","--no-first-run","--disable-back-forward-cache"],Su=(...s)=>_g.createHash("sha256").update(s.join("")).digest("hex"),vu=s=>s.type===O.DEVICE_FARM||s.type===O.HYBRID&&s.provider==="devicefarm",AE=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=M.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(o=>{delete e[o]})}catch{ds.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};kE=it.memoize(PE,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(it.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return Su(i,a,l,r,c,o)}),kg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Ue(s){var e,t,r,n,o,i,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=s.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function Fg(s,e,t){if(!e||!s)return s;if(s.includes("%"))return s.replace(/ /g,"%20");try{return decodeURI(s)!==s?s:encodeURI(s)}catch(r){return t&&t.warn("tried to encode url but failed",{err:r,url:s}),s}}var xu=T(()=>{"use strict"});function Au(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let g=u;g&&g!==u.ownerDocument;g=g.parentNode)if(f(g))return g;return null}function n(u,f){for(let g=u;g&&g!==u.ownerDocument;g=t(g))if(f(g))return g;return null}function o(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let h=window.getComputedStyle(u).getPropertyValue(f);if(h&&h!=="inherit")return h;let y=t(u);return o(y,f)}function i(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let h=o(u,"stroke-width");return!!h&&parseInt(h,10)>0}return o(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(h=>h.nodeType===Node.TEXT_NODE?!0:e(h)?i(h):!1)}function a(u){return o(u,"overflow")==="hidden"}function l(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!i(f)?!0:l(f))}function c(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:c(u.parentNode):!1}if(!s||!c(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,g=>g.tagName.toUpperCase()==="SELECT");return Au(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(o(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(o(u,"opacity"))===0),m=!!n(s,u=>o(u,"display")==="none");return!(d||m||!i(s)||l(s))}var Bg=T(()=>{"use strict"});var jg,$g,Ht,FE,BE,vi,Wg=T(()=>{"use strict";jg=v(require("promise-queue")),$g=v(require("webdriverio"));le();$e();B();j();Mr();Bg();xu();ps();Ht=x("WebDriverApi"),FE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},BE={implicit:0,pageLoad:1,script:2},vi=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}async rejectWithLog(e,t){let{testName:r,testResultId:n}=this,o=t?t.toString().substr(0,2e3):"";throw Ht.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),Fa!==void 0&&(e=Fa);let t=1/0;this.queue=new jg.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(o){return this.rejectWithLog(o,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,i;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),N("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(Ce.GET_BROWSER);try{await this.addToQueue(async()=>{Ht.info("requesting browser",{testResultId:r,testName:t}),N("before this.client.init"),this.client=await $g.remote(e),this.logGridStatus(r)}),N("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,Ce.GET_BROWSER)}}async logGridStatus(e){var i;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",o;try{o=await this.client.status();for(let a of o.nodes||[])for(let l of a.slots||[])if(((i=l==null?void 0:l.session)==null?void 0:i.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){Ht.info("grid status is not supported by the grid",{testResultId:e});return}Ht.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Ht.info("grid status",{gridStatusMsg:o.message,ready:o.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},o=()=>this.client.execute(e,t).catch(n),i=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return o();t=t.map(a=>{if(a===null){Ht.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await i()}catch(a){if(Ue(a))return this.unsupportedActions.add("execute"),o();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),o=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await o()}catch(i){if(Ue(i))return this.unsupportedActions.add("executeAsync"),n();throw i}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Ce.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,Ce.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Ce.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Le(e)))}finally{this.seleniumPerfStats.markEnd(t,Ce.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(Au,{ELEMENT:e,[zt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Ue(n))return this.unsupportedActions.add("elementIdDisplayed"),r();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(Fg(e,this.isSafari(),Ht))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let r=()=>{let o=[];return o[BE[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(o){if(Ue(o))return this.unsupportedActions.add("timeouts"),n();throw o}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,o){window.scrollTo(n,o)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(Le(e)),await this.elementIdValue(Le(e),t)}async getViewportSize(e){let t=await this.execute(FE);if(typeof e=="string"&&e.match(/(width|height)/)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async keys(e){let t=i=>Object.hasOwn(_a,i)?[_a[i]]:i.split(""),r=[];if(typeof e=="string")r=t(e);else if(Array.isArray(e))for(let i of e)r=r.concat(t(i));else throw new Error("number or type of arguments don't agree with keys protocol command");let n=()=>{var i;return(i=this.client)==null?void 0:i.requestHandler.create("/session/:sessionId/keys",{value:r})},o=()=>{let i=r.map(l=>({type:"keyDown",value:l})),a=r.map(l=>({type:"keyUp",value:l}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};if(this.unsupportedActions.has("keys"))return o();try{return await this.addToQueue(()=>n())}catch(i){if(Ue(i))return this.unsupportedActions.add("keys"),o();throw i}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(Le(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let o=Math.abs(e.width),i=Math.abs(e.height);r=async()=>await this.client.setWindowSize(o,i),n=async()=>await this.client._setWindowSize(o,i)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(o){if(Ue(o))return this.unsupportedActions.add("windowHandleSize"),r();throw o}})}}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>{var l;return(l=this.client)==null?void 0:l.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){Ht.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return Ht.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var Vg={};V(Vg,{doubleClick:()=>jE});var jE,Gg=T(()=>{"use strict";jE=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(u){function f(I,b,w){return w>I&&w<b}let g=u.pointerPosition||{},h=r.getBoundingClientRect(),y=g.originX&&f(h.left,h.left+h.width,g.originX)?g.originX:h.left+h.width/2,E=g.originY&&f(h.top,h.top+h.height,g.originY)?g.originY:h.top+h.height/2;return{x:y,y:E}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,f,g){if(!window.PointerEvent)return;let h=a(f,g);return new window.PointerEvent(u,h)},c=function(u,f,g){let h=document.createEvent("MouseEvents");return h.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,g,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),h},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=i(u),g=u.event;return t.includes(g)?l(g,f.x,f.y):c(g,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var An={};V(An,{dispatchFocus:()=>$E});function $E(s,e){function t(o){let i=document.createEvent("HTMLEvents");return i.initEvent(o,!0,!1),i}function r(){var i;let o=document.activeElement;for(;(i=o.shadowRoot)!=null&&i.activeElement;)o=o.shadowRoot.activeElement;return o}function n(o,i){i&&(i.dispatchEvent(t("focusout")),i.dispatchEvent(t("blur"))),o.dispatchEvent(t("focusin")),o.dispatchEvent(t("focus")),typeof o.focus=="function"&&o.focus();let a=r();i&&a===i&&typeof i.blur=="function"&&i.blur()}if(s){let o=getLocatedElement(s);if(o&&o!==e)try{n(o,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var Cn=T(()=>{"use strict"});var Jg={};V(Jg,{WebDriver:()=>Pr});async function HE(s){var e,t;try{let r=(t=(e=s==null?void 0:s.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return r?await VE(r):void 0}catch(r){Be.info("Error getting cdpAddress",r);return}}var ms,zg,Kg,Be,or,WE,Hg,VE,ir,GE,qg,Cr,Pr,Pn=T(()=>{"use strict";ms=v(require("lodash"));B();$e();Ru();zg=v(require("p-retry")),Kg=v(require("ua-parser-js"));Mr();j();xu();Wg();q();fe();ps();Be=x("webdriver"),[or,WE]=[0,2],{extractElementId:Hg,getCdpAddressForHost:VE}=K,ir=()=>(Te(),he(tr)).getSessionPlayer().codeSnippets,GE=()=>(Te(),he(tr)).getSessionPlayer().locatorBuilderUtils,qg=()=>(Te(),he(tr)).getSessionPlayer().utils,Cr=()=>(Te(),he(tr)).getSessionPlayer().positionUtils;Pr=class extends vi{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var E,I,b,w,R,k,_,$;let{overrideConfiguration:r,browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((b=(I=(E=n==null?void 0:n.company)==null?void 0:E.activePlan)==null?void 0:I.premiumFeatures)==null?void 0:b.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let g=wi({browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r});g.desiredCapabilities&&delete g.desiredCapabilities.marionette,g.capabilities&&delete g.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let h=u?0:1500,y=u?()=>null:()=>this.executeJS("window.focus()");try{N("before initClient in webdriver.js init");let S=await this.initClient(g,o,d);N("after initResult before getCdpAddress in init"),this.cdpUrl=await HE(S),N("after getCdpAddress in webdriver.js init"),Be.info(`init new session testName: ${o}`,{sessionId:this.getSessionId(),testResultId:d}),await oe(h),M.flags.dontFocusOnInit.isEnabled()||await y(),N("after focus and delay in webdriver.js init")}catch(S){let A=JSON.stringify(ms.omit(g,"capabilities.extensions","capabilities.capabilities.extensions"));Be.error("failed to init webdriver",{err:S,capabilitiesAsString:A});let L=((R=(w=n==null?void 0:n.company)==null?void 0:w.activePlan)==null?void 0:R.plan)==="free";throw(k=S.stack)!=null&&k.includes("at startWebDriverSession")&&((_=S.message)!=null&&_.startsWith("Failed to create session"))&&(($=S.message)!=null&&$.includes("Timeout awaiting 'request'"))&&L?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):S.message.match(/Invalid username or password/)?new Br(S.message):S.message.match(/capabilit(y|ies)/)?new ro(S.message):new Error("failed to init client driver")}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>ms.zip(o.slice(0,-1),o.slice(1)),r=this._keepAliveRequests.map(({start:o})=>o).filter(Boolean),n=t(r).map(([o,i])=>i-o);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function o(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let i=re();r(i);try{await this.executeJS(o),this._isAlive=!0,n("end",i),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",i),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Be.warn("close unexpected alert open"),await this.alertAccept().catch(l=>Be.warn("failed to click on alert",{err:l}));return}if(Be.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;Be.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:l,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=l&&this.browserClosedCallbacks.forEach(c=>{try{c(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=Hg(r.value);return await this.switchToFrame({ELEMENT:n,[zt]:n}),r}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new so:r}}async getElement(t){var o;let r=this.seleniumPerfStats.markStart(Ce.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,Ce.GET_ELEMENT)}if(((o=t==null?void 0:t.shadowPath)==null?void 0:o.length)||M.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
23
23
|
var fn = ${ir().getLocatedElementCode};
|
|
24
24
|
return fn.apply(null, arguments);
|
|
25
25
|
`,t)}finally{this.seleniumPerfStats.markEnd(r,Ce.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(r,Ce.GET_ELEMENT)}}executeJS(t,...r){return this.execute(t,...r)}async executeCodeAsync(t,r,...n){return await this.timeouts("script",r),await this.executeAsync(t,...n)}async markDynamicParent(t,r){function n({attributeName:o,attributeValue:i,locatedElement:a}){let l=getLocatedElement(a);if(!l)throw new Error("could not find dynamic parent");l.setAttribute(o,i)}await this.executeJS(`
|
|
@@ -405,12 +405,12 @@ Please make sure the CLI has stable access to the internet. ${oc()?"(Internal: n
|
|
|
405
405
|
`;return this.driver.executeJS(n,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(n){throw Qi.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(n){let o="The element is not editable",i="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",l="element not interactable",c="element is not pointer- or keyboard interactable",d="invalid element state: Element is not currently interactable and may not be manipulated",m="Element must not be hidden, disabled or read-only",u="is not reachable by keyboard",f=n?n.message:"";if(f===d||f.startsWith(m)||f.startsWith(o)||f.startsWith(i)||f.startsWith(a)||f.includes(u)||f.includes(l)||f.includes(c)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw Qi.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(Le(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=M.flags.overrideAzureStorageUrl.isEnabled(),n=M.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:o,context:i,step:a,stepActionUtils:l,driver:c}=this,d=await o.utils.addTokenToFileUrl(i.project.id,a.fileUrls,l.testimServicesApi,r,Qi);if(d.length===0)throw new Error("No files urls to upload");if(n&&(d=await Promise.all(d.map(async({name:u,url:f})=>{let g=await Nt(f);return{name:u,url:`data:${g.type};base64,${Buffer.from(g.body).toString("base64")}`}}))),c.isSafari()||c.isFirefox()||c.isEdgeChromium()){await this.driver.executeJS(`
|
|
406
406
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
407
407
|
const downloadAndUploadFile = ${zS()};
|
|
408
|
-
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Ay(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ea,ta,ky=T(()=>{"use strict";ea=require("url");ue();ta=class extends W{async updateBaseUrl(e){let t=new ea.URL(e),r=new ea.URL(this.context.recordedBaseUrl),n=new ea.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 ra,Oy=T(()=>{"use strict";ue();B();ra=class extends W{async performAction(){await oe(this.step.durationMS||0)}}});var sa,_y=T(()=>{"use strict";ue();sa=class extends W{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Un,Ly=T(()=>{"use strict";ue();Un=class extends W{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 na,Dy=T(()=>{"use strict";ue();na=class extends W{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 My,tp,rp,Ny=T(()=>{"use strict";My=v(require("@applitools/spec-driver-webdriverio"));Xn();Te();tp=class{constructor(){let{EyeSdkBuilder:e}=se(),t=Wp["@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:My.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=se(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},rp=new tp});var Fy,Uy,Fn,By=T(()=>{"use strict";Fy=v(require("lodash"));ue();j();Ny();Uy=x("pixel-validation-step-action"),Fn=class extends W{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 rp.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}),h={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};Fy.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(h,i.applitoolsStepSettings),Uy.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await f.check({settings:h}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){Uy.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await rp.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Is,sp=T(()=>{"use strict";kr();q();Hi();Is=class extends lr{async executeCliCode(){var g,h,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(h=(g=t.company)==null?void 0:g.activePlan)==null?void 0:h.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 hs(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,jy=T(()=>{"use strict";sp();ur=class extends Is{isFailedResult(e){return e===!1}}});var oa,$y=T(()=>{"use strict";sp();oa=class extends Is{isFailedResult(e){return!e}}});var ia,Wy=T(()=>{"use strict";kr();ue();q();ia=class extends W{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await gs(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof Rt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ne?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Dr,Vy=T(()=>{"use strict";ue();Dr=class extends W{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ve,Gy=T(()=>{"use strict";ue();ve=class extends W{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 aa,Hy=T(()=>{"use strict";ue();aa=class extends W{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 ca,qy=T(()=>{"use strict";ue();ca=class extends W{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 KS(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function la(s,e){KS(JS,e),e.registerLocateStepActionUtils(Dn.getUtils(s))}var JS,np=T(()=>{"use strict";Vh();qh();ty();ry();ny();ay();uy();py();dy();gy();hy();yy();wy();Sy();Py();ky();Oy();_y();Ly();Dy();By();jy();$y();Wy();Vy();Gy();Hy();qy();JS={locate:Dn,scroll:ji,mouse:$i,submit:Ki,text:Vi,"special-key":qi,"user-code":qt,"validation-code-step":qt,"wait-for-code-step":qt,"action-code-step":qt,"condition-step":Ss,"skip-code-step":Ss,"element-code-step":Ss,"evaluate-expression":Wi,"text-validation":Nn,"wait-for-text-validation":Nn,"select-option":zi,"drop-file":Xi,"input-file":Zi,hover:Ji,navigation:ta,wheel:Yi,sleep:ra,refresh:sa,"api-validation":Un,"api-action":Un,"api-code-step":qt,"extract-text":na,"simple-ui-verification":Fn,"wait-for-simple-ui-verification":Fn,"cli-validation-download-file":Dr,"cli-wait-for-download-file":Dr,"network-validation-step":Dr,"cli-validation-code-step":ur,"cli-wait-for-code-step":ur,"cli-action-code-step":ur,"cli-api-code-step":ur,"cli-condition-step":oa,"node-package":ia,"email-code-step":qt,"cli-email-code-step":ur,"sfdc-internal-test-step":ca,"sfdc-recorded-step":aa,"sfdc-step-login":ve,"sfdc-step-loginas":ve,"sfdc-step-logout":ve,"sfdc-step-sobjectcreate":ve,"sfdc-step-sobjectdelete":ve,"sfdc-step-findrecord":ve,"sfdc-step-quickaction":ve,"sfdc-step-sobjectedit":ve,"sfdc-step-sobjectvalidate":ve,"sfdc-step-launchapp":ve,"sfdc-step-wait-for-page-load":ve,"sfdc-step-closeconsoletabs":ve,"sfdc-step-relatedlistaction":ve,"sfdc-step-permission-validation":ve,"sfdc-step-convert-lead-to-opportunity":ve,"sfdc-step-quotelineeditor":ve,"sfdc-document-validation":Dr}});var zy,YS,Rs,op=T(()=>{"use strict";zy=["simple-ui-verification","wait-for-simple-ui-verification"],YS=[...zy,"custom-validation","sfdc-internal-test-step","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-wait-for-page-load","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation","sfdc-step-convert-lead-to-opportunity","sfdc-step-quotelineeditor","sfdc-document-validation"],Rs=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=YS.includes(e.stepType)?[r]:t(r);this.resetStepVariables(r,n),e.context.data.maxTotalStepTime=r}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let r=e.context.config.stepTimeout;return zy.includes(e.stepType)&&(r=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(r=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:r}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let r=Date.now()-e.startTimestamp;return t-r}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+1e3}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,r=e.step.type,n=3e4;return r==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),n)}}});var Jy={};V(Jy,{SeleniumTestPlayer:()=>Bn});var Ky,Bn,ip=T(()=>{"use strict";B();Ky=require("@applitools/eyes-sdk-core");Pn();q();Ku();Uh();Qu();Fh();$h();Zu();Te();np();op();Bn=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new Rs(Bi());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=se();this.driver=n??new Pr;let d=new Fi(this.driver);this.stepActionFactory=new c(d),la(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ni(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=jh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new vs(this.driver),FrameLocator:m,portSelector:Ui,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Ky.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=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}=se(),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 Yy={};V(Yy,{WorkerSelenium:()=>ap});function QS(s){let{playback:e}=se().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>N(`Got event ${t}`))}var ua,XS,ap,Xy=T(()=>{"use strict";B();$e();Ln();j();Ot();Ho();ae();qu();q();ip();Te();ua=x("worker-selenium"),XS=1e9,ap=class extends at{initPlayer(t){return new Bn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){N("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ws(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}),N("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),N("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,XS),await this.windowUtils.validatePageIsAvailable(),N("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof It||d||m?new It(`Page '${l}' is not available`):(ua.error("failed to navigate to page",{baseUrl:l,err:c}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:o}=se(),{driver:i,sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),QS(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),o.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await fn(this.options))[this.testId]);let d=async()=>ce(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(f)}),this.testRunTimeout,Fe.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()||(ua.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&&(ua.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let h={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h});i.start(),N("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),N("right after super.runTestOnce in workerSelenium");let u=await d();return N("right after runSeleniumTest"),u}catch(u){throw ua.error("failed to run test once",{err:u}),u}}}});var Qy,He,ZS,eI,cp,vt,pa=T(()=>{"use strict";j();ae();le();ye();Ke();Qy=v(require("ora")),He=x("mobile-grid-service"),ZS="https://tdc.tricentis-cloud.com",eI="https://ui.headspin.io",cp=class{constructor(){this.gridsAppIdGetter={[O.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[O.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[O.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[O.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[O.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[O.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===O.TESTIM_TDC||e===O.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e)?`${t}/lock`:""}getBaseApiUrl(e){return e===O.TESTIM_HEADSPIN?`${id}/devices`:e===O.TESTIM_TDC?`${cd}/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 Ge({url:r,headers:n,body:o})}catch(i){throw He.debug(`error while locking device ${t}`,{error:i}),i.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):i}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e.type)}/device_id:${t}/automation-config`;try{let o=await Ee(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw He.error("error while getting automation config for device",{error:o,deviceId:t}),o}}async getPCloudyAuthToken(e,t){let r=await Vs(`${Ba}/access`,void 0,{Authorization:`Basic ${Buffer.from(`${e}:${t}`).toString("base64")}`});return JSON.parse(r).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,o=new URL(n);return{hostname:o.hostname,port:Number(o.port),protocol:o.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){if(this.isTdcOrHeadSpinGrid(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:`/v0/${e.accessToken}/wd/hub`};if(e.type===O.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===O.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([O.BROWSERSTACK,O.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:o,gridId:i}){var a,l;if(t===O.TESTIM_HEADSPIN||t===O.TESTIM_TDC){let c=await fl({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=c==null?void 0:c[0])==null?void 0:a.name)||e.device}if(t===O.BROWSERSTACK)return(l=e.mobile)==null?void 0:l.version.split("-")[0];if(t===O.SAUCELABS)return e.testobject_device_name;if(t===O.P_CLOUDY){if(e.pCloudy_DeviceFullName){let c=e.pCloudy_DeviceFullName.split("_");return`${c[0]} ${c[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r){var E;let{executionId:n,testId:o,testResultId:i}=e,{project:a,projectData:{type:l}={},company:{companyId:c=""}={},gridData:{gridId:d="",type:m=""}={}}=r,u=t.capabilities,f=await this.getDeviceNameFromSessionCaps({capabilities:u,gridType:m,projectId:a,projectType:l,companyId:c,gridId:d}),g=u.platformVersion;!g&&m===O.BROWSERSTACK&&(g=(E=u.mobile)==null?void 0:E.version.split("-")[1]),!g&&m===O.TESTIM_TVC&&(g=u.os_version);let h={name:f??"",model:u.deviceModel,osVersion:g,udid:u.udid,osType:u.platformName,scaleFactor:u.pixelRatio,isVirtual:m===O.TESTIM_TVC,...m===O.TESTIM_TVC&&{model:u.deviceModel||t.capabilities.device,height:t.capabilities.screen.height,width:t.capabilities.screen.width,scaleFactor:t.capabilities.screen.scale}},y=await this.buildRemoteResultLink(r.gridData,t.sessionId,u);return await Er(a,n,o,i,"RUNNING",{device:h,...y&&{remoteResultLink:y}}),He.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:h,remoteResultLink:y,gridType:m}),h}async buildRemoteResultLink(e,t,r){return e.type===O.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ns}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===O.SAUCELABS?r.testobject_test_report_url:e.type===O.TESTIM_TVC?r.replayUrl:e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC?`${e.type===O.TESTIM_HEADSPIN?eI:ZS}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let t=await Ee(`${md}/devices`),r=t==null?void 0:t.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,resolution:`${r.width}x${r.height}`,geo:"local",manufacturer:r.model,osVersion:r.osVersion,type:r.deviceType||"",osType:r.osType,isLandscape:r.screenMirror.orientation==="LANDSCAPE",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}),He.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 zc({appId:e,projectId:t});if(!i)throw He.error("mobile app not found",{appId:e,projectId:t,executionId:n,testResultId:o}),new Error("mobile app not found");return{appUrl:`${me}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}catch(i){throw He.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/(od*60))+1)*60*1e3,Math.max(nd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let i={[O.BROWSERSTACK]:{name:"Browserstack",appPath:"browserStackAppId"},[O.TESTIM_TVC]:{name:"Mobile Virtual Grid",appPath:"testimTvcAppId"},[O.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,Qy.default)(`uploading app to ${a} please wait..`).start();try{He.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await gl({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}`),He.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:o,mobileAppId:i}){let a=t.get(i);if(a&&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:g=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){He.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:i});let I=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d,executionId:i,testResultId:a});n=I.appUrl,o=I.mobileApp,e.nativeApp=o}else He.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:i}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,y=this.gridsAppIdGetter[f]({testRunHandler:e,mobileApp:o,gridHost:g}),E=f===O.BROWSERSTACK||f===O.TESTIM_TVC||f===O.P_CLOUDY;if(y){let I=t.projectData.type,b=await this.verifyAppStillExistsOnGrid({gridAppId:y,gridData:m,projectType:I});b&&(He.info("app exists on grid, using gridAppId",{gridAppId:y,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=y),!b&&E&&(He.info("app not exists on grid, uploading it",{gridAppId:y,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!b&&!E&&He.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:i})}return!y&&E&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var c,d;let{accessToken:n,user:o,host:i,key:a,type:l}=t;if(l===O.BROWSERSTACK){let m=`${Ns}/recent_apps`;return(await this.fetchWithUserAndPasswordAuth({url:m,user:o,key:a})).some(f=>f.app_url===e)}if(l===O.SAUCELABS){let u=`${i.includes("eu-central-1")?dd:pd}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:o,key:a})).items.some(g=>g.id===e)}if(l===O.TESTIM_HEADSPIN||l===O.TESTIM_TDC){let m=l===O.TESTIM_HEADSPIN?`${ad}/apps`:`${ld}/apps`;return(await this.fetchWithTokenAuth({url:m,accessToken:n,authType:"Bearer"})).apps.some(f=>f.app_id===e)}if(l===O.TESTIM_TVC){let m=`${ud}/versions/${e}/info`,u=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:m,accessToken:u,authType:"Upload-Token"}),!0}catch(f){return f.status!==404&&He.error("error while verifying app exists on TVC",{error:f}),!1}}if(l===O.P_CLOUDY){let m=await this.getPCloudyAuthToken(o,a),u=`${Ba}/drive`,f=await tc({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(h=>h.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 Ee(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r}){let n={Authorization:`${r} ${t}`};return await Ee(e,void 0,n)}},vt=new cp});function lp({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"&&!tI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function rI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==O.TESTIM_TDC&&e.type!==O.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function sI(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 nI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===O.TESTIM_TDC,a=s===O.TESTIM_HEADSPIN,l=i?"tdc":"headspin",c=a&&M.flags.enableBatchHeadSpin.isEnabled(),d=i&&(M.flags.enableBatchTDC.isEnabled()||M.flags.headSpinTdcEnableFlagCapability.isEnabled());return{[`${l}:capture`]:!0,...M.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...o&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:sI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n}}}function da(s){return"id"in s?s.id:s.packageName}function oI(s,e){return{[`${e===O.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function iI({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=oI(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":da(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":da(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function ma({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:o=""}){switch(s){case"ios":return{...e,platformName:"iOS",[`${o}autoAcceptAlerts`]:!0,[`${o}automationName`]:"XCUITest",...t&&{[`${o}bundleId`]:da(t)},...r&&{[`${o}app`]:r}};case"android":return{...e,platformName:"Android",[`${o}autoGrantPermissions`]:!0,[`${o}automationName`]:"UiAutomator2",...n&&{[`${o}appWaitActivity`]:n},...t&&{[`${o}appPackage`]:da(t),[`${o}appActivity`]:t.activity??".*"},...r&&{[`${o}app`]:r}};default:throw Error(`unsupported mobile project ${s}`)}}function eb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=nI(i.type,o,n);return iI({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function up({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 pp({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o}=e,i=r===O.P_CLOUDY;return s||(n!=null&&n.deviceName?i?n.deviceUdid:n.deviceName:o!=null&&o.deviceNameRegex?t==="android"&&o.deviceNameRegex===".*"&&i?ja:o.deviceNameRegex:t==="ios"&&r===O.BROWSERSTACK?"iPhone.*":i?t==="ios"?"apple":ja:".*")}function aI(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 cI({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=aI(o,s),f=up({osVersion:l,mobileConfig:d}),g=pp({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=qe(n.editorUrl,n.project,i.testId,i.testResultId,i.branch),y={device:g,os_version:f,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:externalUrl":h,"waldo:options":{token:u}};return ma({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function lI({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,g=up({osVersion:l,mobileConfig:d}),h=pp({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),y=/^[a-zA-Z]+$/.test(h),E={...g!==".*"&&{pCloudy_DeviceVersion:g},...y&&{pCloudy_DeviceManufacturer:h},...!y&&{pCloudy_DeviceFullName:h}},I={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...E,pCloudy_DurationInMinutes:n.duration?Number(n.duration):fd,pCloudy_ApplicationName:t,newCommandTimeout:120,fullReset:!0};return t="",ma({projectType:s,sessionCaps:I,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function uI({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=m===O.BROWSERSTACK?"browserstack":"saucelabs",f=up({osVersion:l,mobileConfig:d}),g=pp({deviceName:c,mobileConfig:d,projectType:s,gridType:m});if(s==="android"&&/1[4-9]/.test(f)&&m===O.SAUCELABS){let I={appiumVersion:"latest",user:o.user,key:o.key,debug:!0,networkLogs:!0,tags:Object.values(i),name:i.testResultId,build:i.executionId};return ma({projectType:s,sessionCaps:{"appium:platformVersion":f,"appium:deviceName":g,"sauce:options":I},appiumPrefix:"appium:",nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let E={...m===O.BROWSERSTACK&&{os_version:f,device:g,realDevice:!0,project:i.project,buildTags:Object.values(i).join(",")},...m===O.SAUCELABS&&{platformVersion:f,deviceName:g,tags:Object.values(i)},name:i.testResultId,build:i.executionId,[`${u}.user`]:o.user,[`${u}.key`]:o.key,[`${u}.debug`]:!0,[`${u}.networkLogs`]:!0};return ma({projectType:s,sessionCaps:E,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function tb(s){return O.TESTIM_TDC===s.gridInfo.type||O.TESTIM_HEADSPIN===s.gridInfo.type?eb(s):O.TESTIM_TVC===s.gridInfo.type?cI(s):O.P_CLOUDY===s.gridInfo.type?lI(s):uI(s)}function pI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:o,osVersion:i,deviceUdid:a}=s,l={};return n==="dynamic"&&(!o&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!i&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),o&&(l.manufacturer=o),i&&(l.os_version=i),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}function rb(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}`);lp({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=vt.getGridConnection(e),l=tb(s);if(e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC){let d=e.type===O.TESTIM_HEADSPIN?"headspin":"tdc",m=pI(r,o==null?void 0:o.mobile);if(!(0,Zy.isEmpty)(m)){let u=Object.entries(m).map(([f,g])=>g.split(",").map(h=>h===".*"||h==="="?"":`${f}:${h}`).join(",")).join(" ").trim();l[`${d}:selector`]=u}}let c=e.type===O.TESTIM_TVC?{alwaysMatch:l}:l;return{...a,desiredCapabilities:l,capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function sb(s){var g,h;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;lp({nativeAppMetadata:r,appPath:o,gridInfo:t}),rI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((h=(g=l.mobile)==null?void 0:g.staticAllocation)==null?void 0:h.deviceUdid),m=await vt.getGridDirectConnection(t,d),f=eb({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 nb(s){return lp(s),tb(s)}function ob(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 Zy,tI,dp=T(()=>{"use strict";fe();ae();pa();Zy=require("lodash");B();le();tI=[O.BROWSERSTACK,O.SAUCELABS,O.TESTIM_HEADSPIN,O.TESTIM_TDC,O.TESTIM_TVC,O.P_CLOUDY]});var fa,ab=T(()=>{"use strict";fa=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 ga,cb=T(()=>{"use strict";ga=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 mp,ha,lb=T(()=>{"use strict";j();mp=x("mobile-frame-locator-mock"),ha=class{foundFrameCallback(){return mp.info("foundFrameCallback-mock invoked"),{}}locate(){return mp.info("locate-mock invoked"),{}}async findFrame(){return mp.info("findFrame-mock invoked"),{}}}});var dI,pb,ub,xs,fp=T(()=>{"use strict";dI=v(require("webdriverio")),pb=require("@applitools/eyes-sdk-core");ab();Qu();j();cb();Zu();Te();np();lb();op();ub=x("appium-test-player"),xs=class{constructor(e,t,r,n=dI,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=se(),m=new ga(this.driver);this.stepActionFactory=new c(m),la(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Rs(Bi()),this.sessionPlayer=new a(e,{tabService:new fa,cookieUtils:void 0,FrameLocator:ha,portSelector:Ui,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:pb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=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{await(n==null?void 0:n.endSession()),ub.info("appium session deleted",o)}catch(i){ub.error("error while deleting appium session",{...o,error:i})}finally{let{commonConstants:i}=se();e.off(i.playback.RESULT),this.sessionPlayer=null,this.stepActionFactory=null,this.driver=null}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function mI(s){return await Ee(`${s}/api/status`)}async function db(s,e){return await Ee(`${s}/api/devices/${e}/status`)}async function mb(s){if((await mI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var fb=T(()=>{"use strict";Ke()});var gb={};V(gb,{WorkerLocalTma:()=>bp});var ya,gp,hp,yp,bp,hb=T(()=>{"use strict";Ke();dp();Ln();B();j();Ot();fp();Te();fb();pa();ya=x("worker-appium"),gp=class extends Error{},hp=class extends Error{},yp=class extends Error{},bp=class extends at{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new xs(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}=se(),{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 R;if(Q.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:i,deviceUdid:a,projectData:l}=this.options;await mb(i);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{executionId:k,testResultId:_}=t,{mobileApp:$}=await vt.getMobileAppDataByAppId({appId:f,projectId:c,token:d,executionId:k,testResultId:_});t.nativeApp=$}let g=u==="android"?t.androidActivityWait:null,h=t.nativeAppMetadata,y=t.downloadableAppPublicLink,E=t.appPackageNameOrBundleId;if(!h)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!E)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:I,version:b},w]=await Promise.all([this.getAppStateFromDevice(i,a,E),db(i,a)]).catch(k=>{throw this.handleDeviceNotFoundError(k),k});if(!I&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!I&&y&&await this.installApp(i,a,y);try{let k={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(R=this.options.projectData)==null?void 0:R.name}-${this.options.project}`},_=nb({projectType:u,nativeAppMetadata:h,appPath:y,androidActivityWait:g,sessionTags:k,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),$={capabilities:{udid:a,..._}},S=await this.requestNewAppiumSessionFromTma(i,$,h);this.sessionData=S;let A=await m.attach({sessionId:S.sessionId,capabilities:_});this.device=await vt.updateTmaDeviceDetails(a,this.options,t),ya.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:A.sessionId,testResultId:this.testResultId,nativeAppMetadata:h,sessionCaps:A.capabilities})}catch(k){throw ya.error("failed to start application",{err:k}),k}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await Ge({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"}}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 yp(l):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,l=(await Ee(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 Nt(n);await Ws(`${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 hp(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 gp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=se(),{sessionPlayer:i}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),o.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{i.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await o.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw ya.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw ya.error("failed to run test once",{err:c}),c}}}});var bb={};V(bb,{WorkerAppium:()=>Tp});var yb,As,Tp,Tb=T(()=>{"use strict";dp();yb=require("linkedom");Ln();j();Ot();fp();Te();pa();ae();ls();As=x("worker-appium"),Tp=class extends at{initPlayer(t){return new xs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,l=await vt.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},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 vt.lockDevice(o,this.options.deviceUdid),f=await sb(u)):f=rb(u),As.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:ob(f)}),this.activeSession=await i.remote(f),this.device=await vt.updateDeviceOnRemoteTestResult(t,this.activeSession,this.options);let g=`${this.getServerAddressFromGrid()}/session/${this.activeSession.sessionId}`;this.updateSlotData(g),As.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw As.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}updateSlotData(t){try{this.options.slotService==="redis"&&qf(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){As.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===O.TESTIM_HEADSPIN||o===O.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:o===O.TESTIM_TVC?`https://${t}/wd/hub`:o===O.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:o,directConnectPath:i}=t;if(r&&n&&o&&i)return`${r}://${n}:${o}${i}`}async runTestOnce(t,r){var u,f;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=se(),{sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let c;if(this.options.skipLoadBalancer){let g=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:h,hostname:y,port:E,path:I}=await vt.getHeadSpinDeviceConnection(this.options.gridData,g);c=`${h}://${y}:${E}${I}`}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,yb.DOMParser),i.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let g=await new Promise((y,E)=>{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(E)});return await i.drain(),g.stepsResults=null,g.resultId=this.testResultId,{...g,...t.seleniumPerfStats.getStats()}}catch(g){throw As.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:g}),g}};try{return await super.runTestOnce(t,r),await m()}catch(g){throw As.error("failed to run test once",{err:g}),g}}}});var ba,wb=T(()=>{"use strict";B();Pn();q();ba=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 vb,Ta,Eb=T(()=>{"use strict";vb=v(require("ws"));B();Ta=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new vb.default(this._cdpUrl,{timeout:e}),r=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 va,wp,wa,Sb=T(()=>{"use strict";B();va=v(require("chrome-launcher"));Ru();Eb();un();wp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Ta}async init(e){var u,f,g,h;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l}=e,c=wi({browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l}),d=[...((u=c.desiredCapabilities)==null?void 0:u.chromeOptions.args)??[],...((h=(g=(f=c.capabilities)==null?void 0:f.alwaysMatch)==null?void 0:g["goog:chromeOptions"])==null?void 0:h.args)??[],...va.Launcher.defaultFlags().filter(y=>y!=="--disable-extensions")];this.chrome=await va.launch({chromeFlags:d,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let m=await br(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(m),rs(()=>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}},wa=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new wp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Rb={};V(Rb,{WorkerExtension:()=>jn});function fI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Ib(s){return fI(s)?s:new Error(s)}var ct,jn,vp=T(()=>{"use strict";$e();q();Ln();B();j();Ot();ae();wb();Sb();ct=x("worker-ext"),jn=class extends at{initPlayer(){return this.options.useChromeLauncher?new wa(this.id):new ba(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})}catch(a){throw ct.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var o;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((o=this.options.browserstack)!=null&&o["browserstack.user"])){let i={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(i)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:o}=this;N("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,Fe.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ne))throw u;return ct.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 ct.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(N("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(g){throw ct.warn("failed to run test via CDP",{err:g}),g}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let g=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,g,u),l(u)]),this.options.testStartTimeout,Fe.TEST_START_TIMEOUT_MSG)}catch(E){if(!(E instanceof ne))throw E;ct.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let h=new AbortController,y=E=>{e.onCompletedCleanup(),ct.warn("on browser closed error detected",{err:E,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),E.type=Hs.BROWSER_CLOSED,h.abort(E)};m.registerToClosedBrowser(y);try{let E=ce(e.onCompleted(),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG),I=await Ya(E,h.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(I.success),I.reason)}catch(R){ct.error("Could not update the grid about the test status",{err:R})}m.isAlive()||(ct.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(ct.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.keepAliveIssue=b),{...I,...e.seleniumPerfStats.getStats()}}catch(E){throw ct.warn("timeout wait until test completed",{err:E,testResultId:r,executionId:n,testId:o}),Ib(E)}finally{m.unregisterToClosedBrowser(y)}}catch(g){throw ct.warn("failed to start url",{err:g}),Ib(g)}};t.driver.start();try{return await super.runTestOnce(e,t),N("WorkerExtension super.runTestOnce"),await c()}catch(d){throw ct.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var xb={};V(xb,{WorkerExtensionSingleBrowser:()=>Ep});var gI,hI,Ep,Ab=T(()=>{"use strict";$e();B();j();$u();Ot();vp();gI=x("base-worker"),hI=500,Ep=class extends jn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await On(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,o){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,o)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(gI.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;N("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(hI)}}});function yI(s,e){e===0?s():setTimeout(s,e*Qp)}var Sp,Ea,Cb=T(()=>{"use strict";Pn();le();$e();fu();Ct();ku();q();j();ae();Ih();Sp=x("parallel-worker-manager"),Ea=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Y.SELENIUM:return(Xy(),he(Yy)).WorkerSelenium;case Y.APPIUM:return e.localTmaUrl?(hb(),he(gb)).WorkerLocalTma:(Tb(),he(bb)).WorkerAppium;default:return Ei.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Ab(),he(xb)).WorkerExtensionSingleBrowser:(vp(),he(Rb)).WorkerExtension}}createWorkers(e,t,...r){let n=r[0],o=this.getWorkerType(n),i=()=>{try{return N("before new Worker",n.mode),new o(t,...r)}finally{N("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=>new Promise(g=>{var lt,dr,P,D,F,z,ut,Ca;let h=o.project,y=new Pi(r,n,e,o,i,t),E={},I=e.length,b=((lt=o.company)==null?void 0:lt.ucid)||"",w=(dr=o.company)==null?void 0:dr.companyId,R=(P=o.company)==null?void 0:P.name,k=o.source||"cli",_=o.user,$=(D=o.company)==null?void 0:D.planType,S=(F=o.company)==null?void 0:F.isStartUp,A=(z=o.projectData)==null?void 0:z.name,L=(ut=o.projectData)==null?void 0:ut.type,U=o.lightweightMode,J=(Ca=o.gridData)==null?void 0:Ca.type,H=(Lt,pt,be,Pa,Wn,ka)=>(m++,ig({executionId:r,projectId:h,testId:pt,resultId:be,ucid:b,companyId:w,companyName:R,projectName:A,companyPlan:$,source:k,user:_,lightweightMode:U,isStartUp:S,projectType:L,appSource:ka,gridType:J}),t.testStartAndReport(Lt,r,be,Pa,Wn)),X=async(Lt,pt,be,Pa,Wn,ka)=>{var Mp,Np,Up;m--;let et={...(U==null?void 0:U.onlyTestIdsNoSuite)&&{show:!0},...be.seleniumStats&&{seleniumStats:be.seleniumStats},...be.gridIssues&&{gridIssues:be.gridIssues},...be.keepAliveIssue&&{keepAliveIssue:be.keepAliveIssue},...o.host&&{gridHost:o.host}};if(be.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(be.seleniumPerfMarks),delete be.seleniumPerfMarks),o.grid||o.gridId?(et.gridName=o.grid||((Mp=o.gridData)==null?void 0:Mp.name),et.gridType=(Np=o.gridData)==null?void 0:Np.type,et.gridProvider=(Up=o.gridData)==null?void 0:Up.provider):o.localTmaUrl?(et.gridName="local-tma-from-options",et.gridType="local-tma"):o.useLocalChromeDriver?(et.gridName="local-chrome-driver-from-options",et.gridType="local-chrome"):o.useChromeLauncher?(et.gridName="chrome-launcher-from-options",et.gridType="local-chrome"):o.browserstack?et.gridName="browserstack-from-options":o.saucelabs&&(et.gridName="saucelabs-from-options"),await t.testEndAndReport(Lt,be,r,Pa,Wn,et).catch(vT=>Sp.error("testEndAndReport threw an error",{err:vT})),Wn)return;E[be.resultId]=be,ag({executionId:r,projectId:h,testId:pt,resultId:be.resultId,result:be,ucid:b,companyId:w,companyName:R,projectName:A,companyPlan:$,source:k,user:_,lightweightMode:U,logger:Sp,isStartUp:S,projectType:L,appSource:ka}),c&&!be.success&&(y.stop(),d=!0),(Object.keys(E).length===I||d&&m===0)&&g(E)},de=(Lt,pt)=>{E[pt.resultId]=pt,t.onTestIgnored(Lt,pt.resultId),m--,(Object.keys(E).length===I||d&&m===0)&&g(E)},Et=(Lt,pt)=>t.onGridSlot(Lt,pt);o.userData={loginData:Object.assign({},jt(),{refreshToken:ko(),authData:jt(),token:f}),projectId:o.project,company:o.company,servicesUrl:me},N("in localStrategy before createWorker"),this.createWorkers(l,y,o,this.customExtensionLocalLocation,r,H,X,Et,de).forEach((Lt,pt)=>{N("before schedule worker.run after createWorkers"),yI(()=>{N("right before worker.run"),Lt.run()},pt)})});try{let f=await Zt(),g=await u(f);if(d)throw new Kt;return g}catch(f){throw Sp.error("failed running parallel workers",{executionId:r,err:f}),f}}}});async function kb(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await qc({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 Ip(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 Rp(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=Pb.difference(qs(s,e),t);if(r.length>0)throw ht("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new C(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Pb,Ob=T(()=>{"use strict";Pb=v(require("lodash"));B();ss();ye();q()});var $n,FL,xp,Ap,Sa,_b=T(()=>{"use strict";$n=v(require("lodash"));B();j();le();ae();$e();as();Xl();fu();ye();Ct();Ot();Cg();q();Cb();Ob();({testRunStatus:FL,CLI_MODE:xp}=Ut),Ap=x("test-plan-runner"),Sa=class{constructor(e){this.startTime=Date.now();this.workerManager=new Ea(e)}async runTestAllPhases(e,t,r,n,o,i,a,l){let c={},d=jt(),m=async()=>{let h=o.beforeParallel||1,y=!0,E=await this.workerManager.runTests(e,l,i,a,o,n,d,h,y);Object.assign(c,E)},u=async()=>{let h=to||o.parallel,y=!1;N("right before this.workerManager.runTests");let E=await this.workerManager.runTests(t,l,i,a,o,n,d,h,y);N("right after this.workerManager.runTests"),Object.assign(c,E)},f=async()=>{let h=o.afterParallel||1,y=!1,E=await this.workerManager.runTests(r,l,i,a,o,n,d,h,y);Object.assign(c,E)};cg({executionId:i,projectId:o.project}),N("right before runBeforeTests");try{return await m(),N("right before runTestPlanTests"),await u(),N("right after runTestPlanTests"),await f(),c}catch(h){if(Ap.error("error running test plan",{err:h}),h instanceof Kt)return l.markAllQueuedTests(i,pe.ABORTED,"aborted",!1);throw h}finally{await g()}async function g(){var y,E,I,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===xp.SELENIUM){let[{getSessionPlayer:w},{makeSDK:R}]=await Promise.all([Promise.resolve().then(()=>(Te(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:k}=w();await k.closeBatch(i,R);return}let h;try{if(!((b=(I=(E=o.company)==null?void 0:E.activePlan)==null?void 0:I.premiumFeatures)!=null&&b.applitools)||(h=await ll(o.project),$n.default.isEmpty(h)||!i))return;let{runKey:w,url:R}=h;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:R,apiKey:w}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,l){var b,w,R;let c=re(),d=n.project;Ha(c),e.forEach(k=>Object.assign(k,{isBeforeTestPlan:!0})),r.forEach(k=>Object.assign(k,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Ti(m,n,i,a),f=$n.default.chain(m).map(k=>{var _;return((_=k.overrideTestConfig)==null?void 0:_.name)||""}).uniq().compact().value(),g=(f==null?void 0:f.length)===1?f[0]:null,h=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(k=>k.name),y=(w=n.lightweightMode)!=null&&w.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,o,h);N("before testListInfoPromise");let E=await y;(R=n.lightweightMode)!=null&&R.onlyTestIdsNoSuite||Q.onTestPlanStarted(E.beforeTests,E.tests,E.afterTests,o,c,l,g),N("before runTestAllPhases");let I=await this.runTestAllPhases(E.beforeTests,E.tests,E.afterTests,a,n,c,o||"All Tests",u);return N("before executionEnd"),await u.executionEnd(c),N("after executionEnd"),{results:I,executionId:c,testPlanName:o,configName:g}}async runTestPlans(e,t){Ap.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function r(d){return $n.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await Hc(i,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==xp.APPIUM&&await Rp(e,r(c)),await ie(l,async d=>{var g;let m=d.testPlanId;n[m]={};let u=Object.assign({},e);u.baseUrl||=d.startUrl,u.appId||=((g=d.mobileApp)==null?void 0:g.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await Bf(e,d);let f=u.overrideExecutionName||d.name;return await ie(c[m],async h=>{let y=await this.runTestPlan(h.beforeTests,h.tests,h.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let E=Object.keys(n[m]).map(R=>({executionId:R,status:Ip(n[m][R])})),I=Object.keys(n[m]).map(R=>n[m][R]).reduce((R,k)=>Object.assign(R,k),{}),b=Ip(I);Object.assign(o,I);let w=b?E[0].executionId:E.find(R=>!R.status).executionId;return await Wc(i,m,{success:b,executions:E,executionId:w}),y})})}async runAnonymousTestPlan(e,t){var a;Ap.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),N("before getSuite");let r=await kb(e,t);if(N("after getSuite"),!((a=r==null?void 0:r.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new C("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new C("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new C("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;return N("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!==xp.APPIUM&&await Rp(e,l),N("right before runTestPlan");let c=await this.runTestPlan([],l,[],e,o,null,t,i);return N("right after runTestPlan"),await Q.onTestPlanFinished(c.results,o,this.startTime,c.executionId,i),c})}async run(e){let t=vn(),r=[];zs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=$n.default.flattenDeep(r);return N("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),N("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var Nb={};V(Nb,{init:()=>FI,run:()=>LI});async function bI(s){let e=s.project,t=await Kc(e);if(t!=null&&t.isExecutionBlocked)throw console.error("You have reached the limit of runs for the billing month, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli"),pn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Us}function TI(s,e){var i,a,l,c,d,m,u;let t=mo(e.activePlan),r=s.parallel;if(t==="free"&&r>Db)throw new C(`The free plan allows only ${Db} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let f=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!f)throw new C("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let g=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.runInTurboMode;s.lightweightMode&&!g&&(console.warn(`
|
|
409
|
-
Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((d=s.gridData)==null?void 0:d.type)===O.TESTIM_TVC){let f=e.tvcLicense.expireAt||1;if(Date.now()>f)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let g=Number(e.tvcLicense.maxParallel);if(r>g)throw new C(`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`)}let n=s.retentionDays;if(!n)return;let o=(u=(m=e.activePlan)==null?void 0:m.premiumFeatures)==null?void 0:u.resultRetention;if(n>o)throw new C(`Retention days (${n}) cannot be greater than the company's retention days (${o}). Run aborted`)}async function
|
|
408
|
+
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Ay(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ea,ta,ky=T(()=>{"use strict";ea=require("url");ue();ta=class extends W{async updateBaseUrl(e){let t=new ea.URL(e),r=new ea.URL(this.context.recordedBaseUrl),n=new ea.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 ra,Oy=T(()=>{"use strict";ue();B();ra=class extends W{async performAction(){await oe(this.step.durationMS||0)}}});var sa,_y=T(()=>{"use strict";ue();sa=class extends W{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Un,Ly=T(()=>{"use strict";ue();Un=class extends W{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 na,Dy=T(()=>{"use strict";ue();na=class extends W{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 My,tp,rp,Ny=T(()=>{"use strict";My=v(require("@applitools/spec-driver-webdriverio"));Xn();Te();tp=class{constructor(){let{EyeSdkBuilder:e}=se(),t=Wp["@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:My.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=se(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},rp=new tp});var Fy,Uy,Fn,By=T(()=>{"use strict";Fy=v(require("lodash"));ue();j();Ny();Uy=x("pixel-validation-step-action"),Fn=class extends W{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 rp.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}),h={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};Fy.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(h,i.applitoolsStepSettings),Uy.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await f.check({settings:h}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){Uy.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await rp.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Is,sp=T(()=>{"use strict";kr();q();Hi();Is=class extends lr{async executeCliCode(){var g,h,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(h=(g=t.company)==null?void 0:g.activePlan)==null?void 0:h.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 hs(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,jy=T(()=>{"use strict";sp();ur=class extends Is{isFailedResult(e){return e===!1}}});var oa,$y=T(()=>{"use strict";sp();oa=class extends Is{isFailedResult(e){return!e}}});var ia,Wy=T(()=>{"use strict";kr();ue();q();ia=class extends W{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await gs(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof Rt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ne?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Dr,Vy=T(()=>{"use strict";ue();Dr=class extends W{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ve,Gy=T(()=>{"use strict";ue();ve=class extends W{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 aa,Hy=T(()=>{"use strict";ue();aa=class extends W{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 ca,qy=T(()=>{"use strict";ue();ca=class extends W{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 KS(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function la(s,e){KS(JS,e),e.registerLocateStepActionUtils(Dn.getUtils(s))}var JS,np=T(()=>{"use strict";Vh();qh();ty();ry();ny();ay();uy();py();dy();gy();hy();yy();wy();Sy();Py();ky();Oy();_y();Ly();Dy();By();jy();$y();Wy();Vy();Gy();Hy();qy();JS={locate:Dn,scroll:ji,mouse:$i,submit:Ki,text:Vi,"special-key":qi,"user-code":qt,"validation-code-step":qt,"wait-for-code-step":qt,"action-code-step":qt,"condition-step":Ss,"skip-code-step":Ss,"element-code-step":Ss,"evaluate-expression":Wi,"text-validation":Nn,"wait-for-text-validation":Nn,"select-option":zi,"drop-file":Xi,"input-file":Zi,hover:Ji,navigation:ta,wheel:Yi,sleep:ra,refresh:sa,"api-validation":Un,"api-action":Un,"api-code-step":qt,"extract-text":na,"simple-ui-verification":Fn,"wait-for-simple-ui-verification":Fn,"cli-validation-download-file":Dr,"cli-wait-for-download-file":Dr,"network-validation-step":Dr,"cli-validation-code-step":ur,"cli-wait-for-code-step":ur,"cli-action-code-step":ur,"cli-api-code-step":ur,"cli-condition-step":oa,"node-package":ia,"email-code-step":qt,"cli-email-code-step":ur,"sfdc-internal-test-step":ca,"sfdc-recorded-step":aa,"sfdc-step-login":ve,"sfdc-step-loginas":ve,"sfdc-step-logout":ve,"sfdc-step-sobjectcreate":ve,"sfdc-step-sobjectdelete":ve,"sfdc-step-findrecord":ve,"sfdc-step-quickaction":ve,"sfdc-step-sobjectedit":ve,"sfdc-step-sobjectvalidate":ve,"sfdc-step-launchapp":ve,"sfdc-step-wait-for-page-load":ve,"sfdc-step-closeconsoletabs":ve,"sfdc-step-relatedlistaction":ve,"sfdc-step-permission-validation":ve,"sfdc-step-convert-lead-to-opportunity":ve,"sfdc-step-quotelineeditor":ve,"sfdc-document-validation":Dr}});var zy,YS,Rs,op=T(()=>{"use strict";zy=["simple-ui-verification","wait-for-simple-ui-verification"],YS=[...zy,"custom-validation","sfdc-internal-test-step","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-wait-for-page-load","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation","sfdc-step-convert-lead-to-opportunity","sfdc-step-quotelineeditor","sfdc-document-validation"],Rs=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=YS.includes(e.stepType)?[r]:t(r);this.resetStepVariables(r,n),e.context.data.maxTotalStepTime=r}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let r=e.context.config.stepTimeout;return zy.includes(e.stepType)&&(r=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(r=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:r}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let r=Date.now()-e.startTimestamp;return t-r}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+1e3}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,r=e.step.type,n=3e4;return r==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),n)}}});var Jy={};V(Jy,{SeleniumTestPlayer:()=>Bn});var Ky,Bn,ip=T(()=>{"use strict";B();Ky=require("@applitools/eyes-sdk-core");Pn();q();Ku();Uh();Qu();Fh();$h();Zu();Te();np();op();Bn=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new Rs(Bi());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=se();this.driver=n??new Pr;let d=new Fi(this.driver);this.stepActionFactory=new c(d),la(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ni(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=jh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new vs(this.driver),FrameLocator:m,portSelector:Ui,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Ky.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=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}=se(),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 Yy={};V(Yy,{WorkerSelenium:()=>ap});function QS(s){let{playback:e}=se().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>N(`Got event ${t}`))}var ua,XS,ap,Xy=T(()=>{"use strict";B();$e();Ln();j();Ot();Ho();ae();qu();q();ip();Te();ua=x("worker-selenium"),XS=1e9,ap=class extends at{initPlayer(t){return new Bn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){N("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ws(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}),N("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),N("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,XS),await this.windowUtils.validatePageIsAvailable(),N("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof It||d||m?new It(`Page '${l}' is not available`):(ua.error("failed to navigate to page",{baseUrl:l,err:c}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:o}=se(),{driver:i,sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),QS(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),o.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await fn(this.options))[this.testId]);let d=async()=>ce(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(f)}),this.testRunTimeout,Fe.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()||(ua.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&&(ua.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let h={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h});i.start(),N("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),N("right after super.runTestOnce in workerSelenium");let u=await d();return N("right after runSeleniumTest"),u}catch(u){throw ua.error("failed to run test once",{err:u}),u}}}});var Qy,He,ZS,eI,cp,vt,pa=T(()=>{"use strict";j();ae();le();ye();Ke();Qy=v(require("ora")),He=x("mobile-grid-service"),ZS="https://tdc.tricentis-cloud.com",eI="https://ui.headspin.io",cp=class{constructor(){this.gridsAppIdGetter={[O.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[O.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[O.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[O.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[O.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[O.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===O.TESTIM_TDC||e===O.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e)?`${t}/lock`:""}getBaseApiUrl(e){return e===O.TESTIM_HEADSPIN?`${id}/devices`:e===O.TESTIM_TDC?`${cd}/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 Ge({url:r,headers:n,body:o})}catch(i){throw He.debug(`error while locking device ${t}`,{error:i}),i.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):i}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e.type)}/device_id:${t}/automation-config`;try{let o=await Ee(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw He.error("error while getting automation config for device",{error:o,deviceId:t}),o}}async getPCloudyAuthToken(e,t){let r=await Vs(`${Ba}/access`,void 0,{Authorization:`Basic ${Buffer.from(`${e}:${t}`).toString("base64")}`});return JSON.parse(r).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,o=new URL(n);return{hostname:o.hostname,port:Number(o.port),protocol:o.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){if(this.isTdcOrHeadSpinGrid(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:`/v0/${e.accessToken}/wd/hub`};if(e.type===O.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===O.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([O.BROWSERSTACK,O.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:o,gridId:i}){var a,l;if(t===O.TESTIM_HEADSPIN||t===O.TESTIM_TDC){let c=await fl({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=c==null?void 0:c[0])==null?void 0:a.name)||e.device}if(t===O.BROWSERSTACK)return(l=e.mobile)==null?void 0:l.version.split("-")[0];if(t===O.SAUCELABS)return e.testobject_device_name;if(t===O.P_CLOUDY){if(e.pCloudy_DeviceFullName){let c=e.pCloudy_DeviceFullName.split("_");return`${c[0]} ${c[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r){var E;let{executionId:n,testId:o,testResultId:i}=e,{project:a,projectData:{type:l}={},company:{companyId:c=""}={},gridData:{gridId:d="",type:m=""}={}}=r,u=t.capabilities,f=await this.getDeviceNameFromSessionCaps({capabilities:u,gridType:m,projectId:a,projectType:l,companyId:c,gridId:d}),g=u.platformVersion;!g&&m===O.BROWSERSTACK&&(g=(E=u.mobile)==null?void 0:E.version.split("-")[1]),!g&&m===O.TESTIM_TVC&&(g=u.os_version);let h={name:f??"",model:u.deviceModel,osVersion:g,udid:u.udid,osType:u.platformName,scaleFactor:u.pixelRatio,isVirtual:m===O.TESTIM_TVC,...m===O.TESTIM_TVC&&{model:u.deviceModel||t.capabilities.device,height:t.capabilities.screen.height,width:t.capabilities.screen.width,scaleFactor:t.capabilities.screen.scale}},y=await this.buildRemoteResultLink(r.gridData,t.sessionId,u);return await Er(a,n,o,i,"RUNNING",{device:h,...y&&{remoteResultLink:y}}),He.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:h,remoteResultLink:y,gridType:m}),h}async buildRemoteResultLink(e,t,r){return e.type===O.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ns}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===O.SAUCELABS?r.testobject_test_report_url:e.type===O.TESTIM_TVC?r.replayUrl:e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC?`${e.type===O.TESTIM_HEADSPIN?eI:ZS}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let t=await Ee(`${md}/devices`),r=t==null?void 0:t.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,resolution:`${r.width}x${r.height}`,geo:"local",manufacturer:r.model,osVersion:r.osVersion,type:r.deviceType||"",osType:r.osType,isLandscape:r.screenMirror.orientation==="LANDSCAPE",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}),He.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 zc({appId:e,projectId:t});if(!i)throw He.error("mobile app not found",{appId:e,projectId:t,executionId:n,testResultId:o}),new Error("mobile app not found");return{appUrl:`${me}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}catch(i){throw He.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/(od*60))+1)*60*1e3,Math.max(nd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let i={[O.BROWSERSTACK]:{name:"Browserstack",appPath:"browserStackAppId"},[O.TESTIM_TVC]:{name:"Mobile Virtual Grid",appPath:"testimTvcAppId"},[O.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,Qy.default)(`uploading app to ${a} please wait..`).start();try{He.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await gl({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}`),He.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:o,mobileAppId:i}){let a=t.get(i);if(a&&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:g=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){He.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:i});let I=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d,executionId:i,testResultId:a});n=I.appUrl,o=I.mobileApp,e.nativeApp=o}else He.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:i}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,y=this.gridsAppIdGetter[f]({testRunHandler:e,mobileApp:o,gridHost:g}),E=f===O.BROWSERSTACK||f===O.TESTIM_TVC||f===O.P_CLOUDY;if(y){let I=t.projectData.type,b=await this.verifyAppStillExistsOnGrid({gridAppId:y,gridData:m,projectType:I});b&&(He.info("app exists on grid, using gridAppId",{gridAppId:y,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=y),!b&&E&&(He.info("app not exists on grid, uploading it",{gridAppId:y,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!b&&!E&&He.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:i})}return!y&&E&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var c,d;let{accessToken:n,user:o,host:i,key:a,type:l}=t;if(l===O.BROWSERSTACK){let m=`${Ns}/recent_apps`;return(await this.fetchWithUserAndPasswordAuth({url:m,user:o,key:a})).some(f=>f.app_url===e)}if(l===O.SAUCELABS){let u=`${i.includes("eu-central-1")?dd:pd}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:o,key:a})).items.some(g=>g.id===e)}if(l===O.TESTIM_HEADSPIN||l===O.TESTIM_TDC){let m=l===O.TESTIM_HEADSPIN?`${ad}/apps`:`${ld}/apps`;return(await this.fetchWithTokenAuth({url:m,accessToken:n,authType:"Bearer"})).apps.some(f=>f.app_id===e)}if(l===O.TESTIM_TVC){let m=`${ud}/versions/${e}/info`,u=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:m,accessToken:u,authType:"Upload-Token"}),!0}catch(f){return f.status!==404&&He.error("error while verifying app exists on TVC",{error:f}),!1}}if(l===O.P_CLOUDY){let m=await this.getPCloudyAuthToken(o,a),u=`${Ba}/drive`,f=await tc({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(h=>h.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 Ee(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r}){let n={Authorization:`${r} ${t}`};return await Ee(e,void 0,n)}},vt=new cp});function lp({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"&&!tI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function rI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==O.TESTIM_TDC&&e.type!==O.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function sI(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 nI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===O.TESTIM_TDC,a=s===O.TESTIM_HEADSPIN,l=i?"tdc":"headspin",c=a&&M.flags.enableBatchHeadSpin.isEnabled(),d=i&&(M.flags.enableBatchTDC.isEnabled()||M.flags.headSpinTdcEnableFlagCapability.isEnabled());return{[`${l}:capture`]:!0,...M.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...o&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:sI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n}}}function da(s){return"id"in s?s.id:s.packageName}function oI(s,e){return{[`${e===O.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function iI({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=oI(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":da(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":da(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function ma({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:o=""}){switch(s){case"ios":return{...e,platformName:"iOS",[`${o}autoAcceptAlerts`]:!0,[`${o}automationName`]:"XCUITest",[`${o}fullReset`]:!0,...t&&{[`${o}bundleId`]:da(t)},...r&&{[`${o}app`]:r}};case"android":return{...e,platformName:"Android",[`${o}autoGrantPermissions`]:!0,[`${o}automationName`]:"UiAutomator2",...n&&{[`${o}appWaitActivity`]:n},...t&&{[`${o}appPackage`]:da(t),[`${o}appActivity`]:t.activity??".*"},...r&&{[`${o}app`]:r}};default:throw Error(`unsupported mobile project ${s}`)}}function eb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=nI(i.type,o,n);return iI({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function up({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 pp({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o}=e,i=r===O.P_CLOUDY;return s||(n!=null&&n.deviceName?i?n.deviceUdid:n.deviceName:o!=null&&o.deviceNameRegex?t==="android"&&o.deviceNameRegex===".*"&&i?ja:o.deviceNameRegex:t==="ios"&&r===O.BROWSERSTACK?"iPhone.*":i?t==="ios"?"apple":ja:".*")}function aI(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 cI({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=aI(o,s),f=up({osVersion:l,mobileConfig:d}),g=pp({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=qe(n.editorUrl,n.project,i.testId,i.testResultId,i.branch),y={device:g,os_version:f,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:externalUrl":h,"waldo:options":{token:u}};return ma({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function lI({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,g=up({osVersion:l,mobileConfig:d}),h=pp({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),y=/^[a-zA-Z]+$/.test(h),E={...g!==".*"&&{pCloudy_DeviceVersion:g},...y&&{pCloudy_DeviceManufacturer:h},...!y&&{pCloudy_DeviceFullName:h}},I={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...E,pCloudy_DurationInMinutes:n.duration?Number(n.duration):fd,pCloudy_ApplicationName:t,newCommandTimeout:120,fullReset:!0};return t="",ma({projectType:s,sessionCaps:I,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function uI(s,e){let t=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]\.\*\)\.\*$/,r=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]\.\*\)\.\*$/,n=e==="android"&&t.test(s),o=e==="ios"&&r.test(s);return n||o}function pI({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=m===O.BROWSERSTACK?"browserstack":"saucelabs",f=up({osVersion:l,mobileConfig:d}),g=pp({deviceName:c,mobileConfig:d,projectType:s,gridType:m});if(uI(f,s)&&m===O.SAUCELABS){let y={appiumVersion:"latest",user:o.user,key:o.key,debug:!0,networkLogs:!0,tags:Object.values(i),name:i.testResultId,build:i.executionId};return ma({projectType:s,sessionCaps:{"appium:platformVersion":f,"appium:deviceName":g,"sauce:options":y},appiumPrefix:"appium:",nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let h={...m===O.BROWSERSTACK&&{os_version:f,device:g,realDevice:!0,project:i.project,buildTags:Object.values(i).join(",")},...m===O.SAUCELABS&&{platformVersion:f,deviceName:g,tags:Object.values(i)},name:i.testResultId,build:i.executionId,[`${u}.user`]:o.user,[`${u}.key`]:o.key,[`${u}.debug`]:!0,[`${u}.networkLogs`]:!0};return ma({projectType:s,sessionCaps:h,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function tb(s){return O.TESTIM_TDC===s.gridInfo.type||O.TESTIM_HEADSPIN===s.gridInfo.type?eb(s):O.TESTIM_TVC===s.gridInfo.type?cI(s):O.P_CLOUDY===s.gridInfo.type?lI(s):pI(s)}function dI(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 rb(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}`);lp({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=vt.getGridConnection(e),l=tb(s);if(e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC){let d=e.type===O.TESTIM_HEADSPIN?"headspin":"tdc",m=dI(r,o==null?void 0:o.mobile);if(!(0,Zy.isEmpty)(m)){let u=Object.entries(m).map(([f,g])=>g.split(",").map(h=>h===".*"||h==="="?"":`${f}:${h}`).join(",")).join(" ").trim();l[`${d}:selector`]=u}}let c=e.type===O.TESTIM_TVC?{alwaysMatch:l}:l;return{...a,desiredCapabilities:l,capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function sb(s){var g,h;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;lp({nativeAppMetadata:r,appPath:o,gridInfo:t}),rI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((h=(g=l.mobile)==null?void 0:g.staticAllocation)==null?void 0:h.deviceUdid),m=await vt.getGridDirectConnection(t,d),f=eb({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 nb(s){return lp(s),tb(s)}function ob(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 Zy,tI,dp=T(()=>{"use strict";fe();ae();pa();Zy=require("lodash");B();le();tI=[O.BROWSERSTACK,O.SAUCELABS,O.TESTIM_HEADSPIN,O.TESTIM_TDC,O.TESTIM_TVC,O.P_CLOUDY]});var fa,ab=T(()=>{"use strict";fa=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 ga,cb=T(()=>{"use strict";ga=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 mp,ha,lb=T(()=>{"use strict";j();mp=x("mobile-frame-locator-mock"),ha=class{foundFrameCallback(){return mp.info("foundFrameCallback-mock invoked"),{}}locate(){return mp.info("locate-mock invoked"),{}}async findFrame(){return mp.info("findFrame-mock invoked"),{}}}});var mI,pb,ub,xs,fp=T(()=>{"use strict";mI=v(require("webdriverio")),pb=require("@applitools/eyes-sdk-core");ab();Qu();j();cb();Zu();Te();np();lb();op();ub=x("appium-test-player"),xs=class{constructor(e,t,r,n=mI,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=se(),m=new ga(this.driver);this.stepActionFactory=new c(m),la(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Rs(Bi()),this.sessionPlayer=new a(e,{tabService:new fa,cookieUtils:void 0,FrameLocator:ha,portSelector:Ui,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:pb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=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{await(n==null?void 0:n.endSession()),ub.info("appium session deleted",o)}catch(i){ub.error("error while deleting appium session",{...o,error:i})}finally{let{commonConstants:i}=se();e.off(i.playback.RESULT),this.sessionPlayer=null,this.stepActionFactory=null,this.driver=null}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function fI(s){return await Ee(`${s}/api/status`)}async function db(s,e){return await Ee(`${s}/api/devices/${e}/status`)}async function mb(s){if((await fI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var fb=T(()=>{"use strict";Ke()});var gb={};V(gb,{WorkerLocalTma:()=>bp});var ya,gp,hp,yp,bp,hb=T(()=>{"use strict";Ke();dp();Ln();B();j();Ot();fp();Te();fb();pa();ya=x("worker-appium"),gp=class extends Error{},hp=class extends Error{},yp=class extends Error{},bp=class extends at{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new xs(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}=se(),{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 R;if(Q.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:i,deviceUdid:a,projectData:l}=this.options;await mb(i);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{executionId:k,testResultId:_}=t,{mobileApp:$}=await vt.getMobileAppDataByAppId({appId:f,projectId:c,token:d,executionId:k,testResultId:_});t.nativeApp=$}let g=u==="android"?t.androidActivityWait:null,h=t.nativeAppMetadata,y=t.downloadableAppPublicLink,E=t.appPackageNameOrBundleId;if(!h)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!E)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:I,version:b},w]=await Promise.all([this.getAppStateFromDevice(i,a,E),db(i,a)]).catch(k=>{throw this.handleDeviceNotFoundError(k),k});if(!I&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!I&&y&&await this.installApp(i,a,y);try{let k={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(R=this.options.projectData)==null?void 0:R.name}-${this.options.project}`},_=nb({projectType:u,nativeAppMetadata:h,appPath:y,androidActivityWait:g,sessionTags:k,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),$={capabilities:{udid:a,..._}},S=await this.requestNewAppiumSessionFromTma(i,$,h);this.sessionData=S;let A=await m.attach({sessionId:S.sessionId,capabilities:_});this.device=await vt.updateTmaDeviceDetails(a,this.options,t),ya.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:A.sessionId,testResultId:this.testResultId,nativeAppMetadata:h,sessionCaps:A.capabilities})}catch(k){throw ya.error("failed to start application",{err:k}),k}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await Ge({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"}}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 yp(l):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,l=(await Ee(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 Nt(n);await Ws(`${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 hp(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 gp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=se(),{sessionPlayer:i}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),o.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{i.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await o.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw ya.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw ya.error("failed to run test once",{err:c}),c}}}});var bb={};V(bb,{WorkerAppium:()=>Tp});var yb,As,Tp,Tb=T(()=>{"use strict";dp();yb=require("linkedom");Ln();j();Ot();fp();Te();pa();ae();ls();As=x("worker-appium"),Tp=class extends at{initPlayer(t){return new xs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,l=await vt.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},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 vt.lockDevice(o,this.options.deviceUdid),f=await sb(u)):f=rb(u),As.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:ob(f)}),this.activeSession=await i.remote(f),this.device=await vt.updateDeviceOnRemoteTestResult(t,this.activeSession,this.options);let g=`${this.getServerAddressFromGrid()}/session/${this.activeSession.sessionId}`;this.updateSlotData(g),As.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw As.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}updateSlotData(t){try{this.options.slotService==="redis"&&qf(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){As.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===O.TESTIM_HEADSPIN||o===O.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:o===O.TESTIM_TVC?`https://${t}/wd/hub`:o===O.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:o,directConnectPath:i}=t;if(r&&n&&o&&i)return`${r}://${n}:${o}${i}`}async runTestOnce(t,r){var u,f;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=se(),{sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let c;if(this.options.skipLoadBalancer){let g=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:h,hostname:y,port:E,path:I}=await vt.getHeadSpinDeviceConnection(this.options.gridData,g);c=`${h}://${y}:${E}${I}`}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,yb.DOMParser),i.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let g=await new Promise((y,E)=>{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(E)});return await i.drain(),g.stepsResults=null,g.resultId=this.testResultId,{...g,...t.seleniumPerfStats.getStats()}}catch(g){throw As.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:g}),g}};try{return await super.runTestOnce(t,r),await m()}catch(g){throw As.error("failed to run test once",{err:g}),g}}}});var ba,wb=T(()=>{"use strict";B();Pn();q();ba=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 vb,Ta,Eb=T(()=>{"use strict";vb=v(require("ws"));B();Ta=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new vb.default(this._cdpUrl,{timeout:e}),r=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 va,wp,wa,Sb=T(()=>{"use strict";B();va=v(require("chrome-launcher"));Ru();Eb();un();wp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Ta}async init(e){var u,f,g,h;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l}=e,c=wi({browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l}),d=[...((u=c.desiredCapabilities)==null?void 0:u.chromeOptions.args)??[],...((h=(g=(f=c.capabilities)==null?void 0:f.alwaysMatch)==null?void 0:g["goog:chromeOptions"])==null?void 0:h.args)??[],...va.Launcher.defaultFlags().filter(y=>y!=="--disable-extensions")];this.chrome=await va.launch({chromeFlags:d,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let m=await br(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(m),rs(()=>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}},wa=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new wp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Rb={};V(Rb,{WorkerExtension:()=>jn});function gI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Ib(s){return gI(s)?s:new Error(s)}var ct,jn,vp=T(()=>{"use strict";$e();q();Ln();B();j();Ot();ae();wb();Sb();ct=x("worker-ext"),jn=class extends at{initPlayer(){return this.options.useChromeLauncher?new wa(this.id):new ba(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})}catch(a){throw ct.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var o;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((o=this.options.browserstack)!=null&&o["browserstack.user"])){let i={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(i)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:o}=this;N("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,Fe.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ne))throw u;return ct.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 ct.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(N("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(g){throw ct.warn("failed to run test via CDP",{err:g}),g}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let g=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,g,u),l(u)]),this.options.testStartTimeout,Fe.TEST_START_TIMEOUT_MSG)}catch(E){if(!(E instanceof ne))throw E;ct.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let h=new AbortController,y=E=>{e.onCompletedCleanup(),ct.warn("on browser closed error detected",{err:E,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),E.type=Hs.BROWSER_CLOSED,h.abort(E)};m.registerToClosedBrowser(y);try{let E=ce(e.onCompleted(),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG),I=await Ya(E,h.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(I.success),I.reason)}catch(R){ct.error("Could not update the grid about the test status",{err:R})}m.isAlive()||(ct.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(ct.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.keepAliveIssue=b),{...I,...e.seleniumPerfStats.getStats()}}catch(E){throw ct.warn("timeout wait until test completed",{err:E,testResultId:r,executionId:n,testId:o}),Ib(E)}finally{m.unregisterToClosedBrowser(y)}}catch(g){throw ct.warn("failed to start url",{err:g}),Ib(g)}};t.driver.start();try{return await super.runTestOnce(e,t),N("WorkerExtension super.runTestOnce"),await c()}catch(d){throw ct.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var xb={};V(xb,{WorkerExtensionSingleBrowser:()=>Ep});var hI,yI,Ep,Ab=T(()=>{"use strict";$e();B();j();$u();Ot();vp();hI=x("base-worker"),yI=500,Ep=class extends jn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await On(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,o){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,o)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(hI.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;N("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(yI)}}});function bI(s,e){e===0?s():setTimeout(s,e*Qp)}var Sp,Ea,Cb=T(()=>{"use strict";Pn();le();$e();fu();Ct();ku();q();j();ae();Ih();Sp=x("parallel-worker-manager"),Ea=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Y.SELENIUM:return(Xy(),he(Yy)).WorkerSelenium;case Y.APPIUM:return e.localTmaUrl?(hb(),he(gb)).WorkerLocalTma:(Tb(),he(bb)).WorkerAppium;default:return Ei.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Ab(),he(xb)).WorkerExtensionSingleBrowser:(vp(),he(Rb)).WorkerExtension}}createWorkers(e,t,...r){let n=r[0],o=this.getWorkerType(n),i=()=>{try{return N("before new Worker",n.mode),new o(t,...r)}finally{N("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=>new Promise(g=>{var lt,dr,P,D,F,z,ut,Ca;let h=o.project,y=new Pi(r,n,e,o,i,t),E={},I=e.length,b=((lt=o.company)==null?void 0:lt.ucid)||"",w=(dr=o.company)==null?void 0:dr.companyId,R=(P=o.company)==null?void 0:P.name,k=o.source||"cli",_=o.user,$=(D=o.company)==null?void 0:D.planType,S=(F=o.company)==null?void 0:F.isStartUp,A=(z=o.projectData)==null?void 0:z.name,L=(ut=o.projectData)==null?void 0:ut.type,U=o.lightweightMode,J=(Ca=o.gridData)==null?void 0:Ca.type,H=(Lt,pt,be,Pa,Wn,ka)=>(m++,ig({executionId:r,projectId:h,testId:pt,resultId:be,ucid:b,companyId:w,companyName:R,projectName:A,companyPlan:$,source:k,user:_,lightweightMode:U,isStartUp:S,projectType:L,appSource:ka,gridType:J}),t.testStartAndReport(Lt,r,be,Pa,Wn)),X=async(Lt,pt,be,Pa,Wn,ka)=>{var Mp,Np,Up;m--;let et={...(U==null?void 0:U.onlyTestIdsNoSuite)&&{show:!0},...be.seleniumStats&&{seleniumStats:be.seleniumStats},...be.gridIssues&&{gridIssues:be.gridIssues},...be.keepAliveIssue&&{keepAliveIssue:be.keepAliveIssue},...o.host&&{gridHost:o.host}};if(be.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(be.seleniumPerfMarks),delete be.seleniumPerfMarks),o.grid||o.gridId?(et.gridName=o.grid||((Mp=o.gridData)==null?void 0:Mp.name),et.gridType=(Np=o.gridData)==null?void 0:Np.type,et.gridProvider=(Up=o.gridData)==null?void 0:Up.provider):o.localTmaUrl?(et.gridName="local-tma-from-options",et.gridType="local-tma"):o.useLocalChromeDriver?(et.gridName="local-chrome-driver-from-options",et.gridType="local-chrome"):o.useChromeLauncher?(et.gridName="chrome-launcher-from-options",et.gridType="local-chrome"):o.browserstack?et.gridName="browserstack-from-options":o.saucelabs&&(et.gridName="saucelabs-from-options"),await t.testEndAndReport(Lt,be,r,Pa,Wn,et).catch(vT=>Sp.error("testEndAndReport threw an error",{err:vT})),Wn)return;E[be.resultId]=be,ag({executionId:r,projectId:h,testId:pt,resultId:be.resultId,result:be,ucid:b,companyId:w,companyName:R,projectName:A,companyPlan:$,source:k,user:_,lightweightMode:U,logger:Sp,isStartUp:S,projectType:L,appSource:ka}),c&&!be.success&&(y.stop(),d=!0),(Object.keys(E).length===I||d&&m===0)&&g(E)},de=(Lt,pt)=>{E[pt.resultId]=pt,t.onTestIgnored(Lt,pt.resultId),m--,(Object.keys(E).length===I||d&&m===0)&&g(E)},Et=(Lt,pt)=>t.onGridSlot(Lt,pt);o.userData={loginData:Object.assign({},jt(),{refreshToken:ko(),authData:jt(),token:f}),projectId:o.project,company:o.company,servicesUrl:me},N("in localStrategy before createWorker"),this.createWorkers(l,y,o,this.customExtensionLocalLocation,r,H,X,Et,de).forEach((Lt,pt)=>{N("before schedule worker.run after createWorkers"),bI(()=>{N("right before worker.run"),Lt.run()},pt)})});try{let f=await Zt(),g=await u(f);if(d)throw new Kt;return g}catch(f){throw Sp.error("failed running parallel workers",{executionId:r,err:f}),f}}}});async function kb(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await qc({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 Ip(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 Rp(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=Pb.difference(qs(s,e),t);if(r.length>0)throw ht("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new C(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Pb,Ob=T(()=>{"use strict";Pb=v(require("lodash"));B();ss();ye();q()});var $n,BL,xp,Ap,Sa,_b=T(()=>{"use strict";$n=v(require("lodash"));B();j();le();ae();$e();as();Xl();fu();ye();Ct();Ot();Cg();q();Cb();Ob();({testRunStatus:BL,CLI_MODE:xp}=Ut),Ap=x("test-plan-runner"),Sa=class{constructor(e){this.startTime=Date.now();this.workerManager=new Ea(e)}async runTestAllPhases(e,t,r,n,o,i,a,l){let c={},d=jt(),m=async()=>{let h=o.beforeParallel||1,y=!0,E=await this.workerManager.runTests(e,l,i,a,o,n,d,h,y);Object.assign(c,E)},u=async()=>{let h=to||o.parallel,y=!1;N("right before this.workerManager.runTests");let E=await this.workerManager.runTests(t,l,i,a,o,n,d,h,y);N("right after this.workerManager.runTests"),Object.assign(c,E)},f=async()=>{let h=o.afterParallel||1,y=!1,E=await this.workerManager.runTests(r,l,i,a,o,n,d,h,y);Object.assign(c,E)};cg({executionId:i,projectId:o.project}),N("right before runBeforeTests");try{return await m(),N("right before runTestPlanTests"),await u(),N("right after runTestPlanTests"),await f(),c}catch(h){if(Ap.error("error running test plan",{err:h}),h instanceof Kt)return l.markAllQueuedTests(i,pe.ABORTED,"aborted",!1);throw h}finally{await g()}async function g(){var y,E,I,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===xp.SELENIUM){let[{getSessionPlayer:w},{makeSDK:R}]=await Promise.all([Promise.resolve().then(()=>(Te(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:k}=w();await k.closeBatch(i,R);return}let h;try{if(!((b=(I=(E=o.company)==null?void 0:E.activePlan)==null?void 0:I.premiumFeatures)!=null&&b.applitools)||(h=await ll(o.project),$n.default.isEmpty(h)||!i))return;let{runKey:w,url:R}=h;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:R,apiKey:w}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,l){var b,w,R;let c=re(),d=n.project;Ha(c),e.forEach(k=>Object.assign(k,{isBeforeTestPlan:!0})),r.forEach(k=>Object.assign(k,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Ti(m,n,i,a),f=$n.default.chain(m).map(k=>{var _;return((_=k.overrideTestConfig)==null?void 0:_.name)||""}).uniq().compact().value(),g=(f==null?void 0:f.length)===1?f[0]:null,h=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(k=>k.name),y=(w=n.lightweightMode)!=null&&w.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,o,h);N("before testListInfoPromise");let E=await y;(R=n.lightweightMode)!=null&&R.onlyTestIdsNoSuite||Q.onTestPlanStarted(E.beforeTests,E.tests,E.afterTests,o,c,l,g),N("before runTestAllPhases");let I=await this.runTestAllPhases(E.beforeTests,E.tests,E.afterTests,a,n,c,o||"All Tests",u);return N("before executionEnd"),await u.executionEnd(c),N("after executionEnd"),{results:I,executionId:c,testPlanName:o,configName:g}}async runTestPlans(e,t){Ap.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function r(d){return $n.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await Hc(i,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==xp.APPIUM&&await Rp(e,r(c)),await ie(l,async d=>{var g;let m=d.testPlanId;n[m]={};let u=Object.assign({},e);u.baseUrl||=d.startUrl,u.appId||=((g=d.mobileApp)==null?void 0:g.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await Bf(e,d);let f=u.overrideExecutionName||d.name;return await ie(c[m],async h=>{let y=await this.runTestPlan(h.beforeTests,h.tests,h.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let E=Object.keys(n[m]).map(R=>({executionId:R,status:Ip(n[m][R])})),I=Object.keys(n[m]).map(R=>n[m][R]).reduce((R,k)=>Object.assign(R,k),{}),b=Ip(I);Object.assign(o,I);let w=b?E[0].executionId:E.find(R=>!R.status).executionId;return await Wc(i,m,{success:b,executions:E,executionId:w}),y})})}async runAnonymousTestPlan(e,t){var a;Ap.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),N("before getSuite");let r=await kb(e,t);if(N("after getSuite"),!((a=r==null?void 0:r.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new C("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new C("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new C("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;return N("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!==xp.APPIUM&&await Rp(e,l),N("right before runTestPlan");let c=await this.runTestPlan([],l,[],e,o,null,t,i);return N("right after runTestPlan"),await Q.onTestPlanFinished(c.results,o,this.startTime,c.executionId,i),c})}async run(e){let t=vn(),r=[];zs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=$n.default.flattenDeep(r);return N("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),N("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var Nb={};V(Nb,{init:()=>BI,run:()=>DI});async function TI(s){let e=s.project,t=await Kc(e);if(t!=null&&t.isExecutionBlocked)throw console.error("You have reached the limit of runs for the billing month, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli"),pn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Us}function wI(s,e){var i,a,l,c,d,m,u;let t=mo(e.activePlan),r=s.parallel;if(t==="free"&&r>Db)throw new C(`The free plan allows only ${Db} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let f=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!f)throw new C("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let g=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.runInTurboMode;s.lightweightMode&&!g&&(console.warn(`
|
|
409
|
+
Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((d=s.gridData)==null?void 0:d.type)===O.TESTIM_TVC){let f=e.tvcLicense.expireAt||1;if(Date.now()>f)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let g=Number(e.tvcLicense.maxParallel);if(r>g)throw new C(`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`)}let n=s.retentionDays;if(!n)return;let o=(u=(m=e.activePlan)==null?void 0:m.premiumFeatures)==null?void 0:u.resultRetention;if(n>o)throw new C(`Retention days (${n}) cannot be greater than the company's retention days (${o}). Run aborted`)}async function vI(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await TI(s)}catch(t){if([C,Us].some(r=>t instanceof r))throw t;Cp.error("could not validate cli account",{err:t})}}function EI(s){let e=jt();return zm({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function SI(s,{disableResults:e=!1,disableRemoteStep:t=!1,maxNumberOfListeners:r}){if(M.flags.useNewWSCLI.isEnabled()&&!e&&!t)return Tt.connect(s);if(!t){let{remoteStepService:n}=await Promise.resolve().then(()=>(xi(),fh));await n.init(s)}if(!e){let{testResultService:n}=await Promise.resolve().then(()=>(Ai(),yh));n.init(s,r)}}function II(s,e){let{branch:t,autoDetect:r}=s;if(zf(e,r),!e&&!r)throw new C(`branch ${t} does not exist, run aborted.`)}async function RI(s){let{project:e}=s,t=vn();Mb.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")&&(s.sfdcCredential=await jc({projectId:e,branch:t}))}function xI(s,e){let{onprem:t,id:r,storageBaseUrl:n,storageType:o,name:i,activePlan:a={}}=e;if(t){let{mode:m,extensionPath:u,ext:f,playerPath:g}=s;if([Y.SELENIUM].includes(m)&&!g)throw new C("in selenium on prem mode --player-path must be provided");if(m==="extension"&&!u&&!f)throw new C("In extension on prem mode --ext or --extension-path must be provided")}let l=Boolean(a.isPoc),c=Boolean(a.isStartUp),d=mo(a);d==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<Lb?Lb:s.newBrowserWaitTimeout),M.setCompanyId(r),M.setIsPOC(l),M.setIsStartUp(c),M.setPlanType(d),kt.setPlanType(d),s.company={ucid:"",companyId:r,onprem:t,storageBaseUrl:n,storageType:o,name:i,planType:d,isPOC:l,isStartUp:c,activePlan:a}}function AI(s,e){s.editorUrl=Ms||e.editorUrl}function CI(s,e){s.allGrids=e}function PI(s,e){s.authData=e}function kI(s,e){let{id:t,name:r,type:n,defaults:o}=e;M.setProjectId(t),M.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:o}}async function OI(s){s.gridData=await jf(s)}async function _I(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(ht("user-override-file",t),s.mockNetworkRules=await Lm(s.overrideMappingFile))}async function LI(s,e){N("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:o}=s;r||(s.source=n||o?"cli-local":"cli"),await hf(),N("in runner.js after checkNpmVersion"),await vI(s),N("in runRunner before tunnel.connect"),await Zo(s),N("in runRunner after tunnel.connect");let a=await new Sa(e).run(s);return N("before tunnel.disconnect"),await ei(s),await UI(s.slotService,t,s.company.companyId),N("after tunnel.disconnect and gridService.keepAlive.end"),a}function MI(s){var e;kt.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
|
|
410
410
|
\x1B[4m\x1B[36mOur Free grid offers basic service performance.
|
|
411
411
|
If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m
|
|
412
|
-
`)}function
|
|
413
|
-
Turbo mode will ignore step delays. Test artifacts like screenshots and logs will only be saved for failed runs. For more information see our docs: https://help.testim.io/docs/turbo-mode`),
|
|
412
|
+
`)}function NI(s,e,t){s==="redis"&&Tn.start(t,e),s==="mongo"&&yn.start(e)}async function UI(s,e,t){s==="redis"&&await Tn.end(t,e),s==="mongo"&&await yn.end(e)}function FI(s,e){var o,i,a,l,c,d;let t=M.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&&((d=e.mobile)!=null&&d.useRedisSlotManager)&&(s.slotService="redis")}async function BI(s){var h,y,E;N("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:o,parallel:i}=s,a=SI(e,{disableResults:o||Boolean((t==null?void 0:t.disableResults)&&(r||n!=="extension")),disableRemoteStep:o||Boolean(t==null?void 0:t.disableRemoteStep),maxNumberOfListeners:i||1});a.catch(()=>{});let{authData:l,editorConfig:c,companyByProjectId:d,projectById:m,branchName:u,allGrids:f}=await cn(s);if(await a,N("after featureFlagsReady and socketConnected"),AI(s,c),xI(s,d),kI(s,m),II(s,u),CI(s,f),PI(s,l),await RI(s),await OI(s),wI(s,d),FI(s,d),M.flags.clearRunnerFileCache.isEnabled())try{await Jr(),Cp.info("runner file cache cleared")}catch(I){Cp.error("failed to clear runner file cache",{err:I})}(h=s.lightweightMode)!=null&&h.disableLabs||await Ei.loadLabFeatures(m.id,d.activePlan),((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&(M.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((E=s.lightweightMode)==null?void 0:E.type)==="turboMode"&&console.log(`
|
|
413
|
+
Turbo mode will ignore step delays. Test artifacts like screenshots and logs will only be saved for failed runs. For more information see our docs: https://help.testim.io/docs/turbo-mode`),NI(s.slotService,e,d.id),EI(e),await _I(s),MI(s);let g=vn();await Q.setOptions(s,g)}var Mb,Lb,Db,Cp,DI,Ub=T(()=>{"use strict";Mb=v(require("lodash"));B();Wl();Kl();$e();as();ls();ss();Xl();ye();Ct();Bt();j();Ot();le();ae();q();_b();Ii();ku();fe();Sn();Sl();Lb=30*60*1e3,Db=1,Cp=x("runner");DI=LI});function Fb(s){s.get("/",(e,t)=>{let r=Pp();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:$l()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());Ll({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var Bb=T(()=>{"use strict";ns();kp();Wl()});var Op,jb,Cs,Ia,$b=T(()=>{"use strict";Op=v(require("chalk"));kr();jb=require("express");j();q();Cs=x("cli-router"),Ia=(0,jb.Router)();Ia.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:o,testResultId:i,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d}=s.body;if(typeof t!="string"||!r||!n||!o||!i||typeof a!="number"||!l||typeof c!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let m={stepId:r,testResultId:i,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d,incomingParams:n};try{let u=await hs(t,r,n,o,i,a,l,c,d);u.success||(console.log(Op.default.red(u.result.resultValue)),Cs.error("CLI Action Failure",{message:u.result.resultValue,...m})),e.status(200).json({success:!0,data:u})}catch(u){Cs.error("failed to run cli code",{err:u,...m}),console.log(Op.default.red("failed to run cli code",u)),e.status(500).json({success:!1,code:"internal-error"})}});Ia.post("/install",async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,packageData:o,stepResultId:i,timeout:a}=s.body;if(!t||typeof o!="object"||!r||typeof n!="number"||!i||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let l={stepId:t,testResultId:r,retryIndex:n,stepResultId:i,timeout:a,packageData:o};try{let c=await gs(t,r,n,o,i,a);Cs.info("installed packages successfully",l),e.status(200).json({success:!0,data:c})}catch(c){if(c instanceof Rt){Cs.error("failed to install node packages",{err:c,...l}),e.status(200).json({success:!1,code:"invalid-node-package",message:c.message});return}if(c instanceof ne){Cs.error("timeout installing node package",{err:c,...l}),e.status(200).json({success:!1,code:"timeout"});return}Cs.error("failed to install node packages",{err:c,...l}),e.status(500).json({success:!1,code:"internal-error"})}})});var jI,Wb=T(()=>{"use strict";kr();j();$b();jI=x("cli-service");rh().catch(s=>jI.warn("failed to clean local package folder",{err:s}))});async function $I(s,e,t="utf8"){let r=Hb.join(Gb.tmpdir(),s);return await Vb.promises.writeFile(r,e,t),r}async function VI(s){var t;let e=Date.now();try{let r=`
|
|
414
414
|
module.paths = ${JSON.stringify(module.paths)};
|
|
415
415
|
process.on('unhandledRejection', (error) => {
|
|
416
416
|
process.send({type: 'unhandledRejection', error: {message: error.message, stack: error.stack}});
|
|
@@ -421,12 +421,12 @@ Turbo mode will ignore step delays. Test artifacts like screenshots and logs wil
|
|
|
421
421
|
process.exit(1);
|
|
422
422
|
});
|
|
423
423
|
${s};
|
|
424
|
-
`,n=await
|
|
424
|
+
`,n=await $I(`tst-playground-${Date.now()}.js`,r),o=WI(n);Ps[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=Ps[e])==null||t.kill(),delete Ps[e]}}async function zb({code:s,type:e}){if(_p.includes(e))return VI(s);throw new jr}function Kb(){Object.keys(Ps).forEach(s=>{Ps[s].kill(),delete Ps[s]})}var Vb,Gb,Hb,qb,_p,Ps,WI,Jb=T(()=>{"use strict";Vb=v(require("fs")),Gb=v(require("os")),Hb=v(require("path")),qb=require("child_process");q();_p=["playwright","selenium","puppeteer"],Ps={};WI=s=>{let e,t=new Promise(n=>{e=n}),r=(0,qb.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 $r(i.stack)})}),r.on("error",n=>{e({error:n})}),r.on("exit",n=>{e({exitCode:n})}),Object.assign(t,{child:r})}});var Qb,Ra,Zb,Yb,Xb,GI,eT=T(()=>{"use strict";Qb=require("express");j();q();le();Jb();Ra=(0,Qb.Router)(),Zb=x("playground-router"),Yb=["localhost","app.testim.io","playground.testim.io","staging.testim.io","app.staging.testim.cc","tta-crm.tricentis.com"],Xb=s=>{if(!s)return{};try{return new URL(s)}catch{return{}}},GI=(s,e,t)=>{if(Qn)return t();let{referer:r,origin:n}=s.headers;if(!r&&!n)return e.status(400).send();let o=Xb(r),i=Xb(n);return!Yb.includes(o.hostname)&&!Yb.includes(i.hostname)?e.status(400).send():t()};Ra.post("/run",GI,async(s,e)=>{let{code:t,type:r}=s.body;if(!t||!_p.includes(r)){e.status(400).send({success:!1,reason:"missing arguments"});return}try{await zb({code:t,type:r}),e.send({success:!0})}catch(n){if(n instanceof jr){e.status(404).send({success:!1});return}if(n instanceof $r){e.json({success:!1,type:"playground-error",stack:n.innerStack});return}e.json({success:!1,reason:n.message}),Zb.error(n)}});Ra.post("/stop",(s,e)=>{try{Kb(),e.send({success:!0})}catch(t){e.json({success:!1,reason:t.message}),Zb.error(t)}})});function rT(s){let e=(0,tT.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 tT,sT=T(()=>{"use strict";tT=require("express")});var aT={};V(aT,{orchestrateRoutes:()=>HI});function HI(s,e){let t=(0,oT.default)();s(t),t.use(Lp.default.urlencoded({extended:!1,limit:"50mb"})),t.use((0,iT.default)()),t.use(Lp.default.json({limit:"50mb"}));let n={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:Oe||Qn?"*":["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,nT.default)(n)),Fb(t),t.use("/playground",Ra),t.use("/cliJs",Ia),t.use("/standalone-browser",rT(e)),t.use((o,i)=>{i.status(404).send("Endpoint Not Found")}),t}var nT,oT,Lp,iT,cT=T(()=>{"use strict";nT=v(require("cors")),oT=v(require("express")),Lp=v(require("body-parser")),iT=v(require("compression"));Bb();Wb();eT();sT();le()});var uT={};V(uT,{init:()=>qI});async function qI({agentPort:s,agentBind:e,project:t,token:r,installPlaygroundPlaywrightDeps:n,installPlaygroundPuppeteerDeps:o,installPlaygroundSeleniumDeps:i},a){await KI({installPlaygroundPlaywrightDeps:n,installPlaygroundPuppeteerDeps:o,installPlaygroundSeleniumDeps:i,project:t}),await zI({agentPort:s,agentBind:e,project:t,token:r},a)}async function zI({agentPort:s,agentBind:e,project:t,token:r},n){let{orchestrateRoutes:o}=await Promise.resolve().then(()=>(cT(),aT));return new Promise((i,a)=>{let l=()=>{};t&&(Im(t,r),l=f=>{f.use((g,h,y)=>{Object.assign(g,{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 C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return a(new C(`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}`),JI()}})}function KI({installPlaygroundPlaywrightDeps:s,installPlaygroundPuppeteerDeps:e,installPlaygroundSeleniumDeps:t,project:r}){let n=[];return s&&n.push(Se("playwright")),e&&n.push(Se("puppeteer")),t&&n.push(Se("selenium-webdriver"),wr({projectId:r})),Promise.all(n)}async function JI(){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,pT=T(()=>{"use strict";lT=v(require("http"));Ct();q();Ir();Zr()});var bT={};V(bT,{getStartedWithStart:()=>Pp,runAgentMode:()=>ZI});async function ZI(s){var r;let e;if(await vr(s.playerLocation,s.canary),s.startTestimBrowser){await rR();try{e=await tR(s)}catch(n){throw(r=n==null?void 0:n.message)!=null&&r.includes("user data directory is already in use")?new C('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(pT(),uT));return e!=null&&e.webdriverApi&&setTimeout(async()=>{setTimeout(()=>(ip(),he(Jy)));let o=["webpack"];for(let i of o)await Se(i,{silent:!0}).catch(()=>null)},6e3),t.init(s,e)}function Pp(){return hT}function dT(s){try{return process.kill(s,0)}catch{return!1}}async function eR(s,e,t){let r=pr.join(Ft,`chrome-${tn}-process`),n=3e3,o=()=>{Pe.rmSync(r,{recursive:!0}),console.log(`
|
|
425
425
|
|
|
426
|
-
Browser session ended`),process.exit(0)};if(await ge(r)){let f=JSON.parse(Pe.readFileSync(r));if(dT(f.pid)){let g=()=>dT(f.pid)?setTimeout(g,n):o();return g(),{webdriverApi:f}}}let i=await Co();await ge(ks)||await Pe.promises.mkdir(ks,{recursive:!0});let l=[...yT(ks,e,t,i).desiredCapabilities.chromeOptions.args,...Aa.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 Aa.launch({chromeFlags:l,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:ks,chromePath:i,envVars:c}),u={port:m.port,pid:m.pid,cdpUrl:await br(`localhost:${m.port}`)};return Pe.writeFileSync(r,JSON.stringify(u)),m.process.once("exit",o),m.process.once("close",o),{webdriverApi:u}}async function
|
|
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 br(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function
|
|
426
|
+
Browser session ended`),process.exit(0)};if(await ge(r)){let f=JSON.parse(Pe.readFileSync(r));if(dT(f.pid)){let g=()=>dT(f.pid)?setTimeout(g,n):o();return g(),{webdriverApi:f}}}let i=await Co();await ge(ks)||await Pe.promises.mkdir(ks,{recursive:!0});let l=[...yT(ks,e,t,i).desiredCapabilities.chromeOptions.args,...Aa.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 Aa.launch({chromeFlags:l,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:ks,chromePath:i,envVars:c}),u={port:m.port,pid:m.pid,cdpUrl:await br(`localhost:${m.port}`)};return Pe.writeFileSync(r,JSON.stringify(u)),m.process.once("exit",o),m.process.once("close",o),{webdriverApi:u}}async function tR(s){let e=`${td}/extension/testim-full-master.zip`,t=pr.basename(e),r=pr.join(Ft,t),n=pr.join(Ft,`${t}__unzipped__`),o=!(s.ext||s.extensionPath);if(o&&await ge(r)){let f=await Pe.promises.stat(r);o=Date.now()-XI>f.mtimeMs}if(await Pe.promises.mkdir(Ft,{recursive:!0}),o){let f=(0,fT.default)("Downloading Testim Editor").start();await Je(e,r);try{await st(r,n)}catch{await Pe.promises.rm(r,{recursive:!0,force:!0}),await Je(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 eR(s,i,n);await wr({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=yT(ks,i,s.extensionPath,s.chromeBinaryLocations),{WebDriver:l}=(Pn(),he(Jg)),{SeleniumPerfStats:c}=(ps(),he(Eg)),d=new l;d.seleniumPerfStats=new c;let m=await d.initClient(a);hT=!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 br(m.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:d}}function yT(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:YI,desiredCapabilities:{chromeOptions:{args:o,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function rR(){if(await ge(xa))try{let{webSocketDebuggerUrl:s}=await sR();await nR(s),await Pe.promises.unlink(xa)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Pe.promises.unlink(xa)}}async function sR(){let s=await Pe.promises.readFile(xa,{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 br(`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 oR(s,e);return Yt(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function oR(s,e=100){let t=new gT.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 mT,fT,gT,Pe,pr,Aa,YI,XI,ks,QI,xa,hT,kp=T(()=>{"use strict";mT=v(require("ms")),fT=v(require("ora")),gT=v(require("ws")),Pe=v(require("fs")),pr=v(require("path")),Aa=v(require("chrome-launcher"));le();Zr();q();Ir();_c();B();YI=eo?"verbose":"silent",XI=(0,mT.default)("1h"),ks=pr.join(Ft,"profile"),QI="DevToolsActivePort",xa=pr.join(ks,QI);hT=!1});var CD=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 Bp=require("perf_hooks");var Yn=v(require("os")),_s=v(require("url")),Ls=v(require("http")),Oa=v(require("https")),Gn=v(require("form-data")),Hn=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)}},qn=class extends Hn{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 Gn.default)this._body=null;else throw new Error(`Unsupported send() data ${t}`)}_finalizeHeaders(t,r){this._contentType&&!("content-type"in r)&&(t["Content-Type"]=this._contentType),this._body&&(t["Content-Length"]=this._body.length.toString())}_startUpload(t){this._body&&t.write(this._body),t.end()}},Os=class{constructor(e){this.type=e;this.target=null;this.currentTarget=null;this.lengthComputable=!1;this.loaded=0;this.total=0;this.bubbles=!1;this.cancelable=!1}},zn=class extends Error{},Kn=class extends Error{},Jn=class extends Error{},mr=class extends Error{},Ie=class extends Hn{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=Ls.globalAgent;this.nodejsHttpsAgent=Oa.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 (${Yn.type()} ${Yn.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=Ie.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new qn(this);this._method=null;this._url=null;this._sync=!1;this._headers=null;this._loweredHeaders=null;this._mimeOverride=null;this._request=null;this._response=null;this._responseParts=null;this._responseHeaders=null;this._aborting=null;this._error=null;this._loadedBytes=0;this._totalBytes=0;this._lengthComputable=!1;this._anonymous=t==null?void 0:t.anon}static nodejsSet(t){Ie.prototype.nodejsSet(t)}nodejsSet(t){if("httpAgent"in t&&(this.nodejsHttpAgent=t.httpAgent),"httpsAgent"in t&&(this.nodejsHttpsAgent=t.httpsAgent),"baseUrl"in t){let r=t.baseUrl;if(r!==null&&!_s.parse(r,!1,!0).protocol)throw new zn("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new Jn(`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(Ie.OPENED),this._request=null,this._response=null,this.status=0,this.statusText="",this._responseParts=[],this._responseHeaders=null,this._loadedBytes=0,this._totalBytes=0,this._lengthComputable=!1}setRequestHeader(t,r){if(this.readyState!==Ie.OPENED)throw new 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!==Ie.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 Kn(`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([Ie.LOADING,Ie.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 Os("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new Kn("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:"?Ls:Oa).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 Gn.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 Gn.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=Ls.STATUS_CODES[this.status],this._parseResponseHeaders(r);let n=this._responseHeaders["content-length"];n?(this._totalBytes=parseInt(n,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(Ie.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==Ie.LOADING&&this._setReadyState(Ie.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Ie.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend")}_onHttpResponseClose(t){if(this._response!==t)return;let r=this._request;return this._setError(),r.abort(),this._setReadyState(Ie.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ie.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ie.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let r=new Os(t);r.lengthComputable=this._lengthComputable,r.loaded=this._loadedBytes,r.total=this._totalBytes,this.dispatchEvent(r)}_setError(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null}_parseUrl(t){let r,n,o,i=this.nodejsBaseUrl===null?t:_s.resolve(this.nodejsBaseUrl,t),a=_s.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=Ie;ke.SyntaxError=zn,ke.ProgressEvent=Os,ke.SecurityError=Jn,ke.XMLHttpRequest=Ie,ke.InvalidStateError=mr,ke.XMLHttpRequestUpload=qn,ke.UNSENT=0,ke.OPENED=1,ke.HEADERS_RECEIVED=2,ke.LOADING=3,ke.DONE=4;Object.assign(global,{xhr2:ke,XMLHttpRequest:ke,performance:Bp.performance,...typeof Blob>"u"&&{Blob:require("buffer").Blob}});var TT=v(require("semver"));$e();Sl();Bt();Zr();var Dp=v(require("chalk")),wT=require("events");ae();un();q();ae();Oo();j();var Nm=v(require("os")),Il=v(require("path")),Rl=v(require("chalk")),Fo=require("fs");le();function Um(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=Nm.homedir();(0,Fo.mkdirSync)(Il.resolve(n,".testim_logs"),{recursive:!0});let o=Il.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}`),Yp&&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(Rl.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(Rl.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Fo.writeFileSync)(o,`${s}
|
|
429
429
|
${s==null?void 0:s.stack}
|
|
430
430
|
|
|
431
|
-
${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}Qs();var Yw=x("process-handler"),Fm=!1;function Xw(s){return s instanceof Error?1:Fm?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===Ye.EVALUATING?!1:r!==!0)?1:0)}function Qw(){try{Qt("chromedriver").stop()}catch{}}function Bm(){Fm=!0}async function xl(s){s!=null&&s.stack&&(es?console.error(s,s.stack):Um(s)),Qw(),await Yw.waitForFlush(),process.exit(Xw(s))}ye();j();fe();var
|
|
431
|
+
${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}Qs();var Yw=x("process-handler"),Fm=!1;function Xw(s){return s instanceof Error?1:Fm?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===Ye.EVALUATING?!1:r!==!0)?1:0)}function Qw(){try{Qt("chromedriver").stop()}catch{}}function Bm(){Fm=!0}async function xl(s){s!=null&&s.stack&&(es?console.error(s,s.stack):Um(s)),Qw(),await Yw.waitForFlush(),process.exit(Xw(s))}ye();j();fe();var iR=x("cli-entry");function aR(s){if(!TT.satisfies(process.version,s))throw new C(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=16,t=18,r=Number(process.versions.node.split(".")[0]),n=new Date("2023-09-11T00:00:00.000Z"),o=n<=new Date,i=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(n);if(r<e)throw new C(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&o)throw new C(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(Dp.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${i}. please upgrade to a newer Node.js version.`))}async function cR(){console.log("Starting Testim.io CLI");let[s,e]=await Promise.all([Promise.resolve().then(()=>(B(),K)),Promise.resolve().then(()=>(af(),of))]);N("Starting Testim.io CLI"),Mm(xl);try{aR(s.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{await M.fetch();let t=await e.process();if(N("in main, after options.process"),za(global.proxyUri),"parallel"in t&&t.parallel>5&&(wT.EventEmitter.defaultMaxListeners=t.parallel*2),qa(t.project),Qd("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(),pf));return await o()}if(s.isLoginMode(t))return;if(s.isCreatePrefetchedDataMode(t)){await Jr(),await cn(t);let{preloadTests:o}=await Promise.resolve().then(()=>(Ho(),mf));await o(t),!t.playerRequirePath&&t.mode!==Y.EXTENSION&&await vr(t.playerLocation,t.canary);let i=await Yd();i.success?console.log(`created prefetched data at ${To()}`):console.error("failed to create prefetch data",i.error);return}let r=await Promise.resolve().then(()=>(Ub(),Nb));if(s.isTunnelOnlyMode(t)){await r.init(t);let{serveTunneling:o}=await Promise.resolve().then(()=>(Kl(),zl));await o(t);return}if(s.isAgentMode(t)){let{runAgentMode:o}=await Promise.resolve().then(()=>(kp(),bT));return o(t)}if(t.saveRCALocally){let{initServer:o}=await Promise.resolve().then(()=>(bu(),xg)),{port:i}=await o(t);t.localRCASaver=`http://localhost:${i}`}t.exitCodeIgnoreFailingTests&&Bm(),N("right before testRunner.init/prepareRunner.prepare");let[n]=await Promise.all([_m(t),r.init(t)]);return N("right after testRunner.init/prepareRunner.prepare"),await r.run(t,n)}catch(t){if(t instanceof Fr)return;let r=s.getArgsOnRemoteRunFailure();return r&&await ml({...r,error:t.message}).catch(()=>{}),t instanceof C?(console.log(Dp.default.red("Argument Error:",t.message)),t):(console.log("Error:",t.message),iR.error("runner ended with unexpected error",{err:t}),t)}}cR().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),xl(s)});
|
|
432
432
|
//# sourceMappingURL=cli.js.map
|