browserstack-cypress-cli 1.33.0 → 1.35.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.
@@ -336,26 +336,23 @@ afterEach(() => {
336
336
  } else if (attributes.prevAttempts && attributes.prevAttempts.length > 0) {
337
337
  filePath = (attributes.prevAttempts[0].invocationDetails && attributes.prevAttempts[0].invocationDetails.relativeFile) || '';
338
338
  }
339
- const payloadToSend = {
340
- "saveResults": shouldScanTestForAccessibility,
341
- "testDetails": {
342
- "name": attributes.title,
343
- "testRunId": '5058', // variable not consumed, shouldn't matter what we send
344
- "filePath": filePath,
345
- "scopeList": [
346
- filePath,
347
- attributes.title
348
- ]
349
- },
350
- "platform": {
351
- "os_name": os_data,
352
- "os_version": Cypress.env("OS_VERSION"),
353
- "browser_name": Cypress.browser.name,
354
- "browser_version": Cypress.browser.version
339
+
340
+ let testRunUuid = null;
341
+ cy.task('get_test_run_uuid', { testIdentifier: attributes.title })
342
+ .then((response) => {
343
+ if (response && response.testRunUuid) {
344
+ testRunUuid = response.testRunUuid;
355
345
  }
356
- };
357
- browserStackLog(`Saving accessibility test results`);
358
- cy.wrap(saveTestResults(win, payloadToSend), {timeout: 30000}).then(() => {
346
+
347
+ const payloadToSend = {
348
+ "thTestRunUuid": testRunUuid,
349
+ "thBuildUuid": Cypress.env("BROWSERSTACK_TESTHUB_UUID"),
350
+ "thJwtToken": Cypress.env("BROWSERSTACK_TESTHUB_JWT")
351
+ };
352
+ browserStackLog(`Payload to send: ${JSON.stringify(payloadToSend)}`);
353
+
354
+ return cy.wrap(saveTestResults(win, payloadToSend), {timeout: 30000});
355
+ }).then(() => {
359
356
  browserStackLog(`Saved accessibility test results`);
360
357
  })
361
358
 
@@ -109,7 +109,7 @@ exports.createAccessibilityTestRun = async (user_config, framework) => {
109
109
  logger.debug(`BrowserStack Accessibility Automation Test Run ID: ${response.data.data.id}`);
110
110
 
111
111
  this.setAccessibilityCypressCapabilities(user_config, response.data);
112
- helper.setBrowserstackCypressCliDependency(user_config);
112
+ if(user_config.run_settings.auto_import_dev_dependencies != true) helper.setBrowserstackCypressCliDependency(user_config);
113
113
 
114
114
  } catch (error) {
115
115
  if (error.response) {
@@ -1,6 +1,7 @@
1
1
  const path = require("node:path");
2
2
  const { decodeJWTToken } = require("../../helpers/utils");
3
3
  const utils = require('../../helpers/utils');
4
+ const http = require('http');
4
5
 
5
6
  const browserstackAccessibility = (on, config) => {
6
7
  let browser_validation = true;
@@ -14,6 +15,51 @@ const browserstackAccessibility = (on, config) => {
14
15
 
15
16
  return null
16
17
  },
18
+ get_test_run_uuid({ testIdentifier, retries = 15, interval = 300 } = {}) {
19
+ return new Promise((resolve) => {
20
+ if(!testIdentifier) return resolve(null);
21
+ const port = process.env.REPORTER_API_PORT_NO;
22
+ let attempt = 0;
23
+ const fetchUuid = () => {
24
+ const options = {
25
+ hostname: '127.0.0.1',
26
+ port,
27
+ path: `/test-uuid?testIdentifier=${encodeURIComponent(testIdentifier)}`,
28
+ method: 'GET',
29
+ timeout: 2000
30
+ };
31
+ const httpModule = http;
32
+ const req = httpModule.request(options, (res) => {
33
+ let data = '';
34
+ res.on('data', (chunk) => data += chunk);
35
+ res.on('end', () => {
36
+ if(res.statusCode === 200) {
37
+ try {
38
+ const json = JSON.parse(data || '{}');
39
+ return resolve({ testRunUuid: json.testRunUuid || null });
40
+ } catch(e) {
41
+ return resolve(null);
42
+ }
43
+ } else if (res.statusCode === 404) {
44
+ // Server up but endpoint not responding as expected – stop retrying.
45
+ return resolve(null);
46
+ } else {
47
+ retryOrResolve();
48
+ }
49
+ });
50
+ });
51
+ req.on('error', () => retryOrResolve());
52
+ req.on('timeout', () => { req.destroy(); retryOrResolve(); });
53
+ req.end();
54
+ };
55
+ const retryOrResolve = () => {
56
+ attempt += 1;
57
+ if(attempt >= retries) return resolve(null);
58
+ setTimeout(fetchUuid, interval);
59
+ };
60
+ fetchUuid();
61
+ });
62
+ }
17
63
  })
18
64
  on('before:browser:launch', (browser = {}, launchOptions) => {
19
65
  try {
@@ -51,6 +97,10 @@ const browserstackAccessibility = (on, config) => {
51
97
  config.env.ACCESSIBILITY_EXTENSION_PATH = process.env.ACCESSIBILITY_EXTENSION_PATH
52
98
  config.env.OS_VERSION = process.env.OS_VERSION
53
99
  config.env.OS = process.env.OS
100
+ config.env.BROWSERSTACK_TESTHUB_UUID = process.env.BROWSERSTACK_TESTHUB_UUID
101
+ config.env.BROWSERSTACK_TESTHUB_JWT = process.env.BROWSERSTACK_TESTHUB_JWT
102
+ config.env.BROWSERSTACK_TESTHUB_API_PORT = process.env.BROWSERSTACK_TESTHUB_API_PORT
103
+ config.env.REPORTER_API_PORT_NO = process.env.REPORTER_API_PORT_NO
54
104
 
55
105
  config.env.IS_ACCESSIBILITY_EXTENSION_LOADED = browser_validation.toString()
56
106
 
@@ -37,7 +37,8 @@ const {
37
37
  supportFileCleanup
38
38
  } = require('../accessibility-automation/helper');
39
39
  const { isTurboScaleSession, getTurboScaleGridDetails, patchCypressConfigFileContent, atsFileCleanup } = require('../helpers/atsHelper');
40
-
40
+ const { shouldProcessEventForTesthub, checkAndSetAccessibility, findAvailablePort } = require('../testhub/utils');
41
+ const TestHubHandler = require('../testhub/testhubHandler');
41
42
 
42
43
  module.exports = function run(args, rawArgs) {
43
44
  utils.normalizeTestReportingEnvVars();
@@ -112,9 +113,15 @@ module.exports = function run(args, rawArgs) {
112
113
  // set build tag caps
113
114
  utils.setBuildTags(bsConfig, args);
114
115
 
116
+ checkAndSetAccessibility(bsConfig, isAccessibilitySession);
117
+
118
+ const preferredPort = 5348;
119
+ const port = await findAvailablePort(preferredPort);
120
+ process.env.REPORTER_API_PORT_NO = port
121
+
115
122
  // Send build start to TEST REPORTING AND ANALYTICS
116
- if(isTestObservabilitySession) {
117
- await launchTestSession(bsConfig, bsConfigPath);
123
+ if(shouldProcessEventForTesthub()) {
124
+ await TestHubHandler.launchBuild(bsConfig, bsConfigPath);
118
125
  utils.setO11yProcessHooks(null, bsConfig, args, null, buildReportData);
119
126
  }
120
127
 
@@ -143,13 +150,12 @@ module.exports = function run(args, rawArgs) {
143
150
  // set the no-wrap
144
151
  utils.setNoWrap(bsConfig, args);
145
152
 
153
+ // process auto-import dev dependencies
154
+ utils.processAutoImportDependencies(bsConfig.run_settings);
155
+
146
156
  // add cypress dependency if missing
147
157
  utils.setCypressNpmDependency(bsConfig);
148
158
 
149
- if (isAccessibilitySession && isBrowserstackInfra) {
150
- await createAccessibilityTestRun(bsConfig);
151
- }
152
-
153
159
  if (turboScaleSession) {
154
160
  const gridDetails = await getTurboScaleGridDetails(bsConfig, args, rawArgs);
155
161
 
@@ -203,7 +209,7 @@ module.exports = function run(args, rawArgs) {
203
209
  markBlockStart('validateConfig');
204
210
  logger.debug("Started configs validation");
205
211
  return capabilityHelper.validate(bsConfig, args).then(function (cypressConfigFile) {
206
- if(process.env.BROWSERSTACK_TEST_ACCESSIBILITY) {
212
+ if(process.env.BROWSERSTACK_TEST_ACCESSIBILITY === 'true') {
207
213
  setAccessibilityEventListeners(bsConfig);
208
214
  }
209
215
  if(process.env.BS_TESTOPS_BUILD_COMPLETED) {
@@ -65,6 +65,8 @@ const createBuild = (bsConfig, zip) => {
65
65
  if(error.response) {
66
66
  logger.error(utils.formatRequest(error.response.statusText, error.response, error.response.data));
67
67
  reject(`${Constants.userMessages.BUILD_FAILED} Error: ${error.response.data.message}`);
68
+ } else {
69
+ reject(error);
68
70
  }
69
71
  }
70
72
  }).catch(function(err){
@@ -183,11 +183,17 @@ const getAccessibilityPlatforms = (bsConfig) => {
183
183
  const addCypressZipStartLocation = (runSettings) => {
184
184
  let resolvedHomeDirectoryPath = path.resolve(runSettings.home_directory);
185
185
  let resolvedCypressConfigFilePath = path.resolve(runSettings.cypressConfigFilePath);
186
- runSettings.cypressZipStartLocation = path.dirname(resolvedCypressConfigFilePath.split(resolvedHomeDirectoryPath)[1]);
186
+
187
+ // Convert to POSIX style paths for consistent behavior
188
+ let posixHomePath = resolvedHomeDirectoryPath.split(path.sep).join(path.posix.sep);
189
+ let posixConfigPath = resolvedCypressConfigFilePath.split(path.sep).join(path.posix.sep);
190
+
191
+ runSettings.cypressZipStartLocation = path.posix.dirname(posixConfigPath.split(posixHomePath)[1]);
187
192
  runSettings.cypressZipStartLocation = runSettings.cypressZipStartLocation.substring(1);
188
193
  logger.debug(`Setting cypress zip start location = ${runSettings.cypressZipStartLocation}`);
189
194
  }
190
195
 
196
+
191
197
  const validate = (bsConfig, args) => {
192
198
  return new Promise(function (resolve, reject) {
193
199
  logger.info(Constants.userMessages.VALIDATING_CONFIG);
@@ -196,6 +196,28 @@ const validationMessages = {
196
196
  "You have specified '--record' flag but you've not provided the '--record-key' and we could not find any value in 'CYPRESS_RECORD_KEY' environment variable. Your record functionality on cypress.io dashboard might not work as it needs the key and projectId",
197
197
  NODE_VERSION_PARSING_ERROR:
198
198
  "We weren't able to successfully parse the specified nodeVersion. We will be using the default nodeVersion to run your tests.",
199
+ AUTO_IMPORT_CONFLICT_ERROR:
200
+ "Cannot use both 'auto_import_dev_dependencies' and manual npm dependency configuration. Please either set 'auto_import_dev_dependencies' to false or remove manual 'npm_dependencies', 'win_npm_dependencies', and 'mac_npm_dependencies' configurations.",
201
+ AUTO_IMPORT_INVALID_TYPE:
202
+ "'auto_import_dev_dependencies' must be a boolean value (true or false).",
203
+ PACKAGE_JSON_NOT_FOUND:
204
+ "package.json not found in project directory. Cannot auto-import devDependencies.",
205
+ PACKAGE_JSON_PERMISSION_DENIED:
206
+ "Cannot read package.json due to permission issues. Please check file permissions.",
207
+ PACKAGE_JSON_MALFORMED:
208
+ "package.json contains invalid JSON syntax. Please fix the JSON format.",
209
+ PACKAGE_JSON_NOT_OBJECT:
210
+ "package.json must contain a JSON object, not an array or other type.",
211
+ DEVDEPS_INVALID_FORMAT:
212
+ "devDependencies field in package.json must be an object, not an array or other type.",
213
+ EXCLUDE_DEPS_INVALID_TYPE:
214
+ "'exclude_dependencies' must be an array of strings.",
215
+ EXCLUDE_DEPS_INVALID_PATTERNS:
216
+ "'exclude_dependencies' must contain only string values representing regex patterns.",
217
+ INVALID_REGEX_PATTERN:
218
+ "Invalid regex pattern found in 'exclude_dependencies': {pattern}. Please provide valid regex patterns.",
219
+ DEPENDENCIES_PARAM_INVALID:
220
+ "Dependencies parameter must be an object.",
199
221
  };
200
222
 
201
223
  const cliMessages = {
@@ -182,6 +182,17 @@ exports.getGitMetaData = () => {
182
182
  }
183
183
  })
184
184
  }
185
+
186
+ exports.getHostInfo = () => {
187
+ return {
188
+ hostname: os.hostname(),
189
+ platform: os.platform(),
190
+ type: os.type(),
191
+ version: os.version(),
192
+ arch: os.arch()
193
+ }
194
+ }
195
+
185
196
  exports.getCiInfo = () => {
186
197
  var env = process.env;
187
198
  // Jenkins
@@ -32,9 +32,10 @@ const setupPackageFolder = (runSettings, directoryPath) => {
32
32
  }
33
33
 
34
34
  // Combine win and mac specific dependencies if present
35
- if (typeof runSettings.npm_dependencies === 'object') {
35
+ const combinedDependencies = combineMacWinNpmDependencies(runSettings);
36
+ if (combinedDependencies && Object.keys(combinedDependencies).length > 0) {
36
37
  Object.assign(packageJSON, {
37
- devDependencies: combineMacWinNpmDependencies(runSettings),
38
+ devDependencies: combinedDependencies,
38
39
  });
39
40
  }
40
41
 
@@ -13,6 +13,120 @@ exports.detectLanguage = (cypress_config_filename) => {
13
13
  return constants.CYPRESS_V10_AND_ABOVE_CONFIG_FILE_EXTENSIONS.includes(extension) ? extension : 'js'
14
14
  }
15
15
 
16
+ function resolveTsConfigPath(bsConfig, cypress_config_filepath) {
17
+ const working_dir = path.dirname(cypress_config_filepath);
18
+
19
+ // Priority order for finding tsconfig
20
+ const candidates = [
21
+ bsConfig.run_settings && bsConfig.run_settings.ts_config_file_path, // User specified
22
+ path.join(working_dir, 'tsconfig.json'), // Same directory as cypress config
23
+ path.join(working_dir, '..', 'tsconfig.json'), // Parent directory
24
+ path.join(process.cwd(), 'tsconfig.json') // Project root
25
+ ].filter(Boolean).map(p => path.resolve(p));
26
+
27
+ for (const candidate of candidates) {
28
+ if (fs.existsSync(candidate)) {
29
+ logger.debug(`Found tsconfig at: ${candidate}`);
30
+ return candidate;
31
+ }
32
+ }
33
+
34
+ return null;
35
+ }
36
+
37
+ function generateTscCommandAndTempTsConfig(bsConfig, bstack_node_modules_path, complied_js_dir, cypress_config_filepath) {
38
+ const working_dir = path.dirname(cypress_config_filepath);
39
+ const typescript_path = path.join(bstack_node_modules_path, 'typescript', 'bin', 'tsc');
40
+ const tsc_alias_path = require.resolve('tsc-alias/dist/bin/index.js');
41
+
42
+ // Smart tsconfig detection and validation
43
+ const resolvedTsConfigPath = resolveTsConfigPath(bsConfig, cypress_config_filepath);
44
+ let hasValidTsConfig = false;
45
+
46
+ if (resolvedTsConfigPath) {
47
+ try {
48
+ // Validate the tsconfig is readable and valid JSON
49
+ const tsConfigContent = fs.readFileSync(resolvedTsConfigPath, 'utf8');
50
+ JSON.parse(tsConfigContent);
51
+ hasValidTsConfig = true;
52
+ logger.info(`Using existing tsconfig: ${resolvedTsConfigPath}`);
53
+ } catch (error) {
54
+ logger.warn(`Invalid tsconfig file: ${resolvedTsConfigPath}, falling back to default configuration. Error: ${error.message}`);
55
+ hasValidTsConfig = false;
56
+ }
57
+ } else {
58
+ logger.info('No tsconfig found, using default TypeScript configuration');
59
+ }
60
+
61
+ let tempTsConfig;
62
+
63
+ if (hasValidTsConfig) {
64
+ // Scenario 1: User has valid tsconfig - use extends approach
65
+ tempTsConfig = {
66
+ extends: resolvedTsConfigPath,
67
+ compilerOptions: {
68
+ // Force override critical parameters for BrowserStack compatibility
69
+ "outDir": path.basename(complied_js_dir),
70
+ "listEmittedFiles": true,
71
+ // Ensure these are always set regardless of base tsconfig
72
+ "allowSyntheticDefaultImports": true,
73
+ "esModuleInterop": true
74
+ },
75
+ include: [cypress_config_filepath]
76
+ };
77
+ } else {
78
+ // Scenario 2: No tsconfig or invalid tsconfig - create standalone with all basic parameters
79
+ tempTsConfig = {
80
+ compilerOptions: {
81
+ // Preserve old command-line parameters for backwards compatibility
82
+ "outDir": path.basename(complied_js_dir),
83
+ "listEmittedFiles": true,
84
+ "allowSyntheticDefaultImports": true,
85
+ "module": "commonjs",
86
+ "declaration": false,
87
+
88
+ // Add essential missing parameters for robust compilation
89
+ "target": "es2017",
90
+ "moduleResolution": "node",
91
+ "esModuleInterop": true,
92
+ "allowJs": true,
93
+ "skipLibCheck": true,
94
+ "forceConsistentCasingInFileNames": true,
95
+ "resolveJsonModule": true,
96
+ "strict": false, // Avoid breaking existing code
97
+ "noEmitOnError": false // Continue compilation even with errors
98
+ },
99
+ include: [cypress_config_filepath],
100
+ exclude: ["node_modules", "dist", "build"]
101
+ };
102
+ }
103
+
104
+ // Write the temporary tsconfig
105
+ const tempTsConfigPath = path.join(working_dir, 'tsconfig.singlefile.tmp.json');
106
+ fs.writeFileSync(tempTsConfigPath, JSON.stringify(tempTsConfig, null, 2));
107
+ logger.info(`Temporary tsconfig created at: ${tempTsConfigPath}`);
108
+
109
+ // Platform-specific command generation
110
+ const isWindows = /^win/.test(process.platform);
111
+
112
+ if (isWindows) {
113
+ // Windows: Use && to chain commands, no space after SET
114
+ const setNodePath = isWindows
115
+ ? `set NODE_PATH=${bstack_node_modules_path}`
116
+ : `NODE_PATH="${bstack_node_modules_path}"`;
117
+
118
+ const tscCommand = `${setNodePath} && node "${typescript_path}" --project "${tempTsConfigPath}" && ${setNodePath} && node "${tsc_alias_path}" --project "${tempTsConfigPath}" --verbose`;
119
+ logger.info(`TypeScript compilation command: ${tscCommand}`);
120
+ return { tscCommand, tempTsConfigPath };
121
+ } else {
122
+ // Unix/Linux/macOS: Use ; to separate commands or && to chain
123
+ const nodePathPrefix = `NODE_PATH=${bstack_node_modules_path}`;
124
+ const tscCommand = `${nodePathPrefix} node "${typescript_path}" --project "${tempTsConfigPath}" && ${nodePathPrefix} node "${tsc_alias_path}" --project "${tempTsConfigPath}" --verbose`;
125
+ logger.info(`TypeScript compilation command: ${tscCommand}`);
126
+ return { tscCommand, tempTsConfigPath };
127
+ }
128
+ }
129
+
16
130
  exports.convertTsConfig = (bsConfig, cypress_config_filepath, bstack_node_modules_path) => {
17
131
  const cypress_config_filename = bsConfig.run_settings.cypress_config_filename
18
132
  const working_dir = path.dirname(cypress_config_filepath);
@@ -22,19 +136,12 @@ exports.convertTsConfig = (bsConfig, cypress_config_filepath, bstack_node_module
22
136
  }
23
137
  fs.mkdirSync(complied_js_dir, { recursive: true })
24
138
 
25
- const typescript_path = path.join(bstack_node_modules_path, 'typescript', 'bin', 'tsc')
26
-
27
- let tsc_command = `NODE_PATH=${bstack_node_modules_path} node "${typescript_path}" --outDir "${complied_js_dir}" --listEmittedFiles true --allowSyntheticDefaultImports --module commonjs --declaration false "${cypress_config_filepath}"`
139
+ const { tscCommand, tempTsConfigPath } = generateTscCommandAndTempTsConfig(bsConfig, bstack_node_modules_path, complied_js_dir, cypress_config_filepath);
28
140
 
29
- if (/^win/.test(process.platform)) {
30
- tsc_command = `set NODE_PATH=${bstack_node_modules_path}&& node "${typescript_path}" --outDir "${complied_js_dir}" --listEmittedFiles true --allowSyntheticDefaultImports --module commonjs --declaration false "${cypress_config_filepath}"`
31
- }
32
-
33
-
34
141
  let tsc_output
35
142
  try {
36
- logger.debug(`Running: ${tsc_command}`)
37
- tsc_output = cp.execSync(tsc_command, { cwd: working_dir })
143
+ logger.debug(`Running: ${tscCommand}`)
144
+ tsc_output = cp.execSync(tscCommand, { cwd: working_dir })
38
145
  } catch (err) {
39
146
  // error while compiling ts files
40
147
  logger.debug(err.message);
@@ -44,6 +151,21 @@ exports.convertTsConfig = (bsConfig, cypress_config_filepath, bstack_node_module
44
151
  logger.debug(`Saved compiled js output at: ${complied_js_dir}`);
45
152
  logger.debug(`Finding compiled cypress config file in: ${complied_js_dir}`);
46
153
 
154
+ // Clean up the temporary tsconfig file
155
+ if (fs.existsSync(tempTsConfigPath)) {
156
+ fs.unlinkSync(tempTsConfigPath);
157
+ logger.debug(`Temporary tsconfig file removed: ${tempTsConfigPath}`);
158
+ }
159
+
160
+ if (tsc_output) {
161
+ logger.debug(tsc_output.toString());
162
+ }
163
+
164
+ if (!tsc_output) {
165
+ logger.error('No TypeScript compilation output available');
166
+ return null;
167
+ }
168
+
47
169
  const lines = tsc_output.toString().split('\n');
48
170
  let foundLine = null;
49
171
  for (let i = 0; i < lines.length; i++) {
@@ -53,7 +175,7 @@ exports.convertTsConfig = (bsConfig, cypress_config_filepath, bstack_node_module
53
175
  }
54
176
  }
55
177
  if (foundLine === null) {
56
- logger.error(`No compiled cypress config found. There might some error running ${tsc_command} command`)
178
+ logger.error(`No compiled cypress config found. There might some error running ${tscCommand} command`)
57
179
  return null
58
180
  } else {
59
181
  const compiled_cypress_config_filepath = foundLine.split('TSFILE: ').pop()