@flrande/browserctl 0.1.0

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 (90) hide show
  1. package/LICENSE +21 -0
  2. package/README-CN.md +1155 -0
  3. package/README.md +1155 -0
  4. package/apps/browserctl/src/commands/a11y-snapshot.ts +20 -0
  5. package/apps/browserctl/src/commands/act.ts +20 -0
  6. package/apps/browserctl/src/commands/common.test.ts +87 -0
  7. package/apps/browserctl/src/commands/common.ts +191 -0
  8. package/apps/browserctl/src/commands/console-list.ts +20 -0
  9. package/apps/browserctl/src/commands/cookie-clear.ts +18 -0
  10. package/apps/browserctl/src/commands/cookie-get.ts +18 -0
  11. package/apps/browserctl/src/commands/cookie-set.ts +22 -0
  12. package/apps/browserctl/src/commands/dialog-arm.ts +20 -0
  13. package/apps/browserctl/src/commands/dom-query-all.ts +18 -0
  14. package/apps/browserctl/src/commands/dom-query.ts +18 -0
  15. package/apps/browserctl/src/commands/download-trigger.ts +22 -0
  16. package/apps/browserctl/src/commands/download-wait.test.ts +67 -0
  17. package/apps/browserctl/src/commands/download-wait.ts +27 -0
  18. package/apps/browserctl/src/commands/element-screenshot.ts +20 -0
  19. package/apps/browserctl/src/commands/frame-list.ts +16 -0
  20. package/apps/browserctl/src/commands/frame-snapshot.ts +18 -0
  21. package/apps/browserctl/src/commands/network-wait-for.ts +100 -0
  22. package/apps/browserctl/src/commands/profile-list.ts +16 -0
  23. package/apps/browserctl/src/commands/profile-use.ts +18 -0
  24. package/apps/browserctl/src/commands/response-body.ts +24 -0
  25. package/apps/browserctl/src/commands/screenshot.ts +16 -0
  26. package/apps/browserctl/src/commands/snapshot.ts +16 -0
  27. package/apps/browserctl/src/commands/status.ts +10 -0
  28. package/apps/browserctl/src/commands/storage-get.ts +20 -0
  29. package/apps/browserctl/src/commands/storage-set.ts +22 -0
  30. package/apps/browserctl/src/commands/tab-close.ts +20 -0
  31. package/apps/browserctl/src/commands/tab-focus.ts +20 -0
  32. package/apps/browserctl/src/commands/tab-open.ts +19 -0
  33. package/apps/browserctl/src/commands/tabs.ts +13 -0
  34. package/apps/browserctl/src/commands/upload-arm.ts +26 -0
  35. package/apps/browserctl/src/daemon-client.test.ts +253 -0
  36. package/apps/browserctl/src/daemon-client.ts +632 -0
  37. package/apps/browserctl/src/e2e.test.ts +99 -0
  38. package/apps/browserctl/src/main.test.ts +215 -0
  39. package/apps/browserctl/src/main.ts +372 -0
  40. package/apps/browserctl/src/smoke.test.ts +16 -0
  41. package/apps/browserctl/src/smoke.ts +5 -0
  42. package/apps/browserd/src/bootstrap.ts +432 -0
  43. package/apps/browserd/src/chrome-relay-extension-bridge.test.ts +275 -0
  44. package/apps/browserd/src/chrome-relay-extension-bridge.ts +506 -0
  45. package/apps/browserd/src/container.ts +1531 -0
  46. package/apps/browserd/src/main.test.ts +864 -0
  47. package/apps/browserd/src/main.ts +7 -0
  48. package/bin/browserctl.cjs +21 -0
  49. package/bin/browserd.cjs +21 -0
  50. package/extensions/chrome-relay/README.md +36 -0
  51. package/extensions/chrome-relay/background.js +1687 -0
  52. package/extensions/chrome-relay/manifest.json +15 -0
  53. package/extensions/chrome-relay/popup.html +369 -0
  54. package/extensions/chrome-relay/popup.js +972 -0
  55. package/package.json +51 -0
  56. package/packages/core/src/bootstrap.test.ts +10 -0
  57. package/packages/core/src/driver-registry.test.ts +45 -0
  58. package/packages/core/src/driver-registry.ts +22 -0
  59. package/packages/core/src/driver.ts +47 -0
  60. package/packages/core/src/index.ts +5 -0
  61. package/packages/core/src/ref-cache.test.ts +61 -0
  62. package/packages/core/src/ref-cache.ts +28 -0
  63. package/packages/core/src/session-store.test.ts +49 -0
  64. package/packages/core/src/session-store.ts +33 -0
  65. package/packages/core/src/types.ts +9 -0
  66. package/packages/driver-chrome-relay/src/chrome-relay-driver.test.ts +634 -0
  67. package/packages/driver-chrome-relay/src/chrome-relay-driver.ts +2206 -0
  68. package/packages/driver-chrome-relay/src/chrome-relay-extension-runtime.test.ts +264 -0
  69. package/packages/driver-chrome-relay/src/chrome-relay-extension-runtime.ts +521 -0
  70. package/packages/driver-chrome-relay/src/index.ts +26 -0
  71. package/packages/driver-managed/src/index.ts +22 -0
  72. package/packages/driver-managed/src/managed-driver.test.ts +59 -0
  73. package/packages/driver-managed/src/managed-driver.ts +125 -0
  74. package/packages/driver-managed/src/managed-local-driver.test.ts +506 -0
  75. package/packages/driver-managed/src/managed-local-driver.ts +2021 -0
  76. package/packages/driver-remote-cdp/src/index.ts +19 -0
  77. package/packages/driver-remote-cdp/src/remote-cdp-driver.test.ts +617 -0
  78. package/packages/driver-remote-cdp/src/remote-cdp-driver.ts +2042 -0
  79. package/packages/protocol/src/envelope.test.ts +25 -0
  80. package/packages/protocol/src/envelope.ts +31 -0
  81. package/packages/protocol/src/errors.test.ts +17 -0
  82. package/packages/protocol/src/errors.ts +11 -0
  83. package/packages/protocol/src/index.ts +3 -0
  84. package/packages/protocol/src/tools.ts +3 -0
  85. package/packages/transport-mcp-stdio/src/index.ts +3 -0
  86. package/packages/transport-mcp-stdio/src/sdk-server.ts +139 -0
  87. package/packages/transport-mcp-stdio/src/server.test.ts +281 -0
  88. package/packages/transport-mcp-stdio/src/server.ts +183 -0
  89. package/packages/transport-mcp-stdio/src/tool-map.ts +67 -0
  90. package/scripts/smoke.ps1 +127 -0
@@ -0,0 +1,2042 @@
1
+ import type {
2
+ BrowserDriver,
3
+ BrowserDriverScreenshot,
4
+ DriverObject
5
+ } from "../../core/src/driver";
6
+ import type { ProfileId, TargetId } from "../../core/src/types";
7
+
8
+ export type RemoteCdpDriverConfig = {
9
+ cdpUrl: string;
10
+ runtime?: RemoteCdpDriverRuntime;
11
+ };
12
+
13
+ export type RemoteCdpEndpoint = {
14
+ url: string;
15
+ protocol: string;
16
+ host: string;
17
+ };
18
+
19
+ export type RemoteCdpDriverStatus = {
20
+ kind: "remote-cdp";
21
+ connected: boolean;
22
+ endpoint: RemoteCdpEndpoint;
23
+ };
24
+
25
+ export type RemoteCdpConsoleEntryLocation = {
26
+ url?: string;
27
+ lineNumber?: number;
28
+ columnNumber?: number;
29
+ };
30
+
31
+ export type RemoteCdpConsoleEntry = {
32
+ type: string;
33
+ text: string;
34
+ timestamp: string;
35
+ location?: RemoteCdpConsoleEntryLocation;
36
+ };
37
+
38
+ export type RemoteCdpNetworkRequestSummary = {
39
+ requestId: string;
40
+ url: string;
41
+ method?: string;
42
+ resourceType?: string;
43
+ status?: number;
44
+ timestamp: string;
45
+ };
46
+
47
+ export type RemoteCdpNetworkResponseBody = {
48
+ body: string;
49
+ encoding: "utf8" | "base64";
50
+ };
51
+
52
+ export type RemoteCdpSnapshot = {
53
+ kind: "remote-cdp";
54
+ profile: ProfileId;
55
+ targetId: TargetId;
56
+ endpoint: RemoteCdpEndpoint;
57
+ hasTarget: boolean;
58
+ url?: string;
59
+ title?: string;
60
+ html?: string;
61
+ requestSummaries?: RemoteCdpNetworkRequestSummary[];
62
+ };
63
+
64
+ export type RemoteCdpScreenshot = {
65
+ kind: "remote-cdp";
66
+ profile: ProfileId;
67
+ targetId: TargetId;
68
+ endpoint: RemoteCdpEndpoint;
69
+ hasTarget: boolean;
70
+ mimeType?: string;
71
+ encoding?: "base64";
72
+ imageBase64?: string;
73
+ width?: number;
74
+ height?: number;
75
+ };
76
+
77
+ export type RemoteCdpTelemetryDriverExtensions = {
78
+ getConsoleEntries?(targetId: TargetId, profile?: ProfileId): RemoteCdpConsoleEntry[];
79
+ getNetworkResponseBody?(
80
+ requestId: string,
81
+ targetId: TargetId,
82
+ profile?: ProfileId
83
+ ): RemoteCdpNetworkResponseBody | undefined;
84
+ };
85
+
86
+ export type RemoteCdpLocator = {
87
+ click(): Promise<void>;
88
+ fill(value: string): Promise<void>;
89
+ type(value: string): Promise<void>;
90
+ };
91
+
92
+ export type RemoteCdpKeyboard = {
93
+ press(key: string): Promise<void>;
94
+ };
95
+
96
+ export type RemoteCdpPage = {
97
+ goto(url: string): Promise<void>;
98
+ bringToFront(): Promise<void>;
99
+ close(): Promise<void>;
100
+ url(): string;
101
+ title(): Promise<string>;
102
+ content(): Promise<string>;
103
+ screenshot?(options?: Record<string, unknown>): Promise<unknown>;
104
+ locator(selector: string): RemoteCdpLocator;
105
+ keyboard?: RemoteCdpKeyboard;
106
+ on?(eventName: string, listener: (payload: unknown) => unknown): void;
107
+ };
108
+
109
+ export type RemoteCdpBrowserContext = {
110
+ newPage(): Promise<RemoteCdpPage>;
111
+ close?(): Promise<void>;
112
+ };
113
+
114
+ export type RemoteCdpBrowser = {
115
+ contexts(): RemoteCdpBrowserContext[];
116
+ newContext?(): Promise<RemoteCdpBrowserContext>;
117
+ close(): Promise<void>;
118
+ };
119
+
120
+ export type RemoteCdpDriverRuntime = {
121
+ connectOverCDP(endpointUrl: string): Promise<RemoteCdpBrowser>;
122
+ };
123
+
124
+ const DEFAULT_PROFILE_ID: ProfileId = "profile:remote-cdp:default";
125
+ const TELEMETRY_EVENT_LIMIT = 200;
126
+
127
+ type RemoteCdpTab = {
128
+ url: string;
129
+ page: RemoteCdpPage;
130
+ };
131
+
132
+ type RemoteCdpProfileState = {
133
+ nextTargetNumber: number;
134
+ tabs: Map<TargetId, RemoteCdpTab>;
135
+ tabOrder: TargetId[];
136
+ focusedTargetId?: TargetId;
137
+ };
138
+
139
+ type RemoteCdpTargetOperationState = {
140
+ uploadFiles: string[];
141
+ dialogArmedCount: number;
142
+ triggerCount: number;
143
+ downloadInFlight?: Promise<RemoteCdpDownloadArtifact>;
144
+ latestDownload?: RemoteCdpDownloadArtifact;
145
+ };
146
+
147
+ type RemoteCdpDownloadArtifact = {
148
+ path: string;
149
+ suggestedFilename?: string;
150
+ url?: string;
151
+ mimeType?: string;
152
+ };
153
+
154
+ type RemoteCdpTargetTelemetryState = {
155
+ consoleEntries: RemoteCdpConsoleEntry[];
156
+ requestSummaries: RemoteCdpNetworkRequestSummary[];
157
+ networkResponseBodies: Map<string, RemoteCdpNetworkResponseBody>;
158
+ nextRequestNumber: number;
159
+ };
160
+
161
+ function resolveProfileId(profile?: ProfileId): ProfileId {
162
+ return profile ?? DEFAULT_PROFILE_ID;
163
+ }
164
+
165
+ function parseEndpoint(cdpUrl: string): RemoteCdpEndpoint {
166
+ const trimmedCdpUrl = cdpUrl.trim();
167
+ if (trimmedCdpUrl.length === 0) {
168
+ throw new Error("Invalid cdpUrl: value must not be empty.");
169
+ }
170
+
171
+ try {
172
+ const endpoint = new URL(trimmedCdpUrl);
173
+ return {
174
+ url: endpoint.toString(),
175
+ protocol: endpoint.protocol,
176
+ host: endpoint.host
177
+ };
178
+ } catch {
179
+ throw new Error(`Invalid cdpUrl: ${trimmedCdpUrl}`);
180
+ }
181
+ }
182
+
183
+ function createTargetId(profileId: ProfileId, targetNumber: number): TargetId {
184
+ return `target:remote-cdp:${profileId}:${targetNumber}`;
185
+ }
186
+
187
+ function createProfileState(): RemoteCdpProfileState {
188
+ return {
189
+ nextTargetNumber: 1,
190
+ tabs: new Map<TargetId, RemoteCdpTab>(),
191
+ tabOrder: []
192
+ };
193
+ }
194
+
195
+ function createTargetOperationState(): RemoteCdpTargetOperationState {
196
+ return {
197
+ uploadFiles: [],
198
+ dialogArmedCount: 0,
199
+ triggerCount: 0
200
+ };
201
+ }
202
+
203
+ function createTargetTelemetryState(): RemoteCdpTargetTelemetryState {
204
+ return {
205
+ consoleEntries: [],
206
+ requestSummaries: [],
207
+ networkResponseBodies: new Map<string, RemoteCdpNetworkResponseBody>(),
208
+ nextRequestNumber: 1
209
+ };
210
+ }
211
+
212
+ function trimConsoleEntries(telemetryState: RemoteCdpTargetTelemetryState): void {
213
+ if (telemetryState.consoleEntries.length <= TELEMETRY_EVENT_LIMIT) {
214
+ return;
215
+ }
216
+
217
+ telemetryState.consoleEntries.splice(
218
+ 0,
219
+ telemetryState.consoleEntries.length - TELEMETRY_EVENT_LIMIT
220
+ );
221
+ }
222
+
223
+ function trimNetworkTelemetry(telemetryState: RemoteCdpTargetTelemetryState): void {
224
+ if (telemetryState.requestSummaries.length > TELEMETRY_EVENT_LIMIT) {
225
+ const removedSummaries = telemetryState.requestSummaries.splice(
226
+ 0,
227
+ telemetryState.requestSummaries.length - TELEMETRY_EVENT_LIMIT
228
+ );
229
+ for (const removed of removedSummaries) {
230
+ telemetryState.networkResponseBodies.delete(removed.requestId);
231
+ }
232
+ }
233
+
234
+ const knownRequestIds = new Set(
235
+ telemetryState.requestSummaries.map((summary) => summary.requestId)
236
+ );
237
+ for (const requestId of telemetryState.networkResponseBodies.keys()) {
238
+ if (!knownRequestIds.has(requestId)) {
239
+ telemetryState.networkResponseBodies.delete(requestId);
240
+ }
241
+ }
242
+ }
243
+
244
+ function createDownloadPath(profileId: ProfileId, targetId: TargetId, triggerCount: number): string {
245
+ return `remote-cdp-${encodeURIComponent(profileId)}-${encodeURIComponent(targetId)}-${triggerCount}.bin`;
246
+ }
247
+
248
+ function createRequestId(profileId: ProfileId, targetId: TargetId, requestNumber: number): string {
249
+ return `request:remote-cdp:${encodeURIComponent(profileId)}:${encodeURIComponent(targetId)}:${requestNumber}`;
250
+ }
251
+
252
+ function toErrorMessage(error: unknown): string {
253
+ return error instanceof Error ? error.message : "Unexpected remote-cdp driver failure.";
254
+ }
255
+
256
+ function readActionPayloadString(payload: DriverObject | undefined, key: string): string | undefined {
257
+ const value = payload?.[key];
258
+ return typeof value === "string" && value.trim().length > 0 ? value : undefined;
259
+ }
260
+
261
+ function readActionPayloadNumber(payload: DriverObject | undefined, key: string): number | undefined {
262
+ const value = payload?.[key];
263
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
264
+ }
265
+
266
+ function isObjectRecord(value: unknown): value is Record<string, unknown> {
267
+ return typeof value === "object" && value !== null && !Array.isArray(value);
268
+ }
269
+
270
+ function readObjectMethod<TValue>(value: unknown, methodName: string): TValue | undefined {
271
+ if (typeof value !== "object" || value === null) {
272
+ return undefined;
273
+ }
274
+
275
+ const method = (value as Record<string, unknown>)[methodName];
276
+ if (typeof method !== "function") {
277
+ return undefined;
278
+ }
279
+
280
+ try {
281
+ return (method as () => TValue).call(value);
282
+ } catch {
283
+ return undefined;
284
+ }
285
+ }
286
+
287
+ function getObjectMethod(
288
+ value: unknown,
289
+ methodName: string
290
+ ): ((...args: unknown[]) => unknown) | undefined {
291
+ if (typeof value !== "object" || value === null) {
292
+ return undefined;
293
+ }
294
+
295
+ const method = (value as Record<string, unknown>)[methodName];
296
+ return typeof method === "function" ? (method as (...args: unknown[]) => unknown) : undefined;
297
+ }
298
+
299
+ function readObjectStringProperty(value: unknown, key: string): string | undefined {
300
+ if (typeof value !== "object" || value === null) {
301
+ return undefined;
302
+ }
303
+
304
+ const property = (value as Record<string, unknown>)[key];
305
+ return typeof property === "string" ? property : undefined;
306
+ }
307
+
308
+ function readObjectNumberProperty(value: unknown, key: string): number | undefined {
309
+ if (typeof value !== "object" || value === null) {
310
+ return undefined;
311
+ }
312
+
313
+ const property = (value as Record<string, unknown>)[key];
314
+ return typeof property === "number" ? property : undefined;
315
+ }
316
+
317
+ function readConsoleEntry(value: unknown): RemoteCdpConsoleEntry {
318
+ const locationValue = readObjectMethod<unknown>(value, "location");
319
+ const locationUrl = readObjectStringProperty(locationValue, "url");
320
+ const locationLineNumber = readObjectNumberProperty(locationValue, "lineNumber");
321
+ const locationColumnNumber = readObjectNumberProperty(locationValue, "columnNumber");
322
+
323
+ const hasLocation =
324
+ locationUrl !== undefined || locationLineNumber !== undefined || locationColumnNumber !== undefined;
325
+
326
+ return {
327
+ type: readObjectMethod<string>(value, "type") ?? "log",
328
+ text: readObjectMethod<string>(value, "text") ?? "",
329
+ timestamp: new Date().toISOString(),
330
+ ...(hasLocation
331
+ ? {
332
+ location: {
333
+ ...(locationUrl !== undefined ? { url: locationUrl } : {}),
334
+ ...(locationLineNumber !== undefined ? { lineNumber: locationLineNumber } : {}),
335
+ ...(locationColumnNumber !== undefined ? { columnNumber: locationColumnNumber } : {})
336
+ }
337
+ }
338
+ : {})
339
+ };
340
+ }
341
+
342
+ function readNetworkSummary(value: unknown, requestId: string): RemoteCdpNetworkRequestSummary {
343
+ const requestValue = readObjectMethod<unknown>(value, "request");
344
+ const method = readObjectMethod<string>(requestValue, "method");
345
+ const resourceType = readObjectMethod<string>(requestValue, "resourceType");
346
+ const status = readObjectMethod<number>(value, "status");
347
+
348
+ return {
349
+ requestId,
350
+ url: readObjectMethod<string>(value, "url") ?? "",
351
+ ...(typeof method === "string" ? { method } : {}),
352
+ ...(typeof resourceType === "string" ? { resourceType } : {}),
353
+ ...(typeof status === "number" ? { status } : {}),
354
+ timestamp: new Date().toISOString()
355
+ };
356
+ }
357
+
358
+ function toBase64(value: ArrayBuffer | Uint8Array): string {
359
+ const bytes = value instanceof Uint8Array ? value : new Uint8Array(value);
360
+ return Buffer.from(bytes).toString("base64");
361
+ }
362
+
363
+ function parseScreenshotBase64(
364
+ value: string
365
+ ): { mimeType: string; imageBase64: string } | undefined {
366
+ const trimmedValue = value.trim();
367
+ if (trimmedValue.length === 0) {
368
+ return undefined;
369
+ }
370
+
371
+ const dataUrlMatch = /^data:([^;,]+);base64,(.+)$/i.exec(trimmedValue);
372
+ if (dataUrlMatch !== null) {
373
+ const mimeType = dataUrlMatch[1] ?? "image/png";
374
+ const imageBase64 = dataUrlMatch[2] ?? "";
375
+ if (imageBase64.length === 0) {
376
+ return undefined;
377
+ }
378
+
379
+ return {
380
+ mimeType,
381
+ imageBase64
382
+ };
383
+ }
384
+
385
+ return {
386
+ mimeType: "image/png",
387
+ imageBase64: trimmedValue
388
+ };
389
+ }
390
+
391
+ type RemoteCdpScreenshotImage = {
392
+ mimeType: string;
393
+ encoding: "base64";
394
+ imageBase64: string;
395
+ width?: number;
396
+ height?: number;
397
+ };
398
+
399
+ function toOptionalPositiveNumber(value: unknown): number | undefined {
400
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
401
+ }
402
+
403
+ function readScreenshotImage(value: unknown): RemoteCdpScreenshotImage | undefined {
404
+ if (value instanceof Uint8Array || value instanceof ArrayBuffer) {
405
+ return {
406
+ mimeType: "image/png",
407
+ encoding: "base64",
408
+ imageBase64: toBase64(value)
409
+ };
410
+ }
411
+
412
+ if (typeof value === "string") {
413
+ const parsed = parseScreenshotBase64(value);
414
+ if (parsed === undefined) {
415
+ return undefined;
416
+ }
417
+
418
+ return {
419
+ mimeType: parsed.mimeType,
420
+ encoding: "base64",
421
+ imageBase64: parsed.imageBase64
422
+ };
423
+ }
424
+
425
+ if (typeof value !== "object" || value === null) {
426
+ return undefined;
427
+ }
428
+
429
+ const imageBase64 = readObjectStringProperty(value, "imageBase64");
430
+ if (imageBase64 === undefined || imageBase64.trim().length === 0) {
431
+ return undefined;
432
+ }
433
+
434
+ const rawEncoding = readObjectStringProperty(value, "encoding");
435
+ if (rawEncoding !== undefined && rawEncoding !== "base64") {
436
+ return undefined;
437
+ }
438
+
439
+ const mimeType = readObjectStringProperty(value, "mimeType") ?? "image/png";
440
+ const width = toOptionalPositiveNumber(readObjectNumberProperty(value, "width"));
441
+ const height = toOptionalPositiveNumber(readObjectNumberProperty(value, "height"));
442
+
443
+ return {
444
+ mimeType,
445
+ encoding: "base64",
446
+ imageBase64: imageBase64.trim(),
447
+ ...(width !== undefined ? { width } : {}),
448
+ ...(height !== undefined ? { height } : {})
449
+ };
450
+ }
451
+
452
+ async function capturePageScreenshot(page: RemoteCdpPage): Promise<RemoteCdpScreenshotImage> {
453
+ const screenshotMethod = getObjectMethod(page, "screenshot");
454
+ if (typeof screenshotMethod !== "function") {
455
+ throw new Error("Screenshot is not supported by this driver runtime.");
456
+ }
457
+
458
+ const screenshot = await screenshotMethod.call(page, {
459
+ type: "png"
460
+ });
461
+ const parsedScreenshot = readScreenshotImage(screenshot);
462
+ if (parsedScreenshot === undefined) {
463
+ throw new Error("Unexpected screenshot payload from driver runtime.");
464
+ }
465
+
466
+ return parsedScreenshot;
467
+ }
468
+
469
+ type RemoteCdpCookie = {
470
+ name: string;
471
+ value: string;
472
+ domain?: string;
473
+ path?: string;
474
+ expires?: number;
475
+ httpOnly?: boolean;
476
+ secure?: boolean;
477
+ sameSite?: string;
478
+ url?: string;
479
+ };
480
+
481
+ function normalizeCookies(value: unknown): RemoteCdpCookie[] {
482
+ if (!Array.isArray(value)) {
483
+ return [];
484
+ }
485
+
486
+ const cookies: RemoteCdpCookie[] = [];
487
+ for (const item of value) {
488
+ if (!isObjectRecord(item)) {
489
+ continue;
490
+ }
491
+
492
+ const name = readObjectStringProperty(item, "name");
493
+ const cookieValue = readObjectStringProperty(item, "value");
494
+ if (name === undefined || cookieValue === undefined) {
495
+ continue;
496
+ }
497
+
498
+ const domain = readObjectStringProperty(item, "domain");
499
+ const path = readObjectStringProperty(item, "path");
500
+ const sameSite = readObjectStringProperty(item, "sameSite");
501
+ const url = readObjectStringProperty(item, "url");
502
+ const expiresRaw = readObjectNumberProperty(item, "expires");
503
+ const httpOnlyRaw = item.httpOnly;
504
+ const secureRaw = item.secure;
505
+
506
+ cookies.push({
507
+ name,
508
+ value: cookieValue,
509
+ ...(domain !== undefined ? { domain } : {}),
510
+ ...(path !== undefined ? { path } : {}),
511
+ ...(typeof expiresRaw === "number" && Number.isFinite(expiresRaw) ? { expires: expiresRaw } : {}),
512
+ ...(typeof httpOnlyRaw === "boolean" ? { httpOnly: httpOnlyRaw } : {}),
513
+ ...(typeof secureRaw === "boolean" ? { secure: secureRaw } : {}),
514
+ ...(sameSite !== undefined ? { sameSite } : {}),
515
+ ...(url !== undefined ? { url } : {})
516
+ });
517
+ }
518
+
519
+ return cookies;
520
+ }
521
+
522
+ function toCookieInput(cookie: RemoteCdpCookie): Record<string, unknown> | undefined {
523
+ const base: Record<string, unknown> = {
524
+ name: cookie.name,
525
+ value: cookie.value
526
+ };
527
+
528
+ if (cookie.url !== undefined) {
529
+ return {
530
+ ...base,
531
+ url: cookie.url,
532
+ ...(cookie.expires !== undefined ? { expires: cookie.expires } : {}),
533
+ ...(cookie.httpOnly !== undefined ? { httpOnly: cookie.httpOnly } : {}),
534
+ ...(cookie.secure !== undefined ? { secure: cookie.secure } : {}),
535
+ ...(cookie.sameSite !== undefined ? { sameSite: cookie.sameSite } : {})
536
+ };
537
+ }
538
+
539
+ if (cookie.domain !== undefined && cookie.path !== undefined) {
540
+ return {
541
+ ...base,
542
+ domain: cookie.domain,
543
+ path: cookie.path,
544
+ ...(cookie.expires !== undefined ? { expires: cookie.expires } : {}),
545
+ ...(cookie.httpOnly !== undefined ? { httpOnly: cookie.httpOnly } : {}),
546
+ ...(cookie.secure !== undefined ? { secure: cookie.secure } : {}),
547
+ ...(cookie.sameSite !== undefined ? { sameSite: cookie.sameSite } : {})
548
+ };
549
+ }
550
+
551
+ return undefined;
552
+ }
553
+
554
+ function parseStorageScope(scope: string | undefined): "local" | "session" | undefined {
555
+ if (scope === "local" || scope === "session") {
556
+ return scope;
557
+ }
558
+
559
+ return undefined;
560
+ }
561
+
562
+ function parseFrameIndex(frameId: string | undefined): number | undefined {
563
+ if (typeof frameId !== "string") {
564
+ return undefined;
565
+ }
566
+
567
+ const match = /^frame:(\d+)$/.exec(frameId.trim());
568
+ if (match === null) {
569
+ return undefined;
570
+ }
571
+
572
+ const parsed = Number.parseInt(match[1] ?? "", 10);
573
+ return Number.isFinite(parsed) ? parsed : undefined;
574
+ }
575
+
576
+ async function evaluateInPage<TResult>(
577
+ page: RemoteCdpPage,
578
+ callback: (arg: unknown) => unknown,
579
+ arg: unknown
580
+ ): Promise<TResult> {
581
+ const evaluateMethod = getObjectMethod(page, "evaluate");
582
+ if (typeof evaluateMethod !== "function") {
583
+ throw new Error("Driver runtime page does not support evaluate.");
584
+ }
585
+
586
+ const result = await evaluateMethod.call(page, callback, arg);
587
+ return result as TResult;
588
+ }
589
+
590
+ async function readNetworkResponseBody(
591
+ value: unknown
592
+ ): Promise<RemoteCdpNetworkResponseBody | undefined> {
593
+ const textMethod = getObjectMethod(value, "text");
594
+ if (typeof textMethod === "function") {
595
+ try {
596
+ const textResult = await textMethod.call(value);
597
+ if (typeof textResult === "string") {
598
+ return {
599
+ body: textResult,
600
+ encoding: "utf8"
601
+ };
602
+ }
603
+ } catch {
604
+ // Ignore body extraction failures from optional runtime hooks.
605
+ }
606
+ }
607
+
608
+ const bodyMethod = getObjectMethod(value, "body");
609
+ if (typeof bodyMethod !== "function") {
610
+ return undefined;
611
+ }
612
+
613
+ try {
614
+ const bodyResult = await bodyMethod.call(value);
615
+ if (typeof bodyResult === "string") {
616
+ return {
617
+ body: bodyResult,
618
+ encoding: "utf8"
619
+ };
620
+ }
621
+
622
+ if (bodyResult instanceof Uint8Array || bodyResult instanceof ArrayBuffer) {
623
+ return {
624
+ body: toBase64(bodyResult),
625
+ encoding: "base64"
626
+ };
627
+ }
628
+
629
+ return undefined;
630
+ } catch {
631
+ return undefined;
632
+ }
633
+ }
634
+
635
+ function attachTelemetryListeners(
636
+ page: RemoteCdpPage,
637
+ profileId: ProfileId,
638
+ targetId: TargetId,
639
+ telemetryState: RemoteCdpTargetTelemetryState,
640
+ operationState: RemoteCdpTargetOperationState
641
+ ): void {
642
+ if (typeof page.on !== "function") {
643
+ return;
644
+ }
645
+
646
+ page.on("console", (message) => {
647
+ telemetryState.consoleEntries.push(readConsoleEntry(message));
648
+ trimConsoleEntries(telemetryState);
649
+ });
650
+
651
+ page.on("response", async (response) => {
652
+ const requestId = createRequestId(profileId, targetId, telemetryState.nextRequestNumber);
653
+ telemetryState.nextRequestNumber += 1;
654
+ telemetryState.requestSummaries.push(readNetworkSummary(response, requestId));
655
+ trimNetworkTelemetry(telemetryState);
656
+
657
+ const body = await readNetworkResponseBody(response);
658
+ if (body !== undefined) {
659
+ telemetryState.networkResponseBodies.set(requestId, body);
660
+ trimNetworkTelemetry(telemetryState);
661
+ }
662
+ });
663
+
664
+ page.on("dialog", async (dialog) => {
665
+ if (operationState.dialogArmedCount <= 0) {
666
+ return;
667
+ }
668
+
669
+ operationState.dialogArmedCount -= 1;
670
+ const acceptMethod = getObjectMethod(dialog, "accept");
671
+ if (typeof acceptMethod === "function") {
672
+ try {
673
+ await acceptMethod.call(dialog);
674
+ return;
675
+ } catch {
676
+ // Fall through to dismiss.
677
+ }
678
+ }
679
+
680
+ const dismissMethod = getObjectMethod(dialog, "dismiss");
681
+ if (typeof dismissMethod === "function") {
682
+ try {
683
+ await dismissMethod.call(dialog);
684
+ } catch {
685
+ // Ignore dialog dismissal failures.
686
+ }
687
+ }
688
+ });
689
+ }
690
+
691
+ async function readDownloadArtifact(
692
+ value: unknown,
693
+ fallbackPath: string
694
+ ): Promise<RemoteCdpDownloadArtifact> {
695
+ let resolvedPath = fallbackPath;
696
+ const pathMethod = getObjectMethod(value, "path");
697
+ if (typeof pathMethod === "function") {
698
+ try {
699
+ const pathResult = await pathMethod.call(value);
700
+ if (typeof pathResult === "string" && pathResult.trim().length > 0) {
701
+ resolvedPath = pathResult;
702
+ }
703
+ } catch {
704
+ // Ignore path() failures and keep fallback path.
705
+ }
706
+ }
707
+
708
+ const saveAsMethod = getObjectMethod(value, "saveAs");
709
+ if (typeof saveAsMethod === "function") {
710
+ try {
711
+ await saveAsMethod.call(value, fallbackPath);
712
+ resolvedPath = fallbackPath;
713
+ } catch {
714
+ // Ignore saveAs failures and keep best-effort path.
715
+ }
716
+ }
717
+
718
+ const suggestedFilename = readObjectMethod<string>(value, "suggestedFilename");
719
+ const url = readObjectMethod<string>(value, "url");
720
+ const mimeType = readObjectMethod<string>(value, "mimeType");
721
+
722
+ return {
723
+ path: resolvedPath,
724
+ ...(typeof suggestedFilename === "string" ? { suggestedFilename } : {}),
725
+ ...(typeof url === "string" ? { url } : {}),
726
+ ...(typeof mimeType === "string" ? { mimeType } : {})
727
+ };
728
+ }
729
+
730
+ function createPlaywrightRuntime(): RemoteCdpDriverRuntime {
731
+ return {
732
+ connectOverCDP: async (endpointUrl) => {
733
+ const playwright = await import("playwright-core");
734
+ return (await playwright.chromium.connectOverCDP(endpointUrl)) as unknown as RemoteCdpBrowser;
735
+ }
736
+ };
737
+ }
738
+
739
+ function cloneConsoleEntry(entry: RemoteCdpConsoleEntry): RemoteCdpConsoleEntry {
740
+ return {
741
+ ...entry,
742
+ ...(entry.location !== undefined ? { location: { ...entry.location } } : {})
743
+ };
744
+ }
745
+
746
+ function cloneRequestSummary(summary: RemoteCdpNetworkRequestSummary): RemoteCdpNetworkRequestSummary {
747
+ return { ...summary };
748
+ }
749
+
750
+ export function createRemoteCdpDriver(
751
+ config: RemoteCdpDriverConfig
752
+ ): BrowserDriver<RemoteCdpDriverStatus, RemoteCdpSnapshot> &
753
+ RemoteCdpTelemetryDriverExtensions &
754
+ BrowserDriverScreenshot<RemoteCdpScreenshot> {
755
+ const endpoint = parseEndpoint(config.cdpUrl);
756
+ const runtime = config.runtime ?? createPlaywrightRuntime();
757
+ const profileStates = new Map<ProfileId, RemoteCdpProfileState>();
758
+ const targetOperationStates = new Map<ProfileId, Map<TargetId, RemoteCdpTargetOperationState>>();
759
+ const targetTelemetryStates = new Map<ProfileId, Map<TargetId, RemoteCdpTargetTelemetryState>>();
760
+ let browser: RemoteCdpBrowser | undefined;
761
+ let browserConnectInFlight: Promise<RemoteCdpBrowser> | undefined;
762
+ let browserContext: RemoteCdpBrowserContext | undefined;
763
+ let browserContextInFlight: Promise<RemoteCdpBrowserContext> | undefined;
764
+
765
+ async function ensureBrowser(): Promise<RemoteCdpBrowser> {
766
+ if (browser !== undefined) {
767
+ return browser;
768
+ }
769
+
770
+ if (browserConnectInFlight === undefined) {
771
+ browserConnectInFlight = runtime.connectOverCDP(endpoint.url)
772
+ .then((createdBrowser) => {
773
+ browser = createdBrowser;
774
+ return createdBrowser;
775
+ })
776
+ .finally(() => {
777
+ browserConnectInFlight = undefined;
778
+ });
779
+ }
780
+
781
+ return browserConnectInFlight;
782
+ }
783
+
784
+ async function ensureBrowserContext(): Promise<RemoteCdpBrowserContext> {
785
+ if (browserContext !== undefined) {
786
+ return browserContext;
787
+ }
788
+
789
+ if (browserContextInFlight === undefined) {
790
+ browserContextInFlight = (async () => {
791
+ const connectedBrowser = await ensureBrowser();
792
+ const existingContext = connectedBrowser.contexts()[0];
793
+ if (existingContext !== undefined) {
794
+ browserContext = existingContext;
795
+ return existingContext;
796
+ }
797
+
798
+ if (typeof connectedBrowser.newContext !== "function") {
799
+ throw new Error("No browser context available from remote CDP connection.");
800
+ }
801
+
802
+ const createdContext = await connectedBrowser.newContext();
803
+ browserContext = createdContext;
804
+ return createdContext;
805
+ })().finally(() => {
806
+ browserContextInFlight = undefined;
807
+ });
808
+ }
809
+
810
+ return browserContextInFlight;
811
+ }
812
+
813
+ function getOrCreateProfileState(profileId: ProfileId): RemoteCdpProfileState {
814
+ const existingState = profileStates.get(profileId);
815
+ if (existingState !== undefined) {
816
+ return existingState;
817
+ }
818
+
819
+ const createdState = createProfileState();
820
+ profileStates.set(profileId, createdState);
821
+ return createdState;
822
+ }
823
+
824
+ function requireTargetInProfile(
825
+ profileId: ProfileId,
826
+ targetId: TargetId
827
+ ): { profileState: RemoteCdpProfileState; tab: RemoteCdpTab } {
828
+ const profileState = profileStates.get(profileId);
829
+ const tab = profileState?.tabs.get(targetId);
830
+ if (profileState === undefined || tab === undefined) {
831
+ throw new Error(`Unknown targetId: ${targetId} (profile: ${profileId})`);
832
+ }
833
+
834
+ return { profileState, tab };
835
+ }
836
+
837
+ function getOrCreateTargetOperationState(
838
+ profileId: ProfileId,
839
+ targetId: TargetId,
840
+ validateTarget = true
841
+ ): RemoteCdpTargetOperationState {
842
+ if (validateTarget) {
843
+ requireTargetInProfile(profileId, targetId);
844
+ }
845
+
846
+ let profileOperationStates = targetOperationStates.get(profileId);
847
+ if (profileOperationStates === undefined) {
848
+ profileOperationStates = new Map<TargetId, RemoteCdpTargetOperationState>();
849
+ targetOperationStates.set(profileId, profileOperationStates);
850
+ }
851
+
852
+ const existingState = profileOperationStates.get(targetId);
853
+ if (existingState !== undefined) {
854
+ return existingState;
855
+ }
856
+
857
+ const createdState = createTargetOperationState();
858
+ profileOperationStates.set(targetId, createdState);
859
+ return createdState;
860
+ }
861
+
862
+ function getOrCreateProfileTelemetryStates(
863
+ profileId: ProfileId
864
+ ): Map<TargetId, RemoteCdpTargetTelemetryState> {
865
+ const existingStates = targetTelemetryStates.get(profileId);
866
+ if (existingStates !== undefined) {
867
+ return existingStates;
868
+ }
869
+
870
+ const createdStates = new Map<TargetId, RemoteCdpTargetTelemetryState>();
871
+ targetTelemetryStates.set(profileId, createdStates);
872
+ return createdStates;
873
+ }
874
+
875
+ function findTelemetryState(
876
+ targetId: TargetId,
877
+ profile?: ProfileId
878
+ ): RemoteCdpTargetTelemetryState | undefined {
879
+ if (profile !== undefined) {
880
+ return targetTelemetryStates.get(resolveProfileId(profile))?.get(targetId);
881
+ }
882
+
883
+ for (const profileTelemetryStates of targetTelemetryStates.values()) {
884
+ const telemetryState = profileTelemetryStates.get(targetId);
885
+ if (telemetryState !== undefined) {
886
+ return telemetryState;
887
+ }
888
+ }
889
+
890
+ return undefined;
891
+ }
892
+
893
+ function ensureDownloadInFlight(
894
+ profileId: ProfileId,
895
+ targetId: TargetId,
896
+ tab: RemoteCdpTab,
897
+ operationState: RemoteCdpTargetOperationState
898
+ ): Promise<RemoteCdpDownloadArtifact> {
899
+ if (operationState.downloadInFlight !== undefined) {
900
+ return operationState.downloadInFlight;
901
+ }
902
+
903
+ const fallbackPath = createDownloadPath(
904
+ profileId,
905
+ targetId,
906
+ Math.max(operationState.triggerCount, 1)
907
+ );
908
+ const waitForEventMethod = getObjectMethod(tab.page, "waitForEvent");
909
+ if (typeof waitForEventMethod !== "function") {
910
+ const artifact: RemoteCdpDownloadArtifact = { path: fallbackPath };
911
+ operationState.latestDownload = artifact;
912
+ const resolved = Promise.resolve(artifact);
913
+ operationState.downloadInFlight = resolved;
914
+ return resolved;
915
+ }
916
+
917
+ const inFlight = (async () => {
918
+ const rawDownload = await waitForEventMethod.call(tab.page, "download");
919
+ const artifact = await readDownloadArtifact(rawDownload, fallbackPath);
920
+ operationState.latestDownload = artifact;
921
+ return artifact;
922
+ })().finally(() => {
923
+ if (operationState.downloadInFlight === inFlight) {
924
+ operationState.downloadInFlight = undefined;
925
+ }
926
+ });
927
+
928
+ operationState.downloadInFlight = inFlight;
929
+ return inFlight;
930
+ }
931
+
932
+ return {
933
+ status: async () => ({ kind: "remote-cdp", connected: browser !== undefined, endpoint }),
934
+ listProfiles: async () => {
935
+ const knownProfiles = new Set<ProfileId>([DEFAULT_PROFILE_ID]);
936
+ for (const profileId of profileStates.keys()) {
937
+ knownProfiles.add(profileId);
938
+ }
939
+
940
+ return Array.from(knownProfiles).sort();
941
+ },
942
+ listTabs: async (profile) => {
943
+ const profileId = resolveProfileId(profile);
944
+ const profileState = profileStates.get(profileId);
945
+ return profileState === undefined ? [] : [...profileState.tabOrder];
946
+ },
947
+ openTab: async (url, profile) => {
948
+ const profileId = resolveProfileId(profile);
949
+ const profileState = getOrCreateProfileState(profileId);
950
+ const targetId = createTargetId(profileId, profileState.nextTargetNumber);
951
+ const page = await (await ensureBrowserContext()).newPage();
952
+ const telemetryState = createTargetTelemetryState();
953
+ const operationState = getOrCreateTargetOperationState(profileId, targetId, false);
954
+ attachTelemetryListeners(page, profileId, targetId, telemetryState, operationState);
955
+ await page.goto(url);
956
+
957
+ profileState.nextTargetNumber += 1;
958
+ profileState.tabs.set(targetId, { url, page });
959
+ profileState.tabOrder.push(targetId);
960
+ getOrCreateProfileTelemetryStates(profileId).set(targetId, telemetryState);
961
+ if (profileState.focusedTargetId === undefined) {
962
+ profileState.focusedTargetId = targetId;
963
+ }
964
+
965
+ return targetId;
966
+ },
967
+ focusTab: async (targetId, profile) => {
968
+ const profileId = resolveProfileId(profile);
969
+ const { profileState, tab } = requireTargetInProfile(profileId, targetId);
970
+ await tab.page.bringToFront();
971
+ profileState.focusedTargetId = targetId;
972
+ },
973
+ closeTab: async (targetId, profile) => {
974
+ const profileId = resolveProfileId(profile);
975
+ const { profileState, tab } = requireTargetInProfile(profileId, targetId);
976
+ await tab.page.close();
977
+
978
+ profileState.tabs.delete(targetId);
979
+ profileState.tabOrder = profileState.tabOrder.filter((existingTargetId) => existingTargetId !== targetId);
980
+ if (profileState.focusedTargetId === targetId) {
981
+ profileState.focusedTargetId = profileState.tabOrder[0];
982
+ }
983
+
984
+ const profileOperationStates = targetOperationStates.get(profileId);
985
+ profileOperationStates?.delete(targetId);
986
+ if (profileOperationStates !== undefined && profileOperationStates.size === 0) {
987
+ targetOperationStates.delete(profileId);
988
+ }
989
+
990
+ const profileTelemetryStates = targetTelemetryStates.get(profileId);
991
+ profileTelemetryStates?.delete(targetId);
992
+ if (profileTelemetryStates !== undefined && profileTelemetryStates.size === 0) {
993
+ targetTelemetryStates.delete(profileId);
994
+ }
995
+
996
+ if (profileState.tabOrder.length === 0) {
997
+ profileStates.delete(profileId);
998
+ }
999
+ },
1000
+ snapshot: async (targetId, profile) => {
1001
+ const profileId = resolveProfileId(profile);
1002
+ const tab = profileStates.get(profileId)?.tabs.get(targetId);
1003
+ if (tab === undefined) {
1004
+ return {
1005
+ kind: "remote-cdp",
1006
+ profile: profileId,
1007
+ targetId,
1008
+ endpoint,
1009
+ hasTarget: false
1010
+ };
1011
+ }
1012
+
1013
+ const requestSummaries =
1014
+ targetTelemetryStates
1015
+ .get(profileId)
1016
+ ?.get(targetId)
1017
+ ?.requestSummaries.map(cloneRequestSummary) ?? [];
1018
+
1019
+ return {
1020
+ kind: "remote-cdp",
1021
+ profile: profileId,
1022
+ targetId,
1023
+ endpoint,
1024
+ hasTarget: true,
1025
+ url: tab.page.url(),
1026
+ title: await tab.page.title(),
1027
+ html: await tab.page.content(),
1028
+ requestSummaries
1029
+ };
1030
+ },
1031
+ screenshot: async (targetId, profile) => {
1032
+ const profileId = resolveProfileId(profile);
1033
+ const tab = profileStates.get(profileId)?.tabs.get(targetId);
1034
+ if (tab === undefined) {
1035
+ return {
1036
+ kind: "remote-cdp",
1037
+ profile: profileId,
1038
+ targetId,
1039
+ endpoint,
1040
+ hasTarget: false
1041
+ };
1042
+ }
1043
+
1044
+ const screenshot = await capturePageScreenshot(tab.page);
1045
+ return {
1046
+ kind: "remote-cdp",
1047
+ profile: profileId,
1048
+ targetId,
1049
+ endpoint,
1050
+ hasTarget: true,
1051
+ ...screenshot
1052
+ };
1053
+ },
1054
+ act: async (action, targetId, profile) => {
1055
+ const profileId = resolveProfileId(profile);
1056
+ const tab = profileStates.get(profileId)?.tabs.get(targetId);
1057
+ if (tab === undefined) {
1058
+ return {
1059
+ actionType: action.type,
1060
+ profile: profileId,
1061
+ targetId,
1062
+ endpoint,
1063
+ targetKnown: false,
1064
+ ok: false,
1065
+ executed: false,
1066
+ error: `Unknown targetId: ${targetId} (profile: ${profileId})`
1067
+ };
1068
+ }
1069
+
1070
+ const payload = action.payload;
1071
+ const operationState = getOrCreateTargetOperationState(profileId, targetId);
1072
+ const baseResult = {
1073
+ actionType: action.type,
1074
+ profile: profileId,
1075
+ targetId,
1076
+ endpoint,
1077
+ targetKnown: true
1078
+ };
1079
+
1080
+ const performAction = async (): Promise<{
1081
+ ok: boolean;
1082
+ executed: boolean;
1083
+ error?: string;
1084
+ data?: Record<string, unknown>;
1085
+ }> => {
1086
+ switch (action.type) {
1087
+ case "navigate":
1088
+ case "goto": {
1089
+ const nextUrl = readActionPayloadString(payload, "url");
1090
+ if (nextUrl === undefined) {
1091
+ return {
1092
+ ok: false,
1093
+ executed: false,
1094
+ error: "action.payload.url is required for navigate action."
1095
+ };
1096
+ }
1097
+
1098
+ await tab.page.goto(nextUrl);
1099
+ tab.url = nextUrl;
1100
+ return { ok: true, executed: true };
1101
+ }
1102
+ case "click": {
1103
+ const selector = readActionPayloadString(payload, "selector");
1104
+ if (selector === undefined) {
1105
+ return {
1106
+ ok: false,
1107
+ executed: false,
1108
+ error: "action.payload.selector is required for click action."
1109
+ };
1110
+ }
1111
+
1112
+ const locator = tab.page.locator(selector);
1113
+ if (operationState.uploadFiles.length > 0) {
1114
+ const setInputFilesMethod = getObjectMethod(locator, "setInputFiles");
1115
+ if (typeof setInputFilesMethod === "function") {
1116
+ await setInputFilesMethod.call(locator, [...operationState.uploadFiles]);
1117
+ operationState.uploadFiles = [];
1118
+ return { ok: true, executed: true };
1119
+ }
1120
+ }
1121
+
1122
+ await locator.click();
1123
+ return { ok: true, executed: true };
1124
+ }
1125
+ case "fill": {
1126
+ const selector = readActionPayloadString(payload, "selector");
1127
+ const value = readActionPayloadString(payload, "value");
1128
+ if (selector === undefined || value === undefined) {
1129
+ return {
1130
+ ok: false,
1131
+ executed: false,
1132
+ error: "action.payload.selector and action.payload.value are required for fill action."
1133
+ };
1134
+ }
1135
+
1136
+ await tab.page.locator(selector).fill(value);
1137
+ return { ok: true, executed: true };
1138
+ }
1139
+ case "type": {
1140
+ const selector = readActionPayloadString(payload, "selector");
1141
+ const text = readActionPayloadString(payload, "text");
1142
+ if (selector === undefined || text === undefined) {
1143
+ return {
1144
+ ok: false,
1145
+ executed: false,
1146
+ error: "action.payload.selector and action.payload.text are required for type action."
1147
+ };
1148
+ }
1149
+
1150
+ await tab.page.locator(selector).type(text);
1151
+ return { ok: true, executed: true };
1152
+ }
1153
+ case "press": {
1154
+ const key = readActionPayloadString(payload, "key");
1155
+ if (key === undefined || tab.page.keyboard === undefined) {
1156
+ return {
1157
+ ok: false,
1158
+ executed: false,
1159
+ error: "action.payload.key is required for press action."
1160
+ };
1161
+ }
1162
+
1163
+ await tab.page.keyboard.press(key);
1164
+ return { ok: true, executed: true };
1165
+ }
1166
+ case "domQuery": {
1167
+ const selector = readActionPayloadString(payload, "selector");
1168
+ if (selector === undefined) {
1169
+ return {
1170
+ ok: false,
1171
+ executed: false,
1172
+ error: "action.payload.selector is required for domQuery action."
1173
+ };
1174
+ }
1175
+
1176
+ const customDomQueryMethod = getObjectMethod(tab.page, "domQuery");
1177
+ if (typeof customDomQueryMethod === "function") {
1178
+ const customResult = await customDomQueryMethod.call(tab.page, selector);
1179
+ return {
1180
+ ok: true,
1181
+ executed: true,
1182
+ data: isObjectRecord(customResult)
1183
+ ? customResult
1184
+ : {
1185
+ selector,
1186
+ found: false
1187
+ }
1188
+ };
1189
+ }
1190
+
1191
+ const queryResult = await evaluateInPage<Record<string, unknown>>(
1192
+ tab.page,
1193
+ (rawArg) => {
1194
+ const selectorValue =
1195
+ rawArg !== null &&
1196
+ typeof rawArg === "object" &&
1197
+ typeof (rawArg as { selector?: unknown }).selector === "string"
1198
+ ? (rawArg as { selector: string }).selector
1199
+ : "";
1200
+ const element = selectorValue.length > 0 ? document.querySelector(selectorValue) : null;
1201
+ if (element === null) {
1202
+ return {
1203
+ selector: selectorValue,
1204
+ found: false
1205
+ };
1206
+ }
1207
+
1208
+ const attributes: Record<string, string> = {};
1209
+ for (const attribute of Array.from(element.attributes)) {
1210
+ attributes[attribute.name] = attribute.value;
1211
+ }
1212
+
1213
+ return {
1214
+ selector: selectorValue,
1215
+ found: true,
1216
+ node: {
1217
+ tagName: element.tagName.toLowerCase(),
1218
+ id: element.id || undefined,
1219
+ className: element.className || undefined,
1220
+ text: (element.textContent || "").trim().slice(0, 300),
1221
+ attributes
1222
+ }
1223
+ };
1224
+ },
1225
+ { selector }
1226
+ );
1227
+
1228
+ return {
1229
+ ok: true,
1230
+ executed: true,
1231
+ data: isObjectRecord(queryResult)
1232
+ ? queryResult
1233
+ : {
1234
+ selector,
1235
+ found: false
1236
+ }
1237
+ };
1238
+ }
1239
+ case "domQueryAll": {
1240
+ const selector = readActionPayloadString(payload, "selector");
1241
+ if (selector === undefined) {
1242
+ return {
1243
+ ok: false,
1244
+ executed: false,
1245
+ error: "action.payload.selector is required for domQueryAll action."
1246
+ };
1247
+ }
1248
+
1249
+ const customDomQueryAllMethod = getObjectMethod(tab.page, "domQueryAll");
1250
+ if (typeof customDomQueryAllMethod === "function") {
1251
+ const customResult = await customDomQueryAllMethod.call(tab.page, selector);
1252
+ return {
1253
+ ok: true,
1254
+ executed: true,
1255
+ data: isObjectRecord(customResult)
1256
+ ? customResult
1257
+ : {
1258
+ selector,
1259
+ count: 0,
1260
+ nodes: []
1261
+ }
1262
+ };
1263
+ }
1264
+
1265
+ const queryResult = await evaluateInPage<Record<string, unknown>>(
1266
+ tab.page,
1267
+ (rawArg) => {
1268
+ const selectorValue =
1269
+ rawArg !== null &&
1270
+ typeof rawArg === "object" &&
1271
+ typeof (rawArg as { selector?: unknown }).selector === "string"
1272
+ ? (rawArg as { selector: string }).selector
1273
+ : "";
1274
+ const elements = selectorValue.length > 0 ? document.querySelectorAll(selectorValue) : [];
1275
+ const nodes = Array.from(elements).map((element, index) => {
1276
+ const attributes: Record<string, string> = {};
1277
+ for (const attribute of Array.from(element.attributes)) {
1278
+ attributes[attribute.name] = attribute.value;
1279
+ }
1280
+
1281
+ return {
1282
+ index,
1283
+ tagName: element.tagName.toLowerCase(),
1284
+ id: element.id || undefined,
1285
+ className: element.className || undefined,
1286
+ text: (element.textContent || "").trim().slice(0, 300),
1287
+ attributes
1288
+ };
1289
+ });
1290
+
1291
+ return {
1292
+ selector: selectorValue,
1293
+ count: nodes.length,
1294
+ nodes
1295
+ };
1296
+ },
1297
+ { selector }
1298
+ );
1299
+
1300
+ return {
1301
+ ok: true,
1302
+ executed: true,
1303
+ data: isObjectRecord(queryResult)
1304
+ ? queryResult
1305
+ : {
1306
+ selector,
1307
+ count: 0,
1308
+ nodes: []
1309
+ }
1310
+ };
1311
+ }
1312
+ case "elementScreenshot": {
1313
+ const selector = readActionPayloadString(payload, "selector");
1314
+ if (selector === undefined) {
1315
+ return {
1316
+ ok: false,
1317
+ executed: false,
1318
+ error: "action.payload.selector is required for elementScreenshot action."
1319
+ };
1320
+ }
1321
+
1322
+ const customElementScreenshotMethod = getObjectMethod(tab.page, "elementScreenshot");
1323
+ if (typeof customElementScreenshotMethod === "function") {
1324
+ const customResult = await customElementScreenshotMethod.call(tab.page, selector);
1325
+ return {
1326
+ ok: true,
1327
+ executed: true,
1328
+ data: isObjectRecord(customResult)
1329
+ ? customResult
1330
+ : {
1331
+ selector,
1332
+ found: false
1333
+ }
1334
+ };
1335
+ }
1336
+
1337
+ const found = await evaluateInPage<boolean>(
1338
+ tab.page,
1339
+ (rawArg) => {
1340
+ const selectorValue =
1341
+ rawArg !== null &&
1342
+ typeof rawArg === "object" &&
1343
+ typeof (rawArg as { selector?: unknown }).selector === "string"
1344
+ ? (rawArg as { selector: string }).selector
1345
+ : "";
1346
+ return selectorValue.length > 0 && document.querySelector(selectorValue) !== null;
1347
+ },
1348
+ { selector }
1349
+ );
1350
+ if (!found) {
1351
+ return {
1352
+ ok: true,
1353
+ executed: true,
1354
+ data: {
1355
+ selector,
1356
+ found: false
1357
+ }
1358
+ };
1359
+ }
1360
+
1361
+ const locator = tab.page.locator(selector);
1362
+ const locatorScreenshotMethod = getObjectMethod(locator, "screenshot");
1363
+ if (typeof locatorScreenshotMethod !== "function") {
1364
+ return {
1365
+ ok: true,
1366
+ executed: false
1367
+ };
1368
+ }
1369
+
1370
+ const rawScreenshot = await locatorScreenshotMethod.call(locator, { type: "png" });
1371
+ const parsedScreenshot = readScreenshotImage(rawScreenshot);
1372
+ if (parsedScreenshot === undefined) {
1373
+ return {
1374
+ ok: false,
1375
+ executed: false,
1376
+ error: "Unable to parse element screenshot payload."
1377
+ };
1378
+ }
1379
+
1380
+ return {
1381
+ ok: true,
1382
+ executed: true,
1383
+ data: {
1384
+ selector,
1385
+ found: true,
1386
+ ...parsedScreenshot
1387
+ }
1388
+ };
1389
+ }
1390
+ case "a11ySnapshot": {
1391
+ const selector = readActionPayloadString(payload, "selector");
1392
+ const customA11ySnapshotMethod = getObjectMethod(tab.page, "a11ySnapshot");
1393
+ if (typeof customA11ySnapshotMethod === "function") {
1394
+ const customResult = await customA11ySnapshotMethod.call(tab.page, selector);
1395
+ return {
1396
+ ok: true,
1397
+ executed: true,
1398
+ data: isObjectRecord(customResult)
1399
+ ? customResult
1400
+ : {
1401
+ found: false
1402
+ }
1403
+ };
1404
+ }
1405
+
1406
+ const accessibilityValue =
1407
+ typeof tab.page === "object" && tab.page !== null
1408
+ ? (tab.page as Record<string, unknown>).accessibility
1409
+ : undefined;
1410
+ const accessibilitySnapshotMethod = getObjectMethod(accessibilityValue, "snapshot");
1411
+ if (typeof accessibilitySnapshotMethod === "function") {
1412
+ const snapshot = await accessibilitySnapshotMethod.call(accessibilityValue, {});
1413
+ return {
1414
+ ok: true,
1415
+ executed: true,
1416
+ data: {
1417
+ selector,
1418
+ found: true,
1419
+ snapshot
1420
+ }
1421
+ };
1422
+ }
1423
+
1424
+ const fallbackSnapshot = await evaluateInPage<Record<string, unknown>>(
1425
+ tab.page,
1426
+ (rawArg) => {
1427
+ const selectorValue =
1428
+ rawArg !== null &&
1429
+ typeof rawArg === "object" &&
1430
+ typeof (rawArg as { selector?: unknown }).selector === "string"
1431
+ ? (rawArg as { selector: string }).selector
1432
+ : "";
1433
+ const root =
1434
+ selectorValue.length > 0
1435
+ ? document.querySelector(selectorValue)
1436
+ : document.body ?? document.documentElement;
1437
+ if (root === null) {
1438
+ return {
1439
+ selector: selectorValue,
1440
+ found: false
1441
+ };
1442
+ }
1443
+
1444
+ const build = (element: Element, depth: number): Record<string, unknown> => {
1445
+ const role =
1446
+ element.getAttribute("role") ??
1447
+ (element.tagName.toLowerCase() === "a"
1448
+ ? "link"
1449
+ : element.tagName.toLowerCase() === "button"
1450
+ ? "button"
1451
+ : element.tagName.toLowerCase() === "input"
1452
+ ? "textbox"
1453
+ : "generic");
1454
+ const name =
1455
+ element.getAttribute("aria-label") ??
1456
+ element.getAttribute("alt") ??
1457
+ (element.textContent || "").trim().slice(0, 120);
1458
+ if (depth >= 5) {
1459
+ return {
1460
+ role,
1461
+ ...(name.length > 0 ? { name } : {})
1462
+ };
1463
+ }
1464
+
1465
+ const children = Array.from(element.children)
1466
+ .slice(0, 30)
1467
+ .map((child) => build(child, depth + 1));
1468
+ return {
1469
+ role,
1470
+ ...(name.length > 0 ? { name } : {}),
1471
+ ...(children.length > 0 ? { children } : {})
1472
+ };
1473
+ };
1474
+
1475
+ return {
1476
+ selector: selectorValue,
1477
+ found: true,
1478
+ snapshot: build(root, 0)
1479
+ };
1480
+ },
1481
+ { selector: selector ?? "" }
1482
+ );
1483
+
1484
+ return {
1485
+ ok: true,
1486
+ executed: true,
1487
+ data: isObjectRecord(fallbackSnapshot)
1488
+ ? fallbackSnapshot
1489
+ : {
1490
+ selector,
1491
+ found: false
1492
+ }
1493
+ };
1494
+ }
1495
+ case "cookieGet": {
1496
+ const cookieName = readActionPayloadString(payload, "name");
1497
+ const customCookieGetMethod = getObjectMethod(tab.page, "cookieGet");
1498
+ if (typeof customCookieGetMethod === "function") {
1499
+ const customResult = await customCookieGetMethod.call(tab.page, cookieName);
1500
+ return {
1501
+ ok: true,
1502
+ executed: true,
1503
+ data: isObjectRecord(customResult)
1504
+ ? customResult
1505
+ : {
1506
+ cookies: []
1507
+ }
1508
+ };
1509
+ }
1510
+
1511
+ const contextMethod = getObjectMethod(tab.page, "context");
1512
+ if (typeof contextMethod !== "function") {
1513
+ return {
1514
+ ok: true,
1515
+ executed: false
1516
+ };
1517
+ }
1518
+
1519
+ const context = await contextMethod.call(tab.page);
1520
+ const cookiesMethod = getObjectMethod(context, "cookies");
1521
+ if (typeof cookiesMethod !== "function") {
1522
+ return {
1523
+ ok: true,
1524
+ executed: false
1525
+ };
1526
+ }
1527
+
1528
+ let rawCookies: unknown;
1529
+ try {
1530
+ rawCookies = await cookiesMethod.call(context, [tab.page.url()]);
1531
+ } catch {
1532
+ rawCookies = await cookiesMethod.call(context);
1533
+ }
1534
+ const cookies = normalizeCookies(rawCookies).filter(
1535
+ (cookie) => cookieName === undefined || cookie.name === cookieName
1536
+ );
1537
+ return {
1538
+ ok: true,
1539
+ executed: true,
1540
+ data: {
1541
+ cookies,
1542
+ ...(cookieName !== undefined ? { name: cookieName } : {})
1543
+ }
1544
+ };
1545
+ }
1546
+ case "cookieSet": {
1547
+ const cookieName = readActionPayloadString(payload, "name");
1548
+ const cookieValue = readActionPayloadString(payload, "value");
1549
+ const cookieUrl = readActionPayloadString(payload, "url") ?? tab.page.url();
1550
+ if (cookieName === undefined || cookieValue === undefined) {
1551
+ return {
1552
+ ok: false,
1553
+ executed: false,
1554
+ error: "action.payload.name and action.payload.value are required for cookieSet action."
1555
+ };
1556
+ }
1557
+
1558
+ const customCookieSetMethod = getObjectMethod(tab.page, "cookieSet");
1559
+ if (typeof customCookieSetMethod === "function") {
1560
+ const customResult = await customCookieSetMethod.call(tab.page, {
1561
+ name: cookieName,
1562
+ value: cookieValue,
1563
+ url: cookieUrl
1564
+ });
1565
+ return {
1566
+ ok: true,
1567
+ executed: true,
1568
+ data: isObjectRecord(customResult)
1569
+ ? customResult
1570
+ : {
1571
+ set: true,
1572
+ cookie: {
1573
+ name: cookieName,
1574
+ value: cookieValue,
1575
+ url: cookieUrl
1576
+ }
1577
+ }
1578
+ };
1579
+ }
1580
+
1581
+ const contextMethod = getObjectMethod(tab.page, "context");
1582
+ if (typeof contextMethod !== "function") {
1583
+ return {
1584
+ ok: true,
1585
+ executed: false
1586
+ };
1587
+ }
1588
+
1589
+ const context = await contextMethod.call(tab.page);
1590
+ const addCookiesMethod = getObjectMethod(context, "addCookies");
1591
+ if (typeof addCookiesMethod !== "function") {
1592
+ return {
1593
+ ok: true,
1594
+ executed: false
1595
+ };
1596
+ }
1597
+
1598
+ await addCookiesMethod.call(context, [
1599
+ {
1600
+ name: cookieName,
1601
+ value: cookieValue,
1602
+ url: cookieUrl
1603
+ }
1604
+ ]);
1605
+
1606
+ return {
1607
+ ok: true,
1608
+ executed: true,
1609
+ data: {
1610
+ set: true,
1611
+ cookie: {
1612
+ name: cookieName,
1613
+ value: cookieValue,
1614
+ url: cookieUrl
1615
+ }
1616
+ }
1617
+ };
1618
+ }
1619
+ case "cookieClear": {
1620
+ const cookieName = readActionPayloadString(payload, "name");
1621
+ const customCookieClearMethod = getObjectMethod(tab.page, "cookieClear");
1622
+ if (typeof customCookieClearMethod === "function") {
1623
+ const customResult = await customCookieClearMethod.call(tab.page, cookieName);
1624
+ return {
1625
+ ok: true,
1626
+ executed: true,
1627
+ data: isObjectRecord(customResult)
1628
+ ? customResult
1629
+ : {
1630
+ cleared: true
1631
+ }
1632
+ };
1633
+ }
1634
+
1635
+ const contextMethod = getObjectMethod(tab.page, "context");
1636
+ if (typeof contextMethod !== "function") {
1637
+ return {
1638
+ ok: true,
1639
+ executed: false
1640
+ };
1641
+ }
1642
+
1643
+ const context = await contextMethod.call(tab.page);
1644
+ const clearCookiesMethod = getObjectMethod(context, "clearCookies");
1645
+ if (typeof clearCookiesMethod !== "function") {
1646
+ return {
1647
+ ok: true,
1648
+ executed: false
1649
+ };
1650
+ }
1651
+
1652
+ if (cookieName === undefined) {
1653
+ await clearCookiesMethod.call(context);
1654
+ return {
1655
+ ok: true,
1656
+ executed: true,
1657
+ data: {
1658
+ cleared: true,
1659
+ count: -1
1660
+ }
1661
+ };
1662
+ }
1663
+
1664
+ const cookiesMethod = getObjectMethod(context, "cookies");
1665
+ const addCookiesMethod = getObjectMethod(context, "addCookies");
1666
+ if (typeof cookiesMethod !== "function" || typeof addCookiesMethod !== "function") {
1667
+ return {
1668
+ ok: true,
1669
+ executed: false
1670
+ };
1671
+ }
1672
+
1673
+ let rawCookies: unknown;
1674
+ try {
1675
+ rawCookies = await cookiesMethod.call(context, [tab.page.url()]);
1676
+ } catch {
1677
+ rawCookies = await cookiesMethod.call(context);
1678
+ }
1679
+ const currentCookies = normalizeCookies(rawCookies);
1680
+ const keptCookieInputs = currentCookies
1681
+ .filter((cookie) => cookie.name !== cookieName)
1682
+ .map((cookie) => toCookieInput(cookie))
1683
+ .filter((cookie): cookie is Record<string, unknown> => cookie !== undefined);
1684
+ const removedCount = currentCookies.length - keptCookieInputs.length;
1685
+
1686
+ await clearCookiesMethod.call(context);
1687
+ if (keptCookieInputs.length > 0) {
1688
+ await addCookiesMethod.call(context, keptCookieInputs);
1689
+ }
1690
+
1691
+ return {
1692
+ ok: true,
1693
+ executed: true,
1694
+ data: {
1695
+ cleared: true,
1696
+ name: cookieName,
1697
+ count: removedCount
1698
+ }
1699
+ };
1700
+ }
1701
+ case "storageGet": {
1702
+ const scope = parseStorageScope(readActionPayloadString(payload, "scope"));
1703
+ const key = readActionPayloadString(payload, "key");
1704
+ if (scope === undefined || key === undefined) {
1705
+ return {
1706
+ ok: false,
1707
+ executed: false,
1708
+ error: "action.payload.scope and action.payload.key are required for storageGet action."
1709
+ };
1710
+ }
1711
+
1712
+ const customStorageGetMethod = getObjectMethod(tab.page, "storageGet");
1713
+ if (typeof customStorageGetMethod === "function") {
1714
+ const customResult = await customStorageGetMethod.call(tab.page, scope, key);
1715
+ return {
1716
+ ok: true,
1717
+ executed: true,
1718
+ data: isObjectRecord(customResult)
1719
+ ? customResult
1720
+ : {
1721
+ scope,
1722
+ key,
1723
+ exists: false
1724
+ }
1725
+ };
1726
+ }
1727
+
1728
+ const result = await evaluateInPage<Record<string, unknown>>(
1729
+ tab.page,
1730
+ (rawArg) => {
1731
+ const scopeValue =
1732
+ rawArg !== null &&
1733
+ typeof rawArg === "object" &&
1734
+ typeof (rawArg as { scope?: unknown }).scope === "string"
1735
+ ? (rawArg as { scope: string }).scope
1736
+ : "local";
1737
+ const keyValue =
1738
+ rawArg !== null &&
1739
+ typeof rawArg === "object" &&
1740
+ typeof (rawArg as { key?: unknown }).key === "string"
1741
+ ? (rawArg as { key: string }).key
1742
+ : "";
1743
+ const storage = scopeValue === "session" ? window.sessionStorage : window.localStorage;
1744
+ const value = storage.getItem(keyValue);
1745
+ return {
1746
+ scope: scopeValue,
1747
+ key: keyValue,
1748
+ exists: value !== null,
1749
+ ...(value !== null ? { value } : {})
1750
+ };
1751
+ },
1752
+ { scope, key }
1753
+ );
1754
+
1755
+ return {
1756
+ ok: true,
1757
+ executed: true,
1758
+ data: isObjectRecord(result)
1759
+ ? result
1760
+ : {
1761
+ scope,
1762
+ key,
1763
+ exists: false
1764
+ }
1765
+ };
1766
+ }
1767
+ case "storageSet": {
1768
+ const scope = parseStorageScope(readActionPayloadString(payload, "scope"));
1769
+ const key = readActionPayloadString(payload, "key");
1770
+ const value = readActionPayloadString(payload, "value");
1771
+ if (scope === undefined || key === undefined || value === undefined) {
1772
+ return {
1773
+ ok: false,
1774
+ executed: false,
1775
+ error: "action.payload.scope, action.payload.key and action.payload.value are required for storageSet action."
1776
+ };
1777
+ }
1778
+
1779
+ const customStorageSetMethod = getObjectMethod(tab.page, "storageSet");
1780
+ if (typeof customStorageSetMethod === "function") {
1781
+ const customResult = await customStorageSetMethod.call(tab.page, scope, key, value);
1782
+ return {
1783
+ ok: true,
1784
+ executed: true,
1785
+ data: isObjectRecord(customResult)
1786
+ ? customResult
1787
+ : {
1788
+ scope,
1789
+ key,
1790
+ value,
1791
+ set: true
1792
+ }
1793
+ };
1794
+ }
1795
+
1796
+ await evaluateInPage(
1797
+ tab.page,
1798
+ (rawArg) => {
1799
+ const scopeValue =
1800
+ rawArg !== null &&
1801
+ typeof rawArg === "object" &&
1802
+ typeof (rawArg as { scope?: unknown }).scope === "string"
1803
+ ? (rawArg as { scope: string }).scope
1804
+ : "local";
1805
+ const keyValue =
1806
+ rawArg !== null &&
1807
+ typeof rawArg === "object" &&
1808
+ typeof (rawArg as { key?: unknown }).key === "string"
1809
+ ? (rawArg as { key: string }).key
1810
+ : "";
1811
+ const valueText =
1812
+ rawArg !== null &&
1813
+ typeof rawArg === "object" &&
1814
+ typeof (rawArg as { value?: unknown }).value === "string"
1815
+ ? (rawArg as { value: string }).value
1816
+ : "";
1817
+ const storage = scopeValue === "session" ? window.sessionStorage : window.localStorage;
1818
+ storage.setItem(keyValue, valueText);
1819
+ },
1820
+ { scope, key, value }
1821
+ );
1822
+
1823
+ return {
1824
+ ok: true,
1825
+ executed: true,
1826
+ data: {
1827
+ scope,
1828
+ key,
1829
+ value,
1830
+ set: true
1831
+ }
1832
+ };
1833
+ }
1834
+ case "frameList": {
1835
+ const customFrameListMethod = getObjectMethod(tab.page, "frameList");
1836
+ if (typeof customFrameListMethod === "function") {
1837
+ const customResult = await customFrameListMethod.call(tab.page);
1838
+ return {
1839
+ ok: true,
1840
+ executed: true,
1841
+ data: isObjectRecord(customResult)
1842
+ ? customResult
1843
+ : {
1844
+ frames: []
1845
+ }
1846
+ };
1847
+ }
1848
+
1849
+ const framesMethod = getObjectMethod(tab.page, "frames");
1850
+ if (typeof framesMethod !== "function") {
1851
+ return {
1852
+ ok: true,
1853
+ executed: false
1854
+ };
1855
+ }
1856
+
1857
+ const rawFrames = await framesMethod.call(tab.page);
1858
+ if (!Array.isArray(rawFrames)) {
1859
+ return {
1860
+ ok: true,
1861
+ executed: true,
1862
+ data: {
1863
+ frames: []
1864
+ }
1865
+ };
1866
+ }
1867
+
1868
+ const mainFrameMethod = getObjectMethod(tab.page, "mainFrame");
1869
+ const mainFrame = typeof mainFrameMethod === "function" ? await mainFrameMethod.call(tab.page) : undefined;
1870
+ const frames = rawFrames.map((frame, index) => {
1871
+ const name = readObjectMethod<string>(frame, "name");
1872
+ const url = readObjectMethod<string>(frame, "url") ?? "";
1873
+ return {
1874
+ frameId: `frame:${index}`,
1875
+ index,
1876
+ ...(typeof name === "string" && name.length > 0 ? { name } : {}),
1877
+ url,
1878
+ isMainFrame: frame === mainFrame
1879
+ };
1880
+ });
1881
+
1882
+ return {
1883
+ ok: true,
1884
+ executed: true,
1885
+ data: {
1886
+ frames
1887
+ }
1888
+ };
1889
+ }
1890
+ case "frameSnapshot": {
1891
+ const frameId = readActionPayloadString(payload, "frameId");
1892
+ if (frameId === undefined) {
1893
+ return {
1894
+ ok: false,
1895
+ executed: false,
1896
+ error: "action.payload.frameId is required for frameSnapshot action."
1897
+ };
1898
+ }
1899
+
1900
+ const customFrameSnapshotMethod = getObjectMethod(tab.page, "frameSnapshot");
1901
+ if (typeof customFrameSnapshotMethod === "function") {
1902
+ const customResult = await customFrameSnapshotMethod.call(tab.page, frameId);
1903
+ return {
1904
+ ok: true,
1905
+ executed: true,
1906
+ data: isObjectRecord(customResult)
1907
+ ? customResult
1908
+ : {
1909
+ frameId,
1910
+ found: false
1911
+ }
1912
+ };
1913
+ }
1914
+
1915
+ const frameIndex = parseFrameIndex(frameId);
1916
+ if (frameIndex === undefined) {
1917
+ return {
1918
+ ok: false,
1919
+ executed: false,
1920
+ error: `Invalid frameId: ${frameId}`
1921
+ };
1922
+ }
1923
+
1924
+ const framesMethod = getObjectMethod(tab.page, "frames");
1925
+ if (typeof framesMethod !== "function") {
1926
+ return {
1927
+ ok: true,
1928
+ executed: false
1929
+ };
1930
+ }
1931
+
1932
+ const rawFrames = await framesMethod.call(tab.page);
1933
+ if (!Array.isArray(rawFrames) || frameIndex >= rawFrames.length) {
1934
+ return {
1935
+ ok: true,
1936
+ executed: true,
1937
+ data: {
1938
+ frameId,
1939
+ found: false
1940
+ }
1941
+ };
1942
+ }
1943
+
1944
+ const frame = rawFrames[frameIndex];
1945
+ const contentMethod = getObjectMethod(frame, "content");
1946
+ if (typeof contentMethod !== "function") {
1947
+ return {
1948
+ ok: true,
1949
+ executed: false
1950
+ };
1951
+ }
1952
+
1953
+ const mainFrameMethod = getObjectMethod(tab.page, "mainFrame");
1954
+ const mainFrame = typeof mainFrameMethod === "function" ? await mainFrameMethod.call(tab.page) : undefined;
1955
+ const frameName = readObjectMethod<string>(frame, "name");
1956
+ const frameUrl = readObjectMethod<string>(frame, "url") ?? "";
1957
+ const frameHtml = await contentMethod.call(frame);
1958
+
1959
+ return {
1960
+ ok: true,
1961
+ executed: true,
1962
+ data: {
1963
+ frameId,
1964
+ index: frameIndex,
1965
+ found: true,
1966
+ ...(typeof frameName === "string" && frameName.length > 0 ? { name: frameName } : {}),
1967
+ url: frameUrl,
1968
+ isMainFrame: frame === mainFrame,
1969
+ html: typeof frameHtml === "string" ? frameHtml : ""
1970
+ }
1971
+ };
1972
+ }
1973
+ default:
1974
+ return {
1975
+ ok: true,
1976
+ executed: false
1977
+ };
1978
+ }
1979
+ };
1980
+
1981
+ try {
1982
+ return {
1983
+ ...baseResult,
1984
+ ...(await performAction())
1985
+ };
1986
+ } catch (error) {
1987
+ return {
1988
+ ...baseResult,
1989
+ ok: false,
1990
+ executed: false,
1991
+ error: toErrorMessage(error)
1992
+ };
1993
+ }
1994
+ },
1995
+ armUpload: async (targetId, files, profile) => {
1996
+ const profileId = resolveProfileId(profile);
1997
+ const operationState = getOrCreateTargetOperationState(profileId, targetId);
1998
+ operationState.uploadFiles = [...files];
1999
+ },
2000
+ armDialog: async (targetId, profile) => {
2001
+ const profileId = resolveProfileId(profile);
2002
+ const operationState = getOrCreateTargetOperationState(profileId, targetId);
2003
+ operationState.dialogArmedCount += 1;
2004
+ },
2005
+ waitDownload: async (targetId, profile) => {
2006
+ const profileId = resolveProfileId(profile);
2007
+ const { tab } = requireTargetInProfile(profileId, targetId);
2008
+ const operationState = getOrCreateTargetOperationState(profileId, targetId);
2009
+ const download = await ensureDownloadInFlight(profileId, targetId, tab, operationState);
2010
+
2011
+ return {
2012
+ path: download.path,
2013
+ profile: profileId,
2014
+ targetId,
2015
+ endpoint,
2016
+ uploadFiles: [...operationState.uploadFiles],
2017
+ dialogArmedCount: operationState.dialogArmedCount,
2018
+ triggerCount: operationState.triggerCount,
2019
+ ...(download.suggestedFilename !== undefined
2020
+ ? { suggestedFilename: download.suggestedFilename }
2021
+ : {}),
2022
+ ...(download.url !== undefined ? { url: download.url } : {}),
2023
+ ...(download.mimeType !== undefined ? { mimeType: download.mimeType } : {})
2024
+ };
2025
+ },
2026
+ triggerDownload: async (targetId, profile) => {
2027
+ const profileId = resolveProfileId(profile);
2028
+ const { tab } = requireTargetInProfile(profileId, targetId);
2029
+ const operationState = getOrCreateTargetOperationState(profileId, targetId);
2030
+ operationState.triggerCount += 1;
2031
+ void ensureDownloadInFlight(profileId, targetId, tab, operationState);
2032
+ },
2033
+ getConsoleEntries: (targetId, profile) => {
2034
+ const telemetryState = findTelemetryState(targetId, profile);
2035
+ return telemetryState === undefined ? [] : telemetryState.consoleEntries.map(cloneConsoleEntry);
2036
+ },
2037
+ getNetworkResponseBody: (requestId, targetId, profile) => {
2038
+ const body = findTelemetryState(targetId, profile)?.networkResponseBodies.get(requestId);
2039
+ return body === undefined ? undefined : { ...body };
2040
+ }
2041
+ };
2042
+ }