automation_model 1.0.663-dev → 1.0.663-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 (60) 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 +1 -1
  7. package/lib/auto_page.js +145 -58
  8. package/lib/auto_page.js.map +1 -1
  9. package/lib/browser_manager.js +28 -8
  10. package/lib/browser_manager.js.map +1 -1
  11. package/lib/bruno.d.ts +1 -0
  12. package/lib/bruno.js +229 -18
  13. package/lib/bruno.js.map +1 -1
  14. package/lib/command_common.d.ts +1 -1
  15. package/lib/command_common.js +24 -4
  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 +2 -0
  28. package/lib/index.js +2 -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.js.map +1 -1
  38. package/lib/route.d.ts +33 -0
  39. package/lib/route.js +274 -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 +63 -25
  46. package/lib/stable_browser.js +1036 -223
  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 +15 -0
  53. package/lib/table_helper.js.map +1 -1
  54. package/lib/test_context.d.ts +1 -0
  55. package/lib/test_context.js +1 -0
  56. package/lib/test_context.js.map +1 -1
  57. package/lib/utils.d.ts +15 -2
  58. package/lib/utils.js +92 -58
  59. package/lib/utils.js.map +1 -1
  60. package/package.json +13 -7
@@ -10,11 +10,12 @@ 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";
@@ -22,23 +23,29 @@ import { 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,9 +217,35 @@ 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
+ }
182
223
  }
183
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
+ }
246
+ }
247
+ throw new Error("Tab not found: " + tabTitleOrIndex);
248
+ }
184
249
  registerConsoleLogListener(page, context) {
185
250
  if (!this.context.webLogger) {
186
251
  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
  }
@@ -459,7 +583,7 @@ class StableBrowser {
459
583
  }
460
584
  return;
461
585
  }
462
- if (info.locatorLog && count === 0) {
586
+ if (info.locatorLog && count === 0 && logErrors) {
463
587
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "NOT_FOUND");
464
588
  }
465
589
  for (let j = 0; j < count; j++) {
@@ -474,7 +598,7 @@ class StableBrowser {
474
598
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "FOUND");
475
599
  }
476
600
  }
477
- else {
601
+ else if (logErrors) {
478
602
  info.failCause.visible = visible;
479
603
  info.failCause.enabled = enabled;
480
604
  if (!info.printMessages) {
@@ -566,7 +690,7 @@ class StableBrowser {
566
690
  let element = await this._locate_internal(selectors, info, _params, timeout, allowDisabled);
567
691
  if (!element.rerun) {
568
692
  const randomToken = Math.random().toString(36).substring(7);
569
- element.evaluate((el, randomToken) => {
693
+ await element.evaluate((el, randomToken) => {
570
694
  el.setAttribute("data-blinq-id-" + randomToken, "");
571
695
  }, randomToken);
572
696
  // if (element._frame) {
@@ -580,7 +704,7 @@ class StableBrowser {
580
704
  if (frameSelectorIndex !== -1) {
581
705
  // remove everything after the >> internal:control=enter-frame
582
706
  const frameSelector = element._selector.substring(0, frameSelectorIndex);
583
- prefixSelector = frameSelector + " >> internal:control=enter-frame";
707
+ prefixSelector = frameSelector + " >> internal:control=enter-frame >>";
584
708
  }
585
709
  // if (element?._frame?._selector) {
586
710
  // prefixSelector = element._frame._selector + " >> " + prefixSelector;
@@ -815,7 +939,7 @@ class StableBrowser {
815
939
  }
816
940
  throw new Error("failed to locate first element no elements found, " + info.log);
817
941
  }
818
- 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) {
819
943
  let foundElements = [];
820
944
  const result = {
821
945
  foundElements: foundElements,
@@ -834,7 +958,9 @@ class StableBrowser {
834
958
  await this._collectLocatorInformation(locatorsGroup, i, this.page, foundLocators, _params, info, visibleOnly, allowDisabled, element_name);
835
959
  }
836
960
  catch (e) {
837
- 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
+ }
838
964
  }
839
965
  }
840
966
  if (foundLocators.length === 1) {
@@ -875,7 +1001,7 @@ class StableBrowser {
875
1001
  });
876
1002
  result.locatorIndex = i;
877
1003
  }
878
- else {
1004
+ else if (logErrors) {
879
1005
  info.failCause.foundMultiple = true;
880
1006
  if (info.locatorLog) {
881
1007
  info.locatorLog.setLocatorSearchStatus(JSON.stringify(locatorsGroup[i]), "FOUND_NOT_UNIQUE");
@@ -927,7 +1053,7 @@ class StableBrowser {
927
1053
  await _commandError(state, "timeout looking for " + elementDescription, this);
928
1054
  }
929
1055
  finally {
930
- _commandFinally(state, this);
1056
+ await _commandFinally(state, this);
931
1057
  }
932
1058
  }
933
1059
  }
@@ -976,7 +1102,7 @@ class StableBrowser {
976
1102
  await _commandError(state, "timeout looking for " + elementDescription, this);
977
1103
  }
978
1104
  finally {
979
- _commandFinally(state, this);
1105
+ await _commandFinally(state, this);
980
1106
  }
981
1107
  }
982
1108
  }
@@ -998,14 +1124,16 @@ class StableBrowser {
998
1124
  try {
999
1125
  await _preCommand(state, this);
1000
1126
  await performAction("click", state.element, options, this, state, _params);
1001
- await this.waitForPageLoad();
1127
+ if (!this.fastMode) {
1128
+ await this.waitForPageLoad();
1129
+ }
1002
1130
  return state.info;
1003
1131
  }
1004
1132
  catch (e) {
1005
1133
  await _commandError(state, e, this);
1006
1134
  }
1007
1135
  finally {
1008
- _commandFinally(state, this);
1136
+ await _commandFinally(state, this);
1009
1137
  }
1010
1138
  }
1011
1139
  async waitForElement(selectors, _params, options = {}, world = null) {
@@ -1036,7 +1164,7 @@ class StableBrowser {
1036
1164
  // await _commandError(state, e, this);
1037
1165
  }
1038
1166
  finally {
1039
- _commandFinally(state, this);
1167
+ await _commandFinally(state, this);
1040
1168
  }
1041
1169
  return found;
1042
1170
  }
@@ -1061,7 +1189,7 @@ class StableBrowser {
1061
1189
  // if (world && world.screenshot && !world.screenshotPath) {
1062
1190
  // console.log(`Highlighting while running from recorder`);
1063
1191
  await this._highlightElements(state.element);
1064
- await state.element.setChecked(checked);
1192
+ await state.element.setChecked(checked, { timeout: 2000 });
1065
1193
  await new Promise((resolve) => setTimeout(resolve, 1000));
1066
1194
  // await this._unHighlightElements(element);
1067
1195
  // }
@@ -1073,11 +1201,28 @@ class StableBrowser {
1073
1201
  this.logger.info("element did not change its state, ignoring...");
1074
1202
  }
1075
1203
  else {
1204
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1076
1205
  //await this.closeUnexpectedPopups();
1077
1206
  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));
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
+ }
1081
1226
  }
1082
1227
  }
1083
1228
  await this.waitForPageLoad();
@@ -1087,7 +1232,7 @@ class StableBrowser {
1087
1232
  await _commandError(state, e, this);
1088
1233
  }
1089
1234
  finally {
1090
- _commandFinally(state, this);
1235
+ await _commandFinally(state, this);
1091
1236
  }
1092
1237
  }
1093
1238
  async hover(selectors, _params, options = {}, world = null) {
@@ -1113,7 +1258,7 @@ class StableBrowser {
1113
1258
  await _commandError(state, e, this);
1114
1259
  }
1115
1260
  finally {
1116
- _commandFinally(state, this);
1261
+ await _commandFinally(state, this);
1117
1262
  }
1118
1263
  }
1119
1264
  async selectOption(selectors, values, _params = null, options = {}, world = null) {
@@ -1149,7 +1294,7 @@ class StableBrowser {
1149
1294
  await _commandError(state, e, this);
1150
1295
  }
1151
1296
  finally {
1152
- _commandFinally(state, this);
1297
+ await _commandFinally(state, this);
1153
1298
  }
1154
1299
  }
1155
1300
  async type(_value, _params = null, options = {}, world = null) {
@@ -1195,7 +1340,7 @@ class StableBrowser {
1195
1340
  await _commandError(state, e, this);
1196
1341
  }
1197
1342
  finally {
1198
- _commandFinally(state, this);
1343
+ await _commandFinally(state, this);
1199
1344
  }
1200
1345
  }
1201
1346
  async setInputValue(selectors, value, _params = null, options = {}, world = null) {
@@ -1231,7 +1376,7 @@ class StableBrowser {
1231
1376
  await _commandError(state, e, this);
1232
1377
  }
1233
1378
  finally {
1234
- _commandFinally(state, this);
1379
+ await _commandFinally(state, this);
1235
1380
  }
1236
1381
  }
1237
1382
  async setDateTime(selectors, value, format = null, enter = false, _params = null, options = {}, world = null) {
@@ -1300,7 +1445,7 @@ class StableBrowser {
1300
1445
  await _commandError(state, e, this);
1301
1446
  }
1302
1447
  finally {
1303
- _commandFinally(state, this);
1448
+ await _commandFinally(state, this);
1304
1449
  }
1305
1450
  }
1306
1451
  async clickType(selectors, _value, enter = false, _params = null, options = {}, world = null) {
@@ -1373,7 +1518,9 @@ class StableBrowser {
1373
1518
  await new Promise((resolve) => setTimeout(resolve, 500));
1374
1519
  }
1375
1520
  }
1521
+ //if (!this.fastMode) {
1376
1522
  await _screenshot(state, this);
1523
+ //}
1377
1524
  if (enter === true) {
1378
1525
  await new Promise((resolve) => setTimeout(resolve, 2000));
1379
1526
  await this.page.keyboard.press("Enter");
@@ -1400,7 +1547,7 @@ class StableBrowser {
1400
1547
  await _commandError(state, e, this);
1401
1548
  }
1402
1549
  finally {
1403
- _commandFinally(state, this);
1550
+ await _commandFinally(state, this);
1404
1551
  }
1405
1552
  }
1406
1553
  async fill(selectors, value, enter = false, _params = null, options = {}, world = null) {
@@ -1430,7 +1577,42 @@ class StableBrowser {
1430
1577
  await _commandError(state, e, this);
1431
1578
  }
1432
1579
  finally {
1433
- _commandFinally(state, this);
1580
+ await _commandFinally(state, this);
1581
+ }
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);
1434
1616
  }
1435
1617
  }
1436
1618
  async getText(selectors, _params = null, options = {}, info = {}, world = null) {
@@ -1546,7 +1728,7 @@ class StableBrowser {
1546
1728
  await _commandError(state, e, this);
1547
1729
  }
1548
1730
  finally {
1549
- _commandFinally(state, this);
1731
+ await _commandFinally(state, this);
1550
1732
  }
1551
1733
  }
1552
1734
  async containsText(selectors, text, climb, _params = null, options = {}, world = null) {
@@ -1623,7 +1805,84 @@ class StableBrowser {
1623
1805
  throw e;
1624
1806
  }
1625
1807
  finally {
1626
- _commandFinally(state, this);
1808
+ await _commandFinally(state, this);
1809
+ }
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);
1627
1886
  }
1628
1887
  }
1629
1888
  async waitForUserInput(message, world = null) {
@@ -1766,12 +2025,7 @@ class StableBrowser {
1766
2025
  }
1767
2026
  }
1768
2027
  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;
2028
+ return _getTestData(world, this.context, this);
1775
2029
  }
1776
2030
  async _screenShot(options = {}, world = null, info = null) {
1777
2031
  // collect url/path/title
@@ -1922,7 +2176,7 @@ class StableBrowser {
1922
2176
  await _commandError(state, e, this);
1923
2177
  }
1924
2178
  finally {
1925
- _commandFinally(state, this);
2179
+ await _commandFinally(state, this);
1926
2180
  }
1927
2181
  }
1928
2182
  async extractAttribute(selectors, attribute, variable, _params = null, options = {}, world = null) {
@@ -1953,10 +2207,102 @@ class StableBrowser {
1953
2207
  case "value":
1954
2208
  state.value = await state.element.inputValue();
1955
2209
  break;
2210
+ case "text":
2211
+ state.value = await state.element.textContent();
2212
+ break;
1956
2213
  default:
1957
2214
  state.value = await state.element.getAttribute(attribute);
1958
2215
  break;
1959
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
+ }
1960
2306
  state.info.value = state.value;
1961
2307
  this.setTestData({ [variable]: state.value }, world);
1962
2308
  this.logger.info("set test data: " + variable + "=" + state.value);
@@ -1967,7 +2313,7 @@ class StableBrowser {
1967
2313
  await _commandError(state, e, this);
1968
2314
  }
1969
2315
  finally {
1970
- _commandFinally(state, this);
2316
+ await _commandFinally(state, this);
1971
2317
  }
1972
2318
  }
1973
2319
  async verifyAttribute(selectors, attribute, value, _params = null, options = {}, world = null) {
@@ -1992,12 +2338,15 @@ class StableBrowser {
1992
2338
  let expectedValue;
1993
2339
  try {
1994
2340
  await _preCommand(state, this);
1995
- expectedValue = state.value;
2341
+ expectedValue = await replaceWithLocalTestData(state.value, world);
1996
2342
  state.info.expectedValue = expectedValue;
1997
2343
  switch (attribute) {
1998
2344
  case "innerText":
1999
2345
  val = String(await state.element.innerText());
2000
2346
  break;
2347
+ case "text":
2348
+ val = String(await state.element.textContent());
2349
+ break;
2001
2350
  case "value":
2002
2351
  val = String(await state.element.inputValue());
2003
2352
  break;
@@ -2019,17 +2368,42 @@ class StableBrowser {
2019
2368
  let regex;
2020
2369
  if (expectedValue.startsWith("/") && expectedValue.endsWith("/")) {
2021
2370
  const patternBody = expectedValue.slice(1, -1);
2022
- regex = new RegExp(patternBody, "g");
2371
+ const processedPattern = patternBody.replace(/\n/g, ".*");
2372
+ regex = new RegExp(processedPattern, "gs");
2373
+ state.info.regex = true;
2023
2374
  }
2024
2375
  else {
2025
2376
  const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2026
2377
  regex = new RegExp(escapedPattern, "g");
2027
2378
  }
2028
- if (!val.match(regex)) {
2029
- let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2030
- state.info.failCause.assertionFailed = true;
2031
- state.info.failCause.lastError = errorMessage;
2032
- 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
+ }
2033
2407
  }
2034
2408
  return state.info;
2035
2409
  }
@@ -2037,7 +2411,224 @@ class StableBrowser {
2037
2411
  await _commandError(state, e, this);
2038
2412
  }
2039
2413
  finally {
2040
- _commandFinally(state, this);
2414
+ await _commandFinally(state, this);
2415
+ }
2416
+ }
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,
2433
+ };
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
+ try {
2559
+ await _preCommand(state, this);
2560
+ const startTime = Date.now();
2561
+ let conditionMet = false;
2562
+ let currentValue = null;
2563
+ const checkCondition = async () => {
2564
+ try {
2565
+ switch (condition.toLowerCase()) {
2566
+ case "checked":
2567
+ currentValue = await state.element.isChecked();
2568
+ return currentValue === true;
2569
+ case "unchecked":
2570
+ currentValue = await state.element.isChecked();
2571
+ return currentValue === false;
2572
+ case "visible":
2573
+ currentValue = await state.element.isVisible();
2574
+ return currentValue === true;
2575
+ case "hidden":
2576
+ currentValue = await state.element.isVisible();
2577
+ return currentValue === false;
2578
+ case "enabled":
2579
+ currentValue = await state.element.isDisabled();
2580
+ return currentValue === false;
2581
+ case "disabled":
2582
+ currentValue = await state.element.isDisabled();
2583
+ return currentValue === true;
2584
+ case "editable":
2585
+ currentValue = await String(await state.element.evaluate((element, prop) => element[prop], "isContentEditable"));
2586
+ return currentValue === true;
2587
+ default:
2588
+ state.info.message = `Unsupported condition: '${condition}'. Supported conditions are: checked, unchecked, visible, hidden, enabled, disabled, editable.`;
2589
+ state.info.success = false;
2590
+ return false;
2591
+ }
2592
+ }
2593
+ catch {
2594
+ return false;
2595
+ }
2596
+ };
2597
+ while (Date.now() - startTime < timeoutMs) {
2598
+ // Use milliseconds for comparison
2599
+ conditionMet = await checkCondition();
2600
+ if (conditionMet)
2601
+ break;
2602
+ await new Promise((res) => setTimeout(res, 50));
2603
+ }
2604
+ const actualWaitTime = Date.now() - startTime;
2605
+ state.info = {
2606
+ success: conditionMet,
2607
+ conditionMet,
2608
+ actualWaitTime,
2609
+ currentValue,
2610
+ message: conditionMet
2611
+ ? `Condition '${condition}' met after ${(actualWaitTime / 1000).toFixed(2)}s`
2612
+ : `Condition '${condition}' not met within ${timeout}s timeout`, // Use original seconds value
2613
+ };
2614
+ state.log += state.info.message + "\n";
2615
+ return state.info;
2616
+ }
2617
+ catch (e) {
2618
+ state.info = {
2619
+ success: false,
2620
+ conditionMet: false,
2621
+ actualWaitTime: timeoutMs, // Store as milliseconds
2622
+ currentValue: null,
2623
+ error: e.message,
2624
+ message: `Error during conditional wait: ${e.message}`,
2625
+ };
2626
+ state.log += `Error during conditional wait: ${e.message}\n`;
2627
+ await new Promise((resolve) => setTimeout(resolve, timeoutMs)); // Use milliseconds
2628
+ return state.info;
2629
+ }
2630
+ finally {
2631
+ await _commandFinally(state, this);
2041
2632
  }
2042
2633
  }
2043
2634
  async extractEmailData(emailAddress, options, world) {
@@ -2197,56 +2788,49 @@ class StableBrowser {
2197
2788
  console.debug(error);
2198
2789
  }
2199
2790
  }
2200
- // async _unhighlightElements(scope, css) {
2201
- // try {
2202
- // if (!scope) {
2203
- // return;
2204
- // }
2205
- // if (!css) {
2206
- // scope
2207
- // .evaluate((node) => {
2208
- // if (node && node.style) {
2209
- // if (!node.__previousOutline) {
2210
- // node.style.outline = "";
2211
- // } else {
2212
- // node.style.outline = node.__previousOutline;
2213
- // }
2214
- // }
2215
- // })
2216
- // .then(() => {})
2217
- // .catch((e) => {
2218
- // // console.log(`Error while unhighlighting node ${JSON.stringify(scope)}: ${e}`);
2219
- // });
2220
- // } else {
2221
- // scope
2222
- // .evaluate(([css]) => {
2223
- // if (!css) {
2224
- // return;
2225
- // }
2226
- // let elements = Array.from(document.querySelectorAll(css));
2227
- // for (i = 0; i < elements.length; i++) {
2228
- // let element = elements[i];
2229
- // if (!element.style) {
2230
- // return;
2231
- // }
2232
- // if (!element.__previousOutline) {
2233
- // element.style.outline = "";
2234
- // } else {
2235
- // element.style.outline = element.__previousOutline;
2236
- // }
2237
- // }
2238
- // })
2239
- // .then(() => {})
2240
- // .catch((e) => {
2241
- // // console.error(`Error while unhighlighting element in css: ${e}`);
2242
- // });
2243
- // }
2244
- // } catch (error) {
2245
- // // console.debug(error);
2246
- // }
2247
- // }
2791
+ _matcher(text) {
2792
+ if (!text) {
2793
+ return { matcher: "contains", queryText: "" };
2794
+ }
2795
+ if (text.length < 2) {
2796
+ return { matcher: "contains", queryText: text };
2797
+ }
2798
+ const split = text.split(":");
2799
+ const matcher = split[0].toLowerCase();
2800
+ const queryText = split.slice(1).join(":").trim();
2801
+ return { matcher, queryText };
2802
+ }
2803
+ _getDomain(url) {
2804
+ if (url.length === 0 || (!url.startsWith("http://") && !url.startsWith("https://"))) {
2805
+ return "";
2806
+ }
2807
+ let hostnameFragments = url.split("/")[2].split(".");
2808
+ if (hostnameFragments.some((fragment) => fragment.includes(":"))) {
2809
+ return hostnameFragments.join("-").split(":").join("-");
2810
+ }
2811
+ let n = hostnameFragments.length;
2812
+ let fragments = [...hostnameFragments];
2813
+ while (n > 0 && hostnameFragments[n - 1].length <= 3) {
2814
+ hostnameFragments.pop();
2815
+ n = hostnameFragments.length;
2816
+ }
2817
+ if (n == 0) {
2818
+ if (fragments[0] === "www")
2819
+ fragments = fragments.slice(1);
2820
+ return fragments.length > 1 ? fragments.slice(0, fragments.length - 1).join("-") : fragments.join("-");
2821
+ }
2822
+ if (hostnameFragments[0] === "www")
2823
+ hostnameFragments = hostnameFragments.slice(1);
2824
+ return hostnameFragments.join(".");
2825
+ }
2826
+ /**
2827
+ * Verify the page path matches the given path.
2828
+ * @param {string} pathPart - The path to verify.
2829
+ * @param {object} options - Options for verification.
2830
+ * @param {object} world - The world context.
2831
+ * @returns {Promise<object>} - The state info after verification.
2832
+ */
2248
2833
  async verifyPagePath(pathPart, options = {}, world = null) {
2249
- const startTime = Date.now();
2250
2834
  let error = null;
2251
2835
  let screenshotId = null;
2252
2836
  let screenshotPath = null;
@@ -2260,113 +2844,212 @@ class StableBrowser {
2260
2844
  pathPart = newValue;
2261
2845
  }
2262
2846
  info.pathPart = pathPart;
2847
+ const { matcher, queryText } = this._matcher(pathPart);
2848
+ const state = {
2849
+ text_search: queryText,
2850
+ options,
2851
+ world,
2852
+ locate: false,
2853
+ scroll: false,
2854
+ highlight: false,
2855
+ type: Types.VERIFY_PAGE_PATH,
2856
+ text: `Verify the page url is ${queryText}`,
2857
+ _text: `Verify the page url is ${queryText}`,
2858
+ operation: "verifyPagePath",
2859
+ log: "***** verify page url is " + queryText + " *****\n",
2860
+ };
2263
2861
  try {
2862
+ await _preCommand(state, this);
2863
+ state.info.text = queryText;
2264
2864
  for (let i = 0; i < 30; i++) {
2265
2865
  const url = await this.page.url();
2266
- if (!url.includes(pathPart)) {
2267
- if (i === 29) {
2268
- throw new Error(`url ${url} doesn't contain ${pathPart}`);
2269
- }
2270
- await new Promise((resolve) => setTimeout(resolve, 1000));
2271
- continue;
2866
+ switch (matcher) {
2867
+ case "exact":
2868
+ if (url !== queryText) {
2869
+ if (i === 29) {
2870
+ throw new Error(`Page URL ${url} is not equal to ${queryText}`);
2871
+ }
2872
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2873
+ continue;
2874
+ }
2875
+ break;
2876
+ case "contains":
2877
+ if (!url.includes(queryText)) {
2878
+ if (i === 29) {
2879
+ throw new Error(`Page URL ${url} doesn't contain ${queryText}`);
2880
+ }
2881
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2882
+ continue;
2883
+ }
2884
+ break;
2885
+ case "starts-with":
2886
+ {
2887
+ const domain = this._getDomain(url);
2888
+ if (domain.length > 0 && domain !== queryText) {
2889
+ if (i === 29) {
2890
+ throw new Error(`Page URL ${url} doesn't start with ${queryText}`);
2891
+ }
2892
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2893
+ continue;
2894
+ }
2895
+ }
2896
+ break;
2897
+ case "ends-with":
2898
+ {
2899
+ const urlObj = new URL(url);
2900
+ let route = "/";
2901
+ if (urlObj.pathname !== "/") {
2902
+ route = urlObj.pathname.split("/").slice(-1)[0].trim();
2903
+ }
2904
+ else {
2905
+ route = "/";
2906
+ }
2907
+ if (route !== queryText) {
2908
+ if (i === 29) {
2909
+ throw new Error(`Page URL ${url} doesn't end with ${queryText}`);
2910
+ }
2911
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2912
+ continue;
2913
+ }
2914
+ }
2915
+ break;
2916
+ case "regex":
2917
+ const regex = new RegExp(queryText.slice(1, -1), "g");
2918
+ if (!regex.test(url)) {
2919
+ if (i === 29) {
2920
+ throw new Error(`Page URL ${url} doesn't match regex ${queryText}`);
2921
+ }
2922
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2923
+ continue;
2924
+ }
2925
+ break;
2926
+ default:
2927
+ console.log("Unknown matching type, defaulting to contains matching");
2928
+ if (!url.includes(pathPart)) {
2929
+ if (i === 29) {
2930
+ throw new Error(`Page URL ${url} does not contain ${pathPart}`);
2931
+ }
2932
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2933
+ continue;
2934
+ }
2272
2935
  }
2273
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2274
- return info;
2936
+ await _screenshot(state, this);
2937
+ return state.info;
2275
2938
  }
2276
2939
  }
2277
2940
  catch (e) {
2278
- //await this.closeUnexpectedPopups();
2279
- this.logger.error("verify page path failed " + info.log);
2280
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2281
- info.screenshotPath = screenshotPath;
2282
- Object.assign(e, { info: info });
2283
- error = e;
2284
- // throw e;
2285
- await _commandError({ text: "verifyPagePath", operation: "verifyPagePath", pathPart, info }, e, this);
2941
+ state.info.failCause.lastError = e.message;
2942
+ state.info.failCause.assertionFailed = true;
2943
+ await _commandError(state, e, this);
2286
2944
  }
2287
2945
  finally {
2288
- const endTime = Date.now();
2289
- _reportToWorld(world, {
2290
- type: Types.VERIFY_PAGE_PATH,
2291
- text: "Verify page path",
2292
- _text: "Verify the page path contains " + pathPart,
2293
- screenshotId,
2294
- result: error
2295
- ? {
2296
- status: "FAILED",
2297
- startTime,
2298
- endTime,
2299
- message: error?.message,
2300
- }
2301
- : {
2302
- status: "PASSED",
2303
- startTime,
2304
- endTime,
2305
- },
2306
- info: info,
2307
- });
2946
+ await _commandFinally(state, this);
2308
2947
  }
2309
2948
  }
2949
+ /**
2950
+ * Verify the page title matches the given title.
2951
+ * @param {string} title - The title to verify.
2952
+ * @param {object} options - Options for verification.
2953
+ * @param {object} world - The world context.
2954
+ * @returns {Promise<object>} - The state info after verification.
2955
+ */
2310
2956
  async verifyPageTitle(title, options = {}, world = null) {
2311
- const startTime = Date.now();
2312
2957
  let error = null;
2313
2958
  let screenshotId = null;
2314
2959
  let screenshotPath = null;
2315
2960
  await new Promise((resolve) => setTimeout(resolve, 2000));
2316
- const info = {};
2317
- info.log = "***** verify page title " + title + " *****\n";
2318
- info.operation = "verifyPageTitle";
2319
2961
  const newValue = await this._replaceWithLocalData(title, world);
2320
2962
  if (newValue !== title) {
2321
2963
  this.logger.info(title + "=" + newValue);
2322
2964
  title = newValue;
2323
2965
  }
2324
- info.title = title;
2966
+ const { matcher, queryText } = this._matcher(title);
2967
+ const state = {
2968
+ text_search: queryText,
2969
+ options,
2970
+ world,
2971
+ locate: false,
2972
+ scroll: false,
2973
+ highlight: false,
2974
+ type: Types.VERIFY_PAGE_TITLE,
2975
+ text: `Verify the page title is ${queryText}`,
2976
+ _text: `Verify the page title is ${queryText}`,
2977
+ operation: "verifyPageTitle",
2978
+ log: "***** verify page title is " + queryText + " *****\n",
2979
+ };
2325
2980
  try {
2981
+ await _preCommand(state, this);
2982
+ state.info.text = queryText;
2326
2983
  for (let i = 0; i < 30; i++) {
2327
2984
  const foundTitle = await this.page.title();
2328
- if (!foundTitle.includes(title)) {
2329
- if (i === 29) {
2330
- throw new Error(`url ${foundTitle} doesn't contain ${title}`);
2331
- }
2332
- await new Promise((resolve) => setTimeout(resolve, 1000));
2333
- continue;
2985
+ switch (matcher) {
2986
+ case "exact":
2987
+ if (foundTitle !== queryText) {
2988
+ if (i === 29) {
2989
+ throw new Error(`Page Title ${foundTitle} is not equal to ${queryText}`);
2990
+ }
2991
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2992
+ continue;
2993
+ }
2994
+ break;
2995
+ case "contains":
2996
+ if (!foundTitle.includes(queryText)) {
2997
+ if (i === 29) {
2998
+ throw new Error(`Page Title ${foundTitle} doesn't contain ${queryText}`);
2999
+ }
3000
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3001
+ continue;
3002
+ }
3003
+ break;
3004
+ case "starts-with":
3005
+ if (!foundTitle.startsWith(queryText)) {
3006
+ if (i === 29) {
3007
+ throw new Error(`Page title ${foundTitle} doesn't start with ${queryText}`);
3008
+ }
3009
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3010
+ continue;
3011
+ }
3012
+ break;
3013
+ case "ends-with":
3014
+ if (!foundTitle.endsWith(queryText)) {
3015
+ if (i === 29) {
3016
+ throw new Error(`Page Title ${foundTitle} doesn't end with ${queryText}`);
3017
+ }
3018
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3019
+ continue;
3020
+ }
3021
+ break;
3022
+ case "regex":
3023
+ const regex = new RegExp(queryText.slice(1, -1), "g");
3024
+ if (!regex.test(foundTitle)) {
3025
+ if (i === 29) {
3026
+ throw new Error(`Page Title ${foundTitle} doesn't match regex ${queryText}`);
3027
+ }
3028
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3029
+ continue;
3030
+ }
3031
+ break;
3032
+ default:
3033
+ console.log("Unknown matching type, defaulting to contains matching");
3034
+ if (!foundTitle.includes(title)) {
3035
+ if (i === 29) {
3036
+ throw new Error(`Page Title ${foundTitle} does not contain ${title}`);
3037
+ }
3038
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3039
+ continue;
3040
+ }
2334
3041
  }
2335
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2336
- return info;
3042
+ await _screenshot(state, this);
3043
+ return state.info;
2337
3044
  }
2338
3045
  }
2339
3046
  catch (e) {
2340
- //await this.closeUnexpectedPopups();
2341
- this.logger.error("verify page title failed " + info.log);
2342
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2343
- info.screenshotPath = screenshotPath;
2344
- Object.assign(e, { info: info });
2345
- error = e;
2346
- // throw e;
2347
- await _commandError({ text: "verifyPageTitle", operation: "verifyPageTitle", title, info, throwError: true }, e, this);
3047
+ state.info.failCause.lastError = e.message;
3048
+ state.info.failCause.assertionFailed = true;
3049
+ await _commandError(state, e, this);
2348
3050
  }
2349
3051
  finally {
2350
- const endTime = Date.now();
2351
- _reportToWorld(world, {
2352
- type: Types.VERIFY_PAGE_PATH,
2353
- text: "Verify page title",
2354
- _text: "Verify the page title contains " + title,
2355
- screenshotId,
2356
- result: error
2357
- ? {
2358
- status: "FAILED",
2359
- startTime,
2360
- endTime,
2361
- message: error?.message,
2362
- }
2363
- : {
2364
- status: "PASSED",
2365
- startTime,
2366
- endTime,
2367
- },
2368
- info: info,
2369
- });
3052
+ await _commandFinally(state, this);
2370
3053
  }
2371
3054
  }
2372
3055
  async findTextInAllFrames(dateAlternatives, numberAlternatives, text, state, partial = true, ignoreCase = false) {
@@ -2408,7 +3091,7 @@ class StableBrowser {
2408
3091
  scroll: false,
2409
3092
  highlight: false,
2410
3093
  type: Types.VERIFY_PAGE_CONTAINS_TEXT,
2411
- text: `Verify the text '${text}' exists in page`,
3094
+ text: `Verify the text '${maskValue(text)}' exists in page`,
2412
3095
  _text: `Verify the text '${text}' exists in page`,
2413
3096
  operation: "verifyTextExistInPage",
2414
3097
  log: "***** verify text " + text + " exists in page *****\n",
@@ -2450,27 +3133,10 @@ class StableBrowser {
2450
3133
  const frame = resultWithElementsFound[0].frame;
2451
3134
  const dataAttribute = `[data-blinq-id-${resultWithElementsFound[0].randomToken}]`;
2452
3135
  await this._highlightElements(frame, dataAttribute);
2453
- // if (world && world.screenshot && !world.screenshotPath) {
2454
- // console.log(`Highlighting for verify text is found while running from recorder`);
2455
- // this._highlightElements(frame, dataAttribute).then(async () => {
2456
- // await new Promise((resolve) => setTimeout(resolve, 1000));
2457
- // this._unhighlightElements(frame, dataAttribute)
2458
- // .then(async () => {
2459
- // console.log(`Unhighlighted frame dataAttribute successfully`);
2460
- // })
2461
- // .catch(
2462
- // (e) => {}
2463
- // console.error(e)
2464
- // );
2465
- // });
2466
- // }
2467
3136
  const element = await frame.locator(dataAttribute).first();
2468
- // await new Promise((resolve) => setTimeout(resolve, 100));
2469
- // await this._unhighlightElements(frame, dataAttribute);
2470
3137
  if (element) {
2471
3138
  await this.scrollIfNeeded(element, state.info);
2472
3139
  await element.dispatchEvent("bvt_verify_page_contains_text");
2473
- // await _screenshot(state, this, element);
2474
3140
  }
2475
3141
  }
2476
3142
  await _screenshot(state, this);
@@ -2480,13 +3146,12 @@ class StableBrowser {
2480
3146
  console.error(error);
2481
3147
  }
2482
3148
  }
2483
- // await expect(element).toHaveCount(1, { timeout: 10000 });
2484
3149
  }
2485
3150
  catch (e) {
2486
3151
  await _commandError(state, e, this);
2487
3152
  }
2488
3153
  finally {
2489
- _commandFinally(state, this);
3154
+ await _commandFinally(state, this);
2490
3155
  }
2491
3156
  }
2492
3157
  async waitForTextToDisappear(text, options = {}, world = null) {
@@ -2499,7 +3164,7 @@ class StableBrowser {
2499
3164
  scroll: false,
2500
3165
  highlight: false,
2501
3166
  type: Types.WAIT_FOR_TEXT_TO_DISAPPEAR,
2502
- text: `Verify the text '${text}' does not exist in page`,
3167
+ text: `Verify the text '${maskValue(text)}' does not exist in page`,
2503
3168
  _text: `Verify the text '${text}' does not exist in page`,
2504
3169
  operation: "verifyTextNotExistInPage",
2505
3170
  log: "***** verify text " + text + " does not exist in page *****\n",
@@ -2543,7 +3208,7 @@ class StableBrowser {
2543
3208
  await _commandError(state, e, this);
2544
3209
  }
2545
3210
  finally {
2546
- _commandFinally(state, this);
3211
+ await _commandFinally(state, this);
2547
3212
  }
2548
3213
  }
2549
3214
  async verifyTextRelatedToText(textAnchor, climb, textToVerify, options = {}, world = null) {
@@ -2654,7 +3319,7 @@ class StableBrowser {
2654
3319
  await _commandError(state, e, this);
2655
3320
  }
2656
3321
  finally {
2657
- _commandFinally(state, this);
3322
+ await _commandFinally(state, this);
2658
3323
  }
2659
3324
  }
2660
3325
  async findRelatedTextInAllFrames(textAnchor, climb, textToVerify, params = {}, options = {}, world = null) {
@@ -2996,8 +3661,51 @@ class StableBrowser {
2996
3661
  });
2997
3662
  }
2998
3663
  }
3664
+ /**
3665
+ * Explicit wait/sleep function that pauses execution for a specified duration
3666
+ * @param duration - Duration to sleep in milliseconds (default: 1000ms)
3667
+ * @param options - Optional configuration object
3668
+ * @param world - Optional world context
3669
+ * @returns Promise that resolves after the specified duration
3670
+ */
3671
+ async sleep(duration = 1000, options = {}, world = null) {
3672
+ const state = {
3673
+ duration,
3674
+ options,
3675
+ world,
3676
+ locate: false,
3677
+ scroll: false,
3678
+ screenshot: false,
3679
+ highlight: false,
3680
+ type: Types.SLEEP,
3681
+ text: `Sleep for ${duration} ms`,
3682
+ _text: `Sleep for ${duration} ms`,
3683
+ operation: "sleep",
3684
+ log: `***** Sleep for ${duration} ms *****\n`,
3685
+ };
3686
+ try {
3687
+ await _preCommand(state, this);
3688
+ if (duration < 0) {
3689
+ throw new Error("Sleep duration cannot be negative");
3690
+ }
3691
+ await new Promise((resolve) => setTimeout(resolve, duration));
3692
+ return state.info;
3693
+ }
3694
+ catch (e) {
3695
+ await _commandError(state, e, this);
3696
+ }
3697
+ finally {
3698
+ await _commandFinally(state, this);
3699
+ }
3700
+ }
2999
3701
  async _replaceWithLocalData(value, world, _decrypt = true, totpWait = true) {
3000
- return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
3702
+ try {
3703
+ return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
3704
+ }
3705
+ catch (error) {
3706
+ this.logger.debug(error);
3707
+ throw error;
3708
+ }
3001
3709
  }
3002
3710
  _getLoadTimeout(options) {
3003
3711
  let timeout = 15000;
@@ -3020,6 +3728,7 @@ class StableBrowser {
3020
3728
  }
3021
3729
  async saveStoreState(path = null, world = null) {
3022
3730
  const storageState = await this.page.context().storageState();
3731
+ path = await this._replaceWithLocalData(path, this.world);
3023
3732
  //const testDataFile = _getDataFile(world, this.context, this);
3024
3733
  if (path) {
3025
3734
  // save { storageState: storageState } into the path
@@ -3030,10 +3739,14 @@ class StableBrowser {
3030
3739
  }
3031
3740
  }
3032
3741
  async restoreSaveState(path = null, world = null) {
3742
+ path = await this._replaceWithLocalData(path, this.world);
3033
3743
  await refreshBrowser(this, path, world);
3034
3744
  this.registerEventListeners(this.context);
3035
3745
  registerNetworkEvents(this.world, this, this.context, this.page);
3036
3746
  registerDownloadEvent(this.page, this.world, this.context);
3747
+ if (this.onRestoreSaveState) {
3748
+ this.onRestoreSaveState(path);
3749
+ }
3037
3750
  }
3038
3751
  async waitForPageLoad(options = {}, world = null) {
3039
3752
  let timeout = this._getLoadTimeout(options);
@@ -3116,7 +3829,7 @@ class StableBrowser {
3116
3829
  await _commandError(state, e, this);
3117
3830
  }
3118
3831
  finally {
3119
- _commandFinally(state, this);
3832
+ await _commandFinally(state, this);
3120
3833
  }
3121
3834
  }
3122
3835
  async tableCellOperation(headerText, rowText, options, _params, world = null) {
@@ -3203,7 +3916,7 @@ class StableBrowser {
3203
3916
  await _commandError(state, e, this);
3204
3917
  }
3205
3918
  finally {
3206
- _commandFinally(state, this);
3919
+ await _commandFinally(state, this);
3207
3920
  }
3208
3921
  }
3209
3922
  saveTestDataAsGlobal(options, world) {
@@ -3308,7 +4021,39 @@ class StableBrowser {
3308
4021
  console.log("#-#");
3309
4022
  }
3310
4023
  }
4024
+ async beforeScenario(world, scenario) {
4025
+ this.beforeScenarioCalled = true;
4026
+ if (scenario && scenario.pickle && scenario.pickle.name) {
4027
+ this.scenarioName = scenario.pickle.name;
4028
+ }
4029
+ if (scenario && scenario.gherkinDocument && scenario.gherkinDocument.feature) {
4030
+ this.featureName = scenario.gherkinDocument.feature.name;
4031
+ }
4032
+ if (this.context) {
4033
+ this.context.examplesRow = extractStepExampleParameters(scenario);
4034
+ }
4035
+ if (this.tags === null && scenario && scenario.pickle && scenario.pickle.tags) {
4036
+ this.tags = scenario.pickle.tags.map((tag) => tag.name);
4037
+ // check if @global_test_data tag is present
4038
+ if (this.tags.includes("@global_test_data")) {
4039
+ this.saveTestDataAsGlobal({}, world);
4040
+ }
4041
+ }
4042
+ // update test data based on feature/scenario
4043
+ let envName = null;
4044
+ if (this.context && this.context.environment) {
4045
+ envName = this.context.environment.name;
4046
+ }
4047
+ if (!process.env.TEMP_RUN) {
4048
+ await getTestData(envName, world, undefined, this.featureName, this.scenarioName, this.context);
4049
+ }
4050
+ await loadBrunoParams(this.context, this.context.environment.name);
4051
+ }
4052
+ async afterScenario(world, scenario) { }
3311
4053
  async beforeStep(world, step) {
4054
+ if (!this.beforeScenarioCalled) {
4055
+ this.beforeScenario(world, step);
4056
+ }
3312
4057
  if (this.stepIndex === undefined) {
3313
4058
  this.stepIndex = 0;
3314
4059
  }
@@ -3325,30 +4070,22 @@ class StableBrowser {
3325
4070
  else {
3326
4071
  this.stepName = "step " + this.stepIndex;
3327
4072
  }
3328
- if (this.context) {
3329
- this.context.examplesRow = extractStepExampleParameters(step);
3330
- }
3331
4073
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
3332
4074
  if (this.context.browserObject.context) {
3333
4075
  await this.context.browserObject.context.tracing.startChunk({ title: this.stepName });
3334
4076
  }
3335
4077
  }
3336
- if (this.tags === null && step && step.pickle && step.pickle.tags) {
3337
- this.tags = step.pickle.tags.map((tag) => tag.name);
3338
- // check if @global_test_data tag is present
3339
- if (this.tags.includes("@global_test_data")) {
3340
- this.saveTestDataAsGlobal({}, world);
3341
- }
3342
- }
3343
4078
  if (this.initSnapshotTaken === false) {
3344
4079
  this.initSnapshotTaken = true;
3345
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4080
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
3346
4081
  const snapshot = await this.getAriaSnapshot();
3347
4082
  if (snapshot) {
3348
4083
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-before");
3349
4084
  }
3350
4085
  }
3351
4086
  }
4087
+ this.context.routeResults = null;
4088
+ await registerBeforeStepRoutes(this.context, this.stepName);
3352
4089
  }
3353
4090
  async getAriaSnapshot() {
3354
4091
  try {
@@ -3364,18 +4101,68 @@ class StableBrowser {
3364
4101
  const content = [`- path: ${path}`, `- title: ${title}`];
3365
4102
  const timeout = this.configuration.ariaSnapshotTimeout ? this.configuration.ariaSnapshotTimeout : 3000;
3366
4103
  for (let i = 0; i < frames.length; i++) {
3367
- content.push(`- frame: ${i}`);
3368
4104
  const frame = frames[i];
3369
- const snapshot = await frame.locator("body").ariaSnapshot({ timeout });
3370
- content.push(snapshot);
4105
+ try {
4106
+ // Ensure frame is attached and has body
4107
+ const body = frame.locator("body");
4108
+ await body.waitFor({ timeout: 200 }); // wait explicitly
4109
+ const snapshot = await body.ariaSnapshot({ timeout });
4110
+ content.push(`- frame: ${i}`);
4111
+ content.push(snapshot);
4112
+ }
4113
+ catch (innerErr) { }
3371
4114
  }
3372
4115
  return content.join("\n");
3373
4116
  }
3374
4117
  catch (e) {
3375
- console.error(e);
4118
+ console.log("Error in getAriaSnapshot");
4119
+ //console.debug(e);
3376
4120
  }
3377
4121
  return null;
3378
4122
  }
4123
+ /**
4124
+ * Sends command with custom payload to report.
4125
+ * @param commandText - Title of the command to be shown in the report.
4126
+ * @param commandStatus - Status of the command (e.g. "PASSED", "FAILED").
4127
+ * @param content - Content of the command to be shown in the report.
4128
+ * @param options - Options for the command. Example: { type: "json", screenshot: true }
4129
+ * @param world - Optional world context.
4130
+ * @public
4131
+ */
4132
+ async addCommandToReport(commandText, commandStatus, content, options = {}, world = null) {
4133
+ const state = {
4134
+ options,
4135
+ world,
4136
+ locate: false,
4137
+ scroll: false,
4138
+ screenshot: options.screenshot ?? false,
4139
+ highlight: options.highlight ?? false,
4140
+ type: Types.REPORT_COMMAND,
4141
+ text: commandText,
4142
+ _text: commandText,
4143
+ operation: "report_command",
4144
+ log: "***** " + commandText + " *****\n",
4145
+ };
4146
+ try {
4147
+ await _preCommand(state, this);
4148
+ const payload = {
4149
+ type: options.type ?? "text",
4150
+ content: content,
4151
+ screenshotId: null,
4152
+ };
4153
+ state.payload = payload;
4154
+ if (commandStatus === "FAILED") {
4155
+ state.throwError = true;
4156
+ throw new Error("Command failed");
4157
+ }
4158
+ }
4159
+ catch (e) {
4160
+ await _commandError(state, e, this);
4161
+ }
4162
+ finally {
4163
+ await _commandFinally(state, this);
4164
+ }
4165
+ }
3379
4166
  async afterStep(world, step) {
3380
4167
  this.stepName = null;
3381
4168
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
@@ -3383,10 +4170,12 @@ class StableBrowser {
3383
4170
  await this.context.browserObject.context.tracing.stopChunk({
3384
4171
  path: path.join(this.context.browserObject.traceFolder, `trace-${this.stepIndex}.zip`),
3385
4172
  });
3386
- await world.attach(JSON.stringify({
3387
- type: "trace",
3388
- traceFilePath: `trace-${this.stepIndex}.zip`,
3389
- }), "application/json+trace");
4173
+ if (world && world.attach) {
4174
+ await world.attach(JSON.stringify({
4175
+ type: "trace",
4176
+ traceFilePath: `trace-${this.stepIndex}.zip`,
4177
+ }), "application/json+trace");
4178
+ }
3390
4179
  // console.log("trace file created", `trace-${this.stepIndex}.zip`);
3391
4180
  }
3392
4181
  }
@@ -3400,6 +4189,30 @@ class StableBrowser {
3400
4189
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-after");
3401
4190
  }
3402
4191
  }
4192
+ this.context.routeResults = await registerAfterStepRoutes(this.context, world);
4193
+ if (!process.env.TEMP_RUN) {
4194
+ const state = {
4195
+ world,
4196
+ locate: false,
4197
+ scroll: false,
4198
+ screenshot: true,
4199
+ highlight: true,
4200
+ type: Types.STEP_COMPLETE,
4201
+ text: "end of scenario",
4202
+ _text: "end of scenario",
4203
+ operation: "step_complete",
4204
+ log: "***** " + "end of scenario" + " *****\n",
4205
+ };
4206
+ try {
4207
+ await _preCommand(state, this);
4208
+ }
4209
+ catch (e) {
4210
+ await _commandError(state, e, this);
4211
+ }
4212
+ finally {
4213
+ await _commandFinally(state, this);
4214
+ }
4215
+ }
3403
4216
  }
3404
4217
  }
3405
4218
  function createTimedPromise(promise, label) {