automation_model 1.0.695-dev → 1.0.695-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 (55) 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 +179 -88
  7. package/lib/auto_page.js.map +1 -1
  8. package/lib/browser_manager.js +35 -9
  9. package/lib/browser_manager.js.map +1 -1
  10. package/lib/bruno.js +8 -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/environment.d.ts +1 -0
  18. package/lib/environment.js +1 -0
  19. package/lib/environment.js.map +1 -1
  20. package/lib/error-messages.js.map +1 -1
  21. package/lib/file_checker.js +129 -25
  22. package/lib/file_checker.js.map +1 -1
  23. package/lib/find_function.js.map +1 -1
  24. package/lib/init_browser.js +4 -4
  25. package/lib/init_browser.js.map +1 -1
  26. package/lib/locate_element.js.map +1 -1
  27. package/lib/locator.d.ts +1 -0
  28. package/lib/locator.js +10 -3
  29. package/lib/locator.js.map +1 -1
  30. package/lib/locator_log.js.map +1 -1
  31. package/lib/network.d.ts +2 -0
  32. package/lib/network.js +232 -4
  33. package/lib/network.js.map +1 -1
  34. package/lib/route.d.ts +21 -0
  35. package/lib/route.js +443 -0
  36. package/lib/route.js.map +1 -0
  37. package/lib/scripts/axe.mini.js +3 -3
  38. package/lib/snapshot_validation.d.ts +4 -2
  39. package/lib/snapshot_validation.js +160 -42
  40. package/lib/snapshot_validation.js.map +1 -1
  41. package/lib/stable_browser.d.ts +57 -26
  42. package/lib/stable_browser.js +921 -202
  43. package/lib/stable_browser.js.map +1 -1
  44. package/lib/table.d.ts +9 -7
  45. package/lib/table.js +82 -12
  46. package/lib/table.js.map +1 -1
  47. package/lib/table_analyze.js.map +1 -1
  48. package/lib/table_helper.js.map +1 -1
  49. package/lib/test_context.d.ts +1 -0
  50. package/lib/test_context.js +1 -0
  51. package/lib/test_context.js.map +1 -1
  52. package/lib/utils.d.ts +2 -1
  53. package/lib/utils.js +74 -63
  54. package/lib/utils.js.map +1 -1
  55. package/package.json +12 -7
@@ -10,7 +10,7 @@ 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 { _convertToRegexQuery, _copyContext, _fixLocatorUsingParams, _fixUsingParams, _getServerUrl, extractStepExampleParameters, KEYBOARD_EVENTS, maskValue, replaceWithLocalTestData, scrollPageToLoadLazyElements, unEscapeString, _getDataFile, testForRegex, performAction, _getTestData, } from "./utils.js";
14
14
  import csv from "csv-parser";
15
15
  import { Readable } from "node:stream";
16
16
  import readline from "readline";
@@ -19,29 +19,33 @@ import { getTestData } from "./auto_page.js";
19
19
  import { locate_element } from "./locate_element.js";
20
20
  import { randomUUID } from "crypto";
21
21
  import { _commandError, _commandFinally, _preCommand, _validateSelectors, _screenshot, _reportToWorld, } from "./command_common.js";
22
- import { registerDownloadEvent, registerNetworkEvents } from "./network.js";
22
+ import { networkAfterStep, networkBeforeStep, registerDownloadEvent, registerNetworkEvents } from "./network.js";
23
23
  import { LocatorLog } from "./locator_log.js";
24
24
  import axios from "axios";
25
25
  import { _findCellArea, findElementsInArea } from "./table_helper.js";
26
- import { snapshotValidation } from "./snapshot_validation.js";
26
+ import { highlightSnapshot, snapshotValidation } from "./snapshot_validation.js";
27
27
  import { loadBrunoParams } from "./bruno.js";
28
+ import { registerAfterStepRoutes, registerBeforeStepRoutes } from "./route.js";
28
29
  export const Types = {
29
30
  CLICK: "click_element",
30
31
  WAIT_ELEMENT: "wait_element",
31
32
  NAVIGATE: "navigate",
33
+ GO_BACK: "go_back",
34
+ GO_FORWARD: "go_forward",
32
35
  FILL: "fill_element",
33
- EXECUTE: "execute_page_method",
34
- OPEN: "open_environment",
36
+ EXECUTE: "execute_page_method", //
37
+ OPEN: "open_environment", //
35
38
  COMPLETE: "step_complete",
36
39
  ASK: "information_needed",
37
- GET_PAGE_STATUS: "get_page_status",
38
- CLICK_ROW_ACTION: "click_row_action",
40
+ GET_PAGE_STATUS: "get_page_status", ///
41
+ CLICK_ROW_ACTION: "click_row_action", //
39
42
  VERIFY_ELEMENT_CONTAINS_TEXT: "verify_element_contains_text",
40
43
  VERIFY_PAGE_CONTAINS_TEXT: "verify_page_contains_text",
41
44
  VERIFY_PAGE_CONTAINS_NO_TEXT: "verify_page_contains_no_text",
42
45
  ANALYZE_TABLE: "analyze_table",
43
- SELECT: "select_combobox",
46
+ SELECT: "select_combobox", //
44
47
  VERIFY_PAGE_PATH: "verify_page_path",
48
+ VERIFY_PAGE_TITLE: "verify_page_title",
45
49
  TYPE_PRESS: "type_press",
46
50
  PRESS: "press_key",
47
51
  HOVER: "hover_element",
@@ -59,9 +63,13 @@ export const Types = {
59
63
  VERIFY_ATTRIBUTE: "verify_element_attribute",
60
64
  VERIFY_TEXT_WITH_RELATION: "verify_text_with_relation",
61
65
  BRUNO: "bruno",
62
- SNAPSHOT_VALIDATION: "snapshot_validation",
63
66
  VERIFY_FILE_EXISTS: "verify_file_exists",
64
67
  SET_INPUT_FILES: "set_input_files",
68
+ SNAPSHOT_VALIDATION: "snapshot_validation",
69
+ REPORT_COMMAND: "report_command",
70
+ STEP_COMPLETE: "step_complete",
71
+ SLEEP: "sleep",
72
+ CONDITIONAL_WAIT: "conditional_wait",
65
73
  };
66
74
  export const apps = {};
67
75
  const formatElementName = (elementName) => {
@@ -73,6 +81,7 @@ class StableBrowser {
73
81
  logger;
74
82
  context;
75
83
  world;
84
+ fastMode;
76
85
  project_path = null;
77
86
  webLogFile = null;
78
87
  networkLogger = null;
@@ -81,12 +90,14 @@ class StableBrowser {
81
90
  tags = null;
82
91
  isRecording = false;
83
92
  initSnapshotTaken = false;
84
- constructor(browser, page, logger = null, context = null, world = null) {
93
+ abortedExecution = false;
94
+ constructor(browser, page, logger = null, context = null, world = null, fastMode = false) {
85
95
  this.browser = browser;
86
96
  this.page = page;
87
97
  this.logger = logger;
88
98
  this.context = context;
89
99
  this.world = world;
100
+ this.fastMode = fastMode;
90
101
  if (!this.logger) {
91
102
  this.logger = console;
92
103
  }
@@ -115,6 +126,19 @@ class StableBrowser {
115
126
  context.pages = [this.page];
116
127
  const logFolder = path.join(this.project_path, "logs", "web");
117
128
  this.world = world;
129
+ if (this.configuration && this.configuration.fastMode === true) {
130
+ this.fastMode = true;
131
+ }
132
+ if (process.env.FAST_MODE === "true") {
133
+ // console.log("Fast mode enabled from environment variable");
134
+ this.fastMode = true;
135
+ }
136
+ if (process.env.FAST_MODE === "false") {
137
+ this.fastMode = false;
138
+ }
139
+ if (this.context) {
140
+ this.context.fastMode = this.fastMode;
141
+ }
118
142
  this.registerEventListeners(this.context);
119
143
  registerNetworkEvents(this.world, this, this.context, this.page);
120
144
  registerDownloadEvent(this.page, this.world, this.context);
@@ -125,6 +149,9 @@ class StableBrowser {
125
149
  if (!context.pageLoading) {
126
150
  context.pageLoading = { status: false };
127
151
  }
152
+ if (this.configuration && this.configuration.acceptDialog && this.page) {
153
+ this.page.on("dialog", (dialog) => dialog.accept());
154
+ }
128
155
  context.playContext.on("page", async function (page) {
129
156
  if (this.configuration && this.configuration.closePopups === true) {
130
157
  console.log("close unexpected popups");
@@ -133,6 +160,14 @@ class StableBrowser {
133
160
  }
134
161
  context.pageLoading.status = true;
135
162
  this.page = page;
163
+ try {
164
+ if (this.configuration && this.configuration.acceptDialog) {
165
+ await page.on("dialog", (dialog) => dialog.accept());
166
+ }
167
+ }
168
+ catch (error) {
169
+ console.error("Error on dialog accept registration", error);
170
+ }
136
171
  context.page = page;
137
172
  context.pages.push(page);
138
173
  registerNetworkEvents(this.world, this, context, this.page);
@@ -184,7 +219,9 @@ class StableBrowser {
184
219
  if (newContextCreated) {
185
220
  this.registerEventListeners(this.context);
186
221
  await this.goto(this.context.environment.baseUrl);
187
- await this.waitForPageLoad();
222
+ if (!this.fastMode) {
223
+ await this.waitForPageLoad();
224
+ }
188
225
  }
189
226
  }
190
227
  async switchTab(tabTitleOrIndex) {
@@ -278,6 +315,7 @@ class StableBrowser {
278
315
  if (!url) {
279
316
  throw new Error("url is null, verify that the environment file is correct");
280
317
  }
318
+ url = await this._replaceWithLocalData(url, this.world);
281
319
  if (!url.startsWith("http")) {
282
320
  url = "https://" + url;
283
321
  }
@@ -309,6 +347,64 @@ class StableBrowser {
309
347
  await _commandFinally(state, this);
310
348
  }
311
349
  }
350
+ async goBack(options, world = null) {
351
+ const state = {
352
+ value: "",
353
+ world: world,
354
+ type: Types.GO_BACK,
355
+ text: `Browser navigate back`,
356
+ operation: "goBack",
357
+ log: "***** navigate back *****\n",
358
+ info: {},
359
+ locate: false,
360
+ scroll: false,
361
+ screenshot: false,
362
+ highlight: false,
363
+ };
364
+ try {
365
+ await _preCommand(state, this);
366
+ await this.page.goBack({
367
+ waitUntil: "load",
368
+ });
369
+ await _screenshot(state, this);
370
+ }
371
+ catch (error) {
372
+ console.error("Error on goBack", error);
373
+ _commandError(state, error, this);
374
+ }
375
+ finally {
376
+ await _commandFinally(state, this);
377
+ }
378
+ }
379
+ async goForward(options, world = null) {
380
+ const state = {
381
+ value: "",
382
+ world: world,
383
+ type: Types.GO_FORWARD,
384
+ text: `Browser navigate forward`,
385
+ operation: "goForward",
386
+ log: "***** navigate forward *****\n",
387
+ info: {},
388
+ locate: false,
389
+ scroll: false,
390
+ screenshot: false,
391
+ highlight: false,
392
+ };
393
+ try {
394
+ await _preCommand(state, this);
395
+ await this.page.goForward({
396
+ waitUntil: "load",
397
+ });
398
+ await _screenshot(state, this);
399
+ }
400
+ catch (error) {
401
+ console.error("Error on goForward", error);
402
+ _commandError(state, error, this);
403
+ }
404
+ finally {
405
+ await _commandFinally(state, this);
406
+ }
407
+ }
312
408
  async _getLocator(locator, scope, _params) {
313
409
  locator = _fixLocatorUsingParams(locator, _params);
314
410
  // locator = await this._replaceWithLocalData(locator);
@@ -422,7 +518,7 @@ class StableBrowser {
422
518
  }
423
519
  return { elementCount: tagCount, randomToken };
424
520
  }
425
- async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null) {
521
+ async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null, logErrors = false) {
426
522
  if (!info) {
427
523
  info = {};
428
524
  }
@@ -434,14 +530,13 @@ class StableBrowser {
434
530
  info.locatorLog = new LocatorLog(selectorHierarchy);
435
531
  }
436
532
  let locatorSearch = selectorHierarchy[index];
437
- let originalLocatorSearch = "";
438
533
  try {
439
- originalLocatorSearch = _fixUsingParams(JSON.stringify(locatorSearch), _params);
440
- locatorSearch = JSON.parse(originalLocatorSearch);
534
+ locatorSearch = _fixLocatorUsingParams(locatorSearch, _params);
441
535
  }
442
536
  catch (e) {
443
537
  console.error(e);
444
538
  }
539
+ let originalLocatorSearch = JSON.stringify(locatorSearch);
445
540
  //info.log += "searching for locator " + JSON.stringify(locatorSearch) + "\n";
446
541
  let locator = null;
447
542
  if (locatorSearch.climb && locatorSearch.climb >= 0) {
@@ -489,7 +584,7 @@ class StableBrowser {
489
584
  }
490
585
  return;
491
586
  }
492
- if (info.locatorLog && count === 0) {
587
+ if (info.locatorLog && count === 0 && logErrors) {
493
588
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "NOT_FOUND");
494
589
  }
495
590
  for (let j = 0; j < count; j++) {
@@ -504,7 +599,7 @@ class StableBrowser {
504
599
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "FOUND");
505
600
  }
506
601
  }
507
- else {
602
+ else if (logErrors) {
508
603
  info.failCause.visible = visible;
509
604
  info.failCause.enabled = enabled;
510
605
  if (!info.printMessages) {
@@ -596,7 +691,7 @@ class StableBrowser {
596
691
  let element = await this._locate_internal(selectors, info, _params, timeout, allowDisabled);
597
692
  if (!element.rerun) {
598
693
  const randomToken = Math.random().toString(36).substring(7);
599
- element.evaluate((el, randomToken) => {
694
+ await element.evaluate((el, randomToken) => {
600
695
  el.setAttribute("data-blinq-id-" + randomToken, "");
601
696
  }, randomToken);
602
697
  // if (element._frame) {
@@ -649,7 +744,7 @@ class StableBrowser {
649
744
  break;
650
745
  }
651
746
  catch (error) {
652
- console.error("frame not found " + frameLocator.css);
747
+ // console.error("frame not found " + frameLocator.css);
653
748
  }
654
749
  }
655
750
  }
@@ -727,7 +822,6 @@ class StableBrowser {
727
822
  let locatorsCount = 0;
728
823
  let lazy_scroll = false;
729
824
  //let arrayMode = Array.isArray(selectors);
730
- let scope = await this._findFrameScope(selectors, timeout, info);
731
825
  let selectorsLocators = null;
732
826
  selectorsLocators = selectors.locators;
733
827
  // group selectors by priority
@@ -755,6 +849,7 @@ class StableBrowser {
755
849
  let highPriorityOnly = true;
756
850
  let visibleOnly = true;
757
851
  while (true) {
852
+ let scope = await this._findFrameScope(selectors, timeout, info);
758
853
  locatorsCount = 0;
759
854
  let result = [];
760
855
  let popupResult = await this.closeUnexpectedPopups(info, _params);
@@ -845,7 +940,7 @@ class StableBrowser {
845
940
  }
846
941
  throw new Error("failed to locate first element no elements found, " + info.log);
847
942
  }
848
- async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name) {
943
+ async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name, logErrors = false) {
849
944
  let foundElements = [];
850
945
  const result = {
851
946
  foundElements: foundElements,
@@ -864,7 +959,9 @@ class StableBrowser {
864
959
  await this._collectLocatorInformation(locatorsGroup, i, this.page, foundLocators, _params, info, visibleOnly, allowDisabled, element_name);
865
960
  }
866
961
  catch (e) {
867
- this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
962
+ if (logErrors) {
963
+ this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
964
+ }
868
965
  }
869
966
  }
870
967
  if (foundLocators.length === 1) {
@@ -905,7 +1002,7 @@ class StableBrowser {
905
1002
  });
906
1003
  result.locatorIndex = i;
907
1004
  }
908
- else {
1005
+ else if (logErrors) {
909
1006
  info.failCause.foundMultiple = true;
910
1007
  if (info.locatorLog) {
911
1008
  info.locatorLog.setLocatorSearchStatus(JSON.stringify(locatorsGroup[i]), "FOUND_NOT_UNIQUE");
@@ -1028,7 +1125,9 @@ class StableBrowser {
1028
1125
  try {
1029
1126
  await _preCommand(state, this);
1030
1127
  await performAction("click", state.element, options, this, state, _params);
1031
- await this.waitForPageLoad();
1128
+ if (!this.fastMode) {
1129
+ await this.waitForPageLoad();
1130
+ }
1032
1131
  return state.info;
1033
1132
  }
1034
1133
  catch (e) {
@@ -1091,7 +1190,7 @@ class StableBrowser {
1091
1190
  // if (world && world.screenshot && !world.screenshotPath) {
1092
1191
  // console.log(`Highlighting while running from recorder`);
1093
1192
  await this._highlightElements(state.element);
1094
- await state.element.setChecked(checked);
1193
+ await state.element.setChecked(checked, { timeout: 2000 });
1095
1194
  await new Promise((resolve) => setTimeout(resolve, 1000));
1096
1195
  // await this._unHighlightElements(element);
1097
1196
  // }
@@ -1103,11 +1202,28 @@ class StableBrowser {
1103
1202
  this.logger.info("element did not change its state, ignoring...");
1104
1203
  }
1105
1204
  else {
1205
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1106
1206
  //await this.closeUnexpectedPopups();
1107
1207
  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));
1208
+ state.element_found = false;
1209
+ try {
1210
+ state.element = await this._locate(selectors, state.info, _params, 100);
1211
+ state.element_found = true;
1212
+ // check the check state
1213
+ }
1214
+ catch (error) {
1215
+ // element dismissed
1216
+ }
1217
+ if (state.element_found) {
1218
+ const isChecked = await state.element.isChecked();
1219
+ if (isChecked !== checked) {
1220
+ // perform click
1221
+ await state.element.click({ timeout: 2000, force: true });
1222
+ }
1223
+ else {
1224
+ this.logger.info(`Element ${selectors.element_name} is already in the desired state (${checked})`);
1225
+ }
1226
+ }
1111
1227
  }
1112
1228
  }
1113
1229
  await this.waitForPageLoad();
@@ -1403,7 +1519,9 @@ class StableBrowser {
1403
1519
  await new Promise((resolve) => setTimeout(resolve, 500));
1404
1520
  }
1405
1521
  }
1522
+ //if (!this.fastMode) {
1406
1523
  await _screenshot(state, this);
1524
+ //}
1407
1525
  if (enter === true) {
1408
1526
  await new Promise((resolve) => setTimeout(resolve, 2000));
1409
1527
  await this.page.keyboard.press("Enter");
@@ -1468,6 +1586,7 @@ class StableBrowser {
1468
1586
  selectors,
1469
1587
  _params,
1470
1588
  files,
1589
+ value: '"' + files.join('", "') + '"',
1471
1590
  options,
1472
1591
  world,
1473
1592
  type: Types.SET_INPUT_FILES,
@@ -1711,14 +1830,17 @@ class StableBrowser {
1711
1830
  throw new Error("referanceSnapshot is null");
1712
1831
  }
1713
1832
  let text = null;
1714
- if (fs.existsSync(path.join(this.project_path, "snapshots", referanceSnapshot + ".yml"))) {
1715
- text = fs.readFileSync(path.join(this.project_path, "snapshots", referanceSnapshot + ".yml"), "utf8");
1833
+ if (fs.existsSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yml"))) {
1834
+ text = fs.readFileSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yml"), "utf8");
1835
+ }
1836
+ else if (fs.existsSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yaml"))) {
1837
+ text = fs.readFileSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yaml"), "utf8");
1716
1838
  }
1717
1839
  else if (referanceSnapshot.startsWith("yaml:")) {
1718
1840
  text = referanceSnapshot.substring(5);
1719
1841
  }
1720
1842
  else {
1721
- throw new Error("referanceSnapshot file not found: " + referanceSnapshot);
1843
+ throw new Error("referenceSnapshot file not found: " + referanceSnapshot);
1722
1844
  }
1723
1845
  state.text = text;
1724
1846
  const newValue = await this._replaceWithLocalData(text, world);
@@ -1736,18 +1858,23 @@ class StableBrowser {
1736
1858
  scope = await this._findFrameScope(frameSelectors, timeout, state.info);
1737
1859
  }
1738
1860
  const snapshot = await scope.locator("body").ariaSnapshot({ timeout });
1739
- matchResult = snapshotValidation(snapshot, newValue);
1861
+ matchResult = snapshotValidation(snapshot, newValue, referanceSnapshot);
1740
1862
  if (matchResult.errorLine !== -1) {
1741
1863
  throw new Error("Snapshot validation failed at line " + matchResult.errorLineText);
1742
1864
  }
1743
1865
  // highlight and screenshot
1866
+ try {
1867
+ await await highlightSnapshot(newValue, scope);
1868
+ await _screenshot(state, this);
1869
+ }
1870
+ catch (e) { }
1744
1871
  return state.info;
1745
1872
  }
1746
1873
  catch (e) {
1747
1874
  // Log error but continue retrying until timeout is reached
1748
- this.logger.warn("Retrying containsText due to: " + e.message);
1875
+ //this.logger.warn("Retrying snapshot validation due to: " + e.message);
1749
1876
  }
1750
- await new Promise((resolve) => setTimeout(resolve, 1000)); // Wait 1 second before retrying
1877
+ await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait 1 second before retrying
1751
1878
  }
1752
1879
  throw new Error("No snapshot match " + matchResult?.errorLineText);
1753
1880
  }
@@ -1899,12 +2026,7 @@ class StableBrowser {
1899
2026
  }
1900
2027
  }
1901
2028
  getTestData(world = null) {
1902
- const dataFile = _getDataFile(world, this.context, this);
1903
- let data = {};
1904
- if (fs.existsSync(dataFile)) {
1905
- data = JSON.parse(fs.readFileSync(dataFile, "utf8"));
1906
- }
1907
- return data;
2029
+ return _getTestData(world, this.context, this);
1908
2030
  }
1909
2031
  async _screenShot(options = {}, world = null, info = null) {
1910
2032
  // collect url/path/title
@@ -2093,6 +2215,95 @@ class StableBrowser {
2093
2215
  state.value = await state.element.getAttribute(attribute);
2094
2216
  break;
2095
2217
  }
2218
+ if (options !== null) {
2219
+ if (options.regex && options.regex !== "") {
2220
+ // Construct a regex pattern from the provided string
2221
+ const regex = options.regex.slice(1, -1);
2222
+ const regexPattern = new RegExp(regex, "g");
2223
+ const matches = state.value.match(regexPattern);
2224
+ if (matches) {
2225
+ let newValue = "";
2226
+ for (const match of matches) {
2227
+ newValue += match;
2228
+ }
2229
+ state.value = newValue;
2230
+ }
2231
+ }
2232
+ if (options.trimSpaces && options.trimSpaces === true) {
2233
+ state.value = state.value.trim();
2234
+ }
2235
+ }
2236
+ state.info.value = state.value;
2237
+ this.setTestData({ [variable]: state.value }, world);
2238
+ this.logger.info("set test data: " + variable + "=" + state.value);
2239
+ // await new Promise((resolve) => setTimeout(resolve, 500));
2240
+ return state.info;
2241
+ }
2242
+ catch (e) {
2243
+ await _commandError(state, e, this);
2244
+ }
2245
+ finally {
2246
+ await _commandFinally(state, this);
2247
+ }
2248
+ }
2249
+ async extractProperty(selectors, property, variable, _params = null, options = {}, world = null) {
2250
+ const state = {
2251
+ selectors,
2252
+ _params,
2253
+ property,
2254
+ variable,
2255
+ options,
2256
+ world,
2257
+ type: Types.EXTRACT_PROPERTY,
2258
+ text: `Extract property from element`,
2259
+ _text: `Extract property ${property} from ${selectors.element_name}`,
2260
+ operation: "extractProperty",
2261
+ log: "***** extract property " + property + " from " + selectors.element_name + " *****\n",
2262
+ allowDisabled: true,
2263
+ };
2264
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2265
+ try {
2266
+ await _preCommand(state, this);
2267
+ switch (property) {
2268
+ case "inner_text":
2269
+ state.value = await state.element.innerText();
2270
+ break;
2271
+ case "href":
2272
+ state.value = await state.element.getAttribute("href");
2273
+ break;
2274
+ case "value":
2275
+ state.value = await state.element.inputValue();
2276
+ break;
2277
+ case "text":
2278
+ state.value = await state.element.textContent();
2279
+ break;
2280
+ default:
2281
+ if (property.startsWith("dataset.")) {
2282
+ const dataAttribute = property.substring(8);
2283
+ state.value = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2284
+ }
2285
+ else {
2286
+ state.value = String(await state.element.evaluate((element, prop) => element[prop], property));
2287
+ }
2288
+ }
2289
+ if (options !== null) {
2290
+ if (options.regex && options.regex !== "") {
2291
+ // Construct a regex pattern from the provided string
2292
+ const regex = options.regex.slice(1, -1);
2293
+ const regexPattern = new RegExp(regex, "g");
2294
+ const matches = state.value.match(regexPattern);
2295
+ if (matches) {
2296
+ let newValue = "";
2297
+ for (const match of matches) {
2298
+ newValue += match;
2299
+ }
2300
+ state.value = newValue;
2301
+ }
2302
+ }
2303
+ if (options.trimSpaces && options.trimSpaces === true) {
2304
+ state.value = state.value.trim();
2305
+ }
2306
+ }
2096
2307
  state.info.value = state.value;
2097
2308
  this.setTestData({ [variable]: state.value }, world);
2098
2309
  this.logger.info("set test data: " + variable + "=" + state.value);
@@ -2158,14 +2369,167 @@ class StableBrowser {
2158
2369
  let regex;
2159
2370
  if (expectedValue.startsWith("/") && expectedValue.endsWith("/")) {
2160
2371
  const patternBody = expectedValue.slice(1, -1);
2161
- regex = new RegExp(patternBody, "g");
2372
+ const processedPattern = patternBody.replace(/\n/g, ".*");
2373
+ regex = new RegExp(processedPattern, "gs");
2374
+ state.info.regex = true;
2162
2375
  }
2163
2376
  else {
2164
2377
  const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2165
2378
  regex = new RegExp(escapedPattern, "g");
2166
2379
  }
2167
- if (!val.match(regex)) {
2168
- let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2380
+ if (attribute === "innerText") {
2381
+ if (state.info.regex) {
2382
+ if (!regex.test(val)) {
2383
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2384
+ state.info.failCause.assertionFailed = true;
2385
+ state.info.failCause.lastError = errorMessage;
2386
+ throw new Error(errorMessage);
2387
+ }
2388
+ }
2389
+ else {
2390
+ const valLines = val.split("\n");
2391
+ const expectedLines = expectedValue.split("\n");
2392
+ const isPart = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine === expectedLine));
2393
+ if (!isPart) {
2394
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2395
+ state.info.failCause.assertionFailed = true;
2396
+ state.info.failCause.lastError = errorMessage;
2397
+ throw new Error(errorMessage);
2398
+ }
2399
+ }
2400
+ }
2401
+ else {
2402
+ if (!val.match(regex)) {
2403
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2404
+ state.info.failCause.assertionFailed = true;
2405
+ state.info.failCause.lastError = errorMessage;
2406
+ throw new Error(errorMessage);
2407
+ }
2408
+ }
2409
+ return state.info;
2410
+ }
2411
+ catch (e) {
2412
+ await _commandError(state, e, this);
2413
+ }
2414
+ finally {
2415
+ await _commandFinally(state, this);
2416
+ }
2417
+ }
2418
+ async verifyProperty(selectors, property, value, _params = null, options = {}, world = null) {
2419
+ const state = {
2420
+ selectors,
2421
+ _params,
2422
+ property,
2423
+ value,
2424
+ options,
2425
+ world,
2426
+ type: Types.VERIFY_PROPERTY,
2427
+ highlight: true,
2428
+ screenshot: true,
2429
+ text: `Verify element property`,
2430
+ _text: `Verify property ${property} from ${selectors.element_name} is ${value}`,
2431
+ operation: "verifyProperty",
2432
+ log: "***** verify property " + property + " from " + selectors.element_name + " *****\n",
2433
+ allowDisabled: true,
2434
+ };
2435
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2436
+ let val;
2437
+ let expectedValue;
2438
+ try {
2439
+ await _preCommand(state, this);
2440
+ expectedValue = await replaceWithLocalTestData(state.value, world);
2441
+ state.info.expectedValue = expectedValue;
2442
+ switch (property) {
2443
+ case "innerText":
2444
+ val = String(await state.element.innerText());
2445
+ break;
2446
+ case "text":
2447
+ val = String(await state.element.textContent());
2448
+ break;
2449
+ case "value":
2450
+ val = String(await state.element.inputValue());
2451
+ break;
2452
+ case "checked":
2453
+ val = String(await state.element.isChecked());
2454
+ break;
2455
+ case "disabled":
2456
+ val = String(await state.element.isDisabled());
2457
+ break;
2458
+ case "readOnly":
2459
+ const isEditable = await state.element.isEditable();
2460
+ val = String(!isEditable);
2461
+ break;
2462
+ case "innerHTML":
2463
+ val = String(await state.element.innerHTML());
2464
+ break;
2465
+ case "outerHTML":
2466
+ val = String(await state.element.evaluate((element) => element.outerHTML));
2467
+ break;
2468
+ default:
2469
+ if (property.startsWith("dataset.")) {
2470
+ const dataAttribute = property.substring(8);
2471
+ val = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2472
+ }
2473
+ else {
2474
+ val = String(await state.element.evaluate((element, prop) => element[prop], property));
2475
+ }
2476
+ }
2477
+ // Helper function to remove all style="" attributes
2478
+ const removeStyleAttributes = (htmlString) => {
2479
+ return htmlString.replace(/\s*style\s*=\s*"[^"]*"/gi, "");
2480
+ };
2481
+ // Remove style attributes for innerHTML and outerHTML properties
2482
+ if (property === "innerHTML" || property === "outerHTML") {
2483
+ val = removeStyleAttributes(val);
2484
+ expectedValue = removeStyleAttributes(expectedValue);
2485
+ }
2486
+ state.info.value = val;
2487
+ let regex;
2488
+ state.info.value = val;
2489
+ const isRegex = expectedValue.startsWith("regex:");
2490
+ const isContains = expectedValue.startsWith("contains:");
2491
+ const isExact = expectedValue.startsWith("exact:");
2492
+ let matchPassed = false;
2493
+ if (isRegex) {
2494
+ const rawPattern = expectedValue.slice(6); // remove "regex:"
2495
+ const lastSlashIndex = rawPattern.lastIndexOf("/");
2496
+ if (rawPattern.startsWith("/") && lastSlashIndex > 0) {
2497
+ const patternBody = rawPattern.slice(1, lastSlashIndex).replace(/\n/g, ".*");
2498
+ const flags = rawPattern.slice(lastSlashIndex + 1) || "gs";
2499
+ const regex = new RegExp(patternBody, flags);
2500
+ state.info.regex = true;
2501
+ matchPassed = regex.test(val);
2502
+ }
2503
+ else {
2504
+ // Fallback: treat as literal
2505
+ const escapedPattern = rawPattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2506
+ const regex = new RegExp(escapedPattern, "g");
2507
+ matchPassed = regex.test(val);
2508
+ }
2509
+ }
2510
+ else if (isContains) {
2511
+ const containsValue = expectedValue.slice(9); // remove "contains:"
2512
+ matchPassed = val.includes(containsValue);
2513
+ }
2514
+ else if (isExact) {
2515
+ const exactValue = expectedValue.slice(6); // remove "exact:"
2516
+ matchPassed = val === exactValue;
2517
+ }
2518
+ else if (property === "innerText") {
2519
+ // Default innerText logic
2520
+ const normalizedExpectedValue = expectedValue.replace(/\\n/g, "\n");
2521
+ const valLines = val.split("\n");
2522
+ const expectedLines = normalizedExpectedValue.split("\n");
2523
+ matchPassed = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine.trim() === expectedLine.trim()));
2524
+ }
2525
+ else {
2526
+ // Fallback exact or loose match
2527
+ const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2528
+ const regex = new RegExp(escapedPattern, "g");
2529
+ matchPassed = regex.test(val);
2530
+ }
2531
+ if (!matchPassed) {
2532
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2169
2533
  state.info.failCause.assertionFailed = true;
2170
2534
  state.info.failCause.lastError = errorMessage;
2171
2535
  throw new Error(errorMessage);
@@ -2179,6 +2543,132 @@ class StableBrowser {
2179
2543
  await _commandFinally(state, this);
2180
2544
  }
2181
2545
  }
2546
+ async conditionalWait(selectors, condition, timeout = 1000, _params = null, options = {}, world = null) {
2547
+ // Convert timeout from seconds to milliseconds
2548
+ const timeoutMs = timeout * 1000;
2549
+ const state = {
2550
+ selectors,
2551
+ _params,
2552
+ condition,
2553
+ timeout: timeoutMs, // Store as milliseconds for internal use
2554
+ options,
2555
+ world,
2556
+ type: Types.CONDITIONAL_WAIT,
2557
+ highlight: true,
2558
+ screenshot: true,
2559
+ text: `Conditional wait for element`,
2560
+ _text: `Wait for ${selectors.element_name} to be ${condition} (timeout: ${timeout}s)`, // Display original seconds
2561
+ operation: "conditionalWait",
2562
+ log: `***** conditional wait for ${condition} on ${selectors.element_name} *****\n`,
2563
+ allowDisabled: true,
2564
+ info: {},
2565
+ };
2566
+ // Initialize startTime outside try block to ensure it's always accessible
2567
+ const startTime = Date.now();
2568
+ let conditionMet = false;
2569
+ let currentValue = null;
2570
+ let lastError = null;
2571
+ // Main retry loop - continues until timeout or condition is met
2572
+ while (Date.now() - startTime < timeoutMs) {
2573
+ const elapsedTime = Date.now() - startTime;
2574
+ const remainingTime = timeoutMs - elapsedTime;
2575
+ try {
2576
+ // Try to execute _preCommand (element location)
2577
+ await _preCommand(state, this);
2578
+ // If _preCommand succeeds, start condition checking
2579
+ const checkCondition = async () => {
2580
+ try {
2581
+ switch (condition.toLowerCase()) {
2582
+ case "checked":
2583
+ currentValue = await state.element.isChecked();
2584
+ return currentValue === true;
2585
+ case "unchecked":
2586
+ currentValue = await state.element.isChecked();
2587
+ return currentValue === false;
2588
+ case "visible":
2589
+ currentValue = await state.element.isVisible();
2590
+ return currentValue === true;
2591
+ case "hidden":
2592
+ currentValue = await state.element.isVisible();
2593
+ return currentValue === false;
2594
+ case "enabled":
2595
+ currentValue = await state.element.isDisabled();
2596
+ return currentValue === false;
2597
+ case "disabled":
2598
+ currentValue = await state.element.isDisabled();
2599
+ return currentValue === true;
2600
+ case "editable":
2601
+ // currentValue = await String(await state.element.evaluate((element, prop) => element[prop], "isContentEditable"));
2602
+ currentValue = await state.element.isContentEditable();
2603
+ return currentValue === true;
2604
+ default:
2605
+ state.info.message = `Unsupported condition: '${condition}'. Supported conditions are: checked, unchecked, visible, hidden, enabled, disabled, editable.`;
2606
+ state.info.success = false;
2607
+ return false;
2608
+ }
2609
+ }
2610
+ catch (error) {
2611
+ // Don't throw here, just return false to continue retrying
2612
+ return false;
2613
+ }
2614
+ };
2615
+ // Inner loop for condition checking (once element is located)
2616
+ while (Date.now() - startTime < timeoutMs) {
2617
+ const currentElapsedTime = Date.now() - startTime;
2618
+ conditionMet = await checkCondition();
2619
+ if (conditionMet) {
2620
+ break;
2621
+ }
2622
+ // Check if we still have time for another attempt
2623
+ if (Date.now() - startTime + 50 < timeoutMs) {
2624
+ await new Promise((res) => setTimeout(res, 50));
2625
+ }
2626
+ else {
2627
+ break;
2628
+ }
2629
+ }
2630
+ // If we got here and condition is met, break out of main loop
2631
+ if (conditionMet) {
2632
+ break;
2633
+ }
2634
+ // If condition not met but no exception, we've timed out
2635
+ break;
2636
+ }
2637
+ catch (e) {
2638
+ lastError = e;
2639
+ const currentElapsedTime = Date.now() - startTime;
2640
+ const timeLeft = timeoutMs - currentElapsedTime;
2641
+ // Check if we have enough time left to retry
2642
+ if (timeLeft > 100) {
2643
+ await new Promise((resolve) => setTimeout(resolve, 50));
2644
+ }
2645
+ else {
2646
+ break;
2647
+ }
2648
+ }
2649
+ }
2650
+ const actualWaitTime = Date.now() - startTime;
2651
+ state.info = {
2652
+ success: conditionMet,
2653
+ conditionMet,
2654
+ actualWaitTime,
2655
+ currentValue,
2656
+ lastError: lastError?.message || null,
2657
+ message: conditionMet
2658
+ ? `Condition '${condition}' met after ${(actualWaitTime / 1000).toFixed(2)}s`
2659
+ : `Condition '${condition}' not met within ${timeout}s timeout`,
2660
+ };
2661
+ if (lastError) {
2662
+ state.log += `Last error: ${lastError.message}\n`;
2663
+ }
2664
+ try {
2665
+ await _commandFinally(state, this);
2666
+ }
2667
+ catch (finallyError) {
2668
+ state.log += `Error in _commandFinally: ${finallyError.message}\n`;
2669
+ }
2670
+ return state.info;
2671
+ }
2182
2672
  async extractEmailData(emailAddress, options, world) {
2183
2673
  if (!emailAddress) {
2184
2674
  throw new Error("email address is null");
@@ -2336,56 +2826,49 @@ class StableBrowser {
2336
2826
  console.debug(error);
2337
2827
  }
2338
2828
  }
2339
- // async _unhighlightElements(scope, css) {
2340
- // try {
2341
- // if (!scope) {
2342
- // return;
2343
- // }
2344
- // if (!css) {
2345
- // scope
2346
- // .evaluate((node) => {
2347
- // if (node && node.style) {
2348
- // if (!node.__previousOutline) {
2349
- // node.style.outline = "";
2350
- // } else {
2351
- // node.style.outline = node.__previousOutline;
2352
- // }
2353
- // }
2354
- // })
2355
- // .then(() => {})
2356
- // .catch((e) => {
2357
- // // console.log(`Error while unhighlighting node ${JSON.stringify(scope)}: ${e}`);
2358
- // });
2359
- // } else {
2360
- // scope
2361
- // .evaluate(([css]) => {
2362
- // if (!css) {
2363
- // return;
2364
- // }
2365
- // let elements = Array.from(document.querySelectorAll(css));
2366
- // for (i = 0; i < elements.length; i++) {
2367
- // let element = elements[i];
2368
- // if (!element.style) {
2369
- // return;
2370
- // }
2371
- // if (!element.__previousOutline) {
2372
- // element.style.outline = "";
2373
- // } else {
2374
- // element.style.outline = element.__previousOutline;
2375
- // }
2376
- // }
2377
- // })
2378
- // .then(() => {})
2379
- // .catch((e) => {
2380
- // // console.error(`Error while unhighlighting element in css: ${e}`);
2381
- // });
2382
- // }
2383
- // } catch (error) {
2384
- // // console.debug(error);
2385
- // }
2386
- // }
2829
+ _matcher(text) {
2830
+ if (!text) {
2831
+ return { matcher: "contains", queryText: "" };
2832
+ }
2833
+ if (text.length < 2) {
2834
+ return { matcher: "contains", queryText: text };
2835
+ }
2836
+ const split = text.split(":");
2837
+ const matcher = split[0].toLowerCase();
2838
+ const queryText = split.slice(1).join(":").trim();
2839
+ return { matcher, queryText };
2840
+ }
2841
+ _getDomain(url) {
2842
+ if (url.length === 0 || (!url.startsWith("http://") && !url.startsWith("https://"))) {
2843
+ return "";
2844
+ }
2845
+ let hostnameFragments = url.split("/")[2].split(".");
2846
+ if (hostnameFragments.some((fragment) => fragment.includes(":"))) {
2847
+ return hostnameFragments.join("-").split(":").join("-");
2848
+ }
2849
+ let n = hostnameFragments.length;
2850
+ let fragments = [...hostnameFragments];
2851
+ while (n > 0 && hostnameFragments[n - 1].length <= 3) {
2852
+ hostnameFragments.pop();
2853
+ n = hostnameFragments.length;
2854
+ }
2855
+ if (n == 0) {
2856
+ if (fragments[0] === "www")
2857
+ fragments = fragments.slice(1);
2858
+ return fragments.length > 1 ? fragments.slice(0, fragments.length - 1).join("-") : fragments.join("-");
2859
+ }
2860
+ if (hostnameFragments[0] === "www")
2861
+ hostnameFragments = hostnameFragments.slice(1);
2862
+ return hostnameFragments.join(".");
2863
+ }
2864
+ /**
2865
+ * Verify the page path matches the given path.
2866
+ * @param {string} pathPart - The path to verify.
2867
+ * @param {object} options - Options for verification.
2868
+ * @param {object} world - The world context.
2869
+ * @returns {Promise<object>} - The state info after verification.
2870
+ */
2387
2871
  async verifyPagePath(pathPart, options = {}, world = null) {
2388
- const startTime = Date.now();
2389
2872
  let error = null;
2390
2873
  let screenshotId = null;
2391
2874
  let screenshotPath = null;
@@ -2399,113 +2882,212 @@ class StableBrowser {
2399
2882
  pathPart = newValue;
2400
2883
  }
2401
2884
  info.pathPart = pathPart;
2885
+ const { matcher, queryText } = this._matcher(pathPart);
2886
+ const state = {
2887
+ text_search: queryText,
2888
+ options,
2889
+ world,
2890
+ locate: false,
2891
+ scroll: false,
2892
+ highlight: false,
2893
+ type: Types.VERIFY_PAGE_PATH,
2894
+ text: `Verify the page url is ${queryText}`,
2895
+ _text: `Verify the page url is ${queryText}`,
2896
+ operation: "verifyPagePath",
2897
+ log: "***** verify page url is " + queryText + " *****\n",
2898
+ };
2402
2899
  try {
2900
+ await _preCommand(state, this);
2901
+ state.info.text = queryText;
2403
2902
  for (let i = 0; i < 30; i++) {
2404
2903
  const url = await this.page.url();
2405
- if (!url.includes(pathPart)) {
2406
- if (i === 29) {
2407
- throw new Error(`url ${url} doesn't contain ${pathPart}`);
2408
- }
2409
- await new Promise((resolve) => setTimeout(resolve, 1000));
2410
- continue;
2904
+ switch (matcher) {
2905
+ case "exact":
2906
+ if (url !== queryText) {
2907
+ if (i === 29) {
2908
+ throw new Error(`Page URL ${url} is not equal to ${queryText}`);
2909
+ }
2910
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2911
+ continue;
2912
+ }
2913
+ break;
2914
+ case "contains":
2915
+ if (!url.includes(queryText)) {
2916
+ if (i === 29) {
2917
+ throw new Error(`Page URL ${url} doesn't contain ${queryText}`);
2918
+ }
2919
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2920
+ continue;
2921
+ }
2922
+ break;
2923
+ case "starts-with":
2924
+ {
2925
+ const domain = this._getDomain(url);
2926
+ if (domain.length > 0 && domain !== queryText) {
2927
+ if (i === 29) {
2928
+ throw new Error(`Page URL ${url} doesn't start with ${queryText}`);
2929
+ }
2930
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2931
+ continue;
2932
+ }
2933
+ }
2934
+ break;
2935
+ case "ends-with":
2936
+ {
2937
+ const urlObj = new URL(url);
2938
+ let route = "/";
2939
+ if (urlObj.pathname !== "/") {
2940
+ route = urlObj.pathname.split("/").slice(-1)[0].trim();
2941
+ }
2942
+ else {
2943
+ route = "/";
2944
+ }
2945
+ if (route !== queryText) {
2946
+ if (i === 29) {
2947
+ throw new Error(`Page URL ${url} doesn't end with ${queryText}`);
2948
+ }
2949
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2950
+ continue;
2951
+ }
2952
+ }
2953
+ break;
2954
+ case "regex":
2955
+ const regex = new RegExp(queryText.slice(1, -1), "g");
2956
+ if (!regex.test(url)) {
2957
+ if (i === 29) {
2958
+ throw new Error(`Page URL ${url} doesn't match regex ${queryText}`);
2959
+ }
2960
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2961
+ continue;
2962
+ }
2963
+ break;
2964
+ default:
2965
+ console.log("Unknown matching type, defaulting to contains matching");
2966
+ if (!url.includes(pathPart)) {
2967
+ if (i === 29) {
2968
+ throw new Error(`Page URL ${url} does not contain ${pathPart}`);
2969
+ }
2970
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2971
+ continue;
2972
+ }
2411
2973
  }
2412
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2413
- return info;
2974
+ await _screenshot(state, this);
2975
+ return state.info;
2414
2976
  }
2415
2977
  }
2416
2978
  catch (e) {
2417
- //await this.closeUnexpectedPopups();
2418
- this.logger.error("verify page path failed " + info.log);
2419
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2420
- info.screenshotPath = screenshotPath;
2421
- Object.assign(e, { info: info });
2422
- error = e;
2423
- // throw e;
2424
- await _commandError({ text: "verifyPagePath", operation: "verifyPagePath", pathPart, info }, e, this);
2979
+ state.info.failCause.lastError = e.message;
2980
+ state.info.failCause.assertionFailed = true;
2981
+ await _commandError(state, e, this);
2425
2982
  }
2426
2983
  finally {
2427
- const endTime = Date.now();
2428
- _reportToWorld(world, {
2429
- type: Types.VERIFY_PAGE_PATH,
2430
- text: "Verify page path",
2431
- _text: "Verify the page path contains " + pathPart,
2432
- screenshotId,
2433
- result: error
2434
- ? {
2435
- status: "FAILED",
2436
- startTime,
2437
- endTime,
2438
- message: error?.message,
2439
- }
2440
- : {
2441
- status: "PASSED",
2442
- startTime,
2443
- endTime,
2444
- },
2445
- info: info,
2446
- });
2984
+ await _commandFinally(state, this);
2447
2985
  }
2448
2986
  }
2987
+ /**
2988
+ * Verify the page title matches the given title.
2989
+ * @param {string} title - The title to verify.
2990
+ * @param {object} options - Options for verification.
2991
+ * @param {object} world - The world context.
2992
+ * @returns {Promise<object>} - The state info after verification.
2993
+ */
2449
2994
  async verifyPageTitle(title, options = {}, world = null) {
2450
- const startTime = Date.now();
2451
2995
  let error = null;
2452
2996
  let screenshotId = null;
2453
2997
  let screenshotPath = null;
2454
2998
  await new Promise((resolve) => setTimeout(resolve, 2000));
2455
- const info = {};
2456
- info.log = "***** verify page title " + title + " *****\n";
2457
- info.operation = "verifyPageTitle";
2458
2999
  const newValue = await this._replaceWithLocalData(title, world);
2459
3000
  if (newValue !== title) {
2460
3001
  this.logger.info(title + "=" + newValue);
2461
3002
  title = newValue;
2462
3003
  }
2463
- info.title = title;
3004
+ const { matcher, queryText } = this._matcher(title);
3005
+ const state = {
3006
+ text_search: queryText,
3007
+ options,
3008
+ world,
3009
+ locate: false,
3010
+ scroll: false,
3011
+ highlight: false,
3012
+ type: Types.VERIFY_PAGE_TITLE,
3013
+ text: `Verify the page title is ${queryText}`,
3014
+ _text: `Verify the page title is ${queryText}`,
3015
+ operation: "verifyPageTitle",
3016
+ log: "***** verify page title is " + queryText + " *****\n",
3017
+ };
2464
3018
  try {
3019
+ await _preCommand(state, this);
3020
+ state.info.text = queryText;
2465
3021
  for (let i = 0; i < 30; i++) {
2466
3022
  const foundTitle = await this.page.title();
2467
- if (!foundTitle.includes(title)) {
2468
- if (i === 29) {
2469
- throw new Error(`url ${foundTitle} doesn't contain ${title}`);
2470
- }
2471
- await new Promise((resolve) => setTimeout(resolve, 1000));
2472
- continue;
3023
+ switch (matcher) {
3024
+ case "exact":
3025
+ if (foundTitle !== queryText) {
3026
+ if (i === 29) {
3027
+ throw new Error(`Page Title ${foundTitle} is not equal to ${queryText}`);
3028
+ }
3029
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3030
+ continue;
3031
+ }
3032
+ break;
3033
+ case "contains":
3034
+ if (!foundTitle.includes(queryText)) {
3035
+ if (i === 29) {
3036
+ throw new Error(`Page Title ${foundTitle} doesn't contain ${queryText}`);
3037
+ }
3038
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3039
+ continue;
3040
+ }
3041
+ break;
3042
+ case "starts-with":
3043
+ if (!foundTitle.startsWith(queryText)) {
3044
+ if (i === 29) {
3045
+ throw new Error(`Page title ${foundTitle} doesn't start with ${queryText}`);
3046
+ }
3047
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3048
+ continue;
3049
+ }
3050
+ break;
3051
+ case "ends-with":
3052
+ if (!foundTitle.endsWith(queryText)) {
3053
+ if (i === 29) {
3054
+ throw new Error(`Page Title ${foundTitle} doesn't end with ${queryText}`);
3055
+ }
3056
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3057
+ continue;
3058
+ }
3059
+ break;
3060
+ case "regex":
3061
+ const regex = new RegExp(queryText.slice(1, -1), "g");
3062
+ if (!regex.test(foundTitle)) {
3063
+ if (i === 29) {
3064
+ throw new Error(`Page Title ${foundTitle} doesn't match regex ${queryText}`);
3065
+ }
3066
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3067
+ continue;
3068
+ }
3069
+ break;
3070
+ default:
3071
+ console.log("Unknown matching type, defaulting to contains matching");
3072
+ if (!foundTitle.includes(title)) {
3073
+ if (i === 29) {
3074
+ throw new Error(`Page Title ${foundTitle} does not contain ${title}`);
3075
+ }
3076
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3077
+ continue;
3078
+ }
2473
3079
  }
2474
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2475
- return info;
3080
+ await _screenshot(state, this);
3081
+ return state.info;
2476
3082
  }
2477
3083
  }
2478
3084
  catch (e) {
2479
- //await this.closeUnexpectedPopups();
2480
- this.logger.error("verify page title failed " + info.log);
2481
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2482
- info.screenshotPath = screenshotPath;
2483
- Object.assign(e, { info: info });
2484
- error = e;
2485
- // throw e;
2486
- await _commandError({ text: "verifyPageTitle", operation: "verifyPageTitle", title, info, throwError: true }, e, this);
3085
+ state.info.failCause.lastError = e.message;
3086
+ state.info.failCause.assertionFailed = true;
3087
+ await _commandError(state, e, this);
2487
3088
  }
2488
3089
  finally {
2489
- const endTime = Date.now();
2490
- _reportToWorld(world, {
2491
- type: Types.VERIFY_PAGE_PATH,
2492
- text: "Verify page title",
2493
- _text: "Verify the page title contains " + title,
2494
- screenshotId,
2495
- result: error
2496
- ? {
2497
- status: "FAILED",
2498
- startTime,
2499
- endTime,
2500
- message: error?.message,
2501
- }
2502
- : {
2503
- status: "PASSED",
2504
- startTime,
2505
- endTime,
2506
- },
2507
- info: info,
2508
- });
3090
+ await _commandFinally(state, this);
2509
3091
  }
2510
3092
  }
2511
3093
  async findTextInAllFrames(dateAlternatives, numberAlternatives, text, state, partial = true, ignoreCase = false) {
@@ -2589,27 +3171,10 @@ class StableBrowser {
2589
3171
  const frame = resultWithElementsFound[0].frame;
2590
3172
  const dataAttribute = `[data-blinq-id-${resultWithElementsFound[0].randomToken}]`;
2591
3173
  await this._highlightElements(frame, dataAttribute);
2592
- // if (world && world.screenshot && !world.screenshotPath) {
2593
- // console.log(`Highlighting for verify text is found while running from recorder`);
2594
- // this._highlightElements(frame, dataAttribute).then(async () => {
2595
- // await new Promise((resolve) => setTimeout(resolve, 1000));
2596
- // this._unhighlightElements(frame, dataAttribute)
2597
- // .then(async () => {
2598
- // console.log(`Unhighlighted frame dataAttribute successfully`);
2599
- // })
2600
- // .catch(
2601
- // (e) => {}
2602
- // console.error(e)
2603
- // );
2604
- // });
2605
- // }
2606
3174
  const element = await frame.locator(dataAttribute).first();
2607
- // await new Promise((resolve) => setTimeout(resolve, 100));
2608
- // await this._unhighlightElements(frame, dataAttribute);
2609
3175
  if (element) {
2610
3176
  await this.scrollIfNeeded(element, state.info);
2611
3177
  await element.dispatchEvent("bvt_verify_page_contains_text");
2612
- // await _screenshot(state, this, element);
2613
3178
  }
2614
3179
  }
2615
3180
  await _screenshot(state, this);
@@ -2619,7 +3184,6 @@ class StableBrowser {
2619
3184
  console.error(error);
2620
3185
  }
2621
3186
  }
2622
- // await expect(element).toHaveCount(1, { timeout: 10000 });
2623
3187
  }
2624
3188
  catch (e) {
2625
3189
  await _commandError(state, e, this);
@@ -2701,6 +3265,8 @@ class StableBrowser {
2701
3265
  operation: "verify_text_with_relation",
2702
3266
  log: "***** search for " + textAnchor + " climb " + climb + " and verify " + textToVerify + " found *****\n",
2703
3267
  };
3268
+ const cmdStartTime = Date.now();
3269
+ let cmdEndTime = null;
2704
3270
  const timeout = this._getFindElementTimeout(options);
2705
3271
  await new Promise((resolve) => setTimeout(resolve, 2000));
2706
3272
  let newValue = await this._replaceWithLocalData(textAnchor, world);
@@ -2736,6 +3302,17 @@ class StableBrowser {
2736
3302
  await new Promise((resolve) => setTimeout(resolve, 1000));
2737
3303
  continue;
2738
3304
  }
3305
+ else {
3306
+ cmdEndTime = Date.now();
3307
+ if (cmdEndTime - cmdStartTime > 55000) {
3308
+ if (foundAncore) {
3309
+ throw new Error(`Text ${textToVerify} not found in page`);
3310
+ }
3311
+ else {
3312
+ throw new Error(`Text ${textAnchor} not found in page`);
3313
+ }
3314
+ }
3315
+ }
2739
3316
  try {
2740
3317
  for (let i = 0; i < resultWithElementsFound.length; i++) {
2741
3318
  foundAncore = true;
@@ -3135,8 +3712,51 @@ class StableBrowser {
3135
3712
  });
3136
3713
  }
3137
3714
  }
3715
+ /**
3716
+ * Explicit wait/sleep function that pauses execution for a specified duration
3717
+ * @param duration - Duration to sleep in milliseconds (default: 1000ms)
3718
+ * @param options - Optional configuration object
3719
+ * @param world - Optional world context
3720
+ * @returns Promise that resolves after the specified duration
3721
+ */
3722
+ async sleep(duration = 1000, options = {}, world = null) {
3723
+ const state = {
3724
+ duration,
3725
+ options,
3726
+ world,
3727
+ locate: false,
3728
+ scroll: false,
3729
+ screenshot: false,
3730
+ highlight: false,
3731
+ type: Types.SLEEP,
3732
+ text: `Sleep for ${duration} ms`,
3733
+ _text: `Sleep for ${duration} ms`,
3734
+ operation: "sleep",
3735
+ log: `***** Sleep for ${duration} ms *****\n`,
3736
+ };
3737
+ try {
3738
+ await _preCommand(state, this);
3739
+ if (duration < 0) {
3740
+ throw new Error("Sleep duration cannot be negative");
3741
+ }
3742
+ await new Promise((resolve) => setTimeout(resolve, duration));
3743
+ return state.info;
3744
+ }
3745
+ catch (e) {
3746
+ await _commandError(state, e, this);
3747
+ }
3748
+ finally {
3749
+ await _commandFinally(state, this);
3750
+ }
3751
+ }
3138
3752
  async _replaceWithLocalData(value, world, _decrypt = true, totpWait = true) {
3139
- return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
3753
+ try {
3754
+ return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
3755
+ }
3756
+ catch (error) {
3757
+ this.logger.debug(error);
3758
+ throw error;
3759
+ }
3140
3760
  }
3141
3761
  _getLoadTimeout(options) {
3142
3762
  let timeout = 15000;
@@ -3159,6 +3779,7 @@ class StableBrowser {
3159
3779
  }
3160
3780
  async saveStoreState(path = null, world = null) {
3161
3781
  const storageState = await this.page.context().storageState();
3782
+ path = await this._replaceWithLocalData(path, this.world);
3162
3783
  //const testDataFile = _getDataFile(world, this.context, this);
3163
3784
  if (path) {
3164
3785
  // save { storageState: storageState } into the path
@@ -3169,10 +3790,14 @@ class StableBrowser {
3169
3790
  }
3170
3791
  }
3171
3792
  async restoreSaveState(path = null, world = null) {
3793
+ path = await this._replaceWithLocalData(path, this.world);
3172
3794
  await refreshBrowser(this, path, world);
3173
3795
  this.registerEventListeners(this.context);
3174
3796
  registerNetworkEvents(this.world, this, this.context, this.page);
3175
3797
  registerDownloadEvent(this.page, this.world, this.context);
3798
+ if (this.onRestoreSaveState) {
3799
+ this.onRestoreSaveState(path);
3800
+ }
3176
3801
  }
3177
3802
  async waitForPageLoad(options = {}, world = null) {
3178
3803
  let timeout = this._getLoadTimeout(options);
@@ -3207,7 +3832,6 @@ class StableBrowser {
3207
3832
  else if (e.label === "domcontentloaded") {
3208
3833
  console.log("waited for the domcontent loaded timeout");
3209
3834
  }
3210
- console.log(".");
3211
3835
  }
3212
3836
  finally {
3213
3837
  await new Promise((resolve) => setTimeout(resolve, 2000));
@@ -3251,7 +3875,6 @@ class StableBrowser {
3251
3875
  await this.page.close();
3252
3876
  }
3253
3877
  catch (e) {
3254
- console.log(".");
3255
3878
  await _commandError(state, e, this);
3256
3879
  }
3257
3880
  finally {
@@ -3366,7 +3989,6 @@ class StableBrowser {
3366
3989
  await this.page.setViewportSize({ width: width, height: hight });
3367
3990
  }
3368
3991
  catch (e) {
3369
- console.log(".");
3370
3992
  await _commandError({ text: "setViewportSize", operation: "setViewportSize", width, hight, info }, e, this);
3371
3993
  }
3372
3994
  finally {
@@ -3404,7 +4026,6 @@ class StableBrowser {
3404
4026
  await this.page.reload();
3405
4027
  }
3406
4028
  catch (e) {
3407
- console.log(".");
3408
4029
  await _commandError({ text: "reloadPage", operation: "reloadPage", info }, e, this);
3409
4030
  }
3410
4031
  finally {
@@ -3448,6 +4069,10 @@ class StableBrowser {
3448
4069
  }
3449
4070
  }
3450
4071
  async beforeScenario(world, scenario) {
4072
+ if (world && world.attach) {
4073
+ world.attach(this.context.reportFolder, { mediaType: "text/plain" });
4074
+ }
4075
+ this.context.loadedRoutes = null;
3451
4076
  this.beforeScenarioCalled = true;
3452
4077
  if (scenario && scenario.pickle && scenario.pickle.name) {
3453
4078
  this.scenarioName = scenario.pickle.name;
@@ -3471,14 +4096,18 @@ class StableBrowser {
3471
4096
  envName = this.context.environment.name;
3472
4097
  }
3473
4098
  if (!process.env.TEMP_RUN) {
3474
- await getTestData(envName, world, undefined, this.featureName, this.scenarioName);
4099
+ await getTestData(envName, world, undefined, this.featureName, this.scenarioName, this.context);
3475
4100
  }
3476
4101
  await loadBrunoParams(this.context, this.context.environment.name);
3477
4102
  }
3478
4103
  async afterScenario(world, scenario) { }
3479
4104
  async beforeStep(world, step) {
4105
+ if (this.abortedExecution) {
4106
+ throw new Error("Aborted");
4107
+ }
3480
4108
  if (!this.beforeScenarioCalled) {
3481
4109
  this.beforeScenario(world, step);
4110
+ this.context.loadedRoutes = null;
3482
4111
  }
3483
4112
  if (this.stepIndex === undefined) {
3484
4113
  this.stepIndex = 0;
@@ -3503,13 +4132,16 @@ class StableBrowser {
3503
4132
  }
3504
4133
  if (this.initSnapshotTaken === false) {
3505
4134
  this.initSnapshotTaken = true;
3506
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4135
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
3507
4136
  const snapshot = await this.getAriaSnapshot();
3508
4137
  if (snapshot) {
3509
4138
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-before");
3510
4139
  }
3511
4140
  }
3512
4141
  }
4142
+ this.context.routeResults = null;
4143
+ await registerBeforeStepRoutes(this.context, this.stepName);
4144
+ networkBeforeStep(this.stepName);
3513
4145
  }
3514
4146
  async getAriaSnapshot() {
3515
4147
  try {
@@ -3525,19 +4157,74 @@ class StableBrowser {
3525
4157
  const content = [`- path: ${path}`, `- title: ${title}`];
3526
4158
  const timeout = this.configuration.ariaSnapshotTimeout ? this.configuration.ariaSnapshotTimeout : 3000;
3527
4159
  for (let i = 0; i < frames.length; i++) {
3528
- content.push(`- frame: ${i}`);
3529
4160
  const frame = frames[i];
3530
- const snapshot = await frame.locator("body").ariaSnapshot({ timeout });
3531
- content.push(snapshot);
4161
+ try {
4162
+ // Ensure frame is attached and has body
4163
+ const body = frame.locator("body");
4164
+ //await body.waitFor({ timeout: 2000 }); // wait explicitly
4165
+ const snapshot = await body.ariaSnapshot({ timeout });
4166
+ if (!snapshot) {
4167
+ continue;
4168
+ }
4169
+ content.push(`- frame: ${i}`);
4170
+ content.push(snapshot);
4171
+ }
4172
+ catch (innerErr) {
4173
+ console.warn(`Frame ${i} snapshot failed:`, innerErr);
4174
+ content.push(`- frame: ${i} - error: ${innerErr.message}`);
4175
+ }
3532
4176
  }
3533
4177
  return content.join("\n");
3534
4178
  }
3535
4179
  catch (e) {
3536
4180
  console.log("Error in getAriaSnapshot");
3537
- console.debug(e);
4181
+ //console.debug(e);
3538
4182
  }
3539
4183
  return null;
3540
4184
  }
4185
+ /**
4186
+ * Sends command with custom payload to report.
4187
+ * @param commandText - Title of the command to be shown in the report.
4188
+ * @param commandStatus - Status of the command (e.g. "PASSED", "FAILED").
4189
+ * @param content - Content of the command to be shown in the report.
4190
+ * @param options - Options for the command. Example: { type: "json", screenshot: true }
4191
+ * @param world - Optional world context.
4192
+ * @public
4193
+ */
4194
+ async addCommandToReport(commandText, commandStatus, content, options = {}, world = null) {
4195
+ const state = {
4196
+ options,
4197
+ world,
4198
+ locate: false,
4199
+ scroll: false,
4200
+ screenshot: options.screenshot ?? false,
4201
+ highlight: options.highlight ?? false,
4202
+ type: Types.REPORT_COMMAND,
4203
+ text: commandText,
4204
+ _text: commandText,
4205
+ operation: "report_command",
4206
+ log: "***** " + commandText + " *****\n",
4207
+ };
4208
+ try {
4209
+ await _preCommand(state, this);
4210
+ const payload = {
4211
+ type: options.type ?? "text",
4212
+ content: content,
4213
+ screenshotId: null,
4214
+ };
4215
+ state.payload = payload;
4216
+ if (commandStatus === "FAILED") {
4217
+ state.throwError = true;
4218
+ throw new Error("Command failed");
4219
+ }
4220
+ }
4221
+ catch (e) {
4222
+ await _commandError(state, e, this);
4223
+ }
4224
+ finally {
4225
+ await _commandFinally(state, this);
4226
+ }
4227
+ }
3541
4228
  async afterStep(world, step) {
3542
4229
  this.stepName = null;
3543
4230
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
@@ -3545,10 +4232,12 @@ class StableBrowser {
3545
4232
  await this.context.browserObject.context.tracing.stopChunk({
3546
4233
  path: path.join(this.context.browserObject.traceFolder, `trace-${this.stepIndex}.zip`),
3547
4234
  });
3548
- await world.attach(JSON.stringify({
3549
- type: "trace",
3550
- traceFilePath: `trace-${this.stepIndex}.zip`,
3551
- }), "application/json+trace");
4235
+ if (world && world.attach) {
4236
+ await world.attach(JSON.stringify({
4237
+ type: "trace",
4238
+ traceFilePath: `trace-${this.stepIndex}.zip`,
4239
+ }), "application/json+trace");
4240
+ }
3552
4241
  // console.log("trace file created", `trace-${this.stepIndex}.zip`);
3553
4242
  }
3554
4243
  }
@@ -3562,6 +4251,36 @@ class StableBrowser {
3562
4251
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-after");
3563
4252
  }
3564
4253
  }
4254
+ this.context.routeResults = await registerAfterStepRoutes(this.context, world);
4255
+ if (this.context.routeResults) {
4256
+ if (world && world.attach) {
4257
+ await world.attach(JSON.stringify(this.context.routeResults), "application/json+intercept-results");
4258
+ }
4259
+ }
4260
+ if (!process.env.TEMP_RUN) {
4261
+ const state = {
4262
+ world,
4263
+ locate: false,
4264
+ scroll: false,
4265
+ screenshot: true,
4266
+ highlight: true,
4267
+ type: Types.STEP_COMPLETE,
4268
+ text: "end of scenario",
4269
+ _text: "end of scenario",
4270
+ operation: "step_complete",
4271
+ log: "***** " + "end of scenario" + " *****\n",
4272
+ };
4273
+ try {
4274
+ await _preCommand(state, this);
4275
+ }
4276
+ catch (e) {
4277
+ await _commandError(state, e, this);
4278
+ }
4279
+ finally {
4280
+ await _commandFinally(state, this);
4281
+ }
4282
+ }
4283
+ networkAfterStep(this.stepName);
3565
4284
  }
3566
4285
  }
3567
4286
  function createTimedPromise(promise, label) {