mcp-browser-dev-tools 0.4.1 → 0.5.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.
@@ -693,6 +693,101 @@ export function pageScript(payload) {
693
693
  };
694
694
  }
695
695
 
696
+ // The elements a locator matches, each with a ref and what its line
697
+ // needs, and on request its box, attributes, and computed styles.
698
+ function queryElements() {
699
+ const result = {
700
+ browserFamily: payload.browserFamily,
701
+ selector: payload.selector,
702
+ };
703
+ const { elements: matches, ...resolved } = resolveLocatorAll(
704
+ payload.selector,
705
+ );
706
+ if (resolved.error) {
707
+ return {
708
+ ...result,
709
+ found: false,
710
+ locator: summarizeLocator(resolved),
711
+ error: resolved.error,
712
+ };
713
+ }
714
+ pruneRefs(refRegistry());
715
+ const names = (list) => (Array.isArray(list) ? list.map(String) : []);
716
+ const attributes = names(payload.attributes);
717
+ const styles = names(payload.styles);
718
+ const tenth = (value) => Math.round(value * 10) / 10;
719
+ return {
720
+ ...result,
721
+ count: matches.length,
722
+ elements: matches.slice(0, payload.limit).map((element) => {
723
+ const entry = {
724
+ ref: refFor(element),
725
+ node: {
726
+ tagName: element.tagName,
727
+ id: element.getAttribute("id"),
728
+ className: element.getAttribute("class"),
729
+ attributes: {
730
+ type: element.getAttribute("type"),
731
+ "aria-checked": element.getAttribute("aria-checked"),
732
+ },
733
+ // A password's value stays in the page; the line says filled.
734
+ value:
735
+ "value" in element && typeof element.value === "string"
736
+ ? isPassword(element)
737
+ ? element.value && "filled"
738
+ : clipText(element.value)
739
+ : null,
740
+ accessibleName:
741
+ clipText(normalizeText(getAccessibleName(element))) || null,
742
+ role: inferRole(element),
743
+ visible: isVisible(element),
744
+ disabled: isDisabled(element),
745
+ checked: "checked" in element ? Boolean(element.checked) : null,
746
+ },
747
+ };
748
+ if (payload.box) {
749
+ const rect = element.getBoundingClientRect();
750
+ entry.box = {
751
+ x: tenth(rect.x),
752
+ y: tenth(rect.y),
753
+ width: tenth(rect.width),
754
+ height: tenth(rect.height),
755
+ };
756
+ }
757
+ if (attributes.length > 0) {
758
+ entry.attributes = Object.fromEntries(
759
+ attributes.map((name) => [
760
+ name,
761
+ isPassword(element) && name.toLowerCase() === "value"
762
+ ? null
763
+ : element.getAttribute(name),
764
+ ]),
765
+ );
766
+ }
767
+ if (styles.length > 0) {
768
+ const computed = getComputedStyle(element);
769
+ entry.styles = Object.fromEntries(
770
+ styles.map((name) => [
771
+ name,
772
+ computed
773
+ .getPropertyValue(
774
+ name.startsWith("--")
775
+ ? name
776
+ : name.replace(
777
+ /[A-Z]/g,
778
+ (letter) => "-" + letter.toLowerCase(),
779
+ ),
780
+ )
781
+ .trim(),
782
+ ]),
783
+ );
784
+ }
785
+ return entry;
786
+ }),
787
+ nextRef: refRegistry().next,
788
+ };
789
+ }
790
+
696
791
  // Actions report what they changed. change_baseline records the visible
697
792
  // headings and controls, and the text of live regions, before the action
698
793
  // and watches the DOM; change_status tells the server how long the DOM has
@@ -913,6 +1008,14 @@ export function pageScript(payload) {
913
1008
  return pending;
914
1009
  }
915
1010
 
1011
+ // A state that holds no snapshot is of no use once its document is left:
1012
+ // the new document gets its own. Ending it then keeps a document in the
1013
+ // back/forward cache from holding an observer and a count on the timers.
1014
+ function stopWhenLeft(state) {
1015
+ state.onLeave = () => stopChangeTracking(state);
1016
+ window.addEventListener("pagehide", state.onLeave, { once: true });
1017
+ }
1018
+
916
1019
  function startChangeTracking(state) {
917
1020
  watchTimers();
918
1021
  if (typeof MutationObserver === "function") {
@@ -931,6 +1034,10 @@ export function pageScript(payload) {
931
1034
 
932
1035
  function stopChangeTracking(state) {
933
1036
  state.observer?.disconnect();
1037
+ if (state.onLeave) {
1038
+ window.removeEventListener("pagehide", state.onLeave);
1039
+ state.onLeave = null;
1040
+ }
934
1041
  const states = window[CHANGE_KEY];
935
1042
  if (states?.get(state.id) === state) {
936
1043
  states.delete(state.id);
@@ -998,6 +1105,23 @@ export function pageScript(payload) {
998
1105
 
999
1106
  function changeBaseline() {
1000
1107
  dropAbandonedStates();
1108
+ // A watch only tells when the page is quiet, so it takes no snapshot.
1109
+ // It follows a new action, so a timer handler that ran under an earlier
1110
+ // watch counts again.
1111
+ if (payload.watchOnly) {
1112
+ startChangeTracking({
1113
+ id: payload.changeId,
1114
+ owner: payload.owner,
1115
+ createdAt: Date.now(),
1116
+ touched: new Set(),
1117
+ revealed: new Set(),
1118
+ lastMutationAt: Date.now(),
1119
+ observer: null,
1120
+ });
1121
+ stopWhenLeft(changeStates().get(payload.changeId));
1122
+ timerWatch().ran = new WeakSet();
1123
+ return { documentId: documentId() };
1124
+ }
1001
1125
  pruneRefs(refRegistry());
1002
1126
  const { lines, beyond } = changeSnapshot();
1003
1127
  startChangeTracking({
@@ -1017,6 +1141,37 @@ export function pageScript(payload) {
1017
1141
  return { documentId: documentId(), nextRef: refRegistry().next };
1018
1142
  }
1019
1143
 
1144
+ // CSS transitions and animations that are running and end within a
1145
+ // second: a page showing one has not reached the state it is moving to.
1146
+ // Endless ones, such as a spinner, never count.
1147
+ const ANIMATION_WAIT_MS = 1000;
1148
+
1149
+ function finishingAnimations() {
1150
+ if (typeof document.getAnimations !== "function") {
1151
+ return 0;
1152
+ }
1153
+ try {
1154
+ return document.getAnimations().filter((animation) => {
1155
+ const end = animation.effect?.getComputedTiming?.().endTime;
1156
+ const now = animation.currentTime;
1157
+ const rate = animation.playbackRate;
1158
+ if (
1159
+ animation.playState !== "running" ||
1160
+ typeof end !== "number" ||
1161
+ typeof now !== "number" ||
1162
+ !rate
1163
+ ) {
1164
+ return false;
1165
+ }
1166
+ // Time left on the clock: played backwards, it ends at zero.
1167
+ const left = rate > 0 ? (end - now) / rate : now / -rate;
1168
+ return left <= ANIMATION_WAIT_MS;
1169
+ }).length;
1170
+ } catch {
1171
+ return 0;
1172
+ }
1173
+ }
1174
+
1020
1175
  function changeStatus() {
1021
1176
  const states = changeStates();
1022
1177
  if (documentId() !== payload.documentId) {
@@ -1032,12 +1187,14 @@ export function pageScript(payload) {
1032
1187
  observer: null,
1033
1188
  };
1034
1189
  startChangeTracking(watcher);
1190
+ stopWhenLeft(watcher);
1035
1191
  }
1036
1192
  return {
1037
1193
  document: "new",
1038
1194
  readyState: document.readyState,
1039
1195
  quietMs: Date.now() - watcher.lastMutationAt,
1040
1196
  timers: pendingTimers(watcher),
1197
+ animations: finishingAnimations(),
1041
1198
  };
1042
1199
  }
1043
1200
  const state = states.get(payload.changeId);
@@ -1048,6 +1205,7 @@ export function pageScript(payload) {
1048
1205
  document: "same",
1049
1206
  quietMs: Date.now() - state.lastMutationAt,
1050
1207
  timers: pendingTimers(state),
1208
+ animations: finishingAnimations(),
1051
1209
  };
1052
1210
  }
1053
1211
 
@@ -1335,121 +1493,247 @@ export function pageScript(payload) {
1335
1493
  }
1336
1494
  }
1337
1495
 
1338
- function resolveLocator(rawLocator) {
1339
- const locator = typeof rawLocator === "string" ? rawLocator.trim() : "";
1340
- if (!locator) {
1341
- throw new Error("selector must be a non-empty string");
1342
- }
1496
+ // The elements one part of a locator matches, in document order. scopes
1497
+ // are the elements the part before it matched (null for the whole page):
1498
+ // the part then looks inside them. Without all, the search stops at the
1499
+ // first match.
1500
+ function matchLocatorPart(part, scopes, all) {
1501
+ const candidates = () =>
1502
+ scopes
1503
+ ? scopes.flatMap((scope) => Array.from(scope.querySelectorAll("*")))
1504
+ : collectCandidates();
1505
+ const pick = (list, test) => {
1506
+ if (all) {
1507
+ return Array.from(new Set(list.filter(test)));
1508
+ }
1509
+ const first = list.find(test);
1510
+ return first ? [first] : [];
1511
+ };
1512
+ // Prefers elements that pass exact; falls back to those that pass loose.
1513
+ const pickEither = (list, exact, loose) => {
1514
+ const matches = pick(list, exact);
1515
+ return matches.length > 0 ? matches : pick(list, loose);
1516
+ };
1343
1517
 
1344
- if (locator.startsWith("ref=")) {
1345
- const query = locator.slice(4).trim();
1346
- const { element, error } = resolveRef(query);
1347
- const resolved = { locator, strategy: "ref", query, element };
1348
- if (error) {
1349
- resolved.error = error;
1518
+ if (part.startsWith("ref=")) {
1519
+ const query = part.slice(4).trim();
1520
+ if (scopes) {
1521
+ return {
1522
+ strategy: "ref",
1523
+ query,
1524
+ elements: [],
1525
+ error: "ref= can only start a locator",
1526
+ };
1350
1527
  }
1351
- return resolved;
1528
+ const { element, error } = resolveRef(query);
1529
+ return {
1530
+ strategy: "ref",
1531
+ query,
1532
+ elements: element ? [element] : [],
1533
+ ...(error ? { error } : {}),
1534
+ };
1352
1535
  }
1353
1536
 
1354
- if (locator.startsWith("text=")) {
1355
- const query = normalizeText(locator.slice(5));
1356
- const candidates = collectCandidates();
1357
- const match =
1358
- candidates.find(
1359
- (element) =>
1360
- isVisible(element) &&
1361
- normalizeText(getVisibleText(element)) === query,
1362
- ) ??
1363
- candidates.find((element) => {
1364
- const text = normalizeText(getVisibleText(element));
1365
- return isVisible(element) && text && text.includes(query);
1366
- });
1537
+ if (part.startsWith("has-text=")) {
1538
+ const query = normalizeText(part.slice(9));
1539
+ if (!scopes) {
1540
+ return {
1541
+ strategy: "has-text",
1542
+ query,
1543
+ elements: [],
1544
+ error:
1545
+ "has-text= filters the elements of the locator before it, for example tr >> has-text=Foo",
1546
+ };
1547
+ }
1548
+ return {
1549
+ strategy: "has-text",
1550
+ query,
1551
+ elements: pick(scopes, (element) =>
1552
+ normalizeText(getVisibleText(element)).includes(query),
1553
+ ),
1554
+ };
1555
+ }
1367
1556
 
1557
+ if (part.startsWith("text=")) {
1558
+ const query = normalizeText(part.slice(5));
1368
1559
  return {
1369
- locator,
1370
1560
  strategy: "text",
1371
1561
  query,
1372
- element: match ?? null,
1562
+ elements: pickEither(
1563
+ candidates(),
1564
+ (element) =>
1565
+ isVisible(element) &&
1566
+ normalizeText(getVisibleText(element)) === query,
1567
+ (element) => {
1568
+ const text = normalizeText(getVisibleText(element));
1569
+ return isVisible(element) && text && text.includes(query);
1570
+ },
1571
+ ),
1373
1572
  };
1374
1573
  }
1375
1574
 
1376
- if (locator.startsWith("role=")) {
1377
- const { role, name } = parseRoleLocator(locator.slice(5).trim());
1378
- const candidates = collectCandidates();
1379
- const match = candidates.find((element) => {
1380
- const elementRole = normalizeText(inferRole(element) ?? "");
1381
- const accessibleName = normalizeText(getAccessibleName(element));
1382
- if (!elementRole || elementRole !== role) {
1383
- return false;
1384
- }
1385
-
1386
- if (!name) {
1387
- return true;
1388
- }
1389
-
1390
- return accessibleName === name || accessibleName.includes(name);
1391
- });
1392
-
1575
+ if (part.startsWith("role=")) {
1576
+ const { role, name } = parseRoleLocator(part.slice(5).trim());
1393
1577
  return {
1394
- locator,
1395
1578
  strategy: "role",
1396
1579
  role,
1397
1580
  name,
1398
- element: match ?? null,
1581
+ elements: pick(candidates(), (element) => {
1582
+ const elementRole = normalizeText(inferRole(element) ?? "");
1583
+ if (!elementRole || elementRole !== role) {
1584
+ return false;
1585
+ }
1586
+ if (!name) {
1587
+ return true;
1588
+ }
1589
+ const accessibleName = normalizeText(getAccessibleName(element));
1590
+ return accessibleName === name || accessibleName.includes(name);
1591
+ }),
1399
1592
  };
1400
1593
  }
1401
1594
 
1402
- if (locator.startsWith("name=")) {
1403
- const query = normalizeText(locator.slice(5));
1404
- const candidates = collectCandidates();
1405
- const found =
1406
- candidates.find((element) => {
1407
- const accessibleName = normalizeText(getAccessibleName(element));
1408
- return isVisible(element) && accessibleName === query;
1409
- }) ??
1410
- candidates.find((element) => {
1595
+ if (part.startsWith("name=")) {
1596
+ const query = normalizeText(part.slice(5));
1597
+ const found = pickEither(
1598
+ candidates(),
1599
+ (element) =>
1600
+ isVisible(element) &&
1601
+ normalizeText(getAccessibleName(element)) === query,
1602
+ (element) => {
1411
1603
  const accessibleName = normalizeText(getAccessibleName(element));
1412
1604
  return (
1413
1605
  isVisible(element) &&
1414
1606
  accessibleName &&
1415
1607
  accessibleName.includes(query)
1416
1608
  );
1417
- });
1418
-
1609
+ },
1610
+ );
1419
1611
  // A label's text names its control, so act on the control when it is
1420
1612
  // visible; a styled checkbox hides its input and leaves the label.
1421
- const match =
1422
- found?.tagName === "LABEL" && found.control && isVisible(found.control)
1423
- ? found.control
1424
- : found;
1425
-
1613
+ // Inside a scope, only a control that is inside it too.
1426
1614
  return {
1427
- locator,
1428
1615
  strategy: "name",
1429
1616
  query,
1430
- element: match ?? null,
1617
+ elements: Array.from(
1618
+ new Set(
1619
+ found.map((element) =>
1620
+ element.tagName === "LABEL" &&
1621
+ element.control &&
1622
+ isVisible(element.control) &&
1623
+ (!scopes ||
1624
+ scopes.some((scope) => scope.contains(element.control)))
1625
+ ? element.control
1626
+ : element,
1627
+ ),
1628
+ ),
1629
+ ),
1431
1630
  };
1432
1631
  }
1433
1632
 
1434
- const cssSelector = locator.startsWith("css=") ? locator.slice(4) : locator;
1633
+ const cssSelector = part.startsWith("css=") ? part.slice(4) : part;
1435
1634
  try {
1436
- return {
1437
- locator,
1438
- strategy: "css",
1439
- query: cssSelector,
1440
- element: document.querySelector(cssSelector),
1441
- };
1635
+ const roots = scopes ?? [document];
1636
+ const elements =
1637
+ all || scopes
1638
+ ? Array.from(
1639
+ new Set(
1640
+ roots.flatMap((root) =>
1641
+ Array.from(root.querySelectorAll(cssSelector)),
1642
+ ),
1643
+ ),
1644
+ )
1645
+ : [document.querySelector(cssSelector)].filter(Boolean);
1646
+ return { strategy: "css", query: cssSelector, elements };
1442
1647
  } catch (error) {
1443
1648
  return {
1444
- locator,
1445
1649
  strategy: "css",
1446
1650
  query: cssSelector,
1447
- element: null,
1651
+ elements: [],
1448
1652
  error: error instanceof Error ? error.message : String(error),
1449
1653
  };
1450
1654
  }
1451
1655
  }
1452
1656
 
1657
+ // Splits a locator at each >> that has whitespace on both sides. One
1658
+ // inside square brackets belongs to a quoted value, as in
1659
+ // [title="a >> b"] or role=button[name="a >> b"], and is left alone;
1660
+ // quotes only count there, so an apostrophe in text=Don't is just text.
1661
+ function splitLocatorParts(locator) {
1662
+ const parts = [];
1663
+ let start = 0;
1664
+ let depth = 0;
1665
+ let quote = null;
1666
+ for (let index = 0; index < locator.length; index += 1) {
1667
+ const char = locator[index];
1668
+ if (quote) {
1669
+ if (char === "\\") {
1670
+ index += 1;
1671
+ } else if (char === quote) {
1672
+ quote = null;
1673
+ }
1674
+ } else if (char === "[") {
1675
+ depth += 1;
1676
+ } else if (char === "]") {
1677
+ depth = Math.max(0, depth - 1);
1678
+ } else if (depth > 0 && (char === '"' || char === "'")) {
1679
+ quote = char;
1680
+ } else if (depth === 0 && char === ">" && locator[index + 1] === ">") {
1681
+ const before = /\s$/.test(locator.slice(start, index));
1682
+ const after = /^\s/.test(locator.slice(index + 2));
1683
+ if (before && after && locator.slice(start, index).trim()) {
1684
+ parts.push(locator.slice(start, index).trim());
1685
+ start = index + 2;
1686
+ index += 1;
1687
+ }
1688
+ }
1689
+ }
1690
+ parts.push(locator.slice(start).trim());
1691
+ return parts;
1692
+ }
1693
+
1694
+ // Resolves a locator to its elements. a >> b looks for b inside the
1695
+ // elements a matches, and has-text= keeps the ones containing a text, so
1696
+ // tr >> has-text=Ada >> text=Delete is the Delete button of Ada's row.
1697
+ // Without all, only the first element is looked for.
1698
+ function resolveLocatorAll(rawLocator, all = true) {
1699
+ const locator = typeof rawLocator === "string" ? rawLocator.trim() : "";
1700
+ if (!locator) {
1701
+ throw new Error("selector must be a non-empty string");
1702
+ }
1703
+
1704
+ const parts = splitLocatorParts(locator);
1705
+ if (parts.length === 1) {
1706
+ return { locator, ...matchLocatorPart(locator, null, all) };
1707
+ }
1708
+
1709
+ let scopes = null;
1710
+ for (const [index, part] of parts.entries()) {
1711
+ const last = index === parts.length - 1;
1712
+ const matched = part
1713
+ ? matchLocatorPart(part, scopes, all || !last)
1714
+ : { elements: [], error: "empty part" };
1715
+ if (matched.error) {
1716
+ return {
1717
+ locator,
1718
+ strategy: "chain",
1719
+ query: locator,
1720
+ elements: [],
1721
+ error: 'Part "' + part + '" of the locator: ' + matched.error,
1722
+ };
1723
+ }
1724
+ scopes = matched.elements;
1725
+ if (scopes.length === 0) {
1726
+ break;
1727
+ }
1728
+ }
1729
+ return { locator, strategy: "chain", query: locator, elements: scopes };
1730
+ }
1731
+
1732
+ function resolveLocator(rawLocator) {
1733
+ const { elements, ...resolved } = resolveLocatorAll(rawLocator, false);
1734
+ return { ...resolved, element: elements[0] ?? null };
1735
+ }
1736
+
1453
1737
  function ensureResolved(rawLocator) {
1454
1738
  const resolved = resolveLocator(rawLocator);
1455
1739
  if (resolved.error) {
@@ -2167,6 +2451,8 @@ export function pageScript(payload) {
2167
2451
  return readText();
2168
2452
  case "snapshot":
2169
2453
  return snapshotPage();
2454
+ case "query":
2455
+ return queryElements();
2170
2456
  case "change_baseline":
2171
2457
  return changeBaseline();
2172
2458
  case "change_status":