browserstack-cypress-cli 1.6.0 → 1.8.1

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.
@@ -3,6 +3,9 @@ const os = require("os");
3
3
  const path = require("path");
4
4
  const fs = require("fs");
5
5
  const glob = require('glob');
6
+ const getmac = require('getmac').default;
7
+ const { v4: uuidv4 } = require('uuid');
8
+ const browserstack = require('browserstack-local');
6
9
 
7
10
  const usageReporting = require("./usageReporting"),
8
11
  logger = require("./logger").winstonLogger,
@@ -11,6 +14,8 @@ const usageReporting = require("./usageReporting"),
11
14
  syncCliLogger = require("../helpers/logger").syncCliLogger,
12
15
  config = require("../helpers/config");
13
16
 
17
+ const request = require('request');
18
+
14
19
  exports.validateBstackJson = (bsConfigPath) => {
15
20
  return new Promise(function (resolve, reject) {
16
21
  try {
@@ -33,34 +38,46 @@ exports.getErrorCodeFromMsg = (errMsg) => {
33
38
  let errorCode = null;
34
39
  switch (errMsg) {
35
40
  case Constants.validationMessages.EMPTY_BROWSERSTACK_JSON:
36
- errorCode = "bstack_json_invalid_empty";
41
+ errorCode = 'bstack_json_invalid_empty';
37
42
  break;
38
43
  case Constants.validationMessages.INCORRECT_AUTH_PARAMS:
39
- errorCode = "bstack_json_invalid_missing_keys";
44
+ errorCode = 'bstack_json_invalid_missing_keys';
40
45
  break;
41
46
  case Constants.validationMessages.EMPTY_BROWSER_LIST:
42
- errorCode = "bstack_json_invalid_no_browsers";
47
+ errorCode = 'bstack_json_invalid_no_browsers';
43
48
  break;
44
49
  case Constants.validationMessages.EMPTY_RUN_SETTINGS:
45
- errorCode = "bstack_json_invalid_no_run_settings";
50
+ errorCode = 'bstack_json_invalid_no_run_settings';
46
51
  break;
47
52
  case Constants.validationMessages.EMPTY_CYPRESS_PROJ_DIR:
48
- errorCode = "bstack_json_invalid_no_cypress_proj_dir";
53
+ errorCode = 'bstack_json_invalid_no_cypress_proj_dir';
49
54
  break;
50
55
  case Constants.validationMessages.INVALID_DEFAULT_AUTH_PARAMS:
51
- errorCode = "bstack_json_default_auth_keys";
56
+ errorCode = 'bstack_json_default_auth_keys';
52
57
  break;
53
58
  case Constants.validationMessages.INVALID_PARALLELS_CONFIGURATION:
54
- errorCode = "invalid_parallels_specified";
59
+ errorCode = 'invalid_parallels_specified';
60
+ break;
61
+ case Constants.validationMessages.INVALID_LOCAL_IDENTIFIER:
62
+ errorCode = 'invalid_local_identifier';
63
+ break;
64
+ case Constants.validationMessages.INVALID_CLI_LOCAL_IDENTIFIER:
65
+ errorCode = 'invalid_local_identifier';
66
+ break;
67
+ case Constants.validationMessages.INVALID_LOCAL_MODE:
68
+ errorCode = 'invalid_local_mode';
69
+ break;
70
+ case Constants.validationMessages.INVALID_LOCAL_CONFIG_FILE:
71
+ errorCode = 'invalid_local_config_file';
55
72
  break;
56
73
  case Constants.validationMessages.LOCAL_NOT_SET:
57
- errorCode = "cypress_json_base_url_no_local";
74
+ errorCode = 'cypress_json_base_url_no_local';
58
75
  break;
59
76
  case Constants.validationMessages.INCORRECT_DIRECTORY_STRUCTURE:
60
- errorCode = "invalid_directory_structure";
77
+ errorCode = 'invalid_directory_structure';
61
78
  break;
62
79
  case Constants.validationMessages.INVALID_CYPRESS_CONFIG_FILE:
63
- errorCode = "invalid_cypress_config_file";
80
+ errorCode = 'invalid_cypress_config_file';
64
81
  break;
65
82
  }
66
83
  if (
@@ -141,6 +158,12 @@ exports.setDefaults = (bsConfig, args) => {
141
158
  if (bsConfig.run_settings && this.isUndefined(bsConfig.run_settings.npm_dependencies)) {
142
159
  bsConfig.run_settings.npm_dependencies = {}
143
160
  }
161
+
162
+ // setting connection_settings to {} if not present
163
+ if (this.isUndefined(bsConfig.connection_settings)) {
164
+ bsConfig.connection_settings = {};
165
+ }
166
+
144
167
  }
145
168
 
146
169
  exports.setUsername = (bsConfig, args) => {
@@ -247,7 +270,7 @@ exports.isParallelValid = (value) => {
247
270
  }
248
271
 
249
272
  exports.getUserAgent = () => {
250
- return `BStack-Cypress-CLI/1.5.1 (${os.arch()}/${os.platform()}/${os.release()})`;
273
+ return `BStack-Cypress-CLI/1.8.1 (${os.arch()}/${os.platform()}/${os.release()})`;
251
274
  };
252
275
 
253
276
  exports.isAbsolute = (configPath) => {
@@ -311,36 +334,255 @@ exports.getLocalFlag = (connectionSettings) => {
311
334
  );
312
335
  };
313
336
 
314
- exports.setLocal = (bsConfig) => {
315
- if (!this.isUndefined(process.env.BROWSERSTACK_LOCAL)) {
337
+ exports.setLocal = (bsConfig, args) => {
338
+ if (!this.isUndefined(args.local)) {
316
339
  let local = false;
317
- if (String(process.env.BROWSERSTACK_LOCAL).toLowerCase() === "true")
340
+ if (String(args.local).toLowerCase() === 'true') {
318
341
  local = true;
319
- bsConfig["connection_settings"]["local"] = local;
342
+ }
343
+ bsConfig['connection_settings']['local'] = local;
344
+ } else if (!this.isUndefined(process.env.BROWSERSTACK_LOCAL)) {
345
+ let local = false;
346
+ if (String(process.env.BROWSERSTACK_LOCAL).toLowerCase() === 'true') {
347
+ local = true;
348
+ }
349
+ bsConfig['connection_settings']['local'] = local;
320
350
  logger.info(
321
- "Reading local setting from the environment variable BROWSERSTACK_LOCAL"
351
+ 'Reading local setting from the environment variable BROWSERSTACK_LOCAL'
322
352
  );
353
+ } else if (!this.isUndefined(bsConfig['connection_settings']['local'])) {
354
+ let local = false;
355
+ if (String(bsConfig['connection_settings']['local']).toLowerCase() === 'true') {
356
+ local = true;
357
+ }
358
+ bsConfig['connection_settings']['local'] = local;
359
+ } else if (
360
+ this.isUndefined(bsConfig['connection_settings']['local']) &&
361
+ (!this.isUndefined(args.localMode) ||
362
+ !this.isUndefined(bsConfig['connection_settings']['local_mode']))
363
+ ) {
364
+ bsConfig['connection_settings']['local'] = true;
365
+ bsConfig.connection_settings.local_inferred = true;
323
366
  }
324
367
  };
325
368
 
326
- exports.setLocalIdentifier = (bsConfig) => {
327
- if (!this.isUndefined(process.env.BROWSERSTACK_LOCAL_IDENTIFIER)) {
369
+ exports.setLocalIdentifier = (bsConfig, args) => {
370
+ if (!this.isUndefined(args.localIdentifier)){
371
+ bsConfig["connection_settings"]["local_identifier"] = args.localIdentifier;
372
+ bsConfig['connection_settings']['local_mode'] = "always-on";
373
+ } else if (!this.isUndefined(process.env.BROWSERSTACK_LOCAL_IDENTIFIER)) {
328
374
  bsConfig["connection_settings"]["local_identifier"] =
329
375
  process.env.BROWSERSTACK_LOCAL_IDENTIFIER;
330
376
  logger.info(
331
377
  "Reading local identifier from the environment variable BROWSERSTACK_LOCAL_IDENTIFIER"
332
378
  );
379
+ bsConfig['connection_settings']['local_mode'] = 'always-on';
380
+ } else if (
381
+ bsConfig['connection_settings']['local'] &&
382
+ !this.isUndefined(bsConfig["connection_settings"]["local_identifier"])
383
+ ){
384
+ bsConfig['connection_settings']['local_mode'] = 'always-on';
385
+ } else if (
386
+ bsConfig['connection_settings']['local'] &&
387
+ this.isUndefined(bsConfig["connection_settings"]["local_identifier"])
388
+ ){
389
+ bsConfig["connection_settings"]["local_identifier"] = this.generateLocalIdentifier(bsConfig['connection_settings']['local_mode']);
390
+ }
391
+ };
392
+
393
+ exports.setLocalMode = (bsConfig, args) => {
394
+ if(String(bsConfig["connection_settings"]["local"]).toLowerCase() === "true"){
395
+ let local_mode = 'on-demand';
396
+
397
+ let localModeUndefined= this.isUndefined(bsConfig["connection_settings"]["local_mode"]);
398
+
399
+ if (!this.isUndefined(args.localMode)) {
400
+ if(String(args.localMode) === "always-on"){
401
+ local_mode = 'always-on';
402
+ }
403
+ } else if (!localModeUndefined && !["always-on", "on-demand"].includes(bsConfig['connection_settings']['local_mode'])) {
404
+ bsConfig.connection_settings.user_defined_local_mode_warning = bsConfig['connection_settings']['local_mode'];
405
+ } else if (
406
+ !this.isUndefined(bsConfig['connection_settings']['local_mode']) &&
407
+ String(bsConfig['connection_settings']['local_mode']).toLowerCase() ===
408
+ 'always-on'
409
+ ) {
410
+ local_mode = 'always-on';
411
+ }
412
+ bsConfig['connection_settings']['local_mode'] = local_mode;
413
+ if (this.isUndefined(args.sync) || !args.sync ){
414
+ bsConfig['connection_settings']['sync_inferred'] = true;
415
+ }
416
+ args.sync = true;
417
+
418
+ let localModeInferred = !(this.searchForOption('--local-mode'));
419
+
420
+ if (localModeInferred && localModeUndefined) {
421
+ bsConfig.connection_settings.local_mode_inferred = local_mode;
422
+ }
423
+ }
424
+ };
425
+
426
+ exports.setupLocalTesting = (bsConfig, args) => {
427
+ return new Promise(async (resolve, reject) => {
428
+ if( bsConfig['connection_settings'] && bsConfig['connection_settings']['local'] && String(bsConfig['connection_settings']['local']) === "true" ){
429
+ let localIdentifierRunning = await this.checkLocalIdentifierRunning(
430
+ bsConfig, bsConfig['connection_settings']['local_identifier']
431
+ );
432
+ if (!localIdentifierRunning){
433
+ var bs_local = this.getLocalBinary();
434
+ var bs_local_args = this.setLocalArgs(bsConfig, args);
435
+ let that = this;
436
+ logger.info('Setting up Local testing...');
437
+ bs_local.start(bs_local_args, function (localStartError) {
438
+ if (that.isUndefined(localStartError)) {
439
+ resolve(bs_local);
440
+ } else {
441
+ let message = `name: ${localStartError.name}, message: ${localStartError.message}, extra: ${localStartError.extra}`,
442
+ errorCode = "local_start_error";
443
+ that.sendUsageReport(
444
+ bsConfig,
445
+ args,
446
+ message,
447
+ Constants.messageTypes.ERROR,
448
+ errorCode
449
+ );
450
+ reject(Constants.userMessages.LOCAL_START_FAILED);
451
+ }
452
+ });
453
+ } else {
454
+ resolve();
455
+ }
456
+ } else {
457
+ resolve();
458
+ }
459
+ });
460
+ };
461
+
462
+ exports.stopLocalBinary = (bsConfig, bs_local, args) => {
463
+ return new Promise(async (resolve, reject) => {
464
+ if(bsConfig['connection_settings'] && bsConfig['connection_settings']['local']){
465
+ let localIdentifierRunning = await this.checkLocalIdentifierRunning(bsConfig,bsConfig["connection_settings"]["local_identifier"]);
466
+ if(!localIdentifierRunning){
467
+ let message = `Local Binary not running.`,
468
+ errorCode = 'local_identifier_error';
469
+ this.sendUsageReport(
470
+ bsConfig,
471
+ args,
472
+ message,
473
+ Constants.messageTypes.ERROR,
474
+ errorCode
475
+ );
476
+ }
477
+ }
478
+ if (!this.isUndefined(bs_local) && bs_local.isRunning() && bsConfig['connection_settings'] && bsConfig['connection_settings']['local_mode'].toLowerCase() != "always-on") {
479
+ let that = this;
480
+ bs_local.stop(function (localStopError) {
481
+ if (that.isUndefined(localStopError)) {
482
+ resolve();
483
+ } else {
484
+ let message = `name: ${localStopError.name}, message: ${localStopError.message}, extra: ${localStopError.extra}`,
485
+ errorCode = 'local_stop_error';
486
+ that.sendUsageReport(
487
+ bsConfig,
488
+ args,
489
+ message,
490
+ Constants.messageTypes.ERROR,
491
+ errorCode
492
+ );
493
+ resolve(Constants.userMessages.LOCAL_STOP_FAILED);
494
+ }
495
+ });
496
+ } else {
497
+ resolve();
498
+ }
499
+ });
500
+ };
501
+
502
+ exports.getLocalBinary = () => {
503
+ return new browserstack.Local();
504
+ };
505
+
506
+ exports.setLocalArgs = (bsConfig, args) => {
507
+ let local_args = {}
508
+ local_args['key'] = bsConfig['auth']['access_key'];
509
+ local_args['localIdentifier'] = bsConfig["connection_settings"]["local_identifier"];
510
+ local_args['daemon'] = true;
511
+ local_args['enable-logging-for-api'] = true
512
+ local_args['source'] = `cypress:${usageReporting.cli_version_and_path(bsConfig).version}`;
513
+ if(!this.isUndefined(bsConfig["connection_settings"]["local_config_file"])){
514
+ local_args['config-file'] = path.resolve(bsConfig["connection_settings"]["local_config_file"]);
515
+ }
516
+ return local_args;
517
+ };
518
+
519
+ exports.generateLocalIdentifier = (mode) => {
520
+ let local_identifier = undefined;
521
+ if(mode == "always-on"){
522
+ local_identifier = getmac();
523
+ } else {
524
+ local_identifier = uuidv4();
525
+ }
526
+ return Buffer.from(local_identifier).toString("base64");
527
+ };
528
+
529
+ exports.checkLocalIdentifierRunning = (bsConfig, localIdentifier) => {
530
+ let options = {
531
+ url: `${config.localTestingListUrl}?auth_token=${bsConfig.auth.access_key}&state=running`,
532
+ auth: {
533
+ user: bsConfig.auth.username,
534
+ password: bsConfig.auth.access_key,
535
+ },
536
+ headers: {
537
+ 'User-Agent': this.getUserAgent(),
538
+ },
539
+ };
540
+ let that = this;
541
+ return new Promise ( function(resolve, reject) {
542
+ request.get(options, function (err, resp, body) {
543
+ if(err){
544
+ reject(err);
545
+ }
546
+ let response = JSON.parse(body);
547
+ let localInstances = [];
548
+ if(!that.isUndefined(response['instances'])){
549
+ localInstances = response['instances'];
550
+ }
551
+ let localIdentifiers = [];
552
+
553
+ localInstances.forEach(function(instance){
554
+ localIdentifiers.push(instance['localIdentifier']);
555
+ });
556
+
557
+ resolve(localIdentifiers.includes(localIdentifier));
558
+ });
559
+ });
560
+ };
561
+
562
+ exports.setLocalConfigFile = (bsConfig, args) => {
563
+ if(!this.isUndefined(args.localConfigFile)){
564
+ bsConfig['connection_settings']['local_config_file'] = args.localConfigFile;
565
+ }
566
+ };
567
+
568
+ exports.setHeaded = (bsConfig, args) => {
569
+ if (!this.isUndefined(args.headed) && args.headed === true) {
570
+ bsConfig.run_settings.headless = false;
333
571
  }
334
572
  };
335
573
 
336
574
  exports.getNumberOfSpecFiles = (bsConfig, args, cypressJson) => {
337
575
  let testFolderPath = cypressJson.integrationFolder || Constants.DEFAULT_CYPRESS_SPEC_PATH;
338
- let globSearchPatttern = bsConfig.run_settings.specs || `${testFolderPath}/**/*.+(${Constants.specFileTypes.join("|")})`;
576
+ let globSearchPattern = this.sanitizeSpecsPattern(bsConfig.run_settings.specs) || `${testFolderPath}/**/*.+(${Constants.specFileTypes.join("|")})`;
339
577
  let ignoreFiles = args.exclude || bsConfig.run_settings.exclude;
340
- let files = glob.sync(globSearchPatttern, {cwd: bsConfig.run_settings.cypressProjectDir, matchBase: true, ignore: ignoreFiles});
578
+ let files = glob.sync(globSearchPattern, {cwd: bsConfig.run_settings.cypressProjectDir, matchBase: true, ignore: ignoreFiles});
341
579
  return files;
342
580
  };
343
581
 
582
+ exports.sanitizeSpecsPattern = (pattern) => {
583
+ return pattern && pattern.split(",").length > 1 ? "{" + pattern + "}" : pattern;
584
+ }
585
+
344
586
  exports.getBrowserCombinations = (bsConfig) => {
345
587
  let osBrowserArray = [];
346
588
  let osBrowser = "";
@@ -380,3 +622,26 @@ exports.versionChangedMessage = (preferredVersion, actualVersion) => {
380
622
  message = message.replace("<actualVersion>", actualVersion);
381
623
  return message
382
624
  }
625
+
626
+ exports.isJSONInvalid = (err, args) => {
627
+ let invalid = true
628
+
629
+ if (err === Constants.validationMessages.INVALID_PARALLELS_CONFIGURATION && !this.isUndefined(args.parallels)) {
630
+ return false
631
+ }
632
+
633
+ if (this.deleteBaseUrlFromError(err) === this.deleteBaseUrlFromError(Constants.validationMessages.LOCAL_NOT_SET)) {
634
+ return false
635
+ }
636
+
637
+ if( err === Constants.validationMessages.INVALID_CLI_LOCAL_IDENTIFIER || err === Constants.validationMessages.INVALID_LOCAL_MODE ){
638
+ return false
639
+ }
640
+
641
+ return invalid
642
+ }
643
+
644
+ exports.deleteBaseUrlFromError = (err) => {
645
+ return err.replace(/To test ([\s\S]*)on BrowserStack/g, 'To test on BrowserStack');
646
+ }
647
+
@@ -37,10 +37,14 @@ const uploadCypressZip = (bsConfig, filePath) => {
37
37
  responseData = null
38
38
  }
39
39
  if (resp.statusCode != 200) {
40
- if (responseData && responseData["error"]) {
40
+ if(responseData && responseData["error"]){
41
41
  reject(responseData["error"]);
42
42
  } else {
43
- reject(Constants.userMessages.ZIP_UPLOADER_NOT_REACHABLE);
43
+ if(resp.statusCode == 401){
44
+ reject(Constants.validationMessages.INVALID_DEFAULT_AUTH_PARAMS);
45
+ } else {
46
+ reject(Constants.userMessages.ZIP_UPLOADER_NOT_REACHABLE);
47
+ }
44
48
  }
45
49
  } else {
46
50
  logger.info(`Uploaded tests successfully (${responseData.zip_url})`);
package/bin/runner.js CHANGED
@@ -200,6 +200,27 @@ var argv = yargs
200
200
  default: false,
201
201
  describe: Constants.cliMessages.RUN.SYNC_DESCRIPTION,
202
202
  type: "boolean"
203
+ },
204
+ 'headed': {
205
+ default: false,
206
+ describe: Constants.cliMessages.RUN.HEADED,
207
+ type: "boolean"
208
+ },
209
+ 'local': {
210
+ describe: Constants.cliMessages.RUN.LOCAL,
211
+ type: "boolean"
212
+ },
213
+ 'local-identifier': {
214
+ describe: Constants.cliMessages.RUN.LOCAL_IDENTIFIER,
215
+ type: "string"
216
+ },
217
+ 'local-mode': {
218
+ describe: Constants.cliMessages.RUN.LOCAL_MODE,
219
+ type: "string"
220
+ },
221
+ 'local-config-file': {
222
+ describe: Constants.cliMessages.RUN.LOCAL_CONFIG_FILE,
223
+ type: "string"
203
224
  }
204
225
  })
205
226
  .help('help')
@@ -60,11 +60,14 @@ module.exports = function () {
60
60
  "npm_dependencies": {
61
61
  },
62
62
  "package_config_options": {
63
- }
63
+ },
64
+ "headless": true
64
65
  },
65
66
  "connection_settings": {
66
67
  "local": false,
67
- "local_identifier": null
68
+ "local_identifier": null,
69
+ "local_mode": null,
70
+ "local_config_file": null
68
71
  },
69
72
  "disable_usage_reporting": false
70
73
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "browserstack-cypress-cli",
3
- "version": "1.6.0",
3
+ "version": "1.8.1",
4
4
  "description": "BrowserStack Cypress CLI for Cypress integration with BrowserStack's remote devices.",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -12,16 +12,20 @@
12
12
  "browserstack-cypress": "bin/runner.js"
13
13
  },
14
14
  "dependencies": {
15
- "archiver": "^3.1.1",
15
+ "archiver": "^5.2.0",
16
+ "async": "^3.2.0",
17
+ "browserstack-local": "^1.4.8",
16
18
  "chalk": "^4.1.0",
17
19
  "fs-extra": "^8.1.0",
20
+ "getmac": "^5.17.0",
21
+ "glob": "^7.1.6",
18
22
  "mkdirp": "^1.0.3",
19
23
  "request": "^2.88.0",
20
24
  "requestretry": "^4.1.0",
21
25
  "table": "^5.4.6",
26
+ "uuid": "^8.3.2",
22
27
  "winston": "^2.3.1",
23
- "yargs": "^14.2.2",
24
- "glob": "^7.1.6"
28
+ "yargs": "^14.2.3"
25
29
  },
26
30
  "repository": {
27
31
  "type": "git",