automation_model 1.0.680-dev → 1.0.680-stage

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +4 -1
  2. package/lib/analyze_helper.js.map +1 -1
  3. package/lib/api.d.ts +0 -1
  4. package/lib/api.js.map +1 -1
  5. package/lib/auto_page.d.ts +4 -2
  6. package/lib/auto_page.js +181 -59
  7. package/lib/auto_page.js.map +1 -1
  8. package/lib/browser_manager.js +31 -8
  9. package/lib/browser_manager.js.map +1 -1
  10. package/lib/bruno.d.ts +1 -0
  11. package/lib/bruno.js +120 -21
  12. package/lib/bruno.js.map +1 -1
  13. package/lib/command_common.js +9 -1
  14. package/lib/command_common.js.map +1 -1
  15. package/lib/date_time.js.map +1 -1
  16. package/lib/drawRect.js.map +1 -1
  17. package/lib/environment.d.ts +1 -0
  18. package/lib/environment.js +1 -0
  19. package/lib/environment.js.map +1 -1
  20. package/lib/error-messages.js.map +1 -1
  21. package/lib/file_checker.d.ts +1 -0
  22. package/lib/file_checker.js +61 -0
  23. package/lib/file_checker.js.map +1 -0
  24. package/lib/find_function.js.map +1 -1
  25. package/lib/index.d.ts +1 -0
  26. package/lib/index.js +1 -0
  27. package/lib/index.js.map +1 -1
  28. package/lib/init_browser.js +4 -4
  29. package/lib/init_browser.js.map +1 -1
  30. package/lib/locate_element.js.map +1 -1
  31. package/lib/locator.d.ts +1 -0
  32. package/lib/locator.js +10 -3
  33. package/lib/locator.js.map +1 -1
  34. package/lib/locator_log.js.map +1 -1
  35. package/lib/network.d.ts +2 -0
  36. package/lib/network.js +148 -0
  37. package/lib/network.js.map +1 -1
  38. package/lib/route.d.ts +21 -0
  39. package/lib/route.js +408 -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 +1105 -254
  47. package/lib/stable_browser.js.map +1 -1
  48. package/lib/table.d.ts +9 -7
  49. package/lib/table.js +82 -12
  50. package/lib/table.js.map +1 -1
  51. package/lib/table_analyze.js.map +1 -1
  52. package/lib/table_helper.js.map +1 -1
  53. package/lib/test_context.d.ts +1 -0
  54. package/lib/test_context.js +1 -0
  55. package/lib/test_context.js.map +1 -1
  56. package/lib/utils.d.ts +3 -2
  57. package/lib/utils.js +83 -57
  58. package/lib/utils.js.map +1 -1
  59. 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,19 @@ 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
+ console.log("Fast mode enabled from environment variable");
133
+ this.fastMode = true;
134
+ }
135
+ if (process.env.FAST_MODE === "false") {
136
+ this.fastMode = false;
137
+ }
138
+ if (this.context) {
139
+ this.context.fastMode = this.fastMode;
140
+ }
112
141
  this.registerEventListeners(this.context);
113
142
  registerNetworkEvents(this.world, this, this.context, this.page);
114
143
  registerDownloadEvent(this.page, this.world, this.context);
@@ -119,6 +148,9 @@ class StableBrowser {
119
148
  if (!context.pageLoading) {
120
149
  context.pageLoading = { status: false };
121
150
  }
151
+ if (this.configuration && this.configuration.acceptDialog && this.page) {
152
+ this.page.on("dialog", (dialog) => dialog.accept());
153
+ }
122
154
  context.playContext.on("page", async function (page) {
123
155
  if (this.configuration && this.configuration.closePopups === true) {
124
156
  console.log("close unexpected popups");
@@ -127,6 +159,14 @@ class StableBrowser {
127
159
  }
128
160
  context.pageLoading.status = true;
129
161
  this.page = page;
162
+ try {
163
+ if (this.configuration && this.configuration.acceptDialog) {
164
+ await page.on("dialog", (dialog) => dialog.accept());
165
+ }
166
+ }
167
+ catch (error) {
168
+ console.error("Error on dialog accept registration", error);
169
+ }
130
170
  context.page = page;
131
171
  context.pages.push(page);
132
172
  registerNetworkEvents(this.world, this, context, this.page);
@@ -178,8 +218,34 @@ class StableBrowser {
178
218
  if (newContextCreated) {
179
219
  this.registerEventListeners(this.context);
180
220
  await this.goto(this.context.environment.baseUrl);
181
- await this.waitForPageLoad();
221
+ if (!this.fastMode) {
222
+ await this.waitForPageLoad();
223
+ }
224
+ }
225
+ }
226
+ async switchTab(tabTitleOrIndex) {
227
+ // first check if the tabNameOrIndex is a number
228
+ let index = parseInt(tabTitleOrIndex);
229
+ if (!isNaN(index)) {
230
+ if (index >= 0 && index < this.context.pages.length) {
231
+ this.page = this.context.pages[index];
232
+ this.context.page = this.page;
233
+ await this.page.bringToFront();
234
+ return;
235
+ }
236
+ }
237
+ // if the tabNameOrIndex is a string, find the tab by name
238
+ for (let i = 0; i < this.context.pages.length; i++) {
239
+ let page = this.context.pages[i];
240
+ let title = await page.title();
241
+ if (title.includes(tabTitleOrIndex)) {
242
+ this.page = page;
243
+ this.context.page = this.page;
244
+ await this.page.bringToFront();
245
+ return;
246
+ }
182
247
  }
248
+ throw new Error("Tab not found: " + tabTitleOrIndex);
183
249
  }
184
250
  registerConsoleLogListener(page, context) {
185
251
  if (!this.context.webLogger) {
@@ -248,6 +314,7 @@ class StableBrowser {
248
314
  if (!url) {
249
315
  throw new Error("url is null, verify that the environment file is correct");
250
316
  }
317
+ url = await this._replaceWithLocalData(url, this.world);
251
318
  if (!url.startsWith("http")) {
252
319
  url = "https://" + url;
253
320
  }
@@ -279,6 +346,64 @@ class StableBrowser {
279
346
  await _commandFinally(state, this);
280
347
  }
281
348
  }
349
+ async goBack(options, world = null) {
350
+ const state = {
351
+ value: "",
352
+ world: world,
353
+ type: Types.GO_BACK,
354
+ text: `Browser navigate back`,
355
+ operation: "goBack",
356
+ log: "***** navigate back *****\n",
357
+ info: {},
358
+ locate: false,
359
+ scroll: false,
360
+ screenshot: false,
361
+ highlight: false,
362
+ };
363
+ try {
364
+ await _preCommand(state, this);
365
+ await this.page.goBack({
366
+ waitUntil: "load",
367
+ });
368
+ await _screenshot(state, this);
369
+ }
370
+ catch (error) {
371
+ console.error("Error on goBack", error);
372
+ _commandError(state, error, this);
373
+ }
374
+ finally {
375
+ await _commandFinally(state, this);
376
+ }
377
+ }
378
+ async goForward(options, world = null) {
379
+ const state = {
380
+ value: "",
381
+ world: world,
382
+ type: Types.GO_FORWARD,
383
+ text: `Browser navigate forward`,
384
+ operation: "goForward",
385
+ log: "***** navigate forward *****\n",
386
+ info: {},
387
+ locate: false,
388
+ scroll: false,
389
+ screenshot: false,
390
+ highlight: false,
391
+ };
392
+ try {
393
+ await _preCommand(state, this);
394
+ await this.page.goForward({
395
+ waitUntil: "load",
396
+ });
397
+ await _screenshot(state, this);
398
+ }
399
+ catch (error) {
400
+ console.error("Error on goForward", error);
401
+ _commandError(state, error, this);
402
+ }
403
+ finally {
404
+ await _commandFinally(state, this);
405
+ }
406
+ }
282
407
  async _getLocator(locator, scope, _params) {
283
408
  locator = _fixLocatorUsingParams(locator, _params);
284
409
  // locator = await this._replaceWithLocalData(locator);
@@ -392,7 +517,7 @@ class StableBrowser {
392
517
  }
393
518
  return { elementCount: tagCount, randomToken };
394
519
  }
395
- async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null) {
520
+ async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null, logErrors = false) {
396
521
  if (!info) {
397
522
  info = {};
398
523
  }
@@ -404,14 +529,13 @@ class StableBrowser {
404
529
  info.locatorLog = new LocatorLog(selectorHierarchy);
405
530
  }
406
531
  let locatorSearch = selectorHierarchy[index];
407
- let originalLocatorSearch = "";
408
532
  try {
409
- originalLocatorSearch = _fixUsingParams(JSON.stringify(locatorSearch), _params);
410
- locatorSearch = JSON.parse(originalLocatorSearch);
533
+ locatorSearch = _fixLocatorUsingParams(locatorSearch, _params);
411
534
  }
412
535
  catch (e) {
413
536
  console.error(e);
414
537
  }
538
+ let originalLocatorSearch = JSON.stringify(locatorSearch);
415
539
  //info.log += "searching for locator " + JSON.stringify(locatorSearch) + "\n";
416
540
  let locator = null;
417
541
  if (locatorSearch.climb && locatorSearch.climb >= 0) {
@@ -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) {
@@ -619,7 +743,7 @@ class StableBrowser {
619
743
  break;
620
744
  }
621
745
  catch (error) {
622
- console.error("frame not found " + frameLocator.css);
746
+ // console.error("frame not found " + frameLocator.css);
623
747
  }
624
748
  }
625
749
  }
@@ -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");
@@ -998,7 +1124,9 @@ 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) {
@@ -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();
@@ -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");
@@ -1433,6 +1580,41 @@ class StableBrowser {
1433
1580
  await _commandFinally(state, this);
1434
1581
  }
1435
1582
  }
1583
+ async setInputFiles(selectors, files, _params = null, options = {}, world = null) {
1584
+ const state = {
1585
+ selectors,
1586
+ _params,
1587
+ files,
1588
+ value: '"' + files.join('", "') + '"',
1589
+ options,
1590
+ world,
1591
+ type: Types.SET_INPUT_FILES,
1592
+ text: `Set input files`,
1593
+ _text: `Set input files on ${selectors.element_name}`,
1594
+ operation: "setInputFiles",
1595
+ log: "***** set input files " + selectors.element_name + " *****\n",
1596
+ };
1597
+ const uploadsFolder = this.configuration.uploadsFolder ?? "data/uploads";
1598
+ try {
1599
+ await _preCommand(state, this);
1600
+ for (let i = 0; i < files.length; i++) {
1601
+ const file = files[i];
1602
+ const filePath = path.join(uploadsFolder, file);
1603
+ if (!fs.existsSync(filePath)) {
1604
+ throw new Error(`File not found: ${filePath}`);
1605
+ }
1606
+ state.files[i] = filePath;
1607
+ }
1608
+ await state.element.setInputFiles(files);
1609
+ return state.info;
1610
+ }
1611
+ catch (e) {
1612
+ await _commandError(state, e, this);
1613
+ }
1614
+ finally {
1615
+ await _commandFinally(state, this);
1616
+ }
1617
+ }
1436
1618
  async getText(selectors, _params = null, options = {}, info = {}, world = null) {
1437
1619
  return await this._getText(selectors, 0, _params, options, info, world);
1438
1620
  }
@@ -1626,6 +1808,83 @@ class StableBrowser {
1626
1808
  await _commandFinally(state, this);
1627
1809
  }
1628
1810
  }
1811
+ async snapshotValidation(frameSelectors, referanceSnapshot, _params = null, options = {}, world = null) {
1812
+ const timeout = this._getFindElementTimeout(options);
1813
+ const startTime = Date.now();
1814
+ const state = {
1815
+ _params,
1816
+ value: referanceSnapshot,
1817
+ options,
1818
+ world,
1819
+ locate: false,
1820
+ scroll: false,
1821
+ screenshot: true,
1822
+ highlight: false,
1823
+ type: Types.SNAPSHOT_VALIDATION,
1824
+ text: `verify snapshot: ${referanceSnapshot}`,
1825
+ operation: "snapshotValidation",
1826
+ log: "***** verify snapshot *****\n",
1827
+ };
1828
+ if (!referanceSnapshot) {
1829
+ throw new Error("referanceSnapshot is null");
1830
+ }
1831
+ let text = null;
1832
+ if (fs.existsSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yml"))) {
1833
+ text = fs.readFileSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yml"), "utf8");
1834
+ }
1835
+ else if (fs.existsSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yaml"))) {
1836
+ text = fs.readFileSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yaml"), "utf8");
1837
+ }
1838
+ else if (referanceSnapshot.startsWith("yaml:")) {
1839
+ text = referanceSnapshot.substring(5);
1840
+ }
1841
+ else {
1842
+ throw new Error("referenceSnapshot file not found: " + referanceSnapshot);
1843
+ }
1844
+ state.text = text;
1845
+ const newValue = await this._replaceWithLocalData(text, world);
1846
+ await _preCommand(state, this);
1847
+ let foundObj = null;
1848
+ try {
1849
+ let matchResult = null;
1850
+ while (Date.now() - startTime < timeout) {
1851
+ try {
1852
+ let scope = null;
1853
+ if (!frameSelectors) {
1854
+ scope = this.page;
1855
+ }
1856
+ else {
1857
+ scope = await this._findFrameScope(frameSelectors, timeout, state.info);
1858
+ }
1859
+ const snapshot = await scope.locator("body").ariaSnapshot({ timeout });
1860
+ matchResult = snapshotValidation(snapshot, newValue, referanceSnapshot);
1861
+ if (matchResult.errorLine !== -1) {
1862
+ throw new Error("Snapshot validation failed at line " + matchResult.errorLineText);
1863
+ }
1864
+ // highlight and screenshot
1865
+ try {
1866
+ await await highlightSnapshot(newValue, scope);
1867
+ await _screenshot(state, this);
1868
+ }
1869
+ catch (e) { }
1870
+ return state.info;
1871
+ }
1872
+ catch (e) {
1873
+ // Log error but continue retrying until timeout is reached
1874
+ //this.logger.warn("Retrying snapshot validation due to: " + e.message);
1875
+ }
1876
+ await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait 1 second before retrying
1877
+ }
1878
+ throw new Error("No snapshot match " + matchResult?.errorLineText);
1879
+ }
1880
+ catch (e) {
1881
+ await _commandError(state, e, this);
1882
+ throw e;
1883
+ }
1884
+ finally {
1885
+ await _commandFinally(state, this);
1886
+ }
1887
+ }
1629
1888
  async waitForUserInput(message, world = null) {
1630
1889
  if (!message) {
1631
1890
  message = "# Wait for user input. Press any key to continue";
@@ -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
@@ -1960,6 +2214,95 @@ class StableBrowser {
1960
2214
  state.value = await state.element.getAttribute(attribute);
1961
2215
  break;
1962
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
+ }
1963
2306
  state.info.value = state.value;
1964
2307
  this.setTestData({ [variable]: state.value }, world);
1965
2308
  this.logger.info("set test data: " + variable + "=" + state.value);
@@ -2025,17 +2368,42 @@ class StableBrowser {
2025
2368
  let regex;
2026
2369
  if (expectedValue.startsWith("/") && expectedValue.endsWith("/")) {
2027
2370
  const patternBody = expectedValue.slice(1, -1);
2028
- regex = new RegExp(patternBody, "g");
2371
+ const processedPattern = patternBody.replace(/\n/g, ".*");
2372
+ regex = new RegExp(processedPattern, "gs");
2373
+ state.info.regex = true;
2029
2374
  }
2030
2375
  else {
2031
2376
  const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2032
2377
  regex = new RegExp(escapedPattern, "g");
2033
2378
  }
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);
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
+ }
2039
2407
  }
2040
2408
  return state.info;
2041
2409
  }
@@ -2046,54 +2414,301 @@ class StableBrowser {
2046
2414
  await _commandFinally(state, this);
2047
2415
  }
2048
2416
  }
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
- }),
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,
2078
2433
  };
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
2434
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2435
+ let val;
2436
+ let expectedValue;
2437
+ try {
2438
+ await _preCommand(state, this);
2439
+ expectedValue = await replaceWithLocalTestData(state.value, world);
2440
+ state.info.expectedValue = expectedValue;
2441
+ switch (property) {
2442
+ case "innerText":
2443
+ val = String(await state.element.innerText());
2444
+ break;
2445
+ case "text":
2446
+ val = String(await state.element.textContent());
2447
+ break;
2448
+ case "value":
2449
+ val = String(await state.element.inputValue());
2450
+ break;
2451
+ case "checked":
2452
+ val = String(await state.element.isChecked());
2453
+ break;
2454
+ case "disabled":
2455
+ val = String(await state.element.isDisabled());
2456
+ break;
2457
+ case "readOnly":
2458
+ const isEditable = await state.element.isEditable();
2459
+ val = String(!isEditable);
2460
+ break;
2461
+ case "innerHTML":
2462
+ val = String(await state.element.innerHTML());
2463
+ break;
2464
+ case "outerHTML":
2465
+ val = String(await state.element.evaluate((element) => element.outerHTML));
2466
+ break;
2467
+ default:
2468
+ if (property.startsWith("dataset.")) {
2469
+ const dataAttribute = property.substring(8);
2470
+ val = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2471
+ }
2472
+ else {
2473
+ val = String(await state.element.evaluate((element, prop) => element[prop], property));
2474
+ }
2475
+ }
2476
+ // Helper function to remove all style="" attributes
2477
+ const removeStyleAttributes = (htmlString) => {
2478
+ return htmlString.replace(/\s*style\s*=\s*"[^"]*"/gi, "");
2479
+ };
2480
+ // Remove style attributes for innerHTML and outerHTML properties
2481
+ if (property === "innerHTML" || property === "outerHTML") {
2482
+ val = removeStyleAttributes(val);
2483
+ expectedValue = removeStyleAttributes(expectedValue);
2484
+ }
2485
+ state.info.value = val;
2486
+ let regex;
2487
+ if (expectedValue.startsWith("/") && expectedValue.endsWith("/")) {
2488
+ const patternBody = expectedValue.slice(1, -1);
2489
+ const processedPattern = patternBody.replace(/\n/g, ".*");
2490
+ regex = new RegExp(processedPattern, "gs");
2491
+ state.info.regex = true;
2492
+ }
2493
+ else {
2494
+ const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2495
+ regex = new RegExp(escapedPattern, "g");
2496
+ }
2497
+ if (property === "innerText") {
2498
+ if (state.info.regex) {
2499
+ if (!regex.test(val)) {
2500
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2501
+ state.info.failCause.assertionFailed = true;
2502
+ state.info.failCause.lastError = errorMessage;
2503
+ throw new Error(errorMessage);
2504
+ }
2505
+ }
2506
+ else {
2507
+ // Fix: Replace escaped newlines with actual newlines before splitting
2508
+ const normalizedExpectedValue = expectedValue.replace(/\\n/g, "\n");
2509
+ const valLines = val.split("\n");
2510
+ const expectedLines = normalizedExpectedValue.split("\n");
2511
+ // Check if all expected lines are present in the actual lines
2512
+ const isPart = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine.trim() === expectedLine.trim()));
2513
+ if (!isPart) {
2514
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2515
+ state.info.failCause.assertionFailed = true;
2516
+ state.info.failCause.lastError = errorMessage;
2517
+ throw new Error(errorMessage);
2518
+ }
2519
+ }
2520
+ }
2521
+ else {
2522
+ if (!val.match(regex)) {
2523
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2524
+ state.info.failCause.assertionFailed = true;
2525
+ state.info.failCause.lastError = errorMessage;
2526
+ throw new Error(errorMessage);
2527
+ }
2528
+ }
2529
+ return state.info;
2530
+ }
2531
+ catch (e) {
2532
+ await _commandError(state, e, this);
2533
+ }
2534
+ finally {
2535
+ await _commandFinally(state, this);
2536
+ }
2537
+ }
2538
+ async conditionalWait(selectors, condition, timeout = 1000, _params = null, options = {}, world = null) {
2539
+ // Convert timeout from seconds to milliseconds
2540
+ const timeoutMs = timeout * 1000;
2541
+ const state = {
2542
+ selectors,
2543
+ _params,
2544
+ condition,
2545
+ timeout: timeoutMs, // Store as milliseconds for internal use
2546
+ options,
2547
+ world,
2548
+ type: Types.CONDITIONAL_WAIT,
2549
+ highlight: true,
2550
+ screenshot: true,
2551
+ text: `Conditional wait for element`,
2552
+ _text: `Wait for ${selectors.element_name} to be ${condition} (timeout: ${timeout}s)`, // Display original seconds
2553
+ operation: "conditionalWait",
2554
+ log: `***** conditional wait for ${condition} on ${selectors.element_name} *****\n`,
2555
+ allowDisabled: true,
2556
+ info: {},
2557
+ };
2558
+ // Initialize startTime outside try block to ensure it's always accessible
2559
+ const startTime = Date.now();
2560
+ let conditionMet = false;
2561
+ let currentValue = null;
2562
+ let lastError = null;
2563
+ // Main retry loop - continues until timeout or condition is met
2564
+ while (Date.now() - startTime < timeoutMs) {
2565
+ const elapsedTime = Date.now() - startTime;
2566
+ const remainingTime = timeoutMs - elapsedTime;
2567
+ try {
2568
+ // Try to execute _preCommand (element location)
2569
+ await _preCommand(state, this);
2570
+ // If _preCommand succeeds, start condition checking
2571
+ const checkCondition = async () => {
2572
+ try {
2573
+ switch (condition.toLowerCase()) {
2574
+ case "checked":
2575
+ currentValue = await state.element.isChecked();
2576
+ return currentValue === true;
2577
+ case "unchecked":
2578
+ currentValue = await state.element.isChecked();
2579
+ return currentValue === false;
2580
+ case "visible":
2581
+ currentValue = await state.element.isVisible();
2582
+ return currentValue === true;
2583
+ case "hidden":
2584
+ currentValue = await state.element.isVisible();
2585
+ return currentValue === false;
2586
+ case "enabled":
2587
+ currentValue = await state.element.isDisabled();
2588
+ return currentValue === false;
2589
+ case "disabled":
2590
+ currentValue = await state.element.isDisabled();
2591
+ return currentValue === true;
2592
+ case "editable":
2593
+ // currentValue = await String(await state.element.evaluate((element, prop) => element[prop], "isContentEditable"));
2594
+ currentValue = await state.element.isContentEditable();
2595
+ return currentValue === true;
2596
+ default:
2597
+ state.info.message = `Unsupported condition: '${condition}'. Supported conditions are: checked, unchecked, visible, hidden, enabled, disabled, editable.`;
2598
+ state.info.success = false;
2599
+ return false;
2600
+ }
2601
+ }
2602
+ catch (error) {
2603
+ // Don't throw here, just return false to continue retrying
2604
+ return false;
2605
+ }
2606
+ };
2607
+ // Inner loop for condition checking (once element is located)
2608
+ while (Date.now() - startTime < timeoutMs) {
2609
+ const currentElapsedTime = Date.now() - startTime;
2610
+ conditionMet = await checkCondition();
2611
+ if (conditionMet) {
2612
+ break;
2613
+ }
2614
+ // Check if we still have time for another attempt
2615
+ if (Date.now() - startTime + 50 < timeoutMs) {
2616
+ await new Promise((res) => setTimeout(res, 50));
2617
+ }
2618
+ else {
2619
+ break;
2620
+ }
2621
+ }
2622
+ // If we got here and condition is met, break out of main loop
2623
+ if (conditionMet) {
2624
+ break;
2625
+ }
2626
+ // If condition not met but no exception, we've timed out
2627
+ break;
2628
+ }
2629
+ catch (e) {
2630
+ lastError = e;
2631
+ const currentElapsedTime = Date.now() - startTime;
2632
+ const timeLeft = timeoutMs - currentElapsedTime;
2633
+ // Check if we have enough time left to retry
2634
+ if (timeLeft > 100) {
2635
+ await new Promise((resolve) => setTimeout(resolve, 50));
2636
+ }
2637
+ else {
2638
+ break;
2639
+ }
2640
+ }
2641
+ }
2642
+ const actualWaitTime = Date.now() - startTime;
2643
+ state.info = {
2644
+ success: conditionMet,
2645
+ conditionMet,
2646
+ actualWaitTime,
2647
+ currentValue,
2648
+ lastError: lastError?.message || null,
2649
+ message: conditionMet
2650
+ ? `Condition '${condition}' met after ${(actualWaitTime / 1000).toFixed(2)}s`
2651
+ : `Condition '${condition}' not met within ${timeout}s timeout`,
2652
+ };
2653
+ if (lastError) {
2654
+ state.log += `Last error: ${lastError.message}\n`;
2655
+ }
2656
+ try {
2657
+ await _commandFinally(state, this);
2658
+ }
2659
+ catch (finallyError) {
2660
+ state.log += `Error in _commandFinally: ${finallyError.message}\n`;
2661
+ }
2662
+ return state.info;
2663
+ }
2664
+ async extractEmailData(emailAddress, options, world) {
2665
+ if (!emailAddress) {
2666
+ throw new Error("email address is null");
2667
+ }
2668
+ // check if address contain @
2669
+ if (emailAddress.indexOf("@") === -1) {
2670
+ emailAddress = emailAddress + "@blinq-mail.io";
2671
+ }
2672
+ else {
2673
+ if (!emailAddress.toLowerCase().endsWith("@blinq-mail.io")) {
2674
+ throw new Error("email address should end with @blinq-mail.io");
2675
+ }
2676
+ }
2677
+ const startTime = Date.now();
2678
+ let timeout = 60000;
2679
+ if (options && options.timeout) {
2680
+ timeout = options.timeout;
2681
+ }
2682
+ const serviceUrl = _getServerUrl() + "/api/mail/createLinkOrCodeFromEmail";
2683
+ const request = {
2684
+ method: "POST",
2685
+ url: serviceUrl,
2686
+ headers: {
2687
+ "Content-Type": "application/json",
2688
+ Authorization: `Bearer ${process.env.TOKEN}`,
2689
+ },
2690
+ data: JSON.stringify({
2691
+ email: emailAddress,
2692
+ }),
2693
+ };
2694
+ let errorCount = 0;
2695
+ while (true) {
2696
+ try {
2697
+ let result = await this.context.api.request(request);
2698
+ // the response body expected to be the following:
2699
+ // {
2700
+ // "status": true,
2701
+ // "content": {
2702
+ // "url": "",
2703
+ // "code": "112112",
2704
+ // "name": "generate_link_or_code"
2705
+ // }
2706
+ //}
2707
+ if ((result && result.data, result.data.status === true)) {
2708
+ let codeOrUrlFound = false;
2709
+ let emailCode = null;
2710
+ let emailUrl = null;
2711
+ // check if a code is returned
2097
2712
  if (result.data.content && result.data.content.code) {
2098
2713
  let code = result.data.content.code;
2099
2714
  this.setTestData({ emailCode: code }, world);
@@ -2203,56 +2818,49 @@ class StableBrowser {
2203
2818
  console.debug(error);
2204
2819
  }
2205
2820
  }
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
- // }
2821
+ _matcher(text) {
2822
+ if (!text) {
2823
+ return { matcher: "contains", queryText: "" };
2824
+ }
2825
+ if (text.length < 2) {
2826
+ return { matcher: "contains", queryText: text };
2827
+ }
2828
+ const split = text.split(":");
2829
+ const matcher = split[0].toLowerCase();
2830
+ const queryText = split.slice(1).join(":").trim();
2831
+ return { matcher, queryText };
2832
+ }
2833
+ _getDomain(url) {
2834
+ if (url.length === 0 || (!url.startsWith("http://") && !url.startsWith("https://"))) {
2835
+ return "";
2836
+ }
2837
+ let hostnameFragments = url.split("/")[2].split(".");
2838
+ if (hostnameFragments.some((fragment) => fragment.includes(":"))) {
2839
+ return hostnameFragments.join("-").split(":").join("-");
2840
+ }
2841
+ let n = hostnameFragments.length;
2842
+ let fragments = [...hostnameFragments];
2843
+ while (n > 0 && hostnameFragments[n - 1].length <= 3) {
2844
+ hostnameFragments.pop();
2845
+ n = hostnameFragments.length;
2846
+ }
2847
+ if (n == 0) {
2848
+ if (fragments[0] === "www")
2849
+ fragments = fragments.slice(1);
2850
+ return fragments.length > 1 ? fragments.slice(0, fragments.length - 1).join("-") : fragments.join("-");
2851
+ }
2852
+ if (hostnameFragments[0] === "www")
2853
+ hostnameFragments = hostnameFragments.slice(1);
2854
+ return hostnameFragments.join(".");
2855
+ }
2856
+ /**
2857
+ * Verify the page path matches the given path.
2858
+ * @param {string} pathPart - The path to verify.
2859
+ * @param {object} options - Options for verification.
2860
+ * @param {object} world - The world context.
2861
+ * @returns {Promise<object>} - The state info after verification.
2862
+ */
2254
2863
  async verifyPagePath(pathPart, options = {}, world = null) {
2255
- const startTime = Date.now();
2256
2864
  let error = null;
2257
2865
  let screenshotId = null;
2258
2866
  let screenshotPath = null;
@@ -2266,113 +2874,212 @@ class StableBrowser {
2266
2874
  pathPart = newValue;
2267
2875
  }
2268
2876
  info.pathPart = pathPart;
2877
+ const { matcher, queryText } = this._matcher(pathPart);
2878
+ const state = {
2879
+ text_search: queryText,
2880
+ options,
2881
+ world,
2882
+ locate: false,
2883
+ scroll: false,
2884
+ highlight: false,
2885
+ type: Types.VERIFY_PAGE_PATH,
2886
+ text: `Verify the page url is ${queryText}`,
2887
+ _text: `Verify the page url is ${queryText}`,
2888
+ operation: "verifyPagePath",
2889
+ log: "***** verify page url is " + queryText + " *****\n",
2890
+ };
2269
2891
  try {
2892
+ await _preCommand(state, this);
2893
+ state.info.text = queryText;
2270
2894
  for (let i = 0; i < 30; i++) {
2271
2895
  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;
2896
+ switch (matcher) {
2897
+ case "exact":
2898
+ if (url !== queryText) {
2899
+ if (i === 29) {
2900
+ throw new Error(`Page URL ${url} is not equal to ${queryText}`);
2901
+ }
2902
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2903
+ continue;
2904
+ }
2905
+ break;
2906
+ case "contains":
2907
+ if (!url.includes(queryText)) {
2908
+ if (i === 29) {
2909
+ throw new Error(`Page URL ${url} doesn't contain ${queryText}`);
2910
+ }
2911
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2912
+ continue;
2913
+ }
2914
+ break;
2915
+ case "starts-with":
2916
+ {
2917
+ const domain = this._getDomain(url);
2918
+ if (domain.length > 0 && domain !== queryText) {
2919
+ if (i === 29) {
2920
+ throw new Error(`Page URL ${url} doesn't start with ${queryText}`);
2921
+ }
2922
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2923
+ continue;
2924
+ }
2925
+ }
2926
+ break;
2927
+ case "ends-with":
2928
+ {
2929
+ const urlObj = new URL(url);
2930
+ let route = "/";
2931
+ if (urlObj.pathname !== "/") {
2932
+ route = urlObj.pathname.split("/").slice(-1)[0].trim();
2933
+ }
2934
+ else {
2935
+ route = "/";
2936
+ }
2937
+ if (route !== queryText) {
2938
+ if (i === 29) {
2939
+ throw new Error(`Page URL ${url} doesn't end with ${queryText}`);
2940
+ }
2941
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2942
+ continue;
2943
+ }
2944
+ }
2945
+ break;
2946
+ case "regex":
2947
+ const regex = new RegExp(queryText.slice(1, -1), "g");
2948
+ if (!regex.test(url)) {
2949
+ if (i === 29) {
2950
+ throw new Error(`Page URL ${url} doesn't match regex ${queryText}`);
2951
+ }
2952
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2953
+ continue;
2954
+ }
2955
+ break;
2956
+ default:
2957
+ console.log("Unknown matching type, defaulting to contains matching");
2958
+ if (!url.includes(pathPart)) {
2959
+ if (i === 29) {
2960
+ throw new Error(`Page URL ${url} does not contain ${pathPart}`);
2961
+ }
2962
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2963
+ continue;
2964
+ }
2278
2965
  }
2279
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2280
- return info;
2966
+ await _screenshot(state, this);
2967
+ return state.info;
2281
2968
  }
2282
2969
  }
2283
2970
  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);
2971
+ state.info.failCause.lastError = e.message;
2972
+ state.info.failCause.assertionFailed = true;
2973
+ await _commandError(state, e, this);
2292
2974
  }
2293
2975
  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
- });
2976
+ await _commandFinally(state, this);
2314
2977
  }
2315
2978
  }
2979
+ /**
2980
+ * Verify the page title matches the given title.
2981
+ * @param {string} title - The title to verify.
2982
+ * @param {object} options - Options for verification.
2983
+ * @param {object} world - The world context.
2984
+ * @returns {Promise<object>} - The state info after verification.
2985
+ */
2316
2986
  async verifyPageTitle(title, options = {}, world = null) {
2317
- const startTime = Date.now();
2318
2987
  let error = null;
2319
2988
  let screenshotId = null;
2320
2989
  let screenshotPath = null;
2321
2990
  await new Promise((resolve) => setTimeout(resolve, 2000));
2322
- const info = {};
2323
- info.log = "***** verify page title " + title + " *****\n";
2324
- info.operation = "verifyPageTitle";
2325
2991
  const newValue = await this._replaceWithLocalData(title, world);
2326
2992
  if (newValue !== title) {
2327
2993
  this.logger.info(title + "=" + newValue);
2328
2994
  title = newValue;
2329
2995
  }
2330
- info.title = title;
2996
+ const { matcher, queryText } = this._matcher(title);
2997
+ const state = {
2998
+ text_search: queryText,
2999
+ options,
3000
+ world,
3001
+ locate: false,
3002
+ scroll: false,
3003
+ highlight: false,
3004
+ type: Types.VERIFY_PAGE_TITLE,
3005
+ text: `Verify the page title is ${queryText}`,
3006
+ _text: `Verify the page title is ${queryText}`,
3007
+ operation: "verifyPageTitle",
3008
+ log: "***** verify page title is " + queryText + " *****\n",
3009
+ };
2331
3010
  try {
3011
+ await _preCommand(state, this);
3012
+ state.info.text = queryText;
2332
3013
  for (let i = 0; i < 30; i++) {
2333
3014
  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;
3015
+ switch (matcher) {
3016
+ case "exact":
3017
+ if (foundTitle !== queryText) {
3018
+ if (i === 29) {
3019
+ throw new Error(`Page Title ${foundTitle} is not equal to ${queryText}`);
3020
+ }
3021
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3022
+ continue;
3023
+ }
3024
+ break;
3025
+ case "contains":
3026
+ if (!foundTitle.includes(queryText)) {
3027
+ if (i === 29) {
3028
+ throw new Error(`Page Title ${foundTitle} doesn't contain ${queryText}`);
3029
+ }
3030
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3031
+ continue;
3032
+ }
3033
+ break;
3034
+ case "starts-with":
3035
+ if (!foundTitle.startsWith(queryText)) {
3036
+ if (i === 29) {
3037
+ throw new Error(`Page title ${foundTitle} doesn't start with ${queryText}`);
3038
+ }
3039
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3040
+ continue;
3041
+ }
3042
+ break;
3043
+ case "ends-with":
3044
+ if (!foundTitle.endsWith(queryText)) {
3045
+ if (i === 29) {
3046
+ throw new Error(`Page Title ${foundTitle} doesn't end with ${queryText}`);
3047
+ }
3048
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3049
+ continue;
3050
+ }
3051
+ break;
3052
+ case "regex":
3053
+ const regex = new RegExp(queryText.slice(1, -1), "g");
3054
+ if (!regex.test(foundTitle)) {
3055
+ if (i === 29) {
3056
+ throw new Error(`Page Title ${foundTitle} doesn't match regex ${queryText}`);
3057
+ }
3058
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3059
+ continue;
3060
+ }
3061
+ break;
3062
+ default:
3063
+ console.log("Unknown matching type, defaulting to contains matching");
3064
+ if (!foundTitle.includes(title)) {
3065
+ if (i === 29) {
3066
+ throw new Error(`Page Title ${foundTitle} does not contain ${title}`);
3067
+ }
3068
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3069
+ continue;
3070
+ }
2340
3071
  }
2341
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2342
- return info;
3072
+ await _screenshot(state, this);
3073
+ return state.info;
2343
3074
  }
2344
3075
  }
2345
3076
  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);
3077
+ state.info.failCause.lastError = e.message;
3078
+ state.info.failCause.assertionFailed = true;
3079
+ await _commandError(state, e, this);
2354
3080
  }
2355
3081
  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
- });
3082
+ await _commandFinally(state, this);
2376
3083
  }
2377
3084
  }
2378
3085
  async findTextInAllFrames(dateAlternatives, numberAlternatives, text, state, partial = true, ignoreCase = false) {
@@ -2414,7 +3121,7 @@ class StableBrowser {
2414
3121
  scroll: false,
2415
3122
  highlight: false,
2416
3123
  type: Types.VERIFY_PAGE_CONTAINS_TEXT,
2417
- text: `Verify the text '${text}' exists in page`,
3124
+ text: `Verify the text '${maskValue(text)}' exists in page`,
2418
3125
  _text: `Verify the text '${text}' exists in page`,
2419
3126
  operation: "verifyTextExistInPage",
2420
3127
  log: "***** verify text " + text + " exists in page *****\n",
@@ -2456,27 +3163,10 @@ class StableBrowser {
2456
3163
  const frame = resultWithElementsFound[0].frame;
2457
3164
  const dataAttribute = `[data-blinq-id-${resultWithElementsFound[0].randomToken}]`;
2458
3165
  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
3166
  const element = await frame.locator(dataAttribute).first();
2474
- // await new Promise((resolve) => setTimeout(resolve, 100));
2475
- // await this._unhighlightElements(frame, dataAttribute);
2476
3167
  if (element) {
2477
3168
  await this.scrollIfNeeded(element, state.info);
2478
3169
  await element.dispatchEvent("bvt_verify_page_contains_text");
2479
- // await _screenshot(state, this, element);
2480
3170
  }
2481
3171
  }
2482
3172
  await _screenshot(state, this);
@@ -2486,7 +3176,6 @@ class StableBrowser {
2486
3176
  console.error(error);
2487
3177
  }
2488
3178
  }
2489
- // await expect(element).toHaveCount(1, { timeout: 10000 });
2490
3179
  }
2491
3180
  catch (e) {
2492
3181
  await _commandError(state, e, this);
@@ -2505,7 +3194,7 @@ class StableBrowser {
2505
3194
  scroll: false,
2506
3195
  highlight: false,
2507
3196
  type: Types.WAIT_FOR_TEXT_TO_DISAPPEAR,
2508
- text: `Verify the text '${text}' does not exist in page`,
3197
+ text: `Verify the text '${maskValue(text)}' does not exist in page`,
2509
3198
  _text: `Verify the text '${text}' does not exist in page`,
2510
3199
  operation: "verifyTextNotExistInPage",
2511
3200
  log: "***** verify text " + text + " does not exist in page *****\n",
@@ -3002,8 +3691,51 @@ class StableBrowser {
3002
3691
  });
3003
3692
  }
3004
3693
  }
3694
+ /**
3695
+ * Explicit wait/sleep function that pauses execution for a specified duration
3696
+ * @param duration - Duration to sleep in milliseconds (default: 1000ms)
3697
+ * @param options - Optional configuration object
3698
+ * @param world - Optional world context
3699
+ * @returns Promise that resolves after the specified duration
3700
+ */
3701
+ async sleep(duration = 1000, options = {}, world = null) {
3702
+ const state = {
3703
+ duration,
3704
+ options,
3705
+ world,
3706
+ locate: false,
3707
+ scroll: false,
3708
+ screenshot: false,
3709
+ highlight: false,
3710
+ type: Types.SLEEP,
3711
+ text: `Sleep for ${duration} ms`,
3712
+ _text: `Sleep for ${duration} ms`,
3713
+ operation: "sleep",
3714
+ log: `***** Sleep for ${duration} ms *****\n`,
3715
+ };
3716
+ try {
3717
+ await _preCommand(state, this);
3718
+ if (duration < 0) {
3719
+ throw new Error("Sleep duration cannot be negative");
3720
+ }
3721
+ await new Promise((resolve) => setTimeout(resolve, duration));
3722
+ return state.info;
3723
+ }
3724
+ catch (e) {
3725
+ await _commandError(state, e, this);
3726
+ }
3727
+ finally {
3728
+ await _commandFinally(state, this);
3729
+ }
3730
+ }
3005
3731
  async _replaceWithLocalData(value, world, _decrypt = true, totpWait = true) {
3006
- return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
3732
+ try {
3733
+ return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
3734
+ }
3735
+ catch (error) {
3736
+ this.logger.debug(error);
3737
+ throw error;
3738
+ }
3007
3739
  }
3008
3740
  _getLoadTimeout(options) {
3009
3741
  let timeout = 15000;
@@ -3026,6 +3758,7 @@ class StableBrowser {
3026
3758
  }
3027
3759
  async saveStoreState(path = null, world = null) {
3028
3760
  const storageState = await this.page.context().storageState();
3761
+ path = await this._replaceWithLocalData(path, this.world);
3029
3762
  //const testDataFile = _getDataFile(world, this.context, this);
3030
3763
  if (path) {
3031
3764
  // save { storageState: storageState } into the path
@@ -3036,10 +3769,14 @@ class StableBrowser {
3036
3769
  }
3037
3770
  }
3038
3771
  async restoreSaveState(path = null, world = null) {
3772
+ path = await this._replaceWithLocalData(path, this.world);
3039
3773
  await refreshBrowser(this, path, world);
3040
3774
  this.registerEventListeners(this.context);
3041
3775
  registerNetworkEvents(this.world, this, this.context, this.page);
3042
3776
  registerDownloadEvent(this.page, this.world, this.context);
3777
+ if (this.onRestoreSaveState) {
3778
+ this.onRestoreSaveState(path);
3779
+ }
3043
3780
  }
3044
3781
  async waitForPageLoad(options = {}, world = null) {
3045
3782
  let timeout = this._getLoadTimeout(options);
@@ -3074,7 +3811,6 @@ class StableBrowser {
3074
3811
  else if (e.label === "domcontentloaded") {
3075
3812
  console.log("waited for the domcontent loaded timeout");
3076
3813
  }
3077
- console.log(".");
3078
3814
  }
3079
3815
  finally {
3080
3816
  await new Promise((resolve) => setTimeout(resolve, 2000));
@@ -3118,7 +3854,6 @@ class StableBrowser {
3118
3854
  await this.page.close();
3119
3855
  }
3120
3856
  catch (e) {
3121
- console.log(".");
3122
3857
  await _commandError(state, e, this);
3123
3858
  }
3124
3859
  finally {
@@ -3233,7 +3968,6 @@ class StableBrowser {
3233
3968
  await this.page.setViewportSize({ width: width, height: hight });
3234
3969
  }
3235
3970
  catch (e) {
3236
- console.log(".");
3237
3971
  await _commandError({ text: "setViewportSize", operation: "setViewportSize", width, hight, info }, e, this);
3238
3972
  }
3239
3973
  finally {
@@ -3271,7 +4005,6 @@ class StableBrowser {
3271
4005
  await this.page.reload();
3272
4006
  }
3273
4007
  catch (e) {
3274
- console.log(".");
3275
4008
  await _commandError({ text: "reloadPage", operation: "reloadPage", info }, e, this);
3276
4009
  }
3277
4010
  finally {
@@ -3314,7 +4047,44 @@ class StableBrowser {
3314
4047
  console.log("#-#");
3315
4048
  }
3316
4049
  }
4050
+ async beforeScenario(world, scenario) {
4051
+ if (world && world.attach) {
4052
+ world.attach(this.context.reportFolder, { mediaType: "text/plain" });
4053
+ }
4054
+ this.context.loadedRoutes = null;
4055
+ this.beforeScenarioCalled = true;
4056
+ if (scenario && scenario.pickle && scenario.pickle.name) {
4057
+ this.scenarioName = scenario.pickle.name;
4058
+ }
4059
+ if (scenario && scenario.gherkinDocument && scenario.gherkinDocument.feature) {
4060
+ this.featureName = scenario.gherkinDocument.feature.name;
4061
+ }
4062
+ if (this.context) {
4063
+ this.context.examplesRow = extractStepExampleParameters(scenario);
4064
+ }
4065
+ if (this.tags === null && scenario && scenario.pickle && scenario.pickle.tags) {
4066
+ this.tags = scenario.pickle.tags.map((tag) => tag.name);
4067
+ // check if @global_test_data tag is present
4068
+ if (this.tags.includes("@global_test_data")) {
4069
+ this.saveTestDataAsGlobal({}, world);
4070
+ }
4071
+ }
4072
+ // update test data based on feature/scenario
4073
+ let envName = null;
4074
+ if (this.context && this.context.environment) {
4075
+ envName = this.context.environment.name;
4076
+ }
4077
+ if (!process.env.TEMP_RUN) {
4078
+ await getTestData(envName, world, undefined, this.featureName, this.scenarioName, this.context);
4079
+ }
4080
+ await loadBrunoParams(this.context, this.context.environment.name);
4081
+ }
4082
+ async afterScenario(world, scenario) { }
3317
4083
  async beforeStep(world, step) {
4084
+ if (!this.beforeScenarioCalled) {
4085
+ this.beforeScenario(world, step);
4086
+ this.context.loadedRoutes = null;
4087
+ }
3318
4088
  if (this.stepIndex === undefined) {
3319
4089
  this.stepIndex = 0;
3320
4090
  }
@@ -3331,30 +4101,23 @@ class StableBrowser {
3331
4101
  else {
3332
4102
  this.stepName = "step " + this.stepIndex;
3333
4103
  }
3334
- if (this.context) {
3335
- this.context.examplesRow = extractStepExampleParameters(step);
3336
- }
3337
4104
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
3338
4105
  if (this.context.browserObject.context) {
3339
4106
  await this.context.browserObject.context.tracing.startChunk({ title: this.stepName });
3340
4107
  }
3341
4108
  }
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
4109
  if (this.initSnapshotTaken === false) {
3350
4110
  this.initSnapshotTaken = true;
3351
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4111
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
3352
4112
  const snapshot = await this.getAriaSnapshot();
3353
4113
  if (snapshot) {
3354
4114
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-before");
3355
4115
  }
3356
4116
  }
3357
4117
  }
4118
+ this.context.routeResults = null;
4119
+ await registerBeforeStepRoutes(this.context, this.stepName);
4120
+ networkBeforeStep(this.stepName);
3358
4121
  }
3359
4122
  async getAriaSnapshot() {
3360
4123
  try {
@@ -3370,18 +4133,74 @@ class StableBrowser {
3370
4133
  const content = [`- path: ${path}`, `- title: ${title}`];
3371
4134
  const timeout = this.configuration.ariaSnapshotTimeout ? this.configuration.ariaSnapshotTimeout : 3000;
3372
4135
  for (let i = 0; i < frames.length; i++) {
3373
- content.push(`- frame: ${i}`);
3374
4136
  const frame = frames[i];
3375
- const snapshot = await frame.locator("body").ariaSnapshot({ timeout });
3376
- content.push(snapshot);
4137
+ try {
4138
+ // Ensure frame is attached and has body
4139
+ const body = frame.locator("body");
4140
+ //await body.waitFor({ timeout: 2000 }); // wait explicitly
4141
+ const snapshot = await body.ariaSnapshot({ timeout });
4142
+ if (!snapshot) {
4143
+ continue;
4144
+ }
4145
+ content.push(`- frame: ${i}`);
4146
+ content.push(snapshot);
4147
+ }
4148
+ catch (innerErr) {
4149
+ console.warn(`Frame ${i} snapshot failed:`, innerErr);
4150
+ content.push(`- frame: ${i} - error: ${innerErr.message}`);
4151
+ }
3377
4152
  }
3378
4153
  return content.join("\n");
3379
4154
  }
3380
4155
  catch (e) {
3381
- console.error(e);
4156
+ console.log("Error in getAriaSnapshot");
4157
+ //console.debug(e);
3382
4158
  }
3383
4159
  return null;
3384
4160
  }
4161
+ /**
4162
+ * Sends command with custom payload to report.
4163
+ * @param commandText - Title of the command to be shown in the report.
4164
+ * @param commandStatus - Status of the command (e.g. "PASSED", "FAILED").
4165
+ * @param content - Content of the command to be shown in the report.
4166
+ * @param options - Options for the command. Example: { type: "json", screenshot: true }
4167
+ * @param world - Optional world context.
4168
+ * @public
4169
+ */
4170
+ async addCommandToReport(commandText, commandStatus, content, options = {}, world = null) {
4171
+ const state = {
4172
+ options,
4173
+ world,
4174
+ locate: false,
4175
+ scroll: false,
4176
+ screenshot: options.screenshot ?? false,
4177
+ highlight: options.highlight ?? false,
4178
+ type: Types.REPORT_COMMAND,
4179
+ text: commandText,
4180
+ _text: commandText,
4181
+ operation: "report_command",
4182
+ log: "***** " + commandText + " *****\n",
4183
+ };
4184
+ try {
4185
+ await _preCommand(state, this);
4186
+ const payload = {
4187
+ type: options.type ?? "text",
4188
+ content: content,
4189
+ screenshotId: null,
4190
+ };
4191
+ state.payload = payload;
4192
+ if (commandStatus === "FAILED") {
4193
+ state.throwError = true;
4194
+ throw new Error("Command failed");
4195
+ }
4196
+ }
4197
+ catch (e) {
4198
+ await _commandError(state, e, this);
4199
+ }
4200
+ finally {
4201
+ await _commandFinally(state, this);
4202
+ }
4203
+ }
3385
4204
  async afterStep(world, step) {
3386
4205
  this.stepName = null;
3387
4206
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
@@ -3389,10 +4208,12 @@ class StableBrowser {
3389
4208
  await this.context.browserObject.context.tracing.stopChunk({
3390
4209
  path: path.join(this.context.browserObject.traceFolder, `trace-${this.stepIndex}.zip`),
3391
4210
  });
3392
- await world.attach(JSON.stringify({
3393
- type: "trace",
3394
- traceFilePath: `trace-${this.stepIndex}.zip`,
3395
- }), "application/json+trace");
4211
+ if (world && world.attach) {
4212
+ await world.attach(JSON.stringify({
4213
+ type: "trace",
4214
+ traceFilePath: `trace-${this.stepIndex}.zip`,
4215
+ }), "application/json+trace");
4216
+ }
3396
4217
  // console.log("trace file created", `trace-${this.stepIndex}.zip`);
3397
4218
  }
3398
4219
  }
@@ -3406,6 +4227,36 @@ class StableBrowser {
3406
4227
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-after");
3407
4228
  }
3408
4229
  }
4230
+ this.context.routeResults = await registerAfterStepRoutes(this.context, world);
4231
+ if (this.context.routeResults) {
4232
+ if (world && world.attach) {
4233
+ await world.attach(JSON.stringify(this.context.routeResults), "application/json+intercept-results");
4234
+ }
4235
+ }
4236
+ if (!process.env.TEMP_RUN) {
4237
+ const state = {
4238
+ world,
4239
+ locate: false,
4240
+ scroll: false,
4241
+ screenshot: true,
4242
+ highlight: true,
4243
+ type: Types.STEP_COMPLETE,
4244
+ text: "end of scenario",
4245
+ _text: "end of scenario",
4246
+ operation: "step_complete",
4247
+ log: "***** " + "end of scenario" + " *****\n",
4248
+ };
4249
+ try {
4250
+ await _preCommand(state, this);
4251
+ }
4252
+ catch (e) {
4253
+ await _commandError(state, e, this);
4254
+ }
4255
+ finally {
4256
+ await _commandFinally(state, this);
4257
+ }
4258
+ }
4259
+ networkAfterStep(this.stepName);
3409
4260
  }
3410
4261
  }
3411
4262
  function createTimedPromise(promise, label) {