automation_model 1.0.675-dev → 1.0.675-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 (61) 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 +2 -2
  5. package/lib/api.js.map +1 -1
  6. package/lib/auto_page.d.ts +4 -2
  7. package/lib/auto_page.js +181 -59
  8. package/lib/auto_page.js.map +1 -1
  9. package/lib/browser_manager.js +31 -8
  10. package/lib/browser_manager.js.map +1 -1
  11. package/lib/bruno.d.ts +1 -0
  12. package/lib/bruno.js +140 -14
  13. package/lib/bruno.js.map +1 -1
  14. package/lib/command_common.d.ts +1 -1
  15. package/lib/command_common.js +9 -8
  16. package/lib/command_common.js.map +1 -1
  17. package/lib/date_time.js.map +1 -1
  18. package/lib/drawRect.js.map +1 -1
  19. package/lib/environment.d.ts +1 -0
  20. package/lib/environment.js +1 -0
  21. package/lib/environment.js.map +1 -1
  22. package/lib/error-messages.js.map +1 -1
  23. package/lib/file_checker.d.ts +1 -0
  24. package/lib/file_checker.js +61 -0
  25. package/lib/file_checker.js.map +1 -0
  26. package/lib/find_function.js.map +1 -1
  27. package/lib/index.d.ts +1 -0
  28. package/lib/index.js +1 -0
  29. package/lib/index.js.map +1 -1
  30. package/lib/init_browser.js +4 -4
  31. package/lib/init_browser.js.map +1 -1
  32. package/lib/locate_element.js.map +1 -1
  33. package/lib/locator.d.ts +1 -0
  34. package/lib/locator.js +10 -3
  35. package/lib/locator.js.map +1 -1
  36. package/lib/locator_log.js.map +1 -1
  37. package/lib/network.d.ts +2 -0
  38. package/lib/network.js +133 -0
  39. package/lib/network.js.map +1 -1
  40. package/lib/route.d.ts +34 -0
  41. package/lib/route.js +325 -0
  42. package/lib/route.js.map +1 -0
  43. package/lib/scripts/axe.mini.js +3 -3
  44. package/lib/snapshot_validation.d.ts +37 -0
  45. package/lib/snapshot_validation.js +357 -0
  46. package/lib/snapshot_validation.js.map +1 -0
  47. package/lib/stable_browser.d.ts +63 -25
  48. package/lib/stable_browser.js +1125 -282
  49. package/lib/stable_browser.js.map +1 -1
  50. package/lib/table.d.ts +9 -7
  51. package/lib/table.js +82 -12
  52. package/lib/table.js.map +1 -1
  53. package/lib/table_analyze.js.map +1 -1
  54. package/lib/table_helper.js.map +1 -1
  55. package/lib/test_context.d.ts +1 -0
  56. package/lib/test_context.js +1 -0
  57. package/lib/test_context.js.map +1 -1
  58. package/lib/utils.d.ts +3 -2
  59. package/lib/utils.js +83 -57
  60. package/lib/utils.js.map +1 -1
  61. package/package.json +14 -8
@@ -10,35 +10,42 @@ 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";
17
17
  import { getContext, refreshBrowser } from "./init_browser.js";
18
+ import { getTestData } from "./auto_page.js";
18
19
  import { locate_element } from "./locate_element.js";
19
20
  import { randomUUID } from "crypto";
20
21
  import { _commandError, _commandFinally, _preCommand, _validateSelectors, _screenshot, _reportToWorld, } from "./command_common.js";
21
- import { registerDownloadEvent, registerNetworkEvents } from "./network.js";
22
+ import { networkAfterStep, networkBeforeStep, registerDownloadEvent, registerNetworkEvents } from "./network.js";
22
23
  import { LocatorLog } from "./locator_log.js";
23
24
  import axios from "axios";
24
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";
25
29
  export const Types = {
26
30
  CLICK: "click_element",
27
31
  WAIT_ELEMENT: "wait_element",
28
32
  NAVIGATE: "navigate",
33
+ GO_BACK: "go_back",
34
+ GO_FORWARD: "go_forward",
29
35
  FILL: "fill_element",
30
- EXECUTE: "execute_page_method",
31
- OPEN: "open_environment",
36
+ EXECUTE: "execute_page_method", //
37
+ OPEN: "open_environment", //
32
38
  COMPLETE: "step_complete",
33
39
  ASK: "information_needed",
34
- GET_PAGE_STATUS: "get_page_status",
35
- CLICK_ROW_ACTION: "click_row_action",
40
+ GET_PAGE_STATUS: "get_page_status", ///
41
+ CLICK_ROW_ACTION: "click_row_action", //
36
42
  VERIFY_ELEMENT_CONTAINS_TEXT: "verify_element_contains_text",
37
43
  VERIFY_PAGE_CONTAINS_TEXT: "verify_page_contains_text",
38
44
  VERIFY_PAGE_CONTAINS_NO_TEXT: "verify_page_contains_no_text",
39
45
  ANALYZE_TABLE: "analyze_table",
40
- SELECT: "select_combobox",
46
+ SELECT: "select_combobox", //
41
47
  VERIFY_PAGE_PATH: "verify_page_path",
48
+ VERIFY_PAGE_TITLE: "verify_page_title",
42
49
  TYPE_PRESS: "type_press",
43
50
  PRESS: "press_key",
44
51
  HOVER: "hover_element",
@@ -56,6 +63,13 @@ export const Types = {
56
63
  VERIFY_ATTRIBUTE: "verify_element_attribute",
57
64
  VERIFY_TEXT_WITH_RELATION: "verify_text_with_relation",
58
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",
59
73
  };
60
74
  export const apps = {};
61
75
  const formatElementName = (elementName) => {
@@ -67,6 +81,7 @@ class StableBrowser {
67
81
  logger;
68
82
  context;
69
83
  world;
84
+ fastMode;
70
85
  project_path = null;
71
86
  webLogFile = null;
72
87
  networkLogger = null;
@@ -75,12 +90,13 @@ class StableBrowser {
75
90
  tags = null;
76
91
  isRecording = false;
77
92
  initSnapshotTaken = false;
78
- constructor(browser, page, logger = null, context = null, world = null) {
93
+ constructor(browser, page, logger = null, context = null, world = null, fastMode = false) {
79
94
  this.browser = browser;
80
95
  this.page = page;
81
96
  this.logger = logger;
82
97
  this.context = context;
83
98
  this.world = world;
99
+ this.fastMode = fastMode;
84
100
  if (!this.logger) {
85
101
  this.logger = console;
86
102
  }
@@ -109,6 +125,18 @@ class StableBrowser {
109
125
  context.pages = [this.page];
110
126
  const logFolder = path.join(this.project_path, "logs", "web");
111
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
+ this.fastMode = true;
133
+ }
134
+ if (process.env.FAST_MODE === "false") {
135
+ this.fastMode = false;
136
+ }
137
+ if (this.context) {
138
+ this.context.fastMode = this.fastMode;
139
+ }
112
140
  this.registerEventListeners(this.context);
113
141
  registerNetworkEvents(this.world, this, this.context, this.page);
114
142
  registerDownloadEvent(this.page, this.world, this.context);
@@ -119,6 +147,9 @@ class StableBrowser {
119
147
  if (!context.pageLoading) {
120
148
  context.pageLoading = { status: false };
121
149
  }
150
+ if (this.configuration && this.configuration.acceptDialog && this.page) {
151
+ this.page.on("dialog", (dialog) => dialog.accept());
152
+ }
122
153
  context.playContext.on("page", async function (page) {
123
154
  if (this.configuration && this.configuration.closePopups === true) {
124
155
  console.log("close unexpected popups");
@@ -127,6 +158,14 @@ class StableBrowser {
127
158
  }
128
159
  context.pageLoading.status = true;
129
160
  this.page = page;
161
+ try {
162
+ if (this.configuration && this.configuration.acceptDialog) {
163
+ await page.on("dialog", (dialog) => dialog.accept());
164
+ }
165
+ }
166
+ catch (error) {
167
+ console.error("Error on dialog accept registration", error);
168
+ }
130
169
  context.page = page;
131
170
  context.pages.push(page);
132
171
  registerNetworkEvents(this.world, this, context, this.page);
@@ -178,8 +217,34 @@ class StableBrowser {
178
217
  if (newContextCreated) {
179
218
  this.registerEventListeners(this.context);
180
219
  await this.goto(this.context.environment.baseUrl);
181
- await this.waitForPageLoad();
220
+ if (!this.fastMode) {
221
+ await this.waitForPageLoad();
222
+ }
223
+ }
224
+ }
225
+ async switchTab(tabTitleOrIndex) {
226
+ // first check if the tabNameOrIndex is a number
227
+ let index = parseInt(tabTitleOrIndex);
228
+ if (!isNaN(index)) {
229
+ if (index >= 0 && index < this.context.pages.length) {
230
+ this.page = this.context.pages[index];
231
+ this.context.page = this.page;
232
+ await this.page.bringToFront();
233
+ return;
234
+ }
235
+ }
236
+ // if the tabNameOrIndex is a string, find the tab by name
237
+ for (let i = 0; i < this.context.pages.length; i++) {
238
+ let page = this.context.pages[i];
239
+ let title = await page.title();
240
+ if (title.includes(tabTitleOrIndex)) {
241
+ this.page = page;
242
+ this.context.page = this.page;
243
+ await this.page.bringToFront();
244
+ return;
245
+ }
182
246
  }
247
+ throw new Error("Tab not found: " + tabTitleOrIndex);
183
248
  }
184
249
  registerConsoleLogListener(page, context) {
185
250
  if (!this.context.webLogger) {
@@ -248,6 +313,7 @@ class StableBrowser {
248
313
  if (!url) {
249
314
  throw new Error("url is null, verify that the environment file is correct");
250
315
  }
316
+ url = await this._replaceWithLocalData(url, this.world);
251
317
  if (!url.startsWith("http")) {
252
318
  url = "https://" + url;
253
319
  }
@@ -276,7 +342,65 @@ class StableBrowser {
276
342
  _commandError(state, error, this);
277
343
  }
278
344
  finally {
279
- _commandFinally(state, this);
345
+ await _commandFinally(state, this);
346
+ }
347
+ }
348
+ async goBack(options, world = null) {
349
+ const state = {
350
+ value: "",
351
+ world: world,
352
+ type: Types.GO_BACK,
353
+ text: `Browser navigate back`,
354
+ operation: "goBack",
355
+ log: "***** navigate back *****\n",
356
+ info: {},
357
+ locate: false,
358
+ scroll: false,
359
+ screenshot: false,
360
+ highlight: false,
361
+ };
362
+ try {
363
+ await _preCommand(state, this);
364
+ await this.page.goBack({
365
+ waitUntil: "load",
366
+ });
367
+ await _screenshot(state, this);
368
+ }
369
+ catch (error) {
370
+ console.error("Error on goBack", error);
371
+ _commandError(state, error, this);
372
+ }
373
+ finally {
374
+ await _commandFinally(state, this);
375
+ }
376
+ }
377
+ async goForward(options, world = null) {
378
+ const state = {
379
+ value: "",
380
+ world: world,
381
+ type: Types.GO_FORWARD,
382
+ text: `Browser navigate forward`,
383
+ operation: "goForward",
384
+ log: "***** navigate forward *****\n",
385
+ info: {},
386
+ locate: false,
387
+ scroll: false,
388
+ screenshot: false,
389
+ highlight: false,
390
+ };
391
+ try {
392
+ await _preCommand(state, this);
393
+ await this.page.goForward({
394
+ waitUntil: "load",
395
+ });
396
+ await _screenshot(state, this);
397
+ }
398
+ catch (error) {
399
+ console.error("Error on goForward", error);
400
+ _commandError(state, error, this);
401
+ }
402
+ finally {
403
+ await _commandFinally(state, this);
280
404
  }
281
405
  }
282
406
  async _getLocator(locator, scope, _params) {
@@ -392,7 +516,7 @@ class StableBrowser {
392
516
  }
393
517
  return { elementCount: tagCount, randomToken };
394
518
  }
395
- async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null) {
519
+ async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null, logErrors = false) {
396
520
  if (!info) {
397
521
  info = {};
398
522
  }
@@ -404,14 +528,13 @@ class StableBrowser {
404
528
  info.locatorLog = new LocatorLog(selectorHierarchy);
405
529
  }
406
530
  let locatorSearch = selectorHierarchy[index];
407
- let originalLocatorSearch = "";
408
531
  try {
409
- originalLocatorSearch = _fixUsingParams(JSON.stringify(locatorSearch), _params);
410
- locatorSearch = JSON.parse(originalLocatorSearch);
532
+ locatorSearch = _fixLocatorUsingParams(locatorSearch, _params);
411
533
  }
412
534
  catch (e) {
413
535
  console.error(e);
414
536
  }
537
+ let originalLocatorSearch = JSON.stringify(locatorSearch);
415
538
  //info.log += "searching for locator " + JSON.stringify(locatorSearch) + "\n";
416
539
  let locator = null;
417
540
  if (locatorSearch.climb && locatorSearch.climb >= 0) {
@@ -459,7 +582,7 @@ class StableBrowser {
459
582
  }
460
583
  return;
461
584
  }
462
- if (info.locatorLog && count === 0) {
585
+ if (info.locatorLog && count === 0 && logErrors) {
463
586
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "NOT_FOUND");
464
587
  }
465
588
  for (let j = 0; j < count; j++) {
@@ -474,7 +597,7 @@ class StableBrowser {
474
597
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "FOUND");
475
598
  }
476
599
  }
477
- else {
600
+ else if (logErrors) {
478
601
  info.failCause.visible = visible;
479
602
  info.failCause.enabled = enabled;
480
603
  if (!info.printMessages) {
@@ -566,7 +689,7 @@ class StableBrowser {
566
689
  let element = await this._locate_internal(selectors, info, _params, timeout, allowDisabled);
567
690
  if (!element.rerun) {
568
691
  const randomToken = Math.random().toString(36).substring(7);
569
- element.evaluate((el, randomToken) => {
692
+ await element.evaluate((el, randomToken) => {
570
693
  el.setAttribute("data-blinq-id-" + randomToken, "");
571
694
  }, randomToken);
572
695
  // if (element._frame) {
@@ -619,7 +742,7 @@ class StableBrowser {
619
742
  break;
620
743
  }
621
744
  catch (error) {
622
- console.error("frame not found " + frameLocator.css);
745
+ // console.error("frame not found " + frameLocator.css);
623
746
  }
624
747
  }
625
748
  }
@@ -815,7 +938,7 @@ class StableBrowser {
815
938
  }
816
939
  throw new Error("failed to locate first element no elements found, " + info.log);
817
940
  }
818
- async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name) {
941
+ async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name, logErrors = false) {
819
942
  let foundElements = [];
820
943
  const result = {
821
944
  foundElements: foundElements,
@@ -834,7 +957,9 @@ class StableBrowser {
834
957
  await this._collectLocatorInformation(locatorsGroup, i, this.page, foundLocators, _params, info, visibleOnly, allowDisabled, element_name);
835
958
  }
836
959
  catch (e) {
837
- this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
960
+ if (logErrors) {
961
+ this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
962
+ }
838
963
  }
839
964
  }
840
965
  if (foundLocators.length === 1) {
@@ -875,7 +1000,7 @@ class StableBrowser {
875
1000
  });
876
1001
  result.locatorIndex = i;
877
1002
  }
878
- else {
1003
+ else if (logErrors) {
879
1004
  info.failCause.foundMultiple = true;
880
1005
  if (info.locatorLog) {
881
1006
  info.locatorLog.setLocatorSearchStatus(JSON.stringify(locatorsGroup[i]), "FOUND_NOT_UNIQUE");
@@ -927,7 +1052,7 @@ class StableBrowser {
927
1052
  await _commandError(state, "timeout looking for " + elementDescription, this);
928
1053
  }
929
1054
  finally {
930
- _commandFinally(state, this);
1055
+ await _commandFinally(state, this);
931
1056
  }
932
1057
  }
933
1058
  }
@@ -976,7 +1101,7 @@ class StableBrowser {
976
1101
  await _commandError(state, "timeout looking for " + elementDescription, this);
977
1102
  }
978
1103
  finally {
979
- _commandFinally(state, this);
1104
+ await _commandFinally(state, this);
980
1105
  }
981
1106
  }
982
1107
  }
@@ -998,14 +1123,16 @@ class StableBrowser {
998
1123
  try {
999
1124
  await _preCommand(state, this);
1000
1125
  await performAction("click", state.element, options, this, state, _params);
1001
- await this.waitForPageLoad();
1126
+ if (!this.fastMode) {
1127
+ await this.waitForPageLoad();
1128
+ }
1002
1129
  return state.info;
1003
1130
  }
1004
1131
  catch (e) {
1005
1132
  await _commandError(state, e, this);
1006
1133
  }
1007
1134
  finally {
1008
- _commandFinally(state, this);
1135
+ await _commandFinally(state, this);
1009
1136
  }
1010
1137
  }
1011
1138
  async waitForElement(selectors, _params, options = {}, world = null) {
@@ -1036,7 +1163,7 @@ class StableBrowser {
1036
1163
  // await _commandError(state, e, this);
1037
1164
  }
1038
1165
  finally {
1039
- _commandFinally(state, this);
1166
+ await _commandFinally(state, this);
1040
1167
  }
1041
1168
  return found;
1042
1169
  }
@@ -1061,7 +1188,7 @@ class StableBrowser {
1061
1188
  // if (world && world.screenshot && !world.screenshotPath) {
1062
1189
  // console.log(`Highlighting while running from recorder`);
1063
1190
  await this._highlightElements(state.element);
1064
- await state.element.setChecked(checked);
1191
+ await state.element.setChecked(checked, { timeout: 2000 });
1065
1192
  await new Promise((resolve) => setTimeout(resolve, 1000));
1066
1193
  // await this._unHighlightElements(element);
1067
1194
  // }
@@ -1073,11 +1200,28 @@ class StableBrowser {
1073
1200
  this.logger.info("element did not change its state, ignoring...");
1074
1201
  }
1075
1202
  else {
1203
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1076
1204
  //await this.closeUnexpectedPopups();
1077
1205
  state.info.log += "setCheck failed, will try again" + "\n";
1078
- state.element = await this._locate(selectors, state.info, _params);
1079
- await state.element.setChecked(checked, { timeout: 5000, force: true });
1080
- await new Promise((resolve) => setTimeout(resolve, 1000));
1206
+ state.element_found = false;
1207
+ try {
1208
+ state.element = await this._locate(selectors, state.info, _params, 100);
1209
+ state.element_found = true;
1210
+ // check the check state
1211
+ }
1212
+ catch (error) {
1213
+ // element dismissed
1214
+ }
1215
+ if (state.element_found) {
1216
+ const isChecked = await state.element.isChecked();
1217
+ if (isChecked !== checked) {
1218
+ // perform click
1219
+ await state.element.click({ timeout: 2000, force: true });
1220
+ }
1221
+ else {
1222
+ this.logger.info(`Element ${selectors.element_name} is already in the desired state (${checked})`);
1223
+ }
1224
+ }
1081
1225
  }
1082
1226
  }
1083
1227
  await this.waitForPageLoad();
@@ -1087,7 +1231,7 @@ class StableBrowser {
1087
1231
  await _commandError(state, e, this);
1088
1232
  }
1089
1233
  finally {
1090
- _commandFinally(state, this);
1234
+ await _commandFinally(state, this);
1091
1235
  }
1092
1236
  }
1093
1237
  async hover(selectors, _params, options = {}, world = null) {
@@ -1113,7 +1257,7 @@ class StableBrowser {
1113
1257
  await _commandError(state, e, this);
1114
1258
  }
1115
1259
  finally {
1116
- _commandFinally(state, this);
1260
+ await _commandFinally(state, this);
1117
1261
  }
1118
1262
  }
1119
1263
  async selectOption(selectors, values, _params = null, options = {}, world = null) {
@@ -1149,7 +1293,7 @@ class StableBrowser {
1149
1293
  await _commandError(state, e, this);
1150
1294
  }
1151
1295
  finally {
1152
- _commandFinally(state, this);
1296
+ await _commandFinally(state, this);
1153
1297
  }
1154
1298
  }
1155
1299
  async type(_value, _params = null, options = {}, world = null) {
@@ -1195,7 +1339,7 @@ class StableBrowser {
1195
1339
  await _commandError(state, e, this);
1196
1340
  }
1197
1341
  finally {
1198
- _commandFinally(state, this);
1342
+ await _commandFinally(state, this);
1199
1343
  }
1200
1344
  }
1201
1345
  async setInputValue(selectors, value, _params = null, options = {}, world = null) {
@@ -1231,7 +1375,7 @@ class StableBrowser {
1231
1375
  await _commandError(state, e, this);
1232
1376
  }
1233
1377
  finally {
1234
- _commandFinally(state, this);
1378
+ await _commandFinally(state, this);
1235
1379
  }
1236
1380
  }
1237
1381
  async setDateTime(selectors, value, format = null, enter = false, _params = null, options = {}, world = null) {
@@ -1300,7 +1444,7 @@ class StableBrowser {
1300
1444
  await _commandError(state, e, this);
1301
1445
  }
1302
1446
  finally {
1303
- _commandFinally(state, this);
1447
+ await _commandFinally(state, this);
1304
1448
  }
1305
1449
  }
1306
1450
  async clickType(selectors, _value, enter = false, _params = null, options = {}, world = null) {
@@ -1373,7 +1517,9 @@ class StableBrowser {
1373
1517
  await new Promise((resolve) => setTimeout(resolve, 500));
1374
1518
  }
1375
1519
  }
1520
+ //if (!this.fastMode) {
1376
1521
  await _screenshot(state, this);
1522
+ //}
1377
1523
  if (enter === true) {
1378
1524
  await new Promise((resolve) => setTimeout(resolve, 2000));
1379
1525
  await this.page.keyboard.press("Enter");
@@ -1400,7 +1546,7 @@ class StableBrowser {
1400
1546
  await _commandError(state, e, this);
1401
1547
  }
1402
1548
  finally {
1403
- _commandFinally(state, this);
1549
+ await _commandFinally(state, this);
1404
1550
  }
1405
1551
  }
1406
1552
  async fill(selectors, value, enter = false, _params = null, options = {}, world = null) {
@@ -1430,7 +1576,42 @@ class StableBrowser {
1430
1576
  await _commandError(state, e, this);
1431
1577
  }
1432
1578
  finally {
1433
- _commandFinally(state, this);
1579
+ await _commandFinally(state, this);
1580
+ }
1581
+ }
1582
+ async setInputFiles(selectors, files, _params = null, options = {}, world = null) {
1583
+ const state = {
1584
+ selectors,
1585
+ _params,
1586
+ files,
1587
+ value: '"' + files.join('", "') + '"',
1588
+ options,
1589
+ world,
1590
+ type: Types.SET_INPUT_FILES,
1591
+ text: `Set input files`,
1592
+ _text: `Set input files on ${selectors.element_name}`,
1593
+ operation: "setInputFiles",
1594
+ log: "***** set input files " + selectors.element_name + " *****\n",
1595
+ };
1596
+ const uploadsFolder = this.configuration.uploadsFolder ?? "data/uploads";
1597
+ try {
1598
+ await _preCommand(state, this);
1599
+ for (let i = 0; i < files.length; i++) {
1600
+ const file = files[i];
1601
+ const filePath = path.join(uploadsFolder, file);
1602
+ if (!fs.existsSync(filePath)) {
1603
+ throw new Error(`File not found: ${filePath}`);
1604
+ }
1605
+ state.files[i] = filePath;
1606
+ }
1607
+ await state.element.setInputFiles(files);
1608
+ return state.info;
1609
+ }
1610
+ catch (e) {
1611
+ await _commandError(state, e, this);
1612
+ }
1613
+ finally {
1614
+ await _commandFinally(state, this);
1434
1615
  }
1435
1616
  }
1436
1617
  async getText(selectors, _params = null, options = {}, info = {}, world = null) {
@@ -1546,7 +1727,7 @@ class StableBrowser {
1546
1727
  await _commandError(state, e, this);
1547
1728
  }
1548
1729
  finally {
1549
- _commandFinally(state, this);
1730
+ await _commandFinally(state, this);
1550
1731
  }
1551
1732
  }
1552
1733
  async containsText(selectors, text, climb, _params = null, options = {}, world = null) {
@@ -1623,7 +1804,84 @@ class StableBrowser {
1623
1804
  throw e;
1624
1805
  }
1625
1806
  finally {
1626
- _commandFinally(state, this);
1807
+ await _commandFinally(state, this);
1808
+ }
1809
+ }
1810
+ async snapshotValidation(frameSelectors, referanceSnapshot, _params = null, options = {}, world = null) {
1811
+ const timeout = this._getFindElementTimeout(options);
1812
+ const startTime = Date.now();
1813
+ const state = {
1814
+ _params,
1815
+ value: referanceSnapshot,
1816
+ options,
1817
+ world,
1818
+ locate: false,
1819
+ scroll: false,
1820
+ screenshot: true,
1821
+ highlight: false,
1822
+ type: Types.SNAPSHOT_VALIDATION,
1823
+ text: `verify snapshot: ${referanceSnapshot}`,
1824
+ operation: "snapshotValidation",
1825
+ log: "***** verify snapshot *****\n",
1826
+ };
1827
+ if (!referanceSnapshot) {
1828
+ throw new Error("referanceSnapshot is null");
1829
+ }
1830
+ let text = null;
1831
+ if (fs.existsSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yml"))) {
1832
+ text = fs.readFileSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yml"), "utf8");
1833
+ }
1834
+ else if (fs.existsSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yaml"))) {
1835
+ text = fs.readFileSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yaml"), "utf8");
1836
+ }
1837
+ else if (referanceSnapshot.startsWith("yaml:")) {
1838
+ text = referanceSnapshot.substring(5);
1839
+ }
1840
+ else {
1841
+ throw new Error("referenceSnapshot file not found: " + referanceSnapshot);
1842
+ }
1843
+ state.text = text;
1844
+ const newValue = await this._replaceWithLocalData(text, world);
1845
+ await _preCommand(state, this);
1846
+ let foundObj = null;
1847
+ try {
1848
+ let matchResult = null;
1849
+ while (Date.now() - startTime < timeout) {
1850
+ try {
1851
+ let scope = null;
1852
+ if (!frameSelectors) {
1853
+ scope = this.page;
1854
+ }
1855
+ else {
1856
+ scope = await this._findFrameScope(frameSelectors, timeout, state.info);
1857
+ }
1858
+ const snapshot = await scope.locator("body").ariaSnapshot({ timeout });
1859
+ matchResult = snapshotValidation(snapshot, newValue, referanceSnapshot);
1860
+ if (matchResult.errorLine !== -1) {
1861
+ throw new Error("Snapshot validation failed at line " + matchResult.errorLineText);
1862
+ }
1863
+ // highlight and screenshot
1864
+ try {
1865
+ await await highlightSnapshot(newValue, scope);
1866
+ await _screenshot(state, this);
1867
+ }
1868
+ catch (e) { }
1869
+ return state.info;
1870
+ }
1871
+ catch (e) {
1872
+ // Log error but continue retrying until timeout is reached
1873
+ //this.logger.warn("Retrying snapshot validation due to: " + e.message);
1874
+ }
1875
+ await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait 1 second before retrying
1876
+ }
1877
+ throw new Error("No snapshot match " + matchResult?.errorLineText);
1878
+ }
1879
+ catch (e) {
1880
+ await _commandError(state, e, this);
1881
+ throw e;
1882
+ }
1883
+ finally {
1884
+ await _commandFinally(state, this);
1627
1885
  }
1628
1886
  }
1629
1887
  async waitForUserInput(message, world = null) {
@@ -1766,12 +2024,7 @@ class StableBrowser {
1766
2024
  }
1767
2025
  }
1768
2026
  getTestData(world = null) {
1769
- const dataFile = _getDataFile(world, this.context, this);
1770
- let data = {};
1771
- if (fs.existsSync(dataFile)) {
1772
- data = JSON.parse(fs.readFileSync(dataFile, "utf8"));
1773
- }
1774
- return data;
2027
+ return _getTestData(world, this.context, this);
1775
2028
  }
1776
2029
  async _screenShot(options = {}, world = null, info = null) {
1777
2030
  // collect url/path/title
@@ -1922,7 +2175,7 @@ class StableBrowser {
1922
2175
  await _commandError(state, e, this);
1923
2176
  }
1924
2177
  finally {
1925
- _commandFinally(state, this);
2178
+ await _commandFinally(state, this);
1926
2179
  }
1927
2180
  }
1928
2181
  async extractAttribute(selectors, attribute, variable, _params = null, options = {}, world = null) {
@@ -1960,6 +2213,95 @@ class StableBrowser {
1960
2213
  state.value = await state.element.getAttribute(attribute);
1961
2214
  break;
1962
2215
  }
2216
+ if (options !== null) {
2217
+ if (options.regex && options.regex !== "") {
2218
+ // Construct a regex pattern from the provided string
2219
+ const regex = options.regex.slice(1, -1);
2220
+ const regexPattern = new RegExp(regex, "g");
2221
+ const matches = state.value.match(regexPattern);
2222
+ if (matches) {
2223
+ let newValue = "";
2224
+ for (const match of matches) {
2225
+ newValue += match;
2226
+ }
2227
+ state.value = newValue;
2228
+ }
2229
+ }
2230
+ if (options.trimSpaces && options.trimSpaces === true) {
2231
+ state.value = state.value.trim();
2232
+ }
2233
+ }
2234
+ state.info.value = state.value;
2235
+ this.setTestData({ [variable]: state.value }, world);
2236
+ this.logger.info("set test data: " + variable + "=" + state.value);
2237
+ // await new Promise((resolve) => setTimeout(resolve, 500));
2238
+ return state.info;
2239
+ }
2240
+ catch (e) {
2241
+ await _commandError(state, e, this);
2242
+ }
2243
+ finally {
2244
+ await _commandFinally(state, this);
2245
+ }
2246
+ }
2247
+ async extractProperty(selectors, property, variable, _params = null, options = {}, world = null) {
2248
+ const state = {
2249
+ selectors,
2250
+ _params,
2251
+ property,
2252
+ variable,
2253
+ options,
2254
+ world,
2255
+ type: Types.EXTRACT_PROPERTY,
2256
+ text: `Extract property from element`,
2257
+ _text: `Extract property ${property} from ${selectors.element_name}`,
2258
+ operation: "extractProperty",
2259
+ log: "***** extract property " + property + " from " + selectors.element_name + " *****\n",
2260
+ allowDisabled: true,
2261
+ };
2262
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2263
+ try {
2264
+ await _preCommand(state, this);
2265
+ switch (property) {
2266
+ case "inner_text":
2267
+ state.value = await state.element.innerText();
2268
+ break;
2269
+ case "href":
2270
+ state.value = await state.element.getAttribute("href");
2271
+ break;
2272
+ case "value":
2273
+ state.value = await state.element.inputValue();
2274
+ break;
2275
+ case "text":
2276
+ state.value = await state.element.textContent();
2277
+ break;
2278
+ default:
2279
+ if (property.startsWith("dataset.")) {
2280
+ const dataAttribute = property.substring(8);
2281
+ state.value = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2282
+ }
2283
+ else {
2284
+ state.value = String(await state.element.evaluate((element, prop) => element[prop], property));
2285
+ }
2286
+ }
2287
+ if (options !== null) {
2288
+ if (options.regex && options.regex !== "") {
2289
+ // Construct a regex pattern from the provided string
2290
+ const regex = options.regex.slice(1, -1);
2291
+ const regexPattern = new RegExp(regex, "g");
2292
+ const matches = state.value.match(regexPattern);
2293
+ if (matches) {
2294
+ let newValue = "";
2295
+ for (const match of matches) {
2296
+ newValue += match;
2297
+ }
2298
+ state.value = newValue;
2299
+ }
2300
+ }
2301
+ if (options.trimSpaces && options.trimSpaces === true) {
2302
+ state.value = state.value.trim();
2303
+ }
2304
+ }
1963
2305
  state.info.value = state.value;
1964
2306
  this.setTestData({ [variable]: state.value }, world);
1965
2307
  this.logger.info("set test data: " + variable + "=" + state.value);
@@ -1970,7 +2312,7 @@ class StableBrowser {
1970
2312
  await _commandError(state, e, this);
1971
2313
  }
1972
2314
  finally {
1973
- _commandFinally(state, this);
2315
+ await _commandFinally(state, this);
1974
2316
  }
1975
2317
  }
1976
2318
  async verifyAttribute(selectors, attribute, value, _params = null, options = {}, world = null) {
@@ -2025,17 +2367,42 @@ class StableBrowser {
2025
2367
  let regex;
2026
2368
  if (expectedValue.startsWith("/") && expectedValue.endsWith("/")) {
2027
2369
  const patternBody = expectedValue.slice(1, -1);
2028
- regex = new RegExp(patternBody, "g");
2370
+ const processedPattern = patternBody.replace(/\n/g, ".*");
2371
+ regex = new RegExp(processedPattern, "gs");
2372
+ state.info.regex = true;
2029
2373
  }
2030
2374
  else {
2031
2375
  const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2032
2376
  regex = new RegExp(escapedPattern, "g");
2033
2377
  }
2034
- if (!val.match(regex)) {
2035
- let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2036
- state.info.failCause.assertionFailed = true;
2037
- state.info.failCause.lastError = errorMessage;
2038
- throw new Error(errorMessage);
2378
+ if (attribute === "innerText") {
2379
+ if (state.info.regex) {
2380
+ if (!regex.test(val)) {
2381
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2382
+ state.info.failCause.assertionFailed = true;
2383
+ state.info.failCause.lastError = errorMessage;
2384
+ throw new Error(errorMessage);
2385
+ }
2386
+ }
2387
+ else {
2388
+ const valLines = val.split("\n");
2389
+ const expectedLines = expectedValue.split("\n");
2390
+ const isPart = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine === expectedLine));
2391
+ if (!isPart) {
2392
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2393
+ state.info.failCause.assertionFailed = true;
2394
+ state.info.failCause.lastError = errorMessage;
2395
+ throw new Error(errorMessage);
2396
+ }
2397
+ }
2398
+ }
2399
+ else {
2400
+ if (!val.match(regex)) {
2401
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2402
+ state.info.failCause.assertionFailed = true;
2403
+ state.info.failCause.lastError = errorMessage;
2404
+ throw new Error(errorMessage);
2405
+ }
2039
2406
  }
2040
2407
  return state.info;
2041
2408
  }
@@ -2043,62 +2410,309 @@ class StableBrowser {
2043
2410
  await _commandError(state, e, this);
2044
2411
  }
2045
2412
  finally {
2046
- _commandFinally(state, this);
2413
+ await _commandFinally(state, this);
2047
2414
  }
2048
2415
  }
2049
- async extractEmailData(emailAddress, options, world) {
2050
- if (!emailAddress) {
2051
- throw new Error("email address is null");
2052
- }
2053
- // check if address contain @
2054
- if (emailAddress.indexOf("@") === -1) {
2055
- emailAddress = emailAddress + "@blinq-mail.io";
2056
- }
2057
- else {
2058
- if (!emailAddress.toLowerCase().endsWith("@blinq-mail.io")) {
2059
- throw new Error("email address should end with @blinq-mail.io");
2060
- }
2061
- }
2062
- const startTime = Date.now();
2063
- let timeout = 60000;
2064
- if (options && options.timeout) {
2065
- timeout = options.timeout;
2066
- }
2067
- const serviceUrl = _getServerUrl() + "/api/mail/createLinkOrCodeFromEmail";
2068
- const request = {
2069
- method: "POST",
2070
- url: serviceUrl,
2071
- headers: {
2072
- "Content-Type": "application/json",
2073
- Authorization: `Bearer ${process.env.TOKEN}`,
2074
- },
2075
- data: JSON.stringify({
2076
- email: emailAddress,
2077
- }),
2416
+ async verifyProperty(selectors, property, value, _params = null, options = {}, world = null) {
2417
+ const state = {
2418
+ selectors,
2419
+ _params,
2420
+ property,
2421
+ value,
2422
+ options,
2423
+ world,
2424
+ type: Types.VERIFY_PROPERTY,
2425
+ highlight: true,
2426
+ screenshot: true,
2427
+ text: `Verify element property`,
2428
+ _text: `Verify property ${property} from ${selectors.element_name} is ${value}`,
2429
+ operation: "verifyProperty",
2430
+ log: "***** verify property " + property + " from " + selectors.element_name + " *****\n",
2431
+ allowDisabled: true,
2078
2432
  };
2079
- let errorCount = 0;
2080
- while (true) {
2081
- try {
2082
- let result = await this.context.api.request(request);
2083
- // the response body expected to be the following:
2084
- // {
2085
- // "status": true,
2086
- // "content": {
2087
- // "url": "",
2088
- // "code": "112112",
2089
- // "name": "generate_link_or_code"
2090
- // }
2091
- //}
2092
- if ((result && result.data, result.data.status === true)) {
2093
- let codeOrUrlFound = false;
2094
- let emailCode = null;
2095
- let emailUrl = null;
2096
- // check if a code is returned
2097
- if (result.data.content && result.data.content.code) {
2098
- let code = result.data.content.code;
2099
- this.setTestData({ emailCode: code }, world);
2100
- this.logger.info("set test data: emailCode = " + code);
2101
- emailCode = code;
2433
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2434
+ let val;
2435
+ let expectedValue;
2436
+ try {
2437
+ await _preCommand(state, this);
2438
+ expectedValue = await replaceWithLocalTestData(state.value, world);
2439
+ state.info.expectedValue = expectedValue;
2440
+ switch (property) {
2441
+ case "innerText":
2442
+ val = String(await state.element.innerText());
2443
+ break;
2444
+ case "text":
2445
+ val = String(await state.element.textContent());
2446
+ break;
2447
+ case "value":
2448
+ val = String(await state.element.inputValue());
2449
+ break;
2450
+ case "checked":
2451
+ val = String(await state.element.isChecked());
2452
+ break;
2453
+ case "disabled":
2454
+ val = String(await state.element.isDisabled());
2455
+ break;
2456
+ case "readOnly":
2457
+ const isEditable = await state.element.isEditable();
2458
+ val = String(!isEditable);
2459
+ break;
2460
+ case "innerHTML":
2461
+ val = String(await state.element.innerHTML());
2462
+ break;
2463
+ case "outerHTML":
2464
+ val = String(await state.element.evaluate((element) => element.outerHTML));
2465
+ break;
2466
+ default:
2467
+ if (property.startsWith("dataset.")) {
2468
+ const dataAttribute = property.substring(8);
2469
+ val = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2470
+ }
2471
+ else {
2472
+ val = String(await state.element.evaluate((element, prop) => element[prop], property));
2473
+ }
2474
+ }
2475
+ // Helper function to remove all style="" attributes
2476
+ const removeStyleAttributes = (htmlString) => {
2477
+ return htmlString.replace(/\s*style\s*=\s*"[^"]*"/gi, "");
2478
+ };
2479
+ // Remove style attributes for innerHTML and outerHTML properties
2480
+ if (property === "innerHTML" || property === "outerHTML") {
2481
+ val = removeStyleAttributes(val);
2482
+ expectedValue = removeStyleAttributes(expectedValue);
2483
+ }
2484
+ state.info.value = val;
2485
+ let regex;
2486
+ if (expectedValue.startsWith("/") && expectedValue.endsWith("/")) {
2487
+ const patternBody = expectedValue.slice(1, -1);
2488
+ const processedPattern = patternBody.replace(/\n/g, ".*");
2489
+ regex = new RegExp(processedPattern, "gs");
2490
+ state.info.regex = true;
2491
+ }
2492
+ else {
2493
+ const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2494
+ regex = new RegExp(escapedPattern, "g");
2495
+ }
2496
+ if (property === "innerText") {
2497
+ if (state.info.regex) {
2498
+ if (!regex.test(val)) {
2499
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2500
+ state.info.failCause.assertionFailed = true;
2501
+ state.info.failCause.lastError = errorMessage;
2502
+ throw new Error(errorMessage);
2503
+ }
2504
+ }
2505
+ else {
2506
+ // Fix: Replace escaped newlines with actual newlines before splitting
2507
+ const normalizedExpectedValue = expectedValue.replace(/\\n/g, "\n");
2508
+ const valLines = val.split("\n");
2509
+ const expectedLines = normalizedExpectedValue.split("\n");
2510
+ // Check if all expected lines are present in the actual lines
2511
+ const isPart = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine.trim() === expectedLine.trim()));
2512
+ if (!isPart) {
2513
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2514
+ state.info.failCause.assertionFailed = true;
2515
+ state.info.failCause.lastError = errorMessage;
2516
+ throw new Error(errorMessage);
2517
+ }
2518
+ }
2519
+ }
2520
+ else {
2521
+ if (!val.match(regex)) {
2522
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2523
+ state.info.failCause.assertionFailed = true;
2524
+ state.info.failCause.lastError = errorMessage;
2525
+ throw new Error(errorMessage);
2526
+ }
2527
+ }
2528
+ return state.info;
2529
+ }
2530
+ catch (e) {
2531
+ await _commandError(state, e, this);
2532
+ }
2533
+ finally {
2534
+ await _commandFinally(state, this);
2535
+ }
2536
+ }
2537
+ async conditionalWait(selectors, condition, timeout = 1000, _params = null, options = {}, world = null) {
2538
+ // Convert timeout from seconds to milliseconds
2539
+ const timeoutMs = timeout * 1000;
2540
+ const state = {
2541
+ selectors,
2542
+ _params,
2543
+ condition,
2544
+ timeout: timeoutMs, // Store as milliseconds for internal use
2545
+ options,
2546
+ world,
2547
+ type: Types.CONDITIONAL_WAIT,
2548
+ highlight: true,
2549
+ screenshot: true,
2550
+ text: `Conditional wait for element`,
2551
+ _text: `Wait for ${selectors.element_name} to be ${condition} (timeout: ${timeout}s)`, // Display original seconds
2552
+ operation: "conditionalWait",
2553
+ log: `***** conditional wait for ${condition} on ${selectors.element_name} *****\n`,
2554
+ allowDisabled: true,
2555
+ info: {},
2556
+ };
2557
+ // Initialize startTime outside try block to ensure it's always accessible
2558
+ const startTime = Date.now();
2559
+ let conditionMet = false;
2560
+ let currentValue = null;
2561
+ let lastError = null;
2562
+ // Main retry loop - continues until timeout or condition is met
2563
+ while (Date.now() - startTime < timeoutMs) {
2564
+ const elapsedTime = Date.now() - startTime;
2565
+ const remainingTime = timeoutMs - elapsedTime;
2566
+ try {
2567
+ // Try to execute _preCommand (element location)
2568
+ await _preCommand(state, this);
2569
+ // If _preCommand succeeds, start condition checking
2570
+ const checkCondition = async () => {
2571
+ try {
2572
+ switch (condition.toLowerCase()) {
2573
+ case "checked":
2574
+ currentValue = await state.element.isChecked();
2575
+ return currentValue === true;
2576
+ case "unchecked":
2577
+ currentValue = await state.element.isChecked();
2578
+ return currentValue === false;
2579
+ case "visible":
2580
+ currentValue = await state.element.isVisible();
2581
+ return currentValue === true;
2582
+ case "hidden":
2583
+ currentValue = await state.element.isVisible();
2584
+ return currentValue === false;
2585
+ case "enabled":
2586
+ currentValue = await state.element.isDisabled();
2587
+ return currentValue === false;
2588
+ case "disabled":
2589
+ currentValue = await state.element.isDisabled();
2590
+ return currentValue === true;
2591
+ case "editable":
2592
+ // currentValue = await String(await state.element.evaluate((element, prop) => element[prop], "isContentEditable"));
2593
+ currentValue = await state.element.isContentEditable();
2594
+ return currentValue === true;
2595
+ default:
2596
+ state.info.message = `Unsupported condition: '${condition}'. Supported conditions are: checked, unchecked, visible, hidden, enabled, disabled, editable.`;
2597
+ state.info.success = false;
2598
+ return false;
2599
+ }
2600
+ }
2601
+ catch (error) {
2602
+ // Don't throw here, just return false to continue retrying
2603
+ return false;
2604
+ }
2605
+ };
2606
+ // Inner loop for condition checking (once element is located)
2607
+ while (Date.now() - startTime < timeoutMs) {
2608
+ const currentElapsedTime = Date.now() - startTime;
2609
+ conditionMet = await checkCondition();
2610
+ if (conditionMet) {
2611
+ break;
2612
+ }
2613
+ // Check if we still have time for another attempt
2614
+ if (Date.now() - startTime + 50 < timeoutMs) {
2615
+ await new Promise((res) => setTimeout(res, 50));
2616
+ }
2617
+ else {
2618
+ break;
2619
+ }
2620
+ }
2621
+ // If we got here and condition is met, break out of main loop
2622
+ if (conditionMet) {
2623
+ break;
2624
+ }
2625
+ // If condition not met but no exception, we've timed out
2626
+ break;
2627
+ }
2628
+ catch (e) {
2629
+ lastError = e;
2630
+ const currentElapsedTime = Date.now() - startTime;
2631
+ const timeLeft = timeoutMs - currentElapsedTime;
2632
+ // Check if we have enough time left to retry
2633
+ if (timeLeft > 100) {
2634
+ await new Promise((resolve) => setTimeout(resolve, 50));
2635
+ }
2636
+ else {
2637
+ break;
2638
+ }
2639
+ }
2640
+ }
2641
+ const actualWaitTime = Date.now() - startTime;
2642
+ state.info = {
2643
+ success: conditionMet,
2644
+ conditionMet,
2645
+ actualWaitTime,
2646
+ currentValue,
2647
+ lastError: lastError?.message || null,
2648
+ message: conditionMet
2649
+ ? `Condition '${condition}' met after ${(actualWaitTime / 1000).toFixed(2)}s`
2650
+ : `Condition '${condition}' not met within ${timeout}s timeout`,
2651
+ };
2652
+ if (lastError) {
2653
+ state.log += `Last error: ${lastError.message}\n`;
2654
+ }
2655
+ try {
2656
+ await _commandFinally(state, this);
2657
+ }
2658
+ catch (finallyError) {
2659
+ state.log += `Error in _commandFinally: ${finallyError.message}\n`;
2660
+ }
2661
+ return state.info;
2662
+ }
2663
+ async extractEmailData(emailAddress, options, world) {
2664
+ if (!emailAddress) {
2665
+ throw new Error("email address is null");
2666
+ }
2667
+ // check if address contain @
2668
+ if (emailAddress.indexOf("@") === -1) {
2669
+ emailAddress = emailAddress + "@blinq-mail.io";
2670
+ }
2671
+ else {
2672
+ if (!emailAddress.toLowerCase().endsWith("@blinq-mail.io")) {
2673
+ throw new Error("email address should end with @blinq-mail.io");
2674
+ }
2675
+ }
2676
+ const startTime = Date.now();
2677
+ let timeout = 60000;
2678
+ if (options && options.timeout) {
2679
+ timeout = options.timeout;
2680
+ }
2681
+ const serviceUrl = _getServerUrl() + "/api/mail/createLinkOrCodeFromEmail";
2682
+ const request = {
2683
+ method: "POST",
2684
+ url: serviceUrl,
2685
+ headers: {
2686
+ "Content-Type": "application/json",
2687
+ Authorization: `Bearer ${process.env.TOKEN}`,
2688
+ },
2689
+ data: JSON.stringify({
2690
+ email: emailAddress,
2691
+ }),
2692
+ };
2693
+ let errorCount = 0;
2694
+ while (true) {
2695
+ try {
2696
+ let result = await this.context.api.request(request);
2697
+ // the response body expected to be the following:
2698
+ // {
2699
+ // "status": true,
2700
+ // "content": {
2701
+ // "url": "",
2702
+ // "code": "112112",
2703
+ // "name": "generate_link_or_code"
2704
+ // }
2705
+ //}
2706
+ if ((result && result.data, result.data.status === true)) {
2707
+ let codeOrUrlFound = false;
2708
+ let emailCode = null;
2709
+ let emailUrl = null;
2710
+ // check if a code is returned
2711
+ if (result.data.content && result.data.content.code) {
2712
+ let code = result.data.content.code;
2713
+ this.setTestData({ emailCode: code }, world);
2714
+ this.logger.info("set test data: emailCode = " + code);
2715
+ emailCode = code;
2102
2716
  codeOrUrlFound = true;
2103
2717
  }
2104
2718
  // check if a url is returned
@@ -2203,56 +2817,49 @@ class StableBrowser {
2203
2817
  console.debug(error);
2204
2818
  }
2205
2819
  }
2206
- // async _unhighlightElements(scope, css) {
2207
- // try {
2208
- // if (!scope) {
2209
- // return;
2210
- // }
2211
- // if (!css) {
2212
- // scope
2213
- // .evaluate((node) => {
2214
- // if (node && node.style) {
2215
- // if (!node.__previousOutline) {
2216
- // node.style.outline = "";
2217
- // } else {
2218
- // node.style.outline = node.__previousOutline;
2219
- // }
2220
- // }
2221
- // })
2222
- // .then(() => {})
2223
- // .catch((e) => {
2224
- // // console.log(`Error while unhighlighting node ${JSON.stringify(scope)}: ${e}`);
2225
- // });
2226
- // } else {
2227
- // scope
2228
- // .evaluate(([css]) => {
2229
- // if (!css) {
2230
- // return;
2231
- // }
2232
- // let elements = Array.from(document.querySelectorAll(css));
2233
- // for (i = 0; i < elements.length; i++) {
2234
- // let element = elements[i];
2235
- // if (!element.style) {
2236
- // return;
2237
- // }
2238
- // if (!element.__previousOutline) {
2239
- // element.style.outline = "";
2240
- // } else {
2241
- // element.style.outline = element.__previousOutline;
2242
- // }
2243
- // }
2244
- // })
2245
- // .then(() => {})
2246
- // .catch((e) => {
2247
- // // console.error(`Error while unhighlighting element in css: ${e}`);
2248
- // });
2249
- // }
2250
- // } catch (error) {
2251
- // // console.debug(error);
2252
- // }
2253
- // }
2820
+ _matcher(text) {
2821
+ if (!text) {
2822
+ return { matcher: "contains", queryText: "" };
2823
+ }
2824
+ if (text.length < 2) {
2825
+ return { matcher: "contains", queryText: text };
2826
+ }
2827
+ const split = text.split(":");
2828
+ const matcher = split[0].toLowerCase();
2829
+ const queryText = split.slice(1).join(":").trim();
2830
+ return { matcher, queryText };
2831
+ }
2832
+ _getDomain(url) {
2833
+ if (url.length === 0 || (!url.startsWith("http://") && !url.startsWith("https://"))) {
2834
+ return "";
2835
+ }
2836
+ let hostnameFragments = url.split("/")[2].split(".");
2837
+ if (hostnameFragments.some((fragment) => fragment.includes(":"))) {
2838
+ return hostnameFragments.join("-").split(":").join("-");
2839
+ }
2840
+ let n = hostnameFragments.length;
2841
+ let fragments = [...hostnameFragments];
2842
+ while (n > 0 && hostnameFragments[n - 1].length <= 3) {
2843
+ hostnameFragments.pop();
2844
+ n = hostnameFragments.length;
2845
+ }
2846
+ if (n == 0) {
2847
+ if (fragments[0] === "www")
2848
+ fragments = fragments.slice(1);
2849
+ return fragments.length > 1 ? fragments.slice(0, fragments.length - 1).join("-") : fragments.join("-");
2850
+ }
2851
+ if (hostnameFragments[0] === "www")
2852
+ hostnameFragments = hostnameFragments.slice(1);
2853
+ return hostnameFragments.join(".");
2854
+ }
2855
+ /**
2856
+ * Verify the page path matches the given path.
2857
+ * @param {string} pathPart - The path to verify.
2858
+ * @param {object} options - Options for verification.
2859
+ * @param {object} world - The world context.
2860
+ * @returns {Promise<object>} - The state info after verification.
2861
+ */
2254
2862
  async verifyPagePath(pathPart, options = {}, world = null) {
2255
- const startTime = Date.now();
2256
2863
  let error = null;
2257
2864
  let screenshotId = null;
2258
2865
  let screenshotPath = null;
@@ -2266,113 +2873,212 @@ class StableBrowser {
2266
2873
  pathPart = newValue;
2267
2874
  }
2268
2875
  info.pathPart = pathPart;
2876
+ const { matcher, queryText } = this._matcher(pathPart);
2877
+ const state = {
2878
+ text_search: queryText,
2879
+ options,
2880
+ world,
2881
+ locate: false,
2882
+ scroll: false,
2883
+ highlight: false,
2884
+ type: Types.VERIFY_PAGE_PATH,
2885
+ text: `Verify the page url is ${queryText}`,
2886
+ _text: `Verify the page url is ${queryText}`,
2887
+ operation: "verifyPagePath",
2888
+ log: "***** verify page url is " + queryText + " *****\n",
2889
+ };
2269
2890
  try {
2891
+ await _preCommand(state, this);
2892
+ state.info.text = queryText;
2270
2893
  for (let i = 0; i < 30; i++) {
2271
2894
  const url = await this.page.url();
2272
- if (!url.includes(pathPart)) {
2273
- if (i === 29) {
2274
- throw new Error(`url ${url} doesn't contain ${pathPart}`);
2275
- }
2276
- await new Promise((resolve) => setTimeout(resolve, 1000));
2277
- continue;
2895
+ switch (matcher) {
2896
+ case "exact":
2897
+ if (url !== queryText) {
2898
+ if (i === 29) {
2899
+ throw new Error(`Page URL ${url} is not equal to ${queryText}`);
2900
+ }
2901
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2902
+ continue;
2903
+ }
2904
+ break;
2905
+ case "contains":
2906
+ if (!url.includes(queryText)) {
2907
+ if (i === 29) {
2908
+ throw new Error(`Page URL ${url} doesn't contain ${queryText}`);
2909
+ }
2910
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2911
+ continue;
2912
+ }
2913
+ break;
2914
+ case "starts-with":
2915
+ {
2916
+ const domain = this._getDomain(url);
2917
+ if (domain.length > 0 && domain !== queryText) {
2918
+ if (i === 29) {
2919
+ throw new Error(`Page URL ${url} doesn't start with ${queryText}`);
2920
+ }
2921
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2922
+ continue;
2923
+ }
2924
+ }
2925
+ break;
2926
+ case "ends-with":
2927
+ {
2928
+ const urlObj = new URL(url);
2929
+ let route = "/";
2930
+ if (urlObj.pathname !== "/") {
2931
+ route = urlObj.pathname.split("/").slice(-1)[0].trim();
2932
+ }
2933
+ else {
2934
+ route = "/";
2935
+ }
2936
+ if (route !== queryText) {
2937
+ if (i === 29) {
2938
+ throw new Error(`Page URL ${url} doesn't end with ${queryText}`);
2939
+ }
2940
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2941
+ continue;
2942
+ }
2943
+ }
2944
+ break;
2945
+ case "regex":
2946
+ const regex = new RegExp(queryText.slice(1, -1), "g");
2947
+ if (!regex.test(url)) {
2948
+ if (i === 29) {
2949
+ throw new Error(`Page URL ${url} doesn't match regex ${queryText}`);
2950
+ }
2951
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2952
+ continue;
2953
+ }
2954
+ break;
2955
+ default:
2956
+ console.log("Unknown matching type, defaulting to contains matching");
2957
+ if (!url.includes(pathPart)) {
2958
+ if (i === 29) {
2959
+ throw new Error(`Page URL ${url} does not contain ${pathPart}`);
2960
+ }
2961
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2962
+ continue;
2963
+ }
2278
2964
  }
2279
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2280
- return info;
2965
+ await _screenshot(state, this);
2966
+ return state.info;
2281
2967
  }
2282
2968
  }
2283
2969
  catch (e) {
2284
- //await this.closeUnexpectedPopups();
2285
- this.logger.error("verify page path failed " + info.log);
2286
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2287
- info.screenshotPath = screenshotPath;
2288
- Object.assign(e, { info: info });
2289
- error = e;
2290
- // throw e;
2291
- await _commandError({ text: "verifyPagePath", operation: "verifyPagePath", pathPart, info }, e, this);
2970
+ state.info.failCause.lastError = e.message;
2971
+ state.info.failCause.assertionFailed = true;
2972
+ await _commandError(state, e, this);
2292
2973
  }
2293
2974
  finally {
2294
- const endTime = Date.now();
2295
- _reportToWorld(world, {
2296
- type: Types.VERIFY_PAGE_PATH,
2297
- text: "Verify page path",
2298
- _text: "Verify the page path contains " + pathPart,
2299
- screenshotId,
2300
- result: error
2301
- ? {
2302
- status: "FAILED",
2303
- startTime,
2304
- endTime,
2305
- message: error?.message,
2306
- }
2307
- : {
2308
- status: "PASSED",
2309
- startTime,
2310
- endTime,
2311
- },
2312
- info: info,
2313
- });
2975
+ await _commandFinally(state, this);
2314
2976
  }
2315
2977
  }
2978
+ /**
2979
+ * Verify the page title matches the given title.
2980
+ * @param {string} title - The title to verify.
2981
+ * @param {object} options - Options for verification.
2982
+ * @param {object} world - The world context.
2983
+ * @returns {Promise<object>} - The state info after verification.
2984
+ */
2316
2985
  async verifyPageTitle(title, options = {}, world = null) {
2317
- const startTime = Date.now();
2318
2986
  let error = null;
2319
2987
  let screenshotId = null;
2320
2988
  let screenshotPath = null;
2321
2989
  await new Promise((resolve) => setTimeout(resolve, 2000));
2322
- const info = {};
2323
- info.log = "***** verify page title " + title + " *****\n";
2324
- info.operation = "verifyPageTitle";
2325
2990
  const newValue = await this._replaceWithLocalData(title, world);
2326
2991
  if (newValue !== title) {
2327
2992
  this.logger.info(title + "=" + newValue);
2328
2993
  title = newValue;
2329
2994
  }
2330
- info.title = title;
2995
+ const { matcher, queryText } = this._matcher(title);
2996
+ const state = {
2997
+ text_search: queryText,
2998
+ options,
2999
+ world,
3000
+ locate: false,
3001
+ scroll: false,
3002
+ highlight: false,
3003
+ type: Types.VERIFY_PAGE_TITLE,
3004
+ text: `Verify the page title is ${queryText}`,
3005
+ _text: `Verify the page title is ${queryText}`,
3006
+ operation: "verifyPageTitle",
3007
+ log: "***** verify page title is " + queryText + " *****\n",
3008
+ };
2331
3009
  try {
3010
+ await _preCommand(state, this);
3011
+ state.info.text = queryText;
2332
3012
  for (let i = 0; i < 30; i++) {
2333
3013
  const foundTitle = await this.page.title();
2334
- if (!foundTitle.includes(title)) {
2335
- if (i === 29) {
2336
- throw new Error(`url ${foundTitle} doesn't contain ${title}`);
2337
- }
2338
- await new Promise((resolve) => setTimeout(resolve, 1000));
2339
- continue;
3014
+ switch (matcher) {
3015
+ case "exact":
3016
+ if (foundTitle !== queryText) {
3017
+ if (i === 29) {
3018
+ throw new Error(`Page Title ${foundTitle} is not equal to ${queryText}`);
3019
+ }
3020
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3021
+ continue;
3022
+ }
3023
+ break;
3024
+ case "contains":
3025
+ if (!foundTitle.includes(queryText)) {
3026
+ if (i === 29) {
3027
+ throw new Error(`Page Title ${foundTitle} doesn't contain ${queryText}`);
3028
+ }
3029
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3030
+ continue;
3031
+ }
3032
+ break;
3033
+ case "starts-with":
3034
+ if (!foundTitle.startsWith(queryText)) {
3035
+ if (i === 29) {
3036
+ throw new Error(`Page title ${foundTitle} doesn't start with ${queryText}`);
3037
+ }
3038
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3039
+ continue;
3040
+ }
3041
+ break;
3042
+ case "ends-with":
3043
+ if (!foundTitle.endsWith(queryText)) {
3044
+ if (i === 29) {
3045
+ throw new Error(`Page Title ${foundTitle} doesn't end with ${queryText}`);
3046
+ }
3047
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3048
+ continue;
3049
+ }
3050
+ break;
3051
+ case "regex":
3052
+ const regex = new RegExp(queryText.slice(1, -1), "g");
3053
+ if (!regex.test(foundTitle)) {
3054
+ if (i === 29) {
3055
+ throw new Error(`Page Title ${foundTitle} doesn't match regex ${queryText}`);
3056
+ }
3057
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3058
+ continue;
3059
+ }
3060
+ break;
3061
+ default:
3062
+ console.log("Unknown matching type, defaulting to contains matching");
3063
+ if (!foundTitle.includes(title)) {
3064
+ if (i === 29) {
3065
+ throw new Error(`Page Title ${foundTitle} does not contain ${title}`);
3066
+ }
3067
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3068
+ continue;
3069
+ }
2340
3070
  }
2341
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2342
- return info;
3071
+ await _screenshot(state, this);
3072
+ return state.info;
2343
3073
  }
2344
3074
  }
2345
3075
  catch (e) {
2346
- //await this.closeUnexpectedPopups();
2347
- this.logger.error("verify page title failed " + info.log);
2348
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2349
- info.screenshotPath = screenshotPath;
2350
- Object.assign(e, { info: info });
2351
- error = e;
2352
- // throw e;
2353
- await _commandError({ text: "verifyPageTitle", operation: "verifyPageTitle", title, info, throwError: true }, e, this);
3076
+ state.info.failCause.lastError = e.message;
3077
+ state.info.failCause.assertionFailed = true;
3078
+ await _commandError(state, e, this);
2354
3079
  }
2355
3080
  finally {
2356
- const endTime = Date.now();
2357
- _reportToWorld(world, {
2358
- type: Types.VERIFY_PAGE_PATH,
2359
- text: "Verify page title",
2360
- _text: "Verify the page title contains " + title,
2361
- screenshotId,
2362
- result: error
2363
- ? {
2364
- status: "FAILED",
2365
- startTime,
2366
- endTime,
2367
- message: error?.message,
2368
- }
2369
- : {
2370
- status: "PASSED",
2371
- startTime,
2372
- endTime,
2373
- },
2374
- info: info,
2375
- });
3081
+ await _commandFinally(state, this);
2376
3082
  }
2377
3083
  }
2378
3084
  async findTextInAllFrames(dateAlternatives, numberAlternatives, text, state, partial = true, ignoreCase = false) {
@@ -2414,7 +3120,7 @@ class StableBrowser {
2414
3120
  scroll: false,
2415
3121
  highlight: false,
2416
3122
  type: Types.VERIFY_PAGE_CONTAINS_TEXT,
2417
- text: `Verify the text '${text}' exists in page`,
3123
+ text: `Verify the text '${maskValue(text)}' exists in page`,
2418
3124
  _text: `Verify the text '${text}' exists in page`,
2419
3125
  operation: "verifyTextExistInPage",
2420
3126
  log: "***** verify text " + text + " exists in page *****\n",
@@ -2456,27 +3162,10 @@ class StableBrowser {
2456
3162
  const frame = resultWithElementsFound[0].frame;
2457
3163
  const dataAttribute = `[data-blinq-id-${resultWithElementsFound[0].randomToken}]`;
2458
3164
  await this._highlightElements(frame, dataAttribute);
2459
- // if (world && world.screenshot && !world.screenshotPath) {
2460
- // console.log(`Highlighting for verify text is found while running from recorder`);
2461
- // this._highlightElements(frame, dataAttribute).then(async () => {
2462
- // await new Promise((resolve) => setTimeout(resolve, 1000));
2463
- // this._unhighlightElements(frame, dataAttribute)
2464
- // .then(async () => {
2465
- // console.log(`Unhighlighted frame dataAttribute successfully`);
2466
- // })
2467
- // .catch(
2468
- // (e) => {}
2469
- // console.error(e)
2470
- // );
2471
- // });
2472
- // }
2473
3165
  const element = await frame.locator(dataAttribute).first();
2474
- // await new Promise((resolve) => setTimeout(resolve, 100));
2475
- // await this._unhighlightElements(frame, dataAttribute);
2476
3166
  if (element) {
2477
3167
  await this.scrollIfNeeded(element, state.info);
2478
3168
  await element.dispatchEvent("bvt_verify_page_contains_text");
2479
- // await _screenshot(state, this, element);
2480
3169
  }
2481
3170
  }
2482
3171
  await _screenshot(state, this);
@@ -2486,13 +3175,12 @@ class StableBrowser {
2486
3175
  console.error(error);
2487
3176
  }
2488
3177
  }
2489
- // await expect(element).toHaveCount(1, { timeout: 10000 });
2490
3178
  }
2491
3179
  catch (e) {
2492
3180
  await _commandError(state, e, this);
2493
3181
  }
2494
3182
  finally {
2495
- _commandFinally(state, this);
3183
+ await _commandFinally(state, this);
2496
3184
  }
2497
3185
  }
2498
3186
  async waitForTextToDisappear(text, options = {}, world = null) {
@@ -2505,7 +3193,7 @@ class StableBrowser {
2505
3193
  scroll: false,
2506
3194
  highlight: false,
2507
3195
  type: Types.WAIT_FOR_TEXT_TO_DISAPPEAR,
2508
- text: `Verify the text '${text}' does not exist in page`,
3196
+ text: `Verify the text '${maskValue(text)}' does not exist in page`,
2509
3197
  _text: `Verify the text '${text}' does not exist in page`,
2510
3198
  operation: "verifyTextNotExistInPage",
2511
3199
  log: "***** verify text " + text + " does not exist in page *****\n",
@@ -2549,7 +3237,7 @@ class StableBrowser {
2549
3237
  await _commandError(state, e, this);
2550
3238
  }
2551
3239
  finally {
2552
- _commandFinally(state, this);
3240
+ await _commandFinally(state, this);
2553
3241
  }
2554
3242
  }
2555
3243
  async verifyTextRelatedToText(textAnchor, climb, textToVerify, options = {}, world = null) {
@@ -2660,7 +3348,7 @@ class StableBrowser {
2660
3348
  await _commandError(state, e, this);
2661
3349
  }
2662
3350
  finally {
2663
- _commandFinally(state, this);
3351
+ await _commandFinally(state, this);
2664
3352
  }
2665
3353
  }
2666
3354
  async findRelatedTextInAllFrames(textAnchor, climb, textToVerify, params = {}, options = {}, world = null) {
@@ -3002,8 +3690,51 @@ class StableBrowser {
3002
3690
  });
3003
3691
  }
3004
3692
  }
3693
+ /**
3694
+ * Explicit wait/sleep function that pauses execution for a specified duration
3695
+ * @param duration - Duration to sleep in milliseconds (default: 1000ms)
3696
+ * @param options - Optional configuration object
3697
+ * @param world - Optional world context
3698
+ * @returns Promise that resolves after the specified duration
3699
+ */
3700
+ async sleep(duration = 1000, options = {}, world = null) {
3701
+ const state = {
3702
+ duration,
3703
+ options,
3704
+ world,
3705
+ locate: false,
3706
+ scroll: false,
3707
+ screenshot: false,
3708
+ highlight: false,
3709
+ type: Types.SLEEP,
3710
+ text: `Sleep for ${duration} ms`,
3711
+ _text: `Sleep for ${duration} ms`,
3712
+ operation: "sleep",
3713
+ log: `***** Sleep for ${duration} ms *****\n`,
3714
+ };
3715
+ try {
3716
+ await _preCommand(state, this);
3717
+ if (duration < 0) {
3718
+ throw new Error("Sleep duration cannot be negative");
3719
+ }
3720
+ await new Promise((resolve) => setTimeout(resolve, duration));
3721
+ return state.info;
3722
+ }
3723
+ catch (e) {
3724
+ await _commandError(state, e, this);
3725
+ }
3726
+ finally {
3727
+ await _commandFinally(state, this);
3728
+ }
3729
+ }
3005
3730
  async _replaceWithLocalData(value, world, _decrypt = true, totpWait = true) {
3006
- return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
3731
+ try {
3732
+ return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
3733
+ }
3734
+ catch (error) {
3735
+ this.logger.debug(error);
3736
+ throw error;
3737
+ }
3007
3738
  }
3008
3739
  _getLoadTimeout(options) {
3009
3740
  let timeout = 15000;
@@ -3026,6 +3757,7 @@ class StableBrowser {
3026
3757
  }
3027
3758
  async saveStoreState(path = null, world = null) {
3028
3759
  const storageState = await this.page.context().storageState();
3760
+ path = await this._replaceWithLocalData(path, this.world);
3029
3761
  //const testDataFile = _getDataFile(world, this.context, this);
3030
3762
  if (path) {
3031
3763
  // save { storageState: storageState } into the path
@@ -3036,10 +3768,14 @@ class StableBrowser {
3036
3768
  }
3037
3769
  }
3038
3770
  async restoreSaveState(path = null, world = null) {
3771
+ path = await this._replaceWithLocalData(path, this.world);
3039
3772
  await refreshBrowser(this, path, world);
3040
3773
  this.registerEventListeners(this.context);
3041
3774
  registerNetworkEvents(this.world, this, this.context, this.page);
3042
3775
  registerDownloadEvent(this.page, this.world, this.context);
3776
+ if (this.onRestoreSaveState) {
3777
+ this.onRestoreSaveState(path);
3778
+ }
3043
3779
  }
3044
3780
  async waitForPageLoad(options = {}, world = null) {
3045
3781
  let timeout = this._getLoadTimeout(options);
@@ -3074,7 +3810,6 @@ class StableBrowser {
3074
3810
  else if (e.label === "domcontentloaded") {
3075
3811
  console.log("waited for the domcontent loaded timeout");
3076
3812
  }
3077
- console.log(".");
3078
3813
  }
3079
3814
  finally {
3080
3815
  await new Promise((resolve) => setTimeout(resolve, 2000));
@@ -3118,11 +3853,10 @@ class StableBrowser {
3118
3853
  await this.page.close();
3119
3854
  }
3120
3855
  catch (e) {
3121
- console.log(".");
3122
3856
  await _commandError(state, e, this);
3123
3857
  }
3124
3858
  finally {
3125
- _commandFinally(state, this);
3859
+ await _commandFinally(state, this);
3126
3860
  }
3127
3861
  }
3128
3862
  async tableCellOperation(headerText, rowText, options, _params, world = null) {
@@ -3209,7 +3943,7 @@ class StableBrowser {
3209
3943
  await _commandError(state, e, this);
3210
3944
  }
3211
3945
  finally {
3212
- _commandFinally(state, this);
3946
+ await _commandFinally(state, this);
3213
3947
  }
3214
3948
  }
3215
3949
  saveTestDataAsGlobal(options, world) {
@@ -3233,7 +3967,6 @@ class StableBrowser {
3233
3967
  await this.page.setViewportSize({ width: width, height: hight });
3234
3968
  }
3235
3969
  catch (e) {
3236
- console.log(".");
3237
3970
  await _commandError({ text: "setViewportSize", operation: "setViewportSize", width, hight, info }, e, this);
3238
3971
  }
3239
3972
  finally {
@@ -3271,7 +4004,6 @@ class StableBrowser {
3271
4004
  await this.page.reload();
3272
4005
  }
3273
4006
  catch (e) {
3274
- console.log(".");
3275
4007
  await _commandError({ text: "reloadPage", operation: "reloadPage", info }, e, this);
3276
4008
  }
3277
4009
  finally {
@@ -3314,7 +4046,42 @@ class StableBrowser {
3314
4046
  console.log("#-#");
3315
4047
  }
3316
4048
  }
4049
+ async beforeScenario(world, scenario) {
4050
+ if (world && world.attach) {
4051
+ world.attach(this.context.reportFolder, { mediaType: "text/plain" });
4052
+ }
4053
+ this.beforeScenarioCalled = true;
4054
+ if (scenario && scenario.pickle && scenario.pickle.name) {
4055
+ this.scenarioName = scenario.pickle.name;
4056
+ }
4057
+ if (scenario && scenario.gherkinDocument && scenario.gherkinDocument.feature) {
4058
+ this.featureName = scenario.gherkinDocument.feature.name;
4059
+ }
4060
+ if (this.context) {
4061
+ this.context.examplesRow = extractStepExampleParameters(scenario);
4062
+ }
4063
+ if (this.tags === null && scenario && scenario.pickle && scenario.pickle.tags) {
4064
+ this.tags = scenario.pickle.tags.map((tag) => tag.name);
4065
+ // check if @global_test_data tag is present
4066
+ if (this.tags.includes("@global_test_data")) {
4067
+ this.saveTestDataAsGlobal({}, world);
4068
+ }
4069
+ }
4070
+ // update test data based on feature/scenario
4071
+ let envName = null;
4072
+ if (this.context && this.context.environment) {
4073
+ envName = this.context.environment.name;
4074
+ }
4075
+ if (!process.env.TEMP_RUN) {
4076
+ await getTestData(envName, world, undefined, this.featureName, this.scenarioName, this.context);
4077
+ }
4078
+ await loadBrunoParams(this.context, this.context.environment.name);
4079
+ }
4080
+ async afterScenario(world, scenario) { }
3317
4081
  async beforeStep(world, step) {
4082
+ if (!this.beforeScenarioCalled) {
4083
+ this.beforeScenario(world, step);
4084
+ }
3318
4085
  if (this.stepIndex === undefined) {
3319
4086
  this.stepIndex = 0;
3320
4087
  }
@@ -3331,30 +4098,23 @@ class StableBrowser {
3331
4098
  else {
3332
4099
  this.stepName = "step " + this.stepIndex;
3333
4100
  }
3334
- if (this.context) {
3335
- this.context.examplesRow = extractStepExampleParameters(step);
3336
- }
3337
4101
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
3338
4102
  if (this.context.browserObject.context) {
3339
4103
  await this.context.browserObject.context.tracing.startChunk({ title: this.stepName });
3340
4104
  }
3341
4105
  }
3342
- if (this.tags === null && step && step.pickle && step.pickle.tags) {
3343
- this.tags = step.pickle.tags.map((tag) => tag.name);
3344
- // check if @global_test_data tag is present
3345
- if (this.tags.includes("@global_test_data")) {
3346
- this.saveTestDataAsGlobal({}, world);
3347
- }
3348
- }
3349
4106
  if (this.initSnapshotTaken === false) {
3350
4107
  this.initSnapshotTaken = true;
3351
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4108
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
3352
4109
  const snapshot = await this.getAriaSnapshot();
3353
4110
  if (snapshot) {
3354
4111
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-before");
3355
4112
  }
3356
4113
  }
3357
4114
  }
4115
+ this.context.routeResults = null;
4116
+ await registerBeforeStepRoutes(this.context, this.stepName);
4117
+ networkBeforeStep(this.stepName);
3358
4118
  }
3359
4119
  async getAriaSnapshot() {
3360
4120
  try {
@@ -3370,18 +4130,74 @@ class StableBrowser {
3370
4130
  const content = [`- path: ${path}`, `- title: ${title}`];
3371
4131
  const timeout = this.configuration.ariaSnapshotTimeout ? this.configuration.ariaSnapshotTimeout : 3000;
3372
4132
  for (let i = 0; i < frames.length; i++) {
3373
- content.push(`- frame: ${i}`);
3374
4133
  const frame = frames[i];
3375
- const snapshot = await frame.locator("body").ariaSnapshot({ timeout });
3376
- content.push(snapshot);
4134
+ try {
4135
+ // Ensure frame is attached and has body
4136
+ const body = frame.locator("body");
4137
+ //await body.waitFor({ timeout: 2000 }); // wait explicitly
4138
+ const snapshot = await body.ariaSnapshot({ timeout });
4139
+ if (!snapshot) {
4140
+ continue;
4141
+ }
4142
+ content.push(`- frame: ${i}`);
4143
+ content.push(snapshot);
4144
+ }
4145
+ catch (innerErr) {
4146
+ console.warn(`Frame ${i} snapshot failed:`, innerErr);
4147
+ content.push(`- frame: ${i} - error: ${innerErr.message}`);
4148
+ }
3377
4149
  }
3378
4150
  return content.join("\n");
3379
4151
  }
3380
4152
  catch (e) {
3381
- console.error(e);
4153
+ console.log("Error in getAriaSnapshot");
4154
+ //console.debug(e);
3382
4155
  }
3383
4156
  return null;
3384
4157
  }
4158
+ /**
4159
+ * Sends command with custom payload to report.
4160
+ * @param commandText - Title of the command to be shown in the report.
4161
+ * @param commandStatus - Status of the command (e.g. "PASSED", "FAILED").
4162
+ * @param content - Content of the command to be shown in the report.
4163
+ * @param options - Options for the command. Example: { type: "json", screenshot: true }
4164
+ * @param world - Optional world context.
4165
+ * @public
4166
+ */
4167
+ async addCommandToReport(commandText, commandStatus, content, options = {}, world = null) {
4168
+ const state = {
4169
+ options,
4170
+ world,
4171
+ locate: false,
4172
+ scroll: false,
4173
+ screenshot: options.screenshot ?? false,
4174
+ highlight: options.highlight ?? false,
4175
+ type: Types.REPORT_COMMAND,
4176
+ text: commandText,
4177
+ _text: commandText,
4178
+ operation: "report_command",
4179
+ log: "***** " + commandText + " *****\n",
4180
+ };
4181
+ try {
4182
+ await _preCommand(state, this);
4183
+ const payload = {
4184
+ type: options.type ?? "text",
4185
+ content: content,
4186
+ screenshotId: null,
4187
+ };
4188
+ state.payload = payload;
4189
+ if (commandStatus === "FAILED") {
4190
+ state.throwError = true;
4191
+ throw new Error("Command failed");
4192
+ }
4193
+ }
4194
+ catch (e) {
4195
+ await _commandError(state, e, this);
4196
+ }
4197
+ finally {
4198
+ await _commandFinally(state, this);
4199
+ }
4200
+ }
3385
4201
  async afterStep(world, step) {
3386
4202
  this.stepName = null;
3387
4203
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
@@ -3389,10 +4205,12 @@ class StableBrowser {
3389
4205
  await this.context.browserObject.context.tracing.stopChunk({
3390
4206
  path: path.join(this.context.browserObject.traceFolder, `trace-${this.stepIndex}.zip`),
3391
4207
  });
3392
- await world.attach(JSON.stringify({
3393
- type: "trace",
3394
- traceFilePath: `trace-${this.stepIndex}.zip`,
3395
- }), "application/json+trace");
4208
+ if (world && world.attach) {
4209
+ await world.attach(JSON.stringify({
4210
+ type: "trace",
4211
+ traceFilePath: `trace-${this.stepIndex}.zip`,
4212
+ }), "application/json+trace");
4213
+ }
3396
4214
  // console.log("trace file created", `trace-${this.stepIndex}.zip`);
3397
4215
  }
3398
4216
  }
@@ -3406,6 +4224,31 @@ class StableBrowser {
3406
4224
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-after");
3407
4225
  }
3408
4226
  }
4227
+ this.context.routeResults = await registerAfterStepRoutes(this.context, world);
4228
+ if (!process.env.TEMP_RUN) {
4229
+ const state = {
4230
+ world,
4231
+ locate: false,
4232
+ scroll: false,
4233
+ screenshot: true,
4234
+ highlight: true,
4235
+ type: Types.STEP_COMPLETE,
4236
+ text: "end of scenario",
4237
+ _text: "end of scenario",
4238
+ operation: "step_complete",
4239
+ log: "***** " + "end of scenario" + " *****\n",
4240
+ };
4241
+ try {
4242
+ await _preCommand(state, this);
4243
+ }
4244
+ catch (e) {
4245
+ await _commandError(state, e, this);
4246
+ }
4247
+ finally {
4248
+ await _commandFinally(state, this);
4249
+ }
4250
+ }
4251
+ networkAfterStep(this.stepName);
3409
4252
  }
3410
4253
  }
3411
4254
  function createTimedPromise(promise, label) {