automation_model 1.0.706-dev → 1.0.706-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.map +1 -1
  5. package/lib/auto_page.d.ts +4 -2
  6. package/lib/auto_page.js +190 -132
  7. package/lib/auto_page.js.map +1 -1
  8. package/lib/browser_manager.d.ts +5 -0
  9. package/lib/browser_manager.js +73 -1
  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.map +1 -1
  22. package/lib/locate_element.js.map +1 -1
  23. package/lib/locator.d.ts +1 -0
  24. package/lib/locator.js +10 -3
  25. package/lib/locator.js.map +1 -1
  26. package/lib/locator_log.js.map +1 -1
  27. package/lib/network.d.ts +2 -0
  28. package/lib/network.js +334 -86
  29. package/lib/network.js.map +1 -1
  30. package/lib/route.d.ts +21 -0
  31. package/lib/route.js +450 -0
  32. package/lib/route.js.map +1 -0
  33. package/lib/scripts/axe.mini.js +3 -3
  34. package/lib/snapshot_validation.d.ts +4 -2
  35. package/lib/snapshot_validation.js +160 -42
  36. package/lib/snapshot_validation.js.map +1 -1
  37. package/lib/stable_browser.d.ts +61 -26
  38. package/lib/stable_browser.js +992 -194
  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");
@@ -1740,18 +1976,23 @@ class StableBrowser {
1740
1976
  scope = await this._findFrameScope(frameSelectors, timeout, state.info);
1741
1977
  }
1742
1978
  const snapshot = await scope.locator("body").ariaSnapshot({ timeout });
1743
- matchResult = snapshotValidation(snapshot, newValue);
1979
+ matchResult = snapshotValidation(snapshot, newValue, referanceSnapshot);
1744
1980
  if (matchResult.errorLine !== -1) {
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 containsText due to: " + e.message);
1993
+ //this.logger.warn("Retrying snapshot validation due to: " + e.message);
1753
1994
  }
1754
- await new Promise((resolve) => setTimeout(resolve, 1000)); // Wait 1 second before retrying
1995
+ await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait 1 second before retrying
1755
1996
  }
1756
1997
  throw new Error("No snapshot match " + matchResult?.errorLineText);
1757
1998
  }
@@ -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,
@@ -2180,14 +2487,167 @@ class StableBrowser {
2180
2487
  let regex;
2181
2488
  if (expectedValue.startsWith("/") && expectedValue.endsWith("/")) {
2182
2489
  const patternBody = expectedValue.slice(1, -1);
2183
- regex = new RegExp(patternBody, "g");
2490
+ const processedPattern = patternBody.replace(/\n/g, ".*");
2491
+ regex = new RegExp(processedPattern, "gs");
2492
+ state.info.regex = true;
2184
2493
  }
2185
2494
  else {
2186
2495
  const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2187
2496
  regex = new RegExp(escapedPattern, "g");
2188
2497
  }
2189
- if (!val.match(regex)) {
2190
- let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2498
+ if (attribute === "innerText") {
2499
+ if (state.info.regex) {
2500
+ if (!regex.test(val)) {
2501
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2502
+ state.info.failCause.assertionFailed = true;
2503
+ state.info.failCause.lastError = errorMessage;
2504
+ throw new Error(errorMessage);
2505
+ }
2506
+ }
2507
+ else {
2508
+ const valLines = val.split("\n");
2509
+ const expectedLines = expectedValue.split("\n");
2510
+ const isPart = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine === expectedLine));
2511
+ if (!isPart) {
2512
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2513
+ state.info.failCause.assertionFailed = true;
2514
+ state.info.failCause.lastError = errorMessage;
2515
+ throw new Error(errorMessage);
2516
+ }
2517
+ }
2518
+ }
2519
+ else {
2520
+ if (!val.match(regex)) {
2521
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2522
+ state.info.failCause.assertionFailed = true;
2523
+ state.info.failCause.lastError = errorMessage;
2524
+ throw new Error(errorMessage);
2525
+ }
2526
+ }
2527
+ return state.info;
2528
+ }
2529
+ catch (e) {
2530
+ await _commandError(state, e, this);
2531
+ }
2532
+ finally {
2533
+ await _commandFinally(state, this);
2534
+ }
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}"`;
2191
2651
  state.info.failCause.assertionFailed = true;
2192
2652
  state.info.failCause.lastError = errorMessage;
2193
2653
  throw new Error(errorMessage);
@@ -2201,6 +2661,132 @@ class StableBrowser {
2201
2661
  await _commandFinally(state, this);
2202
2662
  }
2203
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
+ }
2204
2790
  async extractEmailData(emailAddress, options, world) {
2205
2791
  if (!emailAddress) {
2206
2792
  throw new Error("email address is null");
@@ -2358,56 +2944,49 @@ class StableBrowser {
2358
2944
  console.debug(error);
2359
2945
  }
2360
2946
  }
2361
- // async _unhighlightElements(scope, css) {
2362
- // try {
2363
- // if (!scope) {
2364
- // return;
2365
- // }
2366
- // if (!css) {
2367
- // scope
2368
- // .evaluate((node) => {
2369
- // if (node && node.style) {
2370
- // if (!node.__previousOutline) {
2371
- // node.style.outline = "";
2372
- // } else {
2373
- // node.style.outline = node.__previousOutline;
2374
- // }
2375
- // }
2376
- // })
2377
- // .then(() => {})
2378
- // .catch((e) => {
2379
- // // console.log(`Error while unhighlighting node ${JSON.stringify(scope)}: ${e}`);
2380
- // });
2381
- // } else {
2382
- // scope
2383
- // .evaluate(([css]) => {
2384
- // if (!css) {
2385
- // return;
2386
- // }
2387
- // let elements = Array.from(document.querySelectorAll(css));
2388
- // for (i = 0; i < elements.length; i++) {
2389
- // let element = elements[i];
2390
- // if (!element.style) {
2391
- // return;
2392
- // }
2393
- // if (!element.__previousOutline) {
2394
- // element.style.outline = "";
2395
- // } else {
2396
- // element.style.outline = element.__previousOutline;
2397
- // }
2398
- // }
2399
- // })
2400
- // .then(() => {})
2401
- // .catch((e) => {
2402
- // // console.error(`Error while unhighlighting element in css: ${e}`);
2403
- // });
2404
- // }
2405
- // } catch (error) {
2406
- // // console.debug(error);
2407
- // }
2408
- // }
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
+ */
2409
2989
  async verifyPagePath(pathPart, options = {}, world = null) {
2410
- const startTime = Date.now();
2411
2990
  let error = null;
2412
2991
  let screenshotId = null;
2413
2992
  let screenshotPath = null;
@@ -2421,113 +3000,212 @@ class StableBrowser {
2421
3000
  pathPart = newValue;
2422
3001
  }
2423
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
+ };
2424
3017
  try {
3018
+ await _preCommand(state, this);
3019
+ state.info.text = queryText;
2425
3020
  for (let i = 0; i < 30; i++) {
2426
3021
  const url = await this.page.url();
2427
- if (!url.includes(pathPart)) {
2428
- if (i === 29) {
2429
- throw new Error(`url ${url} doesn't contain ${pathPart}`);
2430
- }
2431
- await new Promise((resolve) => setTimeout(resolve, 1000));
2432
- 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
+ }
2433
3091
  }
2434
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2435
- return info;
3092
+ await _screenshot(state, this);
3093
+ return state.info;
2436
3094
  }
2437
3095
  }
2438
3096
  catch (e) {
2439
- //await this.closeUnexpectedPopups();
2440
- this.logger.error("verify page path failed " + info.log);
2441
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2442
- info.screenshotPath = screenshotPath;
2443
- Object.assign(e, { info: info });
2444
- error = e;
2445
- // throw e;
2446
- 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);
2447
3100
  }
2448
3101
  finally {
2449
- const endTime = Date.now();
2450
- _reportToWorld(world, {
2451
- type: Types.VERIFY_PAGE_PATH,
2452
- text: "Verify page path",
2453
- _text: "Verify the page path contains " + pathPart,
2454
- screenshotId,
2455
- result: error
2456
- ? {
2457
- status: "FAILED",
2458
- startTime,
2459
- endTime,
2460
- message: error?.message,
2461
- }
2462
- : {
2463
- status: "PASSED",
2464
- startTime,
2465
- endTime,
2466
- },
2467
- info: info,
2468
- });
3102
+ await _commandFinally(state, this);
2469
3103
  }
2470
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
+ */
2471
3112
  async verifyPageTitle(title, options = {}, world = null) {
2472
- const startTime = Date.now();
2473
3113
  let error = null;
2474
3114
  let screenshotId = null;
2475
3115
  let screenshotPath = null;
2476
3116
  await new Promise((resolve) => setTimeout(resolve, 2000));
2477
- const info = {};
2478
- info.log = "***** verify page title " + title + " *****\n";
2479
- info.operation = "verifyPageTitle";
2480
3117
  const newValue = await this._replaceWithLocalData(title, world);
2481
3118
  if (newValue !== title) {
2482
3119
  this.logger.info(title + "=" + newValue);
2483
3120
  title = newValue;
2484
3121
  }
2485
- 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
+ };
2486
3136
  try {
3137
+ await _preCommand(state, this);
3138
+ state.info.text = queryText;
2487
3139
  for (let i = 0; i < 30; i++) {
2488
3140
  const foundTitle = await this.page.title();
2489
- if (!foundTitle.includes(title)) {
2490
- if (i === 29) {
2491
- throw new Error(`url ${foundTitle} doesn't contain ${title}`);
2492
- }
2493
- await new Promise((resolve) => setTimeout(resolve, 1000));
2494
- 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
+ }
2495
3197
  }
2496
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2497
- return info;
3198
+ await _screenshot(state, this);
3199
+ return state.info;
2498
3200
  }
2499
3201
  }
2500
3202
  catch (e) {
2501
- //await this.closeUnexpectedPopups();
2502
- this.logger.error("verify page title failed " + info.log);
2503
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2504
- info.screenshotPath = screenshotPath;
2505
- Object.assign(e, { info: info });
2506
- error = e;
2507
- // throw e;
2508
- 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);
2509
3206
  }
2510
3207
  finally {
2511
- const endTime = Date.now();
2512
- _reportToWorld(world, {
2513
- type: Types.VERIFY_PAGE_PATH,
2514
- text: "Verify page title",
2515
- _text: "Verify the page title contains " + title,
2516
- screenshotId,
2517
- result: error
2518
- ? {
2519
- status: "FAILED",
2520
- startTime,
2521
- endTime,
2522
- message: error?.message,
2523
- }
2524
- : {
2525
- status: "PASSED",
2526
- startTime,
2527
- endTime,
2528
- },
2529
- info: info,
2530
- });
3208
+ await _commandFinally(state, this);
2531
3209
  }
2532
3210
  }
2533
3211
  async findTextInAllFrames(dateAlternatives, numberAlternatives, text, state, partial = true, ignoreCase = false) {
@@ -2611,27 +3289,10 @@ class StableBrowser {
2611
3289
  const frame = resultWithElementsFound[0].frame;
2612
3290
  const dataAttribute = `[data-blinq-id-${resultWithElementsFound[0].randomToken}]`;
2613
3291
  await this._highlightElements(frame, dataAttribute);
2614
- // if (world && world.screenshot && !world.screenshotPath) {
2615
- // console.log(`Highlighting for verify text is found while running from recorder`);
2616
- // this._highlightElements(frame, dataAttribute).then(async () => {
2617
- // await new Promise((resolve) => setTimeout(resolve, 1000));
2618
- // this._unhighlightElements(frame, dataAttribute)
2619
- // .then(async () => {
2620
- // console.log(`Unhighlighted frame dataAttribute successfully`);
2621
- // })
2622
- // .catch(
2623
- // (e) => {}
2624
- // console.error(e)
2625
- // );
2626
- // });
2627
- // }
2628
3292
  const element = await frame.locator(dataAttribute).first();
2629
- // await new Promise((resolve) => setTimeout(resolve, 100));
2630
- // await this._unhighlightElements(frame, dataAttribute);
2631
3293
  if (element) {
2632
3294
  await this.scrollIfNeeded(element, state.info);
2633
3295
  await element.dispatchEvent("bvt_verify_page_contains_text");
2634
- // await _screenshot(state, this, element);
2635
3296
  }
2636
3297
  }
2637
3298
  await _screenshot(state, this);
@@ -2641,7 +3302,6 @@ class StableBrowser {
2641
3302
  console.error(error);
2642
3303
  }
2643
3304
  }
2644
- // await expect(element).toHaveCount(1, { timeout: 10000 });
2645
3305
  }
2646
3306
  catch (e) {
2647
3307
  await _commandError(state, e, this);
@@ -2723,6 +3383,8 @@ class StableBrowser {
2723
3383
  operation: "verify_text_with_relation",
2724
3384
  log: "***** search for " + textAnchor + " climb " + climb + " and verify " + textToVerify + " found *****\n",
2725
3385
  };
3386
+ const cmdStartTime = Date.now();
3387
+ let cmdEndTime = null;
2726
3388
  const timeout = this._getFindElementTimeout(options);
2727
3389
  await new Promise((resolve) => setTimeout(resolve, 2000));
2728
3390
  let newValue = await this._replaceWithLocalData(textAnchor, world);
@@ -2758,6 +3420,17 @@ class StableBrowser {
2758
3420
  await new Promise((resolve) => setTimeout(resolve, 1000));
2759
3421
  continue;
2760
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
+ }
2761
3434
  try {
2762
3435
  for (let i = 0; i < resultWithElementsFound.length; i++) {
2763
3436
  foundAncore = true;
@@ -3157,6 +3830,43 @@ class StableBrowser {
3157
3830
  });
3158
3831
  }
3159
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
+ }
3160
3870
  async _replaceWithLocalData(value, world, _decrypt = true, totpWait = true) {
3161
3871
  try {
3162
3872
  return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
@@ -3187,6 +3897,7 @@ class StableBrowser {
3187
3897
  }
3188
3898
  async saveStoreState(path = null, world = null) {
3189
3899
  const storageState = await this.page.context().storageState();
3900
+ path = await this._replaceWithLocalData(path, this.world);
3190
3901
  //const testDataFile = _getDataFile(world, this.context, this);
3191
3902
  if (path) {
3192
3903
  // save { storageState: storageState } into the path
@@ -3197,6 +3908,7 @@ class StableBrowser {
3197
3908
  }
3198
3909
  }
3199
3910
  async restoreSaveState(path = null, world = null) {
3911
+ path = await this._replaceWithLocalData(path, this.world);
3200
3912
  await refreshBrowser(this, path, world);
3201
3913
  this.registerEventListeners(this.context);
3202
3914
  registerNetworkEvents(this.world, this, this.context, this.page);
@@ -3238,7 +3950,6 @@ class StableBrowser {
3238
3950
  else if (e.label === "domcontentloaded") {
3239
3951
  console.log("waited for the domcontent loaded timeout");
3240
3952
  }
3241
- console.log(".");
3242
3953
  }
3243
3954
  finally {
3244
3955
  await new Promise((resolve) => setTimeout(resolve, 2000));
@@ -3282,7 +3993,6 @@ class StableBrowser {
3282
3993
  await this.page.close();
3283
3994
  }
3284
3995
  catch (e) {
3285
- console.log(".");
3286
3996
  await _commandError(state, e, this);
3287
3997
  }
3288
3998
  finally {
@@ -3397,7 +4107,6 @@ class StableBrowser {
3397
4107
  await this.page.setViewportSize({ width: width, height: hight });
3398
4108
  }
3399
4109
  catch (e) {
3400
- console.log(".");
3401
4110
  await _commandError({ text: "setViewportSize", operation: "setViewportSize", width, hight, info }, e, this);
3402
4111
  }
3403
4112
  finally {
@@ -3435,7 +4144,6 @@ class StableBrowser {
3435
4144
  await this.page.reload();
3436
4145
  }
3437
4146
  catch (e) {
3438
- console.log(".");
3439
4147
  await _commandError({ text: "reloadPage", operation: "reloadPage", info }, e, this);
3440
4148
  }
3441
4149
  finally {
@@ -3479,6 +4187,10 @@ class StableBrowser {
3479
4187
  }
3480
4188
  }
3481
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;
3482
4194
  this.beforeScenarioCalled = true;
3483
4195
  if (scenario && scenario.pickle && scenario.pickle.name) {
3484
4196
  this.scenarioName = scenario.pickle.name;
@@ -3502,14 +4214,18 @@ class StableBrowser {
3502
4214
  envName = this.context.environment.name;
3503
4215
  }
3504
4216
  if (!process.env.TEMP_RUN) {
3505
- await getTestData(envName, world, undefined, this.featureName, this.scenarioName);
4217
+ await getTestData(envName, world, undefined, this.featureName, this.scenarioName, this.context);
3506
4218
  }
3507
4219
  await loadBrunoParams(this.context, this.context.environment.name);
3508
4220
  }
3509
4221
  async afterScenario(world, scenario) { }
3510
4222
  async beforeStep(world, step) {
4223
+ if (this.abortedExecution) {
4224
+ throw new Error("Aborted");
4225
+ }
3511
4226
  if (!this.beforeScenarioCalled) {
3512
4227
  this.beforeScenario(world, step);
4228
+ this.context.loadedRoutes = null;
3513
4229
  }
3514
4230
  if (this.stepIndex === undefined) {
3515
4231
  this.stepIndex = 0;
@@ -3534,13 +4250,16 @@ class StableBrowser {
3534
4250
  }
3535
4251
  if (this.initSnapshotTaken === false) {
3536
4252
  this.initSnapshotTaken = true;
3537
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4253
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
3538
4254
  const snapshot = await this.getAriaSnapshot();
3539
4255
  if (snapshot) {
3540
4256
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-before");
3541
4257
  }
3542
4258
  }
3543
4259
  }
4260
+ this.context.routeResults = null;
4261
+ await registerBeforeStepRoutes(this.context, this.stepName);
4262
+ networkBeforeStep(this.stepName);
3544
4263
  }
3545
4264
  async getAriaSnapshot() {
3546
4265
  try {
@@ -3560,12 +4279,18 @@ class StableBrowser {
3560
4279
  try {
3561
4280
  // Ensure frame is attached and has body
3562
4281
  const body = frame.locator("body");
3563
- await body.waitFor({ timeout }); // wait explicitly
4282
+ //await body.waitFor({ timeout: 2000 }); // wait explicitly
3564
4283
  const snapshot = await body.ariaSnapshot({ timeout });
4284
+ if (!snapshot) {
4285
+ continue;
4286
+ }
3565
4287
  content.push(`- frame: ${i}`);
3566
4288
  content.push(snapshot);
3567
4289
  }
3568
- catch (innerErr) { }
4290
+ catch (innerErr) {
4291
+ console.warn(`Frame ${i} snapshot failed:`, innerErr);
4292
+ content.push(`- frame: ${i} - error: ${innerErr.message}`);
4293
+ }
3569
4294
  }
3570
4295
  return content.join("\n");
3571
4296
  }
@@ -3575,6 +4300,49 @@ class StableBrowser {
3575
4300
  }
3576
4301
  return null;
3577
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
+ }
3578
4346
  async afterStep(world, step) {
3579
4347
  this.stepName = null;
3580
4348
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
@@ -3594,13 +4362,43 @@ class StableBrowser {
3594
4362
  if (this.context) {
3595
4363
  this.context.examplesRow = null;
3596
4364
  }
3597
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4365
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
3598
4366
  const snapshot = await this.getAriaSnapshot();
3599
4367
  if (snapshot) {
3600
4368
  const obj = {};
3601
4369
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-after");
3602
4370
  }
3603
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);
3604
4402
  }
3605
4403
  }
3606
4404
  function createTimedPromise(promise, label) {