mcp-browser-dev-tools 0.0.1 → 0.0.2

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,7 +1,10 @@
1
1
  import {
2
+ exportHarLikeSummary,
2
3
  filterConsoleMessages,
3
4
  summarizeNetworkRequests,
4
5
  } from "./session-events.mjs";
6
+ import { DEFAULT_FIREFOX_BIDI_WS_URL } from "./config.mjs";
7
+ import { waitForPageCondition } from "./wait-for.mjs";
5
8
  import { buildPageContextExpression } from "./page-context.mjs";
6
9
 
7
10
  function toErrorMessage(error) {
@@ -258,6 +261,36 @@ function toWebSocketEndpointUrl(endpointUrl) {
258
261
  return url;
259
262
  }
260
263
 
264
+ function buildDiscoveryWebSocketUrls(configuredUrl) {
265
+ const configured = new URL(configuredUrl);
266
+ const candidatePorts = [
267
+ configured.port || "9222",
268
+ "9223",
269
+ "9224",
270
+ "9225",
271
+ "9226",
272
+ ];
273
+ const seen = new Set();
274
+ const candidates = [];
275
+
276
+ for (const port of candidatePorts) {
277
+ const candidate = new URL(configured.toString());
278
+ candidate.port = port;
279
+ candidate.pathname = "/";
280
+ candidate.search = "";
281
+ candidate.hash = "";
282
+ const normalized = candidate.toString().replace(/\/+$/, "");
283
+ if (seen.has(normalized)) {
284
+ continue;
285
+ }
286
+
287
+ seen.add(normalized);
288
+ candidates.push(normalized);
289
+ }
290
+
291
+ return candidates;
292
+ }
293
+
261
294
  function joinUrlPath(baseUrl, pathname) {
262
295
  const url = new URL(baseUrl);
263
296
  const basePath = url.pathname.replace(/\/+$/, "");
@@ -344,9 +377,14 @@ export class FirefoxBidiSessionManager {
344
377
  this.browserSessionId = null;
345
378
  this.capabilities = null;
346
379
  this.connectPromise = null;
380
+ this.discoveredEndpointUrl = null;
347
381
  this.resolvedWebSocketUrl = null;
348
382
  }
349
383
 
384
+ shouldAutoDiscoverEndpoint() {
385
+ return this.config.firefoxBidiWsUrl === DEFAULT_FIREFOX_BIDI_WS_URL;
386
+ }
387
+
350
388
  async ensureConnected() {
351
389
  if (
352
390
  this.browserSessionId &&
@@ -368,9 +406,31 @@ export class FirefoxBidiSessionManager {
368
406
  }
369
407
 
370
408
  async openConnection() {
371
- const endpoint = await this.resolveConnectionEndpoint();
372
- this.resolvedWebSocketUrl = endpoint.webSocketUrl;
373
- this.websocket = this.websocketFactory(endpoint.webSocketUrl);
409
+ const candidates = this.shouldAutoDiscoverEndpoint()
410
+ ? buildDiscoveryWebSocketUrls(this.config.firefoxBidiWsUrl)
411
+ : [this.config.firefoxBidiWsUrl];
412
+ let lastError = null;
413
+
414
+ for (const candidate of candidates) {
415
+ const endpoint = this.resolveConnectionEndpoint(candidate);
416
+ try {
417
+ await this.openConnectionAt(endpoint);
418
+ this.discoveredEndpointUrl = candidate;
419
+ return;
420
+ } catch (error) {
421
+ lastError = error;
422
+ await this.resetConnectionState();
423
+ }
424
+ }
425
+
426
+ throw (
427
+ lastError ?? new Error("Unable to connect to a Firefox BiDi endpoint")
428
+ );
429
+ }
430
+
431
+ async openConnectionAt(endpoint) {
432
+ const websocket = this.websocketFactory(endpoint.webSocketUrl);
433
+ this.websocket = websocket;
374
434
 
375
435
  await new Promise((resolve, reject) => {
376
436
  let settled = false;
@@ -380,7 +440,7 @@ export class FirefoxBidiSessionManager {
380
440
  }
381
441
 
382
442
  settled = true;
383
- this.websocket?.close?.();
443
+ websocket.close?.();
384
444
  reject(
385
445
  new Error(
386
446
  `Timed out connecting to Firefox BiDi at ${endpoint.webSocketUrl}`,
@@ -399,7 +459,7 @@ export class FirefoxBidiSessionManager {
399
459
  callback();
400
460
  };
401
461
 
402
- this.websocket.addEventListener(
462
+ websocket.addEventListener(
403
463
  "open",
404
464
  () => {
405
465
  settle(resolve);
@@ -407,27 +467,35 @@ export class FirefoxBidiSessionManager {
407
467
  { once: true },
408
468
  );
409
469
 
410
- this.websocket.addEventListener(
470
+ websocket.addEventListener(
411
471
  "error",
412
472
  () => {
413
473
  settle(() => {
414
- reject(
415
- new Error(`Failed to connect to ${this.config.firefoxBidiWsUrl}`),
416
- );
474
+ reject(new Error(`Failed to connect to ${endpoint.webSocketUrl}`));
417
475
  });
418
476
  },
419
477
  { once: true },
420
478
  );
421
479
 
422
- this.websocket.addEventListener("message", (event) => {
480
+ websocket.addEventListener("message", (event) => {
481
+ if (this.websocket !== websocket) {
482
+ return;
483
+ }
484
+
423
485
  void this.handleMessage(event.data);
424
486
  });
425
487
 
426
- this.websocket.addEventListener("close", () => {
488
+ websocket.addEventListener("close", () => {
489
+ if (this.websocket !== websocket) {
490
+ return;
491
+ }
492
+
427
493
  this.rejectPending(new Error("Firefox BiDi connection closed"));
428
494
  this.websocket = null;
429
495
  this.browserSessionId = null;
430
496
  this.capabilities = null;
497
+ this.discoveredEndpointUrl = null;
498
+ this.resolvedWebSocketUrl = null;
431
499
  this.sessions.clear();
432
500
  settle(() => {
433
501
  reject(
@@ -446,15 +514,31 @@ export class FirefoxBidiSessionManager {
446
514
 
447
515
  this.browserSessionId = result.sessionId;
448
516
  this.capabilities = result.capabilities ?? {};
517
+ this.resolvedWebSocketUrl = endpoint.webSocketUrl;
449
518
  return;
450
519
  }
451
520
 
452
521
  this.browserSessionId = endpoint.sessionId;
453
522
  this.capabilities = endpoint.capabilities ?? {};
523
+ this.resolvedWebSocketUrl = endpoint.webSocketUrl;
524
+ }
525
+
526
+ async resetConnectionState() {
527
+ if (this.websocket?.readyState < WebSocket.CLOSING) {
528
+ this.websocket.close();
529
+ await this.waitForWebSocketClose(this.websocket, 50);
530
+ }
531
+
532
+ this.rejectPending(new Error("Firefox BiDi connection closed"));
533
+ this.websocket = null;
534
+ this.browserSessionId = null;
535
+ this.capabilities = null;
536
+ this.discoveredEndpointUrl = null;
537
+ this.resolvedWebSocketUrl = null;
454
538
  }
455
539
 
456
- async resolveConnectionEndpoint() {
457
- const configuredUrl = new URL(this.config.firefoxBidiWsUrl);
540
+ resolveConnectionEndpoint(endpointUrl = this.config.firefoxBidiWsUrl) {
541
+ const configuredUrl = new URL(endpointUrl);
458
542
 
459
543
  if (isHttpProtocol(configuredUrl.protocol)) {
460
544
  return {
@@ -588,17 +672,20 @@ export class FirefoxBidiSessionManager {
588
672
  await this.ensureConnected();
589
673
  return {
590
674
  available: true,
591
- endpoint: this.config.firefoxBidiWsUrl,
675
+ endpoint: this.discoveredEndpointUrl ?? this.config.firefoxBidiWsUrl,
592
676
  sessionCount: this.sessions.size,
593
677
  browser: this.capabilities?.browserName || "firefox",
594
678
  browserVersion: this.capabilities?.browserVersion ?? null,
595
679
  protocol: "webdriver-bidi",
596
- webSocketUrl: this.resolvedWebSocketUrl ?? this.config.firefoxBidiWsUrl,
680
+ webSocketUrl:
681
+ this.resolvedWebSocketUrl ??
682
+ this.discoveredEndpointUrl ??
683
+ this.config.firefoxBidiWsUrl,
597
684
  };
598
685
  } catch (error) {
599
686
  return {
600
687
  available: false,
601
- endpoint: this.config.firefoxBidiWsUrl,
688
+ endpoint: this.discoveredEndpointUrl ?? this.config.firefoxBidiWsUrl,
602
689
  sessionCount: this.sessions.size,
603
690
  protocol: "webdriver-bidi",
604
691
  error: toErrorMessage(error),
@@ -620,6 +707,46 @@ export class FirefoxBidiSessionManager {
620
707
  );
621
708
  }
622
709
 
710
+ async createTab(url = "about:blank") {
711
+ await this.ensureConnected();
712
+ const targetUrl =
713
+ typeof url === "string" && url.trim() ? url.trim() : "about:blank";
714
+ const result = await this.send("browsingContext.create", {
715
+ type: "tab",
716
+ });
717
+ const targetId = result.context;
718
+ if (!targetId) {
719
+ throw new Error(
720
+ "Firefox did not return a browsing context id for the new tab",
721
+ );
722
+ }
723
+
724
+ if (targetUrl !== "about:blank") {
725
+ await this.send("browsingContext.navigate", {
726
+ context: targetId,
727
+ url: targetUrl,
728
+ wait: "complete",
729
+ });
730
+ }
731
+
732
+ const target = (await this.listTargets()).find(
733
+ (candidate) => candidate.targetId === targetId,
734
+ );
735
+
736
+ return {
737
+ browserFamily: "firefox",
738
+ ...(target ?? {
739
+ targetId,
740
+ type: "page",
741
+ title: inferTitle(targetUrl),
742
+ url: targetUrl,
743
+ attached: false,
744
+ userContext: null,
745
+ clientWindow: null,
746
+ }),
747
+ };
748
+ }
749
+
623
750
  getSession(sessionId) {
624
751
  const session = this.sessions.get(sessionId);
625
752
  if (!session) {
@@ -674,6 +801,28 @@ export class FirefoxBidiSessionManager {
674
801
  };
675
802
  }
676
803
 
804
+ async closeTarget(targetId) {
805
+ await this.ensureConnected();
806
+ await this.send("browsingContext.close", {
807
+ context: targetId,
808
+ });
809
+
810
+ const detachedSessions = Array.from(this.sessions.values())
811
+ .filter((session) => session.target.targetId === targetId)
812
+ .map((session) => {
813
+ session.closed = true;
814
+ this.sessions.delete(session.id);
815
+ return { sessionId: session.id };
816
+ });
817
+
818
+ return {
819
+ browserFamily: "firefox",
820
+ closed: true,
821
+ targetId,
822
+ detachedSessions,
823
+ };
824
+ }
825
+
677
826
  async evaluate(sessionId, expression, options = {}) {
678
827
  const session = this.getSession(sessionId);
679
828
  const result = await this.evaluateInContext(session, expression, options);
@@ -784,6 +933,14 @@ export class FirefoxBidiSessionManager {
784
933
  };
785
934
  }
786
935
 
936
+ async waitFor(sessionId, options = {}) {
937
+ return waitForPageCondition({
938
+ getPageState: () => this.getPageState(sessionId),
939
+ inspectElement: (selector) => this.inspectElement(sessionId, selector),
940
+ options,
941
+ });
942
+ }
943
+
787
944
  async navigate(sessionId, url, options = {}) {
788
945
  const session = this.getSession(sessionId);
789
946
  const waitUntil = normalizeWaitUntil(options.waitUntil);
@@ -993,6 +1150,84 @@ export class FirefoxBidiSessionManager {
993
1150
  return this.getSession(sessionId).getNetworkRequests(limit);
994
1151
  }
995
1152
 
1153
+ async getCookies(sessionId) {
1154
+ return this.runPageAction(this.getSession(sessionId), {
1155
+ action: "cookie_snapshot",
1156
+ });
1157
+ }
1158
+
1159
+ async getStorage(sessionId) {
1160
+ return this.runPageAction(this.getSession(sessionId), {
1161
+ action: "storage_snapshot",
1162
+ });
1163
+ }
1164
+
1165
+ async captureDebugReport(sessionId, options = {}) {
1166
+ const session = this.getSession(sessionId);
1167
+ const consoleLimit =
1168
+ Number.isInteger(options.consoleLimit) && options.consoleLimit > 0
1169
+ ? options.consoleLimit
1170
+ : 20;
1171
+ const networkLimit =
1172
+ Number.isInteger(options.networkLimit) && options.networkLimit > 0
1173
+ ? options.networkLimit
1174
+ : 20;
1175
+ const includeScreenshot = options.includeScreenshot !== false;
1176
+ const screenshotFormat = options.screenshotFormat ?? "png";
1177
+ const snapshot = await this.runPageAction(session, {
1178
+ action: "debug_report",
1179
+ });
1180
+
1181
+ return {
1182
+ browserFamily: "firefox",
1183
+ capturedAt: new Date().toISOString(),
1184
+ page: {
1185
+ ...(await this.getPageState(sessionId)),
1186
+ },
1187
+ cookies: snapshot.cookies,
1188
+ storage: snapshot.storage,
1189
+ console: session.getConsoleMessages(consoleLimit),
1190
+ network: session.getNetworkRequests(networkLimit),
1191
+ screenshot: includeScreenshot
1192
+ ? await this.takeScreenshot(sessionId, screenshotFormat)
1193
+ : null,
1194
+ };
1195
+ }
1196
+
1197
+ getHar(sessionId, options = {}) {
1198
+ const session = this.getSession(sessionId);
1199
+ return exportHarLikeSummary(session.bufferedEvents, {
1200
+ limit: options.limit ?? 50,
1201
+ page: {
1202
+ title: session.target.title,
1203
+ url: session.target.url,
1204
+ },
1205
+ });
1206
+ }
1207
+
1208
+ async captureSessionSnapshot(sessionId) {
1209
+ return {
1210
+ browserFamily: "firefox",
1211
+ capturedAt: new Date().toISOString(),
1212
+ page: await this.getPageState(sessionId),
1213
+ ...(await this.getCookies(sessionId)),
1214
+ ...(await this.getStorage(sessionId)),
1215
+ };
1216
+ }
1217
+
1218
+ async restoreSessionSnapshot(sessionId, snapshot, options = {}) {
1219
+ const result = await this.runPageAction(this.getSession(sessionId), {
1220
+ action: "restore_snapshot",
1221
+ snapshot,
1222
+ clearStorage: options.clearStorage === true,
1223
+ });
1224
+
1225
+ return {
1226
+ ...result,
1227
+ page: await this.getPageState(sessionId),
1228
+ };
1229
+ }
1230
+
996
1231
  async inspectElement(sessionId, selector) {
997
1232
  return this.runPageAction(this.getSession(sessionId), {
998
1233
  action: "inspect",
package/src/index.mjs CHANGED
@@ -14,14 +14,17 @@ export {
14
14
  DEFAULT_CDP_BASE_URL,
15
15
  DEFAULT_EVENT_BUFFER_SIZE,
16
16
  DEFAULT_FIREFOX_BIDI_WS_URL,
17
+ DEFAULT_LOG_LEVEL,
17
18
  DEFAULT_PROTOCOL_VERSION,
18
19
  isLoopbackHost,
19
20
  isLoopbackOrigin,
20
21
  isTruthyFlag,
21
22
  loadConfig,
23
+ loadLoggingConfig,
22
24
  normalizeBaseUrl,
23
25
  normalizeWebSocketUrl,
24
26
  parseBrowserFamily,
27
+ parseLogLevel,
25
28
  parsePositiveInteger,
26
29
  } from "./config.mjs";
27
30
  export { collectDoctorReport, renderDoctorReport } from "./doctor.mjs";
package/src/logger.mjs ADDED
@@ -0,0 +1,53 @@
1
+ import process from "node:process";
2
+
3
+ import { PACKAGE_NAME } from "./package-info.mjs";
4
+
5
+ export const LOG_LEVELS = {
6
+ error: 0,
7
+ warn: 1,
8
+ info: 2,
9
+ debug: 3,
10
+ };
11
+
12
+ function normalizeMessage(message) {
13
+ if (message instanceof Error) {
14
+ return message.message;
15
+ }
16
+
17
+ return String(message);
18
+ }
19
+
20
+ export function createLogger({
21
+ level = "error",
22
+ output = process.stderr,
23
+ name = PACKAGE_NAME,
24
+ } = {}) {
25
+ const threshold = LOG_LEVELS[level] ?? LOG_LEVELS.error;
26
+
27
+ return {
28
+ level,
29
+ enabled(messageLevel) {
30
+ return (LOG_LEVELS[messageLevel] ?? -1) <= threshold;
31
+ },
32
+ log(messageLevel, message, options = {}) {
33
+ if (!options.force && !this.enabled(messageLevel)) {
34
+ return false;
35
+ }
36
+
37
+ output.write(`[${name}] ${messageLevel}: ${normalizeMessage(message)}\n`);
38
+ return true;
39
+ },
40
+ error(message, options) {
41
+ return this.log("error", message, options);
42
+ },
43
+ warn(message, options) {
44
+ return this.log("warn", message, options);
45
+ },
46
+ info(message, options) {
47
+ return this.log("info", message, options);
48
+ },
49
+ debug(message, options) {
50
+ return this.log("debug", message, options);
51
+ },
52
+ };
53
+ }