@testim/testim-cli 4.50.0 → 4.501.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 CHANGED
@@ -19,7 +19,7 @@ Testim had missing write access to ${l||s}
19
19
  WARNING: ${s} is deprecated. ${t}
20
20
  `))},vl=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:El,argv:Il,exit:bl,cwd:At}=global.process,jw=["trace","debug","info","warn","error","silent"];rc(Il,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));Sl.description("Testim.io CLI").option("-h --help","output usage information",$m).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",De,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",De,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",De,[]).option("-w, --webpackConfig [webpack-configuration]","webpack configuration used to build the code based project").option("--test-id [test-id]","test ID to run",De,[]).option("-l, --label [label]","labels to search test by",De,[]).option("-n, --name [test-name]","test name to run",De,[]).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",Uw).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--is-regression-baseline-run","save doms and run results as regression baseline data").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",De,[]).option("--test-plan-id [test-plan-id]","test plan to run",De,[]).option("--suite [suite-name]","suite to run",De,[]).option("--suite-id [suite-id]","suite ID to run",De,[]).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",De,[]).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("-roso --reset-on-session-start-only [reset-on-session-start-only]","set resetOnSessionStartOnly appium capability to true to avoid uninstall app on session end (ios run only)",!1).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--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(El.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,Tl.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,Tl.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: ${vl.join("/")}`,De,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",De,[]).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",De,[]).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)",De,[]).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)",De,[]).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(Il);p=Sl.opts(),$w=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},Ww=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},Vw=async()=>{var v,I,b,T,R,k,_,$;p.inspect&&require("inspector").open(p.inspect);let s={},e={},t=[],r={};if(!Il.slice(2).length)throw $m(),new Dr;if(p.requireCredentials){let S=await Promise.resolve().then(()=>(ts(),an)),x=await S.getProjectId(),L=await S.getToken();(!x||!L)&&await S.doLogin()}if(p.login)return await(await Promise.resolve().then(()=>(ts(),an))).doLogin(),{loginMode:!0};if(p.version){let S="Testim CLI Version: ";El.npm_package_version&&(console.log(S,El.npm_package_version),bl(0));let x=ut();x&&(console.log(S,x),bl(0)),console.log("Could not find version, please check the package.json manually"),bl(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Bd(),p.clearFileCache&&qr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let S=Me.resolve(n);Ud(S)}if(p.usePrefechedData&&jd(),p.playerRequirePath){let S=Me.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",S);let x=Me.join(S,"tsconfig.node.json"),U=require("ts-node").register({project:x,ignore:[/node_modules/,new RegExp(`^${$t.escapeRegExp(Me.relative(At(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:U.config.options.paths,baseUrl:U.config.options.baseUrl}),(Te(),he(Qt)).options.playerPath=S;let H=require("module"),X=H.prototype.require;H.prototype.require=function(Tt){return Tt==="rox-alias"?X.call(this,"rox-node"):X.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=wl.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")),p.proxyForGrid&&!p.proxy)throw new C("missing --proxy option");if(Om(p))return _m(p);try{let S={};p.configFile?S=require(Me.join(At(),p.configFile)).config:p.optionsFile&&(S=require(Me.join(At(),p.optionsFile))),S&&typeof S.then=="function"&&(S=await S),Object.keys(S).forEach(x=>{let L=Nw(x);p[L]=Fw(p[L],S[x])})}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=((v=p.testConfig)==null?void 0:v.length)||((I=p.testConfigId)==null?void 0:I.length),i=((b=p.testPlan)==null?void 0:b.length)||((T=p.testPlanId)==null?void 0:T.length),a=((R=p.suite)==null?void 0:R.length)||((k=p.suiteId)==null?void 0:k.length);if(p.seleniumCapsFile)try{r=require(Me.join(At(),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(Me.join(At(),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 x of S){let[L]=x.split("=");Um.includes(L)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(x),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(Um)}`)}}if(p.paramsFile)try{s=Object.assign({},s,require(Me.join(At(),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&&($w(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let S=require(Me.join(At(),p.sauceOptions)),x=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)>=Sa&&(p.browser="edge-chromium");let L=parseFloat(S.version)<50&&!["dev","beta"].includes(S.version);if(!x&&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&&(Ww(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let S=require(Me.join(At(),p.browserstackOptions)),x=S.platform&&["mac","android"].includes(S.platform.toLowerCase());if(S.browserName&&(p.browser=S.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(S.browser_version)>=Sa&&(p.browser="edge-chromium"),!x&&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(Me.join(At(),p.perfectoOptions)),x={location:"US East",securityToken:p.perfectoToken};p.perfecto=Object.assign({},x,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(Me.join(At(),p.testobjectOptions)),x={testobjectApiKey:p.testobjectKey};p.testobjectSauce=Object.assign({},x,S)}catch(S){throw new C(`Failed to parse test object options file error: ${S.message}`)}if(!p.project){let x=await(await Promise.resolve().then(()=>(ts(),an))).getProjectId();if(x)p.project=x;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 l=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 x=await(await Promise.resolve().then(()=>(ts(),an))).getToken();if(x)p.token=x;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"),!jw.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=Bm.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(x=>x.trim()).filter(Boolean);let S=p.resultLabel.filter(x=>x.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&fr()&&p.resultLabel.unshift(fr()),S.length)throw new C("A result label cannot exceed 250 characters")}let u=Rm(p),f=Mo(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&&!$t.inRange($t.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&&$t.difference(p.codeCoverageReporter,vl).length){let S=$t.difference(p.codeCoverageReporter,vl);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(x=>h[x]).join(" and ")} ${S} only applicable in extension mode`)}if(p.tmsFieldFile)try{let S=wl.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(S)}catch(S){throw new C(`failed to parse field file error: ${S.message}`)}if(p.highSpeed&&(Bw("--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.resetOnSessionStartOnly&&!p.fullReset&&console.warn("Ignoring --reset-on-session-start-only flag, should be used when --full-reset is provided for ios runs"),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"},x=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode=Object.assign({},S,x)}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"?fr():p.branch)||"master",autoDetect:p.branch==="auto-detect",token:p.token,userParamsData:s,mode:p.mode,isRegressionBaselineRun:p.isRegressionBaselineRun,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,skipLoadBalancer:p.skipLoadBalancer,lockDevice:p.lockDevice,appId:p.appId,appiumLogLevel:p.appiumLogLevel,setNoReset:p.setNoReset,fullReset:p.fullReset,resetOnSessionStartOnly:p.resetOnSessionStartOnly,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:l,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}}});var zm={};V(zm,{installAllLazyDependencies:()=>qw,lazyRequire:()=>Ee});async function Ee(s,e={}){let t=dc(s);if(t)return t;let r;e.silent||(r=(0,Gm.default)(`Installing ${s} before first usage...`).start());try{let n=await Hw(s);return r&&r.succeed(),n}catch(n){Gw.warn("failed to install dependency lazily",{dependency:s,err:n});let o=qm(s),i=`${s}@${o}`,c=process.argv.includes("npx")?"":"-g ",l=`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 ${c}${i}`;throw r&&r.fail(l),n}}async function Hw(s){return rs.has(s)||(rs.set(s,Hm(s)),rs.get(s).catch(()=>{rs.delete(s)})),rs.get(s)}async function Hm(s){let e=dc(s);if(e)return e;let t=qm(s),r=`${s}@${t}`;return await bo(pt(),r),Jt(s)}async function qw(){let s=Object.keys(Aa);for(let e of s)await Hm(e)}function qm(s){let e=Object.entries(Aa).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Gm,Gw,rs,wr=w(()=>{"use strict";Gm=E(require("ora"));zs();j();B();qn();qs();Gw=A("lazy-require"),rs=new Map});var Jm={};V(Jm,{preloadTests:()=>cn});async function cn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await dt(async()=>{let t=await ae(s.testId,r=>Pc({...e,testId:r}),{concurrency:2});return Km.keyBy(t,"testData.id")},"loadTests",zw,[e,s.testId])()}var Km,zw,jo=w(()=>{"use strict";Km=E(require("lodash"));Ut();be();B();zw=1e3*60*60*10});function Rl(){return ut()}async function Qm(){if(!ke)try{let s=await ce(Jw(),5e3,"The API call to NPM timed out"),e=Rl();e&&Xm.lt(e,s)&&console.log(Ym.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){Kw.warn("Failed to get NPM version",{err:s})}}var Ym,Xm,Kw,Jw,xl=w(()=>{"use strict";Ym=E(require("chalk")),Xm=E(require("semver"));B();le();zs();Ut();j();Kw=A("npm-driver"),Jw=dt(()=>Gd("@testim/testim-cli"),"getNpmVersion")});var Al,Xw,ss,Zm,ef,Cl,tf,rf=w(()=>{"use strict";B();z();j();wr();Al=A("testimNgrok"),Xw=".whitelisted-ngrok.testim.io",ss="",ef=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}${Xw}`);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 Ee("ngrok")).connect(r);s.tunnelUseHttpAddress&&o.startsWith("https://")?(Al.info("replace https to http"),ss=o.replace("https://","http://")):ss=o,s.tunnelDiagnostics&&Cl(),s.baseUrl=ss},Cl=async(s=!0)=>{try{let t=(await Ee("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(o=>o.public_url===ss);console.log("ngrok stats",n),Al.info("ngrok stats",{tunnel:n})}catch(e){Al.error("error collecting ngrok stats",{err:e})}s&&(Zm=setTimeout(()=>Cl(),1e4))},tf=async s=>{if(!ss)return;clearTimeout(Zm),s.tunnelDiagnostics&&await Cl(!1),await(await Ee("ngrok")).disconnect(ss)}});var Zt,kl,sf,Zw,ev,Pl,$o,Vo,Wo,tv,nf,of,af=w(()=>{"use strict";Zt=E(require("os")),kl=E(require("fs")),sf=E(require("child_process"));B();be();Zw="https://github.com/cloudflare/cloudflared/releases/download/2022.4.1/",ev={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"}},Pl=Zt.tmpdir(),$o=`${Pl}/cloudflared`,Vo=null,Wo=null,tv=async()=>{if(await fe($o))return;let e=ev[Zt.platform()+Zt.arch()];if(!e)throw new Error(`tunnel on ${Zt.platform()+Zt.arch()} platform is not supported.`);let t=e.extract?Pl+e.path:$o;await ze(`${Zw}/${e.path}`,t),e.extract&&await rt(t,Pl),await kl.promises.chmod($o,"755")},nf=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Qc(s.company.companyId,t),tv()]);Vo=r._id,Wo=sf.spawn($o,["tunnel","--no-autoupdate","run","--force","--token",r.token],{stdio:"inherit"}),await Zc(s.company.companyId,Vo),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await kl.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},of=async s=>{let e=[];return Vo&&e.push(el(s.company.companyId,Vo)),Wo&&e.push(new Promise((t,r)=>{Wo.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),Wo.kill()})),await Promise.all(e)}});var cf,lf,Wt,uf,pf,df,Go,mf,Ol,sv,nv,ln,ov,iv,te,Ho=w(()=>{"use strict";cf=E(require("ms")),lf=E(require("p-retry")),Wt=E(require("os")),uf=E(require("portfinder")),pf=E(require("child_process"));B();qe();be();df=E(require("fs")),Go=E(require("fs/promises")),mf=require("path");z();j();No();ie();ge();B();Ol=A("lambdatestService"),sv="https://downloads.lambdatest.com/tunnel/v3",nv={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"},ln=`${Wt.tmpdir()}/LT`,ov=`${ln}/LT`,iv=(0,cf.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||=Gc(),te.lambdatestConfig=await te.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?iv:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await fe(ov))return;let t=nv[Wt.platform()+Wt.arch()];if(!t)throw new Error(`tunnel on ${Wt.platform()+Wt.arch()} platform is not supported.`);let r=`${ln}.zip`;await ze(`${sv}/${t}`,r),await rt(r,ln)}static async chmodLtTunnel(e){if(!(Wt.platform()==="win32"||!await fe(e))){try{await Go.access(e,df.constants.X_OK);return}catch{}try{await Go.chmod(e,"777")}catch(r){throw Ol.error("Failed to make LT tunnel executable",{e:r}),r}}}static async connectTunnel(e){if(e.externalLambdatestTunnelId){te.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await uf.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:o,externalLambdatestNTLMTunnelUsername:i,externalLambdatestNTLMTunnelPassword:a}=e,c=global.proxyUri;te.tunnelName=re();let l=["--tunnelName",te.tunnelName,"--infoAPIPort",String(t)];if(M.flags.enableLambdaTestTunnelNTLM.isEnabled())if(l=[...l,"--ntlm"],i&&a)l=[...l,"--ntlm-username",i,"--ntlm-password",a];else{let u=JSON.parse(M.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(l=[...l,...sc(u)])}if(M.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(l=[...l,"--skip-upgrade"]),e.externalLambdatestUseWss&&(l=[...l,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(l=[...l,"--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)l=[...l,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&o)l=[...l,"--user",n,"--key",o];else throw new C("tunnel requires username and password");if(c)try{let u=new URL(c);l=[...l,"--proxy-host",u.hostname],u.port&&(l=[...l,"--proxy-port",u.port]),u.username&&u.password&&(l=[...l,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new C("proxy url is invalid")}e.externalLambdatestMitm&&(l=[...l,"--mitm"]),await ne(3e3),await te.chmodLtTunnel((0,mf.join)(ln,"LT")),te.tunnel=pf.spawn("./LT",l,{cwd:ln});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,lf.default)(()=>Re(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});Ol.info("LT tunnel info",u)}catch(u){throw Ol.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){if(!this.isActive)return{};let i=te.lambdatestConfig.CAPABILITIES[t]||{},a={...te.tunnelName&&{tunnel:!0,tunnelName:te.tunnelName}},c=[],{mode:l,canary:d,ext:m,extensionPath:u,installCustomExtension:f}=e;if(l===Y.EXTENSION&&!m){let g=dl({canary:d},!0);!u&&g[t]&&(c=[...c,g[t]]),u&&je(u)&&(c=[...c,u])}return f&&je(f)&&(c=[...c,f]),{build:r,name:`${n} - ${o}`,platform:te.lambdatestConfig.PLATFORM,selenium_version:te.lambdatestConfig.SELENIUM_VERSION,resolution:te.lambdatestConfig.RESOLUTION,timezone:te.lambdatestConfig.TIMEZONE,...i,loadExtension:c,...a,console:!0,queueTimeout:300,network:M.flags.LTNetworkCapabilities.isEnabled(),ntlm:M.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:M.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}}});var _l={};V(_l,{connect:()=>zo,disconnect:()=>Ko,serveTunneling:()=>cv});var qo,ff,gf,av,zo,Ko,cv,Ll=w(()=>{"use strict";rf();sn();af();xt();qo=E(require("ora"));j();ie();Ho();ff=A("tunnel"),gf=s=>{var e;return[O.LAMBDATEST,O.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},av=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=Ft(),t;try{gf(s)?(t=(0,qo.default)("Starting testim lambdatest tunnel...").start(),await te.connectTunnel(s)):av(s)?(t=(0,qo.default)("Starting testim cloudflare tunnel...").start(),await nf(s)):(t=(0,qo.default)("Starting testim ngrok tunnel...").start(),await ef(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw ff.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(n)}},Ko=async s=>{if(s.tunnel)try{gf(s)?await te.disconnectTunnel(s):"tunnelRoutes"in s?await of(s):await tf(s)}catch(e){let t="catch error - failed to close tunnel";throw ff.error(t,{err:e}),new Error(t)}},cv=async(s,e=new Promise(()=>{}))=>(await zo(s),Zr(()=>Ko(s)),await e)});function lv(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=hf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function uv(s){let e=hf.exec(s);return e==null?void 0:e[3]}function Yo(s){var I,b,T,R,k,_,$,S,x,L,U;let e=s&&uv(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&lv(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,c=(b=s==null?void 0:s.external)==null?void 0:b.user,l=(T=s==null?void 0:s.external)==null?void 0:T.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):c,u=d===O.HYBRID?a&&((x=(S=($=s.hybrid)==null?void 0:$.external)==null?void 0:S[s.hybrid.tunnel])==null?void 0:x.key):l,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,v=(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:c,key:l,type:d,name:f,provider:h,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:v}}async function bf(s,e,t,r,n){let o;try{o=await n()}catch(i){throw Xe.error("failed to get grid",{projectId:s,companyId:e,err:i}),new Error($r.UNKNOWN)}if(Xe.info("get grid info",Object.assign({},o,{projectId:s,companyId:e})),!o||!["success","error"].includes(o.status))throw Xe.error("invalid response - get grid",{res:o}),new Error($r.UNKNOWN);if(o.status==="success"){let i=Yo(o.grid);return pv(t,e,i.gridId,i.slotId,r),i}throw o.code==="not-found"?new Et($r.NOT_FOUND):o.code==="no-available-slot"?new Nr(`Failed to run test on ${r} - concurrency limit reached`):(Xe.error("invalid code error response - get grid",{res:o}),new Et($r.UNKNOWN))}function dv(s,e,t,r,n,o){return bf(t,e,s,n,()=>Co(e,t,r,n,o))}function mv(s,e,t,r,n,o,i){return bf(t,e,s,n,()=>{var l;let c=(l=i.allGrids)==null?void 0:l.find(d=>(d.name||"").toLowerCase()===r.toLowerCase());return c!=null&&c._id?Co(e,t,c._id,n,o):$c(e,t,r,n,o)})}function Tf(s){return Vc(s)}async function wf(s,e,t){let n=(t||await Tf(s)).find(o=>o._id===e);if(!n)throw new C(`Failed to find grid id: ${e}`);return Yo(n)}async function fv(s,e,t){let n=(t||await Tf(s)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new C(`Failed to find grid name: ${e}`);return Yo(n)}async function Dl(s,e){let t=un[s];if(!t)return;let{slotId:r,gridId:n,browser:o,companyId:i}=t;if(delete un[s],!r){Xe.warn("failed to find grid slot id",{projectId:e});return}Xe.info("release slot id",{projectId:e,companyId:i,slotId:r,gridId:n,browser:o});try{await Bc(i,e,r,n,o)}catch(a){Xe.error("failed to release slot",{projectId:e,err:a})}}async function gv(s){let e=Object.values(un).filter(Boolean);if(e.length!==0){Xe.info("keep alive worker slots",{projectId:s,slots:e});try{await Fc(s,e)}catch(t){Xe.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function hv(s){yf=global.setInterval(gv,1e4,s)}async function yv(s){let e=Object.keys(un);if(e.length){Xe.warn("not all slots released before end runner flow",{projectId:s});try{await ae(e,t=>Dl(Number(t),s))}catch(t){Xe.error("failed to release all slots",{err:t,projectId:s})}}}async function bv(s){await yv(s),clearInterval(yf)}function Tv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function wv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function vf(s){let t=(()=>Jo.isEmpty(s.testobjectSauce)?Jo.isEmpty(s.saucelabs)?Jo.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:o,protocol:i}=s,a=Tv(t,s),c=wv(t,s);return{host:r,port:n,path:o,protocol:i,type:t,user:c,key:a}}async function Ef(s,e){let t=s.company.companyId;return await wf(t,e.gridId,s.allGrids)}async function Sf(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:o,useChromeLauncher:i,gridId:a,grid:c}=s;if(n||i||o)return{mode:"local"};if(r)return vf(s);let l=t==null?void 0:t.companyId;if(a)return wf(l,a,e);if(c)return fv(l,c,e);if(js(s)||s.tunnelOnlyMode){Xe.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new Et("Missing host or grid configuration")}async function If(s,e,t,r){let{host:n,project:o,grid:i,gridId:a,localTmaUrl:c,useLocalChromeDriver:l,useChromeLauncher:d,company:m}=t,u=m==null?void 0:m.companyId;if(l||d||c)return{mode:"local"};if(n)return vf(t);if(a)return dv(r,u,o,a,s,e);if(i)return mv(r,u,o,i,s,e,t);throw new Et("Missing host or grid configuration")}var Jo,Xe,un,hf,yf,pv,pn,Rf,ns=w(()=>{"use strict";Jo=E(require("lodash"));be();j();B();ie();z();Xe=A("grid-service"),un={},hf=/(^(https?):\/{2})?(.*)/,yf=null;pv=(s,e,t,r,n)=>{un[s]={gridId:t,companyId:e,slotId:r,browser:n}};pn={start:hv,end:bv};Rf=async(s={},e={},t={},r={},n={})=>{var g,h,y;let{company:{companyId:o}={}}=s,{gridId:i,type:a}=e,c=s.browser||t.browserValue,l=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||!c||!d||!m))return e;let u=await jc({companyId:o,gridId:i,maxRetries:d,currentRetry:m,browser:c,usingTunnel:l});Xe.info("handling hybrid grid",{response:u,companyId:o});let f=Yo({...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}});function mn(){return Xo||"master"}function xf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){Xo="master";return}if(s!=null&&s.isArchived)throw new C(`Branch ${s.branch} is archived, run aborted.`);if(s){Xo=s.branch||s;return}Xo=e?"master":void 0}var Xo,Ml=w(()=>{"use strict";z()});var fn,Nl,vv,Ul,Ev,Qo,Zo,ei,ti,ri,si=w(()=>{"use strict";B();ie();fn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===pe.FAILED},Nl=s=>{let{status:e}=s;return e===pe.ABORTED},vv=s=>{let{status:e}=s;return e===pe.PASSED},Ul=s=>s.runnerStatus===Xa.SKIPPED,Ev=s=>s.testStatus===Ke.EVALUATING,Qo=(s,e)=>Object.values(s).filter(t=>{var r,n;return Ul(t)&&(Je(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,Zo=s=>Object.values(s).filter(e=>fn(e)&&Ev(e)).length,ei=s=>Object.values(s).filter(fn),ti=s=>Object.values(s).filter(vv),ri=s=>Object.values(s).filter(Nl)});function Iv(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Fl,ni,Sv,oi,Cf=w(()=>{"use strict";Fl=E(require("lodash"));j();si();ni=A("debug-reporter"),Sv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],oi=class{constructor(e){this.options=e}onTestStarted(e,t){ni.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,c=r.failedGetBrowserAttempts;ni.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:o,failedGetBrowserAttempts:c,id:i,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Fl.default.omit(this.options,Sv),company:Fl.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,o,i,a){let c=Iv(process.argv);ni.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,r,n,o){let i=ti(e).length,a=Object.keys(e).length-i;ni.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:o,passed:i,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Bl,Ct,gn=w(()=>{"use strict";ie();Bl=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}},Ct=new Bl});var $l={};V($l,{Reporter:()=>Rv});var er,hn,vr,ii,Pf,jl,Rv,Wl=w(()=>{"use strict";er=E(require("chalk")),hn=E(require("lodash"));B();ie();gn();si();vr={success:er.default.green,warn:er.default.yellow,error:er.default.red},{CLI_MODE:ii}=Mt,Pf="device",jl=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: ${er.default.underline(He(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=vr[e.success?"success":"error"];console.log(o(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${no(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=He(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(vr.error("Failed runs are:")),console.log(vr.error(t.join(`
22
- \r`)))}onTestPlanFinished(e,t,r,n,o){let i=ei(e),a=ti(e),c=ri(e),l=a.length,d=c.length,m=i.length,u="",f="";if(Ct.isTestStatusEnabled){let I=Zo(e);u=` FAILED-EVALUATING: ${I}`,m-=I,f=` SKIPPED: ${Qo(e,this.options)}`}let g=this.buildTestPlanName(o,t),h,y=vr[m?"error":"success"],v=`PASSED: ${l} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${no(r)}`;g.trim()===""||g.trim()==="Anonymous"?h=`Tests completed. ${v} (Execution ID: ${n})`:h=`Test plan${g} completed ${v} (${n})`,this.printWorkerDivider(),console.log(y(h)),this.printWorkerDivider(),this.printAllFailedTests(i)}buildTestPlanName(e,t){let r=hn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=hn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,o=hn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,i=hn.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 c=u=>{u.forEach((f,g)=>{var v;let h=(v=f.testData)!=null&&v.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`;console.log(" ",g+1,":",`${f.name}${Je(f,this.options)?"-quarantine":""}`,y,h)})},l=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${l}, 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:"),c(e)),console.log("Test list:"),c(t),r.length>0&&(console.log("After all:"),c(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===ii.APPIUM?Pf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${er.default.underline(n)} slot from ${er.default.underline(r)}`)}onGetSession(e,t,r){let n=r===ii.APPIUM?Pf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${er.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){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===ii.APPIUM?"device":"browser";if(n)console.log(vr.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(vr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===ii.APPIUM?"Appium":"Selenium";console.log(vr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},Rv=jl});var Hl={};V(Hl,{Reporter:()=>Ov});function xv(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function Av(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 Cv(s){return`${s.visitedUrlsJson||""}`}async function Pv(s,e,t,r,n,o){function i(u){let f=He(s,t,u.testId,u.resultId,r),g={$:{name:xv(u),classname:n,time:nc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(fn(u)||Nl(u)){let h=`Step Failed: ${u.failureReason||u.reason}`,y=fn(u)?`${h} More info at: ${f}`:h;g.failure={$:{message:y}}}return Ul(u)&&Je(u,o)&&Ct.isTestStatusEnabled&&(g.skipped={}),o.urls&&(g["visited-urls-list"]=Av(u),g["visited-urls-json"]=Cv(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:l(y),failure:d(y),timestamp:c(e)};if(Ct.isTestStatusEnabled){I.skipped=Qo(y,o);let b=Zo(y);I.failure-=b,I["failure-evaluating"]=b}return{$:I,testcase:Object.keys(y).map(b=>i(y[b]))}}function c(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 l(u){return Object.keys(u).length}function d(u){return ei(u).length+ri(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Gl.Builder().buildObject(m)}catch(u){return kv(u)}}function kv(s){let e=new Gl.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 Gl,kf,Vl,Ov,ql=w(()=>{"use strict";Gl=E(require("xml2js"));B();kf=require("fs");gn();si();Vl=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 Pv(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await kf.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)}};Ov=Vl});var Of={};V(Of,{Reporter:()=>_v});function os(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 zl,Kl,_v,_f=w(()=>{"use strict";j();zl=A("team-city-reporter");Kl=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 os(n)}onTestStarted(e,t,r,n){if(r){zl.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){zl.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${os(t)}' details='${os(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){zl.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='${os(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${os(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${os(t)}']`)}},_v=Kl});var Lf={};V(Lf,{Reporter:()=>Lv});var Jl,Lv,Df=w(()=>{"use strict";Jl=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}}))}},Lv=Jl});var Mf={};V(Mf,{Reporter:()=>Dv});var Yl,Dv,Nf=w(()=>{"use strict";B();ml();Yl=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=He(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Fo(t)}},Dv=Yl});var Fx,Xl,Q,Pt=w(()=>{"use strict";Cf();j();Fx=A("reporter"),Xl=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 oi(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Wl(),$l));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(ql(),Hl));this.reporters.push(new o(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(_f(),Of)),r.includes("console")&&Promise.resolve().then(()=>(Wl(),$l)),r.includes("junit")&&Promise.resolve().then(()=>(ql(),Hl)),r.includes("json")&&Promise.resolve().then(()=>(Df(),Lf)),r.includes("chrome")&&Promise.resolve().then(()=>(Nf(),Mf))])).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 Xl});function Ff(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Bf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:c,source:l,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:g,gridType:h}){let y=Ff({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:c,source:Uf(l,d),isStartUp:u,projectType:f,gridType:h,...["android","ios"].includes(f)&&g&&{appSource:g}},m);mt("test-run-ci",y)}function jf({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:o,companyId:i,companyName:a,projectName:c,companyPlan:l,source:d,user:m,lightweightMode:u,logger:f,isStartUp:g,projectType:h,appSource:y,gridType:v}){try{let I=Ff({executionId:s,projectId:e,testId:t,resultId:r,ucid:o,companyId:i,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:Uf(d,m),isStartUp:g,projectType:h,gridType:v,...["android","ios"].includes(h)&&y&&{appSource:y}},u);if(n.success){mt("test-run-ci-success",I);return}mt("test-run-ci-fail",Object.assign({},I,{failureReason:n.failureReason}))}catch(I){f.error("failed to update test end analytics",{err:I})}}function $f(s){mt("batch-run-ci",s)}var Uf,Ql=w(()=>{"use strict";es();Ro();Uf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:Xr&&e?"ci-with-user":Xr?"ci":e?"cli-with-user":s});var Vf,ai,Gf=w(()=>{"use strict";Vf=require("istanbul-lib-report"),ai=class extends Vf.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 Hf,qf,zf,yn,ft,Kf,ci,Zl,Jf,Mv,Yf,Xf,Nv,Uv,Qf,Fv,Bv,jv,$v,Wv,Zf,eg=w(()=>{"use strict";Hf=E(require("ora")),qf=E(require("dayjs")),zf=E(require("test-exclude")),yn=E(require("fs")),ft=E(require("path")),Kf=E(require("istanbul-reports")),ci=E(require("istanbul-lib-report"));be();z();B();j();wr();Gf();Zl=A("test-run-status"),Jf=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},Mv=s=>!!Jf(s).search,Yf=s=>s?Jf(s).pathname.substring(1):"",Xf=(s,e)=>{let t=Yf(e);return!new zf.default({relativePath:!1,include:s}).shouldInstrument(t)},Nv=s=>s.substring(0,s.indexOf("?")),Uv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await Ee("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)},Qf=(s,e)=>`${ft.resolve(s,Yf(e))}.js`,Fv=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ae(Object.values(t),async n=>{if(!n)return;let o=n.toObject();await ae(o.sources,async(i,a)=>{if(Xf(r,i))return;let c=Qf(e,i);await yn.promises.mkdir(ft.parse(c).dir,{recursive:!0}),await yn.promises.writeFile(c,o.sourcesContent[a])})})},Bv={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(Mv(e)&&(e=Nv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=ft.dirname(this.getPath(s));return ft.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},jv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=ci.createContext({dir:t,coverageMap:e,watermarks:ci.getDefaultWatermarks(),sourceFinder:a=>{try{let c=Qf(r,a);return yn.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new ai({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:Bv}),Kf.create(a,c).execute(i)}),o},$v=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let i=(await Ee("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Xf(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()},Wv=async(s,e)=>{let{mergeProcessCovs:r}=await Ee("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await qc(s,"testResult",`runId=${e}`)).data.docs;return await ae(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await en(c,9e4);await ae(l,async d=>{if(!o.has(d.url)){let m=d.text;d.sourceUrl&&(o.set(d.url,"TEMP"),m=await Ac(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}},Zf=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Zl.info("start js coverage process");let n=(0,Hf.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=ft.resolve(s.codeCoverageReportPath||"./coverage"),i=ft.resolve(o,`.js/${(0,qf.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?ft.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:d}]=await Promise.all([Ee("istanbul-lib-coverage"),Wv(s.project,r)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Zl.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:l.result.length});let m=c.createCoverageMap({}),u={};await ae(l.result,async({url:g,functions:h})=>{let{text:y,sourceMapType:v}=d.get(g),I=await Uv({sourceMapType:v,source:y,sourceMapDir:a});u[g]=I;let b=await $v(s,{source:y,sourceMap:I,functions:h});m.merge(b)}),await Fv(s,i,u);let f=await jv(s,m,o,i);return n.succeed(),f}catch(c){let l="Failed to report coverage information";c instanceof C?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),Zl.error(l,{err:c})}}});var tg={};V(tg,{SELENIUM_PERF_MARKS:()=>Ae,SeleniumPerfStats:()=>Er});var Ae,Vv,Er,is=w(()=>{"use strict";B();Ae={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Vv=["ALL",...Object.values(Ae)],Er=class{constructor(){this.marks=Object.fromEntries(Vv.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`,ao(r,50)],[`${t}_P95`,ao(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var og={};V(og,{initServer:()=>qv,mapFilesToLocalDrive:()=>tu});function tu(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,li[t.id]?{screenshot:li[t.id]}:{})),Object.keys(ui).forEach(t=>{s.assets||={},s.assets[ng[t]]=ui[t]}),s.assets||={},s.assets.screenshots=Object.values(li)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function qv({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await Ee("multer"),n=typeof t=="string"?t:Gv;await eu.promises.mkdir(n,{recursive:!0});let o=r({storage:r.diskStorage({async destination(c,l,d){let m=JSON.parse(c.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=bn.join(n,m.testResultId);try{await eu.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(c,l,d){let{fileName:m}=c.body,u=JSON.parse(c.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=bn.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),i=(0,sg.default)();i.post("/",o.single("file"),(c,l)=>{let d=JSON.parse(c.body.metadata||"{}");d.stepId&&(li[d.stepId]=c.file.path),d.testResultId&&Hv.includes(d.subType)&&(ui[d.subType]||=[],ui[d.subType].push(c.file.path)),l.sendStatus(200)}),i.use((c,l)=>l.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,l)=>{let d=a(i);d.listen(s,e),d.on("error",m),d.on("listening",()=>c(d.address()));function m(u){if(u.syscall!=="listen")return l(u);switch(u.code){case"EACCES":case"EPERM":return l(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return l(new C(`Port ${s} is already in use`));default:return l(u)}}})}var eu,rg,bn,sg,Gv,li,ui,ng,Hv,ru=w(()=>{"use strict";eu=E(require("fs")),rg=E(require("os")),bn=E(require("path")),sg=E(require("express"));z();wr();Gv=bn.join(rg.tmpdir(),"testim/rca/"),li={},ui={},ng={"test-log":"consoleLogs","har-file":"networkLogs"},Hv=Object.keys(ng)});var tr,su,pi,ig=w(()=>{"use strict";tr=E(require("lodash"));B();j();su=A("override-test-data-builder"),pi=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return tr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!tr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):su.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(tr.isObject(e.overrideAllTestsData)&&!tr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):su.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}su.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 tr.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),c=r[i],l=this.createNewTestItems(c,t);return r.splice(i,a-i+1,...l)})}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 di(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Qe.warn("failed to run hook",{err:t}),new C(`failed to run hook promise ${t.message}`)}}var Sr,Qe,zv,Kv,Jv,Yv,mi,ag=w(()=>{"use strict";Sr=E(require("lodash"));B();ie();ns();be();z();j();Pt();sn();eg();is();ru();le();ge();ig();gn();Qe=A("test-run-status"),zv=fr(),Kv=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,Jv=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,Yv=ut();mi=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 Er;var a,c,l,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let o=Bs(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:Yn||t.parallel||1,browser:o,gitBranch:zv,gitCommit:Kv,gitRepoUrl:Jv,runnerVersion:Yv,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||((c=t.gridData)==null?void 0:c.gridId),gridName:t.grid||((l=t.gridData)==null?void 0:l.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:c,testId:l,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:g,testOwnerEmail:h,testLabels:y,testSuites:v,allLabels:I}=a,b={originalTestResultId:t,previousTestResultId:r,config:Sr.cloneDeep(c),testId:l,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:v,allLabels:I}),Yc({projectId:n,runId:o,testId:l,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 l;let{project:n,remoteRunId:o,projectData:i}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await ko(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(d){Qe.error("failed to upload test data artifact (runner)",{err:d})}let c=Sr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,br(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(Je(e,this.options))return;let n=this.exportsGlobal;try{let o=await di(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 Qe.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}),Qe.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:o,testId:i,testStatus:a}=r,{resultId:c,success:l}=t;if(a===Ke.EVALUATING&&Ct.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Ke.EVALUATING} status`);return}if(l){Q.onTestPassed(o);return}Q.onTestFailed(r,r.failureReason,He(this.options.editorUrl,this.options.project,i,c,this.branchToUse),i,n,c)}calcResultText(e){return e.success?pe.PASSED:pe.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Ke.QUARANTINE}`)}monitorMemoryUsage(e){let t=oc();if(t.isOverThreshold){let r=M.flags.useLinkedomToParseHtml.isEnabled()?"linkedom":"jsdom";Qe.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&&tu(i,Qe),i.resultUrl=He(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 c=Object.assign({},this.exportsGlobal,t.exportsGlobal);return this.exportsGlobal=c,i}async testEndReport(e,t,r,n){var i;let o=r.exportsGlobal;try{try{await di(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){Qe.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 br(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 Qe.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}=ec;return e&&(n=o),Wr(t,r)&&(n=i),n}calcTestRunStatus(){var i;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(i=e.gridData)==null?void 0:i.type,o=t.map(a=>{var f,g,h;let c=e.browser?Gs(e.browser,e.saucelabs,e.browserstack):a.runConfig,l=Vr(M,n)&&$s(a.nativeApp)&&!e.appId,d=Ws(e)&&(Wr(a.nativeApp,n)||l),m=Je(a,e)||d,u={testId:a.testId,status:m?pe.SKIPPED:pe.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Ke.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(l,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:c.browserValue.toLowerCase()})};return[a.resultId,u]});return Object.fromEntries(o)}async executionStart(e,t,r,n,o){Qe.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:c}=i;Zr(()=>Promise.all([pn.end(t),Ao("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=r||Date.now();let l={projectId:t,executionId:e,...M.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},d=await di(i.beforeSuite,l),m=new pi(d,Sr.cloneDeep(this.testInfoList),t);this.testInfoList=m.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=d;let{testInfoList:u}=this,f=[],g=[],h=[];for(let v of u){if(v.isBeforeTestPlan){f.push(v);continue}if(v.isAfterTestPlan){h.push(v);continue}g.push(v)}let y=async()=>{let v=Sr.cloneDeep(this.testRunStatus);await ae(Object.keys(v),async R=>{var x;let k=v[R],_=(x=k.config)==null?void 0:x.testData,$=k.testId,S=await ko(t,$,R,_,c.defaults);S&&(delete k.config.testData,k.config.testDataUrl=S)});let I=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),b={executionId:e,projectId:t,labels:n||[],startTime:r,executions:v,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:I,intersections:i.intersections},T=_c(b);return this.executionStartedPromise=T,T.catch(R=>Qe.error(R)),T};try{await y()}catch(v){Qe.error("Failed to start suite",{err:v}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:f,tests:g,afterTests:h}}concatSeleniumPerfMarks(e){Sr.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=ac(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===Ke.EVALUATING&&i++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await di(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"),Qe.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await Zf(this.options,this.branchToUse,r,e);if(Object.assign(c,{coverageSummary:l}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Ao("FINISHED",e,this.options.project,r===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(m){throw Qe.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 Oc(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 Qv(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function cu(s){return ug.readFileSync(s,{encoding:"base64"})}function fg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&je(s))&&s){let r=cu(s);as.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${au(r)} current extension count: ${e.length}`),e.push(r)}}function gg(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;if(s.ext||r){let c=typeof s.ext=="string"?s.ext:`${__dirname}/..`,l=r||c,d=`--load-extension=${l}`;as.info(`adding extension: testim unpacked , path: ${l}`),t.push(d);return}let o=s.canary?"-master.zip":".zip",i=iu.join(process.cwd(),`testim-headless${o}`),a=cu(i);as.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${au(a)} current extension count: ${e.length}`),e.push(a)}function Zv(s,e,t,r,n,o,i){var g,h;let a=t.seleniumName||t.browserValue,c=[],l=[...mg];e.headless&&l.push("--headless");let d={prefs:{"profile.default_content_setting_values.popups":nu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":nu.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1},w3c:!0};ou(n)&&(d.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest-1",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),ou(n)&&a==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(d.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(y=>l.push(`--${y}`)),e.chromeBlockLocation&&(d.prefs["profile.default_content_setting_values.geolocation"]=nu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&l.push(`--user-data-dir=${e.chromeUserDataDir}`),(h=(g=e.projectData)==null?void 0:g.defaults)!=null&&h.disableChromiumGpu&&l.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+Qa.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}m(),fg(r,c,i),e.mode===Y.EXTENSION&&gg(e,c,l,o,i),c.length>0&&(d.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(d.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),d.args=l;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 tE(s,e,t){let r={"pdfjs.disabled":!0};if(M.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":lg.join(","),"browser.helperApps.neverAsk.openFile":lg.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=iu.join(process.cwd(),`testim-firefox-profile${n}`);s.desiredCapabilities.firefox_profile=cu(o)}return e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function rE(s){return`${s.width}x${s.height}`}function sE(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,dg.cloneDeep)(t.sl);return(r!=null&&r.resolution||t.sl.screenResolution)&&(o["sauce:options"].screenResolution=rE(r.resolution||t.sl.screenResolution),delete i.screenResolution),nt.merge(i,o,n)}return nt.merge(o,n)}return{}}function nE(s,e,t){return nt.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 oE(s){return s.perfecto?s.perfecto:{}}function iE(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 aE(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=Ia(o,i)),a}function fi(s){var v;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:c,lambdatestService:l}=s;if(o.mode==="local"){let I=[],b=[...mg],T={};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&&(T.binary=t.chromeBinaryLocation),t.mode!=="selenium"&&gg(t,I,b,null,l),fg(i,I,l),{logLevel:cg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:b,extensions:I,...T},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:d,driverRequestRetries:m}=t,u=aE(t,o),f={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:cg,connectionRetryTimeout:d,connectionRetryCount:m,getSessionTimeout:Math.max(l.getSessionTimeout,t.getSessionTimeout),getSessionRetries:l.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!nt.isEmpty(u)&&{headers:u},...t.proxyForGrid&&{agent:global.ProxyAgent(global.proxyUri)}};ou(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,f.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(f.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key);let g=Number(t.browserTimeout/1e3),h=t.browser||(n==null?void 0:n.browserValue);nt.merge(f.desiredCapabilities,sE(t,r,n,e),nE(t,r,n),oE(t),iE(t,h,g),l==null?void 0:l.getCapabilities(t,h,a,c,r));let y=null;switch(!t.ext&&!t.extensionPath&&((v=o.host)!=null&&v.endsWith(".testim.io"))&&!t.canary&&t.mode===Y.EXTENSION&&(y="/opt/testim-headless"),h){case"chrome":case"edge-chromium":f=eE(f,t,n,i,o,y,l);break;case"firefox":f=tE(f,t,l);break;case"safari":case"safari technology preview":f=Qv(f,h);break;default:break}nt.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]],T=_=>{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=T(T(R));Object.keys(k).length&&(as.info(`Adding custom capabilities: ${JSON.stringify(k)}`),Object.assign(f.desiredCapabilities,k))}catch(I){as.error("Failed to load custom capabilities",{error:I,customCapabilities:M.flags.addCustomCapabilities.getValue()})}return f.desiredCapabilities&&!f.capabilities&&(Xv(f),f.capabilities={alwaysMatch:f.desiredCapabilities,firstMatch:[{}]},delete f.desiredCapabilities),f.hostname=f.host,f}var ug,iu,pg,nt,dg,as,cg,nu,mg,au,ou,Xv,eE,lg,lu=w(()=>{"use strict";ug=E(require("fs")),iu=E(require("path")),pg=E(require("crypto")),nt=E(require("lodash"));B();le();j();ge();ie();Ho();dg=require("lodash"),as=A("testim-desired-capabilities-builder"),cg=Jn?"debug":"silent",nu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},mg=["--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"],au=(...s)=>pg.createHash("sha256").update(s.join("")).digest("hex"),ou=s=>s.type===O.DEVICE_FARM||s.type===O.HYBRID&&s.provider==="devicefarm",Xv=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{as.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};eE=nt.memoize(Zv,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(nt.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return au(i,a,c,r,l,o)}),lg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Ne(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 yg(s,e,t){if(!e||!s)return s;if(s.includes("%"))return s.replace(/ /g,"%20");try{return decodeURI(s)!==s?s:encodeURI(s)}catch(r){return t&&t.warn("tried to encode url but failed",{err:r,url:s}),s}}var uu=w(()=>{"use strict"});function pu(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 c(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:c(f))}function l(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:l(u.parentNode):!1}if(!s||!l(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 pu(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)||c(s))}var bg=w(()=>{"use strict"});var Tg,wg,Vt,cE,lE,gi,vg=w(()=>{"use strict";Tg=E(require("promise-queue")),wg=E(require("webdriverio"));le();Be();B();j();Or();bg();uu();is();Vt=A("WebDriverApi"),cE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},lE={implicit:0,pageLoad:1,script:2},gi=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 Vt.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),Ca!==void 0&&(e=Ca);let t=1/0;this.queue=new Tg.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(Ae.GET_BROWSER);try{await this.addToQueue(async()=>{Vt.info("requesting browser",{testResultId:r,testName:t}),N("before this.client.init"),this.client=await wg.remote(e),this.logGridStatus(r)}),N("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,Ae.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 c of a.slots||[])if(((i=c==null?void 0:c.session)==null?void 0:i.sessionId)===t){r=a,n=c;break}}catch(a){if(a.message==="unknown error"){Vt.info("grid status is not supported by the grid",{testResultId:e});return}Vt.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Vt.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){Vt.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(Ne(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(Ne(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(Ae.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,Ae.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Ae.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(_e(e)))}finally{this.seleniumPerfStats.markEnd(t,Ae.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(pu,{ELEMENT:e,[Ht]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Ne(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(yg(e,this.isSafari(),Vt))})}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[lE[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(Ne(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(_e(e)),await this.elementIdValue(_e(e),t)}async getViewportSize(e){let t=await this.execute(cE);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(Ea,i)?[Ea[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(c=>({type:"keyDown",value:c})),a=r.map(c=>({type:"keyUp",value:c}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};if(this.unsupportedActions.has("keys"))return o();try{return await this.addToQueue(()=>n())}catch(i){if(Ne(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(_e(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(Ne(o))return this.unsupportedActions.add("windowHandleSize"),r();throw o}})}}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.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){Vt.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 Vt.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 Eg={};V(Eg,{doubleClick:()=>uE});var uE,Sg=w(()=>{"use strict";uE=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,T){return T>I&&T<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,v=g.originY&&f(h.top,h.top+h.height,g.originY)?g.originY:h.top+h.height/2;return{x:y,y:v}},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}},c=function(u,f,g){if(!window.PointerEvent)return;let h=a(f,g);return new window.PointerEvent(u,h)},l=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)?c(g,f.x,f.y):l(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 Tn={};V(Tn,{dispatchFocus:()=>pE});function pE(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 wn=w(()=>{"use strict"});var Cg={};V(Cg,{WebDriver:()=>Rr});async function gE(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 mE(r):void 0}catch(r){Ue.info("Error getting cdpAddress",r);return}}var cs,xg,Ag,Ue,rr,dE,Ig,mE,sr,fE,Rg,Ir,Rr,vn=w(()=>{"use strict";cs=E(require("lodash"));B();Be();lu();xg=E(require("p-retry")),Ag=E(require("ua-parser-js"));Or();j();uu();vg();z();ge();is();Ue=A("webdriver"),[rr,dE]=[0,2],{extractElementId:Ig,getCdpAddressForHost:mE}=K,sr=()=>(Te(),he(Qt)).getSessionPlayer().codeSnippets,fE=()=>(Te(),he(Qt)).getSessionPlayer().locatorBuilderUtils,Rg=()=>(Te(),he(Qt)).getSessionPlayer().utils,Ir=()=>(Te(),he(Qt)).getSessionPlayer().positionUtils;Rr=class extends gi{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 v,I,b,T,R,k,_,$;let{overrideConfiguration:r,browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:c,executionId:l,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((b=(I=(v=n==null?void 0:n.company)==null?void 0:v.activePlan)==null?void 0:I.premiumFeatures)==null?void 0:b.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let g=fi({browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:c,executionId:l,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 gE(S),N("after getCdpAddress in webdriver.js init"),Ue.info(`init new session testName: ${o}`,{sessionId:this.getSessionId(),testResultId:d}),await ne(h),M.flags.dontFocusOnInit.isEnabled()||await y(),N("after focus and delay in webdriver.js init")}catch(S){let x=JSON.stringify(cs.omit(g,"capabilities.extensions","capabilities.capabilities.extensions"));Ue.error("failed to init webdriver",{err:S,capabilitiesAsString:x});let L=((R=(T=n==null?void 0:n.company)==null?void 0:T.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 Mr(S.message):S.message.match(/capabilit(y|ies)/)?new Xn(S.message):new Error("failed to init client driver")}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>cs.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,c)=>{let l=this._keepAliveRequests.find(d=>d.id===c);l&&(l[a]=Date.now())};function o(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let i=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,Ue.warn("close unexpected alert open"),await this.alertAccept().catch(c=>Ue.warn("failed to click on alert",{err:c}));return}if(Ue.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;Ue.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:c,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=c&&this.browserClosedCallbacks.forEach(l=>{try{l(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=Ig(r.value);return await this.switchToFrame({ELEMENT:n,[Ht]: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 Qn:r}}async getElement(t){var o;let r=this.seleniumPerfStats.markStart(Ae.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,Ae.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=ei(e),a=ti(e),c=ri(e),l=a.length,d=c.length,m=i.length,u="",f="";if(Ct.isTestStatusEnabled){let I=Zo(e);u=` FAILED-EVALUATING: ${I}`,m-=I,f=` SKIPPED: ${Qo(e,this.options)}`}let g=this.buildTestPlanName(o,t),h,y=vr[m?"error":"success"],v=`PASSED: ${l} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${no(r)}`;g.trim()===""||g.trim()==="Anonymous"?h=`Tests completed. ${v} (Execution ID: ${n})`:h=`Test plan${g} completed ${v} (${n})`,this.printWorkerDivider(),console.log(y(h)),this.printWorkerDivider(),this.printAllFailedTests(i)}buildTestPlanName(e,t){let r=hn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=hn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,o=hn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,i=hn.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 c=u=>{u.forEach((f,g)=>{var v;let h=(v=f.testData)!=null&&v.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`;console.log(" ",g+1,":",`${f.name}${Je(f,this.options)?"-quarantine":""}`,y,h)})},l=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${l}, 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:"),c(e)),console.log("Test list:"),c(t),r.length>0&&(console.log("After all:"),c(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===ii.APPIUM?Pf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${er.default.underline(n)} slot from ${er.default.underline(r)}`)}onGetSession(e,t,r){let n=r===ii.APPIUM?Pf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${er.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){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===ii.APPIUM?"device":"browser";if(n)console.log(vr.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(vr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===ii.APPIUM?"Appium":"Selenium";console.log(vr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},Rv=jl});var Hl={};V(Hl,{Reporter:()=>Ov});function xv(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function Av(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 Cv(s){return`${s.visitedUrlsJson||""}`}async function Pv(s,e,t,r,n,o){function i(u){let f=He(s,t,u.testId,u.resultId,r),g={$:{name:xv(u),classname:n,time:nc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(fn(u)||Nl(u)){let h=`Step Failed: ${u.failureReason||u.reason}`,y=fn(u)?`${h} More info at: ${f}`:h;g.failure={$:{message:y}}}return Ul(u)&&Je(u,o)&&Ct.isTestStatusEnabled&&(g.skipped={}),o.urls&&(g["visited-urls-list"]=Av(u),g["visited-urls-json"]=Cv(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:l(y),failures:d(y),timestamp:c(e)};if(Ct.isTestStatusEnabled){I.skipped=Qo(y,o);let b=Zo(y);I.failures-=b,I["failure-evaluating"]=b}return{$:I,testcase:Object.keys(y).map(b=>i(y[b]))}}function c(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 l(u){return Object.keys(u).length}function d(u){return ei(u).length+ri(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Gl.Builder().buildObject(m)}catch(u){return kv(u)}}function kv(s){let e=new Gl.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 Gl,kf,Vl,Ov,ql=w(()=>{"use strict";Gl=E(require("xml2js"));B();kf=require("fs");gn();si();Vl=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 Pv(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await kf.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)}};Ov=Vl});var Of={};V(Of,{Reporter:()=>_v});function os(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 zl,Kl,_v,_f=w(()=>{"use strict";j();zl=A("team-city-reporter");Kl=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 os(n)}onTestStarted(e,t,r,n){if(r){zl.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){zl.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${os(t)}' details='${os(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){zl.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='${os(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${os(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${os(t)}']`)}},_v=Kl});var Lf={};V(Lf,{Reporter:()=>Lv});var Jl,Lv,Df=w(()=>{"use strict";Jl=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}}))}},Lv=Jl});var Mf={};V(Mf,{Reporter:()=>Dv});var Yl,Dv,Nf=w(()=>{"use strict";B();ml();Yl=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=He(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Fo(t)}},Dv=Yl});var Fx,Xl,Q,Pt=w(()=>{"use strict";Cf();j();Fx=A("reporter"),Xl=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 oi(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Wl(),$l));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(ql(),Hl));this.reporters.push(new o(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(_f(),Of)),r.includes("console")&&Promise.resolve().then(()=>(Wl(),$l)),r.includes("junit")&&Promise.resolve().then(()=>(ql(),Hl)),r.includes("json")&&Promise.resolve().then(()=>(Df(),Lf)),r.includes("chrome")&&Promise.resolve().then(()=>(Nf(),Mf))])).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 Xl});function Ff(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Bf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:c,source:l,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:g,gridType:h}){let y=Ff({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:c,source:Uf(l,d),isStartUp:u,projectType:f,gridType:h,...["android","ios"].includes(f)&&g&&{appSource:g}},m);mt("test-run-ci",y)}function jf({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:o,companyId:i,companyName:a,projectName:c,companyPlan:l,source:d,user:m,lightweightMode:u,logger:f,isStartUp:g,projectType:h,appSource:y,gridType:v}){try{let I=Ff({executionId:s,projectId:e,testId:t,resultId:r,ucid:o,companyId:i,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:Uf(d,m),isStartUp:g,projectType:h,gridType:v,...["android","ios"].includes(h)&&y&&{appSource:y}},u);if(n.success){mt("test-run-ci-success",I);return}mt("test-run-ci-fail",Object.assign({},I,{failureReason:n.failureReason}))}catch(I){f.error("failed to update test end analytics",{err:I})}}function $f(s){mt("batch-run-ci",s)}var Uf,Ql=w(()=>{"use strict";es();Ro();Uf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:Xr&&e?"ci-with-user":Xr?"ci":e?"cli-with-user":s});var Vf,ai,Gf=w(()=>{"use strict";Vf=require("istanbul-lib-report"),ai=class extends Vf.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 Hf,qf,zf,yn,ft,Kf,ci,Zl,Jf,Mv,Yf,Xf,Nv,Uv,Qf,Fv,Bv,jv,$v,Wv,Zf,eg=w(()=>{"use strict";Hf=E(require("ora")),qf=E(require("dayjs")),zf=E(require("test-exclude")),yn=E(require("fs")),ft=E(require("path")),Kf=E(require("istanbul-reports")),ci=E(require("istanbul-lib-report"));be();z();B();j();wr();Gf();Zl=A("test-run-status"),Jf=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},Mv=s=>!!Jf(s).search,Yf=s=>s?Jf(s).pathname.substring(1):"",Xf=(s,e)=>{let t=Yf(e);return!new zf.default({relativePath:!1,include:s}).shouldInstrument(t)},Nv=s=>s.substring(0,s.indexOf("?")),Uv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await Ee("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)},Qf=(s,e)=>`${ft.resolve(s,Yf(e))}.js`,Fv=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ae(Object.values(t),async n=>{if(!n)return;let o=n.toObject();await ae(o.sources,async(i,a)=>{if(Xf(r,i))return;let c=Qf(e,i);await yn.promises.mkdir(ft.parse(c).dir,{recursive:!0}),await yn.promises.writeFile(c,o.sourcesContent[a])})})},Bv={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(Mv(e)&&(e=Nv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=ft.dirname(this.getPath(s));return ft.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},jv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=ci.createContext({dir:t,coverageMap:e,watermarks:ci.getDefaultWatermarks(),sourceFinder:a=>{try{let c=Qf(r,a);return yn.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new ai({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:Bv}),Kf.create(a,c).execute(i)}),o},$v=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let i=(await Ee("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Xf(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()},Wv=async(s,e)=>{let{mergeProcessCovs:r}=await Ee("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await qc(s,"testResult",`runId=${e}`)).data.docs;return await ae(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await en(c,9e4);await ae(l,async d=>{if(!o.has(d.url)){let m=d.text;d.sourceUrl&&(o.set(d.url,"TEMP"),m=await Ac(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}},Zf=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Zl.info("start js coverage process");let n=(0,Hf.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=ft.resolve(s.codeCoverageReportPath||"./coverage"),i=ft.resolve(o,`.js/${(0,qf.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?ft.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:d}]=await Promise.all([Ee("istanbul-lib-coverage"),Wv(s.project,r)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Zl.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:l.result.length});let m=c.createCoverageMap({}),u={};await ae(l.result,async({url:g,functions:h})=>{let{text:y,sourceMapType:v}=d.get(g),I=await Uv({sourceMapType:v,source:y,sourceMapDir:a});u[g]=I;let b=await $v(s,{source:y,sourceMap:I,functions:h});m.merge(b)}),await Fv(s,i,u);let f=await jv(s,m,o,i);return n.succeed(),f}catch(c){let l="Failed to report coverage information";c instanceof C?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),Zl.error(l,{err:c})}}});var tg={};V(tg,{SELENIUM_PERF_MARKS:()=>Ae,SeleniumPerfStats:()=>Er});var Ae,Vv,Er,is=w(()=>{"use strict";B();Ae={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Vv=["ALL",...Object.values(Ae)],Er=class{constructor(){this.marks=Object.fromEntries(Vv.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`,ao(r,50)],[`${t}_P95`,ao(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var og={};V(og,{initServer:()=>qv,mapFilesToLocalDrive:()=>tu});function tu(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,li[t.id]?{screenshot:li[t.id]}:{})),Object.keys(ui).forEach(t=>{s.assets||={},s.assets[ng[t]]=ui[t]}),s.assets||={},s.assets.screenshots=Object.values(li)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function qv({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await Ee("multer"),n=typeof t=="string"?t:Gv;await eu.promises.mkdir(n,{recursive:!0});let o=r({storage:r.diskStorage({async destination(c,l,d){let m=JSON.parse(c.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=bn.join(n,m.testResultId);try{await eu.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(c,l,d){let{fileName:m}=c.body,u=JSON.parse(c.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=bn.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),i=(0,sg.default)();i.post("/",o.single("file"),(c,l)=>{let d=JSON.parse(c.body.metadata||"{}");d.stepId&&(li[d.stepId]=c.file.path),d.testResultId&&Hv.includes(d.subType)&&(ui[d.subType]||=[],ui[d.subType].push(c.file.path)),l.sendStatus(200)}),i.use((c,l)=>l.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,l)=>{let d=a(i);d.listen(s,e),d.on("error",m),d.on("listening",()=>c(d.address()));function m(u){if(u.syscall!=="listen")return l(u);switch(u.code){case"EACCES":case"EPERM":return l(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return l(new C(`Port ${s} is already in use`));default:return l(u)}}})}var eu,rg,bn,sg,Gv,li,ui,ng,Hv,ru=w(()=>{"use strict";eu=E(require("fs")),rg=E(require("os")),bn=E(require("path")),sg=E(require("express"));z();wr();Gv=bn.join(rg.tmpdir(),"testim/rca/"),li={},ui={},ng={"test-log":"consoleLogs","har-file":"networkLogs"},Hv=Object.keys(ng)});var tr,su,pi,ig=w(()=>{"use strict";tr=E(require("lodash"));B();j();su=A("override-test-data-builder"),pi=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return tr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!tr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):su.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(tr.isObject(e.overrideAllTestsData)&&!tr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):su.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}su.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 tr.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),c=r[i],l=this.createNewTestItems(c,t);return r.splice(i,a-i+1,...l)})}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 di(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Qe.warn("failed to run hook",{err:t}),new C(`failed to run hook promise ${t.message}`)}}var Sr,Qe,zv,Kv,Jv,Yv,mi,ag=w(()=>{"use strict";Sr=E(require("lodash"));B();ie();ns();be();z();j();Pt();sn();eg();is();ru();le();ge();ig();gn();Qe=A("test-run-status"),zv=fr(),Kv=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,Jv=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,Yv=ut();mi=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 Er;var a,c,l,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let o=Bs(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:Yn||t.parallel||1,browser:o,gitBranch:zv,gitCommit:Kv,gitRepoUrl:Jv,runnerVersion:Yv,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||((c=t.gridData)==null?void 0:c.gridId),gridName:t.grid||((l=t.gridData)==null?void 0:l.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:c,testId:l,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:g,testOwnerEmail:h,testLabels:y,testSuites:v,allLabels:I}=a,b={originalTestResultId:t,previousTestResultId:r,config:Sr.cloneDeep(c),testId:l,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:v,allLabels:I}),Yc({projectId:n,runId:o,testId:l,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 l;let{project:n,remoteRunId:o,projectData:i}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await ko(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(d){Qe.error("failed to upload test data artifact (runner)",{err:d})}let c=Sr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,br(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(Je(e,this.options))return;let n=this.exportsGlobal;try{let o=await di(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 Qe.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}),Qe.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:o,testId:i,testStatus:a}=r,{resultId:c,success:l}=t;if(a===Ke.EVALUATING&&Ct.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Ke.EVALUATING} status`);return}if(l){Q.onTestPassed(o);return}Q.onTestFailed(r,r.failureReason,He(this.options.editorUrl,this.options.project,i,c,this.branchToUse),i,n,c)}calcResultText(e){return e.success?pe.PASSED:pe.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Ke.QUARANTINE}`)}monitorMemoryUsage(e){let t=oc();if(t.isOverThreshold){let r=M.flags.useLinkedomToParseHtml.isEnabled()?"linkedom":"jsdom";Qe.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&&tu(i,Qe),i.resultUrl=He(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 c=Object.assign({},this.exportsGlobal,t.exportsGlobal);return this.exportsGlobal=c,i}async testEndReport(e,t,r,n){var i;let o=r.exportsGlobal;try{try{await di(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){Qe.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 br(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 Qe.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}=ec;return e&&(n=o),Wr(t,r)&&(n=i),n}calcTestRunStatus(){var i;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(i=e.gridData)==null?void 0:i.type,o=t.map(a=>{var f,g,h;let c=e.browser?Gs(e.browser,e.saucelabs,e.browserstack):a.runConfig,l=Vr(M,n)&&$s(a.nativeApp)&&!e.appId,d=Ws(e)&&(Wr(a.nativeApp,n)||l),m=Je(a,e)||d,u={testId:a.testId,status:m?pe.SKIPPED:pe.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Ke.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(l,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:c.browserValue.toLowerCase()})};return[a.resultId,u]});return Object.fromEntries(o)}async executionStart(e,t,r,n,o){Qe.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:c}=i;Zr(()=>Promise.all([pn.end(t),Ao("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=r||Date.now();let l={projectId:t,executionId:e,...M.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},d=await di(i.beforeSuite,l),m=new pi(d,Sr.cloneDeep(this.testInfoList),t);this.testInfoList=m.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=d;let{testInfoList:u}=this,f=[],g=[],h=[];for(let v of u){if(v.isBeforeTestPlan){f.push(v);continue}if(v.isAfterTestPlan){h.push(v);continue}g.push(v)}let y=async()=>{let v=Sr.cloneDeep(this.testRunStatus);await ae(Object.keys(v),async R=>{var x;let k=v[R],_=(x=k.config)==null?void 0:x.testData,$=k.testId,S=await ko(t,$,R,_,c.defaults);S&&(delete k.config.testData,k.config.testDataUrl=S)});let I=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),b={executionId:e,projectId:t,labels:n||[],startTime:r,executions:v,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:I,intersections:i.intersections},T=_c(b);return this.executionStartedPromise=T,T.catch(R=>Qe.error(R)),T};try{await y()}catch(v){Qe.error("Failed to start suite",{err:v}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:f,tests:g,afterTests:h}}concatSeleniumPerfMarks(e){Sr.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=ac(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===Ke.EVALUATING&&i++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await di(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"),Qe.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await Zf(this.options,this.branchToUse,r,e);if(Object.assign(c,{coverageSummary:l}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Ao("FINISHED",e,this.options.project,r===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(m){throw Qe.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 Oc(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 Qv(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function cu(s){return ug.readFileSync(s,{encoding:"base64"})}function fg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&je(s))&&s){let r=cu(s);as.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${au(r)} current extension count: ${e.length}`),e.push(r)}}function gg(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;if(s.ext||r){let c=typeof s.ext=="string"?s.ext:`${__dirname}/..`,l=r||c,d=`--load-extension=${l}`;as.info(`adding extension: testim unpacked , path: ${l}`),t.push(d);return}let o=s.canary?"-master.zip":".zip",i=iu.join(process.cwd(),`testim-headless${o}`),a=cu(i);as.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${au(a)} current extension count: ${e.length}`),e.push(a)}function Zv(s,e,t,r,n,o,i){var g,h;let a=t.seleniumName||t.browserValue,c=[],l=[...mg];e.headless&&l.push("--headless");let d={prefs:{"profile.default_content_setting_values.popups":nu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":nu.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1},w3c:!0};ou(n)&&(d.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest-2",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),ou(n)&&a==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(d.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(y=>l.push(`--${y}`)),e.chromeBlockLocation&&(d.prefs["profile.default_content_setting_values.geolocation"]=nu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&l.push(`--user-data-dir=${e.chromeUserDataDir}`),(h=(g=e.projectData)==null?void 0:g.defaults)!=null&&h.disableChromiumGpu&&l.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+Qa.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}m(),fg(r,c,i),e.mode===Y.EXTENSION&&gg(e,c,l,o,i),c.length>0&&(d.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(d.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),d.args=l;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 tE(s,e,t){let r={"pdfjs.disabled":!0};if(M.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":lg.join(","),"browser.helperApps.neverAsk.openFile":lg.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=iu.join(process.cwd(),`testim-firefox-profile${n}`);s.desiredCapabilities.firefox_profile=cu(o)}return e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function rE(s){return`${s.width}x${s.height}`}function sE(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,dg.cloneDeep)(t.sl);return(r!=null&&r.resolution||t.sl.screenResolution)&&(o["sauce:options"].screenResolution=rE(r.resolution||t.sl.screenResolution),delete i.screenResolution),nt.merge(i,o,n)}return nt.merge(o,n)}return{}}function nE(s,e,t){return nt.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 oE(s){return s.perfecto?s.perfecto:{}}function iE(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 aE(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=Ia(o,i)),a}function fi(s){var v;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:c,lambdatestService:l}=s;if(o.mode==="local"){let I=[],b=[...mg],T={};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&&(T.binary=t.chromeBinaryLocation),t.mode!=="selenium"&&gg(t,I,b,null,l),fg(i,I,l),{logLevel:cg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:b,extensions:I,...T},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:d,driverRequestRetries:m}=t,u=aE(t,o),f={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:cg,connectionRetryTimeout:d,connectionRetryCount:m,getSessionTimeout:Math.max(l.getSessionTimeout,t.getSessionTimeout),getSessionRetries:l.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!nt.isEmpty(u)&&{headers:u},...t.proxyForGrid&&{agent:global.ProxyAgent(global.proxyUri)}};ou(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,f.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(f.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key);let g=Number(t.browserTimeout/1e3),h=t.browser||(n==null?void 0:n.browserValue);nt.merge(f.desiredCapabilities,sE(t,r,n,e),nE(t,r,n),oE(t),iE(t,h,g),l==null?void 0:l.getCapabilities(t,h,a,c,r));let y=null;switch(!t.ext&&!t.extensionPath&&((v=o.host)!=null&&v.endsWith(".testim.io"))&&!t.canary&&t.mode===Y.EXTENSION&&(y="/opt/testim-headless"),h){case"chrome":case"edge-chromium":f=eE(f,t,n,i,o,y,l);break;case"firefox":f=tE(f,t,l);break;case"safari":case"safari technology preview":f=Qv(f,h);break;default:break}nt.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]],T=_=>{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=T(T(R));Object.keys(k).length&&(as.info(`Adding custom capabilities: ${JSON.stringify(k)}`),Object.assign(f.desiredCapabilities,k))}catch(I){as.error("Failed to load custom capabilities",{error:I,customCapabilities:M.flags.addCustomCapabilities.getValue()})}return f.desiredCapabilities&&!f.capabilities&&(Xv(f),f.capabilities={alwaysMatch:f.desiredCapabilities,firstMatch:[{}]},delete f.desiredCapabilities),f.hostname=f.host,f}var ug,iu,pg,nt,dg,as,cg,nu,mg,au,ou,Xv,eE,lg,lu=w(()=>{"use strict";ug=E(require("fs")),iu=E(require("path")),pg=E(require("crypto")),nt=E(require("lodash"));B();le();j();ge();ie();Ho();dg=require("lodash"),as=A("testim-desired-capabilities-builder"),cg=Jn?"debug":"silent",nu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},mg=["--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"],au=(...s)=>pg.createHash("sha256").update(s.join("")).digest("hex"),ou=s=>s.type===O.DEVICE_FARM||s.type===O.HYBRID&&s.provider==="devicefarm",Xv=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{as.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};eE=nt.memoize(Zv,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(nt.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return au(i,a,c,r,l,o)}),lg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Ne(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 yg(s,e,t){if(!e||!s)return s;if(s.includes("%"))return s.replace(/ /g,"%20");try{return decodeURI(s)!==s?s:encodeURI(s)}catch(r){return t&&t.warn("tried to encode url but failed",{err:r,url:s}),s}}var uu=w(()=>{"use strict"});function pu(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 c(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:c(f))}function l(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:l(u.parentNode):!1}if(!s||!l(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 pu(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)||c(s))}var bg=w(()=>{"use strict"});var Tg,wg,Vt,cE,lE,gi,vg=w(()=>{"use strict";Tg=E(require("promise-queue")),wg=E(require("webdriverio"));le();Be();B();j();Or();bg();uu();is();Vt=A("WebDriverApi"),cE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},lE={implicit:0,pageLoad:1,script:2},gi=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 Vt.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),Ca!==void 0&&(e=Ca);let t=1/0;this.queue=new Tg.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(Ae.GET_BROWSER);try{await this.addToQueue(async()=>{Vt.info("requesting browser",{testResultId:r,testName:t}),N("before this.client.init"),this.client=await wg.remote(e),this.logGridStatus(r)}),N("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,Ae.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 c of a.slots||[])if(((i=c==null?void 0:c.session)==null?void 0:i.sessionId)===t){r=a,n=c;break}}catch(a){if(a.message==="unknown error"){Vt.info("grid status is not supported by the grid",{testResultId:e});return}Vt.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Vt.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){Vt.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(Ne(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(Ne(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(Ae.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,Ae.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Ae.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(_e(e)))}finally{this.seleniumPerfStats.markEnd(t,Ae.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(pu,{ELEMENT:e,[Ht]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Ne(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(yg(e,this.isSafari(),Vt))})}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[lE[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(Ne(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(_e(e)),await this.elementIdValue(_e(e),t)}async getViewportSize(e){let t=await this.execute(cE);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(Ea,i)?[Ea[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(c=>({type:"keyDown",value:c})),a=r.map(c=>({type:"keyUp",value:c}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};if(this.unsupportedActions.has("keys"))return o();try{return await this.addToQueue(()=>n())}catch(i){if(Ne(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(_e(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(Ne(o))return this.unsupportedActions.add("windowHandleSize"),r();throw o}})}}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.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){Vt.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 Vt.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 Eg={};V(Eg,{doubleClick:()=>uE});var uE,Sg=w(()=>{"use strict";uE=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,T){return T>I&&T<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,v=g.originY&&f(h.top,h.top+h.height,g.originY)?g.originY:h.top+h.height/2;return{x:y,y:v}},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}},c=function(u,f,g){if(!window.PointerEvent)return;let h=a(f,g);return new window.PointerEvent(u,h)},l=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)?c(g,f.x,f.y):l(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 Tn={};V(Tn,{dispatchFocus:()=>pE});function pE(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 wn=w(()=>{"use strict"});var Cg={};V(Cg,{WebDriver:()=>Rr});async function gE(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 mE(r):void 0}catch(r){Ue.info("Error getting cdpAddress",r);return}}var cs,xg,Ag,Ue,rr,dE,Ig,mE,sr,fE,Rg,Ir,Rr,vn=w(()=>{"use strict";cs=E(require("lodash"));B();Be();lu();xg=E(require("p-retry")),Ag=E(require("ua-parser-js"));Or();j();uu();vg();z();ge();is();Ue=A("webdriver"),[rr,dE]=[0,2],{extractElementId:Ig,getCdpAddressForHost:mE}=K,sr=()=>(Te(),he(Qt)).getSessionPlayer().codeSnippets,fE=()=>(Te(),he(Qt)).getSessionPlayer().locatorBuilderUtils,Rg=()=>(Te(),he(Qt)).getSessionPlayer().utils,Ir=()=>(Te(),he(Qt)).getSessionPlayer().positionUtils;Rr=class extends gi{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 v,I,b,T,R,k,_,$;let{overrideConfiguration:r,browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:c,executionId:l,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((b=(I=(v=n==null?void 0:n.company)==null?void 0:v.activePlan)==null?void 0:I.premiumFeatures)==null?void 0:b.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let g=fi({browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:c,executionId:l,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 gE(S),N("after getCdpAddress in webdriver.js init"),Ue.info(`init new session testName: ${o}`,{sessionId:this.getSessionId(),testResultId:d}),await ne(h),M.flags.dontFocusOnInit.isEnabled()||await y(),N("after focus and delay in webdriver.js init")}catch(S){let x=JSON.stringify(cs.omit(g,"capabilities.extensions","capabilities.capabilities.extensions"));Ue.error("failed to init webdriver",{err:S,capabilitiesAsString:x});let L=((R=(T=n==null?void 0:n.company)==null?void 0:T.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 Mr(S.message):S.message.match(/capabilit(y|ies)/)?new Xn(S.message):new Error("failed to init client driver")}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>cs.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,c)=>{let l=this._keepAliveRequests.find(d=>d.id===c);l&&(l[a]=Date.now())};function o(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let i=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,Ue.warn("close unexpected alert open"),await this.alertAccept().catch(c=>Ue.warn("failed to click on alert",{err:c}));return}if(Ue.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;Ue.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:c,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=c&&this.browserClosedCallbacks.forEach(l=>{try{l(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=Ig(r.value);return await this.switchToFrame({ELEMENT:n,[Ht]: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 Qn:r}}async getElement(t){var o;let r=this.seleniumPerfStats.markStart(Ae.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,Ae.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 = ${sr().getLocatedElementCode};
24
24
  return fn.apply(null, arguments);
25
25
  `,t)}finally{this.seleniumPerfStats.markEnd(r,Ae.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(r,Ae.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 c=getLocatedElement(a);if(!c)throw new Error("could not find dynamic parent");c.setAttribute(o,i)}await this.executeJS(`