automation_model 1.0.684-dev → 1.0.684-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 (59) 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 -98
  7. package/lib/auto_page.js.map +1 -1
  8. package/lib/browser_manager.js +29 -9
  9. package/lib/browser_manager.js.map +1 -1
  10. package/lib/bruno.d.ts +1 -0
  11. package/lib/bruno.js +120 -21
  12. package/lib/bruno.js.map +1 -1
  13. package/lib/command_common.js +9 -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.d.ts +1 -0
  22. package/lib/file_checker.js +165 -0
  23. package/lib/file_checker.js.map +1 -0
  24. package/lib/find_function.js.map +1 -1
  25. package/lib/index.d.ts +1 -0
  26. package/lib/index.js +1 -0
  27. package/lib/index.js.map +1 -1
  28. package/lib/init_browser.js +4 -4
  29. package/lib/init_browser.js.map +1 -1
  30. package/lib/locate_element.js.map +1 -1
  31. package/lib/locator.d.ts +1 -0
  32. package/lib/locator.js +10 -3
  33. package/lib/locator.js.map +1 -1
  34. package/lib/locator_log.js.map +1 -1
  35. package/lib/network.d.ts +2 -0
  36. package/lib/network.js +148 -0
  37. package/lib/network.js.map +1 -1
  38. package/lib/route.d.ts +21 -0
  39. package/lib/route.js +390 -0
  40. package/lib/route.js.map +1 -0
  41. package/lib/scripts/axe.mini.js +3 -3
  42. package/lib/snapshot_validation.d.ts +37 -0
  43. package/lib/snapshot_validation.js +357 -0
  44. package/lib/snapshot_validation.js.map +1 -0
  45. package/lib/stable_browser.d.ts +62 -25
  46. package/lib/stable_browser.js +1100 -273
  47. package/lib/stable_browser.js.map +1 -1
  48. package/lib/table.d.ts +9 -7
  49. package/lib/table.js +82 -12
  50. package/lib/table.js.map +1 -1
  51. package/lib/table_analyze.js.map +1 -1
  52. package/lib/table_helper.js.map +1 -1
  53. package/lib/test_context.d.ts +1 -0
  54. package/lib/test_context.js +1 -0
  55. package/lib/test_context.js.map +1 -1
  56. package/lib/utils.d.ts +3 -2
  57. package/lib/utils.js +78 -56
  58. package/lib/utils.js.map +1 -1
  59. package/package.json +14 -8
@@ -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,27 +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 { highlightSnapshot, snapshotValidation } from "./snapshot_validation.js";
27
+ import { loadBrunoParams } from "./bruno.js";
28
+ import { registerAfterStepRoutes, registerBeforeStepRoutes } from "./route.js";
26
29
  export const Types = {
27
30
  CLICK: "click_element",
28
31
  WAIT_ELEMENT: "wait_element",
29
32
  NAVIGATE: "navigate",
33
+ GO_BACK: "go_back",
34
+ GO_FORWARD: "go_forward",
30
35
  FILL: "fill_element",
31
- EXECUTE: "execute_page_method",
32
- OPEN: "open_environment",
36
+ EXECUTE: "execute_page_method", //
37
+ OPEN: "open_environment", //
33
38
  COMPLETE: "step_complete",
34
39
  ASK: "information_needed",
35
- GET_PAGE_STATUS: "get_page_status",
36
- CLICK_ROW_ACTION: "click_row_action",
40
+ GET_PAGE_STATUS: "get_page_status", ///
41
+ CLICK_ROW_ACTION: "click_row_action", //
37
42
  VERIFY_ELEMENT_CONTAINS_TEXT: "verify_element_contains_text",
38
43
  VERIFY_PAGE_CONTAINS_TEXT: "verify_page_contains_text",
39
44
  VERIFY_PAGE_CONTAINS_NO_TEXT: "verify_page_contains_no_text",
40
45
  ANALYZE_TABLE: "analyze_table",
41
- SELECT: "select_combobox",
46
+ SELECT: "select_combobox", //
42
47
  VERIFY_PAGE_PATH: "verify_page_path",
48
+ VERIFY_PAGE_TITLE: "verify_page_title",
43
49
  TYPE_PRESS: "type_press",
44
50
  PRESS: "press_key",
45
51
  HOVER: "hover_element",
@@ -57,6 +63,13 @@ export const Types = {
57
63
  VERIFY_ATTRIBUTE: "verify_element_attribute",
58
64
  VERIFY_TEXT_WITH_RELATION: "verify_text_with_relation",
59
65
  BRUNO: "bruno",
66
+ VERIFY_FILE_EXISTS: "verify_file_exists",
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",
60
73
  };
61
74
  export const apps = {};
62
75
  const formatElementName = (elementName) => {
@@ -68,6 +81,7 @@ class StableBrowser {
68
81
  logger;
69
82
  context;
70
83
  world;
84
+ fastMode;
71
85
  project_path = null;
72
86
  webLogFile = null;
73
87
  networkLogger = null;
@@ -76,12 +90,13 @@ class StableBrowser {
76
90
  tags = null;
77
91
  isRecording = false;
78
92
  initSnapshotTaken = false;
79
- constructor(browser, page, logger = null, context = null, world = null) {
93
+ constructor(browser, page, logger = null, context = null, world = null, fastMode = false) {
80
94
  this.browser = browser;
81
95
  this.page = page;
82
96
  this.logger = logger;
83
97
  this.context = context;
84
98
  this.world = world;
99
+ this.fastMode = fastMode;
85
100
  if (!this.logger) {
86
101
  this.logger = console;
87
102
  }
@@ -110,6 +125,19 @@ class StableBrowser {
110
125
  context.pages = [this.page];
111
126
  const logFolder = path.join(this.project_path, "logs", "web");
112
127
  this.world = world;
128
+ if (this.configuration && this.configuration.fastMode === true) {
129
+ this.fastMode = true;
130
+ }
131
+ if (process.env.FAST_MODE === "true") {
132
+ // console.log("Fast mode enabled from environment variable");
133
+ this.fastMode = true;
134
+ }
135
+ if (process.env.FAST_MODE === "false") {
136
+ this.fastMode = false;
137
+ }
138
+ if (this.context) {
139
+ this.context.fastMode = this.fastMode;
140
+ }
113
141
  this.registerEventListeners(this.context);
114
142
  registerNetworkEvents(this.world, this, this.context, this.page);
115
143
  registerDownloadEvent(this.page, this.world, this.context);
@@ -120,6 +148,9 @@ class StableBrowser {
120
148
  if (!context.pageLoading) {
121
149
  context.pageLoading = { status: false };
122
150
  }
151
+ if (this.configuration && this.configuration.acceptDialog && this.page) {
152
+ this.page.on("dialog", (dialog) => dialog.accept());
153
+ }
123
154
  context.playContext.on("page", async function (page) {
124
155
  if (this.configuration && this.configuration.closePopups === true) {
125
156
  console.log("close unexpected popups");
@@ -128,6 +159,14 @@ class StableBrowser {
128
159
  }
129
160
  context.pageLoading.status = true;
130
161
  this.page = page;
162
+ try {
163
+ if (this.configuration && this.configuration.acceptDialog) {
164
+ await page.on("dialog", (dialog) => dialog.accept());
165
+ }
166
+ }
167
+ catch (error) {
168
+ console.error("Error on dialog accept registration", error);
169
+ }
131
170
  context.page = page;
132
171
  context.pages.push(page);
133
172
  registerNetworkEvents(this.world, this, context, this.page);
@@ -179,7 +218,9 @@ class StableBrowser {
179
218
  if (newContextCreated) {
180
219
  this.registerEventListeners(this.context);
181
220
  await this.goto(this.context.environment.baseUrl);
182
- await this.waitForPageLoad();
221
+ if (!this.fastMode) {
222
+ await this.waitForPageLoad();
223
+ }
183
224
  }
184
225
  }
185
226
  async switchTab(tabTitleOrIndex) {
@@ -273,6 +314,7 @@ class StableBrowser {
273
314
  if (!url) {
274
315
  throw new Error("url is null, verify that the environment file is correct");
275
316
  }
317
+ url = await this._replaceWithLocalData(url, this.world);
276
318
  if (!url.startsWith("http")) {
277
319
  url = "https://" + url;
278
320
  }
@@ -304,6 +346,64 @@ class StableBrowser {
304
346
  await _commandFinally(state, this);
305
347
  }
306
348
  }
349
+ async goBack(options, world = null) {
350
+ const state = {
351
+ value: "",
352
+ world: world,
353
+ type: Types.GO_BACK,
354
+ text: `Browser navigate back`,
355
+ operation: "goBack",
356
+ log: "***** navigate back *****\n",
357
+ info: {},
358
+ locate: false,
359
+ scroll: false,
360
+ screenshot: false,
361
+ highlight: false,
362
+ };
363
+ try {
364
+ await _preCommand(state, this);
365
+ await this.page.goBack({
366
+ waitUntil: "load",
367
+ });
368
+ await _screenshot(state, this);
369
+ }
370
+ catch (error) {
371
+ console.error("Error on goBack", error);
372
+ _commandError(state, error, this);
373
+ }
374
+ finally {
375
+ await _commandFinally(state, this);
376
+ }
377
+ }
378
+ async goForward(options, world = null) {
379
+ const state = {
380
+ value: "",
381
+ world: world,
382
+ type: Types.GO_FORWARD,
383
+ text: `Browser navigate forward`,
384
+ operation: "goForward",
385
+ log: "***** navigate forward *****\n",
386
+ info: {},
387
+ locate: false,
388
+ scroll: false,
389
+ screenshot: false,
390
+ highlight: false,
391
+ };
392
+ try {
393
+ await _preCommand(state, this);
394
+ await this.page.goForward({
395
+ waitUntil: "load",
396
+ });
397
+ await _screenshot(state, this);
398
+ }
399
+ catch (error) {
400
+ console.error("Error on goForward", error);
401
+ _commandError(state, error, this);
402
+ }
403
+ finally {
404
+ await _commandFinally(state, this);
405
+ }
406
+ }
307
407
  async _getLocator(locator, scope, _params) {
308
408
  locator = _fixLocatorUsingParams(locator, _params);
309
409
  // locator = await this._replaceWithLocalData(locator);
@@ -417,7 +517,7 @@ class StableBrowser {
417
517
  }
418
518
  return { elementCount: tagCount, randomToken };
419
519
  }
420
- async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null) {
520
+ async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null, logErrors = false) {
421
521
  if (!info) {
422
522
  info = {};
423
523
  }
@@ -429,14 +529,13 @@ class StableBrowser {
429
529
  info.locatorLog = new LocatorLog(selectorHierarchy);
430
530
  }
431
531
  let locatorSearch = selectorHierarchy[index];
432
- let originalLocatorSearch = "";
433
532
  try {
434
- originalLocatorSearch = _fixUsingParams(JSON.stringify(locatorSearch), _params);
435
- locatorSearch = JSON.parse(originalLocatorSearch);
533
+ locatorSearch = _fixLocatorUsingParams(locatorSearch, _params);
436
534
  }
437
535
  catch (e) {
438
536
  console.error(e);
439
537
  }
538
+ let originalLocatorSearch = JSON.stringify(locatorSearch);
440
539
  //info.log += "searching for locator " + JSON.stringify(locatorSearch) + "\n";
441
540
  let locator = null;
442
541
  if (locatorSearch.climb && locatorSearch.climb >= 0) {
@@ -484,7 +583,7 @@ class StableBrowser {
484
583
  }
485
584
  return;
486
585
  }
487
- if (info.locatorLog && count === 0) {
586
+ if (info.locatorLog && count === 0 && logErrors) {
488
587
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "NOT_FOUND");
489
588
  }
490
589
  for (let j = 0; j < count; j++) {
@@ -499,7 +598,7 @@ class StableBrowser {
499
598
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "FOUND");
500
599
  }
501
600
  }
502
- else {
601
+ else if (logErrors) {
503
602
  info.failCause.visible = visible;
504
603
  info.failCause.enabled = enabled;
505
604
  if (!info.printMessages) {
@@ -591,7 +690,7 @@ class StableBrowser {
591
690
  let element = await this._locate_internal(selectors, info, _params, timeout, allowDisabled);
592
691
  if (!element.rerun) {
593
692
  const randomToken = Math.random().toString(36).substring(7);
594
- element.evaluate((el, randomToken) => {
693
+ await element.evaluate((el, randomToken) => {
595
694
  el.setAttribute("data-blinq-id-" + randomToken, "");
596
695
  }, randomToken);
597
696
  // if (element._frame) {
@@ -644,7 +743,7 @@ class StableBrowser {
644
743
  break;
645
744
  }
646
745
  catch (error) {
647
- console.error("frame not found " + frameLocator.css);
746
+ // console.error("frame not found " + frameLocator.css);
648
747
  }
649
748
  }
650
749
  }
@@ -840,7 +939,7 @@ class StableBrowser {
840
939
  }
841
940
  throw new Error("failed to locate first element no elements found, " + info.log);
842
941
  }
843
- async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name) {
942
+ async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name, logErrors = false) {
844
943
  let foundElements = [];
845
944
  const result = {
846
945
  foundElements: foundElements,
@@ -859,7 +958,9 @@ class StableBrowser {
859
958
  await this._collectLocatorInformation(locatorsGroup, i, this.page, foundLocators, _params, info, visibleOnly, allowDisabled, element_name);
860
959
  }
861
960
  catch (e) {
862
- this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
961
+ if (logErrors) {
962
+ this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
963
+ }
863
964
  }
864
965
  }
865
966
  if (foundLocators.length === 1) {
@@ -900,7 +1001,7 @@ class StableBrowser {
900
1001
  });
901
1002
  result.locatorIndex = i;
902
1003
  }
903
- else {
1004
+ else if (logErrors) {
904
1005
  info.failCause.foundMultiple = true;
905
1006
  if (info.locatorLog) {
906
1007
  info.locatorLog.setLocatorSearchStatus(JSON.stringify(locatorsGroup[i]), "FOUND_NOT_UNIQUE");
@@ -1023,7 +1124,9 @@ class StableBrowser {
1023
1124
  try {
1024
1125
  await _preCommand(state, this);
1025
1126
  await performAction("click", state.element, options, this, state, _params);
1026
- await this.waitForPageLoad();
1127
+ if (!this.fastMode) {
1128
+ await this.waitForPageLoad();
1129
+ }
1027
1130
  return state.info;
1028
1131
  }
1029
1132
  catch (e) {
@@ -1086,7 +1189,7 @@ class StableBrowser {
1086
1189
  // if (world && world.screenshot && !world.screenshotPath) {
1087
1190
  // console.log(`Highlighting while running from recorder`);
1088
1191
  await this._highlightElements(state.element);
1089
- await state.element.setChecked(checked);
1192
+ await state.element.setChecked(checked, { timeout: 2000 });
1090
1193
  await new Promise((resolve) => setTimeout(resolve, 1000));
1091
1194
  // await this._unHighlightElements(element);
1092
1195
  // }
@@ -1098,11 +1201,28 @@ class StableBrowser {
1098
1201
  this.logger.info("element did not change its state, ignoring...");
1099
1202
  }
1100
1203
  else {
1204
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1101
1205
  //await this.closeUnexpectedPopups();
1102
1206
  state.info.log += "setCheck failed, will try again" + "\n";
1103
- state.element = await this._locate(selectors, state.info, _params);
1104
- await state.element.setChecked(checked, { timeout: 5000, force: true });
1105
- await new Promise((resolve) => setTimeout(resolve, 1000));
1207
+ state.element_found = false;
1208
+ try {
1209
+ state.element = await this._locate(selectors, state.info, _params, 100);
1210
+ state.element_found = true;
1211
+ // check the check state
1212
+ }
1213
+ catch (error) {
1214
+ // element dismissed
1215
+ }
1216
+ if (state.element_found) {
1217
+ const isChecked = await state.element.isChecked();
1218
+ if (isChecked !== checked) {
1219
+ // perform click
1220
+ await state.element.click({ timeout: 2000, force: true });
1221
+ }
1222
+ else {
1223
+ this.logger.info(`Element ${selectors.element_name} is already in the desired state (${checked})`);
1224
+ }
1225
+ }
1106
1226
  }
1107
1227
  }
1108
1228
  await this.waitForPageLoad();
@@ -1398,7 +1518,9 @@ class StableBrowser {
1398
1518
  await new Promise((resolve) => setTimeout(resolve, 500));
1399
1519
  }
1400
1520
  }
1521
+ //if (!this.fastMode) {
1401
1522
  await _screenshot(state, this);
1523
+ //}
1402
1524
  if (enter === true) {
1403
1525
  await new Promise((resolve) => setTimeout(resolve, 2000));
1404
1526
  await this.page.keyboard.press("Enter");
@@ -1458,6 +1580,41 @@ class StableBrowser {
1458
1580
  await _commandFinally(state, this);
1459
1581
  }
1460
1582
  }
1583
+ async setInputFiles(selectors, files, _params = null, options = {}, world = null) {
1584
+ const state = {
1585
+ selectors,
1586
+ _params,
1587
+ files,
1588
+ value: '"' + files.join('", "') + '"',
1589
+ options,
1590
+ world,
1591
+ type: Types.SET_INPUT_FILES,
1592
+ text: `Set input files`,
1593
+ _text: `Set input files on ${selectors.element_name}`,
1594
+ operation: "setInputFiles",
1595
+ log: "***** set input files " + selectors.element_name + " *****\n",
1596
+ };
1597
+ const uploadsFolder = this.configuration.uploadsFolder ?? "data/uploads";
1598
+ try {
1599
+ await _preCommand(state, this);
1600
+ for (let i = 0; i < files.length; i++) {
1601
+ const file = files[i];
1602
+ const filePath = path.join(uploadsFolder, file);
1603
+ if (!fs.existsSync(filePath)) {
1604
+ throw new Error(`File not found: ${filePath}`);
1605
+ }
1606
+ state.files[i] = filePath;
1607
+ }
1608
+ await state.element.setInputFiles(files);
1609
+ return state.info;
1610
+ }
1611
+ catch (e) {
1612
+ await _commandError(state, e, this);
1613
+ }
1614
+ finally {
1615
+ await _commandFinally(state, this);
1616
+ }
1617
+ }
1461
1618
  async getText(selectors, _params = null, options = {}, info = {}, world = null) {
1462
1619
  return await this._getText(selectors, 0, _params, options, info, world);
1463
1620
  }
@@ -1651,6 +1808,83 @@ class StableBrowser {
1651
1808
  await _commandFinally(state, this);
1652
1809
  }
1653
1810
  }
1811
+ async snapshotValidation(frameSelectors, referanceSnapshot, _params = null, options = {}, world = null) {
1812
+ const timeout = this._getFindElementTimeout(options);
1813
+ const startTime = Date.now();
1814
+ const state = {
1815
+ _params,
1816
+ value: referanceSnapshot,
1817
+ options,
1818
+ world,
1819
+ locate: false,
1820
+ scroll: false,
1821
+ screenshot: true,
1822
+ highlight: false,
1823
+ type: Types.SNAPSHOT_VALIDATION,
1824
+ text: `verify snapshot: ${referanceSnapshot}`,
1825
+ operation: "snapshotValidation",
1826
+ log: "***** verify snapshot *****\n",
1827
+ };
1828
+ if (!referanceSnapshot) {
1829
+ throw new Error("referanceSnapshot is null");
1830
+ }
1831
+ let text = null;
1832
+ if (fs.existsSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yml"))) {
1833
+ text = fs.readFileSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yml"), "utf8");
1834
+ }
1835
+ else if (fs.existsSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yaml"))) {
1836
+ text = fs.readFileSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yaml"), "utf8");
1837
+ }
1838
+ else if (referanceSnapshot.startsWith("yaml:")) {
1839
+ text = referanceSnapshot.substring(5);
1840
+ }
1841
+ else {
1842
+ throw new Error("referenceSnapshot file not found: " + referanceSnapshot);
1843
+ }
1844
+ state.text = text;
1845
+ const newValue = await this._replaceWithLocalData(text, world);
1846
+ await _preCommand(state, this);
1847
+ let foundObj = null;
1848
+ try {
1849
+ let matchResult = null;
1850
+ while (Date.now() - startTime < timeout) {
1851
+ try {
1852
+ let scope = null;
1853
+ if (!frameSelectors) {
1854
+ scope = this.page;
1855
+ }
1856
+ else {
1857
+ scope = await this._findFrameScope(frameSelectors, timeout, state.info);
1858
+ }
1859
+ const snapshot = await scope.locator("body").ariaSnapshot({ timeout });
1860
+ matchResult = snapshotValidation(snapshot, newValue, referanceSnapshot);
1861
+ if (matchResult.errorLine !== -1) {
1862
+ throw new Error("Snapshot validation failed at line " + matchResult.errorLineText);
1863
+ }
1864
+ // highlight and screenshot
1865
+ try {
1866
+ await await highlightSnapshot(newValue, scope);
1867
+ await _screenshot(state, this);
1868
+ }
1869
+ catch (e) { }
1870
+ return state.info;
1871
+ }
1872
+ catch (e) {
1873
+ // Log error but continue retrying until timeout is reached
1874
+ //this.logger.warn("Retrying snapshot validation due to: " + e.message);
1875
+ }
1876
+ await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait 1 second before retrying
1877
+ }
1878
+ throw new Error("No snapshot match " + matchResult?.errorLineText);
1879
+ }
1880
+ catch (e) {
1881
+ await _commandError(state, e, this);
1882
+ throw e;
1883
+ }
1884
+ finally {
1885
+ await _commandFinally(state, this);
1886
+ }
1887
+ }
1654
1888
  async waitForUserInput(message, world = null) {
1655
1889
  if (!message) {
1656
1890
  message = "# Wait for user input. Press any key to continue";
@@ -1791,12 +2025,7 @@ class StableBrowser {
1791
2025
  }
1792
2026
  }
1793
2027
  getTestData(world = null) {
1794
- const dataFile = _getDataFile(world, this.context, this);
1795
- let data = {};
1796
- if (fs.existsSync(dataFile)) {
1797
- data = JSON.parse(fs.readFileSync(dataFile, "utf8"));
1798
- }
1799
- return data;
2028
+ return _getTestData(world, this.context, this);
1800
2029
  }
1801
2030
  async _screenShot(options = {}, world = null, info = null) {
1802
2031
  // collect url/path/title
@@ -1985,6 +2214,95 @@ class StableBrowser {
1985
2214
  state.value = await state.element.getAttribute(attribute);
1986
2215
  break;
1987
2216
  }
2217
+ if (options !== null) {
2218
+ if (options.regex && options.regex !== "") {
2219
+ // Construct a regex pattern from the provided string
2220
+ const regex = options.regex.slice(1, -1);
2221
+ const regexPattern = new RegExp(regex, "g");
2222
+ const matches = state.value.match(regexPattern);
2223
+ if (matches) {
2224
+ let newValue = "";
2225
+ for (const match of matches) {
2226
+ newValue += match;
2227
+ }
2228
+ state.value = newValue;
2229
+ }
2230
+ }
2231
+ if (options.trimSpaces && options.trimSpaces === true) {
2232
+ state.value = state.value.trim();
2233
+ }
2234
+ }
2235
+ state.info.value = state.value;
2236
+ this.setTestData({ [variable]: state.value }, world);
2237
+ this.logger.info("set test data: " + variable + "=" + state.value);
2238
+ // await new Promise((resolve) => setTimeout(resolve, 500));
2239
+ return state.info;
2240
+ }
2241
+ catch (e) {
2242
+ await _commandError(state, e, this);
2243
+ }
2244
+ finally {
2245
+ await _commandFinally(state, this);
2246
+ }
2247
+ }
2248
+ async extractProperty(selectors, property, variable, _params = null, options = {}, world = null) {
2249
+ const state = {
2250
+ selectors,
2251
+ _params,
2252
+ property,
2253
+ variable,
2254
+ options,
2255
+ world,
2256
+ type: Types.EXTRACT_PROPERTY,
2257
+ text: `Extract property from element`,
2258
+ _text: `Extract property ${property} from ${selectors.element_name}`,
2259
+ operation: "extractProperty",
2260
+ log: "***** extract property " + property + " from " + selectors.element_name + " *****\n",
2261
+ allowDisabled: true,
2262
+ };
2263
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2264
+ try {
2265
+ await _preCommand(state, this);
2266
+ switch (property) {
2267
+ case "inner_text":
2268
+ state.value = await state.element.innerText();
2269
+ break;
2270
+ case "href":
2271
+ state.value = await state.element.getAttribute("href");
2272
+ break;
2273
+ case "value":
2274
+ state.value = await state.element.inputValue();
2275
+ break;
2276
+ case "text":
2277
+ state.value = await state.element.textContent();
2278
+ break;
2279
+ default:
2280
+ if (property.startsWith("dataset.")) {
2281
+ const dataAttribute = property.substring(8);
2282
+ state.value = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2283
+ }
2284
+ else {
2285
+ state.value = String(await state.element.evaluate((element, prop) => element[prop], property));
2286
+ }
2287
+ }
2288
+ if (options !== null) {
2289
+ if (options.regex && options.regex !== "") {
2290
+ // Construct a regex pattern from the provided string
2291
+ const regex = options.regex.slice(1, -1);
2292
+ const regexPattern = new RegExp(regex, "g");
2293
+ const matches = state.value.match(regexPattern);
2294
+ if (matches) {
2295
+ let newValue = "";
2296
+ for (const match of matches) {
2297
+ newValue += match;
2298
+ }
2299
+ state.value = newValue;
2300
+ }
2301
+ }
2302
+ if (options.trimSpaces && options.trimSpaces === true) {
2303
+ state.value = state.value.trim();
2304
+ }
2305
+ }
1988
2306
  state.info.value = state.value;
1989
2307
  this.setTestData({ [variable]: state.value }, world);
1990
2308
  this.logger.info("set test data: " + variable + "=" + state.value);
@@ -2050,17 +2368,42 @@ class StableBrowser {
2050
2368
  let regex;
2051
2369
  if (expectedValue.startsWith("/") && expectedValue.endsWith("/")) {
2052
2370
  const patternBody = expectedValue.slice(1, -1);
2053
- regex = new RegExp(patternBody, "g");
2371
+ const processedPattern = patternBody.replace(/\n/g, ".*");
2372
+ regex = new RegExp(processedPattern, "gs");
2373
+ state.info.regex = true;
2054
2374
  }
2055
2375
  else {
2056
2376
  const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2057
2377
  regex = new RegExp(escapedPattern, "g");
2058
2378
  }
2059
- if (!val.match(regex)) {
2060
- let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2061
- state.info.failCause.assertionFailed = true;
2062
- state.info.failCause.lastError = errorMessage;
2063
- throw new Error(errorMessage);
2379
+ if (attribute === "innerText") {
2380
+ if (state.info.regex) {
2381
+ if (!regex.test(val)) {
2382
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2383
+ state.info.failCause.assertionFailed = true;
2384
+ state.info.failCause.lastError = errorMessage;
2385
+ throw new Error(errorMessage);
2386
+ }
2387
+ }
2388
+ else {
2389
+ const valLines = val.split("\n");
2390
+ const expectedLines = expectedValue.split("\n");
2391
+ const isPart = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine === expectedLine));
2392
+ if (!isPart) {
2393
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2394
+ state.info.failCause.assertionFailed = true;
2395
+ state.info.failCause.lastError = errorMessage;
2396
+ throw new Error(errorMessage);
2397
+ }
2398
+ }
2399
+ }
2400
+ else {
2401
+ if (!val.match(regex)) {
2402
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2403
+ state.info.failCause.assertionFailed = true;
2404
+ state.info.failCause.lastError = errorMessage;
2405
+ throw new Error(errorMessage);
2406
+ }
2064
2407
  }
2065
2408
  return state.info;
2066
2409
  }
@@ -2071,61 +2414,308 @@ class StableBrowser {
2071
2414
  await _commandFinally(state, this);
2072
2415
  }
2073
2416
  }
2074
- async extractEmailData(emailAddress, options, world) {
2075
- if (!emailAddress) {
2076
- throw new Error("email address is null");
2077
- }
2078
- // check if address contain @
2079
- if (emailAddress.indexOf("@") === -1) {
2080
- emailAddress = emailAddress + "@blinq-mail.io";
2081
- }
2082
- else {
2083
- if (!emailAddress.toLowerCase().endsWith("@blinq-mail.io")) {
2084
- throw new Error("email address should end with @blinq-mail.io");
2085
- }
2086
- }
2087
- const startTime = Date.now();
2088
- let timeout = 60000;
2089
- if (options && options.timeout) {
2090
- timeout = options.timeout;
2091
- }
2092
- const serviceUrl = _getServerUrl() + "/api/mail/createLinkOrCodeFromEmail";
2093
- const request = {
2094
- method: "POST",
2095
- url: serviceUrl,
2096
- headers: {
2097
- "Content-Type": "application/json",
2098
- Authorization: `Bearer ${process.env.TOKEN}`,
2099
- },
2100
- data: JSON.stringify({
2101
- email: emailAddress,
2102
- }),
2417
+ async verifyProperty(selectors, property, value, _params = null, options = {}, world = null) {
2418
+ const state = {
2419
+ selectors,
2420
+ _params,
2421
+ property,
2422
+ value,
2423
+ options,
2424
+ world,
2425
+ type: Types.VERIFY_PROPERTY,
2426
+ highlight: true,
2427
+ screenshot: true,
2428
+ text: `Verify element property`,
2429
+ _text: `Verify property ${property} from ${selectors.element_name} is ${value}`,
2430
+ operation: "verifyProperty",
2431
+ log: "***** verify property " + property + " from " + selectors.element_name + " *****\n",
2432
+ allowDisabled: true,
2103
2433
  };
2104
- let errorCount = 0;
2105
- while (true) {
2106
- try {
2107
- let result = await this.context.api.request(request);
2108
- // the response body expected to be the following:
2109
- // {
2110
- // "status": true,
2111
- // "content": {
2112
- // "url": "",
2113
- // "code": "112112",
2114
- // "name": "generate_link_or_code"
2115
- // }
2116
- //}
2117
- if ((result && result.data, result.data.status === true)) {
2118
- let codeOrUrlFound = false;
2119
- let emailCode = null;
2120
- let emailUrl = null;
2121
- // check if a code is returned
2122
- if (result.data.content && result.data.content.code) {
2123
- let code = result.data.content.code;
2124
- this.setTestData({ emailCode: code }, world);
2125
- this.logger.info("set test data: emailCode = " + code);
2126
- emailCode = code;
2127
- codeOrUrlFound = true;
2128
- }
2434
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2435
+ let val;
2436
+ let expectedValue;
2437
+ try {
2438
+ await _preCommand(state, this);
2439
+ expectedValue = await replaceWithLocalTestData(state.value, world);
2440
+ state.info.expectedValue = expectedValue;
2441
+ switch (property) {
2442
+ case "innerText":
2443
+ val = String(await state.element.innerText());
2444
+ break;
2445
+ case "text":
2446
+ val = String(await state.element.textContent());
2447
+ break;
2448
+ case "value":
2449
+ val = String(await state.element.inputValue());
2450
+ break;
2451
+ case "checked":
2452
+ val = String(await state.element.isChecked());
2453
+ break;
2454
+ case "disabled":
2455
+ val = String(await state.element.isDisabled());
2456
+ break;
2457
+ case "readOnly":
2458
+ const isEditable = await state.element.isEditable();
2459
+ val = String(!isEditable);
2460
+ break;
2461
+ case "innerHTML":
2462
+ val = String(await state.element.innerHTML());
2463
+ break;
2464
+ case "outerHTML":
2465
+ val = String(await state.element.evaluate((element) => element.outerHTML));
2466
+ break;
2467
+ default:
2468
+ if (property.startsWith("dataset.")) {
2469
+ const dataAttribute = property.substring(8);
2470
+ val = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2471
+ }
2472
+ else {
2473
+ val = String(await state.element.evaluate((element, prop) => element[prop], property));
2474
+ }
2475
+ }
2476
+ // Helper function to remove all style="" attributes
2477
+ const removeStyleAttributes = (htmlString) => {
2478
+ return htmlString.replace(/\s*style\s*=\s*"[^"]*"/gi, "");
2479
+ };
2480
+ // Remove style attributes for innerHTML and outerHTML properties
2481
+ if (property === "innerHTML" || property === "outerHTML") {
2482
+ val = removeStyleAttributes(val);
2483
+ expectedValue = removeStyleAttributes(expectedValue);
2484
+ }
2485
+ state.info.value = val;
2486
+ let regex;
2487
+ if (expectedValue.startsWith("/") && expectedValue.endsWith("/")) {
2488
+ const patternBody = expectedValue.slice(1, -1);
2489
+ const processedPattern = patternBody.replace(/\n/g, ".*");
2490
+ regex = new RegExp(processedPattern, "gs");
2491
+ state.info.regex = true;
2492
+ }
2493
+ else {
2494
+ const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2495
+ regex = new RegExp(escapedPattern, "g");
2496
+ }
2497
+ if (property === "innerText") {
2498
+ if (state.info.regex) {
2499
+ if (!regex.test(val)) {
2500
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2501
+ state.info.failCause.assertionFailed = true;
2502
+ state.info.failCause.lastError = errorMessage;
2503
+ throw new Error(errorMessage);
2504
+ }
2505
+ }
2506
+ else {
2507
+ // Fix: Replace escaped newlines with actual newlines before splitting
2508
+ const normalizedExpectedValue = expectedValue.replace(/\\n/g, "\n");
2509
+ const valLines = val.split("\n");
2510
+ const expectedLines = normalizedExpectedValue.split("\n");
2511
+ // Check if all expected lines are present in the actual lines
2512
+ const isPart = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine.trim() === expectedLine.trim()));
2513
+ if (!isPart) {
2514
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2515
+ state.info.failCause.assertionFailed = true;
2516
+ state.info.failCause.lastError = errorMessage;
2517
+ throw new Error(errorMessage);
2518
+ }
2519
+ }
2520
+ }
2521
+ else {
2522
+ if (!val.match(regex)) {
2523
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2524
+ state.info.failCause.assertionFailed = true;
2525
+ state.info.failCause.lastError = errorMessage;
2526
+ throw new Error(errorMessage);
2527
+ }
2528
+ }
2529
+ return state.info;
2530
+ }
2531
+ catch (e) {
2532
+ await _commandError(state, e, this);
2533
+ }
2534
+ finally {
2535
+ await _commandFinally(state, this);
2536
+ }
2537
+ }
2538
+ async conditionalWait(selectors, condition, timeout = 1000, _params = null, options = {}, world = null) {
2539
+ // Convert timeout from seconds to milliseconds
2540
+ const timeoutMs = timeout * 1000;
2541
+ const state = {
2542
+ selectors,
2543
+ _params,
2544
+ condition,
2545
+ timeout: timeoutMs, // Store as milliseconds for internal use
2546
+ options,
2547
+ world,
2548
+ type: Types.CONDITIONAL_WAIT,
2549
+ highlight: true,
2550
+ screenshot: true,
2551
+ text: `Conditional wait for element`,
2552
+ _text: `Wait for ${selectors.element_name} to be ${condition} (timeout: ${timeout}s)`, // Display original seconds
2553
+ operation: "conditionalWait",
2554
+ log: `***** conditional wait for ${condition} on ${selectors.element_name} *****\n`,
2555
+ allowDisabled: true,
2556
+ info: {},
2557
+ };
2558
+ // Initialize startTime outside try block to ensure it's always accessible
2559
+ const startTime = Date.now();
2560
+ let conditionMet = false;
2561
+ let currentValue = null;
2562
+ let lastError = null;
2563
+ // Main retry loop - continues until timeout or condition is met
2564
+ while (Date.now() - startTime < timeoutMs) {
2565
+ const elapsedTime = Date.now() - startTime;
2566
+ const remainingTime = timeoutMs - elapsedTime;
2567
+ try {
2568
+ // Try to execute _preCommand (element location)
2569
+ await _preCommand(state, this);
2570
+ // If _preCommand succeeds, start condition checking
2571
+ const checkCondition = async () => {
2572
+ try {
2573
+ switch (condition.toLowerCase()) {
2574
+ case "checked":
2575
+ currentValue = await state.element.isChecked();
2576
+ return currentValue === true;
2577
+ case "unchecked":
2578
+ currentValue = await state.element.isChecked();
2579
+ return currentValue === false;
2580
+ case "visible":
2581
+ currentValue = await state.element.isVisible();
2582
+ return currentValue === true;
2583
+ case "hidden":
2584
+ currentValue = await state.element.isVisible();
2585
+ return currentValue === false;
2586
+ case "enabled":
2587
+ currentValue = await state.element.isDisabled();
2588
+ return currentValue === false;
2589
+ case "disabled":
2590
+ currentValue = await state.element.isDisabled();
2591
+ return currentValue === true;
2592
+ case "editable":
2593
+ // currentValue = await String(await state.element.evaluate((element, prop) => element[prop], "isContentEditable"));
2594
+ currentValue = await state.element.isContentEditable();
2595
+ return currentValue === true;
2596
+ default:
2597
+ state.info.message = `Unsupported condition: '${condition}'. Supported conditions are: checked, unchecked, visible, hidden, enabled, disabled, editable.`;
2598
+ state.info.success = false;
2599
+ return false;
2600
+ }
2601
+ }
2602
+ catch (error) {
2603
+ // Don't throw here, just return false to continue retrying
2604
+ return false;
2605
+ }
2606
+ };
2607
+ // Inner loop for condition checking (once element is located)
2608
+ while (Date.now() - startTime < timeoutMs) {
2609
+ const currentElapsedTime = Date.now() - startTime;
2610
+ conditionMet = await checkCondition();
2611
+ if (conditionMet) {
2612
+ break;
2613
+ }
2614
+ // Check if we still have time for another attempt
2615
+ if (Date.now() - startTime + 50 < timeoutMs) {
2616
+ await new Promise((res) => setTimeout(res, 50));
2617
+ }
2618
+ else {
2619
+ break;
2620
+ }
2621
+ }
2622
+ // If we got here and condition is met, break out of main loop
2623
+ if (conditionMet) {
2624
+ break;
2625
+ }
2626
+ // If condition not met but no exception, we've timed out
2627
+ break;
2628
+ }
2629
+ catch (e) {
2630
+ lastError = e;
2631
+ const currentElapsedTime = Date.now() - startTime;
2632
+ const timeLeft = timeoutMs - currentElapsedTime;
2633
+ // Check if we have enough time left to retry
2634
+ if (timeLeft > 100) {
2635
+ await new Promise((resolve) => setTimeout(resolve, 50));
2636
+ }
2637
+ else {
2638
+ break;
2639
+ }
2640
+ }
2641
+ }
2642
+ const actualWaitTime = Date.now() - startTime;
2643
+ state.info = {
2644
+ success: conditionMet,
2645
+ conditionMet,
2646
+ actualWaitTime,
2647
+ currentValue,
2648
+ lastError: lastError?.message || null,
2649
+ message: conditionMet
2650
+ ? `Condition '${condition}' met after ${(actualWaitTime / 1000).toFixed(2)}s`
2651
+ : `Condition '${condition}' not met within ${timeout}s timeout`,
2652
+ };
2653
+ if (lastError) {
2654
+ state.log += `Last error: ${lastError.message}\n`;
2655
+ }
2656
+ try {
2657
+ await _commandFinally(state, this);
2658
+ }
2659
+ catch (finallyError) {
2660
+ state.log += `Error in _commandFinally: ${finallyError.message}\n`;
2661
+ }
2662
+ return state.info;
2663
+ }
2664
+ async extractEmailData(emailAddress, options, world) {
2665
+ if (!emailAddress) {
2666
+ throw new Error("email address is null");
2667
+ }
2668
+ // check if address contain @
2669
+ if (emailAddress.indexOf("@") === -1) {
2670
+ emailAddress = emailAddress + "@blinq-mail.io";
2671
+ }
2672
+ else {
2673
+ if (!emailAddress.toLowerCase().endsWith("@blinq-mail.io")) {
2674
+ throw new Error("email address should end with @blinq-mail.io");
2675
+ }
2676
+ }
2677
+ const startTime = Date.now();
2678
+ let timeout = 60000;
2679
+ if (options && options.timeout) {
2680
+ timeout = options.timeout;
2681
+ }
2682
+ const serviceUrl = _getServerUrl() + "/api/mail/createLinkOrCodeFromEmail";
2683
+ const request = {
2684
+ method: "POST",
2685
+ url: serviceUrl,
2686
+ headers: {
2687
+ "Content-Type": "application/json",
2688
+ Authorization: `Bearer ${process.env.TOKEN}`,
2689
+ },
2690
+ data: JSON.stringify({
2691
+ email: emailAddress,
2692
+ }),
2693
+ };
2694
+ let errorCount = 0;
2695
+ while (true) {
2696
+ try {
2697
+ let result = await this.context.api.request(request);
2698
+ // the response body expected to be the following:
2699
+ // {
2700
+ // "status": true,
2701
+ // "content": {
2702
+ // "url": "",
2703
+ // "code": "112112",
2704
+ // "name": "generate_link_or_code"
2705
+ // }
2706
+ //}
2707
+ if ((result && result.data, result.data.status === true)) {
2708
+ let codeOrUrlFound = false;
2709
+ let emailCode = null;
2710
+ let emailUrl = null;
2711
+ // check if a code is returned
2712
+ if (result.data.content && result.data.content.code) {
2713
+ let code = result.data.content.code;
2714
+ this.setTestData({ emailCode: code }, world);
2715
+ this.logger.info("set test data: emailCode = " + code);
2716
+ emailCode = code;
2717
+ codeOrUrlFound = true;
2718
+ }
2129
2719
  // check if a url is returned
2130
2720
  if (result.data.content && result.data.content.url) {
2131
2721
  let url = result.data.content.url;
@@ -2228,56 +2818,49 @@ class StableBrowser {
2228
2818
  console.debug(error);
2229
2819
  }
2230
2820
  }
2231
- // async _unhighlightElements(scope, css) {
2232
- // try {
2233
- // if (!scope) {
2234
- // return;
2235
- // }
2236
- // if (!css) {
2237
- // scope
2238
- // .evaluate((node) => {
2239
- // if (node && node.style) {
2240
- // if (!node.__previousOutline) {
2241
- // node.style.outline = "";
2242
- // } else {
2243
- // node.style.outline = node.__previousOutline;
2244
- // }
2245
- // }
2246
- // })
2247
- // .then(() => {})
2248
- // .catch((e) => {
2249
- // // console.log(`Error while unhighlighting node ${JSON.stringify(scope)}: ${e}`);
2250
- // });
2251
- // } else {
2252
- // scope
2253
- // .evaluate(([css]) => {
2254
- // if (!css) {
2255
- // return;
2256
- // }
2257
- // let elements = Array.from(document.querySelectorAll(css));
2258
- // for (i = 0; i < elements.length; i++) {
2259
- // let element = elements[i];
2260
- // if (!element.style) {
2261
- // return;
2262
- // }
2263
- // if (!element.__previousOutline) {
2264
- // element.style.outline = "";
2265
- // } else {
2266
- // element.style.outline = element.__previousOutline;
2267
- // }
2268
- // }
2269
- // })
2270
- // .then(() => {})
2271
- // .catch((e) => {
2272
- // // console.error(`Error while unhighlighting element in css: ${e}`);
2273
- // });
2274
- // }
2275
- // } catch (error) {
2276
- // // console.debug(error);
2277
- // }
2278
- // }
2821
+ _matcher(text) {
2822
+ if (!text) {
2823
+ return { matcher: "contains", queryText: "" };
2824
+ }
2825
+ if (text.length < 2) {
2826
+ return { matcher: "contains", queryText: text };
2827
+ }
2828
+ const split = text.split(":");
2829
+ const matcher = split[0].toLowerCase();
2830
+ const queryText = split.slice(1).join(":").trim();
2831
+ return { matcher, queryText };
2832
+ }
2833
+ _getDomain(url) {
2834
+ if (url.length === 0 || (!url.startsWith("http://") && !url.startsWith("https://"))) {
2835
+ return "";
2836
+ }
2837
+ let hostnameFragments = url.split("/")[2].split(".");
2838
+ if (hostnameFragments.some((fragment) => fragment.includes(":"))) {
2839
+ return hostnameFragments.join("-").split(":").join("-");
2840
+ }
2841
+ let n = hostnameFragments.length;
2842
+ let fragments = [...hostnameFragments];
2843
+ while (n > 0 && hostnameFragments[n - 1].length <= 3) {
2844
+ hostnameFragments.pop();
2845
+ n = hostnameFragments.length;
2846
+ }
2847
+ if (n == 0) {
2848
+ if (fragments[0] === "www")
2849
+ fragments = fragments.slice(1);
2850
+ return fragments.length > 1 ? fragments.slice(0, fragments.length - 1).join("-") : fragments.join("-");
2851
+ }
2852
+ if (hostnameFragments[0] === "www")
2853
+ hostnameFragments = hostnameFragments.slice(1);
2854
+ return hostnameFragments.join(".");
2855
+ }
2856
+ /**
2857
+ * Verify the page path matches the given path.
2858
+ * @param {string} pathPart - The path to verify.
2859
+ * @param {object} options - Options for verification.
2860
+ * @param {object} world - The world context.
2861
+ * @returns {Promise<object>} - The state info after verification.
2862
+ */
2279
2863
  async verifyPagePath(pathPart, options = {}, world = null) {
2280
- const startTime = Date.now();
2281
2864
  let error = null;
2282
2865
  let screenshotId = null;
2283
2866
  let screenshotPath = null;
@@ -2291,113 +2874,212 @@ class StableBrowser {
2291
2874
  pathPart = newValue;
2292
2875
  }
2293
2876
  info.pathPart = pathPart;
2877
+ const { matcher, queryText } = this._matcher(pathPart);
2878
+ const state = {
2879
+ text_search: queryText,
2880
+ options,
2881
+ world,
2882
+ locate: false,
2883
+ scroll: false,
2884
+ highlight: false,
2885
+ type: Types.VERIFY_PAGE_PATH,
2886
+ text: `Verify the page url is ${queryText}`,
2887
+ _text: `Verify the page url is ${queryText}`,
2888
+ operation: "verifyPagePath",
2889
+ log: "***** verify page url is " + queryText + " *****\n",
2890
+ };
2294
2891
  try {
2892
+ await _preCommand(state, this);
2893
+ state.info.text = queryText;
2295
2894
  for (let i = 0; i < 30; i++) {
2296
2895
  const url = await this.page.url();
2297
- if (!url.includes(pathPart)) {
2298
- if (i === 29) {
2299
- throw new Error(`url ${url} doesn't contain ${pathPart}`);
2300
- }
2301
- await new Promise((resolve) => setTimeout(resolve, 1000));
2302
- continue;
2896
+ switch (matcher) {
2897
+ case "exact":
2898
+ if (url !== queryText) {
2899
+ if (i === 29) {
2900
+ throw new Error(`Page URL ${url} is not equal to ${queryText}`);
2901
+ }
2902
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2903
+ continue;
2904
+ }
2905
+ break;
2906
+ case "contains":
2907
+ if (!url.includes(queryText)) {
2908
+ if (i === 29) {
2909
+ throw new Error(`Page URL ${url} doesn't contain ${queryText}`);
2910
+ }
2911
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2912
+ continue;
2913
+ }
2914
+ break;
2915
+ case "starts-with":
2916
+ {
2917
+ const domain = this._getDomain(url);
2918
+ if (domain.length > 0 && domain !== queryText) {
2919
+ if (i === 29) {
2920
+ throw new Error(`Page URL ${url} doesn't start with ${queryText}`);
2921
+ }
2922
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2923
+ continue;
2924
+ }
2925
+ }
2926
+ break;
2927
+ case "ends-with":
2928
+ {
2929
+ const urlObj = new URL(url);
2930
+ let route = "/";
2931
+ if (urlObj.pathname !== "/") {
2932
+ route = urlObj.pathname.split("/").slice(-1)[0].trim();
2933
+ }
2934
+ else {
2935
+ route = "/";
2936
+ }
2937
+ if (route !== queryText) {
2938
+ if (i === 29) {
2939
+ throw new Error(`Page URL ${url} doesn't end with ${queryText}`);
2940
+ }
2941
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2942
+ continue;
2943
+ }
2944
+ }
2945
+ break;
2946
+ case "regex":
2947
+ const regex = new RegExp(queryText.slice(1, -1), "g");
2948
+ if (!regex.test(url)) {
2949
+ if (i === 29) {
2950
+ throw new Error(`Page URL ${url} doesn't match regex ${queryText}`);
2951
+ }
2952
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2953
+ continue;
2954
+ }
2955
+ break;
2956
+ default:
2957
+ console.log("Unknown matching type, defaulting to contains matching");
2958
+ if (!url.includes(pathPart)) {
2959
+ if (i === 29) {
2960
+ throw new Error(`Page URL ${url} does not contain ${pathPart}`);
2961
+ }
2962
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2963
+ continue;
2964
+ }
2303
2965
  }
2304
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2305
- return info;
2966
+ await _screenshot(state, this);
2967
+ return state.info;
2306
2968
  }
2307
2969
  }
2308
2970
  catch (e) {
2309
- //await this.closeUnexpectedPopups();
2310
- this.logger.error("verify page path failed " + info.log);
2311
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2312
- info.screenshotPath = screenshotPath;
2313
- Object.assign(e, { info: info });
2314
- error = e;
2315
- // throw e;
2316
- await _commandError({ text: "verifyPagePath", operation: "verifyPagePath", pathPart, info }, e, this);
2971
+ state.info.failCause.lastError = e.message;
2972
+ state.info.failCause.assertionFailed = true;
2973
+ await _commandError(state, e, this);
2317
2974
  }
2318
2975
  finally {
2319
- const endTime = Date.now();
2320
- _reportToWorld(world, {
2321
- type: Types.VERIFY_PAGE_PATH,
2322
- text: "Verify page path",
2323
- _text: "Verify the page path contains " + pathPart,
2324
- screenshotId,
2325
- result: error
2326
- ? {
2327
- status: "FAILED",
2328
- startTime,
2329
- endTime,
2330
- message: error?.message,
2331
- }
2332
- : {
2333
- status: "PASSED",
2334
- startTime,
2335
- endTime,
2336
- },
2337
- info: info,
2338
- });
2976
+ await _commandFinally(state, this);
2339
2977
  }
2340
2978
  }
2979
+ /**
2980
+ * Verify the page title matches the given title.
2981
+ * @param {string} title - The title to verify.
2982
+ * @param {object} options - Options for verification.
2983
+ * @param {object} world - The world context.
2984
+ * @returns {Promise<object>} - The state info after verification.
2985
+ */
2341
2986
  async verifyPageTitle(title, options = {}, world = null) {
2342
- const startTime = Date.now();
2343
2987
  let error = null;
2344
2988
  let screenshotId = null;
2345
2989
  let screenshotPath = null;
2346
2990
  await new Promise((resolve) => setTimeout(resolve, 2000));
2347
- const info = {};
2348
- info.log = "***** verify page title " + title + " *****\n";
2349
- info.operation = "verifyPageTitle";
2350
2991
  const newValue = await this._replaceWithLocalData(title, world);
2351
2992
  if (newValue !== title) {
2352
2993
  this.logger.info(title + "=" + newValue);
2353
2994
  title = newValue;
2354
2995
  }
2355
- info.title = title;
2996
+ const { matcher, queryText } = this._matcher(title);
2997
+ const state = {
2998
+ text_search: queryText,
2999
+ options,
3000
+ world,
3001
+ locate: false,
3002
+ scroll: false,
3003
+ highlight: false,
3004
+ type: Types.VERIFY_PAGE_TITLE,
3005
+ text: `Verify the page title is ${queryText}`,
3006
+ _text: `Verify the page title is ${queryText}`,
3007
+ operation: "verifyPageTitle",
3008
+ log: "***** verify page title is " + queryText + " *****\n",
3009
+ };
2356
3010
  try {
3011
+ await _preCommand(state, this);
3012
+ state.info.text = queryText;
2357
3013
  for (let i = 0; i < 30; i++) {
2358
3014
  const foundTitle = await this.page.title();
2359
- if (!foundTitle.includes(title)) {
2360
- if (i === 29) {
2361
- throw new Error(`url ${foundTitle} doesn't contain ${title}`);
2362
- }
2363
- await new Promise((resolve) => setTimeout(resolve, 1000));
2364
- continue;
3015
+ switch (matcher) {
3016
+ case "exact":
3017
+ if (foundTitle !== queryText) {
3018
+ if (i === 29) {
3019
+ throw new Error(`Page Title ${foundTitle} is not equal to ${queryText}`);
3020
+ }
3021
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3022
+ continue;
3023
+ }
3024
+ break;
3025
+ case "contains":
3026
+ if (!foundTitle.includes(queryText)) {
3027
+ if (i === 29) {
3028
+ throw new Error(`Page Title ${foundTitle} doesn't contain ${queryText}`);
3029
+ }
3030
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3031
+ continue;
3032
+ }
3033
+ break;
3034
+ case "starts-with":
3035
+ if (!foundTitle.startsWith(queryText)) {
3036
+ if (i === 29) {
3037
+ throw new Error(`Page title ${foundTitle} doesn't start with ${queryText}`);
3038
+ }
3039
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3040
+ continue;
3041
+ }
3042
+ break;
3043
+ case "ends-with":
3044
+ if (!foundTitle.endsWith(queryText)) {
3045
+ if (i === 29) {
3046
+ throw new Error(`Page Title ${foundTitle} doesn't end with ${queryText}`);
3047
+ }
3048
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3049
+ continue;
3050
+ }
3051
+ break;
3052
+ case "regex":
3053
+ const regex = new RegExp(queryText.slice(1, -1), "g");
3054
+ if (!regex.test(foundTitle)) {
3055
+ if (i === 29) {
3056
+ throw new Error(`Page Title ${foundTitle} doesn't match regex ${queryText}`);
3057
+ }
3058
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3059
+ continue;
3060
+ }
3061
+ break;
3062
+ default:
3063
+ console.log("Unknown matching type, defaulting to contains matching");
3064
+ if (!foundTitle.includes(title)) {
3065
+ if (i === 29) {
3066
+ throw new Error(`Page Title ${foundTitle} does not contain ${title}`);
3067
+ }
3068
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3069
+ continue;
3070
+ }
2365
3071
  }
2366
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2367
- return info;
3072
+ await _screenshot(state, this);
3073
+ return state.info;
2368
3074
  }
2369
3075
  }
2370
3076
  catch (e) {
2371
- //await this.closeUnexpectedPopups();
2372
- this.logger.error("verify page title failed " + info.log);
2373
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2374
- info.screenshotPath = screenshotPath;
2375
- Object.assign(e, { info: info });
2376
- error = e;
2377
- // throw e;
2378
- await _commandError({ text: "verifyPageTitle", operation: "verifyPageTitle", title, info, throwError: true }, e, this);
3077
+ state.info.failCause.lastError = e.message;
3078
+ state.info.failCause.assertionFailed = true;
3079
+ await _commandError(state, e, this);
2379
3080
  }
2380
3081
  finally {
2381
- const endTime = Date.now();
2382
- _reportToWorld(world, {
2383
- type: Types.VERIFY_PAGE_PATH,
2384
- text: "Verify page title",
2385
- _text: "Verify the page title contains " + title,
2386
- screenshotId,
2387
- result: error
2388
- ? {
2389
- status: "FAILED",
2390
- startTime,
2391
- endTime,
2392
- message: error?.message,
2393
- }
2394
- : {
2395
- status: "PASSED",
2396
- startTime,
2397
- endTime,
2398
- },
2399
- info: info,
2400
- });
3082
+ await _commandFinally(state, this);
2401
3083
  }
2402
3084
  }
2403
3085
  async findTextInAllFrames(dateAlternatives, numberAlternatives, text, state, partial = true, ignoreCase = false) {
@@ -2439,7 +3121,7 @@ class StableBrowser {
2439
3121
  scroll: false,
2440
3122
  highlight: false,
2441
3123
  type: Types.VERIFY_PAGE_CONTAINS_TEXT,
2442
- text: `Verify the text '${text}' exists in page`,
3124
+ text: `Verify the text '${maskValue(text)}' exists in page`,
2443
3125
  _text: `Verify the text '${text}' exists in page`,
2444
3126
  operation: "verifyTextExistInPage",
2445
3127
  log: "***** verify text " + text + " exists in page *****\n",
@@ -2481,27 +3163,10 @@ class StableBrowser {
2481
3163
  const frame = resultWithElementsFound[0].frame;
2482
3164
  const dataAttribute = `[data-blinq-id-${resultWithElementsFound[0].randomToken}]`;
2483
3165
  await this._highlightElements(frame, dataAttribute);
2484
- // if (world && world.screenshot && !world.screenshotPath) {
2485
- // console.log(`Highlighting for verify text is found while running from recorder`);
2486
- // this._highlightElements(frame, dataAttribute).then(async () => {
2487
- // await new Promise((resolve) => setTimeout(resolve, 1000));
2488
- // this._unhighlightElements(frame, dataAttribute)
2489
- // .then(async () => {
2490
- // console.log(`Unhighlighted frame dataAttribute successfully`);
2491
- // })
2492
- // .catch(
2493
- // (e) => {}
2494
- // console.error(e)
2495
- // );
2496
- // });
2497
- // }
2498
3166
  const element = await frame.locator(dataAttribute).first();
2499
- // await new Promise((resolve) => setTimeout(resolve, 100));
2500
- // await this._unhighlightElements(frame, dataAttribute);
2501
3167
  if (element) {
2502
3168
  await this.scrollIfNeeded(element, state.info);
2503
3169
  await element.dispatchEvent("bvt_verify_page_contains_text");
2504
- // await _screenshot(state, this, element);
2505
3170
  }
2506
3171
  }
2507
3172
  await _screenshot(state, this);
@@ -2511,7 +3176,6 @@ class StableBrowser {
2511
3176
  console.error(error);
2512
3177
  }
2513
3178
  }
2514
- // await expect(element).toHaveCount(1, { timeout: 10000 });
2515
3179
  }
2516
3180
  catch (e) {
2517
3181
  await _commandError(state, e, this);
@@ -2530,7 +3194,7 @@ class StableBrowser {
2530
3194
  scroll: false,
2531
3195
  highlight: false,
2532
3196
  type: Types.WAIT_FOR_TEXT_TO_DISAPPEAR,
2533
- text: `Verify the text '${text}' does not exist in page`,
3197
+ text: `Verify the text '${maskValue(text)}' does not exist in page`,
2534
3198
  _text: `Verify the text '${text}' does not exist in page`,
2535
3199
  operation: "verifyTextNotExistInPage",
2536
3200
  log: "***** verify text " + text + " does not exist in page *****\n",
@@ -2593,6 +3257,8 @@ class StableBrowser {
2593
3257
  operation: "verify_text_with_relation",
2594
3258
  log: "***** search for " + textAnchor + " climb " + climb + " and verify " + textToVerify + " found *****\n",
2595
3259
  };
3260
+ const cmdStartTime = Date.now();
3261
+ let cmdEndTime = null;
2596
3262
  const timeout = this._getFindElementTimeout(options);
2597
3263
  await new Promise((resolve) => setTimeout(resolve, 2000));
2598
3264
  let newValue = await this._replaceWithLocalData(textAnchor, world);
@@ -2628,6 +3294,17 @@ class StableBrowser {
2628
3294
  await new Promise((resolve) => setTimeout(resolve, 1000));
2629
3295
  continue;
2630
3296
  }
3297
+ else {
3298
+ cmdEndTime = Date.now();
3299
+ if (cmdEndTime - cmdStartTime > 55000) {
3300
+ if (foundAncore) {
3301
+ throw new Error(`Text ${textToVerify} not found in page`);
3302
+ }
3303
+ else {
3304
+ throw new Error(`Text ${textAnchor} not found in page`);
3305
+ }
3306
+ }
3307
+ }
2631
3308
  try {
2632
3309
  for (let i = 0; i < resultWithElementsFound.length; i++) {
2633
3310
  foundAncore = true;
@@ -3027,8 +3704,51 @@ class StableBrowser {
3027
3704
  });
3028
3705
  }
3029
3706
  }
3707
+ /**
3708
+ * Explicit wait/sleep function that pauses execution for a specified duration
3709
+ * @param duration - Duration to sleep in milliseconds (default: 1000ms)
3710
+ * @param options - Optional configuration object
3711
+ * @param world - Optional world context
3712
+ * @returns Promise that resolves after the specified duration
3713
+ */
3714
+ async sleep(duration = 1000, options = {}, world = null) {
3715
+ const state = {
3716
+ duration,
3717
+ options,
3718
+ world,
3719
+ locate: false,
3720
+ scroll: false,
3721
+ screenshot: false,
3722
+ highlight: false,
3723
+ type: Types.SLEEP,
3724
+ text: `Sleep for ${duration} ms`,
3725
+ _text: `Sleep for ${duration} ms`,
3726
+ operation: "sleep",
3727
+ log: `***** Sleep for ${duration} ms *****\n`,
3728
+ };
3729
+ try {
3730
+ await _preCommand(state, this);
3731
+ if (duration < 0) {
3732
+ throw new Error("Sleep duration cannot be negative");
3733
+ }
3734
+ await new Promise((resolve) => setTimeout(resolve, duration));
3735
+ return state.info;
3736
+ }
3737
+ catch (e) {
3738
+ await _commandError(state, e, this);
3739
+ }
3740
+ finally {
3741
+ await _commandFinally(state, this);
3742
+ }
3743
+ }
3030
3744
  async _replaceWithLocalData(value, world, _decrypt = true, totpWait = true) {
3031
- return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
3745
+ try {
3746
+ return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
3747
+ }
3748
+ catch (error) {
3749
+ this.logger.debug(error);
3750
+ throw error;
3751
+ }
3032
3752
  }
3033
3753
  _getLoadTimeout(options) {
3034
3754
  let timeout = 15000;
@@ -3051,6 +3771,7 @@ class StableBrowser {
3051
3771
  }
3052
3772
  async saveStoreState(path = null, world = null) {
3053
3773
  const storageState = await this.page.context().storageState();
3774
+ path = await this._replaceWithLocalData(path, this.world);
3054
3775
  //const testDataFile = _getDataFile(world, this.context, this);
3055
3776
  if (path) {
3056
3777
  // save { storageState: storageState } into the path
@@ -3061,10 +3782,14 @@ class StableBrowser {
3061
3782
  }
3062
3783
  }
3063
3784
  async restoreSaveState(path = null, world = null) {
3785
+ path = await this._replaceWithLocalData(path, this.world);
3064
3786
  await refreshBrowser(this, path, world);
3065
3787
  this.registerEventListeners(this.context);
3066
3788
  registerNetworkEvents(this.world, this, this.context, this.page);
3067
3789
  registerDownloadEvent(this.page, this.world, this.context);
3790
+ if (this.onRestoreSaveState) {
3791
+ this.onRestoreSaveState(path);
3792
+ }
3068
3793
  }
3069
3794
  async waitForPageLoad(options = {}, world = null) {
3070
3795
  let timeout = this._getLoadTimeout(options);
@@ -3099,7 +3824,6 @@ class StableBrowser {
3099
3824
  else if (e.label === "domcontentloaded") {
3100
3825
  console.log("waited for the domcontent loaded timeout");
3101
3826
  }
3102
- console.log(".");
3103
3827
  }
3104
3828
  finally {
3105
3829
  await new Promise((resolve) => setTimeout(resolve, 2000));
@@ -3143,7 +3867,6 @@ class StableBrowser {
3143
3867
  await this.page.close();
3144
3868
  }
3145
3869
  catch (e) {
3146
- console.log(".");
3147
3870
  await _commandError(state, e, this);
3148
3871
  }
3149
3872
  finally {
@@ -3258,7 +3981,6 @@ class StableBrowser {
3258
3981
  await this.page.setViewportSize({ width: width, height: hight });
3259
3982
  }
3260
3983
  catch (e) {
3261
- console.log(".");
3262
3984
  await _commandError({ text: "setViewportSize", operation: "setViewportSize", width, hight, info }, e, this);
3263
3985
  }
3264
3986
  finally {
@@ -3296,7 +4018,6 @@ class StableBrowser {
3296
4018
  await this.page.reload();
3297
4019
  }
3298
4020
  catch (e) {
3299
- console.log(".");
3300
4021
  await _commandError({ text: "reloadPage", operation: "reloadPage", info }, e, this);
3301
4022
  }
3302
4023
  finally {
@@ -3339,7 +4060,44 @@ class StableBrowser {
3339
4060
  console.log("#-#");
3340
4061
  }
3341
4062
  }
4063
+ async beforeScenario(world, scenario) {
4064
+ if (world && world.attach) {
4065
+ world.attach(this.context.reportFolder, { mediaType: "text/plain" });
4066
+ }
4067
+ this.context.loadedRoutes = null;
4068
+ this.beforeScenarioCalled = true;
4069
+ if (scenario && scenario.pickle && scenario.pickle.name) {
4070
+ this.scenarioName = scenario.pickle.name;
4071
+ }
4072
+ if (scenario && scenario.gherkinDocument && scenario.gherkinDocument.feature) {
4073
+ this.featureName = scenario.gherkinDocument.feature.name;
4074
+ }
4075
+ if (this.context) {
4076
+ this.context.examplesRow = extractStepExampleParameters(scenario);
4077
+ }
4078
+ if (this.tags === null && scenario && scenario.pickle && scenario.pickle.tags) {
4079
+ this.tags = scenario.pickle.tags.map((tag) => tag.name);
4080
+ // check if @global_test_data tag is present
4081
+ if (this.tags.includes("@global_test_data")) {
4082
+ this.saveTestDataAsGlobal({}, world);
4083
+ }
4084
+ }
4085
+ // update test data based on feature/scenario
4086
+ let envName = null;
4087
+ if (this.context && this.context.environment) {
4088
+ envName = this.context.environment.name;
4089
+ }
4090
+ if (!process.env.TEMP_RUN) {
4091
+ await getTestData(envName, world, undefined, this.featureName, this.scenarioName, this.context);
4092
+ }
4093
+ await loadBrunoParams(this.context, this.context.environment.name);
4094
+ }
4095
+ async afterScenario(world, scenario) { }
3342
4096
  async beforeStep(world, step) {
4097
+ if (!this.beforeScenarioCalled) {
4098
+ this.beforeScenario(world, step);
4099
+ this.context.loadedRoutes = null;
4100
+ }
3343
4101
  if (this.stepIndex === undefined) {
3344
4102
  this.stepIndex = 0;
3345
4103
  }
@@ -3356,42 +4114,23 @@ class StableBrowser {
3356
4114
  else {
3357
4115
  this.stepName = "step " + this.stepIndex;
3358
4116
  }
3359
- if (step && step.gherkinDocument && step.gherkinDocument.feature && step.gherkinDocument.feature.name) {
3360
- this.featureName = step.gherkinDocument.feature.name;
3361
- }
3362
- if (step && step.pickle && step.pickle.name) {
3363
- this.scenarioName = step.pickle.name;
3364
- }
3365
- if (this.context) {
3366
- this.context.examplesRow = extractStepExampleParameters(step);
3367
- }
3368
4117
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
3369
4118
  if (this.context.browserObject.context) {
3370
4119
  await this.context.browserObject.context.tracing.startChunk({ title: this.stepName });
3371
4120
  }
3372
4121
  }
3373
- if (this.tags === null && step && step.pickle && step.pickle.tags) {
3374
- this.tags = step.pickle.tags.map((tag) => tag.name);
3375
- // check if @global_test_data tag is present
3376
- if (this.tags.includes("@global_test_data")) {
3377
- this.saveTestDataAsGlobal({}, world);
3378
- }
3379
- }
3380
4122
  if (this.initSnapshotTaken === false) {
3381
4123
  this.initSnapshotTaken = true;
3382
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4124
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
3383
4125
  const snapshot = await this.getAriaSnapshot();
3384
4126
  if (snapshot) {
3385
4127
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-before");
3386
4128
  }
3387
4129
  }
3388
4130
  }
3389
- // update test data based on feature/scenario
3390
- let envName = null;
3391
- if (this.context && this.context.environment) {
3392
- envName = this.context.environment.name;
3393
- }
3394
- await await getTestData(envName, world, undefined, this.featureName, this.scenarioName);
4131
+ this.context.routeResults = null;
4132
+ await registerBeforeStepRoutes(this.context, this.stepName);
4133
+ networkBeforeStep(this.stepName);
3395
4134
  }
3396
4135
  async getAriaSnapshot() {
3397
4136
  try {
@@ -3407,18 +4146,74 @@ class StableBrowser {
3407
4146
  const content = [`- path: ${path}`, `- title: ${title}`];
3408
4147
  const timeout = this.configuration.ariaSnapshotTimeout ? this.configuration.ariaSnapshotTimeout : 3000;
3409
4148
  for (let i = 0; i < frames.length; i++) {
3410
- content.push(`- frame: ${i}`);
3411
4149
  const frame = frames[i];
3412
- const snapshot = await frame.locator("body").ariaSnapshot({ timeout });
3413
- content.push(snapshot);
4150
+ try {
4151
+ // Ensure frame is attached and has body
4152
+ const body = frame.locator("body");
4153
+ //await body.waitFor({ timeout: 2000 }); // wait explicitly
4154
+ const snapshot = await body.ariaSnapshot({ timeout });
4155
+ if (!snapshot) {
4156
+ continue;
4157
+ }
4158
+ content.push(`- frame: ${i}`);
4159
+ content.push(snapshot);
4160
+ }
4161
+ catch (innerErr) {
4162
+ console.warn(`Frame ${i} snapshot failed:`, innerErr);
4163
+ content.push(`- frame: ${i} - error: ${innerErr.message}`);
4164
+ }
3414
4165
  }
3415
4166
  return content.join("\n");
3416
4167
  }
3417
4168
  catch (e) {
3418
- console.error(e);
4169
+ console.log("Error in getAriaSnapshot");
4170
+ //console.debug(e);
3419
4171
  }
3420
4172
  return null;
3421
4173
  }
4174
+ /**
4175
+ * Sends command with custom payload to report.
4176
+ * @param commandText - Title of the command to be shown in the report.
4177
+ * @param commandStatus - Status of the command (e.g. "PASSED", "FAILED").
4178
+ * @param content - Content of the command to be shown in the report.
4179
+ * @param options - Options for the command. Example: { type: "json", screenshot: true }
4180
+ * @param world - Optional world context.
4181
+ * @public
4182
+ */
4183
+ async addCommandToReport(commandText, commandStatus, content, options = {}, world = null) {
4184
+ const state = {
4185
+ options,
4186
+ world,
4187
+ locate: false,
4188
+ scroll: false,
4189
+ screenshot: options.screenshot ?? false,
4190
+ highlight: options.highlight ?? false,
4191
+ type: Types.REPORT_COMMAND,
4192
+ text: commandText,
4193
+ _text: commandText,
4194
+ operation: "report_command",
4195
+ log: "***** " + commandText + " *****\n",
4196
+ };
4197
+ try {
4198
+ await _preCommand(state, this);
4199
+ const payload = {
4200
+ type: options.type ?? "text",
4201
+ content: content,
4202
+ screenshotId: null,
4203
+ };
4204
+ state.payload = payload;
4205
+ if (commandStatus === "FAILED") {
4206
+ state.throwError = true;
4207
+ throw new Error("Command failed");
4208
+ }
4209
+ }
4210
+ catch (e) {
4211
+ await _commandError(state, e, this);
4212
+ }
4213
+ finally {
4214
+ await _commandFinally(state, this);
4215
+ }
4216
+ }
3422
4217
  async afterStep(world, step) {
3423
4218
  this.stepName = null;
3424
4219
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
@@ -3426,10 +4221,12 @@ class StableBrowser {
3426
4221
  await this.context.browserObject.context.tracing.stopChunk({
3427
4222
  path: path.join(this.context.browserObject.traceFolder, `trace-${this.stepIndex}.zip`),
3428
4223
  });
3429
- await world.attach(JSON.stringify({
3430
- type: "trace",
3431
- traceFilePath: `trace-${this.stepIndex}.zip`,
3432
- }), "application/json+trace");
4224
+ if (world && world.attach) {
4225
+ await world.attach(JSON.stringify({
4226
+ type: "trace",
4227
+ traceFilePath: `trace-${this.stepIndex}.zip`,
4228
+ }), "application/json+trace");
4229
+ }
3433
4230
  // console.log("trace file created", `trace-${this.stepIndex}.zip`);
3434
4231
  }
3435
4232
  }
@@ -3443,6 +4240,36 @@ class StableBrowser {
3443
4240
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-after");
3444
4241
  }
3445
4242
  }
4243
+ this.context.routeResults = await registerAfterStepRoutes(this.context, world);
4244
+ if (this.context.routeResults) {
4245
+ if (world && world.attach) {
4246
+ await world.attach(JSON.stringify(this.context.routeResults), "application/json+intercept-results");
4247
+ }
4248
+ }
4249
+ if (!process.env.TEMP_RUN) {
4250
+ const state = {
4251
+ world,
4252
+ locate: false,
4253
+ scroll: false,
4254
+ screenshot: true,
4255
+ highlight: true,
4256
+ type: Types.STEP_COMPLETE,
4257
+ text: "end of scenario",
4258
+ _text: "end of scenario",
4259
+ operation: "step_complete",
4260
+ log: "***** " + "end of scenario" + " *****\n",
4261
+ };
4262
+ try {
4263
+ await _preCommand(state, this);
4264
+ }
4265
+ catch (e) {
4266
+ await _commandError(state, e, this);
4267
+ }
4268
+ finally {
4269
+ await _commandFinally(state, this);
4270
+ }
4271
+ }
4272
+ networkAfterStep(this.stepName);
3446
4273
  }
3447
4274
  }
3448
4275
  function createTimedPromise(promise, label) {