automation_model 1.0.709-dev → 1.0.709-stage

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.
Files changed (48) hide show
  1. package/README.md +4 -1
  2. package/lib/analyze_helper.js.map +1 -1
  3. package/lib/api.d.ts +0 -1
  4. package/lib/api.js +4 -3
  5. package/lib/api.js.map +1 -1
  6. package/lib/auto_page.d.ts +4 -2
  7. package/lib/auto_page.js +142 -86
  8. package/lib/auto_page.js.map +1 -1
  9. package/lib/browser_manager.js +22 -25
  10. package/lib/browser_manager.js.map +1 -1
  11. package/lib/bruno.js.map +1 -1
  12. package/lib/command_common.d.ts +1 -1
  13. package/lib/command_common.js +18 -1
  14. package/lib/command_common.js.map +1 -1
  15. package/lib/date_time.js.map +1 -1
  16. package/lib/drawRect.js.map +1 -1
  17. package/lib/error-messages.js.map +1 -1
  18. package/lib/file_checker.js +129 -25
  19. package/lib/file_checker.js.map +1 -1
  20. package/lib/find_function.js.map +1 -1
  21. package/lib/init_browser.js +115 -125
  22. package/lib/init_browser.js.map +1 -1
  23. package/lib/locate_element.js.map +1 -1
  24. package/lib/locator.d.ts +1 -0
  25. package/lib/locator.js +10 -3
  26. package/lib/locator.js.map +1 -1
  27. package/lib/locator_log.js.map +1 -1
  28. package/lib/network.d.ts +2 -0
  29. package/lib/network.js +334 -86
  30. package/lib/network.js.map +1 -1
  31. package/lib/route.d.ts +21 -0
  32. package/lib/route.js +450 -0
  33. package/lib/route.js.map +1 -0
  34. package/lib/scripts/axe.mini.js +3 -3
  35. package/lib/snapshot_validation.js +150 -39
  36. package/lib/snapshot_validation.js.map +1 -1
  37. package/lib/stable_browser.d.ts +61 -26
  38. package/lib/stable_browser.js +962 -189
  39. package/lib/stable_browser.js.map +1 -1
  40. package/lib/table.d.ts +9 -7
  41. package/lib/table.js +82 -12
  42. package/lib/table.js.map +1 -1
  43. package/lib/table_analyze.js.map +1 -1
  44. package/lib/table_helper.js.map +1 -1
  45. package/lib/utils.d.ts +3 -1
  46. package/lib/utils.js +88 -63
  47. package/lib/utils.js.map +1 -1
  48. package/package.json +13 -7
@@ -10,7 +10,8 @@ import { getDateTimeValue } from "./date_time.js";
10
10
  import drawRectangle from "./drawRect.js";
11
11
  //import { closeUnexpectedPopups } from "./popups.js";
12
12
  import { getTableCells, getTableData } from "./table_analyze.js";
13
- import { _convertToRegexQuery, _copyContext, _fixLocatorUsingParams, _fixUsingParams, _getServerUrl, extractStepExampleParameters, KEYBOARD_EVENTS, maskValue, replaceWithLocalTestData, scrollPageToLoadLazyElements, unEscapeString, _getDataFile, testForRegex, performAction, } from "./utils.js";
13
+ import errorStackParser from "error-stack-parser";
14
+ import { _convertToRegexQuery, _copyContext, _fixLocatorUsingParams, _fixUsingParams, _getServerUrl, extractStepExampleParameters, KEYBOARD_EVENTS, maskValue, replaceWithLocalTestData, scrollPageToLoadLazyElements, unEscapeString, _getDataFile, testForRegex, performAction, _getTestData, } from "./utils.js";
14
15
  import csv from "csv-parser";
15
16
  import { Readable } from "node:stream";
16
17
  import readline from "readline";
@@ -19,35 +20,42 @@ import { getTestData } from "./auto_page.js";
19
20
  import { locate_element } from "./locate_element.js";
20
21
  import { randomUUID } from "crypto";
21
22
  import { _commandError, _commandFinally, _preCommand, _validateSelectors, _screenshot, _reportToWorld, } from "./command_common.js";
22
- import { registerDownloadEvent, registerNetworkEvents } from "./network.js";
23
+ import { networkAfterStep, networkBeforeStep, registerDownloadEvent, registerNetworkEvents } from "./network.js";
23
24
  import { LocatorLog } from "./locator_log.js";
24
25
  import axios from "axios";
25
26
  import { _findCellArea, findElementsInArea } from "./table_helper.js";
26
- import { snapshotValidation } from "./snapshot_validation.js";
27
+ import { highlightSnapshot, snapshotValidation } from "./snapshot_validation.js";
27
28
  import { loadBrunoParams } from "./bruno.js";
29
+ import { registerAfterStepRoutes, registerBeforeStepRoutes } from "./route.js";
30
+ import { existsSync } from "node:fs";
28
31
  export const Types = {
29
32
  CLICK: "click_element",
30
33
  WAIT_ELEMENT: "wait_element",
31
34
  NAVIGATE: "navigate",
35
+ GO_BACK: "go_back",
36
+ GO_FORWARD: "go_forward",
32
37
  FILL: "fill_element",
33
- EXECUTE: "execute_page_method",
34
- OPEN: "open_environment",
38
+ EXECUTE: "execute_page_method", //
39
+ OPEN: "open_environment", //
35
40
  COMPLETE: "step_complete",
36
41
  ASK: "information_needed",
37
- GET_PAGE_STATUS: "get_page_status",
38
- CLICK_ROW_ACTION: "click_row_action",
42
+ GET_PAGE_STATUS: "get_page_status", ///
43
+ CLICK_ROW_ACTION: "click_row_action", //
39
44
  VERIFY_ELEMENT_CONTAINS_TEXT: "verify_element_contains_text",
40
45
  VERIFY_PAGE_CONTAINS_TEXT: "verify_page_contains_text",
41
46
  VERIFY_PAGE_CONTAINS_NO_TEXT: "verify_page_contains_no_text",
42
47
  ANALYZE_TABLE: "analyze_table",
43
- SELECT: "select_combobox",
48
+ SELECT: "select_combobox", //
49
+ VERIFY_PROPERTY: "verify_element_property",
44
50
  VERIFY_PAGE_PATH: "verify_page_path",
51
+ VERIFY_PAGE_TITLE: "verify_page_title",
45
52
  TYPE_PRESS: "type_press",
46
53
  PRESS: "press_key",
47
54
  HOVER: "hover_element",
48
55
  CHECK: "check_element",
49
56
  UNCHECK: "uncheck_element",
50
57
  EXTRACT: "extract_attribute",
58
+ EXTRACT_PROPERTY: "extract_property",
51
59
  CLOSE_PAGE: "close_page",
52
60
  TABLE_OPERATION: "table_operation",
53
61
  SET_DATE_TIME: "set_date_time",
@@ -59,9 +67,13 @@ export const Types = {
59
67
  VERIFY_ATTRIBUTE: "verify_element_attribute",
60
68
  VERIFY_TEXT_WITH_RELATION: "verify_text_with_relation",
61
69
  BRUNO: "bruno",
62
- SNAPSHOT_VALIDATION: "snapshot_validation",
63
70
  VERIFY_FILE_EXISTS: "verify_file_exists",
64
71
  SET_INPUT_FILES: "set_input_files",
72
+ SNAPSHOT_VALIDATION: "snapshot_validation",
73
+ REPORT_COMMAND: "report_command",
74
+ STEP_COMPLETE: "step_complete",
75
+ SLEEP: "sleep",
76
+ CONDITIONAL_WAIT: "conditional_wait",
65
77
  };
66
78
  export const apps = {};
67
79
  const formatElementName = (elementName) => {
@@ -73,6 +85,7 @@ class StableBrowser {
73
85
  logger;
74
86
  context;
75
87
  world;
88
+ fastMode;
76
89
  project_path = null;
77
90
  webLogFile = null;
78
91
  networkLogger = null;
@@ -81,12 +94,14 @@ class StableBrowser {
81
94
  tags = null;
82
95
  isRecording = false;
83
96
  initSnapshotTaken = false;
84
- constructor(browser, page, logger = null, context = null, world = null) {
97
+ abortedExecution = false;
98
+ constructor(browser, page, logger = null, context = null, world = null, fastMode = false) {
85
99
  this.browser = browser;
86
100
  this.page = page;
87
101
  this.logger = logger;
88
102
  this.context = context;
89
103
  this.world = world;
104
+ this.fastMode = fastMode;
90
105
  if (!this.logger) {
91
106
  this.logger = console;
92
107
  }
@@ -115,6 +130,19 @@ class StableBrowser {
115
130
  context.pages = [this.page];
116
131
  const logFolder = path.join(this.project_path, "logs", "web");
117
132
  this.world = world;
133
+ if (this.configuration && this.configuration.fastMode === true) {
134
+ this.fastMode = true;
135
+ }
136
+ if (process.env.FAST_MODE === "true") {
137
+ // console.log("Fast mode enabled from environment variable");
138
+ this.fastMode = true;
139
+ }
140
+ if (process.env.FAST_MODE === "false") {
141
+ this.fastMode = false;
142
+ }
143
+ if (this.context) {
144
+ this.context.fastMode = this.fastMode;
145
+ }
118
146
  this.registerEventListeners(this.context);
119
147
  registerNetworkEvents(this.world, this, this.context, this.page);
120
148
  registerDownloadEvent(this.page, this.world, this.context);
@@ -125,6 +153,9 @@ class StableBrowser {
125
153
  if (!context.pageLoading) {
126
154
  context.pageLoading = { status: false };
127
155
  }
156
+ if (this.configuration && this.configuration.acceptDialog && this.page) {
157
+ this.page.on("dialog", (dialog) => dialog.accept());
158
+ }
128
159
  context.playContext.on("page", async function (page) {
129
160
  if (this.configuration && this.configuration.closePopups === true) {
130
161
  console.log("close unexpected popups");
@@ -133,6 +164,14 @@ class StableBrowser {
133
164
  }
134
165
  context.pageLoading.status = true;
135
166
  this.page = page;
167
+ try {
168
+ if (this.configuration && this.configuration.acceptDialog) {
169
+ await page.on("dialog", (dialog) => dialog.accept());
170
+ }
171
+ }
172
+ catch (error) {
173
+ console.error("Error on dialog accept registration", error);
174
+ }
136
175
  context.page = page;
137
176
  context.pages.push(page);
138
177
  registerNetworkEvents(this.world, this, context, this.page);
@@ -184,7 +223,9 @@ class StableBrowser {
184
223
  if (newContextCreated) {
185
224
  this.registerEventListeners(this.context);
186
225
  await this.goto(this.context.environment.baseUrl);
187
- await this.waitForPageLoad();
226
+ if (!this.fastMode) {
227
+ await this.waitForPageLoad();
228
+ }
188
229
  }
189
230
  }
190
231
  async switchTab(tabTitleOrIndex) {
@@ -278,6 +319,7 @@ class StableBrowser {
278
319
  if (!url) {
279
320
  throw new Error("url is null, verify that the environment file is correct");
280
321
  }
322
+ url = await this._replaceWithLocalData(url, this.world);
281
323
  if (!url.startsWith("http")) {
282
324
  url = "https://" + url;
283
325
  }
@@ -309,6 +351,64 @@ class StableBrowser {
309
351
  await _commandFinally(state, this);
310
352
  }
311
353
  }
354
+ async goBack(options, world = null) {
355
+ const state = {
356
+ value: "",
357
+ world: world,
358
+ type: Types.GO_BACK,
359
+ text: `Browser navigate back`,
360
+ operation: "goBack",
361
+ log: "***** navigate back *****\n",
362
+ info: {},
363
+ locate: false,
364
+ scroll: false,
365
+ screenshot: false,
366
+ highlight: false,
367
+ };
368
+ try {
369
+ await _preCommand(state, this);
370
+ await this.page.goBack({
371
+ waitUntil: "load",
372
+ });
373
+ await _screenshot(state, this);
374
+ }
375
+ catch (error) {
376
+ console.error("Error on goBack", error);
377
+ _commandError(state, error, this);
378
+ }
379
+ finally {
380
+ await _commandFinally(state, this);
381
+ }
382
+ }
383
+ async goForward(options, world = null) {
384
+ const state = {
385
+ value: "",
386
+ world: world,
387
+ type: Types.GO_FORWARD,
388
+ text: `Browser navigate forward`,
389
+ operation: "goForward",
390
+ log: "***** navigate forward *****\n",
391
+ info: {},
392
+ locate: false,
393
+ scroll: false,
394
+ screenshot: false,
395
+ highlight: false,
396
+ };
397
+ try {
398
+ await _preCommand(state, this);
399
+ await this.page.goForward({
400
+ waitUntil: "load",
401
+ });
402
+ await _screenshot(state, this);
403
+ }
404
+ catch (error) {
405
+ console.error("Error on goForward", error);
406
+ _commandError(state, error, this);
407
+ }
408
+ finally {
409
+ await _commandFinally(state, this);
410
+ }
411
+ }
312
412
  async _getLocator(locator, scope, _params) {
313
413
  locator = _fixLocatorUsingParams(locator, _params);
314
414
  // locator = await this._replaceWithLocalData(locator);
@@ -422,7 +522,7 @@ class StableBrowser {
422
522
  }
423
523
  return { elementCount: tagCount, randomToken };
424
524
  }
425
- async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null) {
525
+ async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null, logErrors = false) {
426
526
  if (!info) {
427
527
  info = {};
428
528
  }
@@ -434,14 +534,13 @@ class StableBrowser {
434
534
  info.locatorLog = new LocatorLog(selectorHierarchy);
435
535
  }
436
536
  let locatorSearch = selectorHierarchy[index];
437
- let originalLocatorSearch = "";
438
537
  try {
439
- originalLocatorSearch = _fixUsingParams(JSON.stringify(locatorSearch), _params);
440
- locatorSearch = JSON.parse(originalLocatorSearch);
538
+ locatorSearch = _fixLocatorUsingParams(locatorSearch, _params);
441
539
  }
442
540
  catch (e) {
443
541
  console.error(e);
444
542
  }
543
+ let originalLocatorSearch = JSON.stringify(locatorSearch);
445
544
  //info.log += "searching for locator " + JSON.stringify(locatorSearch) + "\n";
446
545
  let locator = null;
447
546
  if (locatorSearch.climb && locatorSearch.climb >= 0) {
@@ -489,7 +588,7 @@ class StableBrowser {
489
588
  }
490
589
  return;
491
590
  }
492
- if (info.locatorLog && count === 0) {
591
+ if (info.locatorLog && count === 0 && logErrors) {
493
592
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "NOT_FOUND");
494
593
  }
495
594
  for (let j = 0; j < count; j++) {
@@ -504,7 +603,7 @@ class StableBrowser {
504
603
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "FOUND");
505
604
  }
506
605
  }
507
- else {
606
+ else if (logErrors) {
508
607
  info.failCause.visible = visible;
509
608
  info.failCause.enabled = enabled;
510
609
  if (!info.printMessages) {
@@ -583,21 +682,135 @@ class StableBrowser {
583
682
  }
584
683
  return { rerun: false };
585
684
  }
685
+ getFilePath() {
686
+ const stackFrames = errorStackParser.parse(new Error());
687
+ const stackFrame = stackFrames.findLast((frame) => frame.fileName && frame.fileName.endsWith(".mjs"));
688
+ // return stackFrame?.fileName || null;
689
+ const filepath = stackFrame?.fileName;
690
+ if (filepath) {
691
+ let jsonFilePath = filepath.replace(".mjs", ".json");
692
+ if (existsSync(jsonFilePath)) {
693
+ return jsonFilePath;
694
+ }
695
+ const config = this.configuration ?? {};
696
+ if (!config?.locatorsMetadataDir) {
697
+ config.locatorsMetadataDir = "features/step_definitions/locators";
698
+ }
699
+ if (config && config.locatorsMetadataDir) {
700
+ jsonFilePath = path.join(config.locatorsMetadataDir, path.basename(jsonFilePath));
701
+ }
702
+ if (existsSync(jsonFilePath)) {
703
+ return jsonFilePath;
704
+ }
705
+ return null;
706
+ }
707
+ return null;
708
+ }
709
+ getFullElementLocators(selectors, filePath) {
710
+ if (!filePath || !existsSync(filePath)) {
711
+ return null;
712
+ }
713
+ const content = fs.readFileSync(filePath, "utf8");
714
+ try {
715
+ const allElements = JSON.parse(content);
716
+ const element_key = selectors?.element_key;
717
+ if (element_key && allElements[element_key]) {
718
+ return allElements[element_key];
719
+ }
720
+ for (const elementKey in allElements) {
721
+ const element = allElements[elementKey];
722
+ let foundStrategy = null;
723
+ for (const key in element) {
724
+ if (key === "strategy") {
725
+ continue;
726
+ }
727
+ const locators = element[key];
728
+ if (!locators || !locators.length) {
729
+ continue;
730
+ }
731
+ for (const locator of locators) {
732
+ delete locator.score;
733
+ }
734
+ if (JSON.stringify(locators) === JSON.stringify(selectors.locators)) {
735
+ foundStrategy = key;
736
+ break;
737
+ }
738
+ }
739
+ if (foundStrategy) {
740
+ return element;
741
+ }
742
+ }
743
+ }
744
+ catch (error) {
745
+ console.error("Error parsing locators from file: " + filePath, error);
746
+ }
747
+ return null;
748
+ }
586
749
  async _locate(selectors, info, _params, timeout, allowDisabled = false) {
587
750
  if (!timeout) {
588
751
  timeout = 30000;
589
752
  }
753
+ let element = null;
754
+ let allStrategyLocators = null;
755
+ let selectedStrategy = null;
756
+ if (this.tryAllStrategies) {
757
+ allStrategyLocators = this.getFullElementLocators(selectors, this.getFilePath());
758
+ selectedStrategy = allStrategyLocators?.strategy;
759
+ }
590
760
  for (let i = 0; i < 3; i++) {
591
761
  info.log += "attempt " + i + ": total locators " + selectors.locators.length + "\n";
592
762
  for (let j = 0; j < selectors.locators.length; j++) {
593
763
  let selector = selectors.locators[j];
594
764
  info.log += "searching for locator " + j + ":" + JSON.stringify(selector) + "\n";
595
765
  }
596
- let element = await this._locate_internal(selectors, info, _params, timeout, allowDisabled);
766
+ if (this.tryAllStrategies && selectedStrategy) {
767
+ const strategyLocators = allStrategyLocators[selectedStrategy];
768
+ let err;
769
+ if (strategyLocators && strategyLocators.length) {
770
+ try {
771
+ selectors.locators = strategyLocators;
772
+ element = await this._locate_internal(selectors, info, _params, 10_000, allowDisabled);
773
+ info.selectedStrategy = selectedStrategy;
774
+ info.log += "element found using strategy " + selectedStrategy + "\n";
775
+ }
776
+ catch (error) {
777
+ err = error;
778
+ }
779
+ }
780
+ if (!element) {
781
+ for (const key in allStrategyLocators) {
782
+ if (key === "strategy" || key === selectedStrategy) {
783
+ continue;
784
+ }
785
+ const strategyLocators = allStrategyLocators[key];
786
+ if (strategyLocators && strategyLocators.length) {
787
+ try {
788
+ info.log += "using strategy " + key + " with locators " + JSON.stringify(strategyLocators) + "\n";
789
+ selectors.locators = strategyLocators;
790
+ element = await this._locate_internal(selectors, info, _params, 10_000, allowDisabled);
791
+ err = null;
792
+ info.selectedStrategy = key;
793
+ info.log += "element found using strategy " + key + "\n";
794
+ break;
795
+ }
796
+ catch (error) {
797
+ err = error;
798
+ }
799
+ }
800
+ }
801
+ }
802
+ if (err) {
803
+ throw err;
804
+ }
805
+ }
806
+ else {
807
+ element = await this._locate_internal(selectors, info, _params, timeout, allowDisabled);
808
+ }
597
809
  if (!element.rerun) {
598
810
  const randomToken = Math.random().toString(36).substring(7);
599
- element.evaluate((el, randomToken) => {
811
+ await element.evaluate((el, randomToken) => {
600
812
  el.setAttribute("data-blinq-id-" + randomToken, "");
813
+ console.log("set data-blinq-id-" + randomToken + " on element", el);
601
814
  }, randomToken);
602
815
  // if (element._frame) {
603
816
  // return element;
@@ -649,7 +862,7 @@ class StableBrowser {
649
862
  break;
650
863
  }
651
864
  catch (error) {
652
- console.error("frame not found " + frameLocator.css);
865
+ // console.error("frame not found " + frameLocator.css);
653
866
  }
654
867
  }
655
868
  }
@@ -727,7 +940,6 @@ class StableBrowser {
727
940
  let locatorsCount = 0;
728
941
  let lazy_scroll = false;
729
942
  //let arrayMode = Array.isArray(selectors);
730
- let scope = await this._findFrameScope(selectors, timeout, info);
731
943
  let selectorsLocators = null;
732
944
  selectorsLocators = selectors.locators;
733
945
  // group selectors by priority
@@ -755,6 +967,7 @@ class StableBrowser {
755
967
  let highPriorityOnly = true;
756
968
  let visibleOnly = true;
757
969
  while (true) {
970
+ let scope = await this._findFrameScope(selectors, timeout, info);
758
971
  locatorsCount = 0;
759
972
  let result = [];
760
973
  let popupResult = await this.closeUnexpectedPopups(info, _params);
@@ -845,7 +1058,7 @@ class StableBrowser {
845
1058
  }
846
1059
  throw new Error("failed to locate first element no elements found, " + info.log);
847
1060
  }
848
- async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name) {
1061
+ async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name, logErrors = false) {
849
1062
  let foundElements = [];
850
1063
  const result = {
851
1064
  foundElements: foundElements,
@@ -864,7 +1077,9 @@ class StableBrowser {
864
1077
  await this._collectLocatorInformation(locatorsGroup, i, this.page, foundLocators, _params, info, visibleOnly, allowDisabled, element_name);
865
1078
  }
866
1079
  catch (e) {
867
- this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
1080
+ if (logErrors) {
1081
+ this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
1082
+ }
868
1083
  }
869
1084
  }
870
1085
  if (foundLocators.length === 1) {
@@ -905,7 +1120,7 @@ class StableBrowser {
905
1120
  });
906
1121
  result.locatorIndex = i;
907
1122
  }
908
- else {
1123
+ else if (logErrors) {
909
1124
  info.failCause.foundMultiple = true;
910
1125
  if (info.locatorLog) {
911
1126
  info.locatorLog.setLocatorSearchStatus(JSON.stringify(locatorsGroup[i]), "FOUND_NOT_UNIQUE");
@@ -1028,7 +1243,9 @@ class StableBrowser {
1028
1243
  try {
1029
1244
  await _preCommand(state, this);
1030
1245
  await performAction("click", state.element, options, this, state, _params);
1031
- await this.waitForPageLoad();
1246
+ if (!this.fastMode) {
1247
+ await this.waitForPageLoad();
1248
+ }
1032
1249
  return state.info;
1033
1250
  }
1034
1251
  catch (e) {
@@ -1091,7 +1308,7 @@ class StableBrowser {
1091
1308
  // if (world && world.screenshot && !world.screenshotPath) {
1092
1309
  // console.log(`Highlighting while running from recorder`);
1093
1310
  await this._highlightElements(state.element);
1094
- await state.element.setChecked(checked);
1311
+ await state.element.setChecked(checked, { timeout: 2000 });
1095
1312
  await new Promise((resolve) => setTimeout(resolve, 1000));
1096
1313
  // await this._unHighlightElements(element);
1097
1314
  // }
@@ -1103,11 +1320,28 @@ class StableBrowser {
1103
1320
  this.logger.info("element did not change its state, ignoring...");
1104
1321
  }
1105
1322
  else {
1323
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1106
1324
  //await this.closeUnexpectedPopups();
1107
1325
  state.info.log += "setCheck failed, will try again" + "\n";
1108
- state.element = await this._locate(selectors, state.info, _params);
1109
- await state.element.setChecked(checked, { timeout: 5000, force: true });
1110
- await new Promise((resolve) => setTimeout(resolve, 1000));
1326
+ state.element_found = false;
1327
+ try {
1328
+ state.element = await this._locate(selectors, state.info, _params, 100);
1329
+ state.element_found = true;
1330
+ // check the check state
1331
+ }
1332
+ catch (error) {
1333
+ // element dismissed
1334
+ }
1335
+ if (state.element_found) {
1336
+ const isChecked = await state.element.isChecked();
1337
+ if (isChecked !== checked) {
1338
+ // perform click
1339
+ await state.element.click({ timeout: 2000, force: true });
1340
+ }
1341
+ else {
1342
+ this.logger.info(`Element ${selectors.element_name} is already in the desired state (${checked})`);
1343
+ }
1344
+ }
1111
1345
  }
1112
1346
  }
1113
1347
  await this.waitForPageLoad();
@@ -1403,7 +1637,9 @@ class StableBrowser {
1403
1637
  await new Promise((resolve) => setTimeout(resolve, 500));
1404
1638
  }
1405
1639
  }
1640
+ //if (!this.fastMode) {
1406
1641
  await _screenshot(state, this);
1642
+ //}
1407
1643
  if (enter === true) {
1408
1644
  await new Promise((resolve) => setTimeout(resolve, 2000));
1409
1645
  await this.page.keyboard.press("Enter");
@@ -1745,11 +1981,16 @@ class StableBrowser {
1745
1981
  throw new Error("Snapshot validation failed at line " + matchResult.errorLineText);
1746
1982
  }
1747
1983
  // highlight and screenshot
1984
+ try {
1985
+ await await highlightSnapshot(newValue, scope);
1986
+ await _screenshot(state, this);
1987
+ }
1988
+ catch (e) { }
1748
1989
  return state.info;
1749
1990
  }
1750
1991
  catch (e) {
1751
1992
  // Log error but continue retrying until timeout is reached
1752
- this.logger.warn("Retrying snapshot validation due to: " + e.message);
1993
+ //this.logger.warn("Retrying snapshot validation due to: " + e.message);
1753
1994
  }
1754
1995
  await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait 1 second before retrying
1755
1996
  }
@@ -1903,12 +2144,7 @@ class StableBrowser {
1903
2144
  }
1904
2145
  }
1905
2146
  getTestData(world = null) {
1906
- const dataFile = _getDataFile(world, this.context, this);
1907
- let data = {};
1908
- if (fs.existsSync(dataFile)) {
1909
- data = JSON.parse(fs.readFileSync(dataFile, "utf8"));
1910
- }
1911
- return data;
2147
+ return _getTestData(world, this.context, this);
1912
2148
  }
1913
2149
  async _screenShot(options = {}, world = null, info = null) {
1914
2150
  // collect url/path/title
@@ -2128,6 +2364,77 @@ class StableBrowser {
2128
2364
  await _commandFinally(state, this);
2129
2365
  }
2130
2366
  }
2367
+ async extractProperty(selectors, property, variable, _params = null, options = {}, world = null) {
2368
+ const state = {
2369
+ selectors,
2370
+ _params,
2371
+ property,
2372
+ variable,
2373
+ options,
2374
+ world,
2375
+ type: Types.EXTRACT_PROPERTY,
2376
+ text: `Extract property from element`,
2377
+ _text: `Extract property ${property} from ${selectors.element_name}`,
2378
+ operation: "extractProperty",
2379
+ log: "***** extract property " + property + " from " + selectors.element_name + " *****\n",
2380
+ allowDisabled: true,
2381
+ };
2382
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2383
+ try {
2384
+ await _preCommand(state, this);
2385
+ switch (property) {
2386
+ case "inner_text":
2387
+ state.value = await state.element.innerText();
2388
+ break;
2389
+ case "href":
2390
+ state.value = await state.element.getAttribute("href");
2391
+ break;
2392
+ case "value":
2393
+ state.value = await state.element.inputValue();
2394
+ break;
2395
+ case "text":
2396
+ state.value = await state.element.textContent();
2397
+ break;
2398
+ default:
2399
+ if (property.startsWith("dataset.")) {
2400
+ const dataAttribute = property.substring(8);
2401
+ state.value = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2402
+ }
2403
+ else {
2404
+ state.value = String(await state.element.evaluate((element, prop) => element[prop], property));
2405
+ }
2406
+ }
2407
+ if (options !== null) {
2408
+ if (options.regex && options.regex !== "") {
2409
+ // Construct a regex pattern from the provided string
2410
+ const regex = options.regex.slice(1, -1);
2411
+ const regexPattern = new RegExp(regex, "g");
2412
+ const matches = state.value.match(regexPattern);
2413
+ if (matches) {
2414
+ let newValue = "";
2415
+ for (const match of matches) {
2416
+ newValue += match;
2417
+ }
2418
+ state.value = newValue;
2419
+ }
2420
+ }
2421
+ if (options.trimSpaces && options.trimSpaces === true) {
2422
+ state.value = state.value.trim();
2423
+ }
2424
+ }
2425
+ state.info.value = state.value;
2426
+ this.setTestData({ [variable]: state.value }, world);
2427
+ this.logger.info("set test data: " + variable + "=" + state.value);
2428
+ // await new Promise((resolve) => setTimeout(resolve, 500));
2429
+ return state.info;
2430
+ }
2431
+ catch (e) {
2432
+ await _commandError(state, e, this);
2433
+ }
2434
+ finally {
2435
+ await _commandFinally(state, this);
2436
+ }
2437
+ }
2131
2438
  async verifyAttribute(selectors, attribute, value, _params = null, options = {}, world = null) {
2132
2439
  const state = {
2133
2440
  selectors,
@@ -2226,6 +2533,260 @@ class StableBrowser {
2226
2533
  await _commandFinally(state, this);
2227
2534
  }
2228
2535
  }
2536
+ async verifyProperty(selectors, property, value, _params = null, options = {}, world = null) {
2537
+ const state = {
2538
+ selectors,
2539
+ _params,
2540
+ property,
2541
+ value,
2542
+ options,
2543
+ world,
2544
+ type: Types.VERIFY_PROPERTY,
2545
+ highlight: true,
2546
+ screenshot: true,
2547
+ text: `Verify element property`,
2548
+ _text: `Verify property ${property} from ${selectors.element_name} is ${value}`,
2549
+ operation: "verifyProperty",
2550
+ log: "***** verify property " + property + " from " + selectors.element_name + " *****\n",
2551
+ allowDisabled: true,
2552
+ };
2553
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2554
+ let val;
2555
+ let expectedValue;
2556
+ try {
2557
+ await _preCommand(state, this);
2558
+ expectedValue = await replaceWithLocalTestData(state.value, world);
2559
+ state.info.expectedValue = expectedValue;
2560
+ switch (property) {
2561
+ case "innerText":
2562
+ val = String(await state.element.innerText());
2563
+ break;
2564
+ case "text":
2565
+ val = String(await state.element.textContent());
2566
+ break;
2567
+ case "value":
2568
+ val = String(await state.element.inputValue());
2569
+ break;
2570
+ case "checked":
2571
+ val = String(await state.element.isChecked());
2572
+ break;
2573
+ case "disabled":
2574
+ val = String(await state.element.isDisabled());
2575
+ break;
2576
+ case "readOnly":
2577
+ const isEditable = await state.element.isEditable();
2578
+ val = String(!isEditable);
2579
+ break;
2580
+ case "innerHTML":
2581
+ val = String(await state.element.innerHTML());
2582
+ break;
2583
+ case "outerHTML":
2584
+ val = String(await state.element.evaluate((element) => element.outerHTML));
2585
+ break;
2586
+ default:
2587
+ if (property.startsWith("dataset.")) {
2588
+ const dataAttribute = property.substring(8);
2589
+ val = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2590
+ }
2591
+ else {
2592
+ val = String(await state.element.evaluate((element, prop) => element[prop], property));
2593
+ }
2594
+ }
2595
+ // Helper function to remove all style="" attributes
2596
+ const removeStyleAttributes = (htmlString) => {
2597
+ return htmlString.replace(/\s*style\s*=\s*"[^"]*"/gi, "");
2598
+ };
2599
+ // Remove style attributes for innerHTML and outerHTML properties
2600
+ if (property === "innerHTML" || property === "outerHTML") {
2601
+ val = removeStyleAttributes(val);
2602
+ expectedValue = removeStyleAttributes(expectedValue);
2603
+ }
2604
+ state.info.value = val;
2605
+ let regex;
2606
+ state.info.value = val;
2607
+ const isRegex = expectedValue.startsWith("regex:");
2608
+ const isContains = expectedValue.startsWith("contains:");
2609
+ const isExact = expectedValue.startsWith("exact:");
2610
+ let matchPassed = false;
2611
+ if (isRegex) {
2612
+ const rawPattern = expectedValue.slice(6); // remove "regex:"
2613
+ const lastSlashIndex = rawPattern.lastIndexOf("/");
2614
+ if (rawPattern.startsWith("/") && lastSlashIndex > 0) {
2615
+ const patternBody = rawPattern.slice(1, lastSlashIndex).replace(/\n/g, ".*");
2616
+ const flags = rawPattern.slice(lastSlashIndex + 1) || "gs";
2617
+ const regex = new RegExp(patternBody, flags);
2618
+ state.info.regex = true;
2619
+ matchPassed = regex.test(val);
2620
+ }
2621
+ else {
2622
+ // Fallback: treat as literal
2623
+ const escapedPattern = rawPattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2624
+ const regex = new RegExp(escapedPattern, "g");
2625
+ matchPassed = regex.test(val);
2626
+ }
2627
+ }
2628
+ else if (isContains) {
2629
+ const containsValue = expectedValue.slice(9); // remove "contains:"
2630
+ matchPassed = val.includes(containsValue);
2631
+ }
2632
+ else if (isExact) {
2633
+ const exactValue = expectedValue.slice(6); // remove "exact:"
2634
+ matchPassed = val === exactValue;
2635
+ }
2636
+ else if (property === "innerText") {
2637
+ // Default innerText logic
2638
+ const normalizedExpectedValue = expectedValue.replace(/\\n/g, "\n");
2639
+ const valLines = val.split("\n");
2640
+ const expectedLines = normalizedExpectedValue.split("\n");
2641
+ matchPassed = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine.trim() === expectedLine.trim()));
2642
+ }
2643
+ else {
2644
+ // Fallback exact or loose match
2645
+ const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2646
+ const regex = new RegExp(escapedPattern, "g");
2647
+ matchPassed = regex.test(val);
2648
+ }
2649
+ if (!matchPassed) {
2650
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2651
+ state.info.failCause.assertionFailed = true;
2652
+ state.info.failCause.lastError = errorMessage;
2653
+ throw new Error(errorMessage);
2654
+ }
2655
+ return state.info;
2656
+ }
2657
+ catch (e) {
2658
+ await _commandError(state, e, this);
2659
+ }
2660
+ finally {
2661
+ await _commandFinally(state, this);
2662
+ }
2663
+ }
2664
+ async conditionalWait(selectors, condition, timeout = 1000, _params = null, options = {}, world = null) {
2665
+ // Convert timeout from seconds to milliseconds
2666
+ const timeoutMs = timeout * 1000;
2667
+ const state = {
2668
+ selectors,
2669
+ _params,
2670
+ condition,
2671
+ timeout: timeoutMs, // Store as milliseconds for internal use
2672
+ options,
2673
+ world,
2674
+ type: Types.CONDITIONAL_WAIT,
2675
+ highlight: true,
2676
+ screenshot: true,
2677
+ text: `Conditional wait for element`,
2678
+ _text: `Wait for ${selectors.element_name} to be ${condition} (timeout: ${timeout}s)`, // Display original seconds
2679
+ operation: "conditionalWait",
2680
+ log: `***** conditional wait for ${condition} on ${selectors.element_name} *****\n`,
2681
+ allowDisabled: true,
2682
+ info: {},
2683
+ };
2684
+ // Initialize startTime outside try block to ensure it's always accessible
2685
+ const startTime = Date.now();
2686
+ let conditionMet = false;
2687
+ let currentValue = null;
2688
+ let lastError = null;
2689
+ // Main retry loop - continues until timeout or condition is met
2690
+ while (Date.now() - startTime < timeoutMs) {
2691
+ const elapsedTime = Date.now() - startTime;
2692
+ const remainingTime = timeoutMs - elapsedTime;
2693
+ try {
2694
+ // Try to execute _preCommand (element location)
2695
+ await _preCommand(state, this);
2696
+ // If _preCommand succeeds, start condition checking
2697
+ const checkCondition = async () => {
2698
+ try {
2699
+ switch (condition.toLowerCase()) {
2700
+ case "checked":
2701
+ currentValue = await state.element.isChecked();
2702
+ return currentValue === true;
2703
+ case "unchecked":
2704
+ currentValue = await state.element.isChecked();
2705
+ return currentValue === false;
2706
+ case "visible":
2707
+ currentValue = await state.element.isVisible();
2708
+ return currentValue === true;
2709
+ case "hidden":
2710
+ currentValue = await state.element.isVisible();
2711
+ return currentValue === false;
2712
+ case "enabled":
2713
+ currentValue = await state.element.isDisabled();
2714
+ return currentValue === false;
2715
+ case "disabled":
2716
+ currentValue = await state.element.isDisabled();
2717
+ return currentValue === true;
2718
+ case "editable":
2719
+ // currentValue = await String(await state.element.evaluate((element, prop) => element[prop], "isContentEditable"));
2720
+ currentValue = await state.element.isContentEditable();
2721
+ return currentValue === true;
2722
+ default:
2723
+ state.info.message = `Unsupported condition: '${condition}'. Supported conditions are: checked, unchecked, visible, hidden, enabled, disabled, editable.`;
2724
+ state.info.success = false;
2725
+ return false;
2726
+ }
2727
+ }
2728
+ catch (error) {
2729
+ // Don't throw here, just return false to continue retrying
2730
+ return false;
2731
+ }
2732
+ };
2733
+ // Inner loop for condition checking (once element is located)
2734
+ while (Date.now() - startTime < timeoutMs) {
2735
+ const currentElapsedTime = Date.now() - startTime;
2736
+ conditionMet = await checkCondition();
2737
+ if (conditionMet) {
2738
+ break;
2739
+ }
2740
+ // Check if we still have time for another attempt
2741
+ if (Date.now() - startTime + 50 < timeoutMs) {
2742
+ await new Promise((res) => setTimeout(res, 50));
2743
+ }
2744
+ else {
2745
+ break;
2746
+ }
2747
+ }
2748
+ // If we got here and condition is met, break out of main loop
2749
+ if (conditionMet) {
2750
+ break;
2751
+ }
2752
+ // If condition not met but no exception, we've timed out
2753
+ break;
2754
+ }
2755
+ catch (e) {
2756
+ lastError = e;
2757
+ const currentElapsedTime = Date.now() - startTime;
2758
+ const timeLeft = timeoutMs - currentElapsedTime;
2759
+ // Check if we have enough time left to retry
2760
+ if (timeLeft > 100) {
2761
+ await new Promise((resolve) => setTimeout(resolve, 50));
2762
+ }
2763
+ else {
2764
+ break;
2765
+ }
2766
+ }
2767
+ }
2768
+ const actualWaitTime = Date.now() - startTime;
2769
+ state.info = {
2770
+ success: conditionMet,
2771
+ conditionMet,
2772
+ actualWaitTime,
2773
+ currentValue,
2774
+ lastError: lastError?.message || null,
2775
+ message: conditionMet
2776
+ ? `Condition '${condition}' met after ${(actualWaitTime / 1000).toFixed(2)}s`
2777
+ : `Condition '${condition}' not met within ${timeout}s timeout`,
2778
+ };
2779
+ if (lastError) {
2780
+ state.log += `Last error: ${lastError.message}\n`;
2781
+ }
2782
+ try {
2783
+ await _commandFinally(state, this);
2784
+ }
2785
+ catch (finallyError) {
2786
+ state.log += `Error in _commandFinally: ${finallyError.message}\n`;
2787
+ }
2788
+ return state.info;
2789
+ }
2229
2790
  async extractEmailData(emailAddress, options, world) {
2230
2791
  if (!emailAddress) {
2231
2792
  throw new Error("email address is null");
@@ -2383,56 +2944,49 @@ class StableBrowser {
2383
2944
  console.debug(error);
2384
2945
  }
2385
2946
  }
2386
- // async _unhighlightElements(scope, css) {
2387
- // try {
2388
- // if (!scope) {
2389
- // return;
2390
- // }
2391
- // if (!css) {
2392
- // scope
2393
- // .evaluate((node) => {
2394
- // if (node && node.style) {
2395
- // if (!node.__previousOutline) {
2396
- // node.style.outline = "";
2397
- // } else {
2398
- // node.style.outline = node.__previousOutline;
2399
- // }
2400
- // }
2401
- // })
2402
- // .then(() => {})
2403
- // .catch((e) => {
2404
- // // console.log(`Error while unhighlighting node ${JSON.stringify(scope)}: ${e}`);
2405
- // });
2406
- // } else {
2407
- // scope
2408
- // .evaluate(([css]) => {
2409
- // if (!css) {
2410
- // return;
2411
- // }
2412
- // let elements = Array.from(document.querySelectorAll(css));
2413
- // for (i = 0; i < elements.length; i++) {
2414
- // let element = elements[i];
2415
- // if (!element.style) {
2416
- // return;
2417
- // }
2418
- // if (!element.__previousOutline) {
2419
- // element.style.outline = "";
2420
- // } else {
2421
- // element.style.outline = element.__previousOutline;
2422
- // }
2423
- // }
2424
- // })
2425
- // .then(() => {})
2426
- // .catch((e) => {
2427
- // // console.error(`Error while unhighlighting element in css: ${e}`);
2428
- // });
2429
- // }
2430
- // } catch (error) {
2431
- // // console.debug(error);
2432
- // }
2433
- // }
2947
+ _matcher(text) {
2948
+ if (!text) {
2949
+ return { matcher: "contains", queryText: "" };
2950
+ }
2951
+ if (text.length < 2) {
2952
+ return { matcher: "contains", queryText: text };
2953
+ }
2954
+ const split = text.split(":");
2955
+ const matcher = split[0].toLowerCase();
2956
+ const queryText = split.slice(1).join(":").trim();
2957
+ return { matcher, queryText };
2958
+ }
2959
+ _getDomain(url) {
2960
+ if (url.length === 0 || (!url.startsWith("http://") && !url.startsWith("https://"))) {
2961
+ return "";
2962
+ }
2963
+ let hostnameFragments = url.split("/")[2].split(".");
2964
+ if (hostnameFragments.some((fragment) => fragment.includes(":"))) {
2965
+ return hostnameFragments.join("-").split(":").join("-");
2966
+ }
2967
+ let n = hostnameFragments.length;
2968
+ let fragments = [...hostnameFragments];
2969
+ while (n > 0 && hostnameFragments[n - 1].length <= 3) {
2970
+ hostnameFragments.pop();
2971
+ n = hostnameFragments.length;
2972
+ }
2973
+ if (n == 0) {
2974
+ if (fragments[0] === "www")
2975
+ fragments = fragments.slice(1);
2976
+ return fragments.length > 1 ? fragments.slice(0, fragments.length - 1).join("-") : fragments.join("-");
2977
+ }
2978
+ if (hostnameFragments[0] === "www")
2979
+ hostnameFragments = hostnameFragments.slice(1);
2980
+ return hostnameFragments.join(".");
2981
+ }
2982
+ /**
2983
+ * Verify the page path matches the given path.
2984
+ * @param {string} pathPart - The path to verify.
2985
+ * @param {object} options - Options for verification.
2986
+ * @param {object} world - The world context.
2987
+ * @returns {Promise<object>} - The state info after verification.
2988
+ */
2434
2989
  async verifyPagePath(pathPart, options = {}, world = null) {
2435
- const startTime = Date.now();
2436
2990
  let error = null;
2437
2991
  let screenshotId = null;
2438
2992
  let screenshotPath = null;
@@ -2446,113 +3000,212 @@ class StableBrowser {
2446
3000
  pathPart = newValue;
2447
3001
  }
2448
3002
  info.pathPart = pathPart;
3003
+ const { matcher, queryText } = this._matcher(pathPart);
3004
+ const state = {
3005
+ text_search: queryText,
3006
+ options,
3007
+ world,
3008
+ locate: false,
3009
+ scroll: false,
3010
+ highlight: false,
3011
+ type: Types.VERIFY_PAGE_PATH,
3012
+ text: `Verify the page url is ${queryText}`,
3013
+ _text: `Verify the page url is ${queryText}`,
3014
+ operation: "verifyPagePath",
3015
+ log: "***** verify page url is " + queryText + " *****\n",
3016
+ };
2449
3017
  try {
3018
+ await _preCommand(state, this);
3019
+ state.info.text = queryText;
2450
3020
  for (let i = 0; i < 30; i++) {
2451
3021
  const url = await this.page.url();
2452
- if (!url.includes(pathPart)) {
2453
- if (i === 29) {
2454
- throw new Error(`url ${url} doesn't contain ${pathPart}`);
2455
- }
2456
- await new Promise((resolve) => setTimeout(resolve, 1000));
2457
- continue;
3022
+ switch (matcher) {
3023
+ case "exact":
3024
+ if (url !== queryText) {
3025
+ if (i === 29) {
3026
+ throw new Error(`Page URL ${url} is not equal to ${queryText}`);
3027
+ }
3028
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3029
+ continue;
3030
+ }
3031
+ break;
3032
+ case "contains":
3033
+ if (!url.includes(queryText)) {
3034
+ if (i === 29) {
3035
+ throw new Error(`Page URL ${url} doesn't contain ${queryText}`);
3036
+ }
3037
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3038
+ continue;
3039
+ }
3040
+ break;
3041
+ case "starts-with":
3042
+ {
3043
+ const domain = this._getDomain(url);
3044
+ if (domain.length > 0 && domain !== queryText) {
3045
+ if (i === 29) {
3046
+ throw new Error(`Page URL ${url} doesn't start with ${queryText}`);
3047
+ }
3048
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3049
+ continue;
3050
+ }
3051
+ }
3052
+ break;
3053
+ case "ends-with":
3054
+ {
3055
+ const urlObj = new URL(url);
3056
+ let route = "/";
3057
+ if (urlObj.pathname !== "/") {
3058
+ route = urlObj.pathname.split("/").slice(-1)[0].trim();
3059
+ }
3060
+ else {
3061
+ route = "/";
3062
+ }
3063
+ if (route !== queryText) {
3064
+ if (i === 29) {
3065
+ throw new Error(`Page URL ${url} doesn't end with ${queryText}`);
3066
+ }
3067
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3068
+ continue;
3069
+ }
3070
+ }
3071
+ break;
3072
+ case "regex":
3073
+ const regex = new RegExp(queryText.slice(1, -1), "g");
3074
+ if (!regex.test(url)) {
3075
+ if (i === 29) {
3076
+ throw new Error(`Page URL ${url} doesn't match regex ${queryText}`);
3077
+ }
3078
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3079
+ continue;
3080
+ }
3081
+ break;
3082
+ default:
3083
+ console.log("Unknown matching type, defaulting to contains matching");
3084
+ if (!url.includes(pathPart)) {
3085
+ if (i === 29) {
3086
+ throw new Error(`Page URL ${url} does not contain ${pathPart}`);
3087
+ }
3088
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3089
+ continue;
3090
+ }
2458
3091
  }
2459
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2460
- return info;
3092
+ await _screenshot(state, this);
3093
+ return state.info;
2461
3094
  }
2462
3095
  }
2463
3096
  catch (e) {
2464
- //await this.closeUnexpectedPopups();
2465
- this.logger.error("verify page path failed " + info.log);
2466
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2467
- info.screenshotPath = screenshotPath;
2468
- Object.assign(e, { info: info });
2469
- error = e;
2470
- // throw e;
2471
- await _commandError({ text: "verifyPagePath", operation: "verifyPagePath", pathPart, info }, e, this);
3097
+ state.info.failCause.lastError = e.message;
3098
+ state.info.failCause.assertionFailed = true;
3099
+ await _commandError(state, e, this);
2472
3100
  }
2473
3101
  finally {
2474
- const endTime = Date.now();
2475
- _reportToWorld(world, {
2476
- type: Types.VERIFY_PAGE_PATH,
2477
- text: "Verify page path",
2478
- _text: "Verify the page path contains " + pathPart,
2479
- screenshotId,
2480
- result: error
2481
- ? {
2482
- status: "FAILED",
2483
- startTime,
2484
- endTime,
2485
- message: error?.message,
2486
- }
2487
- : {
2488
- status: "PASSED",
2489
- startTime,
2490
- endTime,
2491
- },
2492
- info: info,
2493
- });
3102
+ await _commandFinally(state, this);
2494
3103
  }
2495
3104
  }
3105
+ /**
3106
+ * Verify the page title matches the given title.
3107
+ * @param {string} title - The title to verify.
3108
+ * @param {object} options - Options for verification.
3109
+ * @param {object} world - The world context.
3110
+ * @returns {Promise<object>} - The state info after verification.
3111
+ */
2496
3112
  async verifyPageTitle(title, options = {}, world = null) {
2497
- const startTime = Date.now();
2498
3113
  let error = null;
2499
3114
  let screenshotId = null;
2500
3115
  let screenshotPath = null;
2501
3116
  await new Promise((resolve) => setTimeout(resolve, 2000));
2502
- const info = {};
2503
- info.log = "***** verify page title " + title + " *****\n";
2504
- info.operation = "verifyPageTitle";
2505
3117
  const newValue = await this._replaceWithLocalData(title, world);
2506
3118
  if (newValue !== title) {
2507
3119
  this.logger.info(title + "=" + newValue);
2508
3120
  title = newValue;
2509
3121
  }
2510
- info.title = title;
3122
+ const { matcher, queryText } = this._matcher(title);
3123
+ const state = {
3124
+ text_search: queryText,
3125
+ options,
3126
+ world,
3127
+ locate: false,
3128
+ scroll: false,
3129
+ highlight: false,
3130
+ type: Types.VERIFY_PAGE_TITLE,
3131
+ text: `Verify the page title is ${queryText}`,
3132
+ _text: `Verify the page title is ${queryText}`,
3133
+ operation: "verifyPageTitle",
3134
+ log: "***** verify page title is " + queryText + " *****\n",
3135
+ };
2511
3136
  try {
3137
+ await _preCommand(state, this);
3138
+ state.info.text = queryText;
2512
3139
  for (let i = 0; i < 30; i++) {
2513
3140
  const foundTitle = await this.page.title();
2514
- if (!foundTitle.includes(title)) {
2515
- if (i === 29) {
2516
- throw new Error(`url ${foundTitle} doesn't contain ${title}`);
2517
- }
2518
- await new Promise((resolve) => setTimeout(resolve, 1000));
2519
- continue;
3141
+ switch (matcher) {
3142
+ case "exact":
3143
+ if (foundTitle !== queryText) {
3144
+ if (i === 29) {
3145
+ throw new Error(`Page Title ${foundTitle} is not equal to ${queryText}`);
3146
+ }
3147
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3148
+ continue;
3149
+ }
3150
+ break;
3151
+ case "contains":
3152
+ if (!foundTitle.includes(queryText)) {
3153
+ if (i === 29) {
3154
+ throw new Error(`Page Title ${foundTitle} doesn't contain ${queryText}`);
3155
+ }
3156
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3157
+ continue;
3158
+ }
3159
+ break;
3160
+ case "starts-with":
3161
+ if (!foundTitle.startsWith(queryText)) {
3162
+ if (i === 29) {
3163
+ throw new Error(`Page title ${foundTitle} doesn't start with ${queryText}`);
3164
+ }
3165
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3166
+ continue;
3167
+ }
3168
+ break;
3169
+ case "ends-with":
3170
+ if (!foundTitle.endsWith(queryText)) {
3171
+ if (i === 29) {
3172
+ throw new Error(`Page Title ${foundTitle} doesn't end with ${queryText}`);
3173
+ }
3174
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3175
+ continue;
3176
+ }
3177
+ break;
3178
+ case "regex":
3179
+ const regex = new RegExp(queryText.slice(1, -1), "g");
3180
+ if (!regex.test(foundTitle)) {
3181
+ if (i === 29) {
3182
+ throw new Error(`Page Title ${foundTitle} doesn't match regex ${queryText}`);
3183
+ }
3184
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3185
+ continue;
3186
+ }
3187
+ break;
3188
+ default:
3189
+ console.log("Unknown matching type, defaulting to contains matching");
3190
+ if (!foundTitle.includes(title)) {
3191
+ if (i === 29) {
3192
+ throw new Error(`Page Title ${foundTitle} does not contain ${title}`);
3193
+ }
3194
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3195
+ continue;
3196
+ }
2520
3197
  }
2521
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2522
- return info;
3198
+ await _screenshot(state, this);
3199
+ return state.info;
2523
3200
  }
2524
3201
  }
2525
3202
  catch (e) {
2526
- //await this.closeUnexpectedPopups();
2527
- this.logger.error("verify page title failed " + info.log);
2528
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2529
- info.screenshotPath = screenshotPath;
2530
- Object.assign(e, { info: info });
2531
- error = e;
2532
- // throw e;
2533
- await _commandError({ text: "verifyPageTitle", operation: "verifyPageTitle", title, info, throwError: true }, e, this);
3203
+ state.info.failCause.lastError = e.message;
3204
+ state.info.failCause.assertionFailed = true;
3205
+ await _commandError(state, e, this);
2534
3206
  }
2535
3207
  finally {
2536
- const endTime = Date.now();
2537
- _reportToWorld(world, {
2538
- type: Types.VERIFY_PAGE_PATH,
2539
- text: "Verify page title",
2540
- _text: "Verify the page title contains " + title,
2541
- screenshotId,
2542
- result: error
2543
- ? {
2544
- status: "FAILED",
2545
- startTime,
2546
- endTime,
2547
- message: error?.message,
2548
- }
2549
- : {
2550
- status: "PASSED",
2551
- startTime,
2552
- endTime,
2553
- },
2554
- info: info,
2555
- });
3208
+ await _commandFinally(state, this);
2556
3209
  }
2557
3210
  }
2558
3211
  async findTextInAllFrames(dateAlternatives, numberAlternatives, text, state, partial = true, ignoreCase = false) {
@@ -2636,27 +3289,10 @@ class StableBrowser {
2636
3289
  const frame = resultWithElementsFound[0].frame;
2637
3290
  const dataAttribute = `[data-blinq-id-${resultWithElementsFound[0].randomToken}]`;
2638
3291
  await this._highlightElements(frame, dataAttribute);
2639
- // if (world && world.screenshot && !world.screenshotPath) {
2640
- // console.log(`Highlighting for verify text is found while running from recorder`);
2641
- // this._highlightElements(frame, dataAttribute).then(async () => {
2642
- // await new Promise((resolve) => setTimeout(resolve, 1000));
2643
- // this._unhighlightElements(frame, dataAttribute)
2644
- // .then(async () => {
2645
- // console.log(`Unhighlighted frame dataAttribute successfully`);
2646
- // })
2647
- // .catch(
2648
- // (e) => {}
2649
- // console.error(e)
2650
- // );
2651
- // });
2652
- // }
2653
3292
  const element = await frame.locator(dataAttribute).first();
2654
- // await new Promise((resolve) => setTimeout(resolve, 100));
2655
- // await this._unhighlightElements(frame, dataAttribute);
2656
3293
  if (element) {
2657
3294
  await this.scrollIfNeeded(element, state.info);
2658
3295
  await element.dispatchEvent("bvt_verify_page_contains_text");
2659
- // await _screenshot(state, this, element);
2660
3296
  }
2661
3297
  }
2662
3298
  await _screenshot(state, this);
@@ -2666,7 +3302,6 @@ class StableBrowser {
2666
3302
  console.error(error);
2667
3303
  }
2668
3304
  }
2669
- // await expect(element).toHaveCount(1, { timeout: 10000 });
2670
3305
  }
2671
3306
  catch (e) {
2672
3307
  await _commandError(state, e, this);
@@ -2748,6 +3383,8 @@ class StableBrowser {
2748
3383
  operation: "verify_text_with_relation",
2749
3384
  log: "***** search for " + textAnchor + " climb " + climb + " and verify " + textToVerify + " found *****\n",
2750
3385
  };
3386
+ const cmdStartTime = Date.now();
3387
+ let cmdEndTime = null;
2751
3388
  const timeout = this._getFindElementTimeout(options);
2752
3389
  await new Promise((resolve) => setTimeout(resolve, 2000));
2753
3390
  let newValue = await this._replaceWithLocalData(textAnchor, world);
@@ -2783,6 +3420,17 @@ class StableBrowser {
2783
3420
  await new Promise((resolve) => setTimeout(resolve, 1000));
2784
3421
  continue;
2785
3422
  }
3423
+ else {
3424
+ cmdEndTime = Date.now();
3425
+ if (cmdEndTime - cmdStartTime > 55000) {
3426
+ if (foundAncore) {
3427
+ throw new Error(`Text ${textToVerify} not found in page`);
3428
+ }
3429
+ else {
3430
+ throw new Error(`Text ${textAnchor} not found in page`);
3431
+ }
3432
+ }
3433
+ }
2786
3434
  try {
2787
3435
  for (let i = 0; i < resultWithElementsFound.length; i++) {
2788
3436
  foundAncore = true;
@@ -3182,6 +3830,43 @@ class StableBrowser {
3182
3830
  });
3183
3831
  }
3184
3832
  }
3833
+ /**
3834
+ * Explicit wait/sleep function that pauses execution for a specified duration
3835
+ * @param duration - Duration to sleep in milliseconds (default: 1000ms)
3836
+ * @param options - Optional configuration object
3837
+ * @param world - Optional world context
3838
+ * @returns Promise that resolves after the specified duration
3839
+ */
3840
+ async sleep(duration = 1000, options = {}, world = null) {
3841
+ const state = {
3842
+ duration,
3843
+ options,
3844
+ world,
3845
+ locate: false,
3846
+ scroll: false,
3847
+ screenshot: false,
3848
+ highlight: false,
3849
+ type: Types.SLEEP,
3850
+ text: `Sleep for ${duration} ms`,
3851
+ _text: `Sleep for ${duration} ms`,
3852
+ operation: "sleep",
3853
+ log: `***** Sleep for ${duration} ms *****\n`,
3854
+ };
3855
+ try {
3856
+ await _preCommand(state, this);
3857
+ if (duration < 0) {
3858
+ throw new Error("Sleep duration cannot be negative");
3859
+ }
3860
+ await new Promise((resolve) => setTimeout(resolve, duration));
3861
+ return state.info;
3862
+ }
3863
+ catch (e) {
3864
+ await _commandError(state, e, this);
3865
+ }
3866
+ finally {
3867
+ await _commandFinally(state, this);
3868
+ }
3869
+ }
3185
3870
  async _replaceWithLocalData(value, world, _decrypt = true, totpWait = true) {
3186
3871
  try {
3187
3872
  return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
@@ -3212,6 +3897,7 @@ class StableBrowser {
3212
3897
  }
3213
3898
  async saveStoreState(path = null, world = null) {
3214
3899
  const storageState = await this.page.context().storageState();
3900
+ path = await this._replaceWithLocalData(path, this.world);
3215
3901
  //const testDataFile = _getDataFile(world, this.context, this);
3216
3902
  if (path) {
3217
3903
  // save { storageState: storageState } into the path
@@ -3222,6 +3908,7 @@ class StableBrowser {
3222
3908
  }
3223
3909
  }
3224
3910
  async restoreSaveState(path = null, world = null) {
3911
+ path = await this._replaceWithLocalData(path, this.world);
3225
3912
  await refreshBrowser(this, path, world);
3226
3913
  this.registerEventListeners(this.context);
3227
3914
  registerNetworkEvents(this.world, this, this.context, this.page);
@@ -3263,7 +3950,6 @@ class StableBrowser {
3263
3950
  else if (e.label === "domcontentloaded") {
3264
3951
  console.log("waited for the domcontent loaded timeout");
3265
3952
  }
3266
- console.log(".");
3267
3953
  }
3268
3954
  finally {
3269
3955
  await new Promise((resolve) => setTimeout(resolve, 2000));
@@ -3307,7 +3993,6 @@ class StableBrowser {
3307
3993
  await this.page.close();
3308
3994
  }
3309
3995
  catch (e) {
3310
- console.log(".");
3311
3996
  await _commandError(state, e, this);
3312
3997
  }
3313
3998
  finally {
@@ -3422,7 +4107,6 @@ class StableBrowser {
3422
4107
  await this.page.setViewportSize({ width: width, height: hight });
3423
4108
  }
3424
4109
  catch (e) {
3425
- console.log(".");
3426
4110
  await _commandError({ text: "setViewportSize", operation: "setViewportSize", width, hight, info }, e, this);
3427
4111
  }
3428
4112
  finally {
@@ -3460,7 +4144,6 @@ class StableBrowser {
3460
4144
  await this.page.reload();
3461
4145
  }
3462
4146
  catch (e) {
3463
- console.log(".");
3464
4147
  await _commandError({ text: "reloadPage", operation: "reloadPage", info }, e, this);
3465
4148
  }
3466
4149
  finally {
@@ -3504,6 +4187,10 @@ class StableBrowser {
3504
4187
  }
3505
4188
  }
3506
4189
  async beforeScenario(world, scenario) {
4190
+ if (world && world.attach) {
4191
+ world.attach(this.context.reportFolder, { mediaType: "text/plain" });
4192
+ }
4193
+ this.context.loadedRoutes = null;
3507
4194
  this.beforeScenarioCalled = true;
3508
4195
  if (scenario && scenario.pickle && scenario.pickle.name) {
3509
4196
  this.scenarioName = scenario.pickle.name;
@@ -3527,14 +4214,18 @@ class StableBrowser {
3527
4214
  envName = this.context.environment.name;
3528
4215
  }
3529
4216
  if (!process.env.TEMP_RUN) {
3530
- await getTestData(envName, world, undefined, this.featureName, this.scenarioName);
4217
+ await getTestData(envName, world, undefined, this.featureName, this.scenarioName, this.context);
3531
4218
  }
3532
4219
  await loadBrunoParams(this.context, this.context.environment.name);
3533
4220
  }
3534
4221
  async afterScenario(world, scenario) { }
3535
4222
  async beforeStep(world, step) {
4223
+ if (this.abortedExecution) {
4224
+ throw new Error("Aborted");
4225
+ }
3536
4226
  if (!this.beforeScenarioCalled) {
3537
4227
  this.beforeScenario(world, step);
4228
+ this.context.loadedRoutes = null;
3538
4229
  }
3539
4230
  if (this.stepIndex === undefined) {
3540
4231
  this.stepIndex = 0;
@@ -3559,13 +4250,16 @@ class StableBrowser {
3559
4250
  }
3560
4251
  if (this.initSnapshotTaken === false) {
3561
4252
  this.initSnapshotTaken = true;
3562
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4253
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
3563
4254
  const snapshot = await this.getAriaSnapshot();
3564
4255
  if (snapshot) {
3565
4256
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-before");
3566
4257
  }
3567
4258
  }
3568
4259
  }
4260
+ this.context.routeResults = null;
4261
+ await registerBeforeStepRoutes(this.context, this.stepName);
4262
+ networkBeforeStep(this.stepName);
3569
4263
  }
3570
4264
  async getAriaSnapshot() {
3571
4265
  try {
@@ -3585,12 +4279,18 @@ class StableBrowser {
3585
4279
  try {
3586
4280
  // Ensure frame is attached and has body
3587
4281
  const body = frame.locator("body");
3588
- await body.waitFor({ timeout }); // wait explicitly
4282
+ //await body.waitFor({ timeout: 2000 }); // wait explicitly
3589
4283
  const snapshot = await body.ariaSnapshot({ timeout });
4284
+ if (!snapshot) {
4285
+ continue;
4286
+ }
3590
4287
  content.push(`- frame: ${i}`);
3591
4288
  content.push(snapshot);
3592
4289
  }
3593
- catch (innerErr) { }
4290
+ catch (innerErr) {
4291
+ console.warn(`Frame ${i} snapshot failed:`, innerErr);
4292
+ content.push(`- frame: ${i} - error: ${innerErr.message}`);
4293
+ }
3594
4294
  }
3595
4295
  return content.join("\n");
3596
4296
  }
@@ -3600,6 +4300,49 @@ class StableBrowser {
3600
4300
  }
3601
4301
  return null;
3602
4302
  }
4303
+ /**
4304
+ * Sends command with custom payload to report.
4305
+ * @param commandText - Title of the command to be shown in the report.
4306
+ * @param commandStatus - Status of the command (e.g. "PASSED", "FAILED").
4307
+ * @param content - Content of the command to be shown in the report.
4308
+ * @param options - Options for the command. Example: { type: "json", screenshot: true }
4309
+ * @param world - Optional world context.
4310
+ * @public
4311
+ */
4312
+ async addCommandToReport(commandText, commandStatus, content, options = {}, world = null) {
4313
+ const state = {
4314
+ options,
4315
+ world,
4316
+ locate: false,
4317
+ scroll: false,
4318
+ screenshot: options.screenshot ?? false,
4319
+ highlight: options.highlight ?? false,
4320
+ type: Types.REPORT_COMMAND,
4321
+ text: commandText,
4322
+ _text: commandText,
4323
+ operation: "report_command",
4324
+ log: "***** " + commandText + " *****\n",
4325
+ };
4326
+ try {
4327
+ await _preCommand(state, this);
4328
+ const payload = {
4329
+ type: options.type ?? "text",
4330
+ content: content,
4331
+ screenshotId: null,
4332
+ };
4333
+ state.payload = payload;
4334
+ if (commandStatus === "FAILED") {
4335
+ state.throwError = true;
4336
+ throw new Error("Command failed");
4337
+ }
4338
+ }
4339
+ catch (e) {
4340
+ await _commandError(state, e, this);
4341
+ }
4342
+ finally {
4343
+ await _commandFinally(state, this);
4344
+ }
4345
+ }
3603
4346
  async afterStep(world, step) {
3604
4347
  this.stepName = null;
3605
4348
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
@@ -3619,13 +4362,43 @@ class StableBrowser {
3619
4362
  if (this.context) {
3620
4363
  this.context.examplesRow = null;
3621
4364
  }
3622
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4365
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
3623
4366
  const snapshot = await this.getAriaSnapshot();
3624
4367
  if (snapshot) {
3625
4368
  const obj = {};
3626
4369
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-after");
3627
4370
  }
3628
4371
  }
4372
+ this.context.routeResults = await registerAfterStepRoutes(this.context, world);
4373
+ if (this.context.routeResults) {
4374
+ if (world && world.attach) {
4375
+ await world.attach(JSON.stringify(this.context.routeResults), "application/json+intercept-results");
4376
+ }
4377
+ }
4378
+ if (!process.env.TEMP_RUN) {
4379
+ const state = {
4380
+ world,
4381
+ locate: false,
4382
+ scroll: false,
4383
+ screenshot: true,
4384
+ highlight: true,
4385
+ type: Types.STEP_COMPLETE,
4386
+ text: "end of scenario",
4387
+ _text: "end of scenario",
4388
+ operation: "step_complete",
4389
+ log: "***** " + "end of scenario" + " *****\n",
4390
+ };
4391
+ try {
4392
+ await _preCommand(state, this);
4393
+ }
4394
+ catch (e) {
4395
+ await _commandError(state, e, this);
4396
+ }
4397
+ finally {
4398
+ await _commandFinally(state, this);
4399
+ }
4400
+ }
4401
+ networkAfterStep(this.stepName);
3629
4402
  }
3630
4403
  }
3631
4404
  function createTimedPromise(promise, label) {