@dev-blinq/cucumber_client 1.0.1457-stage → 1.0.1458-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.
@@ -1,22 +1,13 @@
1
1
  // define the jsdoc type for the input
2
2
  import { closeContext, initContext, _getDataFile, resetTestData } from "automation_model";
3
3
  import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs";
4
- import { rm } from "fs/promises";
5
4
  import path from "node:path";
6
5
  import url from "node:url";
7
6
  import { getImplementedSteps, parseRouteFiles } from "./implemented_steps.js";
8
7
  import { NamesService, PublishService } from "./services.js";
9
8
  import { BVTStepRunner } from "./step_runner.js";
10
- import { readFile, writeFile } from "node:fs/promises";
11
- import {
12
- loadStepDefinitions,
13
- getCommandsForImplementedStep,
14
- updateStepDefinitions,
15
- getCodePage,
16
- getCucumberStep,
17
- _toRecordingStep,
18
- toMethodName,
19
- } from "./step_utils.js";
9
+ import { readFile, rm, writeFile } from "node:fs/promises";
10
+ import { loadStepDefinitions, getCommandsForImplementedStep, _toRecordingStep, getCucumberStep, getCodePage, toMethodName } from "./step_utils.js";
20
11
  import { parseStepTextParameters } from "../cucumber/utils.js";
21
12
  import { AstBuilder, GherkinClassicTokenMatcher, Parser } from "@cucumber/gherkin";
22
13
  import chokidar from "chokidar";
@@ -29,462 +20,154 @@ import { chromium } from "playwright-core";
29
20
  import { axiosClient } from "../utils/axiosClient.js";
30
21
  import { _generateCodeFromCommand } from "../code_gen/playwright_codeget.js";
31
22
  import { Recording } from "../recording.js";
32
-
33
23
  const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
34
-
35
24
  const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
36
-
37
- const clipboardBridgeScript = `
38
- ;(() => {
39
- if (window.__bvtRecorderClipboardBridgeInitialized) {
40
- console.log('[ClipboardBridge] Already initialized, skipping');
41
- return;
42
- }
43
- window.__bvtRecorderClipboardBridgeInitialized = true;
44
- console.log('[ClipboardBridge] Initializing clipboard bridge');
45
-
46
- const emitPayload = (payload, attempt = 0) => {
47
- const reporter = window.__bvt_reportClipboard;
48
- if (typeof reporter === "function") {
49
- try {
50
- console.log('[ClipboardBridge] Reporting clipboard payload:', payload);
51
- reporter(payload);
52
- } catch (error) {
53
- console.warn("[ClipboardBridge] Failed to report payload", error);
54
- }
55
- return;
56
- }
57
- if (attempt < 5) {
58
- console.log('[ClipboardBridge] Reporter not ready, retrying...', attempt);
59
- setTimeout(() => emitPayload(payload, attempt + 1), 50 * (attempt + 1));
60
- } else {
61
- console.warn('[ClipboardBridge] Reporter never became available');
62
- }
63
- };
64
-
65
- const fileToBase64 = (file) => {
66
- return new Promise((resolve) => {
67
- try {
68
- const reader = new FileReader();
69
- reader.onload = () => {
70
- const { result } = reader;
71
- if (typeof result === "string") {
72
- const index = result.indexOf("base64,");
73
- resolve(index !== -1 ? result.substring(index + 7) : result);
74
- return;
75
- }
76
- if (result instanceof ArrayBuffer) {
77
- const bytes = new Uint8Array(result);
78
- let binary = "";
79
- const chunk = 0x8000;
80
- for (let i = 0; i < bytes.length; i += chunk) {
81
- binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
82
- }
83
- resolve(btoa(binary));
84
- return;
85
- }
86
- resolve(null);
87
- };
88
- reader.onerror = () => resolve(null);
89
- reader.readAsDataURL(file);
90
- } catch (error) {
91
- console.warn("[ClipboardBridge] Failed to serialize file", error);
92
- resolve(null);
93
- }
94
- });
95
- };
96
-
97
- const handleClipboardEvent = async (event) => {
98
- try {
99
- console.log('[ClipboardBridge] Handling clipboard event:', event.type);
100
- const payload = { trigger: event.type };
101
- const clipboardData = event.clipboardData;
102
-
103
- if (clipboardData) {
104
- try {
105
- const text = clipboardData.getData("text/plain");
106
- if (text) {
107
- payload.text = text;
108
- console.log('[ClipboardBridge] Captured text:', text.substring(0, 50));
109
- }
110
- } catch (error) {
111
- console.warn("[ClipboardBridge] Could not read text/plain", error);
112
- }
113
-
114
- try {
115
- const html = clipboardData.getData("text/html");
116
- if (html) {
117
- payload.html = html;
118
- console.log('[ClipboardBridge] Captured HTML:', html.substring(0, 50));
119
- }
120
- } catch (error) {
121
- console.warn("[ClipboardBridge] Could not read text/html", error);
122
- }
123
-
124
- const files = clipboardData.files;
125
- if (files && files.length > 0) {
126
- console.log('[ClipboardBridge] Processing files:', files.length);
127
- const serialized = [];
128
- for (const file of files) {
129
- const data = await fileToBase64(file);
130
- if (data) {
131
- serialized.push({
132
- name: file.name,
133
- type: file.type,
134
- lastModified: file.lastModified,
135
- data,
136
- });
137
- }
138
- }
139
- if (serialized.length > 0) {
140
- payload.files = serialized;
141
- }
142
- }
143
- }
144
-
145
- if (!payload.text) {
146
- try {
147
- const selection = window.getSelection?.();
148
- const selectionText = selection?.toString?.();
149
- if (selectionText) {
150
- payload.text = selectionText;
151
- console.log('[ClipboardBridge] Using selection text:', selectionText.substring(0, 50));
152
- }
153
- } catch {
154
- // Ignore selection access errors.
155
- }
156
- }
157
-
158
- emitPayload(payload);
159
- } catch (error) {
160
- console.warn("[ClipboardBridge] Could not process event", error);
161
- }
162
- };
163
-
164
- // NEW: Function to apply clipboard data to the page
165
- window.__bvt_applyClipboardData = (payload) => {
166
- console.log('[ClipboardBridge] Applying clipboard data:', payload);
167
-
168
- if (!payload) {
169
- console.warn('[ClipboardBridge] No payload provided');
170
- return false;
171
- }
172
-
173
- try {
174
- // Create DataTransfer object
175
- let dataTransfer = null;
176
- try {
177
- dataTransfer = new DataTransfer();
178
- console.log('[ClipboardBridge] DataTransfer created');
179
- } catch (error) {
180
- console.warn('[ClipboardBridge] Could not create DataTransfer', error);
181
- }
182
-
183
- if (dataTransfer) {
184
- if (payload.text) {
185
- try {
186
- dataTransfer.setData("text/plain", payload.text);
187
- console.log('[ClipboardBridge] Set text/plain:', payload.text.substring(0, 50));
188
- } catch (error) {
189
- console.warn('[ClipboardBridge] Failed to set text/plain', error);
190
- }
191
- }
192
- if (payload.html) {
193
- try {
194
- dataTransfer.setData("text/html", payload.html);
195
- console.log('[ClipboardBridge] Set text/html:', payload.html.substring(0, 50));
196
- } catch (error) {
197
- console.warn('[ClipboardBridge] Failed to set text/html', error);
198
- }
199
- }
200
- }
201
-
202
- // Get target element
203
- let target = document.activeElement || document.body;
204
- console.log('[ClipboardBridge] Target element:', {
205
- tagName: target.tagName,
206
- type: target.type,
207
- isContentEditable: target.isContentEditable,
208
- id: target.id,
209
- className: target.className
210
- });
211
-
212
- // Try synthetic paste event first
213
- let pasteHandled = false;
214
- if (dataTransfer && target && typeof target.dispatchEvent === "function") {
215
- try {
216
- const pasteEvent = new ClipboardEvent("paste", {
217
- clipboardData: dataTransfer,
218
- bubbles: true,
219
- cancelable: true,
220
- });
221
- pasteHandled = target.dispatchEvent(pasteEvent);
222
- console.log('[ClipboardBridge] Paste event dispatched, handled:', pasteHandled);
223
- } catch (error) {
224
- console.warn('[ClipboardBridge] Failed to dispatch paste event', error);
225
- }
226
- }
227
-
228
-
229
- console.log('[ClipboardBridge] Paste event not handled, trying fallback methods');
230
-
231
- // Fallback: Try execCommand with HTML first (for contenteditable)
232
- if (payload.html && target.isContentEditable) {
233
- console.log('[ClipboardBridge] Trying execCommand insertHTML');
234
- try {
235
- const inserted = document.execCommand('insertHTML', false, payload.html);
236
- if (inserted) {
237
- console.log('[ClipboardBridge] Successfully inserted HTML via execCommand');
238
- return true;
239
- }
240
- } catch (error) {
241
- console.warn('[ClipboardBridge] execCommand insertHTML failed', error);
242
- }
243
-
244
- // Try Range API for HTML
245
- console.log('[ClipboardBridge] Trying Range API for HTML');
246
- try {
247
- const selection = window.getSelection?.();
248
- if (selection && selection.rangeCount > 0) {
249
- const range = selection.getRangeAt(0);
250
- range.deleteContents();
251
- const fragment = range.createContextualFragment(payload.html);
252
- range.insertNode(fragment);
253
- range.collapse(false);
254
- console.log('[ClipboardBridge] Successfully inserted HTML via Range API');
255
- return true;
256
- }
257
- } catch (error) {
258
- console.warn('[ClipboardBridge] Range API HTML insertion failed', error);
259
- }
260
- }
261
-
262
- // Fallback: Try execCommand with text
263
- if (payload.text) {
264
- console.log('[ClipboardBridge] Trying execCommand insertText');
265
- try {
266
- const inserted = document.execCommand('insertText', false, payload.text);
267
- if (inserted) {
268
- console.log('[ClipboardBridge] Successfully inserted text via execCommand');
269
- return true;
270
- }
271
- } catch (error) {
272
- console.warn('[ClipboardBridge] execCommand insertText failed', error);
273
- }
274
-
275
- // Try Range API for text
276
- if (target.isContentEditable) {
277
- console.log('[ClipboardBridge] Trying Range API for text');
278
- try {
279
- const selection = window.getSelection?.();
280
- if (selection && selection.rangeCount > 0) {
281
- const range = selection.getRangeAt(0);
282
- range.deleteContents();
283
- range.insertNode(document.createTextNode(payload.text));
284
- range.collapse(false);
285
- console.log('[ClipboardBridge] Successfully inserted text via Range API');
286
- return true;
287
- }
288
- } catch (error) {
289
- console.warn('[ClipboardBridge] Range API text insertion failed', error);
290
- }
291
- }
292
-
293
- // Last resort: Direct value assignment for input/textarea
294
- if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') {
295
- console.log('[ClipboardBridge] Trying direct value assignment');
296
- try {
297
- const start = target.selectionStart ?? target.value.length ?? 0;
298
- const end = target.selectionEnd ?? target.value.length ?? 0;
299
- const value = target.value ?? "";
300
- const text = payload.text;
301
- target.value = value.slice(0, start) + text + value.slice(end);
302
- const caret = start + text.length;
303
- if (typeof target.setSelectionRange === 'function') {
304
- target.setSelectionRange(caret, caret);
305
- }
306
- target.dispatchEvent(new Event('input', { bubbles: true }));
307
- console.log('[ClipboardBridge] Successfully set value directly');
308
- return true;
309
- } catch (error) {
310
- console.warn('[ClipboardBridge] Direct value assignment failed', error);
311
- }
312
- }
313
- }
314
-
315
- console.warn('[ClipboardBridge] All paste methods failed');
316
- return false;
317
- } catch (error) {
318
- console.error('[ClipboardBridge] Error applying clipboard data:', error);
319
- return false;
320
- }
321
- };
322
-
323
- // Set up event listeners for copy/cut
324
- document.addEventListener(
325
- "copy",
326
- (event) => {
327
- void handleClipboardEvent(event);
328
- },
329
- true
330
- );
331
- document.addEventListener(
332
- "cut",
333
- (event) => {
334
- void handleClipboardEvent(event);
335
- },
336
- true
337
- );
338
-
339
- console.log('[ClipboardBridge] Clipboard bridge initialized successfully');
340
- })();
341
- `;
342
-
343
25
  export function getInitScript(config, options) {
344
- const preScript = `
26
+ const preScript = `
345
27
  window.__bvt_Recorder_config = ${JSON.stringify(config ?? null)};
346
28
  window.__PW_options = ${JSON.stringify(options ?? null)};
347
29
  `;
348
- const recorderScript = readFileSync(
349
- path.join(__dirname, "..", "..", "assets", "bundled_scripts", "recorder.js"),
350
- "utf8"
351
- );
352
- return preScript + recorderScript + clipboardBridgeScript;
30
+ const recorderScript = readFileSync(path.join(__dirname, "..", "..", "assets", "bundled_scripts", "recorder.js"), "utf8");
31
+ return preScript + recorderScript;
353
32
  }
354
-
355
33
  async function evaluate(frame, script) {
356
- if (frame.isDetached()) return;
357
- const url = frame.url();
358
- if (url === "" || url === "about:blank") return;
359
- await frame.evaluate(script);
360
- for (const childFrame of frame.childFrames()) {
361
- await evaluate(childFrame, script);
362
- }
34
+ if (frame.isDetached())
35
+ return;
36
+ const url = frame.url();
37
+ if (url === "" || url === "about:blank")
38
+ return;
39
+ await frame.evaluate(script);
40
+ for (const childFrame of frame.childFrames()) {
41
+ await evaluate(childFrame, script);
42
+ }
363
43
  }
364
-
365
- async function findNestedFrameSelector(frame, obj) {
366
- try {
367
- const parent = frame.parentFrame();
368
- if (!parent) return { children: obj };
369
- const frameElement = await frame.frameElement();
370
- if (!frameElement) return;
371
- const selectors = await parent.evaluate((element) => {
372
- return window.__bvt_Recorder.locatorGenerator.getElementLocators(element, { excludeText: true }).locators;
373
- }, frameElement);
374
- return findNestedFrameSelector(parent, { children: obj, selectors });
375
- } catch (e) {
376
- socketLogger.error(`Error in script evaluation: ${getErrorMessage(e)}`, undefined, "findNestedFrameSelector");
377
- }
44
+ async function findNestedFrameSelector(frame, obj = {}) {
45
+ try {
46
+ const parent = frame.parentFrame();
47
+ if (!parent)
48
+ return { children: obj };
49
+ const frameElement = await frame.frameElement();
50
+ if (!frameElement)
51
+ return;
52
+ const selectors = await frameElement.evaluate((element) => {
53
+ const recorder = window.__bvt_Recorder;
54
+ return recorder.locatorGenerator.getElementLocators(element, { excludeText: true }).locators;
55
+ });
56
+ return findNestedFrameSelector(parent, { children: obj, selectors });
57
+ }
58
+ catch (e) {
59
+ socketLogger.error(`Error in script evaluation: ${getErrorMessage(e)}`, undefined, "findNestedFrameSelector");
60
+ }
378
61
  }
379
62
  const transformFillAction = (action, el) => {
380
- if (el.tagName.toLowerCase() === "input") {
381
- switch (el.type) {
382
- case "date":
383
- case "datetime-local":
384
- case "month":
385
- case "time":
386
- case "week":
387
- case "range":
388
- case "color":
389
- return {
390
- type: "set_input",
391
- value: action.text,
392
- };
63
+ if (el.tagName.toLowerCase() === "input") {
64
+ switch (el.type) {
65
+ case "date":
66
+ case "datetime-local":
67
+ case "month":
68
+ case "time":
69
+ case "week":
70
+ case "range":
71
+ case "color":
72
+ return {
73
+ type: "set_input",
74
+ value: action.text,
75
+ };
76
+ }
393
77
  }
394
- }
395
- return {
396
- type: "fill_element",
397
- value: action.text,
398
- };
399
- };
400
- const transformClickAction = (action, el, isVerify, isPopupCloseClick, isInHoverMode, isSnapshot) => {
401
- if (isInHoverMode) {
402
- return {
403
- type: "hover_element",
404
- };
405
- }
406
- if (isVerify) {
407
- return {
408
- type: "verify_page_contains_text",
409
- value: el.value ?? el.text,
410
- };
411
- }
412
- if (isPopupCloseClick) {
413
78
  return {
414
- type: "popup_close",
79
+ type: "fill_element",
80
+ value: action.text,
415
81
  };
416
- }
417
- if (isSnapshot) {
82
+ };
83
+ const transformClickAction = (action, el, isVerify, isPopupCloseClick, isInHoverMode, isSnapshot) => {
84
+ if (isInHoverMode) {
85
+ return {
86
+ type: "hover_element",
87
+ };
88
+ }
89
+ if (isVerify) {
90
+ return {
91
+ type: "verify_page_contains_text",
92
+ value: el.value ?? el.text,
93
+ };
94
+ }
95
+ if (isPopupCloseClick) {
96
+ return {
97
+ type: "popup_close",
98
+ };
99
+ }
100
+ if (isSnapshot) {
101
+ return {
102
+ type: "snapshot_element",
103
+ value: action.value,
104
+ };
105
+ }
418
106
  return {
419
- type: "snapshot_element",
420
- value: action.value,
107
+ type: "click_element",
421
108
  };
422
- }
423
- return {
424
- type: "click_element",
425
- };
426
109
  };
427
110
  const transformAction = (action, el, isVerify, isPopupCloseClick, isInHoverMode, isSnapshot) => {
428
- switch (action.name) {
429
- case "click":
430
- return transformClickAction(action, el, isVerify, isPopupCloseClick, isInHoverMode, isSnapshot);
431
- case "fill": {
432
- return transformFillAction(action, el);
433
- }
434
- case "select": {
435
- return {
436
- type: "select_combobox",
437
- value: action.options[0],
438
- };
439
- }
440
-
441
- case "check": {
442
- return {
443
- type: "check_element",
444
- check: true,
445
- };
446
- }
447
- case "uncheck": {
448
- return {
449
- type: "check_element",
450
- check: false,
451
- };
452
- }
453
- case "assertText": {
454
- return {
455
- type: "verify_page_contains_text",
456
- value: action.text,
457
- };
458
- }
459
- case "press": {
460
- return {
461
- type: "press_key",
462
- value: action.key,
463
- };
464
- }
465
- case "setInputFiles": {
466
- return {
467
- type: "set_input_files",
468
- files: action.files,
469
- };
470
- }
471
- default: {
472
- socketLogger.error(`Action not supported: ${action.name}`);
473
- console.log("action not supported", action);
474
- throw new Error("action not supported");
475
- }
476
- }
111
+ switch (action.name) {
112
+ case "click":
113
+ return transformClickAction(action, el, isVerify, isPopupCloseClick, isInHoverMode, isSnapshot);
114
+ case "fill": {
115
+ return transformFillAction(action, el);
116
+ }
117
+ case "select": {
118
+ return {
119
+ type: "select_combobox",
120
+ value: action.options?.[0] ?? "",
121
+ };
122
+ }
123
+ case "check": {
124
+ return {
125
+ type: "check_element",
126
+ check: true,
127
+ };
128
+ }
129
+ case "uncheck": {
130
+ return {
131
+ type: "check_element",
132
+ check: false,
133
+ };
134
+ }
135
+ case "assertText": {
136
+ return {
137
+ type: "verify_page_contains_text",
138
+ value: action.text,
139
+ };
140
+ }
141
+ case "press": {
142
+ return {
143
+ type: "press_key",
144
+ value: action.key,
145
+ };
146
+ }
147
+ case "setInputFiles": {
148
+ return {
149
+ type: "set_input_files",
150
+ files: action.files,
151
+ };
152
+ }
153
+ default: {
154
+ socketLogger.error(`Action not supported: ${action.name}`);
155
+ console.log("action not supported", action);
156
+ throw new Error("action not supported");
157
+ }
158
+ }
477
159
  };
478
160
  const diffPaths = (currentPath, newPath) => {
479
- const currentDomain = new URL(currentPath).hostname;
480
- const newDomain = new URL(newPath).hostname;
481
- if (currentDomain !== newDomain) {
482
- return true;
483
- } else {
484
- const currentRoute = new URL(currentPath).pathname;
485
- const newRoute = new URL(newPath).pathname;
486
- return currentRoute !== newRoute;
487
- }
161
+ const currentDomain = new URL(currentPath).hostname;
162
+ const newDomain = new URL(newPath).hostname;
163
+ if (currentDomain !== newDomain) {
164
+ return true;
165
+ }
166
+ else {
167
+ const currentRoute = new URL(currentPath).pathname;
168
+ const newRoute = new URL(newPath).pathname;
169
+ return currentRoute !== newRoute;
170
+ }
488
171
  };
489
172
  /**
490
173
  * @typedef {Object} BVTRecorderInput
@@ -495,1993 +178,1427 @@ const diffPaths = (currentPath, newPath) => {
495
178
  * @property {Object} logger
496
179
  */
497
180
  export class BVTRecorder {
498
- #currentURL = "";
499
- #activeFrame = null;
500
- #mode = "noop";
501
- #previousMode = "noop";
502
- #remoteDebuggerPort = null;
503
- /**
504
- *
505
- * @param {BVTRecorderInput} initialState
506
- */
507
- constructor(initialState) {
508
- Object.assign(this, initialState);
509
- this.screenshotMap = new Map();
510
- this.snapshotMap = new Map();
511
- this.scenariosStepsMap = new Map();
512
- this.namesService = new NamesService({
513
- screenshotMap: this.screenshotMap,
514
- TOKEN: this.TOKEN,
515
- projectDir: this.projectDir,
516
- logger: this.logger,
517
- });
518
- this.workspaceService = new PublishService(this.TOKEN);
519
- this.pageSet = new Set();
520
- this.lastKnownUrlPath = "";
521
- this.world = { attach: () => { } };
522
- this.shouldTakeScreenshot = true;
523
- this.watcher = null;
524
- this.networkEventsFolder = path.join(tmpdir(), "blinq_network_events");
525
- this.tempProjectFolder = `${tmpdir()}/bvt_temp_project_${Math.floor(Math.random() * 1000000)}`;
526
- this.tempSnapshotsFolder = path.join(this.tempProjectFolder, "data/snapshots");
527
-
528
- if (existsSync(this.networkEventsFolder)) {
529
- rmSync(this.networkEventsFolder, { recursive: true, force: true });
530
- }
531
- }
532
- events = {
533
- onFrameNavigate: "BVTRecorder.onFrameNavigate",
534
- onPageClose: "BVTRecorder.onPageClose",
535
- onBrowserClose: "BVTRecorder.onBrowserClose",
536
- onNewCommand: "BVTRecorder.command.new",
537
- onCommandDetails: "BVTRecorder.onCommandDetails",
538
- onStepDetails: "BVTRecorder.onStepDetails",
539
- getTestData: "BVTRecorder.getTestData",
540
- onGoto: "BVTRecorder.onGoto",
541
- cmdExecutionStart: "BVTRecorder.cmdExecutionStart",
542
- cmdExecutionSuccess: "BVTRecorder.cmdExecutionSuccess",
543
- cmdExecutionError: "BVTRecorder.cmdExecutionError",
544
- interceptResults: "BVTRecorder.interceptResults",
545
- onDebugURLChange: "BVTRecorder.onDebugURLChange",
546
- updateCommand: "BVTRecorder.updateCommand",
547
- browserStateSync: "BrowserService.stateSync",
548
- browserStateError: "BrowserService.stateError",
549
- clipboardPush: "BrowserService.clipboardPush",
550
- clipboardError: "BrowserService.clipboardError",
551
- };
552
- bindings = {
553
- __bvt_recordCommand: async ({ frame, page, context }, event) => {
554
- this.#activeFrame = frame;
555
- const nestFrmLoc = await findNestedFrameSelector(frame);
556
- this.logger.info(`Time taken for action: ${event.statistics.time}`);
557
- await this.onAction({ ...event, nestFrmLoc });
558
- },
559
- __bvt_getMode: async () => {
560
- return this.#mode;
561
- },
562
- __bvt_setMode: async (src, mode) => {
563
- await this.setMode(mode);
564
- },
565
- __bvt_revertMode: async () => {
566
- await this.revertMode();
567
- },
568
- __bvt_recordPageClose: async ({ page }) => {
569
- this.pageSet.delete(page);
570
- },
571
- __bvt_closePopups: async () => {
572
- await this.onClosePopup();
573
- },
574
- __bvt_log: async (src, message) => {
575
- this.logger.info(`Inside Browser: ${message}`);
576
- },
577
- __bvt_getObject: (_src, obj) => {
578
- this.processObject(obj);
579
- },
580
- __bvt_reportClipboard: async ({ page }, payload) => {
581
- try {
582
- if (!payload) {
583
- return;
584
- }
585
- const activePage = this.browserEmitter?.getSelectedPage() ?? this.page;
586
- if (activePage && activePage !== page) {
587
- return;
588
- }
589
- const pageUrl = typeof page?.url === "function" ? page.url() : null;
590
- this.sendEvent(this.events.clipboardPush, {
591
- data: payload,
592
- trigger: payload?.trigger ?? "copy",
593
- pageUrl,
594
- });
595
- } catch (error) {
596
- this.logger.error("Error forwarding clipboard payload from page", error);
597
- }
598
- },
599
- };
600
-
601
- getSnapshot = async (attr) => {
602
- const selector = `[__bvt_snapshot="${attr}"]`;
603
- const locator = await this.web.page.locator(selector);
604
- const snapshot = await locator.ariaSnapshot();
605
- return snapshot;
606
- };
607
-
608
- processObject = async ({ type, action, value }) => {
609
- switch (type) {
610
- case "snapshot-element": {
611
- if (action === "get-template") {
612
- return true;
613
- }
614
- break;
615
- }
616
- default: {
617
- console.log("Unknown object type", type);
618
- break;
619
- }
620
- }
621
- };
622
-
623
- getPWScript() {
624
- const pwFolder = path.join(__dirname, "..", "..", "assets", "preload", "pw_utils");
625
- const result = [];
626
- for (const script of readdirSync(pwFolder)) {
627
- const path = path.join(pwFolder, script);
628
- const content = readFileSync(path, "utf8");
629
- result.push(content);
630
- }
631
- return result;
632
- }
633
- getRecorderScripts() {
634
- const recorderFolder = path.join(__dirname, "..", "..", "assets", "preload", "recorder");
635
- const result = [];
636
- for (const script of readdirSync(recorderFolder)) {
637
- const path = path.join(recorderFolder, script);
638
- const content = readFileSync(path, "utf8");
639
- result.push(content);
640
- }
641
- return result;
642
- }
643
- getInitScripts(config) {
644
- return getInitScript(config, {
645
- sdkLanguage: "javascript",
646
- testIdAttributeName: "blinq-test-id",
647
- stableRafCount: 0,
648
- browserName: this.browser?.browserType().name(),
649
- inputFileRoleTextbox: false,
650
- customEngines: [],
651
- isUnderTest: true,
652
- });
653
- }
654
-
655
- async _initBrowser({ url }) {
656
- if (process.env.CDP_LISTEN_PORT === undefined) {
657
- this.#remoteDebuggerPort = await findAvailablePort();
658
- process.env.CDP_LISTEN_PORT = this.#remoteDebuggerPort;
659
- } else {
660
- this.#remoteDebuggerPort = process.env.CDP_LISTEN_PORT;
661
- }
662
-
663
- // this.stepRunner.setRemoteDebugPort(this.#remoteDebuggerPort);
664
- this.world = { attach: () => { } };
665
-
666
- const ai_config_file = path.join(this.projectDir, "ai_config.json");
667
- let ai_config = {};
668
- if (existsSync(ai_config_file)) {
669
- try {
670
- ai_config = JSON.parse(readFileSync(ai_config_file, "utf8"));
671
- } catch (error) {
672
- this.logger.error("Error reading ai_config.json", error);
673
- }
674
- }
675
- this.config = ai_config;
676
- const initScripts = {
677
- // recorderCjs: injectedScriptSource,
678
- scripts: [
679
- this.getInitScripts(ai_config),
680
- `\ndelete Object.getPrototypeOf(navigator).webdriver;${process.env.WINDOW_DEBUGGER ? "window.debug=true;\n" : ""}`,
681
- ],
682
- };
683
-
684
- const scenario = { pickle: this.scenarioDoc };
685
- const bvtContext = await initContext(url, false, false, this.world, 450, initScripts, this.envName, scenario);
686
- this.bvtContext = bvtContext;
687
- this.stepRunner = new BVTStepRunner({
688
- projectDir: this.projectDir,
689
- sendExecutionStatus: (data) => {
690
- if (data && data.type) {
691
- switch (data.type) {
692
- case "cmdExecutionStart":
693
- this.sendEvent(this.events.cmdExecutionStart, data);
694
- break;
695
- case "cmdExecutionSuccess":
696
- this.sendEvent(this.events.cmdExecutionSuccess, data);
697
- break;
698
- case "cmdExecutionError":
699
- this.sendEvent(this.events.cmdExecutionError, data);
700
- break;
701
- case "interceptResults":
702
- this.sendEvent(this.events.interceptResults, data);
703
- break;
704
- default:
705
- break;
706
- }
707
- }
708
- },
709
- bvtContext: this.bvtContext,
710
- });
711
- this.context = bvtContext.playContext;
712
- this.web = bvtContext.stable || bvtContext.web;
713
- this.web.tryAllStrategies = true;
714
- this.page = bvtContext.page;
715
- this.pageSet.add(this.page);
716
- this.lastKnownUrlPath = this._updateUrlPath();
717
- const browser = await this.context.browser();
718
- this.browser = browser;
719
-
720
- // add bindings
721
- for (const [name, handler] of Object.entries(this.bindings)) {
722
- await this.context.exposeBinding(name, handler);
723
- }
724
- this._watchTestData();
725
- this.web.onRestoreSaveState = async (url) => {
726
- await this._initBrowser({ url });
727
- this._addPagelisteners(this.context);
728
- this._addFrameNavigateListener(this.page);
181
+ #currentURL = "";
182
+ #activeFrame = null;
183
+ #mode = "noop";
184
+ #previousMode = "noop";
185
+ #remoteDebuggerPort = null;
186
+ envName;
187
+ projectDir;
188
+ TOKEN;
189
+ sendEvent;
190
+ logger;
191
+ screenshotMap = new Map();
192
+ snapshotMap = new Map();
193
+ scenariosStepsMap = new Map();
194
+ namesService;
195
+ workspaceService;
196
+ pageSet = new Set();
197
+ lastKnownUrlPath = "";
198
+ world = {
199
+ attach: async () => { },
200
+ parameters: {},
201
+ log: (message) => {
202
+ socketLogger.log.call(socketLogger, "info", message, undefined, "Cucumber.JS World");
203
+ },
729
204
  };
730
-
731
- // create a second browser for locator generation
732
- this.backgroundBrowser = await chromium.launch({
733
- headless: true,
734
- });
735
- this.backgroundContext = await this.backgroundBrowser.newContext({});
736
- await this.backgroundContext.addInitScript({ content: this.getInitScripts(this.config) });
737
- await this.backgroundContext.newPage();
738
- }
739
- async onClosePopup() {
740
- // console.log("close popups");
741
- await this.bvtContext.web.closeUnexpectedPopups();
742
- }
743
- async evaluateInAllFrames(context, script) {
744
- // retry 3 times
745
- for (let i = 0; i < 3; i++) {
746
- try {
747
- for (const page of context.pages()) {
748
- await evaluate(page.mainFrame(), script);
749
- }
750
- return;
751
- } catch (error) {
752
- // console.error("Error evaluting in context:", error);
753
- this.logger.error("Error evaluating in context:", error);
754
- }
755
- }
756
- }
757
-
758
- getMode() {
759
- // console.log("getMode", this.#mode);
760
- this.logger.info("Current mode:", this.#mode);
761
- return this.#mode;
762
- }
763
-
764
- async setMode(mode) {
765
- await this.evaluateInAllFrames(this.context, `window.__bvt_Recorder.mode = "${mode}";`);
766
- this.#previousMode = this.#mode;
767
- this.#mode = mode;
768
- }
769
- async revertMode() {
770
- await this.setMode(this.#previousMode);
771
- }
772
-
773
- async _openTab({ url }) {
774
- // add listeners for new pages
775
- this._addPagelisteners(this.context);
776
-
777
- await this.page.goto(url, {
778
- waitUntil: "domcontentloaded",
779
- timeout: this.config.page_timeout ?? 60_000,
780
- });
781
- // add listener for frame navigation on current tab
782
- this._addFrameNavigateListener(this.page);
783
-
784
- // eval init script on current tab
785
- // await this._initPage(this.page);
786
- this.#currentURL = url;
787
-
788
- await this.page.dispatchEvent("html", "scroll");
789
- await delay(1000);
790
- }
791
- _addFrameNavigateListener(page) {
792
- page.on("close", () => {
793
- try {
794
- if (!this.pageSet.has(page)) return;
795
- // console.log(this.context.pages().length);
796
- if (this.context.pages().length > 0) {
797
- this.sendEvent(this.events.onPageClose);
798
- } else {
799
- // closed all tabs
800
- this.sendEvent(this.events.onBrowserClose);
801
- }
802
- } catch (error) {
803
- this.logger.error("Error in page close event");
804
- this.logger.error(error);
805
- console.error("Error in page close event");
806
- console.error(error);
807
- }
808
- });
809
-
810
- page.on("framenavigated", async (frame) => {
811
- try {
812
- if (frame !== page.mainFrame()) return;
813
- this.handlePageTransition();
814
- } catch (error) {
815
- this.logger.error("Error in handlePageTransition event");
816
- this.logger.error(error);
817
- console.error("Error in handlePageTransition event");
818
- console.error(error);
819
- }
820
- try {
821
- if (frame !== this.#activeFrame) return;
822
-
823
- // hack to sync the action event with the frame navigation
824
- await this.storeScreenshot({
825
- element: { inputID: "frame" },
205
+ shouldTakeScreenshot = true;
206
+ watcher = null;
207
+ networkEventsFolder;
208
+ tempProjectFolder;
209
+ tempSnapshotsFolder;
210
+ config = {};
211
+ bvtContext;
212
+ stepRunner;
213
+ context;
214
+ web;
215
+ page;
216
+ browser = null;
217
+ backgroundBrowser;
218
+ backgroundContext;
219
+ timerId = null;
220
+ previousIndex = null;
221
+ previousHistoryLength = null;
222
+ previousEntries = null;
223
+ previousUrl = null;
224
+ scenarioDoc;
225
+ isVerify = false;
226
+ /**
227
+ * @param initialState Initial recorder state and dependencies
228
+ */
229
+ constructor(initialState) {
230
+ this.envName = initialState.envName;
231
+ this.projectDir = initialState.projectDir;
232
+ this.TOKEN = initialState.TOKEN;
233
+ this.sendEvent = initialState.sendEvent;
234
+ this.logger = initialState.logger;
235
+ this.namesService = new NamesService({
236
+ screenshotMap: this.screenshotMap,
237
+ TOKEN: this.TOKEN,
238
+ projectDir: this.projectDir,
239
+ logger: this.logger,
826
240
  });
827
-
828
- const newUrl = frame.url();
829
- const newPath = new URL(newUrl).pathname;
830
- const newTitle = await frame.title();
831
- const changed = diffPaths(this.#currentURL, newUrl);
832
-
833
- if (changed) {
834
- this.sendEvent(this.events.onFrameNavigate, { url: newPath, title: newTitle });
835
- this.#currentURL = newUrl;
836
- }
837
- } catch (error) {
838
- this.logger.error("Error in frame navigate event");
839
- this.logger.error(error);
840
- console.error("Error in frame navigate event");
841
- // console.error(error);
842
- }
843
- });
844
- }
845
-
846
- hasHistoryReplacementAtIndex(previousEntries, currentEntries, index) {
847
- if (!previousEntries || !currentEntries) return false;
848
- if (index >= previousEntries.length || index >= currentEntries.length) return false;
849
-
850
- const prevEntry = previousEntries[index];
851
- // console.log("prevEntry", prevEntry);
852
- const currEntry = currentEntries[index];
853
- // console.log("currEntry", currEntry);
854
-
855
- // Check if the entry at this index has been replaced
856
- return prevEntry.id !== currEntry.id;
857
- }
858
-
859
- // Even simpler approach for your specific case
860
- analyzeTransitionType(entries, currentIndex, currentEntry) {
861
- // console.log("Analyzing transition type");
862
- // console.log("===========================");
863
- // console.log("Current Index:", currentIndex);
864
- // console.log("Current Entry:", currentEntry);
865
- // console.log("Current Entries:", entries);
866
- // console.log("Current entries length:", entries.length);
867
- // console.log("===========================");
868
- // console.log("Previous Index:", this.previousIndex);
869
- // // console.log("Previous Entry:", this.previousEntries[this.previousIndex]);
870
- // console.log("Previous Entries:", this.previousEntries);
871
- // console.log("Previous entries length:", this.previousHistoryLength);
872
-
873
- if (this.previousIndex === null || this.previousHistoryLength === null || !this.previousEntries) {
874
- return {
875
- action: "initial",
876
- };
877
- }
878
-
879
- const indexDiff = currentIndex - this.previousIndex;
880
- const lengthDiff = entries.length - this.previousHistoryLength;
881
-
882
- // Backward navigation
883
- if (indexDiff < 0) {
884
- return { action: "back" };
885
- }
886
-
887
- // Forward navigation
888
- if (indexDiff > 0 && lengthDiff === 0) {
889
- // Check if the entry at current index is the same as before
890
- const entryReplaced = this.hasHistoryReplacementAtIndex(this.previousEntries, entries, currentIndex);
891
-
892
- if (entryReplaced) {
893
- return { action: "navigate" }; // New navigation that replaced forward history
894
- } else {
895
- return { action: "forward" }; // True forward navigation
896
- }
897
- }
898
-
899
- // New navigation (history grew)
900
- if (lengthDiff > 0) {
901
- return { action: "navigate" };
902
- }
903
-
904
- // Same position, same length
905
- if (lengthDiff <= 0) {
906
- const entryReplaced = this.hasHistoryReplacementAtIndex(this.previousEntries, entries, currentIndex);
907
-
908
- return entryReplaced ? { action: "navigate" } : { action: "reload" };
909
- }
910
-
911
- return { action: "unknown" };
912
- }
913
-
914
- async getCurrentTransition() {
915
- if (this?.web?.browser?._name !== "chromium") {
916
- return;
917
- }
918
- const client = await this.context.newCDPSession(this.web.page);
919
-
920
- try {
921
- const result = await client.send("Page.getNavigationHistory");
922
- const entries = result.entries;
923
- const currentIndex = result.currentIndex;
924
-
925
- const currentEntry = entries[currentIndex];
926
- const transitionInfo = this.analyzeTransitionType(entries, currentIndex, currentEntry);
927
- this.previousIndex = currentIndex;
928
- this.previousHistoryLength = entries.length;
929
- this.previousUrl = currentEntry.url;
930
- this.previousEntries = [...entries]; // Store a copy of current entries
931
-
932
- return {
933
- currentEntry,
934
- navigationAction: transitionInfo.action,
935
- };
936
- } catch (error) {
937
- this.logger.error("Error in getCurrentTransition event");
938
- this.logger.error(error);
939
- console.error("Error in getTransistionType event", error);
940
- } finally {
941
- await client.detach();
942
- }
943
- }
944
- userInitiatedTransitionTypes = ["typed", "address_bar"];
945
- async handlePageTransition() {
946
- const transition = await this.getCurrentTransition();
947
- if (!transition) return;
948
-
949
- const { currentEntry, navigationAction } = transition;
950
-
951
- switch (navigationAction) {
952
- case "initial":
953
- // console.log("Initial navigation, no action taken");
954
- return;
955
- case "navigate":
956
- // console.log("transitionType", transition.transitionType);
957
- // console.log("sending onGoto event", { url: currentEntry.url,
958
- // type: "navigate", });
959
- if (this.userInitiatedTransitionTypes.includes(currentEntry.transitionType)) {
960
- const env = JSON.parse(readFileSync(this.envName), "utf8");
961
- const baseUrl = env.baseUrl;
962
- let url = currentEntry.userTypedURL;
963
- if (baseUrl && url.startsWith(baseUrl)) {
964
- url = url.replace(baseUrl, "{{env.baseUrl}}");
965
- }
966
- // console.log("User initiated transition");
967
- this.sendEvent(this.events.onGoto, { url, type: "navigate" });
241
+ this.workspaceService = new PublishService(this.TOKEN);
242
+ this.networkEventsFolder = path.join(tmpdir(), "blinq_network_events");
243
+ this.tempProjectFolder = `${tmpdir()}/bvt_temp_project_${Math.floor(Math.random() * 1000000)}`;
244
+ this.tempSnapshotsFolder = path.join(this.tempProjectFolder, "data/snapshots");
245
+ if (existsSync(this.networkEventsFolder)) {
246
+ rmSync(this.networkEventsFolder, { recursive: true, force: true });
968
247
  }
969
- return;
970
- case "back":
971
- // console.log("User navigated back");
972
- // console.log("sending onGoto event", {
973
- // type: "back",
974
- // });
975
- this.sendEvent(this.events.onGoto, { type: "back" });
976
- return;
977
- case "forward":
978
- // console.log("User navigated forward"); console.log("sending onGoto event", { type: "forward", });
979
- this.sendEvent(this.events.onGoto, { type: "forward" });
980
- return;
981
- default:
982
- this.sendEvent(this.events.onGoto, { type: "unknown" });
983
- return;
984
248
  }
985
- }
986
-
987
- async getCurrentPageTitle() {
988
- const title = await this.page.title();
989
- return title;
990
- }
991
- async getCurrentPageUrl() {
992
- const url = await this.page.url();
993
- return url;
994
- }
995
-
996
- _addPagelisteners(context) {
997
- context.on("page", async (page) => {
998
- try {
999
- if (page.isClosed()) return;
1000
- this.pageSet.add(page);
1001
- await page.waitForLoadState("domcontentloaded");
1002
-
1003
- // add listener for frame navigation on new tab
1004
- this._addFrameNavigateListener(page);
1005
- } catch (error) {
1006
- this.logger.error("Error in page event");
1007
- this.logger.error(error);
1008
- console.error("Error in page event");
1009
- console.error(error);
1010
- }
1011
- });
1012
- }
1013
- async openBrowser() {
1014
- const env = JSON.parse(readFileSync(this.envName), "utf8");
1015
- const url = env.baseUrl;
1016
- await this._initBrowser({ url });
1017
- await this._openTab({ url });
1018
- process.env.TEMP_RUN = true;
1019
- }
1020
- overlayLocators(event) {
1021
- let locatorsResults = [...event.locators];
1022
- const cssLocators = event.cssLocators;
1023
- for (const cssLocator of cssLocators) {
1024
- locatorsResults.push({ mode: "NO_TEXT", css: cssLocator });
1025
- }
1026
- if (event.digitLocators) {
1027
- for (const digitLocator of event.digitLocators) {
1028
- digitLocator.mode = "IGNORE_DIGIT";
1029
- locatorsResults.push(digitLocator);
1030
- }
1031
- }
1032
- if (event.contextLocator) {
1033
- locatorsResults.push({
1034
- mode: "CONTEXT",
1035
- text: event.contextLocator.texts[0],
1036
- css: event.contextLocator.css,
1037
- climb: event.contextLocator.climbCount,
1038
- });
1039
- }
1040
- return locatorsResults;
1041
- }
1042
- async getScreenShot() {
1043
- const client = await this.context.newCDPSession(this.web.page);
1044
- try {
1045
- // Using CDP to capture the screenshot
1046
- const { data } = await client.send("Page.captureScreenshot", { format: "png" });
1047
- return data;
1048
- } catch (error) {
1049
- this.logger.error("Error in taking browser screenshot");
1050
- console.error("Error in taking browser screenshot", error);
1051
- } finally {
1052
- await client.detach();
1053
- }
1054
- }
1055
- async storeScreenshot(event) {
1056
- try {
1057
- // const spath = path.join(__dirname, "media", `${event.inputID}.png`);
1058
- const screenshotURL = await this.getScreenShot();
1059
- this.screenshotMap.set(event.element.inputID, screenshotURL);
1060
- // writeFileSync(spath, screenshotURL, "base64");
1061
- } catch (error) {
1062
- console.error("Error in saving screenshot: ", error);
1063
- }
1064
- }
1065
- async generateLocators(event) {
1066
- const snapshotDetails = event.snapshotDetails;
1067
- if (!snapshotDetails) {
1068
- throw new Error("No snapshot details found");
1069
- }
1070
- const mode = event.mode;
1071
- const inputID = event.element.inputID;
1072
-
1073
- const { id, contextId, doc } = snapshotDetails;
1074
- // const selector = `[data-blinq-id="${id}"]`;
1075
- const newPage = await this.backgroundContext.newPage();
1076
- await newPage.setContent(doc, { waitUntil: "domcontentloaded" });
1077
- const locatorsObj = await newPage.evaluate(
1078
- ([id, contextId, mode]) => {
1079
- const recorder = window.__bvt_Recorder;
1080
- const contextElement = document.querySelector(`[data-blinq-context-id="${contextId}"]`);
1081
- const el = document.querySelector(`[data-blinq-id="${id}"]`);
1082
- if (contextElement) {
1083
- const result = recorder.locatorGenerator.toContextLocators(el, contextElement);
1084
- return result;
1085
- }
1086
- const isRecordingText = mode === "recordingText";
1087
- return recorder.locatorGenerator.getElementLocators(el, {
1088
- excludeText: isRecordingText,
1089
- });
1090
- },
1091
- [id, contextId, mode]
1092
- );
1093
-
1094
- // console.log(`Generated locators: for ${inputID}: `, JSON.stringify(locatorsObj));
1095
- await newPage.close();
1096
- if (event.nestFrmLoc?.children) {
1097
- locatorsObj.nestFrmLoc = event.nestFrmLoc.children;
1098
- }
1099
-
1100
- this.sendEvent(this.events.updateCommand, {
1101
- locators: {
1102
- locators: locatorsObj.locators,
1103
- nestFrmLoc: locatorsObj.nestFrmLoc,
1104
- iframe_src: !event.frame.isTop ? event.frame.url : undefined,
1105
- },
1106
- allStrategyLocators: locatorsObj.allStrategyLocators,
1107
- inputID,
1108
- });
1109
- // const
1110
- }
1111
- async onAction(event) {
1112
- this._updateUrlPath();
1113
- // const locators = this.overlayLocators(event);
1114
- const cmdEvent = {
1115
- ...event.element,
1116
- ...transformAction(
1117
- event.action,
1118
- event.element,
1119
- event.mode === "recordingText" || event.mode === "recordingContext",
1120
- event.isPopupCloseClick,
1121
- event.mode === "recordingHover",
1122
- event.mode === "multiInspecting"
1123
- ),
1124
- // locators: {
1125
- // locators: event.locators,
1126
- // iframe_src: !event.frame.isTop ? event.frame.url : undefined,
1127
- // },
1128
- // allStrategyLocators: event.allStrategyLocators,
1129
- url: event.frame.url,
1130
- title: event.frame.title,
1131
- extract: {},
1132
- lastKnownUrlPath: this.lastKnownUrlPath,
249
+ events = {
250
+ onFrameNavigate: "BVTRecorder.onFrameNavigate",
251
+ onPageClose: "BVTRecorder.onPageClose",
252
+ onBrowserClose: "BVTRecorder.onBrowserClose",
253
+ onNewCommand: "BVTRecorder.command.new",
254
+ onCommandDetails: "BVTRecorder.onCommandDetails",
255
+ onStepDetails: "BVTRecorder.onStepDetails",
256
+ getTestData: "BVTRecorder.getTestData",
257
+ onGoto: "BVTRecorder.onGoto",
258
+ cmdExecutionStart: "BVTRecorder.cmdExecutionStart",
259
+ cmdExecutionSuccess: "BVTRecorder.cmdExecutionSuccess",
260
+ cmdExecutionError: "BVTRecorder.cmdExecutionError",
261
+ interceptResults: "BVTRecorder.interceptResults",
262
+ onDebugURLChange: "BVTRecorder.onDebugURLChange",
263
+ updateCommand: "BVTRecorder.updateCommand",
1133
264
  };
1134
- // if (event.nestFrmLoc?.children) {
1135
- // cmdEvent.locators.nestFrmLoc = event.nestFrmLoc.children;
1136
- // }
1137
- // this.logger.info({ event });
1138
- if (this.shouldTakeScreenshot) {
1139
- await this.storeScreenshot(event);
1140
- }
1141
- // this.sendEvent(this.events.onNewCommand, cmdEvent);
1142
- // this._updateUrlPath();
1143
- if (event.locators) {
1144
- Object.assign(cmdEvent, {
1145
- locators: {
1146
- locators: event.locators,
1147
- iframe_src: !event.frame.isTop ? event.frame.url : undefined,
1148
- nestFrmLoc: event.nestFrmLoc?.children,
265
+ bindings = {
266
+ __bvt_recordCommand: async ({ frame, page, context }, event) => {
267
+ this.#activeFrame = frame;
268
+ const nestFrmLoc = await findNestedFrameSelector(frame);
269
+ if (event.statistics?.time !== undefined) {
270
+ this.logger.info(`Time taken for action: ${event.statistics.time}`);
271
+ }
272
+ await this.onAction({ ...event, nestFrmLoc });
1149
273
  },
1150
- allStrategyLocators: event.allStrategyLocators,
1151
- })
1152
- this.sendEvent(this.events.onNewCommand, cmdEvent);
1153
- this._updateUrlPath();
1154
- } else {
1155
- this.sendEvent(this.events.onNewCommand, cmdEvent);
1156
- this._updateUrlPath();
1157
- await this.generateLocators(event);
1158
- }
1159
- }
1160
- _updateUrlPath() {
1161
- try {
1162
- let url = this.bvtContext.web.page.url();
1163
- if (url === "about:blank") {
1164
- return;
1165
- } else {
1166
- this.lastKnownUrlPath = new URL(url).pathname;
1167
- }
1168
- } catch (error) {
1169
- console.error("Error in getting last known url path", error);
1170
- }
1171
- }
1172
- async closeBrowser() {
1173
- delete process.env.TEMP_RUN;
1174
- await this.watcher.close().then(() => { });
1175
- this.watcher = null;
1176
- this.previousIndex = null;
1177
- this.previousHistoryLength = null;
1178
- this.previousUrl = null;
1179
- this.previousEntries = null;
1180
- await closeContext();
1181
- this.pageSet.clear();
1182
- }
1183
- async reOpenBrowser(input) {
1184
- if (input && input.envName) {
1185
- this.envName = path.join(this.projectDir, "environments", input.envName + ".json");
1186
- process.env.BLINQ_ENV = this.envName;
1187
- }
1188
- await this.closeBrowser();
1189
- // logger.log("closed");
1190
- await delay(1000);
1191
- await this.openBrowser();
1192
- // logger.log("opened");
1193
- }
1194
- async getNumberOfOccurrences({ searchString, regex = false, partial = true, ignoreCase = false, tag = "*" }) {
1195
- this.isVerify = false;
1196
- //const script = `window.countStringOccurrences(${JSON.stringify(searchString)});`;
1197
- if (searchString.length === 0) return -1;
1198
- let result = 0;
1199
- for (let i = 0; i < 3; i++) {
1200
- result = 0;
1201
- try {
1202
- // for (const page of this.context.pages()) {
1203
- const page = this.web.page;
1204
- for (const frame of page.frames()) {
1205
- try {
1206
- //scope, text1, tag1, regex1 = false, partial1, ignoreCase = true, _params: Params)
1207
- const frameResult = await this.web._locateElementByText(
1208
- frame,
1209
- searchString,
1210
- tag,
1211
- regex,
1212
- partial,
1213
- ignoreCase,
1214
- {}
1215
- );
1216
- result += frameResult.elementCount;
1217
- } catch (e) {
1218
- console.log(e);
1219
- }
1220
- }
1221
- // }
1222
-
1223
- return result;
1224
- } catch (e) {
1225
- console.log(e);
1226
- result = 0;
1227
- }
1228
- }
1229
- }
1230
-
1231
- async startRecordingInput() {
1232
- await this.setMode("recordingInput");
1233
- }
1234
- async stopRecordingInput() {
1235
- await this.setMode("idle");
1236
- }
1237
- async startRecordingText(isInspectMode) {
1238
- if (isInspectMode) {
1239
- await this.setMode("inspecting");
1240
- } else {
1241
- await this.setMode("recordingText");
1242
- }
1243
- }
1244
- async stopRecordingText() {
1245
- await this.setMode("idle");
1246
- }
1247
- async startRecordingContext() {
1248
- await this.setMode("recordingContext");
1249
- }
1250
- async stopRecordingContext() {
1251
- await this.setMode("idle");
1252
- }
1253
-
1254
- async abortExecution() {
1255
- await this.stepRunner.abortExecution();
1256
- }
1257
-
1258
- async pauseExecution({ cmdId }) {
1259
- await this.stepRunner.pauseExecution(cmdId);
1260
- }
1261
-
1262
- async resumeExecution({ cmdId }) {
1263
- await this.stepRunner.resumeExecution(cmdId);
1264
- }
1265
-
1266
- async dealyedRevertMode() {
1267
- const timerId = setTimeout(async () => {
1268
- await this.revertMode();
1269
- }, 100);
1270
- this.timerId = timerId;
1271
- }
1272
- async runStep({ step, parametersMap, tags, isFirstStep, listenNetwork, AICode }, options) {
1273
- const { skipAfter = true, skipBefore = !isFirstStep } = options || {};
1274
-
1275
- const env = path.basename(this.envName, ".json");
1276
- const _env = {
1277
- TOKEN: this.TOKEN,
1278
- TEMP_RUN: true,
1279
- REPORT_FOLDER: this.bvtContext.reportFolder,
1280
- BLINQ_ENV: this.envName,
1281
- DEBUG: "blinq:route",
1282
- // BVT_TEMP_SNAPSHOTS_FOLDER: step.isImplemented ? path.join(this.tempSnapshotsFolder, env) : undefined,
1283
- };
1284
- if (!step.isImplemented) {
1285
- _env.BVT_TEMP_SNAPSHOTS_FOLDER = path.join(this.tempSnapshotsFolder, env);
1286
- }
1287
-
1288
- this.bvtContext.navigate = true;
1289
- this.bvtContext.loadedRoutes = null;
1290
- if (listenNetwork) {
1291
- this.bvtContext.STORE_DETAILED_NETWORK_DATA = true;
1292
- } else {
1293
- this.bvtContext.STORE_DETAILED_NETWORK_DATA = false;
1294
- }
1295
- for (const [key, value] of Object.entries(_env)) {
1296
- process.env[key] = value;
1297
- }
1298
-
1299
- if (this.timerId) {
1300
- clearTimeout(this.timerId);
1301
- this.timerId = null;
1302
- }
1303
- await this.setMode("running");
1304
-
1305
- try {
1306
- step.text = step.text.trim();
1307
- const { result, info } = await this.stepRunner.runStep(
1308
- {
1309
- step,
1310
- parametersMap,
1311
- envPath: this.envName,
1312
- tags,
1313
- config: this.config,
1314
- AICode,
274
+ __bvt_getMode: async () => {
275
+ return this.#mode;
1315
276
  },
1316
- this.bvtContext,
1317
- {
1318
- skipAfter,
1319
- skipBefore,
1320
- }
1321
- );
1322
- await this.revertMode();
1323
- return { info };
1324
- } catch (error) {
1325
- await this.revertMode();
1326
- throw error;
1327
- } finally {
1328
- for (const key of Object.keys(_env)) {
1329
- delete process.env[key];
1330
- }
1331
- this.bvtContext.navigate = false;
1332
- }
1333
- }
1334
- async saveScenario({ scenario, featureName, override, isSingleStep, branch, isEditing, env, AICode }) {
1335
- const res = await this.workspaceService.saveScenario({
1336
- scenario,
1337
- featureName,
1338
- override,
1339
- isSingleStep,
1340
- branch,
1341
- isEditing,
1342
- projectId: path.basename(this.projectDir),
1343
- env: env ?? this.envName,
1344
- AICode,
1345
- });
1346
- if (res.success) {
1347
- await this.cleanup({ tags: scenario.tags });
1348
- } else {
1349
- throw new Error(res.message || "Error saving scenario");
1350
- }
1351
- }
1352
- async getImplementedSteps() {
1353
- const stepsAndScenarios = await getImplementedSteps(this.projectDir);
1354
- const implementedSteps = stepsAndScenarios.implementedSteps;
1355
- const scenarios = stepsAndScenarios.scenarios;
1356
- for (const scenario of scenarios) {
1357
- this.scenariosStepsMap.set(scenario.name, scenario.steps);
1358
- delete scenario.steps;
1359
- }
1360
- return {
1361
- implementedSteps,
1362
- scenarios,
1363
- };
1364
- }
1365
- async getStepsAndCommandsForScenario({ name, featureName }) {
1366
- const steps = this.scenariosStepsMap.get(name) || [];
1367
- for (const step of steps) {
1368
- if (step.isImplemented) {
1369
- step.commands = this.getCommandsForImplementedStep({ stepName: step.text });
1370
- } else {
1371
- step.commands = [];
1372
- }
1373
- }
1374
- return steps;
1375
- // return getStepsAndCommandsForScenario({
1376
- // name,
1377
- // featureName,
1378
- // projectDir: this.projectDir,
1379
- // map: this.scenariosStepsMap,
1380
- // });
1381
- }
1382
-
1383
- async generateStepName({ commands, stepsNames, parameters, map }) {
1384
- return await this.namesService.generateStepName({ commands, stepsNames, parameters, map });
1385
- }
1386
- async generateScenarioAndFeatureNames(scenarioAsText) {
1387
- return await this.namesService.generateScenarioAndFeatureNames(scenarioAsText);
1388
- }
1389
- async generateCommandName({ command }) {
1390
- return await this.namesService.generateCommandName({ command });
1391
- }
1392
-
1393
- async getCurrentChromiumPath() {
1394
- const currentURL = await this.bvtContext.web.page.url();
1395
- const env = JSON.parse(readFileSync(this.envName), "utf8");
1396
- const baseURL = env.baseUrl;
1397
- const relativeURL = currentURL.startsWith(baseURL) ? currentURL.replace(baseURL, "/") : undefined;
1398
- return {
1399
- relativeURL,
1400
- baseURL,
1401
- currentURL,
1402
- };
1403
- }
1404
-
1405
- getReportFolder() {
1406
- if (this.bvtContext.reportFolder) {
1407
- return this.bvtContext.reportFolder;
1408
- } else return "";
1409
- }
1410
-
1411
- getSnapshotFolder() {
1412
- if (this.bvtContext.snapshotFolder) {
1413
- return path.join(process.cwd(), this.bvtContext.snapshotFolder);
1414
- } else return "";
1415
- }
1416
-
1417
- async overwriteTestData(data) {
1418
- this.bvtContext.stable.overwriteTestData(data.value, this.world);
1419
- }
1420
-
1421
- _watchTestData() {
1422
- this.watcher = chokidar.watch(_getDataFile(this.world, this.bvtContext, this.web), {
1423
- persistent: true,
1424
- ignoreInitial: true,
1425
- awaitWriteFinish: {
1426
- stabilityThreshold: 2000,
1427
- pollInterval: 100,
1428
- },
1429
- });
1430
-
1431
- if (existsSync(_getDataFile(this.world, this.bvtContext, this.web))) {
1432
- try {
1433
- const testData = JSON.parse(readFileSync(_getDataFile(this.world, this.bvtContext, this.web), "utf8"));
1434
- // this.logger.info("Test data", testData);
1435
- this.sendEvent(this.events.getTestData, testData);
1436
- } catch (e) {
1437
- // this.logger.error("Error reading test data file", e);
1438
- console.log("Error reading test data file", e);
1439
- }
1440
- }
1441
-
1442
- this.logger.info("Watching for test data changes");
1443
-
1444
- this.watcher.on("all", async (event, path) => {
1445
- try {
1446
- const testData = JSON.parse(await readFile(_getDataFile(this.world, this.bvtContext, this.web), "utf8"));
1447
- // this.logger.info("Test data", testData);
1448
- console.log("Test data changed", testData);
1449
- this.sendEvent(this.events.getTestData, testData);
1450
- } catch (e) {
1451
- // this.logger.error("Error reading test data file", e);
1452
- console.log("Error reading test data file", e);
1453
- }
1454
- });
1455
- }
1456
- async loadTestData({ data, type }) {
1457
- if (type === "user") {
1458
- const username = data.username;
1459
- await this.web.loadTestDataAsync("users", username, this.world);
1460
- } else {
1461
- const csv = data.csv;
1462
- const row = data.row;
1463
- // code = `await context.web.loadTestDataAsync("csv","${csv}:${row}", this)`;
1464
- await this.web.loadTestDataAsync("csv", `${csv}:${row}`, this.world);
1465
- }
1466
- }
1467
-
1468
- async discardTestData({ tags }) {
1469
- resetTestData(this.envName, this.world);
1470
- await this.cleanup({ tags });
1471
- }
1472
- async addToTestData(obj) {
1473
- if (!existsSync(_getDataFile(this.world, this.bvtContext, this.web))) {
1474
- await writeFile(_getDataFile(this.world, this.bvtContext, this.web), JSON.stringify({}), "utf8");
1475
- }
1476
- let data = JSON.parse(await readFile(_getDataFile(this.world, this.bvtContext, this.web), "utf8"));
1477
- data = Object.assign(data, obj);
1478
- await writeFile(_getDataFile(this.world, this.bvtContext, this.web), JSON.stringify(data), "utf8");
1479
- }
1480
- getScenarios() {
1481
- const featureFiles = readdirSync(path.join(this.projectDir, "features"))
1482
- .filter((file) => file.endsWith(".feature"))
1483
- .map((file) => path.join(this.projectDir, "features", file));
1484
- try {
1485
- const parsedFiles = featureFiles.map((file) => this.parseFeatureFile(file));
1486
- const output = {};
1487
- parsedFiles.forEach((file) => {
1488
- if (!file.feature) return;
1489
- if (!file.feature.name) return;
1490
- output[file.feature.name] = [];
1491
- file.feature.children.forEach((child) => {
1492
- if (child.scenario) {
1493
- output[file.feature.name].push(child.scenario.name);
1494
- }
1495
- });
1496
- });
1497
-
1498
- return output;
1499
- } catch (e) {
1500
- console.log(e);
1501
- }
1502
- return {};
1503
- }
1504
- getCommandsForImplementedStep({ stepName }) {
1505
- const step_definitions = loadStepDefinitions(this.projectDir);
1506
- const stepParams = parseStepTextParameters(stepName);
1507
- return getCommandsForImplementedStep(stepName, step_definitions, stepParams).commands;
1508
- }
1509
-
1510
- loadExistingScenario({ featureName, scenarioName }) {
1511
- const step_definitions = loadStepDefinitions(this.projectDir);
1512
- const featureFilePath = path.join(this.projectDir, "features", featureName);
1513
- const gherkinDoc = this.parseFeatureFile(featureFilePath);
1514
- const scenario = gherkinDoc.feature.children.find((child) => child.scenario.name === scenarioName)?.scenario;
1515
- this.scenarioDoc = scenario;
1516
-
1517
- const steps = [];
1518
- const parameters = [];
1519
- const datasets = [];
1520
- if (scenario.examples && scenario.examples.length > 0) {
1521
- const example = scenario.examples[0];
1522
- example?.tableHeader?.cells.forEach((cell, index) => {
1523
- parameters.push({
1524
- key: cell.value,
1525
- value: unEscapeNonPrintables(example.tableBody[0].cells[index].value),
1526
- });
1527
- // datasets.push({
1528
- // data: example.tableBody[]
1529
- // })
1530
- });
1531
-
1532
- for (let i = 0; i < example.tableBody.length; i++) {
1533
- const row = example.tableBody[i];
1534
- // for (const row of example.tableBody) {
1535
- const paramters = [];
1536
- row.cells.forEach((cell, index) => {
1537
- paramters.push({
1538
- key: example.tableHeader.cells[index].value,
1539
- value: unEscapeNonPrintables(cell.value),
1540
- });
1541
- });
1542
- datasets.push({
1543
- data: paramters,
1544
- datasetId: i,
1545
- });
1546
- }
1547
- }
1548
-
1549
- for (const step of scenario.steps) {
1550
- const stepParams = parseStepTextParameters(step.text);
1551
- // console.log("Parsing step ", step, stepParams);
1552
- const _s = getCommandsForImplementedStep(step.text, step_definitions, stepParams);
1553
- delete step.location;
1554
- const _step = {
1555
- ...step,
1556
- ..._s,
1557
- keyword: step.keyword.trim(),
1558
- };
1559
- parseRouteFiles(this.projectDir, _step);
1560
- steps.push(_step);
1561
- }
1562
- return {
1563
- name: scenario.name,
1564
- tags: scenario.tags.map((tag) => tag.name),
1565
- steps,
1566
- parameters,
1567
- datasets,
1568
- };
1569
- }
1570
- async findRelatedTextInAllFrames({ searchString, climb, contextText, params }) {
1571
- if (searchString.length === 0) return -1;
1572
- let result = 0;
1573
- for (let i = 0; i < 3; i++) {
1574
- result = 0;
1575
- try {
1576
- try {
1577
- const allFrameResult = await this.web.findRelatedTextInAllFrames(
1578
- contextText,
1579
- climb,
1580
- searchString,
1581
- params,
1582
- {},
1583
- this.world
1584
- );
1585
- for (const frameResult of allFrameResult) {
1586
- result += frameResult.elementCount;
1587
- }
1588
- } catch (e) {
1589
- console.log(e);
1590
- }
1591
-
1592
- return result;
1593
- } catch (e) {
1594
- console.log(e);
1595
- result = 0;
1596
- }
1597
- }
1598
- return result;
1599
- }
1600
- async setStepCodeByScenario({
1601
- function_name,
1602
- mjs_file_content,
1603
- user_request,
1604
- selectedTarget,
1605
- page_context,
1606
- AIMemory,
1607
- steps_context,
1608
- }) {
1609
- const runsURL = getRunsServiceBaseURL();
1610
- const url = `${runsURL}/process-user-request/generate-code-with-context`;
1611
- try {
1612
- const result = await axiosClient({
1613
- url,
1614
- method: "POST",
1615
- data: {
1616
- function_name,
1617
- mjs_file_content,
1618
- user_request,
1619
- selectedTarget,
1620
- page_context,
1621
- AIMemory,
1622
- steps_context,
277
+ __bvt_setMode: async (_src, mode) => {
278
+ await this.setMode(mode);
1623
279
  },
1624
- headers: {
1625
- Authorization: `Bearer ${this.TOKEN}`,
1626
- "X-Source": "recorder",
280
+ __bvt_revertMode: async () => {
281
+ await this.revertMode();
1627
282
  },
1628
- });
1629
- if (result.status !== 200) {
1630
- return { success: false, message: "Error while fetching code changes" };
1631
- }
1632
- return { success: true, data: result.data };
1633
- } catch (error) {
1634
- // @ts-ignore
1635
- const reason = error?.response?.data?.error || "";
1636
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
1637
- throw new Error(`Failed to fetch code changes: ${errorMessage} \n ${reason}`);
1638
- }
1639
- }
1640
-
1641
- async getStepCodeByScenario({ featureName, scenarioName, projectId, branch }) {
1642
- try {
1643
- const runsURL = getRunsServiceBaseURL();
1644
- const ssoURL = runsURL.replace("/runs", "/auth");
1645
- const privateRepoURL = `${ssoURL}/isRepoPrivate?project_id=${projectId}`;
1646
-
1647
- const isPrivateRepoReq = await axiosClient({
1648
- url: privateRepoURL,
1649
- method: "GET",
1650
- headers: {
1651
- Authorization: `Bearer ${this.TOKEN}`,
1652
- "X-Source": "recorder",
283
+ __bvt_recordPageClose: async ({ page }) => {
284
+ this.pageSet.delete(page);
1653
285
  },
1654
- });
1655
-
1656
- if (isPrivateRepoReq.status !== 200) {
1657
- return { success: false, message: "Error while checking repo privacy" };
1658
- }
1659
-
1660
- const isPrivateRepo = isPrivateRepoReq.data.isPrivate ? isPrivateRepoReq.data.isPrivate : false;
1661
-
1662
- const workspaceURL = runsURL.replace("/runs", "/workspace");
1663
- const url = `${workspaceURL}/get-step-code-by-scenario`;
1664
-
1665
- const result = await axiosClient({
1666
- url,
1667
- method: "POST",
1668
- data: {
1669
- scenarioName,
1670
- featureName,
1671
- projectId,
1672
- isPrivateRepo,
1673
- branch,
286
+ __bvt_closePopups: async () => {
287
+ await this.onClosePopup();
1674
288
  },
1675
- headers: {
1676
- Authorization: `Bearer ${this.TOKEN}`,
1677
- "X-Source": "recorder",
289
+ __bvt_log: async (_src, message) => {
290
+ this.logger.info(`Inside Browser: ${message}`);
1678
291
  },
1679
- });
1680
- if (result.status !== 200) {
1681
- return { success: false, message: "Error while getting step code" };
1682
- }
1683
- return { success: true, data: result.data.stepInfo };
1684
- } catch (error) {
1685
- const reason = error?.response?.data?.error || "";
1686
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
1687
- throw new Error(`Failed to get step code: ${errorMessage} \n ${reason}`);
1688
- }
1689
- }
1690
- async getContext() {
1691
- await this.page.waitForLoadState("domcontentloaded");
1692
- await this.page.waitForSelector("body");
1693
- await this.page.waitForTimeout(500);
1694
- return await this.page.evaluate(() => {
1695
- return document.documentElement.outerHTML;
1696
- });
1697
- }
1698
- async deleteCommandFromStepCode({ scenario, AICode, command }) {
1699
- if (!AICode || AICode.length === 0) {
1700
- console.log("No AI code available to delete.");
1701
- return;
1702
- }
1703
-
1704
- const __temp_features_FolderName = "__temp_features" + Math.random().toString(36).substring(2, 7);
1705
- const tempFolderPath = path.join(this.projectDir, __temp_features_FolderName);
1706
- process.env.tempFeaturesFolderPath = __temp_features_FolderName;
1707
- process.env.TESTCASE_REPORT_FOLDER_PATH = tempFolderPath;
1708
-
1709
- try {
1710
- await this.stepRunner.copyCodetoTempFolder({ tempFolderPath, AICode });
1711
- await this.stepRunner.writeWrapperCode(tempFolderPath);
1712
- const codeView = AICode.find((f) => f.stepName === scenario.step.text);
1713
-
1714
- if (!codeView) {
1715
- throw new Error("Step code not found for step: " + scenario.step.text);
1716
- }
1717
-
1718
- const functionName = codeView.functionName;
1719
- const mjsPath = path
1720
- .normalize(codeView.mjsFile)
1721
- .split(path.sep)
1722
- .filter((part) => part !== "features")
1723
- .join(path.sep);
1724
- const codePath = path.join(tempFolderPath, mjsPath);
1725
-
1726
- if (!existsSync(codePath)) {
1727
- throw new Error("Step code file not found: " + codePath);
1728
- }
1729
-
1730
- const codePage = getCodePage(codePath);
1731
-
1732
- const elements = codePage.getVariableDeclarationAsObject("elements");
1733
-
1734
- const cucumberStep = getCucumberStep({ step: scenario.step });
1735
- cucumberStep.text = scenario.step.text;
1736
- const stepCommands = scenario.step.commands;
1737
- const cmd = _toRecordingStep(command, scenario.step.name);
1738
-
1739
- const recording = new Recording();
1740
- recording.loadFromObject({ steps: stepCommands, step: cucumberStep });
1741
- const step = { ...recording.steps[0], ...cmd };
1742
- const result = _generateCodeFromCommand(step, elements, {});
1743
-
1744
- codePage._removeCommands(functionName, result.codeLines);
1745
- codePage.removeUnusedElements();
1746
- codePage.save();
1747
-
1748
- await rm(tempFolderPath, { recursive: true, force: true });
1749
-
1750
- return { code: codePage.fileContent, mjsFile: codeView.mjsFile };
1751
- } catch (error) {
1752
- await rm(tempFolderPath, { recursive: true, force: true });
1753
- throw error;
1754
- }
1755
- }
1756
- async addCommandToStepCode({ scenario, AICode }) {
1757
- if (!AICode || AICode.length === 0) {
1758
- console.log("No AI code available to add.");
1759
- return;
1760
- }
1761
-
1762
- const __temp_features_FolderName = "__temp_features" + Math.random().toString(36).substring(2, 7);
1763
- const tempFolderPath = path.join(this.projectDir, __temp_features_FolderName);
1764
- process.env.tempFeaturesFolderPath = __temp_features_FolderName;
1765
- process.env.TESTCASE_REPORT_FOLDER_PATH = tempFolderPath;
1766
-
1767
- try {
1768
- await this.stepRunner.copyCodetoTempFolder({ tempFolderPath, AICode });
1769
- await this.stepRunner.writeWrapperCode(tempFolderPath);
1770
-
1771
- let codeView = AICode.find((f) => f.stepName === scenario.step.text);
1772
-
1773
- if (codeView) {
1774
- scenario.step.commands = [scenario.step.commands.pop()];
1775
- const functionName = codeView.functionName;
1776
- const mjsPath = path
1777
- .normalize(codeView.mjsFile)
1778
- .split(path.sep)
1779
- .filter((part) => part !== "features")
1780
- .join(path.sep);
1781
- const codePath = path.join(tempFolderPath, mjsPath);
1782
-
1783
- if (!existsSync(codePath)) {
1784
- throw new Error("Step code file not found: " + codePath);
1785
- }
1786
-
1787
- const codePage = getCodePage(codePath);
1788
- const elements = codePage.getVariableDeclarationAsObject("elements");
1789
-
1790
- const cucumberStep = getCucumberStep({ step: scenario.step });
1791
- cucumberStep.text = scenario.step.text;
1792
- const stepCommands = scenario.step.commands;
1793
- const cmd = _toRecordingStep(scenario.step.commands[0], scenario.step.name);
1794
-
1795
- const recording = new Recording();
1796
- recording.loadFromObject({ steps: stepCommands, step: cucumberStep });
1797
- const step = { ...recording.steps[0], ...cmd };
1798
-
1799
- const result = _generateCodeFromCommand(step, elements, {});
1800
- codePage.insertElements(result.elements);
1801
-
1802
- codePage._injectOneCommand(functionName, result.codeLines.join("\n"));
1803
- codePage.save();
1804
-
1805
- await rm(tempFolderPath, { recursive: true, force: true });
1806
-
1807
- return { code: codePage.fileContent, newStep: false, mjsFile: codeView.mjsFile };
1808
- }
1809
- console.log("Step code not found for step: ", scenario.step.text);
1810
-
1811
- codeView = AICode[0];
1812
- const functionName = toMethodName(scenario.step.text);
1813
- const codeLines = [];
1814
- const mjsPath = path
1815
- .normalize(codeView.mjsFile)
1816
- .split(path.sep)
1817
- .filter((part) => part !== "features")
1818
- .join(path.sep);
1819
- const codePath = path.join(tempFolderPath, mjsPath);
1820
-
1821
- if (!existsSync(codePath)) {
1822
- throw new Error("Step code file not found: " + codePath);
1823
- }
1824
-
1825
- const codePage = getCodePage(codePath);
1826
- const elements = codePage.getVariableDeclarationAsObject("elements");
1827
- let newElements = { ...elements };
1828
-
1829
- const cucumberStep = getCucumberStep({ step: scenario.step });
1830
- cucumberStep.text = scenario.step.text;
1831
- const stepCommands = scenario.step.commands;
1832
- stepCommands.forEach((command) => {
1833
- const cmd = _toRecordingStep(command, scenario.step.name);
1834
-
1835
- const recording = new Recording();
1836
- recording.loadFromObject({ steps: stepCommands, step: cucumberStep });
1837
- const step = { ...recording.steps[0], ...cmd };
1838
- const result = _generateCodeFromCommand(step, elements, {});
1839
- newElements = { ...result.elements };
1840
- codeLines.push(...result.codeLines);
1841
- });
1842
-
1843
- codePage.insertElements(newElements);
1844
- codePage.addInfraCommand(
1845
- functionName,
1846
- cucumberStep.text,
1847
- cucumberStep.getVariablesList(),
1848
- codeLines,
1849
- false,
1850
- "recorder"
1851
- );
1852
-
1853
- const keyword = (cucumberStep.keywordAlias ?? cucumberStep.keyword).trim();
1854
- codePage.addCucumberStep(keyword, cucumberStep.getTemplate(), functionName, stepCommands.length);
1855
- codePage.save();
1856
-
1857
- await rm(tempFolderPath, { recursive: true, force: true });
1858
-
1859
- return { code: codePage.fileContent, newStep: true, functionName, mjsFile: codeView.mjsFile };
1860
- } catch (error) {
1861
- await rm(tempFolderPath, { recursive: true, force: true });
1862
- throw error;
1863
- }
1864
- }
1865
- async cleanup({ tags }) {
1866
- const noopStep = {
1867
- text: "Noop",
1868
- isImplemented: true,
1869
- };
1870
- const projectDir = this.projectDir;
1871
- console.log("Cleaning up project dir:", projectDir);
1872
-
1873
- try {
1874
- // run a dummy scenario that will run after hooks
1875
- await this.runStep(
1876
- {
1877
- step: noopStep,
1878
- parametersMap: {},
1879
- tags: tags || [],
292
+ __bvt_getObject: (_src, obj) => {
293
+ this.processObject(obj);
1880
294
  },
1881
- {
1882
- skipAfter: false,
1883
- }
1884
- );
1885
-
1886
- // delete the temp folders (any folder that starts with __temp_features)
1887
- const tempFolders = readdirSync(projectDir).filter((folder) => folder.startsWith("__temp_features"));
1888
- for (const folder of tempFolders) {
1889
- const folderPath = path.join(projectDir, folder);
1890
- if (existsSync(folderPath)) {
1891
- this.logger.info(`Deleting temp folder: ${folderPath}`);
1892
- rmSync(folderPath, { recursive: true });
1893
- }
1894
- }
1895
- } catch (error) {
1896
- console.error("Error in cleanup", error);
1897
- }
1898
- }
1899
- async processAriaSnapshot(snapshot) {
1900
- try {
1901
- await this.evaluateInAllFrames(
1902
- this.context,
1903
- `window.__bvt_Recorder.processAriaSnapshot(${JSON.stringify(snapshot)});`
1904
- );
1905
- return true;
1906
- } catch (e) {
1907
- return false;
1908
- }
1909
- }
1910
- async deselectAriaElements() {
1911
- try {
1912
- await this.evaluateInAllFrames(this.context, `window.__bvt_Recorder.deselectAriaElements();`);
1913
- return true;
1914
- } catch (e) {
1915
- return false;
1916
- }
1917
- }
1918
- async initExecution({ tags = [] }) {
1919
- // run before hooks
1920
- const noopStep = {
1921
- text: "Noop",
1922
- isImplemented: true,
1923
295
  };
1924
- await this.runStep(
1925
- {
1926
- step: noopStep,
1927
- parametersMap: {},
1928
- tags,
1929
- },
1930
- {
1931
- skipBefore: false,
1932
- skipAfter: true,
1933
- }
1934
- );
1935
- }
1936
- async cleanupExecution({ tags = [] }) {
1937
- // run after hooks
1938
- const noopStep = {
1939
- text: "Noop",
1940
- isImplemented: true,
296
+ getSnapshot = async (attr) => {
297
+ const selector = `[__bvt_snapshot="${attr}"]`;
298
+ const locator = await this.web.page.locator(selector);
299
+ const snapshot = await locator.ariaSnapshot();
300
+ return snapshot;
1941
301
  };
1942
- await this.runStep(
1943
- {
1944
- step: noopStep,
1945
- parametersMap: {},
1946
- tags,
1947
- },
1948
- {
1949
- skipBefore: true,
1950
- skipAfter: false,
1951
- }
1952
- );
1953
- }
1954
- async resetExecution({ tags = [] }) {
1955
- // run after hooks followed by before hooks
1956
- await this.cleanupExecution({ tags });
1957
- await this.initExecution({ tags });
1958
- }
1959
-
1960
- parseFeatureFile(featureFilePath) {
1961
- try {
1962
- let id = 0;
1963
- const uuidFn = () => (++id).toString(16);
1964
- const builder = new AstBuilder(uuidFn);
1965
- const matcher = new GherkinClassicTokenMatcher();
1966
- const parser = new Parser(builder, matcher);
1967
- const source = readFileSync(featureFilePath, "utf8");
1968
- const gherkinDocument = parser.parse(source);
1969
- return gherkinDocument;
1970
- } catch (e) {
1971
- this.logger.error(`Error parsing feature file: ${featureFilePath}`);
1972
- console.log(e);
1973
- }
1974
- return {};
1975
- }
1976
-
1977
- stopRecordingNetwork(input) {
1978
- if (this.bvtContext) {
1979
- this.bvtContext.STORE_DETAILED_NETWORK_DATA = false;
1980
- }
1981
- }
1982
-
1983
- async fakeParams(params) {
1984
- const newFakeParams = {};
1985
- Object.keys(params).forEach((key) => {
1986
- if (!params[key].startsWith("{{") || !params[key].endsWith("}}")) {
1987
- newFakeParams[key] = params[key];
1988
- return;
1989
- }
1990
-
1991
- try {
1992
- const value = params[key].substring(2, params[key].length - 2).trim();
1993
- const faking = value.split("(")[0].split(".");
1994
- let argument = value.substring(value.indexOf("(") + 1, value.lastIndexOf(")"));
1995
- argument = isNaN(Number(argument)) || argument === "" ? argument : Number(argument);
1996
- let fakeFunc = faker;
1997
- faking.forEach((f) => {
1998
- fakeFunc = fakeFunc[f];
302
+ processObject = async ({ type, action, value }) => {
303
+ switch (type) {
304
+ case "snapshot-element": {
305
+ if (action === "get-template") {
306
+ return true;
307
+ }
308
+ break;
309
+ }
310
+ default: {
311
+ console.log("Unknown object type", type);
312
+ break;
313
+ }
314
+ }
315
+ };
316
+ getPWScript() {
317
+ const pwFolder = path.join(__dirname, "..", "..", "assets", "preload", "pw_utils");
318
+ const result = [];
319
+ for (const script of readdirSync(pwFolder)) {
320
+ const scriptPath = path.join(pwFolder, script);
321
+ const content = readFileSync(scriptPath, "utf8");
322
+ result.push(content);
323
+ }
324
+ return result;
325
+ }
326
+ getRecorderScripts() {
327
+ const recorderFolder = path.join(__dirname, "..", "..", "assets", "preload", "recorder");
328
+ const result = [];
329
+ for (const script of readdirSync(recorderFolder)) {
330
+ const scriptPath = path.join(recorderFolder, script);
331
+ const content = readFileSync(scriptPath, "utf8");
332
+ result.push(content);
333
+ }
334
+ return result;
335
+ }
336
+ getInitScripts(config) {
337
+ return getInitScript(config, {
338
+ sdkLanguage: "javascript",
339
+ testIdAttributeName: "blinq-test-id",
340
+ stableRafCount: 0,
341
+ browserName: this.browser?.browserType().name(),
342
+ inputFileRoleTextbox: false,
343
+ customEngines: [],
344
+ isUnderTest: true,
1999
345
  });
2000
- const newValue = fakeFunc(argument);
2001
- newFakeParams[key] = newValue;
2002
- } catch (error) {
2003
- newFakeParams[key] = params[key];
2004
- }
2005
- });
2006
-
2007
- return newFakeParams;
2008
- }
2009
-
2010
- async getBrowserState() {
2011
- try {
2012
- const state = await this.browserEmitter?.getState();
2013
- this.sendEvent(this.events.browserStateSync, state);
2014
- } catch (error) {
2015
- this.logger.error("Error getting browser state:", error);
2016
- this.sendEvent(this.events.browserStateError, {
2017
- message: "Error getting browser state",
2018
- code: "GET_STATE_ERROR",
2019
- });
2020
- }
2021
- }
2022
-
2023
- async applyClipboardPayload(message) {
2024
- const payload = message?.data ?? message;
2025
-
2026
- this.logger.info("[BVTRecorder] applyClipboardPayload called", {
2027
- hasPayload: !!payload,
2028
- hasText: !!payload?.text,
2029
- hasHtml: !!payload?.html,
2030
- trigger: message?.trigger,
2031
- });
2032
-
2033
- if (!payload) {
2034
- this.logger.warn("[BVTRecorder] No payload provided");
2035
- return;
2036
- }
2037
-
2038
- try {
2039
- if (this.browserEmitter && typeof this.browserEmitter.applyClipboardPayload === "function") {
2040
- this.logger.info("[BVTRecorder] Using RemoteBrowserService to apply clipboard");
2041
- await this.browserEmitter.applyClipboardPayload(payload);
2042
- return;
2043
- }
2044
-
2045
- const activePage = this.browserEmitter?.getSelectedPage() ?? this.page;
2046
- if (!activePage) {
2047
- this.logger.warn("[BVTRecorder] No active page available");
2048
- return;
2049
- }
2050
-
2051
- this.logger.info("[BVTRecorder] Applying clipboard to page", {
2052
- url: activePage.url(),
2053
- isClosed: activePage.isClosed(),
2054
- });
2055
-
2056
- const result = await activePage.evaluate((clipboardData) => {
2057
- console.log("[Page] Executing clipboard application", clipboardData);
2058
- if (typeof window.__bvt_applyClipboardData === "function") {
2059
- return window.__bvt_applyClipboardData(clipboardData);
2060
- }
2061
- console.error("[Page] __bvt_applyClipboardData function not found!");
2062
- return false;
2063
- }, payload);
2064
-
2065
- this.logger.info("[BVTRecorder] Clipboard application result:", result);
2066
-
2067
- if (!result) {
2068
- this.logger.warn("[BVTRecorder] Clipboard data not applied successfully");
2069
- } else {
2070
- this.logger.info("[BVTRecorder] Clipboard data applied successfully");
2071
- }
2072
- } catch (error) {
2073
- this.logger.error("[BVTRecorder] Error applying clipboard payload", error);
2074
- this.sendEvent(this.events.clipboardError, {
2075
- message: "Failed to apply clipboard contents to the remote session",
2076
- trigger: message?.trigger ?? "paste",
2077
- });
2078
- }
2079
- }
2080
-
2081
- hasClipboardPayload(payload) {
2082
- return Boolean(
2083
- payload && (payload.text || payload.html || (Array.isArray(payload.files) && payload.files.length > 0))
2084
- );
2085
- }
2086
-
2087
- async collectClipboardFromPage(page) {
2088
- if (!page) {
2089
- this.logger.warn("[BVTRecorder] No page available to collect clipboard data");
2090
- return null;
2091
346
  }
2092
- try {
2093
- await page
2094
- .context()
2095
- .grantPermissions(["clipboard-read", "clipboard-write"])
2096
- .catch((error) => {
2097
- this.logger.warn("[BVTRecorder] Failed to grant clipboard permissions before read", error);
347
+ async _initBrowser({ url }) {
348
+ if (process.env.CDP_LISTEN_PORT === undefined) {
349
+ this.#remoteDebuggerPort = await findAvailablePort();
350
+ process.env.CDP_LISTEN_PORT = String(this.#remoteDebuggerPort);
351
+ }
352
+ else {
353
+ this.#remoteDebuggerPort = Number(process.env.CDP_LISTEN_PORT);
354
+ }
355
+ // this.stepRunner.setRemoteDebugPort(this.#remoteDebuggerPort);
356
+ const ai_config_file = path.join(this.projectDir, "ai_config.json");
357
+ let ai_config = {};
358
+ if (existsSync(ai_config_file)) {
359
+ try {
360
+ ai_config = JSON.parse(readFileSync(ai_config_file, "utf8"));
361
+ }
362
+ catch (error) {
363
+ this.logger.error("Error reading ai_config.json", { error });
364
+ }
365
+ }
366
+ this.config = ai_config;
367
+ const initScripts = {
368
+ recorderCjs: null,
369
+ scripts: [
370
+ this.getInitScripts(ai_config),
371
+ `\ndelete Object.getPrototypeOf(navigator).webdriver;${process.env.WINDOW_DEBUGGER ? "window.debug=true;\n" : ""}`,
372
+ ],
373
+ };
374
+ const scenario = { pickle: this.scenarioDoc };
375
+ const bvtContext = await initContext(url, false, false, this.world, 450, initScripts, this.envName, scenario);
376
+ this.bvtContext = bvtContext;
377
+ this.stepRunner = new BVTStepRunner({
378
+ projectDir: this.projectDir,
379
+ sendExecutionStatus: (data) => {
380
+ if (data && data.type) {
381
+ switch (data.type) {
382
+ case "cmdExecutionStart":
383
+ this.sendEvent(this.events.cmdExecutionStart, data);
384
+ break;
385
+ case "cmdExecutionSuccess":
386
+ this.sendEvent(this.events.cmdExecutionSuccess, data);
387
+ break;
388
+ case "cmdExecutionError":
389
+ this.sendEvent(this.events.cmdExecutionError, data);
390
+ break;
391
+ case "interceptResults":
392
+ this.sendEvent(this.events.interceptResults, data);
393
+ break;
394
+ default:
395
+ break;
396
+ }
397
+ }
398
+ },
399
+ bvtContext: this.bvtContext,
2098
400
  });
2099
-
2100
- const payload = await page.evaluate(async () => {
2101
- const result = {};
2102
- if (typeof navigator === "undefined" || !navigator.clipboard) {
2103
- return result;
2104
- }
2105
-
2106
- const arrayBufferToBase64 = (buffer) => {
2107
- let binary = "";
2108
- const bytes = new Uint8Array(buffer);
2109
- const chunkSize = 0x8000;
2110
- for (let index = 0; index < bytes.length; index += chunkSize) {
2111
- const chunk = bytes.subarray(index, index + chunkSize);
2112
- binary += String.fromCharCode(...chunk);
2113
- }
2114
- return btoa(binary);
401
+ this.context = bvtContext.playContext;
402
+ this.web = bvtContext.stable || bvtContext.web;
403
+ this.web.tryAllStrategies = true;
404
+ this.page = bvtContext.page;
405
+ this.pageSet.add(this.page);
406
+ this.lastKnownUrlPath = this._updateUrlPath();
407
+ const browser = await this.context.browser();
408
+ this.browser = browser;
409
+ // add bindings
410
+ for (const [name, handler] of Object.entries(this.bindings)) {
411
+ await this.context.exposeBinding(name, handler);
412
+ }
413
+ this._watchTestData();
414
+ this.web.onRestoreSaveState = async (url) => {
415
+ await this._initBrowser({ url });
416
+ this._addPagelisteners(this.context);
417
+ this._addFrameNavigateListener(this.page);
2115
418
  };
2116
-
2117
- const files = [];
2118
-
2119
- if (typeof navigator.clipboard.read === "function") {
2120
- try {
2121
- const items = await navigator.clipboard.read();
2122
- for (const item of items) {
2123
- if (item.types.includes("text/html") && !result.html) {
2124
- const blob = await item.getType("text/html");
2125
- result.html = await blob.text();
2126
- }
2127
- if (item.types.includes("text/plain") && !result.text) {
2128
- const blob = await item.getType("text/plain");
2129
- result.text = await blob.text();
2130
- }
2131
- for (const type of item.types) {
2132
- if (type.startsWith("text/")) {
2133
- continue;
419
+ // create a second browser for locator generation
420
+ this.backgroundBrowser = await chromium.launch({
421
+ headless: true,
422
+ });
423
+ this.backgroundContext = await this.backgroundBrowser.newContext({});
424
+ await this.backgroundContext.addInitScript({ content: this.getInitScripts(this.config) });
425
+ await this.backgroundContext.newPage();
426
+ }
427
+ async onClosePopup() {
428
+ // console.log("close popups");
429
+ await this.bvtContext.web?.closeUnexpectedPopups(null, null);
430
+ }
431
+ async evaluateInAllFrames(context, script) {
432
+ // retry 3 times
433
+ for (let i = 0; i < 3; i++) {
434
+ try {
435
+ for (const page of context.pages()) {
436
+ await evaluate(page.mainFrame(), script);
2134
437
  }
2135
- try {
2136
- const blob = await item.getType(type);
2137
- const buffer = await blob.arrayBuffer();
2138
- files.push({
2139
- name: `clipboard-file-${files.length + 1}`,
2140
- type,
2141
- lastModified: Date.now(),
2142
- data: arrayBufferToBase64(buffer),
2143
- });
2144
- } catch (error) {
2145
- console.warn("[BVTRecorder] Failed to serialize clipboard blob", { type, error });
438
+ return;
439
+ }
440
+ catch (error) {
441
+ // console.error("Error evaluting in context:", error);
442
+ this.logger.error("Error evaluating in context", { error });
443
+ }
444
+ }
445
+ }
446
+ getMode() {
447
+ // console.log("getMode", this.#mode);
448
+ this.logger.info("Current mode", { mode: this.#mode });
449
+ return this.#mode;
450
+ }
451
+ async setMode(mode) {
452
+ await this.evaluateInAllFrames(this.context, `window.__bvt_Recorder.mode = "${mode}";`);
453
+ this.#previousMode = this.#mode;
454
+ this.#mode = mode;
455
+ }
456
+ async revertMode() {
457
+ await this.setMode(this.#previousMode);
458
+ }
459
+ async _openTab({ url }) {
460
+ // add listeners for new pages
461
+ this._addPagelisteners(this.context);
462
+ await this.page.goto(url, {
463
+ waitUntil: "domcontentloaded",
464
+ timeout: typeof this.config.page_timeout === "number" ? this.config.page_timeout : 60_000,
465
+ });
466
+ // add listener for frame navigation on current tab
467
+ this._addFrameNavigateListener(this.page);
468
+ // eval init script on current tab
469
+ // await this._initPage(this.page);
470
+ this.#currentURL = url;
471
+ await this.page.dispatchEvent("html", "scroll");
472
+ await delay(1000);
473
+ }
474
+ _addFrameNavigateListener(page) {
475
+ page.on("close", () => {
476
+ try {
477
+ if (!this.pageSet.has(page))
478
+ return;
479
+ // console.log(this.context.pages().length);
480
+ if (this.context.pages().length > 0) {
481
+ this.sendEvent(this.events.onPageClose);
482
+ }
483
+ else {
484
+ // closed all tabs
485
+ this.sendEvent(this.events.onBrowserClose);
2146
486
  }
2147
- }
2148
487
  }
2149
- } catch (error) {
2150
- console.warn("[BVTRecorder] navigator.clipboard.read failed", error);
2151
- }
2152
- }
2153
-
2154
- if (!result.text && typeof navigator.clipboard.readText === "function") {
2155
- try {
2156
- const text = await navigator.clipboard.readText();
2157
- if (text) {
2158
- result.text = text;
488
+ catch (error) {
489
+ this.logger.error("Error in page close event", { error });
490
+ console.error("Error in page close event");
491
+ console.error(error);
2159
492
  }
2160
- } catch (error) {
2161
- console.warn("[BVTRecorder] navigator.clipboard.readText failed", error);
2162
- }
2163
- }
2164
-
2165
- if (!result.text) {
2166
- const selection = window.getSelection?.()?.toString?.();
2167
- if (selection) {
2168
- result.text = selection;
2169
- }
2170
- }
2171
-
2172
- if (files.length > 0) {
2173
- result.files = files;
2174
- }
2175
-
2176
- return result;
2177
- });
2178
-
2179
- return payload;
2180
- } catch (error) {
2181
- this.logger.error("[BVTRecorder] Error collecting clipboard payload", error);
2182
- return null;
2183
- }
2184
- }
2185
-
2186
- async readClipboardPayload(message) {
2187
- try {
2188
- let payload = null;
2189
- if (this.browserEmitter && typeof this.browserEmitter.readClipboardPayload === "function") {
2190
- payload = await this.browserEmitter.readClipboardPayload();
2191
- } else {
2192
- const activePage = this.browserEmitter?.getSelectedPage() ?? this.page;
2193
- payload = await this.collectClipboardFromPage(activePage);
2194
- }
2195
-
2196
- if (this.hasClipboardPayload(payload)) {
2197
- this.logger.info("[BVTRecorder] Remote clipboard payload ready", {
2198
- hasText: !!payload.text,
2199
- hasHtml: !!payload.html,
2200
- files: payload.files?.length ?? 0,
2201
493
  });
2202
- this.sendEvent(this.events.clipboardPush, {
2203
- data: payload,
2204
- trigger: message?.trigger ?? "copy",
2205
- origin: message?.source ?? "browserUI",
494
+ page.on("framenavigated", async (frame) => {
495
+ try {
496
+ if (frame !== page.mainFrame())
497
+ return;
498
+ await this.handlePageTransition();
499
+ }
500
+ catch (error) {
501
+ this.logger.error("Error in handlePageTransition event", { error });
502
+ console.error("Error in handlePageTransition event");
503
+ console.error(error);
504
+ }
505
+ try {
506
+ if (frame !== this.#activeFrame)
507
+ return;
508
+ // hack to sync the action event with the frame navigation
509
+ await this.storeScreenshot({
510
+ element: { inputID: "frame" },
511
+ });
512
+ const newUrl = frame.url();
513
+ const newPath = new URL(newUrl).pathname;
514
+ const newTitle = await frame.title();
515
+ const changed = diffPaths(this.#currentURL, newUrl);
516
+ if (changed) {
517
+ this.sendEvent(this.events.onFrameNavigate, { url: newPath, title: newTitle });
518
+ this.#currentURL = newUrl;
519
+ }
520
+ }
521
+ catch (error) {
522
+ this.logger.error("Error in frame navigate event", { error });
523
+ console.error("Error in frame navigate event");
524
+ // console.error(error);
525
+ }
2206
526
  });
2207
- return payload;
2208
- }
2209
-
2210
- this.logger.warn("[BVTRecorder] Remote clipboard payload empty or unavailable");
2211
- this.sendEvent(this.events.clipboardError, {
2212
- message: "Remote clipboard is empty",
2213
- trigger: message?.trigger ?? "copy",
2214
- });
2215
- return null;
2216
- } catch (error) {
2217
- this.logger.error("[BVTRecorder] Error reading clipboard payload", error);
2218
- this.sendEvent(this.events.clipboardError, {
2219
- message: "Failed to read clipboard contents from the remote session",
2220
- trigger: message?.trigger ?? "copy",
2221
- details: error instanceof Error ? error.message : String(error),
2222
- });
2223
- throw error;
2224
- }
2225
- }
2226
-
2227
- async injectClipboardIntoPage(page, payload) {
2228
- if (!page) {
2229
- return;
2230
- }
2231
-
2232
- try {
2233
- await page
2234
- .context()
2235
- .grantPermissions(["clipboard-read", "clipboard-write"])
2236
- .catch(() => { });
2237
- await page.evaluate(async (clipboardPayload) => {
2238
- const toArrayBuffer = (base64) => {
2239
- if (!base64) {
2240
- return null;
2241
- }
2242
- const binaryString = atob(base64);
2243
- const len = binaryString.length;
2244
- const bytes = new Uint8Array(len);
2245
- for (let i = 0; i < len; i += 1) {
2246
- bytes[i] = binaryString.charCodeAt(i);
2247
- }
2248
- return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
527
+ }
528
+ hasHistoryReplacementAtIndex(previousEntries, currentEntries, index) {
529
+ if (!previousEntries || !currentEntries)
530
+ return false;
531
+ if (index >= previousEntries.length || index >= currentEntries.length)
532
+ return false;
533
+ const prevEntry = previousEntries[index];
534
+ // console.log("prevEntry", prevEntry);
535
+ const currEntry = currentEntries[index];
536
+ // console.log("currEntry", currEntry);
537
+ // Check if the entry at this index has been replaced
538
+ return prevEntry.id !== currEntry.id;
539
+ }
540
+ // Even simpler approach for your specific case
541
+ analyzeTransitionType(entries, currentIndex, currentEntry) {
542
+ // console.log("Analyzing transition type");
543
+ // console.log("===========================");
544
+ // console.log("Current Index:", currentIndex);
545
+ // console.log("Current Entry:", currentEntry);
546
+ // console.log("Current Entries:", entries);
547
+ // console.log("Current entries length:", entries.length);
548
+ // console.log("===========================");
549
+ // console.log("Previous Index:", this.previousIndex);
550
+ // // console.log("Previous Entry:", this.previousEntries[this.previousIndex]);
551
+ // console.log("Previous Entries:", this.previousEntries);
552
+ // console.log("Previous entries length:", this.previousHistoryLength);
553
+ if (this.previousIndex === null || this.previousHistoryLength === null || !this.previousEntries) {
554
+ return {
555
+ action: "initial",
556
+ };
557
+ }
558
+ const indexDiff = currentIndex - this.previousIndex;
559
+ const lengthDiff = entries.length - this.previousHistoryLength;
560
+ // Backward navigation
561
+ if (indexDiff < 0) {
562
+ return { action: "back" };
563
+ }
564
+ // Forward navigation
565
+ if (indexDiff > 0 && lengthDiff === 0) {
566
+ // Check if the entry at current index is the same as before
567
+ const entryReplaced = this.hasHistoryReplacementAtIndex(this.previousEntries, entries, currentIndex);
568
+ if (entryReplaced) {
569
+ return { action: "navigate" }; // New navigation that replaced forward history
570
+ }
571
+ else {
572
+ return { action: "forward" }; // True forward navigation
573
+ }
574
+ }
575
+ // New navigation (history grew)
576
+ if (lengthDiff > 0) {
577
+ return { action: "navigate" };
578
+ }
579
+ // Same position, same length
580
+ if (lengthDiff <= 0) {
581
+ const entryReplaced = this.hasHistoryReplacementAtIndex(this.previousEntries, entries, currentIndex);
582
+ return entryReplaced ? { action: "navigate" } : { action: "reload" };
583
+ }
584
+ return { action: "unknown" };
585
+ }
586
+ async getCurrentTransition() {
587
+ if (this?.web?.browser?._name !== "chromium") {
588
+ return;
589
+ }
590
+ const client = await this.context.newCDPSession(this.web.page);
591
+ try {
592
+ const result = await client.send("Page.getNavigationHistory");
593
+ const entries = result.entries;
594
+ const currentIndex = result.currentIndex;
595
+ const currentEntry = entries[currentIndex];
596
+ const transitionInfo = this.analyzeTransitionType(entries, currentIndex, currentEntry);
597
+ this.previousIndex = currentIndex;
598
+ this.previousHistoryLength = entries.length;
599
+ this.previousUrl = currentEntry.url;
600
+ this.previousEntries = [...entries]; // Store a copy of current entries
601
+ return {
602
+ currentEntry,
603
+ navigationAction: transitionInfo.action,
604
+ };
605
+ }
606
+ catch (error) {
607
+ this.logger.error("Error in getCurrentTransition event", { error });
608
+ console.error("Error in getTransistionType event", error);
609
+ }
610
+ finally {
611
+ await client.detach();
612
+ }
613
+ }
614
+ userInitiatedTransitionTypes = ["typed", "address_bar"];
615
+ async handlePageTransition() {
616
+ const transition = await this.getCurrentTransition();
617
+ if (!transition)
618
+ return;
619
+ const { currentEntry, navigationAction } = transition;
620
+ switch (navigationAction) {
621
+ case "initial":
622
+ // console.log("Initial navigation, no action taken");
623
+ return;
624
+ case "navigate":
625
+ // console.log("transitionType", transition.transitionType);
626
+ // console.log("sending onGoto event", { url: currentEntry.url,
627
+ // type: "navigate", });
628
+ if (this.userInitiatedTransitionTypes.includes(currentEntry.transitionType)) {
629
+ const env = JSON.parse(readFileSync(this.envName, "utf8"));
630
+ const baseUrl = env.baseUrl;
631
+ let url = currentEntry.userTypedURL;
632
+ if (baseUrl && url.startsWith(baseUrl)) {
633
+ url = url.replace(baseUrl, "{{env.baseUrl}}");
634
+ }
635
+ // console.log("User initiated transition");
636
+ this.sendEvent(this.events.onGoto, { url, type: "navigate" });
637
+ }
638
+ return;
639
+ case "back":
640
+ // console.log("User navigated back");
641
+ // console.log("sending onGoto event", {
642
+ // type: "back",
643
+ // });
644
+ this.sendEvent(this.events.onGoto, { type: "back" });
645
+ return;
646
+ case "forward":
647
+ // console.log("User navigated forward"); console.log("sending onGoto event", { type: "forward", });
648
+ this.sendEvent(this.events.onGoto, { type: "forward" });
649
+ return;
650
+ default:
651
+ this.sendEvent(this.events.onGoto, { type: "unknown" });
652
+ return;
653
+ }
654
+ }
655
+ async getCurrentPageTitle() {
656
+ let title = "";
657
+ try {
658
+ title = await this.bvtContext?.page?.title();
659
+ }
660
+ catch (e) {
661
+ this.logger.error(`Error getting page title: ${getErrorMessage(e)}`);
662
+ }
663
+ return title;
664
+ }
665
+ getCurrentPageUrl() {
666
+ let url = "";
667
+ try {
668
+ url = this.bvtContext?.page?.url();
669
+ }
670
+ catch (e) {
671
+ this.logger.error(`Error getting page url: ${getErrorMessage(e)}`);
672
+ }
673
+ return url;
674
+ }
675
+ _addPagelisteners(context) {
676
+ context.on("page", async (page) => {
677
+ try {
678
+ if (page.isClosed())
679
+ return;
680
+ this.pageSet.add(page);
681
+ await page.waitForLoadState("domcontentloaded");
682
+ // add listener for frame navigation on new tab
683
+ this._addFrameNavigateListener(page);
684
+ }
685
+ catch (error) {
686
+ this.logger.error(`Error in page event: ${getErrorMessage(error)}`, undefined, "_addPagelisteners");
687
+ }
688
+ });
689
+ }
690
+ async openBrowser(_input) {
691
+ const env = JSON.parse(readFileSync(this.envName, "utf8"));
692
+ const url = env.baseUrl;
693
+ await this._initBrowser({ url });
694
+ await this._openTab({ url });
695
+ process.env.TEMP_RUN = "true";
696
+ }
697
+ overlayLocators(event) {
698
+ const locatorsResults = [...(event.locators ?? [])];
699
+ for (const cssLocator of event.cssLocators ?? []) {
700
+ locatorsResults.push({ mode: "NO_TEXT", css: cssLocator });
701
+ }
702
+ if (event.digitLocators) {
703
+ for (const digitLocator of event.digitLocators) {
704
+ locatorsResults.push({ ...digitLocator, mode: "IGNORE_DIGIT" });
705
+ }
706
+ }
707
+ if (event.contextLocator) {
708
+ locatorsResults.push({
709
+ mode: "CONTEXT",
710
+ text: event.contextLocator.texts?.[0],
711
+ css: event.contextLocator.css,
712
+ climb: event.contextLocator.climbCount,
713
+ });
714
+ }
715
+ return locatorsResults;
716
+ }
717
+ setShouldTakeScreenshot(input) {
718
+ this.shouldTakeScreenshot = input?.value;
719
+ }
720
+ async getScreenShot() {
721
+ const client = await this.context.newCDPSession(this.web.page);
722
+ try {
723
+ // Using CDP to capture the screenshot
724
+ const { data } = await client.send("Page.captureScreenshot", { format: "png" });
725
+ return data;
726
+ }
727
+ catch (error) {
728
+ this.logger.error("Error in taking browser screenshot", { error });
729
+ console.error("Error in taking browser screenshot", error);
730
+ }
731
+ finally {
732
+ await client.detach();
733
+ }
734
+ }
735
+ async storeScreenshot(event) {
736
+ try {
737
+ // const spath = path.join(__dirname, "media", `${event.inputID}.png`);
738
+ const screenshotURL = await this.getScreenShot();
739
+ if (!event.element.inputID) {
740
+ return;
741
+ }
742
+ const inputId = event.element.inputID;
743
+ if (!screenshotURL) {
744
+ return;
745
+ }
746
+ this.screenshotMap.set(inputId, screenshotURL);
747
+ // writeFileSync(spath, screenshotURL, "base64");
748
+ }
749
+ catch (error) {
750
+ this.logger.error(`Error in storeScreenshot: ${getErrorMessage(error)}`, undefined, "storeScreenshot");
751
+ }
752
+ }
753
+ async generateLocators(event) {
754
+ const snapshotDetails = event.snapshotDetails;
755
+ if (!snapshotDetails) {
756
+ throw new Error("No snapshot details found");
757
+ }
758
+ const mode = event.mode;
759
+ const inputID = event.element.inputID;
760
+ const { id, contextId, doc } = snapshotDetails;
761
+ if (!doc) {
762
+ throw new Error("Snapshot details missing document content");
763
+ }
764
+ // const selector = `[data-blinq-id="${id}"]`;
765
+ if (!this.backgroundContext) {
766
+ throw new Error("Background context not initialized");
767
+ }
768
+ const newPage = await this.backgroundContext.newPage();
769
+ const htmlDoc = doc;
770
+ await newPage.setContent(htmlDoc, { waitUntil: "domcontentloaded" });
771
+ const locatorsObj = await newPage.evaluate(([id, contextId, mode]) => {
772
+ const recorder = window.__bvt_Recorder;
773
+ const contextElement = document.querySelector(`[data-blinq-context-id="${contextId}"]`);
774
+ const el = document.querySelector(`[data-blinq-id="${id}"]`);
775
+ if (!recorder || !el) {
776
+ return { locators: [], allStrategyLocators: [] };
777
+ }
778
+ if (contextElement && recorder.locatorGenerator.toContextLocators) {
779
+ const result = recorder.locatorGenerator.toContextLocators(el, contextElement);
780
+ return result ?? { locators: [], allStrategyLocators: [] };
781
+ }
782
+ const isRecordingText = mode === "recordingText";
783
+ return recorder.locatorGenerator.getElementLocators(el, {
784
+ excludeText: isRecordingText,
785
+ });
786
+ }, [id, contextId, mode]);
787
+ // console.log(`Generated locators: for ${inputID}: `, JSON.stringify(locatorsObj));
788
+ await newPage.close();
789
+ if (event.nestFrmLoc?.children) {
790
+ locatorsObj.nestFrmLoc = event.nestFrmLoc.children;
791
+ }
792
+ this.sendEvent(this.events.updateCommand, {
793
+ locators: {
794
+ locators: locatorsObj.locators,
795
+ nestFrmLoc: locatorsObj.nestFrmLoc,
796
+ iframe_src: !event.frame.isTop ? event.frame.url : undefined,
797
+ },
798
+ allStrategyLocators: locatorsObj.allStrategyLocators,
799
+ inputID,
800
+ });
801
+ // const
802
+ }
803
+ async onAction(event) {
804
+ this._updateUrlPath();
805
+ // const locators = this.overlayLocators(event);
806
+ const cmdEvent = {
807
+ ...event.element,
808
+ ...transformAction(event.action, event.element, event.mode === "recordingText" || event.mode === "recordingContext", !!event.isPopupCloseClick, event.mode === "recordingHover", event.mode === "multiInspecting"),
809
+ // locators: {
810
+ // locators: event.locators,
811
+ // iframe_src: !event.frame.isTop ? event.frame.url : undefined,
812
+ // },
813
+ // allStrategyLocators: event.allStrategyLocators,
814
+ url: event.frame.url,
815
+ title: event.frame.title,
816
+ extract: {},
817
+ lastKnownUrlPath: this.lastKnownUrlPath,
2249
818
  };
2250
-
2251
- const createFileFromPayload = (filePayload) => {
2252
- const buffer = toArrayBuffer(filePayload?.data);
2253
- if (!buffer) {
2254
- return null;
2255
- }
2256
- const name = filePayload?.name || "clipboard-file";
2257
- const type = filePayload?.type || "application/octet-stream";
2258
- const lastModified = filePayload?.lastModified ?? Date.now();
2259
- try {
2260
- return new File([buffer], name, { type, lastModified });
2261
- } catch (error) {
2262
- console.warn("Clipboard bridge could not recreate File object", error);
2263
- return null;
2264
- }
819
+ // if (event.nestFrmLoc?.children) {
820
+ // cmdEvent.locators.nestFrmLoc = event.nestFrmLoc.children;
821
+ // }
822
+ // this.logger.info({ event });
823
+ if (this.shouldTakeScreenshot) {
824
+ await this.storeScreenshot(event);
825
+ }
826
+ // this.sendEvent(this.events.onNewCommand, cmdEvent);
827
+ // this._updateUrlPath();
828
+ if (event.locators) {
829
+ Object.assign(cmdEvent, {
830
+ locators: {
831
+ locators: event.locators,
832
+ iframe_src: !event.frame.isTop ? event.frame.url : undefined,
833
+ nestFrmLoc: event.nestFrmLoc?.children,
834
+ },
835
+ allStrategyLocators: event.allStrategyLocators,
836
+ });
837
+ this.sendEvent(this.events.onNewCommand, cmdEvent);
838
+ this._updateUrlPath();
839
+ }
840
+ else {
841
+ this.sendEvent(this.events.onNewCommand, cmdEvent);
842
+ this._updateUrlPath();
843
+ await this.generateLocators(event);
844
+ }
845
+ }
846
+ _updateUrlPath() {
847
+ try {
848
+ const url = this.bvtContext?.web?.page.url();
849
+ if (url && url !== "about:blank") {
850
+ this.lastKnownUrlPath = new URL(url).pathname;
851
+ }
852
+ }
853
+ catch (error) {
854
+ this.logger.error("Error in getting last known url path", { error });
855
+ }
856
+ return this.lastKnownUrlPath;
857
+ }
858
+ async closeBrowser(_input) {
859
+ delete process.env.TEMP_RUN;
860
+ await this.watcher?.close();
861
+ this.watcher = null;
862
+ this.previousIndex = null;
863
+ this.previousHistoryLength = null;
864
+ this.previousUrl = null;
865
+ this.previousEntries = null;
866
+ await closeContext();
867
+ this.pageSet.clear();
868
+ }
869
+ async reOpenBrowser(input) {
870
+ if (input && input.envName) {
871
+ this.envName = path.join(this.projectDir, "environments", input.envName + ".json");
872
+ process.env.BLINQ_ENV = this.envName;
873
+ }
874
+ await this.closeBrowser();
875
+ // logger.log("closed");
876
+ await delay(1000);
877
+ await this.openBrowser();
878
+ // logger.log("opened");
879
+ }
880
+ async getNumberOfOccurrences({ searchString, regex = false, partial = true, ignoreCase = false, tag = "*", }) {
881
+ this.isVerify = false;
882
+ //const script = `window.countStringOccurrences(${JSON.stringify(searchString)});`;
883
+ if (searchString.length === 0)
884
+ return -1;
885
+ let result = 0;
886
+ for (let i = 0; i < 3; i++) {
887
+ result = 0;
888
+ try {
889
+ // for (const page of this.context.pages()) {
890
+ const page = this.web.page;
891
+ for (const frame of page.frames()) {
892
+ try {
893
+ //scope, text1, tag1, regex1 = false, partial1, ignoreCase = true, _params: Params)
894
+ const frameResult = await this.web._locateElementByText(frame, searchString, tag, regex, partial, ignoreCase, {});
895
+ result += frameResult.elementCount;
896
+ }
897
+ catch (e) {
898
+ console.log(e);
899
+ }
900
+ }
901
+ // }
902
+ return result;
903
+ }
904
+ catch (e) {
905
+ console.log(e);
906
+ result = 0;
907
+ }
908
+ }
909
+ }
910
+ async startRecordingInput(_input) {
911
+ await this.setMode("recordingInput");
912
+ }
913
+ async stopRecordingInput(_input) {
914
+ await this.setMode("idle");
915
+ }
916
+ async startRecordingText(input) {
917
+ const isInspectMode = typeof input === "boolean" ? input : !!input?.isInspectMode;
918
+ if (isInspectMode) {
919
+ await this.setMode("inspecting");
920
+ }
921
+ else {
922
+ await this.setMode("recordingText");
923
+ }
924
+ }
925
+ async stopRecordingText(_input) {
926
+ await this.setMode("idle");
927
+ }
928
+ async startRecordingContext(_input) {
929
+ await this.setMode("recordingContext");
930
+ }
931
+ async stopRecordingContext(_input) {
932
+ await this.setMode("idle");
933
+ }
934
+ async abortExecution() {
935
+ await this.stepRunner.abortExecution();
936
+ }
937
+ async pauseExecution({ cmdId }) {
938
+ await this.stepRunner.pauseExecution(cmdId);
939
+ }
940
+ async resumeExecution({ cmdId }) {
941
+ await this.stepRunner.resumeExecution(cmdId);
942
+ }
943
+ async dealyedRevertMode() {
944
+ const timerId = setTimeout(async () => {
945
+ await this.revertMode();
946
+ }, 100);
947
+ this.timerId = timerId;
948
+ }
949
+ async runStep({ step, parametersMap, tags, isFirstStep = false, listenNetwork = false, AICode }, options) {
950
+ const { skipAfter = true, skipBefore = !isFirstStep } = options || {};
951
+ const env = path.basename(this.envName, ".json");
952
+ const envVars = {
953
+ TOKEN: this.TOKEN,
954
+ TEMP_RUN: "true",
955
+ REPORT_FOLDER: this.bvtContext?.reportFolder,
956
+ BLINQ_ENV: this.envName,
957
+ DEBUG: "blinq:route",
2265
958
  };
2266
-
2267
- let dataTransfer = null;
959
+ if (!step.isImplemented) {
960
+ envVars.BVT_TEMP_SNAPSHOTS_FOLDER = path.join(this.tempSnapshotsFolder, env);
961
+ }
962
+ this.bvtContext.navigate = true;
963
+ this.bvtContext.loadedRoutes = null;
964
+ this.bvtContext.STORE_DETAILED_NETWORK_DATA = !!listenNetwork;
965
+ for (const [key, value] of Object.entries(envVars)) {
966
+ process.env[key] = value;
967
+ }
968
+ if (this.timerId) {
969
+ clearTimeout(this.timerId);
970
+ this.timerId = null;
971
+ }
972
+ await this.setMode("running");
2268
973
  try {
2269
- dataTransfer = new DataTransfer();
2270
- } catch (error) {
2271
- console.warn("Clipboard bridge could not create DataTransfer", error);
974
+ step.text = step.text.trim();
975
+ const { result, info } = await this.stepRunner.runStep({
976
+ step,
977
+ parametersMap,
978
+ envPath: this.envName,
979
+ tags,
980
+ config: this.config,
981
+ AICode
982
+ }, this.bvtContext, {
983
+ skipAfter,
984
+ skipBefore,
985
+ });
986
+ await this.revertMode();
987
+ return { info };
988
+ }
989
+ catch (error) {
990
+ await this.revertMode();
991
+ throw error;
992
+ }
993
+ finally {
994
+ for (const key of Object.keys(envVars)) {
995
+ delete process.env[key];
996
+ }
997
+ this.bvtContext.navigate = false;
998
+ }
999
+ }
1000
+ async saveScenario({ scenario, featureName, override, isSingleStep, branch, isEditing, env, AICode, }) {
1001
+ const res = await this.workspaceService.saveScenario({
1002
+ scenario,
1003
+ featureName,
1004
+ override,
1005
+ isSingleStep,
1006
+ branch,
1007
+ isEditing,
1008
+ projectId: path.basename(this.projectDir),
1009
+ env: env ?? this.envName,
1010
+ });
1011
+ if (res.success) {
1012
+ await this.cleanup({ tags: scenario.tags });
1013
+ }
1014
+ else {
1015
+ throw new Error(res.message || "Error saving scenario");
2272
1016
  }
2273
-
2274
- if (dataTransfer) {
2275
- if (clipboardPayload?.text) {
1017
+ }
1018
+ async getImplementedSteps(_input) {
1019
+ const stepsAndScenarios = await getImplementedSteps(this.projectDir);
1020
+ const implementedSteps = stepsAndScenarios.implementedSteps;
1021
+ const scenarios = stepsAndScenarios.scenarios;
1022
+ for (const scenario of scenarios) {
1023
+ this.scenariosStepsMap.set(scenario.name, scenario.steps);
1024
+ delete scenario.steps;
1025
+ }
1026
+ return {
1027
+ implementedSteps,
1028
+ scenarios,
1029
+ };
1030
+ }
1031
+ async getStepsAndCommandsForScenario({ name, featureName }) {
1032
+ const steps = this.scenariosStepsMap.get(name) || [];
1033
+ for (const step of steps) {
1034
+ if (step.isImplemented) {
1035
+ step.commands = this.getCommandsForImplementedStep({ stepName: step.text });
1036
+ }
1037
+ else {
1038
+ step.commands = [];
1039
+ }
1040
+ }
1041
+ return steps;
1042
+ }
1043
+ async generateStepName({ commands, stepsNames, parameters, map, }) {
1044
+ return await this.namesService.generateStepName({ commands, stepsNames, parameters, map });
1045
+ }
1046
+ async generateScenarioAndFeatureNames(scenarioAsText) {
1047
+ return await this.namesService.generateScenarioAndFeatureNames(scenarioAsText);
1048
+ }
1049
+ async generateCommandName({ command }) {
1050
+ return await this.namesService.generateCommandName({ command });
1051
+ }
1052
+ getCurrentChromiumPath() {
1053
+ const env = JSON.parse(readFileSync(this.envName, "utf8"));
1054
+ const baseURL = env.baseUrl;
1055
+ let currentURL = null;
1056
+ currentURL = this.bvtContext?.web?.page?.url();
1057
+ let relativeURL = undefined;
1058
+ if (typeof currentURL == "string") {
1059
+ relativeURL = currentURL.startsWith(baseURL) ? currentURL.replace(baseURL, "/") : undefined;
1060
+ }
1061
+ return {
1062
+ relativeURL,
1063
+ baseURL,
1064
+ currentURL,
1065
+ };
1066
+ }
1067
+ getReportFolder() {
1068
+ if (this.bvtContext.reportFolder) {
1069
+ return this.bvtContext.reportFolder;
1070
+ }
1071
+ else
1072
+ return "";
1073
+ }
1074
+ getSnapshotFolder() {
1075
+ if (this.bvtContext.snapshotFolder) {
1076
+ return path.join(process.cwd(), this.bvtContext.snapshotFolder);
1077
+ }
1078
+ else
1079
+ return "";
1080
+ }
1081
+ async overwriteTestData(data) {
1082
+ this.bvtContext.stable?.overwriteTestData(data.value, this.world);
1083
+ }
1084
+ _watchTestData() {
1085
+ this.watcher = chokidar.watch(_getDataFile(this.world, this.bvtContext, this.web), {
1086
+ persistent: true,
1087
+ ignoreInitial: true,
1088
+ awaitWriteFinish: {
1089
+ stabilityThreshold: 2000,
1090
+ pollInterval: 100,
1091
+ },
1092
+ });
1093
+ if (existsSync(_getDataFile(this.world, this.bvtContext, this.web))) {
2276
1094
  try {
2277
- dataTransfer.setData("text/plain", clipboardPayload.text);
2278
- } catch (error) {
2279
- console.warn("Clipboard bridge failed to set text/plain", error);
1095
+ const testData = JSON.parse(readFileSync(_getDataFile(this.world, this.bvtContext, this.web), "utf8"));
1096
+ // this.logger.info("Test data", testData);
1097
+ this.sendEvent(this.events.getTestData, testData);
1098
+ }
1099
+ catch (e) {
1100
+ // this.logger.error("Error reading test data file", e);
1101
+ console.log("Error reading test data file", e);
2280
1102
  }
2281
- }
2282
- if (clipboardPayload?.html) {
1103
+ }
1104
+ this.logger.info("Watching for test data changes");
1105
+ this.watcher.on("all", async (_event, _path) => {
2283
1106
  try {
2284
- dataTransfer.setData("text/html", clipboardPayload.html);
2285
- } catch (error) {
2286
- console.warn("Clipboard bridge failed to set text/html", error);
1107
+ const testData = JSON.parse(await readFile(_getDataFile(this.world, this.bvtContext, this.web), "utf8"));
1108
+ // this.logger.info("Test data", testData);
1109
+ console.log("Test data changed", testData);
1110
+ this.sendEvent(this.events.getTestData, testData);
1111
+ }
1112
+ catch (e) {
1113
+ // this.logger.error("Error reading test data file", e);
1114
+ console.log("Error reading test data file", e);
1115
+ }
1116
+ });
1117
+ }
1118
+ async loadTestData({ data, type }) {
1119
+ if (type === "user") {
1120
+ const username = data.username;
1121
+ await this.web.loadTestDataAsync("users", username, this.world);
1122
+ }
1123
+ else {
1124
+ const csv = data.csv;
1125
+ const row = data.row;
1126
+ // code = `await context.web.loadTestDataAsync("csv","${csv}:${row}", this)`;
1127
+ await this.web.loadTestDataAsync("csv", `${csv}:${row}`, this.world);
1128
+ }
1129
+ }
1130
+ async discardTestData({ tags }) {
1131
+ resetTestData(this.envName, this.world);
1132
+ await this.cleanup({ tags });
1133
+ }
1134
+ async addToTestData(obj) {
1135
+ if (!existsSync(_getDataFile(this.world, this.bvtContext, this.web))) {
1136
+ await writeFile(_getDataFile(this.world, this.bvtContext, this.web), JSON.stringify({}), "utf8");
1137
+ }
1138
+ let data = JSON.parse(await readFile(_getDataFile(this.world, this.bvtContext, this.web), "utf8"));
1139
+ data = Object.assign(data, obj);
1140
+ await writeFile(_getDataFile(this.world, this.bvtContext, this.web), JSON.stringify(data), "utf8");
1141
+ }
1142
+ getScenarios() {
1143
+ const featureFiles = readdirSync(path.join(this.projectDir, "features"))
1144
+ .filter((file) => file.endsWith(".feature"))
1145
+ .map((file) => path.join(this.projectDir, "features", file));
1146
+ try {
1147
+ const parsedFiles = featureFiles.map((file) => this.parseFeatureFile(file));
1148
+ const output = {};
1149
+ parsedFiles.forEach((file) => {
1150
+ if (!file.feature)
1151
+ return;
1152
+ if (!file.feature.name)
1153
+ return;
1154
+ output[file.feature.name] = [];
1155
+ file.feature.children.forEach((child) => {
1156
+ if (child.scenario) {
1157
+ output[file.feature.name].push(child.scenario.name);
1158
+ }
1159
+ });
1160
+ });
1161
+ return output;
1162
+ }
1163
+ catch (e) {
1164
+ console.log(e);
1165
+ }
1166
+ return {};
1167
+ }
1168
+ getCommandsForImplementedStep({ stepName }) {
1169
+ const step_definitions = loadStepDefinitions(this.projectDir);
1170
+ const stepParams = parseStepTextParameters(stepName);
1171
+ return getCommandsForImplementedStep(stepName, step_definitions, stepParams).commands;
1172
+ }
1173
+ loadExistingScenario({ featureName, scenarioName }) {
1174
+ const step_definitions = loadStepDefinitions(this.projectDir);
1175
+ const featureFilePath = path.join(this.projectDir, "features", featureName);
1176
+ const gherkinDoc = this.parseFeatureFile(featureFilePath);
1177
+ const scenario = gherkinDoc.feature.children.find((child) => child.scenario.name === scenarioName)?.scenario;
1178
+ this.scenarioDoc = scenario;
1179
+ const steps = [];
1180
+ const parameters = [];
1181
+ const datasets = [];
1182
+ if (scenario.examples && scenario.examples.length > 0) {
1183
+ const example = scenario.examples[0];
1184
+ example?.tableHeader?.cells.forEach((cell, index) => {
1185
+ parameters.push({
1186
+ key: cell.value,
1187
+ value: unEscapeNonPrintables(example.tableBody[0].cells[index].value),
1188
+ });
1189
+ // datasets.push({
1190
+ // data: example.tableBody[]
1191
+ // })
1192
+ });
1193
+ for (let i = 0; i < example.tableBody.length; i++) {
1194
+ const row = example.tableBody[i];
1195
+ // for (const row of example.tableBody) {
1196
+ const paramters = [];
1197
+ row.cells.forEach((cell, index) => {
1198
+ paramters.push({
1199
+ key: example.tableHeader.cells[index].value,
1200
+ value: unEscapeNonPrintables(cell.value),
1201
+ });
1202
+ });
1203
+ datasets.push({
1204
+ data: paramters,
1205
+ datasetId: i,
1206
+ });
2287
1207
  }
2288
- }
2289
- if (Array.isArray(clipboardPayload?.files)) {
2290
- for (const filePayload of clipboardPayload.files) {
2291
- const file = createFileFromPayload(filePayload);
2292
- if (file) {
1208
+ }
1209
+ for (const step of scenario.steps) {
1210
+ const stepParams = parseStepTextParameters(step.text);
1211
+ // console.log("Parsing step ", step, stepParams);
1212
+ const _s = getCommandsForImplementedStep(step.text, step_definitions, stepParams);
1213
+ delete step.location;
1214
+ const _step = {
1215
+ ...step,
1216
+ ..._s,
1217
+ keyword: step.keyword.trim(),
1218
+ };
1219
+ parseRouteFiles(this.projectDir, _step);
1220
+ steps.push(_step);
1221
+ }
1222
+ return {
1223
+ name: scenario.name,
1224
+ tags: scenario.tags.map((tag) => tag.name),
1225
+ steps,
1226
+ parameters,
1227
+ datasets,
1228
+ };
1229
+ }
1230
+ async findRelatedTextInAllFrames({ searchString, climb, contextText, params, }) {
1231
+ if (searchString.length === 0)
1232
+ return -1;
1233
+ let result = 0;
1234
+ for (let i = 0; i < 3; i++) {
1235
+ result = 0;
1236
+ try {
2293
1237
  try {
2294
- dataTransfer.items.add(file);
2295
- } catch (error) {
2296
- console.warn("Clipboard bridge failed to append file", error);
1238
+ const allFrameResult = await this.web.findRelatedTextInAllFrames(contextText, climb, searchString, params, {}, this.world);
1239
+ for (const frameResult of allFrameResult) {
1240
+ result += frameResult.elementCount;
1241
+ }
1242
+ }
1243
+ catch (e) {
1244
+ console.log(e);
2297
1245
  }
2298
- }
1246
+ return result;
1247
+ }
1248
+ catch (e) {
1249
+ console.log(e);
1250
+ result = 0;
1251
+ }
1252
+ }
1253
+ return result;
1254
+ }
1255
+ async setStepCodeByScenario({ function_name, mjs_file_content, user_request, selectedTarget, page_context, AIMemory, steps_context, }) {
1256
+ const runsURL = getRunsServiceBaseURL();
1257
+ const url = `${runsURL}/process-user-request/generate-code-with-context`;
1258
+ try {
1259
+ const result = await axiosClient({
1260
+ url,
1261
+ method: "POST",
1262
+ data: {
1263
+ function_name,
1264
+ mjs_file_content,
1265
+ user_request,
1266
+ selectedTarget,
1267
+ page_context,
1268
+ AIMemory,
1269
+ steps_context,
1270
+ },
1271
+ headers: {
1272
+ Authorization: `Bearer ${this.TOKEN}`,
1273
+ "X-Source": "recorder",
1274
+ },
1275
+ });
1276
+ if (result.status !== 200) {
1277
+ return { success: false, message: "Error while fetching code changes" };
2299
1278
  }
2300
- }
2301
- }
2302
-
2303
- let target = document.activeElement || document.body;
2304
- if (!target) {
2305
- target = document.body || null;
2306
- }
2307
-
2308
- let pasteHandled = false;
2309
- if (dataTransfer && target && typeof target.dispatchEvent === "function") {
2310
- try {
2311
- const clipboardEvent = new ClipboardEvent("paste", {
2312
- clipboardData: dataTransfer,
2313
- bubbles: true,
2314
- cancelable: true,
1279
+ return { success: true, data: result.data };
1280
+ }
1281
+ catch (error) {
1282
+ // @ts-ignore
1283
+ const reason = error?.response?.data?.error || "";
1284
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
1285
+ throw new Error(`Failed to fetch code changes: ${errorMessage} \n ${reason}`);
1286
+ }
1287
+ }
1288
+ async getStepCodeByScenario({ featureName, scenarioName, projectId, branch, }) {
1289
+ try {
1290
+ const runsURL = getRunsServiceBaseURL();
1291
+ const ssoURL = runsURL.replace("/runs", "/auth");
1292
+ const privateRepoURL = `${ssoURL}/isRepoPrivate?project_id=${projectId}`;
1293
+ const isPrivateRepoReq = await axiosClient({
1294
+ url: privateRepoURL,
1295
+ method: "GET",
1296
+ headers: {
1297
+ Authorization: `Bearer ${this.TOKEN}`,
1298
+ "X-Source": "recorder",
1299
+ },
2315
1300
  });
2316
- pasteHandled = target.dispatchEvent(clipboardEvent);
2317
- } catch (error) {
2318
- console.warn("Clipboard bridge failed to dispatch synthetic paste event", error);
2319
- }
2320
- }
2321
-
2322
- if (pasteHandled) {
2323
- return;
2324
- }
2325
-
2326
- const callLegacyExecCommand = (command, value) => {
2327
- const execCommand = document && document["execCommand"];
2328
- if (typeof execCommand === "function") {
2329
- try {
2330
- return execCommand.call(document, command, false, value);
2331
- } catch (error) {
2332
- console.warn("Clipboard bridge failed to execute legacy command", error);
1301
+ if (isPrivateRepoReq.status !== 200) {
1302
+ return { success: false, message: "Error while checking repo privacy" };
2333
1303
  }
2334
- }
2335
- return false;
2336
- };
2337
-
2338
- if (clipboardPayload?.html) {
2339
- const inserted = callLegacyExecCommand("insertHTML", clipboardPayload.html);
2340
- if (inserted) {
1304
+ const isPrivateRepo = isPrivateRepoReq.data.isPrivate ? isPrivateRepoReq.data.isPrivate : false;
1305
+ const workspaceURL = runsURL.replace("/runs", "/workspace");
1306
+ const url = `${workspaceURL}/get-step-code-by-scenario`;
1307
+ const result = await axiosClient({
1308
+ url,
1309
+ method: "POST",
1310
+ data: {
1311
+ scenarioName,
1312
+ featureName,
1313
+ projectId,
1314
+ isPrivateRepo,
1315
+ branch,
1316
+ },
1317
+ headers: {
1318
+ Authorization: `Bearer ${this.TOKEN}`,
1319
+ "X-Source": "recorder",
1320
+ },
1321
+ });
1322
+ if (result.status !== 200) {
1323
+ return { success: false, message: "Error while getting step code" };
1324
+ }
1325
+ return { success: true, data: result.data.stepInfo };
1326
+ }
1327
+ catch (error) {
1328
+ const axiosError = error;
1329
+ const reason = axiosError?.response?.data?.error || "";
1330
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
1331
+ throw new Error(`Failed to get step code: ${errorMessage} \n ${reason}`);
1332
+ }
1333
+ }
1334
+ async getContext() {
1335
+ await this.page.waitForLoadState("domcontentloaded");
1336
+ await this.page.waitForSelector("body");
1337
+ await this.page.waitForTimeout(500);
1338
+ return await this.page.evaluate(() => {
1339
+ return document.documentElement.outerHTML;
1340
+ });
1341
+ }
1342
+ async deleteCommandFromStepCode({ scenario, AICode, command }) {
1343
+ if (!AICode || AICode.length === 0) {
1344
+ console.log("No AI code available to delete.");
2341
1345
  return;
2342
- }
2343
- try {
2344
- const selection = window.getSelection?.();
2345
- if (selection && selection.rangeCount > 0) {
2346
- const range = selection.getRangeAt(0);
2347
- range.deleteContents();
2348
- const fragment = range.createContextualFragment(clipboardPayload.html);
2349
- range.insertNode(fragment);
2350
- range.collapse(false);
2351
- return;
1346
+ }
1347
+ const __temp_features_FolderName = "__temp_features" + Math.random().toString(36).substring(2, 7);
1348
+ const tempFolderPath = path.join(this.projectDir, __temp_features_FolderName);
1349
+ process.env.tempFeaturesFolderPath = __temp_features_FolderName;
1350
+ process.env.TESTCASE_REPORT_FOLDER_PATH = tempFolderPath;
1351
+ try {
1352
+ await this.stepRunner.copyCodetoTempFolder({ tempFolderPath, AICode });
1353
+ await this.stepRunner.writeWrapperCode(tempFolderPath);
1354
+ const codeView = AICode.find((f) => f.stepName === scenario.step.text);
1355
+ if (!codeView) {
1356
+ throw new Error("Step code not found for step: " + scenario.step.text);
1357
+ }
1358
+ const functionName = codeView.functionName;
1359
+ const mjsPath = path
1360
+ .normalize(codeView.mjsFile)
1361
+ .split(path.sep)
1362
+ .filter((part) => part !== "features")
1363
+ .join(path.sep);
1364
+ const codePath = path.join(tempFolderPath, mjsPath);
1365
+ if (!existsSync(codePath)) {
1366
+ throw new Error("Step code file not found: " + codePath);
2352
1367
  }
2353
- } catch (error) {
2354
- console.warn("Clipboard bridge could not insert HTML via Range APIs", error);
2355
- }
2356
- }
2357
-
2358
- if (clipboardPayload?.text) {
2359
- const inserted = callLegacyExecCommand("insertText", clipboardPayload.text);
2360
- if (inserted) {
1368
+ const codePage = getCodePage(codePath);
1369
+ const elements = codePage.getVariableDeclarationAsObject("elements");
1370
+ const cucumberStep = getCucumberStep({ step: scenario.step });
1371
+ cucumberStep.text = scenario.step.text;
1372
+ const stepCommands = scenario.step.commands;
1373
+ const cmd = _toRecordingStep(command, scenario.step.name);
1374
+ const recording = new Recording();
1375
+ recording.loadFromObject({ steps: stepCommands, step: cucumberStep });
1376
+ const step = { ...(recording.steps[0] ?? {}), ...(cmd ?? {}) };
1377
+ const result = _generateCodeFromCommand(step, elements, {});
1378
+ codePage._removeCommands(functionName, result.codeLines);
1379
+ codePage.removeUnusedElements();
1380
+ codePage.save();
1381
+ await rm(tempFolderPath, { recursive: true, force: true });
1382
+ return { code: codePage.fileContent, mjsFile: codeView.mjsFile };
1383
+ }
1384
+ catch (error) {
1385
+ await rm(tempFolderPath, { recursive: true, force: true });
1386
+ throw error;
1387
+ }
1388
+ }
1389
+ async addCommandToStepCode({ scenario, AICode }) {
1390
+ if (!AICode || AICode.length === 0) {
1391
+ console.log("No AI code available to add.");
2361
1392
  return;
2362
- }
2363
- try {
2364
- const selection = window.getSelection?.();
2365
- if (selection && selection.rangeCount > 0) {
2366
- const range = selection.getRangeAt(0);
2367
- range.deleteContents();
2368
- range.insertNode(document.createTextNode(clipboardPayload.text));
2369
- range.collapse(false);
2370
- return;
1393
+ }
1394
+ const __temp_features_FolderName = "__temp_features" + Math.random().toString(36).substring(2, 7);
1395
+ const tempFolderPath = path.join(this.projectDir, __temp_features_FolderName);
1396
+ process.env.tempFeaturesFolderPath = __temp_features_FolderName;
1397
+ process.env.TESTCASE_REPORT_FOLDER_PATH = tempFolderPath;
1398
+ try {
1399
+ await this.stepRunner.copyCodetoTempFolder({ tempFolderPath, AICode });
1400
+ await this.stepRunner.writeWrapperCode(tempFolderPath);
1401
+ let codeView = AICode.find((f) => f.stepName === scenario.step.text);
1402
+ if (codeView) {
1403
+ scenario.step.commands = [scenario.step.commands.pop()];
1404
+ const functionName = codeView.functionName;
1405
+ const mjsPath = path
1406
+ .normalize(codeView.mjsFile)
1407
+ .split(path.sep)
1408
+ .filter((part) => part !== "features")
1409
+ .join(path.sep);
1410
+ const codePath = path.join(tempFolderPath, mjsPath);
1411
+ if (!existsSync(codePath)) {
1412
+ throw new Error("Step code file not found: " + codePath);
1413
+ }
1414
+ const codePage = getCodePage(codePath);
1415
+ const elements = codePage.getVariableDeclarationAsObject("elements");
1416
+ const cucumberStep = getCucumberStep({ step: scenario.step });
1417
+ cucumberStep.text = scenario.step.text;
1418
+ const stepCommands = scenario.step.commands;
1419
+ const cmd = _toRecordingStep(scenario.step.commands[0], scenario.step.name);
1420
+ const recording = new Recording();
1421
+ recording.loadFromObject({ steps: stepCommands, step: cucumberStep });
1422
+ const step = { ...(recording.steps[0] ?? {}), ...(cmd ?? {}) };
1423
+ const result = _generateCodeFromCommand(step, elements, {});
1424
+ codePage.insertElements(result.elements);
1425
+ codePage._injectOneCommand(functionName, result.codeLines.join("\n"));
1426
+ codePage.save();
1427
+ await rm(tempFolderPath, { recursive: true, force: true });
1428
+ return { code: codePage.fileContent, newStep: false, mjsFile: codeView.mjsFile };
2371
1429
  }
2372
- } catch (error) {
2373
- console.warn("Clipboard bridge could not insert text via Range APIs", error);
2374
- }
2375
- }
2376
-
2377
- if (clipboardPayload?.text && target && "value" in target) {
2378
- try {
2379
- const input = target;
2380
- const start = input.selectionStart ?? input.value.length ?? 0;
2381
- const end = input.selectionEnd ?? input.value.length ?? 0;
2382
- const value = input.value ?? "";
2383
- const text = clipboardPayload.text;
2384
- input.value = `${value.slice(0, start)}${text}${value.slice(end)}`;
2385
- const caret = start + text.length;
2386
- if (typeof input.setSelectionRange === "function") {
2387
- input.setSelectionRange(caret, caret);
1430
+ console.log("Step code not found for step: ", scenario.step.text);
1431
+ codeView = AICode[0];
1432
+ const functionName = toMethodName(scenario.step.text);
1433
+ const codeLines = [];
1434
+ const mjsPath = path
1435
+ .normalize(codeView.mjsFile)
1436
+ .split(path.sep)
1437
+ .filter((part) => part !== "features")
1438
+ .join(path.sep);
1439
+ const codePath = path.join(tempFolderPath, mjsPath);
1440
+ if (!existsSync(codePath)) {
1441
+ throw new Error("Step code file not found: " + codePath);
2388
1442
  }
2389
- input.dispatchEvent(new Event("input", { bubbles: true }));
2390
- } catch (error) {
2391
- console.warn("Clipboard bridge failed to mutate input element", error);
2392
- }
2393
- }
2394
- }, payload);
2395
- } catch (error) {
2396
- throw error;
2397
- }
2398
- }
2399
-
2400
- async createTab(url) {
2401
- try {
2402
- await this.browserEmitter?.createTab(url);
2403
- } catch (error) {
2404
- this.logger.error("Error creating tab:", error);
2405
- this.sendEvent(this.events.browserStateError, {
2406
- message: "Error creating tab",
2407
- code: "CREATE_TAB_ERROR",
2408
- });
2409
- }
2410
- }
2411
-
2412
- async closeTab(pageId) {
2413
- try {
2414
- await this.browserEmitter?.closeTab(pageId);
2415
- } catch (error) {
2416
- this.logger.error("Error closing tab:", error);
2417
- this.sendEvent(this.events.browserStateError, {
2418
- message: "Error closing tab",
2419
- code: "CLOSE_TAB_ERROR",
2420
- });
2421
- }
2422
- }
2423
-
2424
- async selectTab(pageId) {
2425
- try {
2426
- await this.browserEmitter?.selectTab(pageId);
2427
- } catch (error) {
2428
- this.logger.error("Error selecting tab:", error);
2429
- this.sendEvent(this.events.browserStateError, {
2430
- message: "Error selecting tab",
2431
- code: "SELECT_TAB_ERROR",
2432
- });
2433
- }
2434
- }
2435
-
2436
- async navigateTab({ pageId, url }) {
2437
- try {
2438
- if (!pageId || !url) {
2439
- this.logger.error("navigateTab called without pageId or url", { pageId, url });
2440
- return;
2441
- }
2442
- await this.browserEmitter?.navigateTab(pageId, url);
2443
- } catch (error) {
2444
- this.logger.error("Error navigating tab:", error);
2445
- this.sendEvent(this.events.browserStateError, {
2446
- message: "Error navigating tab",
2447
- code: "NAVIGATE_TAB_ERROR",
2448
- });
2449
- }
2450
- }
2451
-
2452
- async reloadTab(pageId) {
2453
- try {
2454
- await this.browserEmitter?.reloadTab(pageId);
2455
- } catch (error) {
2456
- this.logger.error("Error reloading tab:", error);
2457
- this.sendEvent(this.events.browserStateError, {
2458
- message: "Error reloading tab",
2459
- code: "RELOAD_TAB_ERROR",
2460
- });
2461
- }
2462
- }
2463
-
2464
- async goBack(pageId) {
2465
- try {
2466
- await this.browserEmitter?.goBack(pageId);
2467
- } catch (error) {
2468
- this.logger.error("Error navigating back:", error);
2469
- this.sendEvent(this.events.browserStateError, {
2470
- message: "Error navigating back",
2471
- code: "GO_BACK_ERROR",
2472
- });
2473
- }
2474
- }
2475
-
2476
- async goForward(pageId) {
2477
- try {
2478
- await this.browserEmitter?.goForward(pageId);
2479
- } catch (error) {
2480
- this.logger.error("Error navigating forward:", error);
2481
- this.sendEvent(this.events.browserStateError, {
2482
- message: "Error navigating forward",
2483
- code: "GO_FORWARD_ERROR",
2484
- });
2485
- }
2486
- }
1443
+ const codePage = getCodePage(codePath);
1444
+ const elements = codePage.getVariableDeclarationAsObject("elements") || {};
1445
+ let newElements = { ...elements };
1446
+ const cucumberStep = getCucumberStep({ step: scenario.step });
1447
+ cucumberStep.text = scenario.step.text;
1448
+ const stepCommands = scenario.step.commands;
1449
+ stepCommands.forEach((command) => {
1450
+ const cmd = _toRecordingStep(command, scenario.step.name);
1451
+ const recording = new Recording();
1452
+ recording.loadFromObject({ steps: stepCommands, step: cucumberStep });
1453
+ const step = { ...(recording.steps[0] ?? {}), ...(cmd ?? {}) };
1454
+ const result = _generateCodeFromCommand(step, elements, {});
1455
+ const elementUpdates = result.elements ?? {};
1456
+ newElements = { ...elementUpdates };
1457
+ codeLines.push(...(result.codeLines ?? []));
1458
+ });
1459
+ codePage.insertElements(newElements);
1460
+ codePage.addInfraCommand(functionName, cucumberStep.text, cucumberStep.getVariablesList(), codeLines, false, "recorder");
1461
+ const keyword = (cucumberStep.keywordAlias ?? cucumberStep.keyword).trim();
1462
+ codePage.addCucumberStep(keyword, cucumberStep.getTemplate(), functionName, stepCommands.length);
1463
+ codePage.save();
1464
+ await rm(tempFolderPath, { recursive: true, force: true });
1465
+ return { code: codePage.fileContent, newStep: true, functionName, mjsFile: codeView.mjsFile };
1466
+ }
1467
+ catch (error) {
1468
+ await rm(tempFolderPath, { recursive: true, force: true });
1469
+ throw error;
1470
+ }
1471
+ }
1472
+ async cleanup({ tags }) {
1473
+ const noopStep = {
1474
+ text: "Noop",
1475
+ isImplemented: true,
1476
+ };
1477
+ const projectDir = this.projectDir;
1478
+ console.log("Cleaning up project dir:", projectDir);
1479
+ try {
1480
+ // run a dummy scenario that will run after hooks
1481
+ await this.runStep({
1482
+ step: noopStep,
1483
+ parametersMap: {},
1484
+ tags: tags || [],
1485
+ }, {
1486
+ skipAfter: false,
1487
+ });
1488
+ // delete the temp folders (any folder that starts with __temp_features)
1489
+ const tempFolders = readdirSync(projectDir).filter((folder) => folder.startsWith("__temp_features"));
1490
+ for (const folder of tempFolders) {
1491
+ const folderPath = path.join(projectDir, folder);
1492
+ if (existsSync(folderPath)) {
1493
+ this.logger.info(`Deleting temp folder: ${folderPath}`);
1494
+ rmSync(folderPath, { recursive: true });
1495
+ }
1496
+ }
1497
+ }
1498
+ catch (error) {
1499
+ console.error("Error in cleanup", error);
1500
+ }
1501
+ }
1502
+ async processAriaSnapshot(snapshot) {
1503
+ try {
1504
+ await this.evaluateInAllFrames(this.context, `window.__bvt_Recorder.processAriaSnapshot(${JSON.stringify(snapshot)});`);
1505
+ return true;
1506
+ }
1507
+ catch (e) {
1508
+ return false;
1509
+ }
1510
+ }
1511
+ async deselectAriaElements() {
1512
+ try {
1513
+ await this.evaluateInAllFrames(this.context, `window.__bvt_Recorder.deselectAriaElements();`);
1514
+ return true;
1515
+ }
1516
+ catch (e) {
1517
+ return false;
1518
+ }
1519
+ }
1520
+ async initExecution({ tags = [] }) {
1521
+ // run before hooks
1522
+ const noopStep = {
1523
+ text: "Noop",
1524
+ isImplemented: true,
1525
+ };
1526
+ await this.runStep({
1527
+ step: noopStep,
1528
+ parametersMap: {},
1529
+ tags,
1530
+ }, {
1531
+ skipBefore: false,
1532
+ skipAfter: true,
1533
+ });
1534
+ }
1535
+ async cleanupExecution({ tags = [] }) {
1536
+ // run after hooks
1537
+ const noopStep = {
1538
+ text: "Noop",
1539
+ isImplemented: true,
1540
+ };
1541
+ await this.runStep({
1542
+ step: noopStep,
1543
+ parametersMap: {},
1544
+ tags,
1545
+ }, {
1546
+ skipBefore: true,
1547
+ skipAfter: false,
1548
+ });
1549
+ }
1550
+ async resetExecution({ tags = [] }) {
1551
+ // run after hooks followed by before hooks
1552
+ await this.cleanupExecution({ tags });
1553
+ await this.initExecution({ tags });
1554
+ }
1555
+ parseFeatureFile(featureFilePath) {
1556
+ try {
1557
+ let id = 0;
1558
+ const uuidFn = () => (++id).toString(16);
1559
+ const builder = new AstBuilder(uuidFn);
1560
+ const matcher = new GherkinClassicTokenMatcher();
1561
+ const parser = new Parser(builder, matcher);
1562
+ const source = readFileSync(featureFilePath, "utf8");
1563
+ const gherkinDocument = parser.parse(source);
1564
+ return gherkinDocument;
1565
+ }
1566
+ catch (e) {
1567
+ this.logger.error(`Error parsing feature file: ${featureFilePath}`, { error: e });
1568
+ console.log(e);
1569
+ }
1570
+ return {};
1571
+ }
1572
+ stopRecordingNetwork(_input) {
1573
+ if (this.bvtContext) {
1574
+ this.bvtContext.STORE_DETAILED_NETWORK_DATA = false;
1575
+ }
1576
+ }
1577
+ async fakeParams(params) {
1578
+ const newFakeParams = {};
1579
+ Object.entries(params).forEach(([key, rawValue]) => {
1580
+ if (!rawValue.startsWith("{{") || !rawValue.endsWith("}}")) {
1581
+ newFakeParams[key] = rawValue;
1582
+ return;
1583
+ }
1584
+ try {
1585
+ const value = params[key].substring(2, params[key].length - 2).trim();
1586
+ const faking = value.split("(")[0].split(".");
1587
+ let argument = value.substring(value.indexOf("(") + 1, value.lastIndexOf(")"));
1588
+ argument = isNaN(Number(argument)) || argument === "" ? argument : Number(argument);
1589
+ let fakeFunc = faker;
1590
+ faking.forEach((f) => {
1591
+ //@ts-expect-error Trying to support both old and new faker versions
1592
+ fakeFunc = fakeFunc[f];
1593
+ });
1594
+ //@ts-expect-error Trying to support both old and new faker versions
1595
+ const newValue = fakeFunc(argument);
1596
+ newFakeParams[key] = newValue;
1597
+ }
1598
+ catch (error) {
1599
+ newFakeParams[key] = rawValue;
1600
+ }
1601
+ });
1602
+ return newFakeParams;
1603
+ }
2487
1604
  }