@dev-blinq/cucumber_client 1.0.1433-dev → 1.0.1433-stage

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/bin/assets/bundled_scripts/recorder.js +73 -73
  2. package/bin/assets/preload/css_gen.js +10 -10
  3. package/bin/assets/preload/toolbar.js +27 -29
  4. package/bin/assets/preload/unique_locators.js +1 -1
  5. package/bin/assets/preload/yaml.js +288 -275
  6. package/bin/assets/scripts/aria_snapshot.js +223 -220
  7. package/bin/assets/scripts/dom_attr.js +329 -329
  8. package/bin/assets/scripts/dom_parent.js +169 -174
  9. package/bin/assets/scripts/event_utils.js +94 -94
  10. package/bin/assets/scripts/pw.js +2050 -1949
  11. package/bin/assets/scripts/recorder.js +70 -45
  12. package/bin/assets/scripts/snapshot_capturer.js +147 -147
  13. package/bin/assets/scripts/unique_locators.js +170 -49
  14. package/bin/assets/scripts/yaml.js +796 -783
  15. package/bin/assets/templates/_hooks_template.txt +6 -2
  16. package/bin/assets/templates/utils_template.txt +16 -16
  17. package/bin/client/code_cleanup/find_step_definition_references.js +0 -1
  18. package/bin/client/code_gen/api_codegen.js +2 -2
  19. package/bin/client/code_gen/code_inversion.js +63 -2
  20. package/bin/client/code_gen/function_signature.js +4 -0
  21. package/bin/client/code_gen/page_reflection.js +52 -11
  22. package/bin/client/code_gen/playwright_codeget.js +28 -22
  23. package/bin/client/cucumber/feature_data.js +2 -2
  24. package/bin/client/cucumber/project_to_document.js +8 -2
  25. package/bin/client/cucumber/steps_definitions.js +19 -3
  26. package/bin/client/local_agent.js +3 -2
  27. package/bin/client/parse_feature_file.js +23 -26
  28. package/bin/client/playground/projects/env.json +2 -2
  29. package/bin/client/recorderv3/bvt_init.js +363 -0
  30. package/bin/client/recorderv3/bvt_recorder.js +1009 -47
  31. package/bin/client/recorderv3/implemented_steps.js +2 -0
  32. package/bin/client/recorderv3/index.js +3 -283
  33. package/bin/client/recorderv3/scriptTest.js +1 -1
  34. package/bin/client/recorderv3/services.js +818 -142
  35. package/bin/client/recorderv3/step_runner.js +27 -8
  36. package/bin/client/recorderv3/step_utils.js +514 -39
  37. package/bin/client/recorderv3/update_feature.js +32 -13
  38. package/bin/client/recorderv3/wbr_entry.js +61 -0
  39. package/bin/client/recording.js +1 -0
  40. package/bin/client/upload-service.js +4 -2
  41. package/bin/client/utils/socket_logger.js +1 -1
  42. package/bin/index.js +4 -1
  43. package/package.json +6 -4
@@ -2,150 +2,826 @@ import { readdirSync, readFileSync } from "fs";
2
2
  import { getRunsServiceBaseURL } from "../utils/index.js";
3
3
  import { axiosClient } from "../utils/axiosClient.js";
4
4
  import path from "path";
5
-
5
+ import { EventEmitter } from "events";
6
+ import { v4 as uuidv4 } from "uuid"; // Import uuid
6
7
  export class NamesService {
7
- constructor({ screenshotMap, TOKEN, projectDir, logger }) {
8
- this.screenshotMap = screenshotMap;
9
- this.TOKEN = TOKEN;
10
- this.projectDir = projectDir;
11
- this.logger = logger;
12
- }
13
- async generateStepName({ commands, stepsNames, parameters, map }) {
14
- let screenshot = this.screenshotMap.get(commands[commands.length - 1].inputID);
15
- if (!screenshot && commands.length > 1) {
16
- screenshot = this.screenshotMap.get(commands[commands.length - 2].inputID);
17
- }
18
-
19
- const url = `${getRunsServiceBaseURL()}/generate-step-information/generate`;
20
- const TIMEOUT = 120; // 2 minutes
21
- const { data } = await axiosClient({
22
- url,
23
- method: "POST",
24
- data: {
25
- commands,
26
- stepsNames,
27
- parameters,
28
- //screenshot,
29
- map,
30
- },
31
- headers: {
32
- Authorization: `Bearer ${this.TOKEN}`,
33
- "X-Source": "recorder",
34
- },
35
- });
36
- const actionUrl = `${getRunsServiceBaseURL()}/action/get-action?id=${data.id}`;
37
- let result = { status: 500 };
38
- for (let i = 0; i < TIMEOUT; i++) {
39
- try {
40
- const action = await axiosClient({
41
- url: actionUrl,
42
- method: "GET",
43
- headers: {
44
- Authorization: `Bearer ${this.TOKEN}`,
45
- "X-Source": "recorder",
46
- },
8
+ screenshotMap;
9
+ TOKEN;
10
+ projectDir;
11
+ logger;
12
+ constructor({ screenshotMap, TOKEN, projectDir, logger }) {
13
+ this.screenshotMap = screenshotMap;
14
+ this.TOKEN = TOKEN;
15
+ this.projectDir = projectDir;
16
+ this.logger = logger;
17
+ }
18
+ //@ts-expect-error
19
+ async generateStepName({ commands, stepsNames, parameters, map }) {
20
+ let screenshot = this.screenshotMap.get(commands[commands.length - 1].inputID);
21
+ if (!screenshot && commands.length > 1) {
22
+ screenshot = this.screenshotMap.get(commands[commands.length - 2].inputID);
23
+ }
24
+ const url = `${getRunsServiceBaseURL()}/generate-step-information/generate`;
25
+ const TIMEOUT = 120; // 2 minutes
26
+ const { data } = await axiosClient({
27
+ url,
28
+ method: "POST",
29
+ data: {
30
+ commands,
31
+ stepsNames,
32
+ parameters,
33
+ //screenshot,
34
+ map,
35
+ },
36
+ headers: {
37
+ Authorization: `Bearer ${this.TOKEN}`,
38
+ "X-Source": "recorder",
39
+ },
40
+ });
41
+ const actionUrl = `${getRunsServiceBaseURL()}/action/get-action?id=${data.id}`;
42
+ let result = { status: 500 };
43
+ for (let i = 0; i < TIMEOUT; i++) {
44
+ try {
45
+ const action = await axiosClient({
46
+ url: actionUrl,
47
+ method: "GET",
48
+ headers: {
49
+ Authorization: `Bearer ${this.TOKEN}`,
50
+ "X-Source": "recorder",
51
+ },
52
+ });
53
+ if (action.data.status) {
54
+ result = action;
55
+ break;
56
+ }
57
+ }
58
+ catch (error) {
59
+ if (i === TIMEOUT - 1) {
60
+ this.logger.error("Timeout while generating step details: ", error instanceof Error ? error : { message: JSON.stringify(error) });
61
+ console.error("Timeout while generating step details: ", error instanceof Error ? error.message : error);
62
+ }
63
+ }
64
+ await new Promise((resolve) => setTimeout(resolve, 1000));
65
+ }
66
+ if (result.status !== 200) {
67
+ return { success: false, message: "Error while generating step details" };
68
+ }
69
+ return result.data;
70
+ }
71
+ async generateScenarioAndFeatureNames(scenarioAsText) {
72
+ if (!this.projectDir) {
73
+ throw new Error("Project directory not found");
74
+ }
75
+ // read all files with .feature extension into an object {files:[{name: "", content: ""}]}
76
+ const featureFiles = readdirSync(path.join(this.projectDir, "features"));
77
+ const featureFilesContent = featureFiles
78
+ .filter((file) => file.endsWith(".feature"))
79
+ .map((file) => {
80
+ return {
81
+ name: file,
82
+ content: readFileSync(path.join(this.projectDir, "features", file), "utf8"),
83
+ };
47
84
  });
48
-
49
- if (action.data.status) {
50
- result = action;
51
- break;
52
- }
53
- } catch (error) {
54
- if (i === TIMEOUT - 1) {
55
- this.logger.error("Timeout while generating step details: ", error);
56
- console.error("Timeout while generating step details: ", error);
57
- }
58
- }
59
-
60
- await new Promise((resolve) => setTimeout(resolve, 1000));
61
- }
62
-
63
- if (result.status !== 200) {
64
- return { success: false, message: "Error while generating step details" };
65
- }
66
- return result.data;
67
- }
68
- async generateScenarioAndFeatureNames(scenarioAsText) {
69
- if (!this.projectDir) {
70
- throw new Error("Project directory not found");
71
- }
72
- // read all files with .feature extension into an object {files:[{name: "", content: ""}]}
73
- const featureFiles = readdirSync(path.join(this.projectDir, "features"));
74
- const featureFilesContent = featureFiles
75
- .filter((file) => file.endsWith(".feature"))
76
- .map((file) => {
77
- return {
78
- name: file,
79
- content: readFileSync(path.join(this.projectDir, "features", file), "utf8"),
85
+ const genObject = {
86
+ files: featureFilesContent,
87
+ scenario: scenarioAsText,
80
88
  };
81
- });
82
- const genObject = {
83
- files: featureFilesContent,
84
- scenario: scenarioAsText,
85
- };
86
-
87
- // get screenshot for the last command
88
- const url = `${getRunsServiceBaseURL()}/generate-step-information/generate_scenario_feature`;
89
- const TIMEOUT = 120; // 2 minutes
90
- const { data } = await axiosClient({
91
- url,
92
- method: "POST",
93
- data: {
94
- ...genObject,
95
- },
96
- headers: {
97
- Authorization: `Bearer ${this.TOKEN}`,
98
- "X-Source": "recorder",
99
- },
100
- });
101
- const actionUrl = `${getRunsServiceBaseURL()}/action/get-action?id=${data.id}`;
102
- let result = { status: 500 };
103
- for (let i = 0; i < TIMEOUT; i++) {
104
- try {
105
- const action = await axiosClient({
106
- url: actionUrl,
107
- method: "GET",
108
- headers: {
109
- Authorization: `Bearer ${this.TOKEN}`,
110
- "X-Source": "recorder",
111
- },
89
+ // get screenshot for the last command
90
+ const url = `${getRunsServiceBaseURL()}/generate-step-information/generate_scenario_feature`;
91
+ const TIMEOUT = 120; // 2 minutes
92
+ const { data } = await axiosClient({
93
+ url,
94
+ method: "POST",
95
+ data: {
96
+ ...genObject,
97
+ },
98
+ headers: {
99
+ Authorization: `Bearer ${this.TOKEN}`,
100
+ "X-Source": "recorder",
101
+ },
102
+ });
103
+ const actionUrl = `${getRunsServiceBaseURL()}/action/get-action?id=${data.id}`;
104
+ let result = { status: 500 };
105
+ for (let i = 0; i < TIMEOUT; i++) {
106
+ try {
107
+ const action = await axiosClient({
108
+ url: actionUrl,
109
+ method: "GET",
110
+ headers: {
111
+ Authorization: `Bearer ${this.TOKEN}`,
112
+ "X-Source": "recorder",
113
+ },
114
+ });
115
+ if (action.data.status) {
116
+ result = action;
117
+ break;
118
+ }
119
+ }
120
+ catch (error) {
121
+ if (i === TIMEOUT - 1) {
122
+ console.error("Timeout while generating step details: ", error);
123
+ }
124
+ }
125
+ await new Promise((resolve) => setTimeout(resolve, 1000));
126
+ }
127
+ if (result.status !== 200) {
128
+ return { success: false, message: "Error while generating step details" };
129
+ }
130
+ return result.data;
131
+ }
132
+ //@ts-expect-error
133
+ async generateCommandName({ command }) {
134
+ const url = `${getRunsServiceBaseURL()}/generate-step-information/generate-element-name`;
135
+ const screenshot = this.screenshotMap.get(command.inputID);
136
+ const result = await axiosClient({
137
+ url,
138
+ method: "POST",
139
+ data: { ...command, screenshot },
140
+ headers: {
141
+ Authorization: `Bearer ${this.TOKEN}`,
142
+ "X-Source": "recorder",
143
+ },
144
+ });
145
+ if (result.status !== 200) {
146
+ return { success: false, message: "Error while generating command details" };
147
+ }
148
+ return result.data;
149
+ }
150
+ }
151
+ export class PublishService {
152
+ TOKEN;
153
+ constructor(TOKEN) {
154
+ this.TOKEN = TOKEN;
155
+ }
156
+ async saveScenario({ scenario, featureName, override, branch, isEditing, projectId, env }) {
157
+ const runsURL = getRunsServiceBaseURL();
158
+ const workspaceURL = runsURL.replace("/runs", "/workspace");
159
+ const url = `${workspaceURL}/publish-recording`;
160
+ try {
161
+ const result = await axiosClient({
162
+ url,
163
+ method: "POST",
164
+ data: {
165
+ scenario,
166
+ featureName,
167
+ override,
168
+ env,
169
+ },
170
+ params: {
171
+ branch,
172
+ },
173
+ headers: {
174
+ Authorization: `Bearer ${this.TOKEN}`,
175
+ "X-Source": "recorder",
176
+ },
177
+ });
178
+ if (result.status !== 200) {
179
+ return { success: false, message: "Error while saving scenario" };
180
+ }
181
+ try {
182
+ this.updateProjectMetadata({
183
+ featureName,
184
+ scenarioName: scenario.name,
185
+ projectId,
186
+ branch,
187
+ isEditing: override,
188
+ });
189
+ }
190
+ catch (error) { }
191
+ return { success: true, data: result.data };
192
+ }
193
+ catch (error) {
194
+ // @ts-ignore
195
+ const reason = error?.response?.data?.error || "";
196
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
197
+ throw new Error(`Failed to save scenario: ${errorMessage} \n ${reason}`);
198
+ }
199
+ }
200
+ async updateProjectMetadata({ featureName, scenarioName, projectId, branch, isEditing }) {
201
+ try {
202
+ await axiosClient({
203
+ method: "POST",
204
+ url: `${getRunsServiceBaseURL()}/project/updateProjectMetadata`,
205
+ data: {
206
+ featureName,
207
+ scenarioName,
208
+ eventType: isEditing ? "editScenario" : "createScenario",
209
+ projectId,
210
+ branch: branch,
211
+ },
212
+ headers: {
213
+ Authorization: `Bearer ${this.TOKEN}`,
214
+ "X-Source": "recorder",
215
+ },
216
+ });
217
+ }
218
+ catch (error) {
219
+ // logger.error("Failed to update project metadata: " + error.message);
220
+ // @ts-ignore
221
+ console.error("run_recorder", `Failed to update project metadata: ${error.message ?? error}`);
222
+ }
223
+ }
224
+ }
225
+ export class RemoteBrowserService extends EventEmitter {
226
+ CDP_CONNECT_URL;
227
+ context;
228
+ pages = new Map();
229
+ _selectedPageId = null;
230
+ wsUrlBase; // Store the base URL
231
+ hasClipboardData(payload) {
232
+ return Boolean(payload && (payload.text || payload.html || (Array.isArray(payload.files) && payload.files.length > 0)));
233
+ }
234
+ getSelectedPageInfo() {
235
+ if (!this._selectedPageId) {
236
+ return null;
237
+ }
238
+ return this.pages.get(this._selectedPageId) ?? null;
239
+ }
240
+ constructor({ CDP_CONNECT_URL, context }) {
241
+ super();
242
+ this.CDP_CONNECT_URL = CDP_CONNECT_URL;
243
+ this.context = context;
244
+ this.wsUrlBase = this.CDP_CONNECT_URL.replace(/^http/, "ws") + "/devtools/page/";
245
+ this.log("🚀 RemoteBrowserService initialized", { CDP_CONNECT_URL });
246
+ this.context.grantPermissions(["clipboard-read", "clipboard-write"]).catch((error) => {
247
+ this.log("âš ī¸ Failed to pre-grant clipboard permissions", { error });
248
+ });
249
+ this.initializeListeners();
250
+ }
251
+ log(message, data) {
252
+ const timestamp = new Date().toISOString();
253
+ console.log(`[${timestamp}] [RemoteBrowserService] ${message}`, data ? JSON.stringify(data, null, 2) : "");
254
+ }
255
+ isTransientPageDataError(error) {
256
+ const message = error instanceof Error ? error.message : typeof error === "string" ? error : undefined;
257
+ if (!message) {
258
+ return false;
259
+ }
260
+ const transientIndicators = [
261
+ "Execution context was destroyed",
262
+ "Execution context is not available",
263
+ "Cannot find context with specified id",
264
+ "Target closed",
265
+ "Navigation interrupted",
266
+ ];
267
+ return transientIndicators.some((indicator) => message.includes(indicator));
268
+ }
269
+ /**
270
+ * Gets the CDP Target ID for a page *directly* from the page.
271
+ * This is the only reliable method during restarts.
272
+ */
273
+ async getCdpTargetId(page) {
274
+ try {
275
+ if (page.isClosed()) {
276
+ this.log("âš ī¸ Attempted to get CDP ID from a closed page");
277
+ return null;
278
+ }
279
+ const cdpSession = await page.context().newCDPSession(page);
280
+ const { targetInfo } = await cdpSession.send("Target.getTargetInfo");
281
+ this.log("🔍 Retrieved TargetInfo via CDP session", targetInfo);
282
+ await cdpSession.detach();
283
+ if (targetInfo && targetInfo.targetId) {
284
+ this.log("✅ Found CDP ID by session", { id: targetInfo.targetId, url: page.url() });
285
+ return targetInfo.targetId;
286
+ }
287
+ throw new Error("Target.getTargetInfo did not return a targetId");
288
+ }
289
+ catch (error) {
290
+ this.log("❌ Error getting CDP ID by session", { url: page.url(), error });
291
+ return null;
292
+ }
293
+ }
294
+ async initializeListeners() {
295
+ this.log("📡 Initializing listeners");
296
+ // Initialize with existing pages
297
+ const existingPages = this.context.pages();
298
+ this.log("📄 Found existing pages", { count: existingPages.length });
299
+ for (const page of existingPages) {
300
+ const stableTabId = uuidv4();
301
+ const cdpTargetId = await this.getCdpTargetId(page);
302
+ this.pages.set(stableTabId, {
303
+ page,
304
+ cdpTargetId,
305
+ lastKnownTitle: undefined,
306
+ lastKnownUrl: page.url(),
307
+ lastKnownWsDebuggerUrl: cdpTargetId ? `${this.wsUrlBase}${cdpTargetId}` : undefined,
308
+ });
309
+ page.on("framenavigated", async () => {
310
+ try {
311
+ await this.ensureClipboardScriptLoaded(page);
312
+ }
313
+ catch (err) {
314
+ this.log("❌ Error injecting clipboard script on navigation", { stableTabId, error: err });
315
+ }
316
+ });
317
+ // this.log("✅ Existing page added to map", { stableTabId, cdpTargetId, url: page.url() });
318
+ // this.attachPageLifecycleListeners(page, stableTabId);
319
+ // this.log("🔍 Attached lifecycle listeners to existing page", { stableTabId });
320
+ }
321
+ // if (this.pages.size > 0 && !this._selectedPageId) {
322
+ // this._selectedPageId = Array.from(this.pages.keys())[0];
323
+ // }
324
+ // await this.syncState();
325
+ this.context.on("page", async (page) => {
326
+ // const stableTabId = uuidv4();
327
+ // this.log("🆕 New page event triggered", { stableTabId, url: page.url() });
328
+ // // We get the ID immediately, but it might be null if the page is too new
329
+ // const cdpTargetId = await this.getCdpTargetId(page);
330
+ // this.pages.set(stableTabId, {
331
+ // page,
332
+ // cdpTargetId,
333
+ // lastKnownTitle: undefined,
334
+ // lastKnownUrl: page.url(),
335
+ // lastKnownWsDebuggerUrl: cdpTargetId ? `${this.wsUrlBase}${cdpTargetId}` : undefined,
336
+ // });
337
+ // if (cdpTargetId) {
338
+ // this.log("✅ Page mapped to CDP ID", { stableTabId, cdpTargetId });
339
+ // } else {
340
+ // this.log("âš ī¸ Could not find CDP ID for new page yet", { stableTabId });
341
+ // }
342
+ // if (!this._selectedPageId) {
343
+ // // Select the first page that opens
344
+ // this._selectedPageId = stableTabId;
345
+ // this.log("đŸŽ¯ Initial selected page set", { selectedPageId: this._selectedPageId });
346
+ // }
347
+ // this.attachPageLifecycleListeners(page, stableTabId);
348
+ // await this.syncState();
349
+ await this.ensureClipboardScriptLoaded(page);
350
+ });
351
+ }
352
+ // private attachPageLifecycleListeners(page: Page, stableTabId: string) {
353
+ // page.on("load", () => this.syncState());
354
+ // page.on("framenavigated", () => this.syncState());
355
+ // page.on("close", async () => {
356
+ // this.log("đŸ—‘ī¸ Page close event", { stableTabId });
357
+ // this.pages.delete(stableTabId);
358
+ // if (this._selectedPageId === stableTabId) {
359
+ // this._selectedPageId = this.pages.size > 0 ? Array.from(this.pages.keys())[0] : null;
360
+ // this.log("🔄 Selected page changed after close", { newSelectedId: this._selectedPageId });
361
+ // }
362
+ // await this.syncState();
363
+ // });
364
+ // }
365
+ // private async syncState() {
366
+ // try {
367
+ // this.log("🔄 Starting state sync");
368
+ // const state = await this.getState();
369
+ // this.log("✅ State sync complete", { pagesCount: state.pages.length, selectedPageId: state.selectedPageId });
370
+ // this.emit("BrowserService.stateSync", state);
371
+ // } catch (error) {
372
+ // this.log("❌ Error syncing state", { error });
373
+ // }
374
+ // }
375
+ // async getState(): Promise<BrowserState> {
376
+ // this.log("📊 Getting current state");
377
+ // const pagesData: PageData[] = [];
378
+ // const pagesToDelete: string[] = []; // To clean up closed pages
379
+ // for (const [stableTabId, pageInfo] of this.pages.entries()) {
380
+ // const pageData: PageData = {
381
+ // id: stableTabId,
382
+ // title: pageInfo.lastKnownTitle ?? "",
383
+ // url: pageInfo.lastKnownUrl ?? pageInfo.page.url(),
384
+ // wsDebuggerUrl: pageInfo.lastKnownWsDebuggerUrl ?? "",
385
+ // };
386
+ // try {
387
+ // if (pageInfo.page.isClosed()) {
388
+ // this.log("🧹 Found closed page during getState, marking for deletion", { stableTabId });
389
+ // pagesToDelete.push(stableTabId);
390
+ // continue;
391
+ // }
392
+ // // Get the one, true, live CDP ID
393
+ // const currentCdpId = await this.getCdpTargetId(pageInfo.page);
394
+ // if (currentCdpId && pageInfo.cdpTargetId !== currentCdpId) {
395
+ // this.log("🔄 CDP ID changed", { stableTabId, old: pageInfo.cdpTargetId, new: currentCdpId });
396
+ // pageInfo.cdpTargetId = currentCdpId; // Update our internal reference
397
+ // }
398
+ // // Manually construct the WebSocket URL
399
+ // const wsDebuggerUrl = currentCdpId
400
+ // ? `${this.wsUrlBase}${currentCdpId}`
401
+ // : (pageInfo.lastKnownWsDebuggerUrl ?? "");
402
+ // if (!wsDebuggerUrl) {
403
+ // this.log("âš ī¸ Could not get CDP ID, wsDebuggerUrl will be empty", { stableTabId });
404
+ // }
405
+ // const title = await pageInfo.page.title();
406
+ // const currentUrl = pageInfo.page.url();
407
+ // pageData.title = title;
408
+ // pageData.url = currentUrl;
409
+ // pageData.wsDebuggerUrl = wsDebuggerUrl; // Use the constructed URL
410
+ // pageInfo.lastKnownTitle = title;
411
+ // pageInfo.lastKnownUrl = currentUrl;
412
+ // pageInfo.lastKnownWsDebuggerUrl = wsDebuggerUrl;
413
+ // this.log("đŸŸĨPage data", pageData);
414
+ // } catch (error) {
415
+ // const message = error instanceof Error ? error.message : JSON.stringify(error);
416
+ // if (this.isTransientPageDataError(error)) {
417
+ // this.log("âŗ Transient error getting page data, will retry", { stableTabId, message });
418
+ // } else {
419
+ // this.log("❌ Error getting page data", { stableTabId, message });
420
+ // pagesToDelete.push(stableTabId); // Mark for deletion
421
+ // continue;
422
+ // }
423
+ // }
424
+ // if (!pageData.title) {
425
+ // pageData.title = pageInfo.page.url() === "about:blank" ? "" : "Loading...";
426
+ // }
427
+ // pagesData.push(pageData);
428
+ // }
429
+ // pagesToDelete.forEach((id) => this.pages.delete(id));
430
+ // if (this._selectedPageId && !this.pages.has(this._selectedPageId)) {
431
+ // this._selectedPageId = pagesData.length > 0 ? pagesData[0].id : null;
432
+ // this.log("🔄 Corrected selectedPageId", { new: this._selectedPageId });
433
+ // }
434
+ // if (!this._selectedPageId && pagesData.length > 0) {
435
+ // this._selectedPageId = pagesData[0].id;
436
+ // this.log("đŸŽ¯ Set default selectedPageId", { new: this._selectedPageId });
437
+ // }
438
+ // const state = {
439
+ // pages: pagesData,
440
+ // selectedPageId: this._selectedPageId,
441
+ // };
442
+ // this.log("đŸ“Ļ Final state", state);
443
+ // return state;
444
+ // }
445
+ // async createTab(url: string = "about:blank"): Promise<void> {
446
+ // try {
447
+ // this.log("🆕 Creating new tab", { url });
448
+ // const page = await this.context.newPage(); // This will trigger the 'page' event
449
+ // if (url !== "about:blank") {
450
+ // await page.goto(url, { waitUntil: "domcontentloaded" });
451
+ // }
452
+ // for (const [stableTabId, pageInfo] of this.pages.entries()) {
453
+ // if (pageInfo.page === page) {
454
+ // this._selectedPageId = stableTabId;
455
+ // this.log("✅ New tab created and selected", { stableTabId, url });
456
+ // break;
457
+ // }
458
+ // }
459
+ // await this.syncState();
460
+ // } catch (error) {
461
+ // this.log("❌ Error creating tab", { error });
462
+ // }
463
+ // }
464
+ // async closeTab(stableTabId: string): Promise<void> {
465
+ // try {
466
+ // this.log("đŸ—‘ī¸ Closing tab", { stableTabId });
467
+ // const pageInfo = this.pages.get(stableTabId);
468
+ // if (pageInfo) {
469
+ // await pageInfo.page.close(); // This will trigger the 'close' event
470
+ // } else {
471
+ // this.log("âš ī¸ Page not found for closing", { stableTabId });
472
+ // }
473
+ // } catch (error) {
474
+ // this.log("❌ Error closing tab", { error });
475
+ // }
476
+ // }
477
+ // async selectTab(stableTabId: string): Promise<void> {
478
+ // try {
479
+ // this.log("đŸŽ¯ Selecting tab", { stableTabId });
480
+ // const pageInfo = this.pages.get(stableTabId);
481
+ // if (pageInfo) {
482
+ // this._selectedPageId = stableTabId;
483
+ // await pageInfo.page.bringToFront();
484
+ // this.log("✅ Tab selected successfully", { stableTabId });
485
+ // await this.syncState();
486
+ // } else {
487
+ // this.log("âš ī¸ Page not found for selection", { stableTabId });
488
+ // }
489
+ // } catch (error) {
490
+ // this.log("❌ Error selecting tab", { error });
491
+ // }
492
+ // }
493
+ getPageInfo(stableTabId) {
494
+ if (!stableTabId) {
495
+ this.log("âš ī¸ Operation requested without a selected tab");
496
+ return null;
497
+ }
498
+ const pageInfo = this.pages.get(stableTabId);
499
+ if (!pageInfo) {
500
+ this.log("âš ī¸ Page not found for operation", { stableTabId });
501
+ return null;
502
+ }
503
+ return pageInfo;
504
+ }
505
+ // async navigateTab(stableTabId: string, url: string): Promise<void> {
506
+ // const pageInfo = this.getPageInfo(stableTabId);
507
+ // if (!pageInfo) {
508
+ // return;
509
+ // }
510
+ // try {
511
+ // this.log("🌐 Navigating tab", { stableTabId, url });
512
+ // await pageInfo.page.goto(url, { waitUntil: "domcontentloaded" });
513
+ // this._selectedPageId = stableTabId;
514
+ // await this.syncState();
515
+ // } catch (error) {
516
+ // this.log("❌ Error navigating tab", { stableTabId, url, error });
517
+ // throw error;
518
+ // }
519
+ // }
520
+ // async reloadTab(stableTabId: string): Promise<void> {
521
+ // const pageInfo = this.getPageInfo(stableTabId);
522
+ // if (!pageInfo) {
523
+ // return;
524
+ // }
525
+ // try {
526
+ // this.log("🔄 Reloading tab", { stableTabId, url: pageInfo.page.url() });
527
+ // await pageInfo.page.reload({ waitUntil: "domcontentloaded" });
528
+ // await this.syncState();
529
+ // } catch (error) {
530
+ // this.log("❌ Error reloading tab", { stableTabId, error });
531
+ // throw error;
532
+ // }
533
+ // }
534
+ // async goBack(stableTabId: string): Promise<void> {
535
+ // const pageInfo = this.getPageInfo(stableTabId);
536
+ // if (!pageInfo) {
537
+ // return;
538
+ // }
539
+ // try {
540
+ // this.log("âŦ…ī¸ Navigating back", { stableTabId });
541
+ // const response = await pageInfo.page.goBack({ waitUntil: "domcontentloaded" });
542
+ // if (!response) {
543
+ // this.log("â„šī¸ No history entry to go back to", { stableTabId });
544
+ // }
545
+ // await this.syncState();
546
+ // } catch (error) {
547
+ // this.log("❌ Error navigating back", { stableTabId, error });
548
+ // throw error;
549
+ // }
550
+ // }
551
+ // async goForward(stableTabId: string): Promise<void> {
552
+ // const pageInfo = this.getPageInfo(stableTabId);
553
+ // if (!pageInfo) {
554
+ // return;
555
+ // }
556
+ // try {
557
+ // this.log("âžĄī¸ Navigating forward", { stableTabId });
558
+ // const response = await pageInfo.page.goForward({ waitUntil: "domcontentloaded" });
559
+ // if (!response) {
560
+ // this.log("â„šī¸ No history entry to go forward to", { stableTabId });
561
+ // }
562
+ // await this.syncState();
563
+ // } catch (error) {
564
+ // this.log("❌ Error navigating forward", { stableTabId, error });
565
+ // throw error;
566
+ // }
567
+ // }
568
+ async applyClipboardPayload(payload) {
569
+ this.log("📋 applyClipboardPayload called", {
570
+ hasText: !!payload?.text,
571
+ hasHtml: !!payload?.html,
572
+ hasFiles: !!payload?.files,
573
+ textLength: payload?.text?.length,
574
+ htmlLength: payload?.html?.length,
575
+ filesCount: payload?.files?.length,
576
+ });
577
+ const pageInfo = this.getPageInfo(this._selectedPageId);
578
+ if (!pageInfo) {
579
+ this.log("âš ī¸ No active page available for clipboard payload", {
580
+ selectedPageId: this._selectedPageId,
581
+ totalPages: this.pages.size,
582
+ });
583
+ return;
584
+ }
585
+ this.log("📄 Target page info", {
586
+ stableTabId: this._selectedPageId,
587
+ url: pageInfo.page.url(),
588
+ isClosed: pageInfo.page.isClosed(),
589
+ title: await pageInfo.page.title().catch(() => "unknown"),
590
+ });
591
+ try {
592
+ // Grant permissions first
593
+ this.log("🔐 Attempting to grant clipboard permissions");
594
+ await pageInfo.page
595
+ .context()
596
+ .grantPermissions(["clipboard-read", "clipboard-write"])
597
+ .then(() => {
598
+ this.log("✅ Clipboard permissions granted");
599
+ })
600
+ .catch((error) => {
601
+ this.log("âš ī¸ Failed to grant clipboard permissions", { error: error.message });
602
+ });
603
+ // Apply the clipboard data using the injected function
604
+ this.log("🚀 Executing clipboard application script", {
605
+ payloadPreview: {
606
+ text: payload?.text?.substring(0, 100),
607
+ html: payload?.html?.substring(0, 100),
608
+ },
609
+ });
610
+ const result = await pageInfo.page.evaluate((clipboardData) => {
611
+ console.log("[RemoteBrowser->Page] Starting clipboard application");
612
+ console.log("[RemoteBrowser->Page] Payload:", {
613
+ hasText: !!clipboardData?.text,
614
+ hasHtml: !!clipboardData?.html,
615
+ text: clipboardData?.text?.substring(0, 50),
616
+ html: clipboardData?.html?.substring(0, 50),
617
+ });
618
+ // Check if the function exists
619
+ if (typeof window.__bvt_applyClipboardData !== "function") {
620
+ console.error("[RemoteBrowser->Page] ❌ __bvt_applyClipboardData function not found!");
621
+ console.log("[RemoteBrowser->Page] Available window properties:", Object.keys(window).filter((k) => k.includes("bvt")));
622
+ return false;
623
+ }
624
+ console.log("[RemoteBrowser->Page] ✅ __bvt_applyClipboardData function found, calling it");
625
+ try {
626
+ const result = window.__bvt_applyClipboardData(clipboardData);
627
+ console.log("[RemoteBrowser->Page] Function returned:", result);
628
+ return result;
629
+ }
630
+ catch (error) {
631
+ console.error("[RemoteBrowser->Page] ❌ Error calling __bvt_applyClipboardData:", error);
632
+ return false;
633
+ }
634
+ }, payload);
635
+ this.log("📊 Clipboard application result", {
636
+ success: result,
637
+ selectedPageId: this._selectedPageId,
638
+ });
639
+ if (!result) {
640
+ this.log("âš ī¸ Clipboard script returned false - data may not have been applied");
641
+ }
642
+ else {
643
+ this.log("✅ Clipboard payload applied successfully");
644
+ }
645
+ }
646
+ catch (error) {
647
+ this.log("❌ Error applying clipboard payload", {
648
+ error: error instanceof Error ? error.message : String(error),
649
+ stack: error instanceof Error ? error.stack : undefined,
650
+ selectedPageId: this._selectedPageId,
651
+ pageUrl: pageInfo.page.url(),
652
+ });
653
+ throw error;
654
+ }
655
+ }
656
+ async readClipboardPayload() {
657
+ const pageInfo = this.getSelectedPageInfo();
658
+ if (!pageInfo) {
659
+ this.log("âš ī¸ Cannot read clipboard - no active page", { selectedPageId: this._selectedPageId });
660
+ return null;
661
+ }
662
+ try {
663
+ await pageInfo.page
664
+ .context()
665
+ .grantPermissions(["clipboard-read", "clipboard-write"])
666
+ .catch((error) => {
667
+ this.log("âš ī¸ Failed to ensure clipboard permissions before read", { error });
668
+ });
669
+ const payload = await pageInfo.page.evaluate(async () => {
670
+ const result = {};
671
+ if (typeof navigator === "undefined" || !navigator.clipboard) {
672
+ return result;
673
+ }
674
+ const arrayBufferToBase64 = (buffer) => {
675
+ let binary = "";
676
+ const bytes = new Uint8Array(buffer);
677
+ const chunkSize = 0x8000;
678
+ for (let index = 0; index < bytes.length; index += chunkSize) {
679
+ const chunk = bytes.subarray(index, index + chunkSize);
680
+ binary += String.fromCharCode(...chunk);
681
+ }
682
+ return btoa(binary);
683
+ };
684
+ const files = [];
685
+ if (typeof navigator.clipboard.read === "function") {
686
+ try {
687
+ const items = await navigator.clipboard.read();
688
+ for (const item of items) {
689
+ if (item.types.includes("text/html") && !result.html) {
690
+ const blob = await item.getType("text/html");
691
+ result.html = await blob.text();
692
+ }
693
+ if (item.types.includes("text/plain") && !result.text) {
694
+ const blob = await item.getType("text/plain");
695
+ result.text = await blob.text();
696
+ }
697
+ for (const type of item.types) {
698
+ if (type.startsWith("text/")) {
699
+ continue;
700
+ }
701
+ try {
702
+ const blob = await item.getType(type);
703
+ const buffer = await blob.arrayBuffer();
704
+ files.push({
705
+ name: `clipboard-file-${files.length + 1}`,
706
+ type,
707
+ lastModified: Date.now(),
708
+ data: arrayBufferToBase64(buffer),
709
+ });
710
+ }
711
+ catch (error) {
712
+ console.warn("[RemoteClipboard] Failed to serialize clipboard blob", { type, error });
713
+ }
714
+ }
715
+ }
716
+ }
717
+ catch (error) {
718
+ console.warn("[RemoteClipboard] navigator.clipboard.read failed", error);
719
+ }
720
+ }
721
+ if (!result.text && typeof navigator.clipboard.readText === "function") {
722
+ try {
723
+ const text = await navigator.clipboard.readText();
724
+ if (text) {
725
+ result.text = text;
726
+ }
727
+ }
728
+ catch (error) {
729
+ console.warn("[RemoteClipboard] navigator.clipboard.readText failed", error);
730
+ }
731
+ }
732
+ if (!result.text) {
733
+ const selection = window.getSelection?.()?.toString?.();
734
+ if (selection) {
735
+ result.text = selection;
736
+ }
737
+ }
738
+ if (files.length > 0) {
739
+ result.files = files;
740
+ }
741
+ return result;
742
+ });
743
+ if (this.hasClipboardData(payload)) {
744
+ this.log("📋 Remote clipboard payload captured", {
745
+ hasText: !!payload.text,
746
+ hasHtml: !!payload.html,
747
+ fileCount: payload.files?.length ?? 0,
748
+ });
749
+ return payload;
750
+ }
751
+ this.log("â„šī¸ Remote clipboard read returned empty payload", {
752
+ selectedPageId: this._selectedPageId,
753
+ });
754
+ return null;
755
+ }
756
+ catch (error) {
757
+ this.log("❌ Error reading remote clipboard", {
758
+ error: error instanceof Error ? error.message : String(error),
759
+ });
760
+ throw error;
761
+ }
762
+ }
763
+ // Add a helper method to verify clipboard script is loaded
764
+ async verifyClipboardScript(stableTabId) {
765
+ const pageInfo = this.pages.get(stableTabId);
766
+ if (!pageInfo) {
767
+ this.log("âš ī¸ Cannot verify clipboard script - page not found", { stableTabId });
768
+ return false;
769
+ }
770
+ try {
771
+ const isLoaded = await pageInfo.page.evaluate(() => {
772
+ return (typeof window.__bvt_applyClipboardData === "function" && typeof window.__bvt_reportClipboard === "function");
773
+ });
774
+ this.log("🔍 Clipboard script verification", {
775
+ stableTabId,
776
+ isLoaded,
777
+ url: pageInfo.page.url(),
778
+ });
779
+ return isLoaded;
780
+ }
781
+ catch (error) {
782
+ this.log("❌ Error verifying clipboard script", {
783
+ stableTabId,
784
+ error: error instanceof Error ? error.message : String(error),
785
+ });
786
+ return false;
787
+ }
788
+ }
789
+ // Call this after navigation to ensure script is loaded
790
+ async ensureClipboardScriptLoaded(page) {
791
+ try {
792
+ const isLoaded = await page.evaluate(() => {
793
+ return typeof window.__bvt_applyClipboardData === "function";
794
+ });
795
+ if (!isLoaded) {
796
+ this.log("âš ī¸ Clipboard script not loaded, attempting to reload");
797
+ // The script should be in initScripts, so it will load on next navigation
798
+ // or you could manually inject it here
799
+ }
800
+ else {
801
+ this.log("✅ Clipboard script confirmed loaded");
802
+ }
803
+ }
804
+ catch (error) {
805
+ this.log("❌ Error checking clipboard script", { error });
806
+ }
807
+ }
808
+ getSelectedPage() {
809
+ const pageInfo = this.getSelectedPageInfo();
810
+ this.log("🔍 Getting selected page", {
811
+ selectedPageId: this._selectedPageId,
812
+ found: !!pageInfo,
813
+ url: pageInfo?.page.url(),
112
814
  });
113
-
114
- if (action.data.status) {
115
- result = action;
116
- break;
117
- }
118
- } catch (error) {
119
- if (i === TIMEOUT - 1) {
120
- console.error("Timeout while generating step details: ", error);
121
- }
122
- }
123
-
124
- await new Promise((resolve) => setTimeout(resolve, 1000));
125
- }
126
-
127
- if (result.status !== 200) {
128
- return { success: false, message: "Error while generating step details" };
129
- }
130
-
131
- return result.data;
132
- }
133
-
134
- async generateCommandName({ command }) {
135
- const url = `${getRunsServiceBaseURL()}/generate-step-information/generate-element-name`;
136
- const screenshot = this.screenshotMap.get(command.inputID);
137
- const result = await axiosClient({
138
- url,
139
- method: "POST",
140
- data: { ...command, screenshot },
141
- headers: {
142
- Authorization: `Bearer ${this.TOKEN}`,
143
- "X-Source": "recorder",
144
- },
145
- });
146
- if (result.status !== 200) {
147
- return { success: false, message: "Error while generating command details" };
148
- }
149
- return result.data;
150
- }
815
+ return pageInfo?.page || null;
816
+ }
817
+ destroy() {
818
+ this.log("đŸ’Ĩ Destroying RemoteBrowserService");
819
+ this.context.removeAllListeners("page");
820
+ for (const [, pageInfo] of this.pages.entries()) {
821
+ pageInfo.page.removeAllListeners(); // Remove all listeners from each page
822
+ }
823
+ this.pages.clear();
824
+ this._selectedPageId = null;
825
+ this.removeAllListeners(); // Remove listeners on the emitter itself
826
+ }
151
827
  }