@flrande/browserctl 0.1.0-dev.7.1

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