mcp-browser-dev-tools 0.0.1-beta.1 → 0.0.1-beta.10

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.
@@ -2,6 +2,7 @@ import {
2
2
  filterConsoleMessages,
3
3
  summarizeNetworkRequests,
4
4
  } from "./session-events.mjs";
5
+ import { buildPageContextExpression } from "./page-context.mjs";
5
6
 
6
7
  function toErrorMessage(error) {
7
8
  return error instanceof Error ? error.message : String(error);
@@ -108,6 +109,52 @@ export function summarizeBidiRemoteValue(value) {
108
109
  }
109
110
  }
110
111
 
112
+ function summarizeFirefoxStackFrames(callFrames = []) {
113
+ return callFrames.map((frame) => ({
114
+ functionName: frame.functionName || null,
115
+ url: frame.url || null,
116
+ lineNumber: frame.lineNumber ?? null,
117
+ columnNumber: frame.columnNumber ?? null,
118
+ }));
119
+ }
120
+
121
+ function firstFirefoxCallFrame(stackTrace) {
122
+ const frame = stackTrace?.callFrames?.[0];
123
+ if (!frame) {
124
+ return null;
125
+ }
126
+
127
+ return {
128
+ functionName: frame.functionName || null,
129
+ url: frame.url || null,
130
+ lineNumber: frame.lineNumber ?? null,
131
+ columnNumber: frame.columnNumber ?? null,
132
+ };
133
+ }
134
+
135
+ function screenshotMimeType(format) {
136
+ return format === "jpeg" ? "image/jpeg" : "image/png";
137
+ }
138
+
139
+ function formatScreenshotResult(data, format, extras = {}) {
140
+ return {
141
+ format,
142
+ mimeType: screenshotMimeType(format),
143
+ encoding: "base64",
144
+ byteLength: Buffer.byteLength(data, "base64"),
145
+ data,
146
+ ...extras,
147
+ };
148
+ }
149
+
150
+ function normalizeWaitUntil(value) {
151
+ if (value === "none" || value === "interactive") {
152
+ return value;
153
+ }
154
+
155
+ return "complete";
156
+ }
157
+
111
158
  function normalizeFirefoxEvent(method, params = {}) {
112
159
  if (method === "log.entryAdded") {
113
160
  return {
@@ -116,6 +163,10 @@ function normalizeFirefoxEvent(method, params = {}) {
116
163
  text: params.text,
117
164
  timestamp: params.timestamp,
118
165
  values: (params.args || []).map((arg) => summarizeBidiRemoteValue(arg)),
166
+ source: firstFirefoxCallFrame(params.stackTrace),
167
+ stackTrace: summarizeFirefoxStackFrames(params.stackTrace?.callFrames),
168
+ realm: params.source?.realm ?? null,
169
+ context: params.source?.context ?? null,
119
170
  };
120
171
  }
121
172
 
@@ -128,6 +179,7 @@ function normalizeFirefoxEvent(method, params = {}) {
128
179
  requestId: params.request?.request,
129
180
  method: params.request?.method,
130
181
  url: params.request?.url,
182
+ source: "protocol",
131
183
  };
132
184
  }
133
185
 
@@ -143,6 +195,7 @@ function normalizeFirefoxEvent(method, params = {}) {
143
195
  statusText: params.response?.statusText,
144
196
  mimeType: params.response?.mimeType,
145
197
  url: params.request?.url,
198
+ source: "protocol",
146
199
  };
147
200
  }
148
201
 
@@ -152,6 +205,7 @@ function normalizeFirefoxEvent(method, params = {}) {
152
205
  timestamp: params.timestamp ?? null,
153
206
  url: params.url ?? null,
154
207
  navigation: params.navigation ?? null,
208
+ context: params.context ?? null,
155
209
  };
156
210
  }
157
211
 
@@ -185,6 +239,33 @@ function normalizeRequestedDepth(depth) {
185
239
  return Number.isInteger(depth) && depth > 0 ? depth : 2;
186
240
  }
187
241
 
242
+ function isHttpProtocol(protocol) {
243
+ return protocol === "http:" || protocol === "https:";
244
+ }
245
+
246
+ function isRootPathname(pathname) {
247
+ return pathname === "" || pathname === "/";
248
+ }
249
+
250
+ function toWebSocketEndpointUrl(endpointUrl) {
251
+ const url = new URL(endpointUrl);
252
+ if (url.protocol === "http:") {
253
+ url.protocol = "ws:";
254
+ } else if (url.protocol === "https:") {
255
+ url.protocol = "wss:";
256
+ }
257
+
258
+ return url;
259
+ }
260
+
261
+ function joinUrlPath(baseUrl, pathname) {
262
+ const url = new URL(baseUrl);
263
+ const basePath = url.pathname.replace(/\/+$/, "");
264
+ const nextPath = pathname.replace(/^\/+/, "");
265
+ url.pathname = `${basePath}/${nextPath}`.replace(/\/{2,}/g, "/");
266
+ return url;
267
+ }
268
+
188
269
  class FirefoxBidiTabSession {
189
270
  constructor(target, options = {}) {
190
271
  this.id = crypto.randomUUID();
@@ -194,15 +275,27 @@ class FirefoxBidiTabSession {
194
275
  this.bufferedEvents = [];
195
276
  this.subscription = null;
196
277
  this.closed = false;
278
+ this.lastNavigationAt = null;
279
+ this.lastReloadAt = null;
280
+ this.viewportOverride = null;
197
281
  }
198
282
 
199
283
  bufferEvent(method, params) {
200
- this.bufferedEvents.push({
284
+ const capturedAt = new Date().toISOString();
285
+ if (method === "browsingContext.load" && params.url) {
286
+ this.target.url = params.url;
287
+ this.lastNavigationAt = capturedAt;
288
+ }
289
+
290
+ this.pushEvent({
201
291
  method,
202
- capturedAt: new Date().toISOString(),
292
+ capturedAt,
203
293
  ...normalizeFirefoxEvent(method, params),
204
294
  });
295
+ }
205
296
 
297
+ pushEvent(event) {
298
+ this.bufferedEvents.push(event);
206
299
  if (this.bufferedEvents.length > this.eventBufferSize) {
207
300
  this.bufferedEvents.shift();
208
301
  }
@@ -231,6 +324,9 @@ class FirefoxBidiTabSession {
231
324
  connectedAt: this.connectedAt,
232
325
  bufferedEvents: this.bufferedEvents.length,
233
326
  subscription: this.subscription,
327
+ lastNavigationAt: this.lastNavigationAt,
328
+ lastReloadAt: this.lastReloadAt,
329
+ viewportOverride: this.viewportOverride,
234
330
  };
235
331
  }
236
332
  }
@@ -241,12 +337,14 @@ export class FirefoxBidiSessionManager {
241
337
  this.sessions = new Map();
242
338
  this.websocketFactory =
243
339
  options.websocketFactory ?? ((url) => new WebSocket(url));
340
+ this.connectionTimeoutMs = options.connectionTimeoutMs ?? 2_000;
244
341
  this.pending = new Map();
245
342
  this.nextMessageId = 1;
246
343
  this.websocket = null;
247
344
  this.browserSessionId = null;
248
345
  this.capabilities = null;
249
346
  this.connectPromise = null;
347
+ this.resolvedWebSocketUrl = null;
250
348
  }
251
349
 
252
350
  async ensureConnected() {
@@ -270,18 +368,41 @@ export class FirefoxBidiSessionManager {
270
368
  }
271
369
 
272
370
  async openConnection() {
273
- this.websocket = this.websocketFactory(this.config.firefoxBidiWsUrl);
371
+ const endpoint = await this.resolveConnectionEndpoint();
372
+ this.resolvedWebSocketUrl = endpoint.webSocketUrl;
373
+ this.websocket = this.websocketFactory(endpoint.webSocketUrl);
274
374
 
275
375
  await new Promise((resolve, reject) => {
276
376
  let settled = false;
377
+ const timer = setTimeout(() => {
378
+ if (settled) {
379
+ return;
380
+ }
381
+
382
+ settled = true;
383
+ this.websocket?.close?.();
384
+ reject(
385
+ new Error(
386
+ `Timed out connecting to Firefox BiDi at ${endpoint.webSocketUrl}`,
387
+ ),
388
+ );
389
+ }, this.connectionTimeoutMs);
390
+ timer.unref?.();
391
+
392
+ const settle = (callback) => {
393
+ if (settled) {
394
+ return;
395
+ }
396
+
397
+ settled = true;
398
+ clearTimeout(timer);
399
+ callback();
400
+ };
277
401
 
278
402
  this.websocket.addEventListener(
279
403
  "open",
280
404
  () => {
281
- if (!settled) {
282
- settled = true;
283
- resolve();
284
- }
405
+ settle(resolve);
285
406
  },
286
407
  { once: true },
287
408
  );
@@ -289,12 +410,11 @@ export class FirefoxBidiSessionManager {
289
410
  this.websocket.addEventListener(
290
411
  "error",
291
412
  () => {
292
- if (!settled) {
293
- settled = true;
413
+ settle(() => {
294
414
  reject(
295
415
  new Error(`Failed to connect to ${this.config.firefoxBidiWsUrl}`),
296
416
  );
297
- }
417
+ });
298
418
  },
299
419
  { once: true },
300
420
  );
@@ -309,23 +429,90 @@ export class FirefoxBidiSessionManager {
309
429
  this.browserSessionId = null;
310
430
  this.capabilities = null;
311
431
  this.sessions.clear();
312
- if (!settled) {
313
- settled = true;
432
+ settle(() => {
314
433
  reject(
315
434
  new Error("Firefox BiDi connection closed before it connected"),
316
435
  );
317
- }
436
+ });
318
437
  });
319
438
  });
320
439
 
321
- const result = await this.send("session.new", {
322
- capabilities: {
323
- alwaysMatch: {},
324
- },
440
+ if (endpoint.requiresSessionNew) {
441
+ const result = await this.send("session.new", {
442
+ capabilities: {
443
+ alwaysMatch: {},
444
+ },
445
+ });
446
+
447
+ this.browserSessionId = result.sessionId;
448
+ this.capabilities = result.capabilities ?? {};
449
+ return;
450
+ }
451
+
452
+ this.browserSessionId = endpoint.sessionId;
453
+ this.capabilities = endpoint.capabilities ?? {};
454
+ }
455
+
456
+ async resolveConnectionEndpoint() {
457
+ const configuredUrl = new URL(this.config.firefoxBidiWsUrl);
458
+
459
+ if (isHttpProtocol(configuredUrl.protocol)) {
460
+ return {
461
+ webSocketUrl: joinUrlPath(
462
+ toWebSocketEndpointUrl(configuredUrl),
463
+ "/session",
464
+ ).toString(),
465
+ requiresSessionNew: true,
466
+ sessionId: null,
467
+ capabilities: null,
468
+ };
469
+ }
470
+
471
+ if (isRootPathname(configuredUrl.pathname)) {
472
+ configuredUrl.pathname = "/session";
473
+ }
474
+
475
+ return {
476
+ webSocketUrl: configuredUrl.toString(),
477
+ requiresSessionNew: configuredUrl.pathname === "/session",
478
+ sessionId:
479
+ configuredUrl.pathname === "/session"
480
+ ? null
481
+ : configuredUrl.pathname.split("/").at(-1) ||
482
+ configuredUrl.toString(),
483
+ capabilities: null,
484
+ };
485
+ }
486
+
487
+ async waitForWebSocketClose(websocket, timeoutMs = 250) {
488
+ if (!websocket || websocket.readyState === WebSocket.CLOSED) {
489
+ return;
490
+ }
491
+
492
+ await new Promise((resolve) => {
493
+ let settled = false;
494
+ const done = () => {
495
+ if (settled) {
496
+ return;
497
+ }
498
+ settled = true;
499
+ resolve();
500
+ };
501
+
502
+ websocket.addEventListener("close", done, { once: true });
503
+ const timer = setTimeout(done, timeoutMs);
504
+ timer.unref?.();
325
505
  });
506
+ }
507
+
508
+ async closeBrowserSession() {
509
+ if (!this.browserSessionId) {
510
+ return;
511
+ }
326
512
 
327
- this.browserSessionId = result.sessionId;
328
- this.capabilities = result.capabilities ?? {};
513
+ if (this.websocket?.readyState === WebSocket.OPEN) {
514
+ await this.send("session.end", {}).catch(() => {});
515
+ }
329
516
  }
330
517
 
331
518
  rejectPending(error) {
@@ -406,7 +593,7 @@ export class FirefoxBidiSessionManager {
406
593
  browser: this.capabilities?.browserName || "firefox",
407
594
  browserVersion: this.capabilities?.browserVersion ?? null,
408
595
  protocol: "webdriver-bidi",
409
- webSocketUrl: this.config.firefoxBidiWsUrl,
596
+ webSocketUrl: this.resolvedWebSocketUrl ?? this.config.firefoxBidiWsUrl,
410
597
  };
411
598
  } catch (error) {
412
599
  return {
@@ -466,6 +653,7 @@ export class FirefoxBidiSessionManager {
466
653
 
467
654
  session.subscription = subscription.subscription ?? null;
468
655
  this.sessions.set(session.id, session);
656
+ await this.seedBufferedState(session);
469
657
  return session.getSummary();
470
658
  }
471
659
 
@@ -488,53 +676,84 @@ export class FirefoxBidiSessionManager {
488
676
 
489
677
  async evaluate(sessionId, expression, options = {}) {
490
678
  const session = this.getSession(sessionId);
491
- const result = await this.send("script.evaluate", {
679
+ const result = await this.evaluateInContext(session, expression, options);
680
+
681
+ return {
682
+ result:
683
+ result.type === "success"
684
+ ? summarizeBidiRemoteValue(result.result)
685
+ : null,
686
+ exceptionDetails:
687
+ result.type === "exception" ? result.exceptionDetails : null,
688
+ realm: result.realm ?? null,
689
+ };
690
+ }
691
+
692
+ async evaluateInContext(session, expression, options = {}) {
693
+ return this.send("script.evaluate", {
492
694
  expression,
493
695
  target: {
494
696
  context: session.target.targetId,
495
697
  },
496
698
  awaitPromise: options.awaitPromise ?? true,
497
699
  resultOwnership: "none",
498
- serializationOptions: {
700
+ serializationOptions: options.serializationOptions ?? {
499
701
  maxObjectDepth: 5,
500
702
  maxDomDepth: 0,
501
703
  },
502
- userActivation: false,
704
+ userActivation: options.userActivation ?? false,
503
705
  });
706
+ }
504
707
 
505
- return {
506
- result:
507
- result.type === "success"
508
- ? summarizeBidiRemoteValue(result.result)
509
- : null,
510
- exceptionDetails:
511
- result.type === "exception" ? result.exceptionDetails : null,
512
- realm: result.realm ?? null,
513
- };
708
+ async runPageAction(session, payload, options = {}) {
709
+ const result = await this.evaluateInContext(
710
+ session,
711
+ buildPageContextExpression(
712
+ {
713
+ browserFamily: "firefox",
714
+ ...payload,
715
+ },
716
+ { serialize: true },
717
+ ),
718
+ {
719
+ awaitPromise: true,
720
+ serializationOptions: {
721
+ maxObjectDepth: 1,
722
+ maxDomDepth: 0,
723
+ },
724
+ userActivation: options.userActivation ?? false,
725
+ },
726
+ );
727
+
728
+ if (result.type !== "success") {
729
+ throw new Error(
730
+ result.exceptionDetails?.text || "Firefox page action failed",
731
+ );
732
+ }
733
+
734
+ const payloadText = summarizeBidiRemoteValue(result.result);
735
+ return JSON.parse(payloadText);
514
736
  }
515
737
 
516
738
  async getDocument(sessionId, depth) {
517
739
  const session = this.getSession(sessionId);
518
740
  const requestedDepth = normalizeRequestedDepth(depth);
519
- const result = await this.send("script.evaluate", {
520
- expression: `JSON.stringify({
741
+ const result = await this.evaluateInContext(
742
+ session,
743
+ `JSON.stringify({
521
744
  title: document.title,
522
745
  url: location.href,
523
746
  readyState: document.readyState,
524
747
  requestedDepth: ${JSON.stringify(requestedDepth)},
525
748
  outerHTML: document.documentElement ? document.documentElement.outerHTML : null
526
749
  })`,
527
- target: {
528
- context: session.target.targetId,
529
- },
530
- awaitPromise: true,
531
- resultOwnership: "none",
532
- serializationOptions: {
533
- maxObjectDepth: 1,
534
- maxDomDepth: 0,
750
+ {
751
+ serializationOptions: {
752
+ maxObjectDepth: 1,
753
+ maxDomDepth: 0,
754
+ },
535
755
  },
536
- userActivation: false,
537
- });
756
+ );
538
757
 
539
758
  if (result.type !== "success") {
540
759
  return {
@@ -550,11 +769,219 @@ export class FirefoxBidiSessionManager {
550
769
  };
551
770
  }
552
771
 
553
- async takeScreenshot(sessionId, format) {
772
+ async getPageState(sessionId) {
554
773
  const session = this.getSession(sessionId);
555
- return this.send("browsingContext.captureScreenshot", {
774
+ const result = await this.runPageAction(session, {
775
+ action: "page_state",
776
+ });
777
+
778
+ return {
779
+ browserFamily: "firefox",
780
+ ...result.page,
781
+ lastNavigationAt: session.lastNavigationAt,
782
+ lastReloadAt: session.lastReloadAt,
783
+ viewportOverride: session.viewportOverride,
784
+ };
785
+ }
786
+
787
+ async navigate(sessionId, url, options = {}) {
788
+ const session = this.getSession(sessionId);
789
+ const waitUntil = normalizeWaitUntil(options.waitUntil);
790
+ const initiatedAt = new Date().toISOString();
791
+ const result = await this.send("browsingContext.navigate", {
792
+ context: session.target.targetId,
793
+ url,
794
+ wait: waitUntil,
795
+ });
796
+
797
+ session.target.url = url;
798
+ const page =
799
+ waitUntil === "none" ? null : await this.getPageState(sessionId);
800
+ return {
801
+ browserFamily: "firefox",
802
+ url,
803
+ navigation: result.navigation ?? null,
804
+ waitUntil,
805
+ initiatedAt,
806
+ page,
807
+ };
808
+ }
809
+
810
+ async reload(sessionId, options = {}) {
811
+ const session = this.getSession(sessionId);
812
+ const waitUntil = normalizeWaitUntil(options.waitUntil);
813
+ const reloadedAt = new Date().toISOString();
814
+ const result = await this.send("browsingContext.reload", {
815
+ context: session.target.targetId,
816
+ ignoreCache: options.ignoreCache ?? false,
817
+ wait: waitUntil,
818
+ });
819
+
820
+ session.lastReloadAt = reloadedAt;
821
+ const page =
822
+ waitUntil === "none" ? null : await this.getPageState(sessionId);
823
+ return {
824
+ browserFamily: "firefox",
825
+ url: session.target.url,
826
+ navigation: result.navigation ?? null,
827
+ waitUntil,
828
+ ignoreCache: options.ignoreCache ?? false,
829
+ reloadedAt,
830
+ page,
831
+ };
832
+ }
833
+
834
+ async click(sessionId, selector) {
835
+ return this.runPageAction(
836
+ this.getSession(sessionId),
837
+ {
838
+ action: "click",
839
+ selector,
840
+ },
841
+ { userActivation: true },
842
+ );
843
+ }
844
+
845
+ async hover(sessionId, selector) {
846
+ return this.runPageAction(
847
+ this.getSession(sessionId),
848
+ {
849
+ action: "hover",
850
+ selector,
851
+ },
852
+ { userActivation: true },
853
+ );
854
+ }
855
+
856
+ async type(sessionId, selector, text, options = {}) {
857
+ return this.runPageAction(
858
+ this.getSession(sessionId),
859
+ {
860
+ action: "type",
861
+ selector,
862
+ text,
863
+ clear: options.clear,
864
+ },
865
+ { userActivation: true },
866
+ );
867
+ }
868
+
869
+ async select(sessionId, selector, options = {}) {
870
+ return this.runPageAction(
871
+ this.getSession(sessionId),
872
+ {
873
+ action: "select",
874
+ selector,
875
+ value: options.value,
876
+ label: options.label,
877
+ },
878
+ { userActivation: true },
879
+ );
880
+ }
881
+
882
+ async pressKey(sessionId, key, selector = null) {
883
+ return this.runPageAction(
884
+ this.getSession(sessionId),
885
+ {
886
+ action: "press_key",
887
+ key,
888
+ selector,
889
+ },
890
+ { userActivation: true },
891
+ );
892
+ }
893
+
894
+ async scroll(sessionId, options = {}) {
895
+ return this.runPageAction(
896
+ this.getSession(sessionId),
897
+ {
898
+ action: "scroll",
899
+ selector: options.selector,
900
+ deltaX: options.deltaX,
901
+ deltaY: options.deltaY,
902
+ block: options.block,
903
+ },
904
+ { userActivation: true },
905
+ );
906
+ }
907
+
908
+ async setViewport(sessionId, options) {
909
+ const session = this.getSession(sessionId);
910
+ const params = {
911
+ context: session.target.targetId,
912
+ viewport: {
913
+ width: options.width,
914
+ height: options.height,
915
+ },
916
+ };
917
+
918
+ if (
919
+ typeof options.deviceScaleFactor === "number" &&
920
+ options.deviceScaleFactor > 0
921
+ ) {
922
+ params.devicePixelRatio = options.deviceScaleFactor;
923
+ }
924
+
925
+ await this.send("browsingContext.setViewport", params);
926
+ session.viewportOverride = {
927
+ width: options.width,
928
+ height: options.height,
929
+ deviceScaleFactor: params.devicePixelRatio ?? null,
930
+ mobile: options.mobile ?? false,
931
+ appliedAt: new Date().toISOString(),
932
+ };
933
+
934
+ return {
935
+ browserFamily: "firefox",
936
+ applied: true,
937
+ viewport: session.viewportOverride,
938
+ page: await this.getPageState(sessionId),
939
+ };
940
+ }
941
+
942
+ async takeScreenshot(sessionId, format, options = {}) {
943
+ const session = this.getSession(sessionId);
944
+ const params = {
556
945
  context: session.target.targetId,
557
946
  format: screenshotFormat(format),
947
+ };
948
+
949
+ if (options.selector) {
950
+ const inspected = await this.runPageAction(session, {
951
+ action: "inspect",
952
+ selector: options.selector,
953
+ scrollIntoView: true,
954
+ });
955
+
956
+ if (!inspected.found) {
957
+ return {
958
+ browserFamily: "firefox",
959
+ format,
960
+ scope: "element",
961
+ selector: options.selector,
962
+ found: false,
963
+ };
964
+ }
965
+
966
+ params.origin = "viewport";
967
+ params.clip = {
968
+ type: "box",
969
+ x: Math.max(inspected.node.box?.x ?? 0, 0),
970
+ y: Math.max(inspected.node.box?.y ?? 0, 0),
971
+ width: Math.max(inspected.node.box?.width ?? 0, 1),
972
+ height: Math.max(inspected.node.box?.height ?? 0, 1),
973
+ };
974
+ }
975
+
976
+ const screenshot = await this.send(
977
+ "browsingContext.captureScreenshot",
978
+ params,
979
+ );
980
+ return formatScreenshotResult(screenshot.data, format, {
981
+ browserFamily: "firefox",
982
+ scope: options.selector ? "element" : "page",
983
+ selector: options.selector ?? null,
984
+ clip: params.clip ?? null,
558
985
  });
559
986
  }
560
987
 
@@ -567,62 +994,35 @@ export class FirefoxBidiSessionManager {
567
994
  }
568
995
 
569
996
  async inspectElement(sessionId, selector) {
570
- const session = this.getSession(sessionId);
571
- const result = await this.send("script.evaluate", {
572
- expression: `(() => {
573
- const selector = ${JSON.stringify(selector)};
574
- const element = document.querySelector(selector);
575
- if (!element) {
576
- return JSON.stringify({
577
- browserFamily: "firefox",
578
- selector,
579
- found: false
580
- });
581
- }
997
+ return this.runPageAction(this.getSession(sessionId), {
998
+ action: "inspect",
999
+ selector,
1000
+ });
1001
+ }
582
1002
 
583
- const attributes = Object.fromEntries(
584
- Array.from(element.attributes, (attribute) => [attribute.name, attribute.value])
585
- );
1003
+ async seedBufferedState(session) {
1004
+ try {
1005
+ const snapshot = await this.runPageAction(session, {
1006
+ action: "network_snapshot",
1007
+ });
586
1008
 
587
- return JSON.stringify({
588
- browserFamily: "firefox",
589
- selector,
590
- found: true,
591
- node: {
592
- tagName: element.tagName,
593
- id: element.getAttribute("id"),
594
- className: element.getAttribute("class"),
595
- childElementCount: element.childElementCount,
596
- attributes,
597
- textContent: element.textContent,
598
- innerText: typeof element.innerText === "string" ? element.innerText : null,
599
- outerHTML: element.outerHTML
600
- }
1009
+ for (const entry of snapshot?.entries ?? []) {
1010
+ session.pushEvent({
1011
+ method: "network.snapshotCaptured",
1012
+ capturedAt: new Date().toISOString(),
1013
+ kind: "network",
1014
+ phase: "snapshot",
1015
+ completed: true,
1016
+ finished: true,
1017
+ failed: false,
1018
+ canceled: false,
1019
+ source: "performance",
1020
+ ...entry,
601
1021
  });
602
- })()`,
603
- target: {
604
- context: session.target.targetId,
605
- },
606
- awaitPromise: true,
607
- resultOwnership: "none",
608
- serializationOptions: {
609
- maxObjectDepth: 1,
610
- maxDomDepth: 0,
611
- },
612
- userActivation: false,
613
- });
614
-
615
- if (result.type !== "success") {
616
- return {
617
- browserFamily: "firefox",
618
- selector,
619
- found: false,
620
- exceptionDetails: result.exceptionDetails ?? null,
621
- };
1022
+ }
1023
+ } catch {
1024
+ // Ignore snapshot failures so attach still succeeds.
622
1025
  }
623
-
624
- const payload = summarizeBidiRemoteValue(result.result);
625
- return JSON.parse(payload);
626
1026
  }
627
1027
 
628
1028
  getEvents(sessionId, limit) {
@@ -636,10 +1036,19 @@ export class FirefoxBidiSessionManager {
636
1036
  ),
637
1037
  );
638
1038
 
639
- if (this.websocket && this.websocket.readyState < WebSocket.CLOSING) {
640
- this.websocket.close();
1039
+ const websocket = this.websocket;
1040
+
1041
+ await this.closeBrowserSession();
1042
+
1043
+ if (websocket && websocket.readyState < WebSocket.CLOSING) {
1044
+ websocket.close();
1045
+ await this.waitForWebSocketClose(websocket);
641
1046
  }
642
1047
 
643
1048
  this.sessions.clear();
1049
+ this.websocket = null;
1050
+ this.browserSessionId = null;
1051
+ this.capabilities = null;
1052
+ this.resolvedWebSocketUrl = null;
644
1053
  }
645
1054
  }