automation_model 1.0.697-dev → 1.0.697-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 +180 -89
  7. package/lib/auto_page.js.map +1 -1
  8. package/lib/browser_manager.d.ts +1 -0
  9. package/lib/browser_manager.js +54 -9
  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/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 +903 -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
@@ -2124,6 +2246,77 @@ class StableBrowser {
2124
2246
  await _commandFinally(state, this);
2125
2247
  }
2126
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
+ }
2307
+ state.info.value = state.value;
2308
+ this.setTestData({ [variable]: state.value }, world);
2309
+ this.logger.info("set test data: " + variable + "=" + state.value);
2310
+ // await new Promise((resolve) => setTimeout(resolve, 500));
2311
+ return state.info;
2312
+ }
2313
+ catch (e) {
2314
+ await _commandError(state, e, this);
2315
+ }
2316
+ finally {
2317
+ await _commandFinally(state, this);
2318
+ }
2319
+ }
2127
2320
  async verifyAttribute(selectors, attribute, value, _params = null, options = {}, world = null) {
2128
2321
  const state = {
2129
2322
  selectors,
@@ -2176,14 +2369,167 @@ class StableBrowser {
2176
2369
  let regex;
2177
2370
  if (expectedValue.startsWith("/") && expectedValue.endsWith("/")) {
2178
2371
  const patternBody = expectedValue.slice(1, -1);
2179
- regex = new RegExp(patternBody, "g");
2372
+ const processedPattern = patternBody.replace(/\n/g, ".*");
2373
+ regex = new RegExp(processedPattern, "gs");
2374
+ state.info.regex = true;
2180
2375
  }
2181
2376
  else {
2182
2377
  const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2183
2378
  regex = new RegExp(escapedPattern, "g");
2184
2379
  }
2185
- if (!val.match(regex)) {
2186
- 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}"`;
2187
2533
  state.info.failCause.assertionFailed = true;
2188
2534
  state.info.failCause.lastError = errorMessage;
2189
2535
  throw new Error(errorMessage);
@@ -2197,6 +2543,132 @@ class StableBrowser {
2197
2543
  await _commandFinally(state, this);
2198
2544
  }
2199
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
+ }
2200
2672
  async extractEmailData(emailAddress, options, world) {
2201
2673
  if (!emailAddress) {
2202
2674
  throw new Error("email address is null");
@@ -2354,56 +2826,49 @@ class StableBrowser {
2354
2826
  console.debug(error);
2355
2827
  }
2356
2828
  }
2357
- // async _unhighlightElements(scope, css) {
2358
- // try {
2359
- // if (!scope) {
2360
- // return;
2361
- // }
2362
- // if (!css) {
2363
- // scope
2364
- // .evaluate((node) => {
2365
- // if (node && node.style) {
2366
- // if (!node.__previousOutline) {
2367
- // node.style.outline = "";
2368
- // } else {
2369
- // node.style.outline = node.__previousOutline;
2370
- // }
2371
- // }
2372
- // })
2373
- // .then(() => {})
2374
- // .catch((e) => {
2375
- // // console.log(`Error while unhighlighting node ${JSON.stringify(scope)}: ${e}`);
2376
- // });
2377
- // } else {
2378
- // scope
2379
- // .evaluate(([css]) => {
2380
- // if (!css) {
2381
- // return;
2382
- // }
2383
- // let elements = Array.from(document.querySelectorAll(css));
2384
- // for (i = 0; i < elements.length; i++) {
2385
- // let element = elements[i];
2386
- // if (!element.style) {
2387
- // return;
2388
- // }
2389
- // if (!element.__previousOutline) {
2390
- // element.style.outline = "";
2391
- // } else {
2392
- // element.style.outline = element.__previousOutline;
2393
- // }
2394
- // }
2395
- // })
2396
- // .then(() => {})
2397
- // .catch((e) => {
2398
- // // console.error(`Error while unhighlighting element in css: ${e}`);
2399
- // });
2400
- // }
2401
- // } catch (error) {
2402
- // // console.debug(error);
2403
- // }
2404
- // }
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
+ */
2405
2871
  async verifyPagePath(pathPart, options = {}, world = null) {
2406
- const startTime = Date.now();
2407
2872
  let error = null;
2408
2873
  let screenshotId = null;
2409
2874
  let screenshotPath = null;
@@ -2417,113 +2882,212 @@ class StableBrowser {
2417
2882
  pathPart = newValue;
2418
2883
  }
2419
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
+ };
2420
2899
  try {
2900
+ await _preCommand(state, this);
2901
+ state.info.text = queryText;
2421
2902
  for (let i = 0; i < 30; i++) {
2422
2903
  const url = await this.page.url();
2423
- if (!url.includes(pathPart)) {
2424
- if (i === 29) {
2425
- throw new Error(`url ${url} doesn't contain ${pathPart}`);
2426
- }
2427
- await new Promise((resolve) => setTimeout(resolve, 1000));
2428
- 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
+ }
2429
2973
  }
2430
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2431
- return info;
2974
+ await _screenshot(state, this);
2975
+ return state.info;
2432
2976
  }
2433
2977
  }
2434
2978
  catch (e) {
2435
- //await this.closeUnexpectedPopups();
2436
- this.logger.error("verify page path failed " + info.log);
2437
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2438
- info.screenshotPath = screenshotPath;
2439
- Object.assign(e, { info: info });
2440
- error = e;
2441
- // throw e;
2442
- 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);
2443
2982
  }
2444
2983
  finally {
2445
- const endTime = Date.now();
2446
- _reportToWorld(world, {
2447
- type: Types.VERIFY_PAGE_PATH,
2448
- text: "Verify page path",
2449
- _text: "Verify the page path contains " + pathPart,
2450
- screenshotId,
2451
- result: error
2452
- ? {
2453
- status: "FAILED",
2454
- startTime,
2455
- endTime,
2456
- message: error?.message,
2457
- }
2458
- : {
2459
- status: "PASSED",
2460
- startTime,
2461
- endTime,
2462
- },
2463
- info: info,
2464
- });
2984
+ await _commandFinally(state, this);
2465
2985
  }
2466
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
+ */
2467
2994
  async verifyPageTitle(title, options = {}, world = null) {
2468
- const startTime = Date.now();
2469
2995
  let error = null;
2470
2996
  let screenshotId = null;
2471
2997
  let screenshotPath = null;
2472
2998
  await new Promise((resolve) => setTimeout(resolve, 2000));
2473
- const info = {};
2474
- info.log = "***** verify page title " + title + " *****\n";
2475
- info.operation = "verifyPageTitle";
2476
2999
  const newValue = await this._replaceWithLocalData(title, world);
2477
3000
  if (newValue !== title) {
2478
3001
  this.logger.info(title + "=" + newValue);
2479
3002
  title = newValue;
2480
3003
  }
2481
- 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
+ };
2482
3018
  try {
3019
+ await _preCommand(state, this);
3020
+ state.info.text = queryText;
2483
3021
  for (let i = 0; i < 30; i++) {
2484
3022
  const foundTitle = await this.page.title();
2485
- if (!foundTitle.includes(title)) {
2486
- if (i === 29) {
2487
- throw new Error(`url ${foundTitle} doesn't contain ${title}`);
2488
- }
2489
- await new Promise((resolve) => setTimeout(resolve, 1000));
2490
- 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
+ }
2491
3079
  }
2492
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2493
- return info;
3080
+ await _screenshot(state, this);
3081
+ return state.info;
2494
3082
  }
2495
3083
  }
2496
3084
  catch (e) {
2497
- //await this.closeUnexpectedPopups();
2498
- this.logger.error("verify page title failed " + info.log);
2499
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2500
- info.screenshotPath = screenshotPath;
2501
- Object.assign(e, { info: info });
2502
- error = e;
2503
- // throw e;
2504
- 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);
2505
3088
  }
2506
3089
  finally {
2507
- const endTime = Date.now();
2508
- _reportToWorld(world, {
2509
- type: Types.VERIFY_PAGE_PATH,
2510
- text: "Verify page title",
2511
- _text: "Verify the page title contains " + title,
2512
- screenshotId,
2513
- result: error
2514
- ? {
2515
- status: "FAILED",
2516
- startTime,
2517
- endTime,
2518
- message: error?.message,
2519
- }
2520
- : {
2521
- status: "PASSED",
2522
- startTime,
2523
- endTime,
2524
- },
2525
- info: info,
2526
- });
3090
+ await _commandFinally(state, this);
2527
3091
  }
2528
3092
  }
2529
3093
  async findTextInAllFrames(dateAlternatives, numberAlternatives, text, state, partial = true, ignoreCase = false) {
@@ -2607,27 +3171,10 @@ class StableBrowser {
2607
3171
  const frame = resultWithElementsFound[0].frame;
2608
3172
  const dataAttribute = `[data-blinq-id-${resultWithElementsFound[0].randomToken}]`;
2609
3173
  await this._highlightElements(frame, dataAttribute);
2610
- // if (world && world.screenshot && !world.screenshotPath) {
2611
- // console.log(`Highlighting for verify text is found while running from recorder`);
2612
- // this._highlightElements(frame, dataAttribute).then(async () => {
2613
- // await new Promise((resolve) => setTimeout(resolve, 1000));
2614
- // this._unhighlightElements(frame, dataAttribute)
2615
- // .then(async () => {
2616
- // console.log(`Unhighlighted frame dataAttribute successfully`);
2617
- // })
2618
- // .catch(
2619
- // (e) => {}
2620
- // console.error(e)
2621
- // );
2622
- // });
2623
- // }
2624
3174
  const element = await frame.locator(dataAttribute).first();
2625
- // await new Promise((resolve) => setTimeout(resolve, 100));
2626
- // await this._unhighlightElements(frame, dataAttribute);
2627
3175
  if (element) {
2628
3176
  await this.scrollIfNeeded(element, state.info);
2629
3177
  await element.dispatchEvent("bvt_verify_page_contains_text");
2630
- // await _screenshot(state, this, element);
2631
3178
  }
2632
3179
  }
2633
3180
  await _screenshot(state, this);
@@ -2637,7 +3184,6 @@ class StableBrowser {
2637
3184
  console.error(error);
2638
3185
  }
2639
3186
  }
2640
- // await expect(element).toHaveCount(1, { timeout: 10000 });
2641
3187
  }
2642
3188
  catch (e) {
2643
3189
  await _commandError(state, e, this);
@@ -2719,6 +3265,8 @@ class StableBrowser {
2719
3265
  operation: "verify_text_with_relation",
2720
3266
  log: "***** search for " + textAnchor + " climb " + climb + " and verify " + textToVerify + " found *****\n",
2721
3267
  };
3268
+ const cmdStartTime = Date.now();
3269
+ let cmdEndTime = null;
2722
3270
  const timeout = this._getFindElementTimeout(options);
2723
3271
  await new Promise((resolve) => setTimeout(resolve, 2000));
2724
3272
  let newValue = await this._replaceWithLocalData(textAnchor, world);
@@ -2754,6 +3302,17 @@ class StableBrowser {
2754
3302
  await new Promise((resolve) => setTimeout(resolve, 1000));
2755
3303
  continue;
2756
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
+ }
2757
3316
  try {
2758
3317
  for (let i = 0; i < resultWithElementsFound.length; i++) {
2759
3318
  foundAncore = true;
@@ -3153,8 +3712,51 @@ class StableBrowser {
3153
3712
  });
3154
3713
  }
3155
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
+ }
3156
3752
  async _replaceWithLocalData(value, world, _decrypt = true, totpWait = true) {
3157
- 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
+ }
3158
3760
  }
3159
3761
  _getLoadTimeout(options) {
3160
3762
  let timeout = 15000;
@@ -3177,6 +3779,7 @@ class StableBrowser {
3177
3779
  }
3178
3780
  async saveStoreState(path = null, world = null) {
3179
3781
  const storageState = await this.page.context().storageState();
3782
+ path = await this._replaceWithLocalData(path, this.world);
3180
3783
  //const testDataFile = _getDataFile(world, this.context, this);
3181
3784
  if (path) {
3182
3785
  // save { storageState: storageState } into the path
@@ -3187,10 +3790,14 @@ class StableBrowser {
3187
3790
  }
3188
3791
  }
3189
3792
  async restoreSaveState(path = null, world = null) {
3793
+ path = await this._replaceWithLocalData(path, this.world);
3190
3794
  await refreshBrowser(this, path, world);
3191
3795
  this.registerEventListeners(this.context);
3192
3796
  registerNetworkEvents(this.world, this, this.context, this.page);
3193
3797
  registerDownloadEvent(this.page, this.world, this.context);
3798
+ if (this.onRestoreSaveState) {
3799
+ this.onRestoreSaveState(path);
3800
+ }
3194
3801
  }
3195
3802
  async waitForPageLoad(options = {}, world = null) {
3196
3803
  let timeout = this._getLoadTimeout(options);
@@ -3225,7 +3832,6 @@ class StableBrowser {
3225
3832
  else if (e.label === "domcontentloaded") {
3226
3833
  console.log("waited for the domcontent loaded timeout");
3227
3834
  }
3228
- console.log(".");
3229
3835
  }
3230
3836
  finally {
3231
3837
  await new Promise((resolve) => setTimeout(resolve, 2000));
@@ -3269,7 +3875,6 @@ class StableBrowser {
3269
3875
  await this.page.close();
3270
3876
  }
3271
3877
  catch (e) {
3272
- console.log(".");
3273
3878
  await _commandError(state, e, this);
3274
3879
  }
3275
3880
  finally {
@@ -3384,7 +3989,6 @@ class StableBrowser {
3384
3989
  await this.page.setViewportSize({ width: width, height: hight });
3385
3990
  }
3386
3991
  catch (e) {
3387
- console.log(".");
3388
3992
  await _commandError({ text: "setViewportSize", operation: "setViewportSize", width, hight, info }, e, this);
3389
3993
  }
3390
3994
  finally {
@@ -3422,7 +4026,6 @@ class StableBrowser {
3422
4026
  await this.page.reload();
3423
4027
  }
3424
4028
  catch (e) {
3425
- console.log(".");
3426
4029
  await _commandError({ text: "reloadPage", operation: "reloadPage", info }, e, this);
3427
4030
  }
3428
4031
  finally {
@@ -3466,6 +4069,10 @@ class StableBrowser {
3466
4069
  }
3467
4070
  }
3468
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;
3469
4076
  this.beforeScenarioCalled = true;
3470
4077
  if (scenario && scenario.pickle && scenario.pickle.name) {
3471
4078
  this.scenarioName = scenario.pickle.name;
@@ -3489,14 +4096,18 @@ class StableBrowser {
3489
4096
  envName = this.context.environment.name;
3490
4097
  }
3491
4098
  if (!process.env.TEMP_RUN) {
3492
- await getTestData(envName, world, undefined, this.featureName, this.scenarioName);
4099
+ await getTestData(envName, world, undefined, this.featureName, this.scenarioName, this.context);
3493
4100
  }
3494
4101
  await loadBrunoParams(this.context, this.context.environment.name);
3495
4102
  }
3496
4103
  async afterScenario(world, scenario) { }
3497
4104
  async beforeStep(world, step) {
4105
+ if (this.abortedExecution) {
4106
+ throw new Error("Aborted");
4107
+ }
3498
4108
  if (!this.beforeScenarioCalled) {
3499
4109
  this.beforeScenario(world, step);
4110
+ this.context.loadedRoutes = null;
3500
4111
  }
3501
4112
  if (this.stepIndex === undefined) {
3502
4113
  this.stepIndex = 0;
@@ -3521,13 +4132,16 @@ class StableBrowser {
3521
4132
  }
3522
4133
  if (this.initSnapshotTaken === false) {
3523
4134
  this.initSnapshotTaken = true;
3524
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4135
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
3525
4136
  const snapshot = await this.getAriaSnapshot();
3526
4137
  if (snapshot) {
3527
4138
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-before");
3528
4139
  }
3529
4140
  }
3530
4141
  }
4142
+ this.context.routeResults = null;
4143
+ await registerBeforeStepRoutes(this.context, this.stepName);
4144
+ networkBeforeStep(this.stepName);
3531
4145
  }
3532
4146
  async getAriaSnapshot() {
3533
4147
  try {
@@ -3543,19 +4157,74 @@ class StableBrowser {
3543
4157
  const content = [`- path: ${path}`, `- title: ${title}`];
3544
4158
  const timeout = this.configuration.ariaSnapshotTimeout ? this.configuration.ariaSnapshotTimeout : 3000;
3545
4159
  for (let i = 0; i < frames.length; i++) {
3546
- content.push(`- frame: ${i}`);
3547
4160
  const frame = frames[i];
3548
- const snapshot = await frame.locator("body").ariaSnapshot({ timeout });
3549
- 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
+ }
3550
4176
  }
3551
4177
  return content.join("\n");
3552
4178
  }
3553
4179
  catch (e) {
3554
4180
  console.log("Error in getAriaSnapshot");
3555
- console.debug(e);
4181
+ //console.debug(e);
3556
4182
  }
3557
4183
  return null;
3558
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
+ }
3559
4228
  async afterStep(world, step) {
3560
4229
  this.stepName = null;
3561
4230
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
@@ -3563,10 +4232,12 @@ class StableBrowser {
3563
4232
  await this.context.browserObject.context.tracing.stopChunk({
3564
4233
  path: path.join(this.context.browserObject.traceFolder, `trace-${this.stepIndex}.zip`),
3565
4234
  });
3566
- await world.attach(JSON.stringify({
3567
- type: "trace",
3568
- traceFilePath: `trace-${this.stepIndex}.zip`,
3569
- }), "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
+ }
3570
4241
  // console.log("trace file created", `trace-${this.stepIndex}.zip`);
3571
4242
  }
3572
4243
  }
@@ -3580,6 +4251,36 @@ class StableBrowser {
3580
4251
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-after");
3581
4252
  }
3582
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);
3583
4284
  }
3584
4285
  }
3585
4286
  function createTimedPromise(promise, label) {