mcp-browser-dev-tools 0.2.2 → 0.3.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.
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  exportHarLikeSummary,
3
3
  filterConsoleMessages,
4
+ InFlightRequests,
4
5
  summarizeNetworkRequests,
5
6
  } from "./session-events.mjs";
6
7
  import { DEFAULT_CDP_BASE_URL } from "./config.mjs";
@@ -13,6 +14,61 @@ import {
13
14
  } from "./page-context.mjs";
14
15
  import { buildCdpKeyEvents } from "./keyboard.mjs";
15
16
  import { sendCheckedInput } from "./input-delivery.mjs";
17
+ import {
18
+ applyNetworkOptions,
19
+ describeNetworkState,
20
+ inNetworkTurn,
21
+ mockHeaders,
22
+ takeMatchingRule,
23
+ } from "./network-control.mjs";
24
+ import {
25
+ FrameKeys,
26
+ probeScope,
27
+ restoreFrameSelector,
28
+ addFrameSnapshots,
29
+ frameElementSnapshot,
30
+ parseFrameRef,
31
+ shiftFramePoints,
32
+ unknownFrame,
33
+ takeFileTarget,
34
+ assertFileInput,
35
+ uploadResult,
36
+ describePointer,
37
+ dragEnd,
38
+ wheelScroll,
39
+ dragPath,
40
+ pointerFields,
41
+ takeNextRef,
42
+ } from "./page-context.mjs";
43
+
44
+ // How long a drag waits after its first move for the page to start an HTML5
45
+ // drag, and the longest a drag's interception stays open.
46
+ const DRAG_START_MS = 100;
47
+ // The categories DevTools' Performance panel records, so a trace opens there
48
+ // with its timeline, call stacks, and CPU profile.
49
+ const TRACE_CATEGORIES = [
50
+ "-*",
51
+ "devtools.timeline",
52
+ "disabled-by-default-devtools.timeline",
53
+ "disabled-by-default-devtools.timeline.frame",
54
+ "disabled-by-default-devtools.timeline.stack",
55
+ "v8.execute",
56
+ "disabled-by-default-v8.cpu_profiler",
57
+ "blink.console",
58
+ "blink.user_timing",
59
+ "latencyInfo",
60
+ "loading",
61
+ ];
62
+ const TRACE_COMPLETE_MS = 60_000;
63
+ // How long a click may take to open a file chooser.
64
+ const FILE_CHOOSER_MS = 2000;
65
+ const DRAG_SESSION_MS = 30_000;
66
+
67
+ function sleep(ms) {
68
+ return new Promise((resolve) => {
69
+ setTimeout(resolve, ms);
70
+ });
71
+ }
16
72
 
17
73
  function toErrorMessage(error) {
18
74
  return error instanceof Error ? error.message : String(error);
@@ -385,6 +441,7 @@ export class CdpSession {
385
441
  this.eventBufferSize = options.eventBufferSize ?? 200;
386
442
  this.onClosed = options.onClosed ?? null;
387
443
  this.bufferedEvents = [];
444
+ this.inFlight = new InFlightRequests();
388
445
  this.pending = new Map();
389
446
  this.nextMessageId = 1;
390
447
  this.connectedAt = new Date().toISOString();
@@ -394,6 +451,12 @@ export class CdpSession {
394
451
  this.lastNavigationAt = null;
395
452
  this.lastReloadAt = null;
396
453
  this.viewportOverride = null;
454
+ // Frames: child sessions of cross-site iframes (attached in flatten
455
+ // mode, by session id), the default execution context of each frame,
456
+ // keyed by session and frame id, and the frame keys refs use.
457
+ this.frameSessions = new Map();
458
+ this.frameContexts = new Map();
459
+ this.frameKeys = new FrameKeys();
397
460
  }
398
461
 
399
462
  markClosed() {
@@ -467,6 +530,14 @@ export class CdpSession {
467
530
  this.send("Log.enable"),
468
531
  this.send("Network.enable"),
469
532
  ]);
533
+ // Chrome's performance counters count from here, so get_performance's
534
+ // layout, style, and script times cover the whole session.
535
+ await this.send("Performance.enable")
536
+ .then(() => {
537
+ this.performanceEnabled = true;
538
+ })
539
+ .catch(() => {});
540
+ await this.autoAttachFrames(null);
470
541
 
471
542
  await this.installInputRecorder();
472
543
  await this.seedBufferedState();
@@ -500,9 +571,247 @@ export class CdpSession {
500
571
  return;
501
572
  }
502
573
 
574
+ // Events of a cross-site iframe's session only keep the frame records,
575
+ // except a file chooser opened there, which an upload waits for.
576
+ if (message.sessionId) {
577
+ if (message.method === "Page.fileChooserOpened") {
578
+ this.resolveEventWaiters(message.method, {
579
+ ...message.params,
580
+ sessionId: message.sessionId,
581
+ });
582
+ }
583
+ this.trackFrameEvent(
584
+ message.method,
585
+ message.params ?? {},
586
+ message.sessionId,
587
+ );
588
+ return;
589
+ }
590
+
591
+ this.trackFrameEvent(message.method, message.params ?? {}, null);
503
592
  this.bufferEvent(message.method, message.params ?? {});
504
593
  }
505
594
 
595
+ // Cross-site iframes run in their own targets; attaching to them in
596
+ // flatten mode gives a session on this connection for each, and doing
597
+ // the same in each such session reaches iframes nested in them.
598
+ async autoAttachFrames(sessionId) {
599
+ await this.send(
600
+ "Target.setAutoAttach",
601
+ { autoAttach: true, waitForDebuggerOnStart: false, flatten: true },
602
+ sessionId,
603
+ ).catch(() => {});
604
+ }
605
+
606
+ trackFrameEvent(method, params, sessionId) {
607
+ const scope = sessionId ?? "";
608
+ if (method === "Runtime.executionContextCreated") {
609
+ const { id, auxData } = params.context ?? {};
610
+ if (auxData?.isDefault && auxData.frameId) {
611
+ this.frameContexts.set(`${scope}:${auxData.frameId}`, id);
612
+ // A frame document that was already loaded gets the recorder late
613
+ // (a new one has it from its start, which this leaves alone).
614
+ this.send(
615
+ "Runtime.evaluate",
616
+ {
617
+ expression: buildInputRecorderExpression(false),
618
+ contextId: id,
619
+ awaitPromise: false,
620
+ returnByValue: true,
621
+ },
622
+ sessionId,
623
+ ).catch(() => {});
624
+ }
625
+ } else if (method === "Runtime.executionContextDestroyed") {
626
+ for (const [key, id] of this.frameContexts) {
627
+ if (key.startsWith(`${scope}:`) && id === params.executionContextId) {
628
+ this.frameContexts.delete(key);
629
+ }
630
+ }
631
+ } else if (method === "Runtime.executionContextsCleared") {
632
+ for (const key of Array.from(this.frameContexts.keys())) {
633
+ if (key.startsWith(`${scope}:`)) {
634
+ this.frameContexts.delete(key);
635
+ }
636
+ }
637
+ } else if (
638
+ method === "Target.attachedToTarget" &&
639
+ params.targetInfo?.type === "iframe"
640
+ ) {
641
+ const child = params.sessionId;
642
+ this.frameSessions.set(child, {
643
+ sessionId: child,
644
+ frameId: params.targetInfo.targetId,
645
+ parentSessionId: sessionId,
646
+ });
647
+ for (const enable of ["Runtime.enable", "DOM.enable", "Page.enable"]) {
648
+ this.send(enable, {}, child).catch(() => {});
649
+ }
650
+ void this.installInputRecorder(child);
651
+ void this.autoAttachFrames(child);
652
+ } else if (method === "Target.detachedFromTarget") {
653
+ this.frameSessions.delete(params.sessionId);
654
+ }
655
+ }
656
+
657
+ // The tab's iframes, outermost first: the top target's own frames, then
658
+ // each cross-site iframe's target and its own frames.
659
+ async listFrames() {
660
+ const frames = [];
661
+ const walk = (node, sessionId) => {
662
+ for (const child of node.childFrames ?? []) {
663
+ frames.push({
664
+ id: child.frame.id,
665
+ url: child.frame.url,
666
+ sessionId,
667
+ root: false,
668
+ });
669
+ walk(child, sessionId);
670
+ }
671
+ };
672
+ const top = await this.send("Page.getFrameTree");
673
+ walk(top.frameTree, null);
674
+ for (const child of this.frameSessions.values()) {
675
+ const tree = await this.send(
676
+ "Page.getFrameTree",
677
+ {},
678
+ child.sessionId,
679
+ ).catch(() => null);
680
+ frames.push({
681
+ id: child.frameId,
682
+ url: tree?.frameTree.frame.url ?? "",
683
+ sessionId: child.sessionId,
684
+ root: true,
685
+ });
686
+ if (tree) {
687
+ walk(tree.frameTree, child.sessionId);
688
+ }
689
+ }
690
+ return frames;
691
+ }
692
+
693
+ // The frame's owner element, found in whichever session holds it, and
694
+ // the top-left of its content box in that session's viewport.
695
+ async frameOwner(frameId) {
696
+ for (const sessionId of [null, ...this.frameSessions.keys()]) {
697
+ try {
698
+ const { backendNodeId } = await this.send(
699
+ "DOM.getFrameOwner",
700
+ { frameId },
701
+ sessionId,
702
+ );
703
+ const { model } = await this.send(
704
+ "DOM.getBoxModel",
705
+ { backendNodeId },
706
+ sessionId,
707
+ );
708
+ return {
709
+ sessionId,
710
+ backendNodeId,
711
+ x: model.content[0],
712
+ y: model.content[1],
713
+ };
714
+ } catch {
715
+ // Not in this session.
716
+ }
717
+ }
718
+ return null;
719
+ }
720
+
721
+ // Where the frame's viewport starts in the top page's viewport, adding up
722
+ // the owners of the cross-site frames it is nested in; null when the
723
+ // frame has no box (hidden) or is gone. With scroll, each owner is
724
+ // scrolled into view first, outermost first.
725
+ async frameOffset(frameId, scroll = false) {
726
+ const owner = await this.frameOwner(frameId);
727
+ if (!owner) {
728
+ return null;
729
+ }
730
+ const parent = owner.sessionId
731
+ ? this.frameSessions.get(owner.sessionId)
732
+ : null;
733
+ if (scroll) {
734
+ if (parent) {
735
+ await this.frameOffset(parent.frameId, true);
736
+ }
737
+ await this.send(
738
+ "DOM.scrollIntoViewIfNeeded",
739
+ { backendNodeId: owner.backendNodeId },
740
+ owner.sessionId,
741
+ ).catch(() => {});
742
+ return this.frameOffset(frameId, false);
743
+ }
744
+ const base = parent
745
+ ? await this.frameOffset(parent.frameId)
746
+ : { x: 0, y: 0 };
747
+ return base ? { x: base.x + owner.x, y: base.y + owner.y } : null;
748
+ }
749
+
750
+ // Runs a page action in a frame: in its target's session for a cross-site
751
+ // frame's own document, else in the frame's default execution context.
752
+ async runInFrame(frameKey, payload, options = {}) {
753
+ const frame = this.frameKeys.get(frameKey);
754
+ if (!frame) {
755
+ return unknownFrame(frameKey, payload.selector);
756
+ }
757
+ // Change tracking needs no position, and works in a hidden frame.
758
+ const positioned = options.offset !== false;
759
+ // A drop target is read without scrolling, so the drag's source stays
760
+ // where it was measured.
761
+ const before = positioned
762
+ ? await this.frameOffset(
763
+ frame.id,
764
+ options.scroll ?? payload.scrollIntoView !== false,
765
+ )
766
+ : { x: 0, y: 0 };
767
+ const contextId = frame.root
768
+ ? undefined
769
+ : this.frameContexts.get(`${frame.sessionId ?? ""}:${frame.id}`);
770
+ if (!before || (!frame.root && contextId === undefined)) {
771
+ return unknownFrame(frameKey, payload.selector);
772
+ }
773
+ const response = await this.send(
774
+ "Runtime.evaluate",
775
+ {
776
+ expression: buildPageContextExpression(
777
+ { browserFamily: cdpBrowserFamily(this.config), ...payload },
778
+ { serialize: true },
779
+ ),
780
+ awaitPromise: true,
781
+ returnByValue: true,
782
+ userGesture: options.userGesture ?? false,
783
+ ...(contextId !== undefined ? { contextId } : {}),
784
+ },
785
+ frame.sessionId,
786
+ );
787
+ if (response.exceptionDetails) {
788
+ throw new Error(pageExceptionMessage(response.exceptionDetails));
789
+ }
790
+ const value = response.result?.value;
791
+ const result = typeof value === "string" ? JSON.parse(value) : value;
792
+ // The action may have scrolled the frame's ancestors, moving the frame.
793
+ const offset = positioned
794
+ ? ((await this.frameOffset(frame.id)) ?? before)
795
+ : before;
796
+ return shiftFramePoints(result, offset);
797
+ }
798
+
799
+ // Where a frame ref's own document runs, for protocol calls that must
800
+ // reach it: the session and execution context.
801
+ frameScope(selector) {
802
+ const route = parseFrameRef(selector);
803
+ const frame = route ? this.frameKeys.get(route.frameKey) : null;
804
+ if (!frame) {
805
+ return { sessionId: null, contextId: undefined };
806
+ }
807
+ return {
808
+ sessionId: frame.sessionId,
809
+ contextId: frame.root
810
+ ? undefined
811
+ : this.frameContexts.get(`${frame.sessionId ?? ""}:${frame.id}`),
812
+ };
813
+ }
814
+
506
815
  bufferEvent(method, params) {
507
816
  const capturedAt = new Date().toISOString();
508
817
  if (
@@ -527,6 +836,10 @@ export class CdpSession {
527
836
  this.autoDismissDialog(params);
528
837
  }
529
838
 
839
+ if (method === "Fetch.requestPaused") {
840
+ void this.handleRequestPaused(params);
841
+ }
842
+
530
843
  this.pushEvent({
531
844
  method,
532
845
  capturedAt,
@@ -535,12 +848,89 @@ export class CdpSession {
535
848
  this.resolveEventWaiters(method, params);
536
849
  }
537
850
 
851
+ // Fetch pauses only requests whose URL matches a rule's pattern, so other
852
+ // requests are not slowed by a round trip to the server.
853
+ // One call at a time per tab, so a reset cannot be undone by a call that
854
+ // started before it.
855
+ async setNetwork(options) {
856
+ return inNetworkTurn(this, () => this.applyNetwork(options));
857
+ }
858
+
859
+ async applyNetwork(options) {
860
+ const before = this.network;
861
+ const state = applyNetworkOptions(before, options);
862
+ // Requests paused once the new patterns apply see the new rules.
863
+ this.network = state;
864
+ if (state.rules.length > 0) {
865
+ await this.send("Fetch.enable", {
866
+ patterns: state.rules.map((rule) => ({
867
+ urlPattern: rule.url,
868
+ requestStage: "Request",
869
+ })),
870
+ });
871
+ } else if (before?.rules.length > 0) {
872
+ await this.send("Fetch.disable");
873
+ }
874
+ if (options.headers !== undefined || options.reset) {
875
+ await this.send("Network.setExtraHTTPHeaders", {
876
+ headers: state.headers,
877
+ });
878
+ }
879
+ const conditions = [
880
+ "offline",
881
+ "latencyMs",
882
+ "downloadKbps",
883
+ "uploadKbps",
884
+ "reset",
885
+ ];
886
+ if (conditions.some((key) => options[key] !== undefined)) {
887
+ const throughput = (kbps) => (kbps ? (kbps * 1024) / 8 : -1);
888
+ await this.send("Network.emulateNetworkConditions", {
889
+ offline: state.offline,
890
+ latency: state.latencyMs ?? 0,
891
+ downloadThroughput: throughput(state.downloadKbps),
892
+ uploadThroughput: throughput(state.uploadKbps),
893
+ });
894
+ }
895
+ return {
896
+ browserFamily: cdpBrowserFamily(this.config),
897
+ ...describeNetworkState(state),
898
+ };
899
+ }
900
+
901
+ async handleRequestPaused(params) {
902
+ const { requestId } = params;
903
+ const rule = takeMatchingRule(this.network, params.request?.url ?? "");
904
+ try {
905
+ if (!rule) {
906
+ await this.send("Fetch.continueRequest", { requestId });
907
+ } else if (rule.action === "block") {
908
+ await this.send("Fetch.failRequest", {
909
+ requestId,
910
+ errorReason: "BlockedByClient",
911
+ });
912
+ } else {
913
+ await this.send("Fetch.fulfillRequest", {
914
+ requestId,
915
+ responseCode: rule.status,
916
+ responseHeaders: mockHeaders(rule),
917
+ body: Buffer.from(rule.body).toString("base64"),
918
+ });
919
+ }
920
+ } catch {
921
+ // Release the request if it is still paused; it may also have gone
922
+ // away, for example because the page navigated.
923
+ await this.send("Fetch.continueRequest", { requestId }).catch(() => {});
924
+ }
925
+ }
926
+
538
927
  autoDismissDialog(params) {
539
928
  const accept = params.type !== "prompt";
540
929
  this.send("Page.handleJavaScriptDialog", { accept }).catch(() => {});
541
930
  }
542
931
 
543
932
  pushEvent(event) {
933
+ this.inFlight.observe(event);
544
934
  this.bufferedEvents.push(event);
545
935
  if (this.bufferedEvents.length > this.eventBufferSize) {
546
936
  this.bufferedEvents.shift();
@@ -614,13 +1004,18 @@ export class CdpSession {
614
1004
  this.pending.clear();
615
1005
  }
616
1006
 
617
- send(method, params = {}) {
1007
+ send(method, params = {}, sessionId = null) {
618
1008
  if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
619
1009
  throw new Error(`CDP session ${this.id} is not connected`);
620
1010
  }
621
1011
 
622
1012
  const id = this.nextMessageId++;
623
- const payload = JSON.stringify({ id, method, params });
1013
+ const payload = JSON.stringify({
1014
+ id,
1015
+ method,
1016
+ params,
1017
+ ...(sessionId ? { sessionId } : {}),
1018
+ });
624
1019
 
625
1020
  return new Promise((resolve, reject) => {
626
1021
  this.pending.set(id, { resolve, reject });
@@ -714,6 +1109,15 @@ export class CdpSession {
714
1109
  }
715
1110
 
716
1111
  async runPageAction(payload, options = {}) {
1112
+ const route = parseFrameRef(payload.selector);
1113
+ if (route) {
1114
+ const result = await this.runInFrame(
1115
+ route.frameKey,
1116
+ { ...payload, selector: route.selector },
1117
+ options,
1118
+ );
1119
+ return restoreFrameSelector(result, route, payload.selector);
1120
+ }
717
1121
  const result = await this.evaluateRuntime(
718
1122
  buildPageContextExpression(
719
1123
  {
@@ -881,8 +1285,71 @@ export class CdpSession {
881
1285
  };
882
1286
  }
883
1287
 
1288
+ // Refs number on from the last snapshot, across navigations, so an old
1289
+ // ref never names an element on a later page.
1290
+ async runSnapshotAction(payload) {
1291
+ const result = await this.runPageAction({
1292
+ ...payload,
1293
+ refStart: this.refStart ?? 1,
1294
+ });
1295
+ return takeNextRef(this, result);
1296
+ }
1297
+
884
1298
  async snapshotControls() {
885
- return this.runPageAction({ action: "controls_snapshot" });
1299
+ return this.runSnapshotAction({ action: "controls_snapshot" });
1300
+ }
1301
+
1302
+ // The top page's headings and controls, then each iframe's.
1303
+ async snapshotPage(options = {}) {
1304
+ const runInFrame = (key, payload, runOptions) =>
1305
+ this.runInFrame(key, payload, runOptions);
1306
+ const route = parseFrameRef(options.selector);
1307
+ if (route) {
1308
+ return frameElementSnapshot({
1309
+ route,
1310
+ frameKeys: this.frameKeys,
1311
+ runInFrame,
1312
+ options,
1313
+ });
1314
+ }
1315
+ const result = await this.runSnapshotAction({
1316
+ action: "snapshot",
1317
+ ...options,
1318
+ });
1319
+ if (options.selector) {
1320
+ return result;
1321
+ }
1322
+ return addFrameSnapshots({
1323
+ result,
1324
+ frames: await this.listFrames().catch(() => []),
1325
+ frameKeys: this.frameKeys,
1326
+ runInFrame,
1327
+ options,
1328
+ });
1329
+ }
1330
+
1331
+ async trackChanges(phase, options = {}) {
1332
+ const { frameKey, ...rest } = options;
1333
+ if (!frameKey) {
1334
+ return this.runSnapshotAction({ action: `change_${phase}`, ...rest });
1335
+ }
1336
+ // In a frame, refs number on from the frame's own last snapshot. A frame
1337
+ // that is gone ends tracking as a lost baseline does.
1338
+ const entry = this.frameKeys.get(frameKey);
1339
+ const result = entry
1340
+ ? await this.runInFrame(
1341
+ frameKey,
1342
+ { action: `change_${phase}`, ...rest, refStart: entry.refStart ?? 1 },
1343
+ { offset: false },
1344
+ )
1345
+ : null;
1346
+ if (!result || result.error?.startsWith("Unknown frame")) {
1347
+ if (phase === "baseline") {
1348
+ throw new Error(`Unknown frame ${frameKey}`);
1349
+ }
1350
+ return { document: "same", lost: true };
1351
+ }
1352
+ return takeNextRef(entry, result);
886
1353
  }
887
1354
 
888
1355
  async readText(options = {}) {
@@ -902,17 +1369,33 @@ export class CdpSession {
902
1369
  action: "pointer_target",
903
1370
  selector,
904
1371
  ...(options.inputProbe ? { inputProbe: options.inputProbe } : {}),
1372
+ ...(options.scrollIntoView === false ? { scrollIntoView: false } : {}),
905
1373
  });
906
1374
  assertPointerTarget(target);
907
1375
  return target;
908
1376
  }
909
1377
 
910
- async readInputProbe(token, disarm) {
1378
+ // A locator, scrolled into view unless scrollIntoView is false, or
1379
+ // viewport coordinates, which never scroll.
1380
+ async resolvePointer(target, options = {}) {
1381
+ if (typeof target === "string") {
1382
+ return this.resolvePointerTarget(target, options);
1383
+ }
1384
+ return this.runSnapshotAction({
1385
+ action: "point_target",
1386
+ x: target.x,
1387
+ y: target.y,
1388
+ ...(options.inputProbe ? { inputProbe: options.inputProbe } : {}),
1389
+ });
1390
+ }
1391
+
1392
+ async readInputProbe(token, disarm, target = null) {
911
1393
  try {
912
1394
  const probe = await this.runPageAction({
913
1395
  action: "input_probe",
914
1396
  token,
915
1397
  disarm,
1398
+ ...probeScope(target),
916
1399
  });
917
1400
  return probe.armed ? probe : null;
918
1401
  } catch {
@@ -920,11 +1403,20 @@ export class CdpSession {
920
1403
  }
921
1404
  }
922
1405
 
923
- async dispatchClick(point) {
924
- const press = { button: "left", clickCount: 1 };
1406
+ // A double click is two presses, the second with clickCount 2, as the
1407
+ // browser reports them.
1408
+ async dispatchClick(point, options = {}) {
1409
+ const button = options.button ?? "left";
1410
+ const buttons = { left: 1, right: 2, middle: 4 }[button] ?? 1;
925
1411
  await this.dispatchMouse("mouseMoved", point);
926
- await this.dispatchMouse("mousePressed", point, { ...press, buttons: 1 });
927
- await this.dispatchMouse("mouseReleased", point, { ...press, buttons: 0 });
1412
+ for (let count = 1; count <= (options.clickCount ?? 1); count += 1) {
1413
+ const press = { button, clickCount: count };
1414
+ await this.dispatchMouse("mousePressed", point, { ...press, buttons });
1415
+ await this.dispatchMouse("mouseReleased", point, {
1416
+ ...press,
1417
+ buttons: 0,
1418
+ });
1419
+ }
928
1420
  }
929
1421
 
930
1422
  async dispatchMouse(type, point, extra = {}) {
@@ -942,31 +1434,29 @@ export class CdpSession {
942
1434
  }
943
1435
  }
944
1436
 
945
- async click(selector) {
1437
+ async click(target, options = {}) {
946
1438
  const token = crypto.randomUUID();
947
- const target = await this.resolvePointerTarget(selector, {
948
- inputProbe: token,
949
- });
950
- if (!target.found) {
951
- return target;
1439
+ const resolved = await this.resolvePointer(target, { inputProbe: token });
1440
+ if (!resolved.found) {
1441
+ return resolved;
1442
+ }
1443
+ if (typeof target === "string") {
1444
+ assertEnabled(resolved);
952
1445
  }
953
- assertEnabled(target);
954
1446
 
955
1447
  const delivery = await sendCheckedInput({
956
- send: () => this.dispatchClick(target.point),
957
- readProbe: (disarm) => this.readInputProbe(token, disarm),
1448
+ send: () => this.dispatchClick(resolved.point, options),
1449
+ readProbe: (disarm) => this.readInputProbe(token, disarm, target),
958
1450
  recover: () => this.bringToFront(),
959
- describe: `The click on "${selector}"`,
1451
+ describe: `The click on ${describePointer(target)}`,
960
1452
  });
961
1453
 
962
1454
  return {
963
1455
  browserFamily: cdpBrowserFamily(this.config),
964
- selector,
965
1456
  found: true,
966
1457
  clicked: true,
967
1458
  ...(delivery.resent ? { resent: true } : {}),
968
- point: target.point,
969
- node: delivery.node ?? target.node,
1459
+ ...pointerFields(target, resolved, delivery.node ?? resolved.node),
970
1460
  };
971
1461
  }
972
1462
 
@@ -976,24 +1466,132 @@ export class CdpSession {
976
1466
  await this.send("Page.bringToFront").catch(() => {});
977
1467
  }
978
1468
 
979
- async hover(selector) {
980
- const target = await this.resolvePointerTarget(selector);
1469
+ async hover(target) {
1470
+ const resolved = await this.resolvePointer(target);
1471
+ if (!resolved.found) {
1472
+ return resolved;
1473
+ }
1474
+
1475
+ await this.dispatchMouse("mouseMoved", resolved.point);
1476
+
1477
+ return {
1478
+ browserFamily: cdpBrowserFamily(this.config),
1479
+ found: true,
1480
+ hovered: true,
1481
+ ...pointerFields(target, resolved),
1482
+ };
1483
+ }
1484
+
1485
+ // Presses at from, moves through dragPath, and releases at to. Chrome
1486
+ // does not run an HTML5 drag (draggable elements, dataTransfer) from CDP
1487
+ // mouse input, so drags are intercepted: when the page starts one, Chrome
1488
+ // hands over its data and the drag finishes with drag events instead.
1489
+ async drag(from, to, options = {}) {
1490
+ const token = crypto.randomUUID();
1491
+ const source = await this.resolvePointer(from, { inputProbe: token });
1492
+ if (!source.found) {
1493
+ await this.readInputProbe(token, true, from);
1494
+ return source;
1495
+ }
1496
+ // The drop point is read without scrolling, so the source stays put.
1497
+ const target = await this.resolvePointer(to, { scrollIntoView: false });
981
1498
  if (!target.found) {
1499
+ await this.readInputProbe(token, true, from);
982
1500
  return target;
983
1501
  }
984
1502
 
985
- await this.dispatchMouse("mouseMoved", target.point);
1503
+ await this.send("Input.setInterceptDrags", { enabled: true });
1504
+ let dragData = null;
1505
+ const intercepted = this.createEventWaiter(
1506
+ "Input.dragIntercepted",
1507
+ () => true,
1508
+ DRAG_SESSION_MS,
1509
+ );
1510
+ intercepted.promise.then(
1511
+ (params) => {
1512
+ dragData = params.data;
1513
+ },
1514
+ () => {},
1515
+ );
1516
+ const held = { button: "left", buttons: 1 };
1517
+ const release = { button: "left", buttons: 0, clickCount: 1 };
1518
+ let delivery;
1519
+ let released = false;
1520
+ try {
1521
+ delivery = await sendCheckedInput({
1522
+ send: async () => {
1523
+ await this.dispatchMouse("mouseMoved", source.point);
1524
+ await this.dispatchMouse("mousePressed", source.point, {
1525
+ ...held,
1526
+ clickCount: 1,
1527
+ });
1528
+ },
1529
+ readProbe: (disarm) => this.readInputProbe(token, disarm, from),
1530
+ recover: () => this.bringToFront(),
1531
+ describe: `The press to drag ${describePointer(from)}`,
1532
+ });
1533
+
1534
+ const path = dragPath(source.point, target.point, options.steps);
1535
+ let index = 0;
1536
+ for (; index < path.length && !dragData; index += 1) {
1537
+ await this.dispatchMouse("mouseMoved", path[index], held);
1538
+ if (index === 0) {
1539
+ // A page starts an HTML5 drag on the first move past a few pixels.
1540
+ await Promise.race([intercepted.promise, sleep(DRAG_START_MS)]).catch(
1541
+ () => {},
1542
+ );
1543
+ }
1544
+ }
1545
+ if (dragData) {
1546
+ const rest = path.slice(index);
1547
+ const enter = rest[0] ?? target.point;
1548
+ await this.dispatchDrag("dragEnter", enter, dragData);
1549
+ for (const point of rest) {
1550
+ await this.dispatchDrag("dragOver", point, dragData);
1551
+ }
1552
+ await this.dispatchDrag("drop", target.point, dragData);
1553
+ }
1554
+ await this.dispatchMouse("mouseReleased", target.point, release);
1555
+ released = true;
1556
+ } finally {
1557
+ // A drag that failed partway must not leave the button down for the
1558
+ // next action.
1559
+ if (!released) {
1560
+ if (dragData) {
1561
+ await this.dispatchDrag("dragCancel", target.point, dragData).catch(
1562
+ () => {},
1563
+ );
1564
+ }
1565
+ await this.dispatchMouse("mouseReleased", target.point, release).catch(
1566
+ () => {},
1567
+ );
1568
+ }
1569
+ intercepted.cancel();
1570
+ await this.send("Input.setInterceptDrags", { enabled: false }).catch(
1571
+ () => {},
1572
+ );
1573
+ }
986
1574
 
987
1575
  return {
988
1576
  browserFamily: cdpBrowserFamily(this.config),
989
- selector,
990
1577
  found: true,
991
- hovered: true,
992
- point: target.point,
993
- node: target.node,
1578
+ dragged: true,
1579
+ html5: Boolean(dragData),
1580
+ ...(delivery.resent ? { resent: true } : {}),
1581
+ from: dragEnd(from, source),
1582
+ to: dragEnd(to, target),
994
1583
  };
995
1584
  }
996
1585
 
1586
+ async dispatchDrag(type, point, data) {
1587
+ await this.send("Input.dispatchDragEvent", {
1588
+ type,
1589
+ x: point.x,
1590
+ y: point.y,
1591
+ data,
1592
+ });
1593
+ }
1594
+
997
1595
  async type(selector, text, options = {}) {
998
1596
  const token = crypto.randomUUID();
999
1597
  const prepared = await this.runPageAction(
@@ -1034,12 +1632,12 @@ export class CdpSession {
1034
1632
  if (text || options.clear !== false) {
1035
1633
  delivery = await sendCheckedInput({
1036
1634
  send: sendText,
1037
- readProbe: (disarm) => this.readInputProbe(token, disarm),
1635
+ readProbe: (disarm) => this.readInputProbe(token, disarm, selector),
1038
1636
  recover: () => this.bringToFront(),
1039
1637
  describe: `The text for "${selector}"`,
1040
1638
  });
1041
1639
  } else {
1042
- await this.readInputProbe(token, true);
1640
+ await this.readInputProbe(token, true, selector);
1043
1641
  }
1044
1642
 
1045
1643
  let node = delivery.node;
@@ -1062,6 +1660,218 @@ export class CdpSession {
1062
1660
  };
1063
1661
  }
1064
1662
 
1663
+ // Sets files on a file input, or, for a button that opens a file chooser
1664
+ // from script, intercepts the chooser its click opens.
1665
+ async uploadFiles(selector, files) {
1666
+ const token = crypto.randomUUID();
1667
+ const target = await this.runPageAction({
1668
+ action: "file_input",
1669
+ selector,
1670
+ token,
1671
+ clear: files.length === 0,
1672
+ });
1673
+ if (!target.found) {
1674
+ return target;
1675
+ }
1676
+ const family = cdpBrowserFamily(this.config);
1677
+ if (target.cleared) {
1678
+ return uploadResult(family, selector, files);
1679
+ }
1680
+ if (target.fileInput) {
1681
+ // The input's handle and the files go to the session of the
1682
+ // document it is in, a frame's for a frame ref.
1683
+ const scope = this.frameScope(selector);
1684
+ const handle = await this.send(
1685
+ "Runtime.evaluate",
1686
+ {
1687
+ expression: takeFileTarget(token),
1688
+ returnByValue: false,
1689
+ ...(scope.contextId !== undefined
1690
+ ? { contextId: scope.contextId }
1691
+ : {}),
1692
+ },
1693
+ scope.sessionId,
1694
+ );
1695
+ const objectId = handle.result?.objectId;
1696
+ try {
1697
+ assertFileInput(target, files);
1698
+ await this.send(
1699
+ "DOM.setFileInputFiles",
1700
+ { files, objectId },
1701
+ scope.sessionId,
1702
+ );
1703
+ } finally {
1704
+ this.send("Runtime.releaseObject", { objectId }, scope.sessionId).catch(
1705
+ () => {},
1706
+ );
1707
+ }
1708
+ return uploadResult(family, selector, files, {
1709
+ multiple: target.multiple,
1710
+ accept: target.accept,
1711
+ });
1712
+ }
1713
+
1714
+ // One chooser at a time per tab, so a chooser goes to the upload whose
1715
+ // click opened it.
1716
+ const previous = this.chooserTurn ?? Promise.resolve();
1717
+ let finished;
1718
+ this.chooserTurn = new Promise((resolve) => {
1719
+ finished = resolve;
1720
+ });
1721
+ await previous;
1722
+ try {
1723
+ return await this.uploadThroughChooser(selector, files, family);
1724
+ } finally {
1725
+ finished();
1726
+ }
1727
+ }
1728
+
1729
+ // The chooser opens in the session of the document whose script opens it,
1730
+ // the button's frame or the top page, so both intercept it.
1731
+ async uploadThroughChooser(selector, files, family) {
1732
+ const sessions = Array.from(
1733
+ new Set([null, this.frameScope(selector).sessionId]),
1734
+ );
1735
+ for (const sessionId of sessions) {
1736
+ await this.send(
1737
+ "Page.setInterceptFileChooserDialog",
1738
+ { enabled: true },
1739
+ sessionId,
1740
+ ).catch(() => {});
1741
+ }
1742
+ const chooser = this.createEventWaiter(
1743
+ "Page.fileChooserOpened",
1744
+ () => true,
1745
+ FILE_CHOOSER_MS,
1746
+ );
1747
+ try {
1748
+ await this.click(selector);
1749
+ let opened;
1750
+ try {
1751
+ opened = await chooser.promise;
1752
+ } catch {
1753
+ throw new Error(
1754
+ `"${selector}" is not a file input, and clicking it opened no file chooser; pass the <input type="file">, which may be hidden`,
1755
+ );
1756
+ }
1757
+ if (files.length > 1 && opened.mode !== "selectMultiple") {
1758
+ throw new Error(
1759
+ `The file chooser "${selector}" opened takes one file, not ${files.length}`,
1760
+ );
1761
+ }
1762
+ await this.send(
1763
+ "DOM.setFileInputFiles",
1764
+ { files, backendNodeId: opened.backendNodeId },
1765
+ opened.sessionId ?? null,
1766
+ );
1767
+ } finally {
1768
+ chooser.cancel();
1769
+ for (const sessionId of sessions) {
1770
+ await this.send(
1771
+ "Page.setInterceptFileChooserDialog",
1772
+ { enabled: false },
1773
+ sessionId,
1774
+ ).catch(() => {});
1775
+ }
1776
+ }
1777
+ return uploadResult(family, selector, files, { chooser: true });
1778
+ }
1779
+
1780
+ // The page's report, with Chromium's own counters: heap, DOM nodes,
1781
+ // listeners, layouts and style recalculations, and script and task time.
1782
+ async getPerformance() {
1783
+ const report = await this.runPageAction({ action: "performance" });
1784
+ let metrics = null;
1785
+ try {
1786
+ if (!this.performanceEnabled) {
1787
+ await this.send("Performance.enable");
1788
+ this.performanceEnabled = true;
1789
+ }
1790
+ const values = Object.fromEntries(
1791
+ (await this.send("Performance.getMetrics")).metrics.map(
1792
+ ({ name, value }) => [name, value],
1793
+ ),
1794
+ );
1795
+ const ms = (seconds) =>
1796
+ seconds === undefined ? null : Math.round(seconds * 1000);
1797
+ metrics = {
1798
+ jsHeapUsedBytes: Math.round(values.JSHeapUsedSize ?? 0),
1799
+ jsHeapTotalBytes: Math.round(values.JSHeapTotalSize ?? 0),
1800
+ domNodes: values.Nodes ?? null,
1801
+ eventListeners: values.JSEventListeners ?? null,
1802
+ layouts: values.LayoutCount ?? null,
1803
+ styleRecalcs: values.RecalcStyleCount ?? null,
1804
+ layoutMs: ms(values.LayoutDuration),
1805
+ styleRecalcMs: ms(values.RecalcStyleDuration),
1806
+ scriptMs: ms(values.ScriptDuration),
1807
+ taskMs: ms(values.TaskDuration),
1808
+ };
1809
+ } catch {
1810
+ // The counters are extra; the page's report stands without them.
1811
+ }
1812
+ return { ...report, metrics };
1813
+ }
1814
+
1815
+ async startTrace(options = {}) {
1816
+ if (this.tracing) {
1817
+ throw new Error("A trace is already recording; stop it first");
1818
+ }
1819
+ await this.send("Tracing.start", {
1820
+ transferMode: "ReturnAsStream",
1821
+ traceConfig: {
1822
+ recordMode: "recordUntilFull",
1823
+ includedCategories: [
1824
+ ...TRACE_CATEGORIES,
1825
+ ...(options.screenshots
1826
+ ? ["disabled-by-default-devtools.screenshot"]
1827
+ : []),
1828
+ ],
1829
+ },
1830
+ });
1831
+ this.tracing = { startedAt: Date.now() };
1832
+ return { browserFamily: cdpBrowserFamily(this.config), recording: true };
1833
+ }
1834
+
1835
+ // Ends the trace and reads it from the stream Chrome hands back.
1836
+ async stopTrace() {
1837
+ if (!this.tracing) {
1838
+ throw new Error("No trace is recording; start one first");
1839
+ }
1840
+ const { startedAt } = this.tracing;
1841
+ const complete = this.createEventWaiter(
1842
+ "Tracing.tracingComplete",
1843
+ () => true,
1844
+ TRACE_COMPLETE_MS,
1845
+ );
1846
+ try {
1847
+ await this.send("Tracing.end");
1848
+ } catch (error) {
1849
+ // Chrome is still recording; a later stop can end it.
1850
+ complete.cancel();
1851
+ throw error;
1852
+ }
1853
+ this.tracing = null;
1854
+ const { stream } = await complete.promise;
1855
+ const chunks = [];
1856
+ try {
1857
+ while (true) {
1858
+ const chunk = await this.send("IO.read", {
1859
+ handle: stream,
1860
+ size: 1 << 20,
1861
+ });
1862
+ chunks.push(
1863
+ Buffer.from(chunk.data, chunk.base64Encoded ? "base64" : "utf8"),
1864
+ );
1865
+ if (chunk.eof) {
1866
+ break;
1867
+ }
1868
+ }
1869
+ } finally {
1870
+ await this.send("IO.close", { handle: stream }).catch(() => {});
1871
+ }
1872
+ return { data: Buffer.concat(chunks), durationMs: Date.now() - startedAt };
1873
+ }
1874
+
1065
1875
  async select(selector, options = {}) {
1066
1876
  return this.runPageAction(
1067
1877
  {
@@ -1091,7 +1901,7 @@ export class CdpSession {
1091
1901
 
1092
1902
  const delivery = await sendCheckedInput({
1093
1903
  send: () => this.dispatchKeyEvents(events),
1094
- readProbe: (disarm) => this.readInputProbe(token, disarm),
1904
+ readProbe: (disarm) => this.readInputProbe(token, disarm, selector),
1095
1905
  recover: () => this.bringToFront(),
1096
1906
  describe: `The key press "${key}"`,
1097
1907
  });
@@ -1105,7 +1915,29 @@ export class CdpSession {
1105
1915
  };
1106
1916
  }
1107
1917
 
1918
+ // A selector alone scrolls its element into view and deltas alone scroll
1919
+ // the page. Coordinates, or a selector with deltas, send a real mouse
1920
+ // wheel there, which scrolls whatever is under the pointer, such as a list
1921
+ // inside the page.
1108
1922
  async scroll(options = {}) {
1923
+ if (wheelScroll(options)) {
1924
+ const target = options.selector ?? { x: options.x, y: options.y };
1925
+ const resolved = await this.resolvePointer(target);
1926
+ if (!resolved.found) {
1927
+ return resolved;
1928
+ }
1929
+ await this.dispatchMouse("mouseWheel", resolved.point, {
1930
+ deltaX: options.deltaX ?? 0,
1931
+ deltaY: options.deltaY ?? 0,
1932
+ });
1933
+ return {
1934
+ browserFamily: cdpBrowserFamily(this.config),
1935
+ found: true,
1936
+ scrolled: true,
1937
+ wheel: { deltaX: options.deltaX ?? 0, deltaY: options.deltaY ?? 0 },
1938
+ ...pointerFields(target, resolved),
1939
+ };
1940
+ }
1109
1941
  return this.runPageAction(
1110
1942
  {
1111
1943
  action: "scroll",
@@ -1215,15 +2047,23 @@ export class CdpSession {
1215
2047
  // Counts trusted input from the start of every later document, and from
1216
2048
  // now on in the current one, so input actions can check that their input
1217
2049
  // arrived. Without it they are reported as sent, unchecked.
1218
- async installInputRecorder() {
2050
+ // A cross-site iframe's target gets the recorder too, by its session.
2051
+ async installInputRecorder(sessionId = null) {
1219
2052
  try {
1220
- await this.send("Page.addScriptToEvaluateOnNewDocument", {
1221
- source: buildInputRecorderExpression(true),
1222
- });
1223
- await this.evaluateRuntime(buildInputRecorderExpression(false), {
1224
- awaitPromise: false,
1225
- replMode: false,
1226
- });
2053
+ await this.send(
2054
+ "Page.addScriptToEvaluateOnNewDocument",
2055
+ { source: buildInputRecorderExpression(true) },
2056
+ sessionId,
2057
+ );
2058
+ await this.send(
2059
+ "Runtime.evaluate",
2060
+ {
2061
+ expression: buildInputRecorderExpression(false),
2062
+ awaitPromise: false,
2063
+ returnByValue: true,
2064
+ },
2065
+ sessionId,
2066
+ );
1227
2067
  } catch {
1228
2068
  // Ignore recorder failures so attach still succeeds.
1229
2069
  }
@@ -1259,6 +2099,10 @@ export class CdpSession {
1259
2099
  return this.bufferedEvents.slice(-safeLimit);
1260
2100
  }
1261
2101
 
2102
+ pendingRequests() {
2103
+ return this.inFlight.list();
2104
+ }
2105
+
1262
2106
  getSummary() {
1263
2107
  return {
1264
2108
  sessionId: this.id,
@@ -1659,12 +2503,36 @@ export class CdpSessionManager {
1659
2503
  return this.getSession(sessionId).reload(options);
1660
2504
  }
1661
2505
 
1662
- async click(sessionId, selector) {
1663
- return this.getSession(sessionId).click(selector);
2506
+ async click(sessionId, target, options) {
2507
+ return this.getSession(sessionId).click(target, options);
2508
+ }
2509
+
2510
+ async hover(sessionId, target) {
2511
+ return this.getSession(sessionId).hover(target);
1664
2512
  }
1665
2513
 
1666
- async hover(sessionId, selector) {
1667
- return this.getSession(sessionId).hover(selector);
2514
+ async drag(sessionId, from, to, options) {
2515
+ return this.getSession(sessionId).drag(from, to, options);
2516
+ }
2517
+
2518
+ async uploadFiles(sessionId, selector, files) {
2519
+ return this.getSession(sessionId).uploadFiles(selector, files);
2520
+ }
2521
+
2522
+ async setNetwork(sessionId, options) {
2523
+ return this.getSession(sessionId).setNetwork(options);
2524
+ }
2525
+
2526
+ async getPerformance(sessionId) {
2527
+ return this.getSession(sessionId).getPerformance();
2528
+ }
2529
+
2530
+ async startTrace(sessionId, options) {
2531
+ return this.getSession(sessionId).startTrace(options);
2532
+ }
2533
+
2534
+ async stopTrace(sessionId) {
2535
+ return this.getSession(sessionId).stopTrace();
1668
2536
  }
1669
2537
 
1670
2538
  async type(sessionId, selector, text, options) {
@@ -1731,10 +2599,22 @@ export class CdpSessionManager {
1731
2599
  return this.getSession(sessionId).snapshotControls();
1732
2600
  }
1733
2601
 
2602
+ async snapshotPage(sessionId, options) {
2603
+ return this.getSession(sessionId).snapshotPage(options);
2604
+ }
2605
+
2606
+ async trackChanges(sessionId, phase, options) {
2607
+ return this.getSession(sessionId).trackChanges(phase, options);
2608
+ }
2609
+
1734
2610
  async inspectElement(sessionId, selector, options) {
1735
2611
  return this.getSession(sessionId).inspectElement(selector, options);
1736
2612
  }
1737
2613
 
2614
+ pendingRequests(sessionId) {
2615
+ return this.getSession(sessionId).pendingRequests();
2616
+ }
2617
+
1738
2618
  getEvents(sessionId, limit) {
1739
2619
  return this.getSession(sessionId).getEvents(limit);
1740
2620
  }