cdp-toolkit 3.1.0 → 3.2.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.
package/dist/mcp.js CHANGED
@@ -803,6 +803,204 @@ var init_frames = __esm(() => {
803
803
  FRAME_SELECTOR_PAGE_ONLY_MESSAGE = "target 'frame:<substring>' selects an out-of-process iframe, and this tool is page-only " + "(closing, selecting, releasing or claiming an iframe is meaningless; these act on the embedder tab). " + `The page-only tools are ${FRAME_PAGE_ONLY_TOOLS.join(", ")}; every other tool that takes a 'target' ` + "accepts a frame: selector.";
804
804
  });
805
805
 
806
+ // src/cdp/endpoint.ts
807
+ import { readFile as readFile3 } from "node:fs/promises";
808
+ import { join as join3 } from "node:path";
809
+ async function browserWsFromPortFile(dir, base) {
810
+ const raw = await readFile3(join3(dir, "DevToolsActivePort"), "utf8").catch(() => {
811
+ return;
812
+ });
813
+ if (!raw)
814
+ return;
815
+ const [port, path] = raw.split(`
816
+ `);
817
+ if (!port?.trim() || !path?.trim())
818
+ return;
819
+ const host = new URL(base).hostname;
820
+ return `ws://${host}:${port.trim()}${path.trim()}`;
821
+ }
822
+ async function discoverBrowserWs(base) {
823
+ const dir = process.env.CDP_USER_DATA_DIR;
824
+ return dir ? browserWsFromPortFile(dir, base) : undefined;
825
+ }
826
+ async function handshake(url, timeoutMs) {
827
+ const conn = new CdpConnection(url, { timeoutMs });
828
+ try {
829
+ await conn.connect();
830
+ return true;
831
+ } catch {
832
+ return false;
833
+ } finally {
834
+ conn.close();
835
+ }
836
+ }
837
+ function detectEndpoint() {
838
+ const endpoint = currentEndpoint();
839
+ const base = endpoint.base;
840
+ const isDefault = isDefaultEndpoint(endpoint);
841
+ const hit = cached.get(base);
842
+ if (hit)
843
+ return hit;
844
+ const detection = (async () => {
845
+ const forced = isDefault ? process.env.CDP_BROWSER_WS : undefined;
846
+ if (forced)
847
+ return { transport: "browser-ws", browserWsUrl: forced };
848
+ const discovered = isDefault ? await discoverBrowserWs(base) : undefined;
849
+ if (discovered && await handshake(discovered, 5000)) {
850
+ return { transport: "browser-ws", browserWsUrl: discovered };
851
+ }
852
+ const version = await fetch(`${base}/json/version`, { signal: AbortSignal.timeout(5000) }).then((r) => r.ok ? r.json() : undefined).catch(() => {
853
+ return;
854
+ });
855
+ if (version?.webSocketDebuggerUrl) {
856
+ return { transport: "http", browserWsUrl: version.webSocketDebuggerUrl };
857
+ }
858
+ const dir = isDefault ? process.env.CDP_USER_DATA_DIR : undefined;
859
+ throw new Error(`no DevTools endpoint at ${base}: GET /json/version did not answer and ` + (dir ? `no live browser socket was named by ${dir}/DevToolsActivePort. ` : `no profile was searched — CDP_USER_DATA_DIR is unset, and no profile is ever scanned unless you name one. `) + `Set CDP_BROWSER_WS to the ws://.../devtools/browser/<uuid> URL, or CDP_USER_DATA_DIR to the profile in use.`);
860
+ })().then((info) => {
861
+ if (info.transport === "http")
862
+ cached.delete(base);
863
+ return info;
864
+ }, (error) => {
865
+ cached.delete(base);
866
+ throw error;
867
+ });
868
+ cached.set(base, detection);
869
+ return detection;
870
+ }
871
+ function forgetEndpoint() {
872
+ cached.delete(currentEndpoint().base);
873
+ }
874
+ var cached;
875
+ var init_endpoint = __esm(() => {
876
+ init_endpoints();
877
+ init_client();
878
+ cached = new Map;
879
+ });
880
+
881
+ // src/cdp/session.ts
882
+ async function acquireBrowserConn() {
883
+ if (shared) {
884
+ shared.refs++;
885
+ return shared.conn;
886
+ }
887
+ if (!opening) {
888
+ opening = (async () => {
889
+ let { browserWsUrl } = await detectEndpoint();
890
+ let conn;
891
+ try {
892
+ conn = await new CdpConnection(browserWsUrl).connect();
893
+ } catch (error) {
894
+ forgetEndpoint();
895
+ const fresh = (await detectEndpoint().catch(() => {
896
+ return;
897
+ }))?.browserWsUrl;
898
+ if (!fresh || fresh === browserWsUrl)
899
+ throw error;
900
+ browserWsUrl = fresh;
901
+ conn = await new CdpConnection(browserWsUrl).connect();
902
+ }
903
+ shared = { conn, refs: 0, url: browserWsUrl };
904
+ return conn;
905
+ })().finally(() => {
906
+ opening = undefined;
907
+ });
908
+ }
909
+ const conn = await opening;
910
+ shared.refs++;
911
+ return conn;
912
+ }
913
+ function releaseBrowserConn() {
914
+ if (!shared)
915
+ return;
916
+ shared.refs--;
917
+ if (shared.refs <= 0) {
918
+ const { conn } = shared;
919
+ shared = undefined;
920
+ conn.close();
921
+ }
922
+ }
923
+ async function withBrowserSocket(fn) {
924
+ const conn = await acquireBrowserConn();
925
+ try {
926
+ return await fn(conn);
927
+ } finally {
928
+ releaseBrowserConn();
929
+ }
930
+ }
931
+
932
+ class SessionConnection {
933
+ browser;
934
+ sessionId;
935
+ opts;
936
+ detached = false;
937
+ offs = [];
938
+ constructor(browser, sessionId, opts = {}) {
939
+ this.browser = browser;
940
+ this.sessionId = sessionId;
941
+ this.opts = opts;
942
+ }
943
+ send(method, params = {}, opts = {}) {
944
+ if (this.detached)
945
+ return Promise.reject(new CdpError("connection not open"));
946
+ return this.browser.send(method, params, {
947
+ timeoutMs: opts.timeoutMs ?? this.opts.timeoutMs,
948
+ sessionId: opts.sessionId ?? this.sessionId
949
+ });
950
+ }
951
+ on(method, handler) {
952
+ const off = this.browser.on(method, (params, sessionId) => {
953
+ if (sessionId && sessionId !== this.sessionId)
954
+ return;
955
+ handler(params, sessionId);
956
+ });
957
+ this.offs.push(off);
958
+ return off;
959
+ }
960
+ waitFor(method, predicate, timeoutMs = this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS) {
961
+ return new Promise((resolve, reject) => {
962
+ const timer = setTimeout(() => {
963
+ off();
964
+ reject(new CdpError(`waitFor('${method}') timed out after ${timeoutMs}ms`));
965
+ }, timeoutMs);
966
+ const off = this.on(method, (params) => {
967
+ if (!predicate || predicate(params)) {
968
+ clearTimeout(timer);
969
+ off();
970
+ resolve(params);
971
+ }
972
+ });
973
+ });
974
+ }
975
+ close() {
976
+ if (this.detached)
977
+ return;
978
+ this.detached = true;
979
+ for (const off of this.offs)
980
+ off();
981
+ this.offs.length = 0;
982
+ this.browser.send("Target.detachFromTarget", { sessionId: this.sessionId }).catch(() => {});
983
+ releaseBrowserConn();
984
+ }
985
+ }
986
+ async function openSession(targetId, opts = {}) {
987
+ const browser = await acquireBrowserConn();
988
+ try {
989
+ const { sessionId } = await browser.send("Target.attachToTarget", { targetId, flatten: true }, { timeoutMs: opts.timeoutMs });
990
+ if (!sessionId)
991
+ throw new CdpError(`Target.attachToTarget returned no sessionId for ${targetId}`);
992
+ return new SessionConnection(browser, sessionId, opts);
993
+ } catch (e) {
994
+ releaseBrowserConn();
995
+ throw e;
996
+ }
997
+ }
998
+ var shared, opening;
999
+ var init_session = __esm(() => {
1000
+ init_client();
1001
+ init_endpoint();
1002
+ });
1003
+
806
1004
  // src/client.ts
807
1005
  class CdpConnection {
808
1006
  wsUrl;
@@ -935,12 +1133,47 @@ async function httpJson(path) {
935
1133
  throw new CdpError(`${path} -> HTTP ${res.status}`);
936
1134
  return await res.json();
937
1135
  }
938
- function listTargets() {
939
- return httpJson("/json/list");
1136
+ async function getTargetsOverBrowserWs() {
1137
+ const { targetInfos } = await withBrowserSocket((conn) => conn.send("Target.getTargets", { filter: [{}] }));
1138
+ return targetInfos.map((t) => ({
1139
+ id: t.targetId,
1140
+ type: t.type,
1141
+ title: t.title,
1142
+ url: t.url,
1143
+ webSocketDebuggerUrl: "",
1144
+ ...t.openerId ? { parentId: t.openerId } : {}
1145
+ }));
1146
+ }
1147
+ async function listTargets() {
1148
+ const base = currentEndpoint().base;
1149
+ if (knownTransports.get(base) === "browser-ws")
1150
+ return getTargetsOverBrowserWs();
1151
+ try {
1152
+ const listing = await httpJson("/json/list");
1153
+ knownTransports.set(base, "http");
1154
+ return listing;
1155
+ } catch (httpError) {
1156
+ const detected = await detectEndpoint().catch(() => {
1157
+ return;
1158
+ });
1159
+ if (detected?.transport !== "browser-ws")
1160
+ throw httpError;
1161
+ const targets = await getTargetsOverBrowserWs().catch(() => {
1162
+ throw httpError;
1163
+ });
1164
+ knownTransports.set(base, "browser-ws");
1165
+ return targets;
1166
+ }
940
1167
  }
941
1168
  async function browserWsUrl() {
942
- const v = await httpJson("/json/version");
943
- return v.webSocketDebuggerUrl;
1169
+ if (knownTransports.get(currentEndpoint().base) !== "browser-ws") {
1170
+ const version = await httpJson("/json/version").catch(() => {
1171
+ return;
1172
+ });
1173
+ if (version?.webSocketDebuggerUrl)
1174
+ return version.webSocketDebuggerUrl;
1175
+ }
1176
+ return (await detectEndpoint()).browserWsUrl;
944
1177
  }
945
1178
  async function resolveTarget(selector, opts = {}) {
946
1179
  const targets = await listTargets();
@@ -1022,7 +1255,7 @@ async function openBrowser(opts = {}) {
1022
1255
  }
1023
1256
  async function openPage(selector, opts = {}) {
1024
1257
  const target = await resolveTarget(selector, { lease: opts.lease });
1025
- const conn = await new CdpConnection(target.webSocketDebuggerUrl, opts).connect();
1258
+ const conn = target.webSocketDebuggerUrl ? await new CdpConnection(target.webSocketDebuggerUrl, opts).connect() : await openSession(target.id, opts);
1026
1259
  return { conn, target };
1027
1260
  }
1028
1261
  async function withPage(selector, fn, opts = {}) {
@@ -1033,13 +1266,16 @@ async function withPage(selector, fn, opts = {}) {
1033
1266
  conn.close();
1034
1267
  }
1035
1268
  }
1036
- var BASE, DEFAULT_TIMEOUT_MS, CdpError;
1269
+ var BASE, DEFAULT_TIMEOUT_MS, CdpError, knownTransports;
1037
1270
  var init_client = __esm(() => {
1038
1271
  init_leases();
1039
1272
  init_origins();
1040
1273
  init_endpoints();
1041
1274
  init_workers();
1042
1275
  init_frames();
1276
+ init_endpoint();
1277
+ init_session();
1278
+ init_session();
1043
1279
  BASE = (() => {
1044
1280
  try {
1045
1281
  return defaultEndpoint().base;
@@ -1058,6 +1294,7 @@ var init_client = __esm(() => {
1058
1294
  this.name = "CdpError";
1059
1295
  }
1060
1296
  };
1297
+ knownTransports = new Map;
1061
1298
  });
1062
1299
 
1063
1300
  // src/activity.ts
@@ -1374,8 +1611,8 @@ var init_network_mock = __esm(() => {
1374
1611
  });
1375
1612
 
1376
1613
  // src/driver.ts
1377
- import { mkdir as mkdir3, readFile as readFile3, unlink as unlink3, writeFile as writeFile3 } from "node:fs/promises";
1378
- import { join as join3 } from "node:path";
1614
+ import { mkdir as mkdir3, readFile as readFile4, unlink as unlink3, writeFile as writeFile3 } from "node:fs/promises";
1615
+ import { join as join4 } from "node:path";
1379
1616
  function isDriverError(e) {
1380
1617
  return e instanceof Error && typeof e.code === "string";
1381
1618
  }
@@ -1391,11 +1628,11 @@ function isTiledCapture(delivery) {
1391
1628
  return delivery.tiled === true;
1392
1629
  }
1393
1630
  function viewportRecordFile(scheme, targetId) {
1394
- return join3(leaseDir(), `viewport-${scheme}-${targetId.replace(/[^A-Za-z0-9._-]/g, "_")}.json`);
1631
+ return join4(leaseDir(), `viewport-${scheme}-${targetId.replace(/[^A-Za-z0-9._-]/g, "_")}.json`);
1395
1632
  }
1396
1633
  async function readViewportRecord(scheme, targetId) {
1397
1634
  try {
1398
- const raw = JSON.parse(await readFile3(viewportRecordFile(scheme, targetId), "utf8"));
1635
+ const raw = JSON.parse(await readFile4(viewportRecordFile(scheme, targetId), "utf8"));
1399
1636
  if (typeof raw?.width !== "number" || typeof raw?.height !== "number")
1400
1637
  return;
1401
1638
  return {
@@ -1408,43 +1645,358 @@ async function readViewportRecord(scheme, targetId) {
1408
1645
  return;
1409
1646
  }
1410
1647
  }
1411
- async function writeViewportRecord(scheme, targetId, rec) {
1412
- try {
1413
- await mkdir3(leaseDir(), { recursive: true });
1414
- await writeFile3(viewportRecordFile(scheme, targetId), JSON.stringify({ scheme, targetId, ...rec }), "utf8");
1415
- } catch {}
1648
+ async function writeViewportRecord(scheme, targetId, rec) {
1649
+ try {
1650
+ await mkdir3(leaseDir(), { recursive: true });
1651
+ await writeFile3(viewportRecordFile(scheme, targetId), JSON.stringify({ scheme, targetId, ...rec }), "utf8");
1652
+ } catch {}
1653
+ }
1654
+ function renderRestoreFailureNote(size, why) {
1655
+ return `— AND the ${size.width}x${size.height} render-size override could NOT be restored (${why}), so this page is STILL ` + `emulated at ${size.width}x${size.height}: put it back with emulate{width,height} or emulate{clearOverrides:true}.`;
1656
+ }
1657
+ async function clearViewportRecord(scheme, targetId) {
1658
+ try {
1659
+ await unlink3(viewportRecordFile(scheme, targetId));
1660
+ } catch {}
1661
+ }
1662
+ var UID_STAMP_ATTR = "data-cdp-uid", LEGACY_NUMERIC_UID, REQUIRED_CAPABILITIES;
1663
+ var init_driver = __esm(() => {
1664
+ init_leases();
1665
+ LEGACY_NUMERIC_UID = /^[0-9]+$/;
1666
+ REQUIRED_CAPABILITIES = {
1667
+ performance_start_trace: ["trace.performance"],
1668
+ performance_stop_trace: ["trace.performance"],
1669
+ performance_analyze_insight: ["trace.performance"],
1670
+ performance_trace: ["trace.performance"],
1671
+ take_heapsnapshot: ["heap.snapshot"],
1672
+ lighthouse_audit: ["audit.lighthouse"],
1673
+ start_screen_recording: ["capture.screencast"],
1674
+ stop_screen_recording: ["capture.screencast"],
1675
+ mock_request: ["network.intercept"],
1676
+ list_mocks: ["network.intercept"],
1677
+ clear_mocks: ["network.intercept"],
1678
+ dispatch_mouse: ["input.raw"],
1679
+ focus_emulation: ["emulate.focus"],
1680
+ click_focus_gated: ["emulate.focus"],
1681
+ wait_for_download: ["browser.downloads"],
1682
+ grant_permissions: ["browser.permissions"]
1683
+ };
1684
+ });
1685
+
1686
+ // src/bidi/snapshot.ts
1687
+ async function takeStampedSnapshot(evaluate) {
1688
+ const raw = await evaluate(buildSnapshotFunctionSource());
1689
+ return coerceSnapshotResult(raw);
1690
+ }
1691
+ function coerceSnapshotResult(raw) {
1692
+ if (typeof raw !== "object" || raw === null || typeof raw.snapshot !== "string" || typeof raw.nodeCount !== "number") {
1693
+ throw new Error("takeStampedSnapshot: evaluate() returned an unexpected shape");
1694
+ }
1695
+ return { snapshot: raw.snapshot, nodeCount: raw.nodeCount };
1696
+ }
1697
+ function buildSnapshotFunctionSource() {
1698
+ return `function() {
1699
+ var STAMP_ATTR = ${JSON.stringify(STAMP_ATTR)};
1700
+ var MAX_NAME_LENGTH = ${MAX_NAME_LENGTH};
1701
+ var lines = [];
1702
+ var nodeCount = 0;
1703
+
1704
+ // THE UID CODEC (driver.ts) documents a bidi payload as exactly 12 lowercase hex chars,
1705
+ // /^[0-9a-f]{12}$/. Build it from two padded random blocks so the length is exact regardless
1706
+ // of the random value drawn, never from string concatenation that could come up short.
1707
+ function nextStamp() {
1708
+ var hi = Math.floor(Math.random() * 0x100000000).toString(16).padStart(8, "0");
1709
+ var lo = Math.floor(Math.random() * 0x10000).toString(16).padStart(4, "0");
1710
+ return hi + lo;
1711
+ }
1712
+
1713
+ function stampOf(el) {
1714
+ var existing = el.getAttribute(STAMP_ATTR);
1715
+ if (existing) return existing;
1716
+ var stamp = nextStamp();
1717
+ el.setAttribute(STAMP_ATTR, stamp);
1718
+ return stamp;
1719
+ }
1720
+
1721
+ // skipSizeCheck exempts <option>/<optgroup> from the zero-size prune: a
1722
+ // closed select's popup is unpainted (0x0) though its options are still
1723
+ // present and pickable. Other visibility rules still apply to them.
1724
+ function isVisible(el, skipSizeCheck) {
1725
+ if (el.hidden) return false;
1726
+ if (el.getAttribute("aria-hidden") === "true") return false;
1727
+ var style;
1728
+ try {
1729
+ style = el.ownerDocument.defaultView.getComputedStyle(el);
1730
+ } catch (e) {
1731
+ style = null;
1732
+ }
1733
+ if (style) {
1734
+ if (style.display === "none" || style.visibility === "hidden") return false;
1735
+ }
1736
+ if (!skipSizeCheck) {
1737
+ var rect = el.getBoundingClientRect();
1738
+ if (rect.width === 0 && rect.height === 0) return false;
1739
+ }
1740
+ return true;
1741
+ }
1742
+
1743
+ ${ACCNAME_HELPERS_SOURCE}
1744
+
1745
+ function headingLevel(el) {
1746
+ var m = /^H([1-6])$/.exec(el.tagName);
1747
+ return m ? m[1] : null;
1748
+ }
1749
+
1750
+ function currentValue(el) {
1751
+ var tag = el.tagName;
1752
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") {
1753
+ return el.value;
1754
+ }
1755
+ if (el.isContentEditable) return textOf(el);
1756
+ return undefined;
1757
+ }
1758
+
1759
+ function isChecked(el) {
1760
+ var tag = el.tagName;
1761
+ if (tag === "INPUT") {
1762
+ var type = (el.getAttribute("type") || "").toLowerCase();
1763
+ if (type === "checkbox" || type === "radio") return !!el.checked;
1764
+ }
1765
+ var aria = el.getAttribute("aria-checked");
1766
+ if (aria === "true") return true;
1767
+ return false;
1768
+ }
1769
+
1770
+ function describeNode(el, role) {
1771
+ var contentNamed = !!CONTENT_NAMED_ROLES[role];
1772
+ var name = accessibleName(el, contentNamed);
1773
+ var extras = [];
1774
+ var value = currentValue(el);
1775
+ if (value !== undefined && value !== "") extras.push("value=" + JSON.stringify(String(value)));
1776
+ if (isChecked(el)) extras.push("checked=true");
1777
+ if (el.tagName === "OPTION" && el.selected) extras.push("selected");
1778
+ var href = el.getAttribute("href");
1779
+ if (href) extras.push("url=" + href);
1780
+ if (el.disabled || el.getAttribute("aria-disabled") === "true") extras.push("disabled");
1781
+ var level = headingLevel(el);
1782
+ if (level) extras.push("level=" + level);
1783
+ var label = name ? " " + JSON.stringify(name) : "";
1784
+ var extra = extras.length ? " [" + extras.join(" ") + "]" : "";
1785
+ return { role: role, label: label, extra: extra, name: name };
1786
+ }
1787
+
1788
+ // Traverses light DOM, open shadow roots, and same-origin iframe documents.
1789
+ // A cross-origin iframe throws on contentDocument access; caught and
1790
+ // skipped rather than aborting the whole walk, and noted in a comment
1791
+ // here rather than silently vanishing from the tree without a trace.
1792
+ function walk(root, depth) {
1793
+ var children = root.children ? Array.prototype.slice.call(root.children) : [];
1794
+ for (var i = 0; i < children.length; i++) {
1795
+ var el = children[i];
1796
+ var isSelectChild = el.tagName === "OPTION" || el.tagName === "OPTGROUP";
1797
+ if (!isVisible(el, isSelectChild)) continue;
1798
+
1799
+ var role = implicitRole(el);
1800
+ var isLandmarkOrControl = !!role;
1801
+ var described = null;
1802
+ if (isLandmarkOrControl) {
1803
+ described = describeNode(el, role);
1804
+ }
1805
+
1806
+ var hasContent = described && (described.name || described.extra);
1807
+ var isStructural = isLandmarkOrControl && (hasContent || isInteractiveRole(role) || isLandmarkRole(role));
1808
+
1809
+ // Role-less visible leaf text (measured vs Chrome's take_snapshot,
1810
+ // which keeps a StaticText under a generic wrapper for this case,
1811
+ // e.g. a plain status <div>). Only a leaf (no element children, so
1812
+ // its text is not already captured by a nested control/label).
1813
+ var hasElementChildren = !!(el.children && el.children.length > 0);
1814
+ var leafName = !isStructural && !hasElementChildren ? truncate(textOf(el)) : "";
1815
+ var isLeafText = !!leafName;
1816
+
1817
+ var nextDepth = depth;
1818
+ if (isStructural || isLeafText) {
1819
+ var stamp = stampOf(el);
1820
+ var indent = new Array(depth + 1).join(" ");
1821
+ var lineTail = isStructural
1822
+ ? described.role + described.label + described.extra
1823
+ : "text " + JSON.stringify(leafName);
1824
+ lines.push(indent + "[" + stamp + "] " + lineTail);
1825
+ nodeCount += 1;
1826
+ nextDepth = depth + 1;
1827
+ }
1828
+
1829
+ if (el.shadowRoot) {
1830
+ walk(el.shadowRoot, nextDepth);
1831
+ } else if (el.tagName === "IFRAME") {
1832
+ try {
1833
+ var doc = el.contentDocument;
1834
+ if (doc && doc.body) walk(doc.body, nextDepth);
1835
+ } catch (e) {
1836
+ // cross-origin iframe: intentionally skipped, not silently merged
1837
+ // into the parent tree as though it were empty.
1838
+ }
1839
+ } else {
1840
+ walk(el, nextDepth);
1841
+ }
1842
+ }
1843
+ }
1844
+
1845
+ function isInteractiveRole(role) {
1846
+ return (
1847
+ role === "button" ||
1848
+ role === "link" ||
1849
+ role === "textbox" ||
1850
+ role === "searchbox" ||
1851
+ role === "checkbox" ||
1852
+ role === "radio" ||
1853
+ role === "combobox" ||
1854
+ role === "listbox" ||
1855
+ role === "option" ||
1856
+ role === "slider" ||
1857
+ role === "spinbutton" ||
1858
+ role === "progressbar" ||
1859
+ role === "meter"
1860
+ );
1861
+ }
1862
+
1863
+ function isLandmarkRole(role) {
1864
+ return (
1865
+ role === "navigation" ||
1866
+ role === "main" ||
1867
+ role === "form" ||
1868
+ role === "dialog" ||
1869
+ role === "region" ||
1870
+ role === "heading" ||
1871
+ role === "list" ||
1872
+ role === "listitem" ||
1873
+ role === "table" ||
1874
+ role === "row" ||
1875
+ role === "cell" ||
1876
+ role === "columnheader" ||
1877
+ role === "img"
1878
+ );
1879
+ }
1880
+
1881
+ walk(document.body, 0);
1882
+ return { snapshot: lines.join("\\n"), nodeCount: nodeCount };
1883
+ }`;
1884
+ }
1885
+ var STAMP_ATTR = "data-cdp-uid", ACCNAME_HELPERS_SOURCE = `
1886
+ function truncate(s) {
1887
+ s = s.trim().replace(/\\s+/g, " ");
1888
+ if (s.length > MAX_NAME_LENGTH) return s.slice(0, MAX_NAME_LENGTH - 1) + "\\u2026";
1889
+ return s;
1890
+ }
1891
+
1892
+ function textOf(el) {
1893
+ return el.textContent || "";
1894
+ }
1895
+
1896
+ function idRefsText(doc, ids) {
1897
+ var parts = [];
1898
+ var list = ids.trim().split(/\\s+/);
1899
+ for (var i = 0; i < list.length; i++) {
1900
+ var ref = doc.getElementById(list[i]);
1901
+ if (ref) parts.push(textOf(ref));
1902
+ }
1903
+ return parts.join(" ").trim();
1904
+ }
1905
+
1906
+ // Text of a <label>, minus any nested form control's own content: a
1907
+ // label that WRAPS its control ("<label>Color <select>...</select></label>")
1908
+ // would otherwise include every option's text in the control's own name.
1909
+ function labelOwnText(label) {
1910
+ var clone = label.cloneNode(true);
1911
+ var controls = clone.querySelectorAll("input, select, textarea, button");
1912
+ for (var i = 0; i < controls.length; i++) {
1913
+ controls[i].parentNode.removeChild(controls[i]);
1914
+ }
1915
+ return textOf(clone);
1416
1916
  }
1417
- function renderRestoreFailureNote(size, why) {
1418
- return `— AND the ${size.width}x${size.height} render-size override could NOT be restored (${why}), so this page is STILL ` + `emulated at ${size.width}x${size.height}: put it back with emulate{width,height} or emulate{clearOverrides:true}.`;
1917
+
1918
+ // Guard: without this, an <option> inside a labelled <select> would
1919
+ // inherit the select's own label via closest("label"), not its text.
1920
+ var LABELABLE_TAGS = { INPUT: 1, TEXTAREA: 1, SELECT: 1, BUTTON: 1, METER: 1, OUTPUT: 1, PROGRESS: 1 };
1921
+
1922
+ function nativeLabelText(el) {
1923
+ if (!LABELABLE_TAGS[el.tagName]) return "";
1924
+ var doc = el.ownerDocument;
1925
+ if (el.id) {
1926
+ var forLabel = doc.querySelector('label[for="' + el.id + '"]');
1927
+ if (forLabel) return labelOwnText(forLabel);
1928
+ }
1929
+ var ancestor = el.closest ? el.closest("label") : null;
1930
+ if (ancestor) return labelOwnText(ancestor);
1931
+ return "";
1419
1932
  }
1420
- async function clearViewportRecord(scheme, targetId) {
1421
- try {
1422
- await unlink3(viewportRecordFile(scheme, targetId));
1423
- } catch {}
1933
+
1934
+ // Reduced accname: aria-labelledby, then aria-label, then native label,
1935
+ // then alt/title/placeholder, then trimmed own text for content-named
1936
+ // elements. Not the full W3C accname algorithm (no recursive traversal
1937
+ // rules for nested presentational content) but covers the common cases.
1938
+ function accessibleName(el, contentNamed) {
1939
+ var doc = el.ownerDocument;
1940
+ var labelledby = el.getAttribute("aria-labelledby");
1941
+ if (labelledby) {
1942
+ var viaIds = idRefsText(doc, labelledby);
1943
+ if (viaIds) return truncate(viaIds);
1944
+ }
1945
+ var ariaLabel = el.getAttribute("aria-label");
1946
+ if (ariaLabel && ariaLabel.trim()) return truncate(ariaLabel);
1947
+ var native = nativeLabelText(el);
1948
+ if (native && native.trim()) return truncate(native);
1949
+ var alt = el.getAttribute("alt");
1950
+ if (alt && alt.trim()) return truncate(alt);
1951
+ var title = el.getAttribute("title");
1952
+ if (title && title.trim()) return truncate(title);
1953
+ var placeholder = el.getAttribute("placeholder");
1954
+ if (placeholder && placeholder.trim()) return truncate(placeholder);
1955
+ if (contentNamed) {
1956
+ var text = textOf(el);
1957
+ if (text && text.trim()) return truncate(text);
1958
+ }
1959
+ return "";
1424
1960
  }
1425
- var UID_STAMP_ATTR = "data-cdp-uid", LEGACY_NUMERIC_UID, REQUIRED_CAPABILITIES;
1426
- var init_driver = __esm(() => {
1427
- init_leases();
1428
- LEGACY_NUMERIC_UID = /^[0-9]+$/;
1429
- REQUIRED_CAPABILITIES = {
1430
- performance_start_trace: ["trace.performance"],
1431
- performance_stop_trace: ["trace.performance"],
1432
- performance_analyze_insight: ["trace.performance"],
1433
- performance_trace: ["trace.performance"],
1434
- take_heapsnapshot: ["heap.snapshot"],
1435
- lighthouse_audit: ["audit.lighthouse"],
1436
- start_screen_recording: ["capture.screencast"],
1437
- stop_screen_recording: ["capture.screencast"],
1438
- mock_request: ["network.intercept"],
1439
- list_mocks: ["network.intercept"],
1440
- clear_mocks: ["network.intercept"],
1441
- dispatch_mouse: ["input.raw"],
1442
- focus_emulation: ["emulate.focus"],
1443
- click_focus_gated: ["emulate.focus"],
1444
- wait_for_download: ["browser.downloads"],
1445
- grant_permissions: ["browser.permissions"]
1446
- };
1447
- });
1961
+
1962
+ var IMPLICIT_ROLE_BY_TAG = {
1963
+ A: "link", BUTTON: "button", NAV: "navigation", MAIN: "main", FORM: "form", DIALOG: "dialog",
1964
+ UL: "list", OL: "list", LI: "listitem", TABLE: "table", TR: "row", TD: "cell", TH: "columnheader",
1965
+ SELECT: "combobox", OPTION: "option", TEXTAREA: "textbox", IMG: "img",
1966
+ H1: "heading", H2: "heading", H3: "heading", H4: "heading", H5: "heading", H6: "heading",
1967
+ PROGRESS: "progressbar", METER: "meter"
1968
+ };
1969
+
1970
+ var INPUT_TYPE_ROLE = {
1971
+ button: "button", submit: "button", reset: "button", checkbox: "checkbox", radio: "radio",
1972
+ range: "slider", number: "spinbutton", search: "searchbox", email: "textbox", tel: "textbox",
1973
+ url: "textbox", password: "textbox", text: "textbox", image: "button"
1974
+ };
1975
+
1976
+ var CONTENT_NAMED_ROLES = {
1977
+ button: true, link: true, heading: true, option: true, cell: true,
1978
+ columnheader: true, listitem: true, menuitem: true, tab: true
1979
+ };
1980
+
1981
+ function implicitRole(el) {
1982
+ var explicit = el.getAttribute("role");
1983
+ if (explicit) return explicit;
1984
+ var tag = el.tagName;
1985
+ if (tag === "INPUT") {
1986
+ var type = (el.getAttribute("type") || "text").toLowerCase();
1987
+ return INPUT_TYPE_ROLE[type] || "textbox";
1988
+ }
1989
+ if (tag === "A" && !el.getAttribute("href")) return "";
1990
+ if (Object.prototype.hasOwnProperty.call(IMPLICIT_ROLE_BY_TAG, tag)) {
1991
+ return IMPLICIT_ROLE_BY_TAG[tag];
1992
+ }
1993
+ // Deliberate divergence: Chrome's real AX tree says "generic" here,
1994
+ // but "textbox" is the useful signal an agent needs. Chrome is out of
1995
+ // step, do not "fix" this toward parity.
1996
+ if (el.isContentEditable) return "textbox";
1997
+ return "";
1998
+ }
1999
+ `, MAX_NAME_LENGTH = 120;
1448
2000
 
1449
2001
  // src/bidi/client.ts
1450
2002
  class BidiConnection {
@@ -1645,16 +2197,16 @@ var init_client2 = __esm(() => {
1645
2197
  });
1646
2198
 
1647
2199
  // src/bidi/session-lease.ts
1648
- import { mkdir as mkdir13, readFile as readFile8, rename as rename3, unlink as unlink5, writeFile as writeFile10 } from "node:fs/promises";
1649
- import { join as join11 } from "node:path";
2200
+ import { mkdir as mkdir13, readFile as readFile9, rename as rename3, unlink as unlink5, writeFile as writeFile10 } from "node:fs/promises";
2201
+ import { join as join12 } from "node:path";
1650
2202
  function safeEndpoint(endpoint) {
1651
2203
  return endpoint.replace(/[^A-Za-z0-9._-]/g, "_");
1652
2204
  }
1653
2205
  function sessionSlotFile(endpoint) {
1654
- return join11(leaseDir(), `ff-session-${safeEndpoint(endpoint)}.json`);
2206
+ return join12(leaseDir(), `ff-session-${safeEndpoint(endpoint)}.json`);
1655
2207
  }
1656
2208
  function muxDaemonLogFile(endpoint) {
1657
- return join11(leaseDir(), `ff-mux-${safeEndpoint(endpoint)}.log`);
2209
+ return join12(leaseDir(), `ff-mux-${safeEndpoint(endpoint)}.log`);
1658
2210
  }
1659
2211
  function sessionWaitMs() {
1660
2212
  const raw = Number(process.env.CDP_FIREFOX_SESSION_WAIT_MS);
@@ -1663,7 +2215,7 @@ function sessionWaitMs() {
1663
2215
  async function readSessionSlot(endpoint) {
1664
2216
  let raw;
1665
2217
  try {
1666
- raw = await readFile8(sessionSlotFile(endpoint), "utf8");
2218
+ raw = await readFile9(sessionSlotFile(endpoint), "utf8");
1667
2219
  } catch (err) {
1668
2220
  if (err.code === "ENOENT")
1669
2221
  return;
@@ -2286,417 +2838,104 @@ class FrameDecoder {
2286
2838
  this.assertDigitsPrefix(colon);
2287
2839
  const len = Number.parseInt(this.buf.toString("ascii", 0, colon), 10);
2288
2840
  const start = colon + 1;
2289
- const end = start + len;
2290
- if (this.buf.length < end)
2291
- return;
2292
- const payload = this.buf.toString("utf8", start, end);
2293
- this.buf = this.buf.subarray(end);
2294
- try {
2295
- return JSON.parse(payload);
2296
- } catch {
2297
- throw new MarionetteProtocolError(`frame body was not valid JSON (${len} bytes): ${payload.slice(0, 80)}`);
2298
- }
2299
- }
2300
- assertDigitsPrefix(upTo) {
2301
- for (let i = 0;i < upTo; i++) {
2302
- const b = this.buf[i];
2303
- if (b < 48 || b > 57) {
2304
- throw new MarionetteProtocolError(`non-digit byte 0x${b.toString(16)} in frame length prefix`);
2305
- }
2306
- }
2307
- }
2308
- }
2309
- function isSlotFreedReply(frame) {
2310
- if (!Array.isArray(frame))
2311
- return false;
2312
- const err = frame[2];
2313
- if (err === null)
2314
- return true;
2315
- if (typeof err === "object" && err !== null && err.error === "invalid session id") {
2316
- return true;
2317
- }
2318
- return false;
2319
- }
2320
- function forceClearOrphanSession(marionettePort, opts = {}) {
2321
- const timeoutMs = opts.timeoutMs !== undefined && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0 ? opts.timeoutMs : DEFAULT_TIMEOUT_MS4;
2322
- return new Promise((resolve) => {
2323
- if (!Number.isFinite(marionettePort) || marionettePort <= 0 || marionettePort > 65535) {
2324
- resolve(false);
2325
- return;
2326
- }
2327
- const sock = new Socket;
2328
- const decoder = new FrameDecoder;
2329
- let settled = false;
2330
- let handshakeSeen = false;
2331
- let commandSent = false;
2332
- const settle = (value) => {
2333
- if (settled)
2334
- return;
2335
- settled = true;
2336
- clearTimeout(timer);
2337
- sock.removeAllListeners();
2338
- sock.destroy();
2339
- resolve(value);
2340
- };
2341
- const timer = setTimeout(() => settle(false), timeoutMs);
2342
- if (typeof timer.unref === "function")
2343
- timer.unref();
2344
- sock.on("error", () => settle(false));
2345
- sock.on("close", () => settle(false));
2346
- sock.on("data", (chunk) => {
2347
- if (settled)
2348
- return;
2349
- try {
2350
- decoder.push(chunk);
2351
- for (;; ) {
2352
- const frame = decoder.next();
2353
- if (frame === undefined)
2354
- break;
2355
- if (!handshakeSeen) {
2356
- handshakeSeen = true;
2357
- continue;
2358
- }
2359
- settle(isSlotFreedReply(frame));
2360
- return;
2361
- }
2362
- if (handshakeSeen && !commandSent) {
2363
- commandSent = true;
2364
- sock.write(DELETE_SESSION_FRAME);
2365
- }
2366
- } catch {
2367
- settle(false);
2368
- }
2369
- });
2370
- try {
2371
- sock.connect(marionettePort, HOST);
2372
- } catch {
2373
- settle(false);
2374
- }
2375
- });
2376
- }
2377
- var DEFAULT_MARIONETTE_PORT = 2828, DEFAULT_TIMEOUT_MS4 = 4000, HOST = "127.0.0.1", COLON = 58, DELETE_SESSION_FRAME, MarionetteProtocolError;
2378
- var init_marionette = __esm(() => {
2379
- DELETE_SESSION_FRAME = encodeFrame2([0, 1, "WebDriver:DeleteSession", {}]);
2380
- MarionetteProtocolError = class MarionetteProtocolError extends Error {
2381
- constructor(message) {
2382
- super(message);
2383
- this.name = "MarionetteProtocolError";
2384
- }
2385
- };
2386
- });
2387
-
2388
- // src/bidi/snapshot.ts
2389
- async function takeStampedSnapshot(evaluate) {
2390
- const raw = await evaluate(buildSnapshotFunctionSource());
2391
- return coerceSnapshotResult(raw);
2392
- }
2393
- function coerceSnapshotResult(raw) {
2394
- if (typeof raw !== "object" || raw === null || typeof raw.snapshot !== "string" || typeof raw.nodeCount !== "number") {
2395
- throw new Error("takeStampedSnapshot: evaluate() returned an unexpected shape");
2396
- }
2397
- return { snapshot: raw.snapshot, nodeCount: raw.nodeCount };
2398
- }
2399
- function buildSnapshotFunctionSource() {
2400
- return `function() {
2401
- var STAMP_ATTR = ${JSON.stringify(STAMP_ATTR)};
2402
- var MAX_NAME_LENGTH = ${MAX_NAME_LENGTH};
2403
- var lines = [];
2404
- var nodeCount = 0;
2405
-
2406
- // THE UID CODEC (driver.ts) documents a bidi payload as exactly 12 lowercase hex chars,
2407
- // /^[0-9a-f]{12}$/. Build it from two padded random blocks so the length is exact regardless
2408
- // of the random value drawn, never from string concatenation that could come up short.
2409
- function nextStamp() {
2410
- var hi = Math.floor(Math.random() * 0x100000000).toString(16).padStart(8, "0");
2411
- var lo = Math.floor(Math.random() * 0x10000).toString(16).padStart(4, "0");
2412
- return hi + lo;
2413
- }
2414
-
2415
- function stampOf(el) {
2416
- var existing = el.getAttribute(STAMP_ATTR);
2417
- if (existing) return existing;
2418
- var stamp = nextStamp();
2419
- el.setAttribute(STAMP_ATTR, stamp);
2420
- return stamp;
2421
- }
2422
-
2423
- // skipSizeCheck exempts <option>/<optgroup> from the zero-size prune: a
2424
- // closed select's popup is unpainted (0x0) though its options are still
2425
- // present and pickable. Other visibility rules still apply to them.
2426
- function isVisible(el, skipSizeCheck) {
2427
- if (el.hidden) return false;
2428
- if (el.getAttribute("aria-hidden") === "true") return false;
2429
- var style;
2430
- try {
2431
- style = el.ownerDocument.defaultView.getComputedStyle(el);
2432
- } catch (e) {
2433
- style = null;
2434
- }
2435
- if (style) {
2436
- if (style.display === "none" || style.visibility === "hidden") return false;
2437
- }
2438
- if (!skipSizeCheck) {
2439
- var rect = el.getBoundingClientRect();
2440
- if (rect.width === 0 && rect.height === 0) return false;
2441
- }
2442
- return true;
2443
- }
2444
-
2445
- function truncate(s) {
2446
- s = s.trim().replace(/\\s+/g, " ");
2447
- if (s.length > MAX_NAME_LENGTH) return s.slice(0, MAX_NAME_LENGTH - 1) + "\\u2026";
2448
- return s;
2449
- }
2450
-
2451
- function textOf(el) {
2452
- return el.textContent || "";
2453
- }
2454
-
2455
- function idRefsText(doc, ids) {
2456
- var parts = [];
2457
- var list = ids.trim().split(/\\s+/);
2458
- for (var i = 0; i < list.length; i++) {
2459
- var ref = doc.getElementById(list[i]);
2460
- if (ref) parts.push(textOf(ref));
2461
- }
2462
- return parts.join(" ").trim();
2463
- }
2464
-
2465
- // Text of a <label>, minus any nested form control's own content: a
2466
- // label that WRAPS its control ("<label>Color <select>...</select></label>")
2467
- // would otherwise include every option's text in the control's own name.
2468
- function labelOwnText(label) {
2469
- var clone = label.cloneNode(true);
2470
- var controls = clone.querySelectorAll("input, select, textarea, button");
2471
- for (var i = 0; i < controls.length; i++) {
2472
- controls[i].parentNode.removeChild(controls[i]);
2473
- }
2474
- return textOf(clone);
2475
- }
2476
-
2477
- // Guard: without this, an <option> inside a labelled <select> would
2478
- // inherit the select's own label via closest("label"), not its text.
2479
- var LABELABLE_TAGS = { INPUT: 1, TEXTAREA: 1, SELECT: 1, BUTTON: 1, METER: 1, OUTPUT: 1, PROGRESS: 1 };
2480
-
2481
- function nativeLabelText(el) {
2482
- if (!LABELABLE_TAGS[el.tagName]) return "";
2483
- var doc = el.ownerDocument;
2484
- if (el.id) {
2485
- var forLabel = doc.querySelector('label[for="' + el.id + '"]');
2486
- if (forLabel) return labelOwnText(forLabel);
2487
- }
2488
- var ancestor = el.closest ? el.closest("label") : null;
2489
- if (ancestor) return labelOwnText(ancestor);
2490
- return "";
2491
- }
2492
-
2493
- // Reduced accname: aria-labelledby, then aria-label, then native label,
2494
- // then alt/title/placeholder, then trimmed own text for content-named
2495
- // elements. Not the full W3C accname algorithm (no recursive traversal
2496
- // rules for nested presentational content) but covers the common cases.
2497
- function accessibleName(el, contentNamed) {
2498
- var doc = el.ownerDocument;
2499
- var labelledby = el.getAttribute("aria-labelledby");
2500
- if (labelledby) {
2501
- var viaIds = idRefsText(doc, labelledby);
2502
- if (viaIds) return truncate(viaIds);
2503
- }
2504
- var ariaLabel = el.getAttribute("aria-label");
2505
- if (ariaLabel && ariaLabel.trim()) return truncate(ariaLabel);
2506
- var native = nativeLabelText(el);
2507
- if (native && native.trim()) return truncate(native);
2508
- var alt = el.getAttribute("alt");
2509
- if (alt && alt.trim()) return truncate(alt);
2510
- var title = el.getAttribute("title");
2511
- if (title && title.trim()) return truncate(title);
2512
- var placeholder = el.getAttribute("placeholder");
2513
- if (placeholder && placeholder.trim()) return truncate(placeholder);
2514
- if (contentNamed) {
2515
- var text = textOf(el);
2516
- if (text && text.trim()) return truncate(text);
2517
- }
2518
- return "";
2519
- }
2520
-
2521
- var IMPLICIT_ROLE_BY_TAG = {
2522
- A: "link", BUTTON: "button", NAV: "navigation", MAIN: "main", FORM: "form", DIALOG: "dialog",
2523
- UL: "list", OL: "list", LI: "listitem", TABLE: "table", TR: "row", TD: "cell", TH: "columnheader",
2524
- SELECT: "combobox", OPTION: "option", TEXTAREA: "textbox", IMG: "img",
2525
- H1: "heading", H2: "heading", H3: "heading", H4: "heading", H5: "heading", H6: "heading",
2526
- PROGRESS: "progressbar", METER: "meter"
2527
- };
2528
-
2529
- var INPUT_TYPE_ROLE = {
2530
- button: "button", submit: "button", reset: "button", checkbox: "checkbox", radio: "radio",
2531
- range: "slider", number: "spinbutton", search: "searchbox", email: "textbox", tel: "textbox",
2532
- url: "textbox", password: "textbox", text: "textbox", image: "button"
2533
- };
2534
-
2535
- var CONTENT_NAMED_ROLES = {
2536
- button: true, link: true, heading: true, option: true, cell: true,
2537
- columnheader: true, listitem: true, menuitem: true, tab: true
2538
- };
2539
-
2540
- function implicitRole(el) {
2541
- var explicit = el.getAttribute("role");
2542
- if (explicit) return explicit;
2543
- var tag = el.tagName;
2544
- if (tag === "INPUT") {
2545
- var type = (el.getAttribute("type") || "text").toLowerCase();
2546
- return INPUT_TYPE_ROLE[type] || "textbox";
2547
- }
2548
- if (tag === "A" && !el.getAttribute("href")) return "";
2549
- if (Object.prototype.hasOwnProperty.call(IMPLICIT_ROLE_BY_TAG, tag)) {
2550
- return IMPLICIT_ROLE_BY_TAG[tag];
2551
- }
2552
- // Deliberate divergence: Chrome's real AX tree says "generic" here,
2553
- // but "textbox" is the useful signal an agent needs. Chrome is out of
2554
- // step, do not "fix" this toward parity.
2555
- if (el.isContentEditable) return "textbox";
2556
- return "";
2557
- }
2558
-
2559
- function headingLevel(el) {
2560
- var m = /^H([1-6])$/.exec(el.tagName);
2561
- return m ? m[1] : null;
2562
- }
2563
-
2564
- function currentValue(el) {
2565
- var tag = el.tagName;
2566
- if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") {
2567
- return el.value;
2568
- }
2569
- if (el.isContentEditable) return textOf(el);
2570
- return undefined;
2841
+ const end = start + len;
2842
+ if (this.buf.length < end)
2843
+ return;
2844
+ const payload = this.buf.toString("utf8", start, end);
2845
+ this.buf = this.buf.subarray(end);
2846
+ try {
2847
+ return JSON.parse(payload);
2848
+ } catch {
2849
+ throw new MarionetteProtocolError(`frame body was not valid JSON (${len} bytes): ${payload.slice(0, 80)}`);
2571
2850
  }
2572
-
2573
- function isChecked(el) {
2574
- var tag = el.tagName;
2575
- if (tag === "INPUT") {
2576
- var type = (el.getAttribute("type") || "").toLowerCase();
2577
- if (type === "checkbox" || type === "radio") return !!el.checked;
2851
+ }
2852
+ assertDigitsPrefix(upTo) {
2853
+ for (let i = 0;i < upTo; i++) {
2854
+ const b = this.buf[i];
2855
+ if (b < 48 || b > 57) {
2856
+ throw new MarionetteProtocolError(`non-digit byte 0x${b.toString(16)} in frame length prefix`);
2578
2857
  }
2579
- var aria = el.getAttribute("aria-checked");
2580
- if (aria === "true") return true;
2581
- return false;
2582
2858
  }
2583
-
2584
- function describeNode(el, role) {
2585
- var contentNamed = !!CONTENT_NAMED_ROLES[role];
2586
- var name = accessibleName(el, contentNamed);
2587
- var extras = [];
2588
- var value = currentValue(el);
2589
- if (value !== undefined && value !== "") extras.push("value=" + JSON.stringify(String(value)));
2590
- if (isChecked(el)) extras.push("checked=true");
2591
- if (el.tagName === "OPTION" && el.selected) extras.push("selected");
2592
- var href = el.getAttribute("href");
2593
- if (href) extras.push("url=" + href);
2594
- if (el.disabled || el.getAttribute("aria-disabled") === "true") extras.push("disabled");
2595
- var level = headingLevel(el);
2596
- if (level) extras.push("level=" + level);
2597
- var label = name ? " " + JSON.stringify(name) : "";
2598
- var extra = extras.length ? " [" + extras.join(" ") + "]" : "";
2599
- return { role: role, label: label, extra: extra, name: name };
2859
+ }
2860
+ }
2861
+ function isSlotFreedReply(frame) {
2862
+ if (!Array.isArray(frame))
2863
+ return false;
2864
+ const err = frame[2];
2865
+ if (err === null)
2866
+ return true;
2867
+ if (typeof err === "object" && err !== null && err.error === "invalid session id") {
2868
+ return true;
2869
+ }
2870
+ return false;
2871
+ }
2872
+ function forceClearOrphanSession(marionettePort, opts = {}) {
2873
+ const timeoutMs = opts.timeoutMs !== undefined && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0 ? opts.timeoutMs : DEFAULT_TIMEOUT_MS4;
2874
+ return new Promise((resolve) => {
2875
+ if (!Number.isFinite(marionettePort) || marionettePort <= 0 || marionettePort > 65535) {
2876
+ resolve(false);
2877
+ return;
2600
2878
  }
2601
-
2602
- // Traverses light DOM, open shadow roots, and same-origin iframe documents.
2603
- // A cross-origin iframe throws on contentDocument access; caught and
2604
- // skipped rather than aborting the whole walk, and noted in a comment
2605
- // here rather than silently vanishing from the tree without a trace.
2606
- function walk(root, depth) {
2607
- var children = root.children ? Array.prototype.slice.call(root.children) : [];
2608
- for (var i = 0; i < children.length; i++) {
2609
- var el = children[i];
2610
- var isSelectChild = el.tagName === "OPTION" || el.tagName === "OPTGROUP";
2611
- if (!isVisible(el, isSelectChild)) continue;
2612
-
2613
- var role = implicitRole(el);
2614
- var isLandmarkOrControl = !!role;
2615
- var described = null;
2616
- if (isLandmarkOrControl) {
2617
- described = describeNode(el, role);
2618
- }
2619
-
2620
- var hasContent = described && (described.name || described.extra);
2621
- var isStructural = isLandmarkOrControl && (hasContent || isInteractiveRole(role) || isLandmarkRole(role));
2622
-
2623
- // Role-less visible leaf text (measured vs Chrome's take_snapshot,
2624
- // which keeps a StaticText under a generic wrapper for this case,
2625
- // e.g. a plain status <div>). Only a leaf (no element children, so
2626
- // its text is not already captured by a nested control/label).
2627
- var hasElementChildren = !!(el.children && el.children.length > 0);
2628
- var leafName = !isStructural && !hasElementChildren ? truncate(textOf(el)) : "";
2629
- var isLeafText = !!leafName;
2630
-
2631
- var nextDepth = depth;
2632
- if (isStructural || isLeafText) {
2633
- var stamp = stampOf(el);
2634
- var indent = new Array(depth + 1).join(" ");
2635
- var lineTail = isStructural
2636
- ? described.role + described.label + described.extra
2637
- : "text " + JSON.stringify(leafName);
2638
- lines.push(indent + "[" + stamp + "] " + lineTail);
2639
- nodeCount += 1;
2640
- nextDepth = depth + 1;
2641
- }
2642
-
2643
- if (el.shadowRoot) {
2644
- walk(el.shadowRoot, nextDepth);
2645
- } else if (el.tagName === "IFRAME") {
2646
- try {
2647
- var doc = el.contentDocument;
2648
- if (doc && doc.body) walk(doc.body, nextDepth);
2649
- } catch (e) {
2650
- // cross-origin iframe: intentionally skipped, not silently merged
2651
- // into the parent tree as though it were empty.
2879
+ const sock = new Socket;
2880
+ const decoder = new FrameDecoder;
2881
+ let settled = false;
2882
+ let handshakeSeen = false;
2883
+ let commandSent = false;
2884
+ const settle = (value) => {
2885
+ if (settled)
2886
+ return;
2887
+ settled = true;
2888
+ clearTimeout(timer);
2889
+ sock.removeAllListeners();
2890
+ sock.destroy();
2891
+ resolve(value);
2892
+ };
2893
+ const timer = setTimeout(() => settle(false), timeoutMs);
2894
+ if (typeof timer.unref === "function")
2895
+ timer.unref();
2896
+ sock.on("error", () => settle(false));
2897
+ sock.on("close", () => settle(false));
2898
+ sock.on("data", (chunk) => {
2899
+ if (settled)
2900
+ return;
2901
+ try {
2902
+ decoder.push(chunk);
2903
+ for (;; ) {
2904
+ const frame = decoder.next();
2905
+ if (frame === undefined)
2906
+ break;
2907
+ if (!handshakeSeen) {
2908
+ handshakeSeen = true;
2909
+ continue;
2652
2910
  }
2653
- } else {
2654
- walk(el, nextDepth);
2911
+ settle(isSlotFreedReply(frame));
2912
+ return;
2913
+ }
2914
+ if (handshakeSeen && !commandSent) {
2915
+ commandSent = true;
2916
+ sock.write(DELETE_SESSION_FRAME);
2655
2917
  }
2918
+ } catch {
2919
+ settle(false);
2656
2920
  }
2921
+ });
2922
+ try {
2923
+ sock.connect(marionettePort, HOST);
2924
+ } catch {
2925
+ settle(false);
2657
2926
  }
2658
-
2659
- function isInteractiveRole(role) {
2660
- return (
2661
- role === "button" ||
2662
- role === "link" ||
2663
- role === "textbox" ||
2664
- role === "searchbox" ||
2665
- role === "checkbox" ||
2666
- role === "radio" ||
2667
- role === "combobox" ||
2668
- role === "listbox" ||
2669
- role === "option" ||
2670
- role === "slider" ||
2671
- role === "spinbutton" ||
2672
- role === "progressbar" ||
2673
- role === "meter"
2674
- );
2675
- }
2676
-
2677
- function isLandmarkRole(role) {
2678
- return (
2679
- role === "navigation" ||
2680
- role === "main" ||
2681
- role === "form" ||
2682
- role === "dialog" ||
2683
- role === "region" ||
2684
- role === "heading" ||
2685
- role === "list" ||
2686
- role === "listitem" ||
2687
- role === "table" ||
2688
- role === "row" ||
2689
- role === "cell" ||
2690
- role === "columnheader" ||
2691
- role === "img"
2692
- );
2693
- }
2694
-
2695
- walk(document.body, 0);
2696
- return { snapshot: lines.join("\\n"), nodeCount: nodeCount };
2697
- }`;
2927
+ });
2698
2928
  }
2699
- var STAMP_ATTR = "data-cdp-uid", MAX_NAME_LENGTH = 120;
2929
+ var DEFAULT_MARIONETTE_PORT = 2828, DEFAULT_TIMEOUT_MS4 = 4000, HOST = "127.0.0.1", COLON = 58, DELETE_SESSION_FRAME, MarionetteProtocolError;
2930
+ var init_marionette = __esm(() => {
2931
+ DELETE_SESSION_FRAME = encodeFrame2([0, 1, "WebDriver:DeleteSession", {}]);
2932
+ MarionetteProtocolError = class MarionetteProtocolError extends Error {
2933
+ constructor(message) {
2934
+ super(message);
2935
+ this.name = "MarionetteProtocolError";
2936
+ }
2937
+ };
2938
+ });
2700
2939
 
2701
2940
  // src/bidi/driver.ts
2702
2941
  import { spawn as spawn3 } from "node:child_process";
@@ -4062,6 +4301,7 @@ import { fileURLToPath as fileURLToPath2 } from "node:url";
4062
4301
 
4063
4302
  // src/cdp/driver.ts
4064
4303
  init_client();
4304
+ init_session();
4065
4305
  init_leases();
4066
4306
  init_endpoints();
4067
4307
  init_activity();
@@ -5149,9 +5389,17 @@ function beaconKey(targetId) {
5149
5389
  const backend = chromeLeaseBackend(currentEndpoint());
5150
5390
  return backend === "chrome" ? targetId : `${backend}\x00${targetId}`;
5151
5391
  }
5152
- async function targetWsUrl(targetId) {
5392
+ async function openTargetConn(targetId, opts = {}) {
5153
5393
  const hit = (await listTargets()).find((t) => t.id === targetId);
5154
- return hit?.webSocketDebuggerUrl;
5394
+ if (!hit)
5395
+ return;
5396
+ if (!hit.webSocketDebuggerUrl)
5397
+ return openSession(targetId, opts).catch(() => {
5398
+ return;
5399
+ });
5400
+ return new CdpConnection(hit.webSocketDebuggerUrl, opts).connect().catch(() => {
5401
+ return;
5402
+ });
5155
5403
  }
5156
5404
  async function readBeaconOver(conn) {
5157
5405
  try {
@@ -5276,12 +5524,7 @@ class CdpBrowserDriver {
5276
5524
  return true;
5277
5525
  beaconSessions.drop(key);
5278
5526
  }
5279
- const wsUrl = await targetWsUrl(targetId).catch(() => {
5280
- return;
5281
- });
5282
- if (!wsUrl)
5283
- return false;
5284
- const conn = await new CdpConnection(wsUrl).connect().catch(() => {
5527
+ const conn = await openTargetConn(targetId).catch(() => {
5285
5528
  return;
5286
5529
  });
5287
5530
  if (!conn)
@@ -5306,12 +5549,7 @@ class CdpBrowserDriver {
5306
5549
  return value;
5307
5550
  beaconSessions.drop(key);
5308
5551
  }
5309
- const wsUrl = await targetWsUrl(targetId).catch(() => {
5310
- return;
5311
- });
5312
- if (!wsUrl)
5313
- return null;
5314
- const conn = await new CdpConnection(wsUrl).connect().catch(() => {
5552
+ const conn = await openTargetConn(targetId).catch(() => {
5315
5553
  return;
5316
5554
  });
5317
5555
  if (!conn)
@@ -5326,17 +5564,11 @@ class CdpBrowserDriver {
5326
5564
  const held = beaconSessions.get(beaconKey(targetId));
5327
5565
  if (held)
5328
5566
  return probeOver(held, timeoutMs);
5329
- const wsUrl = await targetWsUrl(targetId).catch(() => {
5567
+ const conn = await openTargetConn(targetId, { timeoutMs }).catch(() => {
5330
5568
  return;
5331
5569
  });
5332
- if (!wsUrl)
5333
- return { responsive: false, beaconTs: null };
5334
- const conn = new CdpConnection(wsUrl, { timeoutMs });
5335
- try {
5336
- await conn.connect();
5337
- } catch {
5570
+ if (!conn)
5338
5571
  return { responsive: false, beaconTs: null };
5339
- }
5340
5572
  try {
5341
5573
  return await probeOver(conn, timeoutMs);
5342
5574
  } finally {
@@ -5412,7 +5644,7 @@ async function reapStaleAgentTabs(driver, backend) {
5412
5644
  // src/shared-tools.ts
5413
5645
  init_driver();
5414
5646
  import { mkdir as mkdir5, writeFile as writeFile4 } from "node:fs/promises";
5415
- import { dirname as dirname2, join as join4 } from "node:path";
5647
+ import { dirname as dirname2, join as join5 } from "node:path";
5416
5648
 
5417
5649
  // src/png.ts
5418
5650
  import { once } from "node:events";
@@ -6117,7 +6349,7 @@ async function closePage(driver, args) {
6117
6349
  }
6118
6350
  async function writeSelectedFile(id) {
6119
6351
  await mkdir5(STATE_DIR, { recursive: true });
6120
- await writeFile4(join4(STATE_DIR, "selected"), id, "utf8");
6352
+ await writeFile4(join5(STATE_DIR, "selected"), id, "utf8");
6121
6353
  }
6122
6354
  async function selectPage(driver, args) {
6123
6355
  if (args.target === undefined || args.target === "")
@@ -6181,7 +6413,7 @@ function serializeForSink(value) {
6181
6413
  return json ?? "null";
6182
6414
  }
6183
6415
  async function writeJsonSink(savePath, value) {
6184
- const path = savePath.startsWith("/") ? savePath : join4(ARTIFACT_DIR, savePath);
6416
+ const path = savePath.startsWith("/") ? savePath : join5(ARTIFACT_DIR, savePath);
6185
6417
  await mkdir5(dirname2(path), { recursive: true });
6186
6418
  const json = serializeForSink(value);
6187
6419
  await writeFile4(path, json, "utf8");
@@ -6325,10 +6557,45 @@ async function takeSnapshot(driver, args = {}) {
6325
6557
  `), target: target3(page.info), nodeCount: nodes.length };
6326
6558
  });
6327
6559
  }
6560
+ function describeElementSource() {
6561
+ return `function() {
6562
+ var MAX_NAME_LENGTH = ${MAX_NAME_LENGTH};
6563
+ ${ACCNAME_HELPERS_SOURCE}
6564
+ var el = this;
6565
+ if (!el || el.nodeType !== 1) return null;
6566
+ var role = implicitRole(el);
6567
+ var name = accessibleName(el, !!CONTENT_NAMED_ROLES[role]);
6568
+ if (!name) name = truncate(el.innerText || el.textContent || "");
6569
+ return (role || el.tagName.toLowerCase()) + (name ? " " + JSON.stringify(name) : "");
6570
+ }`;
6571
+ }
6572
+ var DESCRIBE_TIMEOUT_MS = 2000;
6573
+ async function describeElement(page, loc) {
6574
+ let timer;
6575
+ try {
6576
+ const timeout = new Promise((r) => {
6577
+ timer = setTimeout(() => r(undefined), DESCRIBE_TIMEOUT_MS);
6578
+ });
6579
+ const desc = await Promise.race([page.callOnElement(loc, describeElementSource()), timeout]);
6580
+ return typeof desc === "string" && desc.length > 0 ? desc : undefined;
6581
+ } catch {
6582
+ return;
6583
+ } finally {
6584
+ clearTimeout(timer);
6585
+ }
6586
+ }
6587
+ function isElementLocator(d) {
6588
+ return !("x" in d) && !("dx" in d);
6589
+ }
6590
+ function elementField(element) {
6591
+ return element === undefined ? {} : { element };
6592
+ }
6328
6593
  async function click(driver, args) {
6594
+ const loc = locatorOf(args);
6329
6595
  return withPage2(driver, args.target, async (page) => {
6330
- const { x, y } = await page.click(locatorOf(args), { button: args.button ?? "left", clickCount: args.clickCount ?? 1, modifiers: args.modifiers });
6331
- return { clicked: true, x, y };
6596
+ const element = await describeElement(page, loc);
6597
+ const { x, y } = await page.click(loc, { button: args.button ?? "left", clickCount: args.clickCount ?? 1, modifiers: args.modifiers });
6598
+ return { clicked: true, ...elementField(element), x, y };
6332
6599
  });
6333
6600
  }
6334
6601
  function resolveScrollAnchor(args) {
@@ -6364,9 +6631,11 @@ async function scroll(driver, args) {
6364
6631
  });
6365
6632
  }
6366
6633
  async function hover(driver, args) {
6634
+ const loc = locatorOf(args);
6367
6635
  return withPage2(driver, args.target, async (page) => {
6368
- const { x, y } = await page.hover(locatorOf(args));
6369
- return { hovered: true, x, y };
6636
+ const element = await describeElement(page, loc);
6637
+ const { x, y } = await page.hover(loc);
6638
+ return { hovered: true, ...elementField(element), x, y };
6370
6639
  });
6371
6640
  }
6372
6641
  function resolveDragTo(to) {
@@ -6432,16 +6701,29 @@ async function drag(driver, args) {
6432
6701
  const steps = resolveDragSteps(args.steps);
6433
6702
  const mode = resolveDragMode(args.mode, driver.capabilities);
6434
6703
  return withPage2(driver, args.target, async (page) => {
6435
- const { from, to } = await page.drag(locatorOf(args.from), destination, { mode, steps });
6436
- return { dragged: true, mode, steps, from, to };
6704
+ const fromLoc = locatorOf(args.from);
6705
+ const element = await describeElement(page, fromLoc);
6706
+ const targetElement = isElementLocator(destination) ? await describeElement(page, destination) : undefined;
6707
+ const { from, to } = await page.drag(fromLoc, destination, { mode, steps });
6708
+ return {
6709
+ dragged: true,
6710
+ ...elementField(element),
6711
+ ...targetElement === undefined ? {} : { target_element: targetElement },
6712
+ mode,
6713
+ steps,
6714
+ from,
6715
+ to
6716
+ };
6437
6717
  });
6438
6718
  }
6439
6719
  async function fill(driver, args) {
6440
6720
  if (typeof args.value !== "string")
6441
6721
  throw new SharedToolError("fill requires a string { value }");
6722
+ const loc = locatorOf(args);
6442
6723
  return withPage2(driver, args.target, async (page) => {
6443
- await page.setValue(locatorOf(args), args.value);
6444
- return { filled: true, value: args.value };
6724
+ const element = await describeElement(page, loc);
6725
+ await page.setValue(loc, args.value);
6726
+ return { filled: true, ...elementField(element), value: args.value };
6445
6727
  });
6446
6728
  }
6447
6729
  async function fillForm(driver, args) {
@@ -6449,21 +6731,26 @@ async function fillForm(driver, args) {
6449
6731
  throw new SharedToolError("fill_form requires a non-empty { fields } array");
6450
6732
  return withPage2(driver, args.target, async (page) => {
6451
6733
  let filled = 0;
6734
+ const elements = [];
6452
6735
  for (const f of args.fields) {
6453
6736
  if (typeof f.value !== "string")
6454
6737
  throw new SharedToolError("each fill_form field requires a string value");
6455
- await page.setValue(locatorOf(f), f.value);
6738
+ const loc = locatorOf(f);
6739
+ elements.push(await describeElement(page, loc) ?? null);
6740
+ await page.setValue(loc, f.value);
6456
6741
  filled++;
6457
6742
  }
6458
- return { filled, fields: args.fields.length };
6743
+ return { filled, fields: args.fields.length, elements };
6459
6744
  });
6460
6745
  }
6461
6746
  async function typeText(driver, args) {
6462
6747
  if (typeof args.text !== "string")
6463
6748
  throw new SharedToolError("type_text requires a string { text }");
6749
+ const loc = locatorOf(args);
6464
6750
  return withPage2(driver, args.target, async (page) => {
6465
- await page.typeText(locatorOf(args), args.text);
6466
- return { typed: true, text: args.text };
6751
+ const element = await describeElement(page, loc);
6752
+ await page.typeText(loc, args.text);
6753
+ return { typed: true, ...elementField(element), text: args.text };
6467
6754
  });
6468
6755
  }
6469
6756
  async function pressKey(driver, args) {
@@ -6481,8 +6768,10 @@ async function uploadFile(driver, args) {
6481
6768
  throw new SharedToolError("upload_file requires { files } as a non-empty path or array of paths");
6482
6769
  }
6483
6770
  return withPage2(driver, args.target, async (page) => {
6484
- await page.setFiles(locatorOf(args), files);
6485
- return { uploaded: files };
6771
+ const loc = locatorOf(args);
6772
+ const element = await describeElement(page, loc);
6773
+ await page.setFiles(loc, files);
6774
+ return { uploaded: files, ...elementField(element) };
6486
6775
  });
6487
6776
  }
6488
6777
  function stamp() {
@@ -6596,7 +6885,7 @@ async function takeScreenshot(driver, args = {}) {
6596
6885
  return withPage2(driver, args.target, async (page) => {
6597
6886
  const clip = args.uid !== undefined || args.selector ? locatorOf(args) : undefined;
6598
6887
  const ext = format === "jpeg" ? "jpg" : "png";
6599
- const path = args.savePath ?? join4(ARTIFACT_DIR, `screenshot-${page.info.id.slice(0, 8)}-${stamp()}.${ext}`);
6888
+ const path = args.savePath ?? join5(ARTIFACT_DIR, `screenshot-${page.info.id.slice(0, 8)}-${stamp()}.${ext}`);
6600
6889
  const stitch = async (banded) => {
6601
6890
  if (format !== "png")
6602
6891
  throw tiledCaptureRefusal("format", banded);
@@ -6821,7 +7110,7 @@ var LEASE_TOOLS = {
6821
7110
 
6822
7111
  // src/tools/console.ts
6823
7112
  init_client();
6824
- import { readFile as readFile4 } from "node:fs/promises";
7113
+ import { readFile as readFile5 } from "node:fs/promises";
6825
7114
 
6826
7115
  // src/tools/recorder.ts
6827
7116
  init_client();
@@ -7024,7 +7313,7 @@ function lineToEntry(line, index) {
7024
7313
  async function readConsoleEntries(file) {
7025
7314
  let raw;
7026
7315
  try {
7027
- raw = await readFile4(file, "utf8");
7316
+ raw = await readFile5(file, "utf8");
7028
7317
  } catch {
7029
7318
  return [];
7030
7319
  }
@@ -7082,7 +7371,7 @@ async function getConsoleMessage(args = {}) {
7082
7371
 
7083
7372
  // src/tools/network.ts
7084
7373
  init_client();
7085
- import { readFile as readFile5 } from "node:fs/promises";
7374
+ import { readFile as readFile6 } from "node:fs/promises";
7086
7375
  var DEFAULT_CAPTURE_MS2 = 2500;
7087
7376
  function asHeaders(v) {
7088
7377
  if (!v || typeof v !== "object")
@@ -7149,7 +7438,7 @@ function correlate(lines) {
7149
7438
  async function readNetworkRequests(file) {
7150
7439
  let raw;
7151
7440
  try {
7152
- raw = await readFile5(file, "utf8");
7441
+ raw = await readFile6(file, "utf8");
7153
7442
  } catch {
7154
7443
  return [];
7155
7444
  }
@@ -7234,8 +7523,8 @@ async function getNetworkRequest(args = {}) {
7234
7523
 
7235
7524
  // src/tools/performance.ts
7236
7525
  init_client();
7237
- import { mkdir as mkdir7, readFile as readFile6, writeFile as writeFile6, stat, unlink as unlink4 } from "node:fs/promises";
7238
- import { join as join5 } from "node:path";
7526
+ import { mkdir as mkdir7, readFile as readFile7, writeFile as writeFile6, stat, unlink as unlink4 } from "node:fs/promises";
7527
+ import { join as join6 } from "node:path";
7239
7528
  var ARTIFACT_DIR2 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7240
7529
  var STATE_DIR2 = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
7241
7530
  var DEFAULT_CATEGORIES = [
@@ -7253,7 +7542,7 @@ function shortId(id) {
7253
7542
  return id.slice(0, 8);
7254
7543
  }
7255
7544
  function stateFilePath() {
7256
- return join5(STATE_DIR2, "trace-state.json");
7545
+ return join6(STATE_DIR2, "trace-state.json");
7257
7546
  }
7258
7547
  function bufferTraceData(conn, sink) {
7259
7548
  return conn.on("Tracing.dataCollected", (params) => {
@@ -7276,7 +7565,7 @@ async function endTrace(conn, sink, timeoutMs = 30000) {
7276
7565
  }
7277
7566
  async function writeTrace(events, targetId) {
7278
7567
  await mkdir7(ARTIFACT_DIR2, { recursive: true });
7279
- const path = join5(ARTIFACT_DIR2, `trace-${shortId(targetId)}-${stamp2()}.json`);
7568
+ const path = join6(ARTIFACT_DIR2, `trace-${shortId(targetId)}-${stamp2()}.json`);
7280
7569
  const body = JSON.stringify({ traceEvents: events, metadata: { source: "cdp-toolkit" } });
7281
7570
  await writeFile6(path, body, "utf8");
7282
7571
  const { size } = await stat(path);
@@ -7319,7 +7608,7 @@ async function performanceStopTrace(args = {}) {
7319
7608
  if (!entry) {
7320
7609
  let hint = "";
7321
7610
  try {
7322
- const raw = await readFile6(stateFilePath(), "utf8");
7611
+ const raw = await readFile7(stateFilePath(), "utf8");
7323
7612
  const state = JSON.parse(raw);
7324
7613
  hint = state.pid === process.pid ? ` (state file lists target ${shortId(state.targetId)} but its live connection is gone)` : ` (trace was started by a DIFFERENT process pid=${state.pid}; live recordings cannot cross process boundaries)`;
7325
7614
  } catch {}
@@ -7449,7 +7738,7 @@ async function performanceAnalyzeInsight(args = {}) {
7449
7738
  }
7450
7739
  let raw;
7451
7740
  try {
7452
- raw = await readFile6(args.tracePath, "utf8");
7741
+ raw = await readFile7(args.tracePath, "utf8");
7453
7742
  } catch (err) {
7454
7743
  throw new CdpError(`cannot read trace file '${args.tracePath}': ${err.message}`);
7455
7744
  }
@@ -7469,7 +7758,7 @@ async function performanceAnalyzeInsight(args = {}) {
7469
7758
  init_client();
7470
7759
  import { spawn } from "node:child_process";
7471
7760
  import { mkdir as mkdir8, rm as rm2, stat as stat2, writeFile as writeFile7 } from "node:fs/promises";
7472
- import { join as join6 } from "node:path";
7761
+ import { join as join7 } from "node:path";
7473
7762
  var ARTIFACT_DIR3 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7474
7763
  var FFMPEG_BIN = process.env.CDP_FFMPEG ?? "ffmpeg";
7475
7764
  function frameDurationsMs(ledger, stopWallclockMs) {
@@ -7585,6 +7874,22 @@ function selectEncoder(encodersOutput) {
7585
7874
  }
7586
7875
  throw new CdpError(`ffmpeg reports none of the supported video encoders (${ENCODER_LADDER.map((c) => c.encoder).join(", ")}). ` + "Install a full ffmpeg build: 'brew install ffmpeg' (macOS) or 'apt install ffmpeg' (Debian/Ubuntu).");
7587
7876
  }
7877
+ function supportsFpsMode(versionOutput) {
7878
+ const m = /ffmpeg version n?(\d+)\.(\d+)/.exec(versionOutput);
7879
+ if (!m)
7880
+ return /ffmpeg version N-/.test(versionOutput) ? true : undefined;
7881
+ const major = Number(m[1]);
7882
+ const minor = Number(m[2]);
7883
+ return major > 5 || major === 5 && minor >= 1;
7884
+ }
7885
+ function chooseFpsMode(versionOutput, helpOutput) {
7886
+ const byVersion = versionOutput === undefined ? undefined : supportsFpsMode(versionOutput);
7887
+ if (byVersion !== undefined)
7888
+ return byVersion;
7889
+ if (helpOutput !== undefined && /-vsync\b|-fps_mode\b/.test(helpOutput))
7890
+ return /-fps_mode\b/.test(helpOutput);
7891
+ return true;
7892
+ }
7588
7893
  function buildFfmpegArgs(manifestPath, outPath, choice) {
7589
7894
  return [
7590
7895
  "-hide_banner",
@@ -7597,8 +7902,7 @@ function buildFfmpegArgs(manifestPath, outPath, choice) {
7597
7902
  "0",
7598
7903
  "-i",
7599
7904
  manifestPath,
7600
- "-vsync",
7601
- "vfr",
7905
+ ...choice.fpsMode ? ["-fps_mode", "vfr"] : ["-vsync", "vfr"],
7602
7906
  "-vf",
7603
7907
  "scale=trunc(iw/2)*2:trunc(ih/2)*2",
7604
7908
  "-c:v",
@@ -7640,8 +7944,19 @@ async function probeEncoder() {
7640
7944
  }
7641
7945
  if (res.code !== 0)
7642
7946
  throw new CdpError(`${FFMPEG_MISSING} ('-encoders' exited ${res.code}: ${res.stderr.trim().slice(0, 300)})`);
7643
- return selectEncoder(`${res.stdout}
7947
+ const choice = selectEncoder(`${res.stdout}
7644
7948
  ${res.stderr}`);
7949
+ const output = async (args) => {
7950
+ const r = await run(FFMPEG_BIN, args).catch(() => {
7951
+ return;
7952
+ });
7953
+ return r && r.code === 0 ? `${r.stdout}
7954
+ ${r.stderr}` : undefined;
7955
+ };
7956
+ const version = await output(["-version"]);
7957
+ const byVersion = version === undefined ? undefined : supportsFpsMode(version);
7958
+ const help = byVersion === undefined ? await output(["-hide_banner", "-h", "full"]) : undefined;
7959
+ return { ...choice, fpsMode: chooseFpsMode(version, help) };
7645
7960
  })();
7646
7961
  encoderProbe.catch(() => {
7647
7962
  encoderProbe = undefined;
@@ -7690,7 +8005,7 @@ async function startScreenRecording(args = {}) {
7690
8005
  conn.close();
7691
8006
  throw err;
7692
8007
  }
7693
- const spoolDir = join6(ARTIFACT_DIR3, `screencast-${shortId2(target.id)}-${stamp3()}`);
8008
+ const spoolDir = join7(ARTIFACT_DIR3, `screencast-${shortId2(target.id)}-${stamp3()}`);
7694
8009
  try {
7695
8010
  await mkdir8(spoolDir, { recursive: true });
7696
8011
  } catch (err) {
@@ -7733,7 +8048,7 @@ async function startScreenRecording(args = {}) {
7733
8048
  seq += 1;
7734
8049
  const file = `frame-${String(seq).padStart(6, "0")}.${ext}`;
7735
8050
  rec.ledger.push({ file, timestamp, width: size.width, height: size.height });
7736
- rec.writes = rec.writes.then(() => writeFile7(join6(spoolDir, file), buf)).catch(() => {
8051
+ rec.writes = rec.writes.then(() => writeFile7(join7(spoolDir, file), buf)).catch(() => {
7737
8052
  rec.dropped += 1;
7738
8053
  rec.unwritten.add(file);
7739
8054
  });
@@ -7797,9 +8112,9 @@ async function stopScreenRecording(args = {}) {
7797
8112
  throw new CdpError(`screen recording captured 0 frames for target ${shortId2(rec.target.id)}. Chrome emits a screencast frame only on repaint: a fully backgrounded or occluded tab may never paint. Retry with bringToFront:true, or drive the page while recording.`);
7798
8113
  }
7799
8114
  await mkdir8(ARTIFACT_DIR3, { recursive: true });
7800
- const outPath = args.savePath ?? join6(ARTIFACT_DIR3, `screen-recording-${shortId2(rec.target.id)}-${stamp3()}.mp4`);
8115
+ const outPath = args.savePath ?? join7(ARTIFACT_DIR3, `screen-recording-${shortId2(rec.target.id)}-${stamp3()}.mp4`);
7801
8116
  const frames = coalesceToConcatGrid(ledger, stoppedAt);
7802
- const manifestPath = join6(rec.spoolDir, "frames.ffconcat");
8117
+ const manifestPath = join7(rec.spoolDir, "frames.ffconcat");
7803
8118
  await writeFile7(manifestPath, buildConcatManifest(frames), "utf8");
7804
8119
  const durationMs = frames.reduce((total, f) => total + f.durationMs, 0);
7805
8120
  const { width, height } = evenDimensions(ledger[0].width, ledger[0].height);
@@ -7833,7 +8148,7 @@ ffmpeg said: ${res.stderr.trim().slice(0, 800)}`);
7833
8148
  // src/tools/heap.ts
7834
8149
  init_client();
7835
8150
  import { mkdir as mkdir9, writeFile as writeFile8 } from "node:fs/promises";
7836
- import { join as join7 } from "node:path";
8151
+ import { join as join8 } from "node:path";
7837
8152
  var ARTIFACT_DIR4 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7838
8153
  function stamp4(targetId) {
7839
8154
  const short = targetId.slice(0, 8);
@@ -7859,7 +8174,7 @@ async function takeHeapsnapshot(args = {}) {
7859
8174
  throw new Error("HeapProfiler.takeHeapSnapshot produced no chunks");
7860
8175
  }
7861
8176
  await mkdir9(ARTIFACT_DIR4, { recursive: true });
7862
- const path = args.savePath ? args.savePath.startsWith("/") ? args.savePath : join7(ARTIFACT_DIR4, args.savePath) : join7(ARTIFACT_DIR4, `take_heapsnapshot-${stamp4(target.id)}.heapsnapshot`);
8177
+ const path = args.savePath ? args.savePath.startsWith("/") ? args.savePath : join8(ARTIFACT_DIR4, args.savePath) : join8(ARTIFACT_DIR4, `take_heapsnapshot-${stamp4(target.id)}.heapsnapshot`);
7863
8178
  await writeFile8(path, snapshot, "utf8");
7864
8179
  const bytes = Buffer.byteLength(snapshot, "utf8");
7865
8180
  return {
@@ -7875,7 +8190,7 @@ async function takeHeapsnapshot(args = {}) {
7875
8190
  init_client();
7876
8191
  init_endpoints();
7877
8192
  import { spawn as spawn2 } from "node:child_process";
7878
- import { mkdir as mkdir10, readFile as readFile7, stat as stat3 } from "node:fs/promises";
8193
+ import { mkdir as mkdir10, readFile as readFile8, stat as stat3 } from "node:fs/promises";
7879
8194
  var ARTIFACT_DIR5 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7880
8195
  function cdpPort() {
7881
8196
  const base = currentEndpoint().base;
@@ -7965,7 +8280,7 @@ async function lighthouseAudit(args) {
7965
8280
  }
7966
8281
  let raw;
7967
8282
  try {
7968
- raw = await readFile7(outPath, "utf8");
8283
+ raw = await readFile8(outPath, "utf8");
7969
8284
  } catch {
7970
8285
  raw = undefined;
7971
8286
  }
@@ -8155,15 +8470,15 @@ async function clickFocusGated(args) {
8155
8470
  // src/tools/downloads.ts
8156
8471
  init_client();
8157
8472
  import { readdir as readdir3, rename as rename2, stat as stat4 } from "node:fs/promises";
8158
- import { basename, extname, join as join9 } from "node:path";
8473
+ import { basename, extname, join as join10 } from "node:path";
8159
8474
 
8160
8475
  // src/tools/browser-session.ts
8161
8476
  init_client();
8162
8477
  init_endpoints();
8163
8478
  import { mkdir as mkdir11 } from "node:fs/promises";
8164
- import { join as join8 } from "node:path";
8479
+ import { join as join9 } from "node:path";
8165
8480
  var ARTIFACT_DIR6 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
8166
- var DOWNLOADS_DIR = join8(ARTIFACT_DIR6, "downloads");
8481
+ var DOWNLOADS_DIR = join9(ARTIFACT_DIR6, "downloads");
8167
8482
  var DOWNLOAD_BUFFER_LIMIT = 50;
8168
8483
  var sessions2 = new Map;
8169
8484
  function sessionKey() {
@@ -8330,7 +8645,7 @@ async function waitForDownload(args = {}) {
8330
8645
  const taken = new Set(await readdir3(DOWNLOADS_DIR).catch(() => []));
8331
8646
  taken.delete(basename(rec.filePath));
8332
8647
  const finalName = nextFreeName(suggestedFilename, taken);
8333
- const path = join9(DOWNLOADS_DIR, finalName);
8648
+ const path = join10(DOWNLOADS_DIR, finalName);
8334
8649
  await rename2(rec.filePath, path);
8335
8650
  const bytes = (await stat4(path)).size;
8336
8651
  return { path, suggestedFilename, bytes, ...rec.url ? { url: rec.url } : {}, target };
@@ -8389,7 +8704,7 @@ async function grantPermissions(args = {}) {
8389
8704
  // src/tools/extract.ts
8390
8705
  init_client();
8391
8706
  import { mkdir as mkdir12, writeFile as writeFile9 } from "node:fs/promises";
8392
- import { dirname as dirname3, join as join10 } from "node:path";
8707
+ import { dirname as dirname3, join as join11 } from "node:path";
8393
8708
  var ARTIFACT_DIR7 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
8394
8709
  var DEFAULT_BASE_URL = "http://127.0.0.1:8090/v1";
8395
8710
  var DEFAULT_MODEL = "schematron";
@@ -8790,7 +9105,7 @@ async function extractPage(driver, args) {
8790
9105
  };
8791
9106
  if (args.savePath === undefined || args.savePath === "")
8792
9107
  return result;
8793
- const path = args.savePath.startsWith("/") ? args.savePath : join10(ARTIFACT_DIR7, args.savePath);
9108
+ const path = args.savePath.startsWith("/") ? args.savePath : join11(ARTIFACT_DIR7, args.savePath);
8794
9109
  await mkdir12(dirname3(path), { recursive: true });
8795
9110
  const json = JSON.stringify(result, null, 2);
8796
9111
  await writeFile9(path, json, "utf8");
@@ -10702,7 +11017,7 @@ import { spawn as spawn4 } from "node:child_process";
10702
11017
  import { existsSync as existsSync2, mkdtempSync, readFileSync as readFileSync2, rmSync, writeFileSync } from "node:fs";
10703
11018
  import { createConnection, createServer as createServer2 } from "node:net";
10704
11019
  import { tmpdir } from "node:os";
10705
- import { join as join12 } from "node:path";
11020
+ import { join as join13 } from "node:path";
10706
11021
  function resolveBinary() {
10707
11022
  const candidates = [
10708
11023
  process.env.FIREFOX_BIN,
@@ -10782,7 +11097,7 @@ var LAUNCH_USER_JS_PREFS = {
10782
11097
  "dom.file.createInChild": true
10783
11098
  };
10784
11099
  function writeLaunchUserJs(profilePath) {
10785
- const target = join12(profilePath, "user.js");
11100
+ const target = join13(profilePath, "user.js");
10786
11101
  const existing = existsSync2(target) ? readFileSync2(target, "utf8") : "";
10787
11102
  const present = new Set;
10788
11103
  for (const line of existing.split(`
@@ -10804,7 +11119,7 @@ async function launchFirefox(opts = {}) {
10804
11119
  const binary = resolveBinary();
10805
11120
  const port = await pickPort(opts.port);
10806
11121
  const isThrowaway = opts.profilePath === undefined;
10807
- const profilePath = opts.profilePath ?? mkdtempSync(join12(tmpdir(), "cdp-toolkit-ff-profile-"));
11122
+ const profilePath = opts.profilePath ?? mkdtempSync(join13(tmpdir(), "cdp-toolkit-ff-profile-"));
10808
11123
  if (isThrowaway)
10809
11124
  writeLaunchUserJs(profilePath);
10810
11125
  const args = ["--profile", profilePath, "--remote-debugging-port", String(port), "--no-remote"];
@@ -11394,7 +11709,7 @@ var TOOL_DOCS = {
11394
11709
  }
11395
11710
  },
11396
11711
  click: {
11397
- description: "Click an element via a synthetic mouse press/release at its scrolled-into-view center. Give exactly one of uid or selector. modifiers (Alt/Control/Meta/Shift) throws on the Firefox backend — use --browser chrome for a modifier-click. clickCount:3 triple-clicks (selects a line/paragraph in most editors).",
11712
+ description: 'Click an element via a synthetic mouse press/release at its scrolled-into-view center. Give exactly one of uid or selector. modifiers (Alt/Control/Meta/Shift) throws on the Firefox backend — use --browser chrome for a modifier-click. clickCount:3 triple-clicks (selects a line/paragraph in most editors). Returns {clicked,element,x,y}; element names what was hit, snapshot-style (button "Save"), read before the click and omitted if it cannot be read.',
11398
11713
  params: {
11399
11714
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11400
11715
  target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
@@ -11492,7 +11807,7 @@ var TOOL_DOCS = {
11492
11807
  }
11493
11808
  },
11494
11809
  fill: {
11495
- description: "Fills an element by focusing it, clearing existing content, then inserting value via Input.insertText (atomic paste-like commit, not per-character keystrokes — won't fire per-keypress handlers). Give exactly one of uid or selector.",
11810
+ description: `Fills an element by focusing it, clearing existing content, then inserting value via Input.insertText (atomic paste-like commit, not per-character keystrokes — won't fire per-keypress handlers). Give exactly one of uid or selector. Returns {filled,element,value}; element names the field (textbox "Email").`,
11496
11811
  params: {
11497
11812
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11498
11813
  target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
@@ -11880,7 +12195,7 @@ function toolAnnotations(name) {
11880
12195
  }
11881
12196
 
11882
12197
  // src/version.ts
11883
- var VERSION = "3.1.0";
12198
+ var VERSION = "3.2.0";
11884
12199
 
11885
12200
  // src/mcp.ts
11886
12201
  function isDirectRun() {