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/index.js CHANGED
@@ -802,6 +802,204 @@ var init_frames = __esm(() => {
802
802
  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.";
803
803
  });
804
804
 
805
+ // src/cdp/endpoint.ts
806
+ import { readFile as readFile3 } from "node:fs/promises";
807
+ import { join as join3 } from "node:path";
808
+ async function browserWsFromPortFile(dir, base) {
809
+ const raw = await readFile3(join3(dir, "DevToolsActivePort"), "utf8").catch(() => {
810
+ return;
811
+ });
812
+ if (!raw)
813
+ return;
814
+ const [port, path] = raw.split(`
815
+ `);
816
+ if (!port?.trim() || !path?.trim())
817
+ return;
818
+ const host = new URL(base).hostname;
819
+ return `ws://${host}:${port.trim()}${path.trim()}`;
820
+ }
821
+ async function discoverBrowserWs(base) {
822
+ const dir = process.env.CDP_USER_DATA_DIR;
823
+ return dir ? browserWsFromPortFile(dir, base) : undefined;
824
+ }
825
+ async function handshake(url, timeoutMs) {
826
+ const conn = new CdpConnection(url, { timeoutMs });
827
+ try {
828
+ await conn.connect();
829
+ return true;
830
+ } catch {
831
+ return false;
832
+ } finally {
833
+ conn.close();
834
+ }
835
+ }
836
+ function detectEndpoint() {
837
+ const endpoint = currentEndpoint();
838
+ const base = endpoint.base;
839
+ const isDefault = isDefaultEndpoint(endpoint);
840
+ const hit = cached.get(base);
841
+ if (hit)
842
+ return hit;
843
+ const detection = (async () => {
844
+ const forced = isDefault ? process.env.CDP_BROWSER_WS : undefined;
845
+ if (forced)
846
+ return { transport: "browser-ws", browserWsUrl: forced };
847
+ const discovered = isDefault ? await discoverBrowserWs(base) : undefined;
848
+ if (discovered && await handshake(discovered, 5000)) {
849
+ return { transport: "browser-ws", browserWsUrl: discovered };
850
+ }
851
+ const version = await fetch(`${base}/json/version`, { signal: AbortSignal.timeout(5000) }).then((r) => r.ok ? r.json() : undefined).catch(() => {
852
+ return;
853
+ });
854
+ if (version?.webSocketDebuggerUrl) {
855
+ return { transport: "http", browserWsUrl: version.webSocketDebuggerUrl };
856
+ }
857
+ const dir = isDefault ? process.env.CDP_USER_DATA_DIR : undefined;
858
+ 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.`);
859
+ })().then((info) => {
860
+ if (info.transport === "http")
861
+ cached.delete(base);
862
+ return info;
863
+ }, (error) => {
864
+ cached.delete(base);
865
+ throw error;
866
+ });
867
+ cached.set(base, detection);
868
+ return detection;
869
+ }
870
+ function forgetEndpoint() {
871
+ cached.delete(currentEndpoint().base);
872
+ }
873
+ var cached;
874
+ var init_endpoint = __esm(() => {
875
+ init_endpoints();
876
+ init_client();
877
+ cached = new Map;
878
+ });
879
+
880
+ // src/cdp/session.ts
881
+ async function acquireBrowserConn() {
882
+ if (shared) {
883
+ shared.refs++;
884
+ return shared.conn;
885
+ }
886
+ if (!opening) {
887
+ opening = (async () => {
888
+ let { browserWsUrl } = await detectEndpoint();
889
+ let conn;
890
+ try {
891
+ conn = await new CdpConnection(browserWsUrl).connect();
892
+ } catch (error) {
893
+ forgetEndpoint();
894
+ const fresh = (await detectEndpoint().catch(() => {
895
+ return;
896
+ }))?.browserWsUrl;
897
+ if (!fresh || fresh === browserWsUrl)
898
+ throw error;
899
+ browserWsUrl = fresh;
900
+ conn = await new CdpConnection(browserWsUrl).connect();
901
+ }
902
+ shared = { conn, refs: 0, url: browserWsUrl };
903
+ return conn;
904
+ })().finally(() => {
905
+ opening = undefined;
906
+ });
907
+ }
908
+ const conn = await opening;
909
+ shared.refs++;
910
+ return conn;
911
+ }
912
+ function releaseBrowserConn() {
913
+ if (!shared)
914
+ return;
915
+ shared.refs--;
916
+ if (shared.refs <= 0) {
917
+ const { conn } = shared;
918
+ shared = undefined;
919
+ conn.close();
920
+ }
921
+ }
922
+ async function withBrowserSocket(fn) {
923
+ const conn = await acquireBrowserConn();
924
+ try {
925
+ return await fn(conn);
926
+ } finally {
927
+ releaseBrowserConn();
928
+ }
929
+ }
930
+
931
+ class SessionConnection {
932
+ browser;
933
+ sessionId;
934
+ opts;
935
+ detached = false;
936
+ offs = [];
937
+ constructor(browser, sessionId, opts = {}) {
938
+ this.browser = browser;
939
+ this.sessionId = sessionId;
940
+ this.opts = opts;
941
+ }
942
+ send(method, params = {}, opts = {}) {
943
+ if (this.detached)
944
+ return Promise.reject(new CdpError("connection not open"));
945
+ return this.browser.send(method, params, {
946
+ timeoutMs: opts.timeoutMs ?? this.opts.timeoutMs,
947
+ sessionId: opts.sessionId ?? this.sessionId
948
+ });
949
+ }
950
+ on(method, handler) {
951
+ const off = this.browser.on(method, (params, sessionId) => {
952
+ if (sessionId && sessionId !== this.sessionId)
953
+ return;
954
+ handler(params, sessionId);
955
+ });
956
+ this.offs.push(off);
957
+ return off;
958
+ }
959
+ waitFor(method, predicate, timeoutMs = this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS) {
960
+ return new Promise((resolve, reject) => {
961
+ const timer = setTimeout(() => {
962
+ off();
963
+ reject(new CdpError(`waitFor('${method}') timed out after ${timeoutMs}ms`));
964
+ }, timeoutMs);
965
+ const off = this.on(method, (params) => {
966
+ if (!predicate || predicate(params)) {
967
+ clearTimeout(timer);
968
+ off();
969
+ resolve(params);
970
+ }
971
+ });
972
+ });
973
+ }
974
+ close() {
975
+ if (this.detached)
976
+ return;
977
+ this.detached = true;
978
+ for (const off of this.offs)
979
+ off();
980
+ this.offs.length = 0;
981
+ this.browser.send("Target.detachFromTarget", { sessionId: this.sessionId }).catch(() => {});
982
+ releaseBrowserConn();
983
+ }
984
+ }
985
+ async function openSession(targetId, opts = {}) {
986
+ const browser = await acquireBrowserConn();
987
+ try {
988
+ const { sessionId } = await browser.send("Target.attachToTarget", { targetId, flatten: true }, { timeoutMs: opts.timeoutMs });
989
+ if (!sessionId)
990
+ throw new CdpError(`Target.attachToTarget returned no sessionId for ${targetId}`);
991
+ return new SessionConnection(browser, sessionId, opts);
992
+ } catch (e) {
993
+ releaseBrowserConn();
994
+ throw e;
995
+ }
996
+ }
997
+ var shared, opening;
998
+ var init_session = __esm(() => {
999
+ init_client();
1000
+ init_endpoint();
1001
+ });
1002
+
805
1003
  // src/client.ts
806
1004
  class CdpConnection {
807
1005
  wsUrl;
@@ -934,12 +1132,47 @@ async function httpJson(path) {
934
1132
  throw new CdpError(`${path} -> HTTP ${res.status}`);
935
1133
  return await res.json();
936
1134
  }
937
- function listTargets() {
938
- return httpJson("/json/list");
1135
+ async function getTargetsOverBrowserWs() {
1136
+ const { targetInfos } = await withBrowserSocket((conn) => conn.send("Target.getTargets", { filter: [{}] }));
1137
+ return targetInfos.map((t) => ({
1138
+ id: t.targetId,
1139
+ type: t.type,
1140
+ title: t.title,
1141
+ url: t.url,
1142
+ webSocketDebuggerUrl: "",
1143
+ ...t.openerId ? { parentId: t.openerId } : {}
1144
+ }));
1145
+ }
1146
+ async function listTargets() {
1147
+ const base = currentEndpoint().base;
1148
+ if (knownTransports.get(base) === "browser-ws")
1149
+ return getTargetsOverBrowserWs();
1150
+ try {
1151
+ const listing = await httpJson("/json/list");
1152
+ knownTransports.set(base, "http");
1153
+ return listing;
1154
+ } catch (httpError) {
1155
+ const detected = await detectEndpoint().catch(() => {
1156
+ return;
1157
+ });
1158
+ if (detected?.transport !== "browser-ws")
1159
+ throw httpError;
1160
+ const targets = await getTargetsOverBrowserWs().catch(() => {
1161
+ throw httpError;
1162
+ });
1163
+ knownTransports.set(base, "browser-ws");
1164
+ return targets;
1165
+ }
939
1166
  }
940
1167
  async function browserWsUrl() {
941
- const v = await httpJson("/json/version");
942
- return v.webSocketDebuggerUrl;
1168
+ if (knownTransports.get(currentEndpoint().base) !== "browser-ws") {
1169
+ const version = await httpJson("/json/version").catch(() => {
1170
+ return;
1171
+ });
1172
+ if (version?.webSocketDebuggerUrl)
1173
+ return version.webSocketDebuggerUrl;
1174
+ }
1175
+ return (await detectEndpoint()).browserWsUrl;
943
1176
  }
944
1177
  async function resolveTarget(selector, opts = {}) {
945
1178
  const targets = await listTargets();
@@ -1021,7 +1254,7 @@ async function openBrowser(opts = {}) {
1021
1254
  }
1022
1255
  async function openPage(selector, opts = {}) {
1023
1256
  const target = await resolveTarget(selector, { lease: opts.lease });
1024
- const conn = await new CdpConnection(target.webSocketDebuggerUrl, opts).connect();
1257
+ const conn = target.webSocketDebuggerUrl ? await new CdpConnection(target.webSocketDebuggerUrl, opts).connect() : await openSession(target.id, opts);
1025
1258
  return { conn, target };
1026
1259
  }
1027
1260
  async function withPage(selector, fn, opts = {}) {
@@ -1032,13 +1265,16 @@ async function withPage(selector, fn, opts = {}) {
1032
1265
  conn.close();
1033
1266
  }
1034
1267
  }
1035
- var BASE, DEFAULT_TIMEOUT_MS, CdpError;
1268
+ var BASE, DEFAULT_TIMEOUT_MS, CdpError, knownTransports;
1036
1269
  var init_client = __esm(() => {
1037
1270
  init_leases();
1038
1271
  init_origins();
1039
1272
  init_endpoints();
1040
1273
  init_workers();
1041
1274
  init_frames();
1275
+ init_endpoint();
1276
+ init_session();
1277
+ init_session();
1042
1278
  BASE = (() => {
1043
1279
  try {
1044
1280
  return defaultEndpoint().base;
@@ -1057,6 +1293,7 @@ var init_client = __esm(() => {
1057
1293
  this.name = "CdpError";
1058
1294
  }
1059
1295
  };
1296
+ knownTransports = new Map;
1060
1297
  });
1061
1298
 
1062
1299
  // src/activity.ts
@@ -1373,8 +1610,8 @@ var init_network_mock = __esm(() => {
1373
1610
  });
1374
1611
 
1375
1612
  // src/driver.ts
1376
- import { mkdir as mkdir3, readFile as readFile3, unlink as unlink3, writeFile as writeFile3 } from "node:fs/promises";
1377
- import { join as join3 } from "node:path";
1613
+ import { mkdir as mkdir3, readFile as readFile4, unlink as unlink3, writeFile as writeFile3 } from "node:fs/promises";
1614
+ import { join as join4 } from "node:path";
1378
1615
  function isDriverError(e) {
1379
1616
  return e instanceof Error && typeof e.code === "string";
1380
1617
  }
@@ -1390,11 +1627,11 @@ function isTiledCapture(delivery) {
1390
1627
  return delivery.tiled === true;
1391
1628
  }
1392
1629
  function viewportRecordFile(scheme, targetId) {
1393
- return join3(leaseDir(), `viewport-${scheme}-${targetId.replace(/[^A-Za-z0-9._-]/g, "_")}.json`);
1630
+ return join4(leaseDir(), `viewport-${scheme}-${targetId.replace(/[^A-Za-z0-9._-]/g, "_")}.json`);
1394
1631
  }
1395
1632
  async function readViewportRecord(scheme, targetId) {
1396
1633
  try {
1397
- const raw = JSON.parse(await readFile3(viewportRecordFile(scheme, targetId), "utf8"));
1634
+ const raw = JSON.parse(await readFile4(viewportRecordFile(scheme, targetId), "utf8"));
1398
1635
  if (typeof raw?.width !== "number" || typeof raw?.height !== "number")
1399
1636
  return;
1400
1637
  return {
@@ -1445,8 +1682,324 @@ var init_driver = __esm(() => {
1445
1682
  };
1446
1683
  });
1447
1684
 
1685
+ // src/bidi/snapshot.ts
1686
+ async function takeStampedSnapshot(evaluate) {
1687
+ const raw = await evaluate(buildSnapshotFunctionSource());
1688
+ return coerceSnapshotResult(raw);
1689
+ }
1690
+ function coerceSnapshotResult(raw) {
1691
+ if (typeof raw !== "object" || raw === null || typeof raw.snapshot !== "string" || typeof raw.nodeCount !== "number") {
1692
+ throw new Error("takeStampedSnapshot: evaluate() returned an unexpected shape");
1693
+ }
1694
+ return { snapshot: raw.snapshot, nodeCount: raw.nodeCount };
1695
+ }
1696
+ function buildSnapshotFunctionSource() {
1697
+ return `function() {
1698
+ var STAMP_ATTR = ${JSON.stringify(STAMP_ATTR)};
1699
+ var MAX_NAME_LENGTH = ${MAX_NAME_LENGTH};
1700
+ var lines = [];
1701
+ var nodeCount = 0;
1702
+
1703
+ // THE UID CODEC (driver.ts) documents a bidi payload as exactly 12 lowercase hex chars,
1704
+ // /^[0-9a-f]{12}$/. Build it from two padded random blocks so the length is exact regardless
1705
+ // of the random value drawn, never from string concatenation that could come up short.
1706
+ function nextStamp() {
1707
+ var hi = Math.floor(Math.random() * 0x100000000).toString(16).padStart(8, "0");
1708
+ var lo = Math.floor(Math.random() * 0x10000).toString(16).padStart(4, "0");
1709
+ return hi + lo;
1710
+ }
1711
+
1712
+ function stampOf(el) {
1713
+ var existing = el.getAttribute(STAMP_ATTR);
1714
+ if (existing) return existing;
1715
+ var stamp = nextStamp();
1716
+ el.setAttribute(STAMP_ATTR, stamp);
1717
+ return stamp;
1718
+ }
1719
+
1720
+ // skipSizeCheck exempts <option>/<optgroup> from the zero-size prune: a
1721
+ // closed select's popup is unpainted (0x0) though its options are still
1722
+ // present and pickable. Other visibility rules still apply to them.
1723
+ function isVisible(el, skipSizeCheck) {
1724
+ if (el.hidden) return false;
1725
+ if (el.getAttribute("aria-hidden") === "true") return false;
1726
+ var style;
1727
+ try {
1728
+ style = el.ownerDocument.defaultView.getComputedStyle(el);
1729
+ } catch (e) {
1730
+ style = null;
1731
+ }
1732
+ if (style) {
1733
+ if (style.display === "none" || style.visibility === "hidden") return false;
1734
+ }
1735
+ if (!skipSizeCheck) {
1736
+ var rect = el.getBoundingClientRect();
1737
+ if (rect.width === 0 && rect.height === 0) return false;
1738
+ }
1739
+ return true;
1740
+ }
1741
+
1742
+ ${ACCNAME_HELPERS_SOURCE}
1743
+
1744
+ function headingLevel(el) {
1745
+ var m = /^H([1-6])$/.exec(el.tagName);
1746
+ return m ? m[1] : null;
1747
+ }
1748
+
1749
+ function currentValue(el) {
1750
+ var tag = el.tagName;
1751
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") {
1752
+ return el.value;
1753
+ }
1754
+ if (el.isContentEditable) return textOf(el);
1755
+ return undefined;
1756
+ }
1757
+
1758
+ function isChecked(el) {
1759
+ var tag = el.tagName;
1760
+ if (tag === "INPUT") {
1761
+ var type = (el.getAttribute("type") || "").toLowerCase();
1762
+ if (type === "checkbox" || type === "radio") return !!el.checked;
1763
+ }
1764
+ var aria = el.getAttribute("aria-checked");
1765
+ if (aria === "true") return true;
1766
+ return false;
1767
+ }
1768
+
1769
+ function describeNode(el, role) {
1770
+ var contentNamed = !!CONTENT_NAMED_ROLES[role];
1771
+ var name = accessibleName(el, contentNamed);
1772
+ var extras = [];
1773
+ var value = currentValue(el);
1774
+ if (value !== undefined && value !== "") extras.push("value=" + JSON.stringify(String(value)));
1775
+ if (isChecked(el)) extras.push("checked=true");
1776
+ if (el.tagName === "OPTION" && el.selected) extras.push("selected");
1777
+ var href = el.getAttribute("href");
1778
+ if (href) extras.push("url=" + href);
1779
+ if (el.disabled || el.getAttribute("aria-disabled") === "true") extras.push("disabled");
1780
+ var level = headingLevel(el);
1781
+ if (level) extras.push("level=" + level);
1782
+ var label = name ? " " + JSON.stringify(name) : "";
1783
+ var extra = extras.length ? " [" + extras.join(" ") + "]" : "";
1784
+ return { role: role, label: label, extra: extra, name: name };
1785
+ }
1786
+
1787
+ // Traverses light DOM, open shadow roots, and same-origin iframe documents.
1788
+ // A cross-origin iframe throws on contentDocument access; caught and
1789
+ // skipped rather than aborting the whole walk, and noted in a comment
1790
+ // here rather than silently vanishing from the tree without a trace.
1791
+ function walk(root, depth) {
1792
+ var children = root.children ? Array.prototype.slice.call(root.children) : [];
1793
+ for (var i = 0; i < children.length; i++) {
1794
+ var el = children[i];
1795
+ var isSelectChild = el.tagName === "OPTION" || el.tagName === "OPTGROUP";
1796
+ if (!isVisible(el, isSelectChild)) continue;
1797
+
1798
+ var role = implicitRole(el);
1799
+ var isLandmarkOrControl = !!role;
1800
+ var described = null;
1801
+ if (isLandmarkOrControl) {
1802
+ described = describeNode(el, role);
1803
+ }
1804
+
1805
+ var hasContent = described && (described.name || described.extra);
1806
+ var isStructural = isLandmarkOrControl && (hasContent || isInteractiveRole(role) || isLandmarkRole(role));
1807
+
1808
+ // Role-less visible leaf text (measured vs Chrome's take_snapshot,
1809
+ // which keeps a StaticText under a generic wrapper for this case,
1810
+ // e.g. a plain status <div>). Only a leaf (no element children, so
1811
+ // its text is not already captured by a nested control/label).
1812
+ var hasElementChildren = !!(el.children && el.children.length > 0);
1813
+ var leafName = !isStructural && !hasElementChildren ? truncate(textOf(el)) : "";
1814
+ var isLeafText = !!leafName;
1815
+
1816
+ var nextDepth = depth;
1817
+ if (isStructural || isLeafText) {
1818
+ var stamp = stampOf(el);
1819
+ var indent = new Array(depth + 1).join(" ");
1820
+ var lineTail = isStructural
1821
+ ? described.role + described.label + described.extra
1822
+ : "text " + JSON.stringify(leafName);
1823
+ lines.push(indent + "[" + stamp + "] " + lineTail);
1824
+ nodeCount += 1;
1825
+ nextDepth = depth + 1;
1826
+ }
1827
+
1828
+ if (el.shadowRoot) {
1829
+ walk(el.shadowRoot, nextDepth);
1830
+ } else if (el.tagName === "IFRAME") {
1831
+ try {
1832
+ var doc = el.contentDocument;
1833
+ if (doc && doc.body) walk(doc.body, nextDepth);
1834
+ } catch (e) {
1835
+ // cross-origin iframe: intentionally skipped, not silently merged
1836
+ // into the parent tree as though it were empty.
1837
+ }
1838
+ } else {
1839
+ walk(el, nextDepth);
1840
+ }
1841
+ }
1842
+ }
1843
+
1844
+ function isInteractiveRole(role) {
1845
+ return (
1846
+ role === "button" ||
1847
+ role === "link" ||
1848
+ role === "textbox" ||
1849
+ role === "searchbox" ||
1850
+ role === "checkbox" ||
1851
+ role === "radio" ||
1852
+ role === "combobox" ||
1853
+ role === "listbox" ||
1854
+ role === "option" ||
1855
+ role === "slider" ||
1856
+ role === "spinbutton" ||
1857
+ role === "progressbar" ||
1858
+ role === "meter"
1859
+ );
1860
+ }
1861
+
1862
+ function isLandmarkRole(role) {
1863
+ return (
1864
+ role === "navigation" ||
1865
+ role === "main" ||
1866
+ role === "form" ||
1867
+ role === "dialog" ||
1868
+ role === "region" ||
1869
+ role === "heading" ||
1870
+ role === "list" ||
1871
+ role === "listitem" ||
1872
+ role === "table" ||
1873
+ role === "row" ||
1874
+ role === "cell" ||
1875
+ role === "columnheader" ||
1876
+ role === "img"
1877
+ );
1878
+ }
1879
+
1880
+ walk(document.body, 0);
1881
+ return { snapshot: lines.join("\\n"), nodeCount: nodeCount };
1882
+ }`;
1883
+ }
1884
+ var STAMP_ATTR = "data-cdp-uid", ACCNAME_HELPERS_SOURCE = `
1885
+ function truncate(s) {
1886
+ s = s.trim().replace(/\\s+/g, " ");
1887
+ if (s.length > MAX_NAME_LENGTH) return s.slice(0, MAX_NAME_LENGTH - 1) + "\\u2026";
1888
+ return s;
1889
+ }
1890
+
1891
+ function textOf(el) {
1892
+ return el.textContent || "";
1893
+ }
1894
+
1895
+ function idRefsText(doc, ids) {
1896
+ var parts = [];
1897
+ var list = ids.trim().split(/\\s+/);
1898
+ for (var i = 0; i < list.length; i++) {
1899
+ var ref = doc.getElementById(list[i]);
1900
+ if (ref) parts.push(textOf(ref));
1901
+ }
1902
+ return parts.join(" ").trim();
1903
+ }
1904
+
1905
+ // Text of a <label>, minus any nested form control's own content: a
1906
+ // label that WRAPS its control ("<label>Color <select>...</select></label>")
1907
+ // would otherwise include every option's text in the control's own name.
1908
+ function labelOwnText(label) {
1909
+ var clone = label.cloneNode(true);
1910
+ var controls = clone.querySelectorAll("input, select, textarea, button");
1911
+ for (var i = 0; i < controls.length; i++) {
1912
+ controls[i].parentNode.removeChild(controls[i]);
1913
+ }
1914
+ return textOf(clone);
1915
+ }
1916
+
1917
+ // Guard: without this, an <option> inside a labelled <select> would
1918
+ // inherit the select's own label via closest("label"), not its text.
1919
+ var LABELABLE_TAGS = { INPUT: 1, TEXTAREA: 1, SELECT: 1, BUTTON: 1, METER: 1, OUTPUT: 1, PROGRESS: 1 };
1920
+
1921
+ function nativeLabelText(el) {
1922
+ if (!LABELABLE_TAGS[el.tagName]) return "";
1923
+ var doc = el.ownerDocument;
1924
+ if (el.id) {
1925
+ var forLabel = doc.querySelector('label[for="' + el.id + '"]');
1926
+ if (forLabel) return labelOwnText(forLabel);
1927
+ }
1928
+ var ancestor = el.closest ? el.closest("label") : null;
1929
+ if (ancestor) return labelOwnText(ancestor);
1930
+ return "";
1931
+ }
1932
+
1933
+ // Reduced accname: aria-labelledby, then aria-label, then native label,
1934
+ // then alt/title/placeholder, then trimmed own text for content-named
1935
+ // elements. Not the full W3C accname algorithm (no recursive traversal
1936
+ // rules for nested presentational content) but covers the common cases.
1937
+ function accessibleName(el, contentNamed) {
1938
+ var doc = el.ownerDocument;
1939
+ var labelledby = el.getAttribute("aria-labelledby");
1940
+ if (labelledby) {
1941
+ var viaIds = idRefsText(doc, labelledby);
1942
+ if (viaIds) return truncate(viaIds);
1943
+ }
1944
+ var ariaLabel = el.getAttribute("aria-label");
1945
+ if (ariaLabel && ariaLabel.trim()) return truncate(ariaLabel);
1946
+ var native = nativeLabelText(el);
1947
+ if (native && native.trim()) return truncate(native);
1948
+ var alt = el.getAttribute("alt");
1949
+ if (alt && alt.trim()) return truncate(alt);
1950
+ var title = el.getAttribute("title");
1951
+ if (title && title.trim()) return truncate(title);
1952
+ var placeholder = el.getAttribute("placeholder");
1953
+ if (placeholder && placeholder.trim()) return truncate(placeholder);
1954
+ if (contentNamed) {
1955
+ var text = textOf(el);
1956
+ if (text && text.trim()) return truncate(text);
1957
+ }
1958
+ return "";
1959
+ }
1960
+
1961
+ var IMPLICIT_ROLE_BY_TAG = {
1962
+ A: "link", BUTTON: "button", NAV: "navigation", MAIN: "main", FORM: "form", DIALOG: "dialog",
1963
+ UL: "list", OL: "list", LI: "listitem", TABLE: "table", TR: "row", TD: "cell", TH: "columnheader",
1964
+ SELECT: "combobox", OPTION: "option", TEXTAREA: "textbox", IMG: "img",
1965
+ H1: "heading", H2: "heading", H3: "heading", H4: "heading", H5: "heading", H6: "heading",
1966
+ PROGRESS: "progressbar", METER: "meter"
1967
+ };
1968
+
1969
+ var INPUT_TYPE_ROLE = {
1970
+ button: "button", submit: "button", reset: "button", checkbox: "checkbox", radio: "radio",
1971
+ range: "slider", number: "spinbutton", search: "searchbox", email: "textbox", tel: "textbox",
1972
+ url: "textbox", password: "textbox", text: "textbox", image: "button"
1973
+ };
1974
+
1975
+ var CONTENT_NAMED_ROLES = {
1976
+ button: true, link: true, heading: true, option: true, cell: true,
1977
+ columnheader: true, listitem: true, menuitem: true, tab: true
1978
+ };
1979
+
1980
+ function implicitRole(el) {
1981
+ var explicit = el.getAttribute("role");
1982
+ if (explicit) return explicit;
1983
+ var tag = el.tagName;
1984
+ if (tag === "INPUT") {
1985
+ var type = (el.getAttribute("type") || "text").toLowerCase();
1986
+ return INPUT_TYPE_ROLE[type] || "textbox";
1987
+ }
1988
+ if (tag === "A" && !el.getAttribute("href")) return "";
1989
+ if (Object.prototype.hasOwnProperty.call(IMPLICIT_ROLE_BY_TAG, tag)) {
1990
+ return IMPLICIT_ROLE_BY_TAG[tag];
1991
+ }
1992
+ // Deliberate divergence: Chrome's real AX tree says "generic" here,
1993
+ // but "textbox" is the useful signal an agent needs. Chrome is out of
1994
+ // step, do not "fix" this toward parity.
1995
+ if (el.isContentEditable) return "textbox";
1996
+ return "";
1997
+ }
1998
+ `, MAX_NAME_LENGTH = 120;
1999
+
1448
2000
  // src/cdp/driver.ts
1449
2001
  init_client();
2002
+ init_session();
1450
2003
  init_leases();
1451
2004
  init_endpoints();
1452
2005
  init_activity();
@@ -2534,9 +3087,17 @@ function beaconKey(targetId) {
2534
3087
  const backend = chromeLeaseBackend(currentEndpoint());
2535
3088
  return backend === "chrome" ? targetId : `${backend}\x00${targetId}`;
2536
3089
  }
2537
- async function targetWsUrl(targetId) {
3090
+ async function openTargetConn(targetId, opts = {}) {
2538
3091
  const hit = (await listTargets()).find((t) => t.id === targetId);
2539
- return hit?.webSocketDebuggerUrl;
3092
+ if (!hit)
3093
+ return;
3094
+ if (!hit.webSocketDebuggerUrl)
3095
+ return openSession(targetId, opts).catch(() => {
3096
+ return;
3097
+ });
3098
+ return new CdpConnection(hit.webSocketDebuggerUrl, opts).connect().catch(() => {
3099
+ return;
3100
+ });
2540
3101
  }
2541
3102
  async function readBeaconOver(conn) {
2542
3103
  try {
@@ -2661,12 +3222,7 @@ class CdpBrowserDriver {
2661
3222
  return true;
2662
3223
  beaconSessions.drop(key);
2663
3224
  }
2664
- const wsUrl = await targetWsUrl(targetId).catch(() => {
2665
- return;
2666
- });
2667
- if (!wsUrl)
2668
- return false;
2669
- const conn = await new CdpConnection(wsUrl).connect().catch(() => {
3225
+ const conn = await openTargetConn(targetId).catch(() => {
2670
3226
  return;
2671
3227
  });
2672
3228
  if (!conn)
@@ -2691,12 +3247,7 @@ class CdpBrowserDriver {
2691
3247
  return value;
2692
3248
  beaconSessions.drop(key);
2693
3249
  }
2694
- const wsUrl = await targetWsUrl(targetId).catch(() => {
2695
- return;
2696
- });
2697
- if (!wsUrl)
2698
- return null;
2699
- const conn = await new CdpConnection(wsUrl).connect().catch(() => {
3250
+ const conn = await openTargetConn(targetId).catch(() => {
2700
3251
  return;
2701
3252
  });
2702
3253
  if (!conn)
@@ -2711,17 +3262,11 @@ class CdpBrowserDriver {
2711
3262
  const held = beaconSessions.get(beaconKey(targetId));
2712
3263
  if (held)
2713
3264
  return probeOver(held, timeoutMs);
2714
- const wsUrl = await targetWsUrl(targetId).catch(() => {
3265
+ const conn = await openTargetConn(targetId, { timeoutMs }).catch(() => {
2715
3266
  return;
2716
3267
  });
2717
- if (!wsUrl)
2718
- return { responsive: false, beaconTs: null };
2719
- const conn = new CdpConnection(wsUrl, { timeoutMs });
2720
- try {
2721
- await conn.connect();
2722
- } catch {
3268
+ if (!conn)
2723
3269
  return { responsive: false, beaconTs: null };
2724
- }
2725
3270
  try {
2726
3271
  return await probeOver(conn, timeoutMs);
2727
3272
  } finally {
@@ -2797,7 +3342,7 @@ async function reapStaleAgentTabs(driver, backend) {
2797
3342
  // src/shared-tools.ts
2798
3343
  init_driver();
2799
3344
  import { mkdir as mkdir5, writeFile as writeFile4 } from "node:fs/promises";
2800
- import { dirname as dirname2, join as join4 } from "node:path";
3345
+ import { dirname as dirname2, join as join5 } from "node:path";
2801
3346
 
2802
3347
  // src/png.ts
2803
3348
  import { once } from "node:events";
@@ -3502,7 +4047,7 @@ async function closePage(driver, args) {
3502
4047
  }
3503
4048
  async function writeSelectedFile(id) {
3504
4049
  await mkdir5(STATE_DIR, { recursive: true });
3505
- await writeFile4(join4(STATE_DIR, "selected"), id, "utf8");
4050
+ await writeFile4(join5(STATE_DIR, "selected"), id, "utf8");
3506
4051
  }
3507
4052
  async function selectPage(driver, args) {
3508
4053
  if (args.target === undefined || args.target === "")
@@ -3566,7 +4111,7 @@ function serializeForSink(value) {
3566
4111
  return json ?? "null";
3567
4112
  }
3568
4113
  async function writeJsonSink(savePath, value) {
3569
- const path = savePath.startsWith("/") ? savePath : join4(ARTIFACT_DIR, savePath);
4114
+ const path = savePath.startsWith("/") ? savePath : join5(ARTIFACT_DIR, savePath);
3570
4115
  await mkdir5(dirname2(path), { recursive: true });
3571
4116
  const json = serializeForSink(value);
3572
4117
  await writeFile4(path, json, "utf8");
@@ -3710,10 +4255,45 @@ async function takeSnapshot(driver, args = {}) {
3710
4255
  `), target: target3(page.info), nodeCount: nodes.length };
3711
4256
  });
3712
4257
  }
4258
+ function describeElementSource() {
4259
+ return `function() {
4260
+ var MAX_NAME_LENGTH = ${MAX_NAME_LENGTH};
4261
+ ${ACCNAME_HELPERS_SOURCE}
4262
+ var el = this;
4263
+ if (!el || el.nodeType !== 1) return null;
4264
+ var role = implicitRole(el);
4265
+ var name = accessibleName(el, !!CONTENT_NAMED_ROLES[role]);
4266
+ if (!name) name = truncate(el.innerText || el.textContent || "");
4267
+ return (role || el.tagName.toLowerCase()) + (name ? " " + JSON.stringify(name) : "");
4268
+ }`;
4269
+ }
4270
+ var DESCRIBE_TIMEOUT_MS = 2000;
4271
+ async function describeElement(page, loc) {
4272
+ let timer;
4273
+ try {
4274
+ const timeout = new Promise((r) => {
4275
+ timer = setTimeout(() => r(undefined), DESCRIBE_TIMEOUT_MS);
4276
+ });
4277
+ const desc = await Promise.race([page.callOnElement(loc, describeElementSource()), timeout]);
4278
+ return typeof desc === "string" && desc.length > 0 ? desc : undefined;
4279
+ } catch {
4280
+ return;
4281
+ } finally {
4282
+ clearTimeout(timer);
4283
+ }
4284
+ }
4285
+ function isElementLocator(d) {
4286
+ return !("x" in d) && !("dx" in d);
4287
+ }
4288
+ function elementField(element) {
4289
+ return element === undefined ? {} : { element };
4290
+ }
3713
4291
  async function click(driver, args) {
4292
+ const loc = locatorOf(args);
3714
4293
  return withPage2(driver, args.target, async (page) => {
3715
- const { x, y } = await page.click(locatorOf(args), { button: args.button ?? "left", clickCount: args.clickCount ?? 1, modifiers: args.modifiers });
3716
- return { clicked: true, x, y };
4294
+ const element = await describeElement(page, loc);
4295
+ const { x, y } = await page.click(loc, { button: args.button ?? "left", clickCount: args.clickCount ?? 1, modifiers: args.modifiers });
4296
+ return { clicked: true, ...elementField(element), x, y };
3717
4297
  });
3718
4298
  }
3719
4299
  function resolveScrollAnchor(args) {
@@ -3749,9 +4329,11 @@ async function scroll(driver, args) {
3749
4329
  });
3750
4330
  }
3751
4331
  async function hover(driver, args) {
4332
+ const loc = locatorOf(args);
3752
4333
  return withPage2(driver, args.target, async (page) => {
3753
- const { x, y } = await page.hover(locatorOf(args));
3754
- return { hovered: true, x, y };
4334
+ const element = await describeElement(page, loc);
4335
+ const { x, y } = await page.hover(loc);
4336
+ return { hovered: true, ...elementField(element), x, y };
3755
4337
  });
3756
4338
  }
3757
4339
  function resolveDragTo(to) {
@@ -3817,16 +4399,29 @@ async function drag(driver, args) {
3817
4399
  const steps = resolveDragSteps(args.steps);
3818
4400
  const mode = resolveDragMode(args.mode, driver.capabilities);
3819
4401
  return withPage2(driver, args.target, async (page) => {
3820
- const { from, to } = await page.drag(locatorOf(args.from), destination, { mode, steps });
3821
- return { dragged: true, mode, steps, from, to };
4402
+ const fromLoc = locatorOf(args.from);
4403
+ const element = await describeElement(page, fromLoc);
4404
+ const targetElement = isElementLocator(destination) ? await describeElement(page, destination) : undefined;
4405
+ const { from, to } = await page.drag(fromLoc, destination, { mode, steps });
4406
+ return {
4407
+ dragged: true,
4408
+ ...elementField(element),
4409
+ ...targetElement === undefined ? {} : { target_element: targetElement },
4410
+ mode,
4411
+ steps,
4412
+ from,
4413
+ to
4414
+ };
3822
4415
  });
3823
4416
  }
3824
4417
  async function fill(driver, args) {
3825
4418
  if (typeof args.value !== "string")
3826
4419
  throw new SharedToolError("fill requires a string { value }");
4420
+ const loc = locatorOf(args);
3827
4421
  return withPage2(driver, args.target, async (page) => {
3828
- await page.setValue(locatorOf(args), args.value);
3829
- return { filled: true, value: args.value };
4422
+ const element = await describeElement(page, loc);
4423
+ await page.setValue(loc, args.value);
4424
+ return { filled: true, ...elementField(element), value: args.value };
3830
4425
  });
3831
4426
  }
3832
4427
  async function fillForm(driver, args) {
@@ -3834,21 +4429,26 @@ async function fillForm(driver, args) {
3834
4429
  throw new SharedToolError("fill_form requires a non-empty { fields } array");
3835
4430
  return withPage2(driver, args.target, async (page) => {
3836
4431
  let filled = 0;
4432
+ const elements = [];
3837
4433
  for (const f of args.fields) {
3838
4434
  if (typeof f.value !== "string")
3839
4435
  throw new SharedToolError("each fill_form field requires a string value");
3840
- await page.setValue(locatorOf(f), f.value);
4436
+ const loc = locatorOf(f);
4437
+ elements.push(await describeElement(page, loc) ?? null);
4438
+ await page.setValue(loc, f.value);
3841
4439
  filled++;
3842
4440
  }
3843
- return { filled, fields: args.fields.length };
4441
+ return { filled, fields: args.fields.length, elements };
3844
4442
  });
3845
4443
  }
3846
4444
  async function typeText(driver, args) {
3847
4445
  if (typeof args.text !== "string")
3848
4446
  throw new SharedToolError("type_text requires a string { text }");
4447
+ const loc = locatorOf(args);
3849
4448
  return withPage2(driver, args.target, async (page) => {
3850
- await page.typeText(locatorOf(args), args.text);
3851
- return { typed: true, text: args.text };
4449
+ const element = await describeElement(page, loc);
4450
+ await page.typeText(loc, args.text);
4451
+ return { typed: true, ...elementField(element), text: args.text };
3852
4452
  });
3853
4453
  }
3854
4454
  async function pressKey(driver, args) {
@@ -3866,8 +4466,10 @@ async function uploadFile(driver, args) {
3866
4466
  throw new SharedToolError("upload_file requires { files } as a non-empty path or array of paths");
3867
4467
  }
3868
4468
  return withPage2(driver, args.target, async (page) => {
3869
- await page.setFiles(locatorOf(args), files);
3870
- return { uploaded: files };
4469
+ const loc = locatorOf(args);
4470
+ const element = await describeElement(page, loc);
4471
+ await page.setFiles(loc, files);
4472
+ return { uploaded: files, ...elementField(element) };
3871
4473
  });
3872
4474
  }
3873
4475
  function stamp() {
@@ -3981,7 +4583,7 @@ async function takeScreenshot(driver, args = {}) {
3981
4583
  return withPage2(driver, args.target, async (page) => {
3982
4584
  const clip = args.uid !== undefined || args.selector ? locatorOf(args) : undefined;
3983
4585
  const ext = format === "jpeg" ? "jpg" : "png";
3984
- const path = args.savePath ?? join4(ARTIFACT_DIR, `screenshot-${page.info.id.slice(0, 8)}-${stamp()}.${ext}`);
4586
+ const path = args.savePath ?? join5(ARTIFACT_DIR, `screenshot-${page.info.id.slice(0, 8)}-${stamp()}.${ext}`);
3985
4587
  const stitch = async (banded) => {
3986
4588
  if (format !== "png")
3987
4589
  throw tiledCaptureRefusal("format", banded);
@@ -4206,7 +4808,7 @@ var LEASE_TOOLS = {
4206
4808
 
4207
4809
  // src/tools/console.ts
4208
4810
  init_client();
4209
- import { readFile as readFile4 } from "node:fs/promises";
4811
+ import { readFile as readFile5 } from "node:fs/promises";
4210
4812
 
4211
4813
  // src/tools/recorder.ts
4212
4814
  init_client();
@@ -4409,7 +5011,7 @@ function lineToEntry(line, index) {
4409
5011
  async function readConsoleEntries(file) {
4410
5012
  let raw;
4411
5013
  try {
4412
- raw = await readFile4(file, "utf8");
5014
+ raw = await readFile5(file, "utf8");
4413
5015
  } catch {
4414
5016
  return [];
4415
5017
  }
@@ -4467,7 +5069,7 @@ async function getConsoleMessage(args = {}) {
4467
5069
 
4468
5070
  // src/tools/network.ts
4469
5071
  init_client();
4470
- import { readFile as readFile5 } from "node:fs/promises";
5072
+ import { readFile as readFile6 } from "node:fs/promises";
4471
5073
  var DEFAULT_CAPTURE_MS2 = 2500;
4472
5074
  function asHeaders(v) {
4473
5075
  if (!v || typeof v !== "object")
@@ -4534,7 +5136,7 @@ function correlate(lines) {
4534
5136
  async function readNetworkRequests(file) {
4535
5137
  let raw;
4536
5138
  try {
4537
- raw = await readFile5(file, "utf8");
5139
+ raw = await readFile6(file, "utf8");
4538
5140
  } catch {
4539
5141
  return [];
4540
5142
  }
@@ -4619,8 +5221,8 @@ async function getNetworkRequest(args = {}) {
4619
5221
 
4620
5222
  // src/tools/performance.ts
4621
5223
  init_client();
4622
- import { mkdir as mkdir7, readFile as readFile6, writeFile as writeFile6, stat, unlink as unlink4 } from "node:fs/promises";
4623
- import { join as join5 } from "node:path";
5224
+ import { mkdir as mkdir7, readFile as readFile7, writeFile as writeFile6, stat, unlink as unlink4 } from "node:fs/promises";
5225
+ import { join as join6 } from "node:path";
4624
5226
  var ARTIFACT_DIR2 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
4625
5227
  var STATE_DIR2 = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
4626
5228
  var DEFAULT_CATEGORIES = [
@@ -4638,7 +5240,7 @@ function shortId(id) {
4638
5240
  return id.slice(0, 8);
4639
5241
  }
4640
5242
  function stateFilePath() {
4641
- return join5(STATE_DIR2, "trace-state.json");
5243
+ return join6(STATE_DIR2, "trace-state.json");
4642
5244
  }
4643
5245
  function bufferTraceData(conn, sink) {
4644
5246
  return conn.on("Tracing.dataCollected", (params) => {
@@ -4661,7 +5263,7 @@ async function endTrace(conn, sink, timeoutMs = 30000) {
4661
5263
  }
4662
5264
  async function writeTrace(events, targetId) {
4663
5265
  await mkdir7(ARTIFACT_DIR2, { recursive: true });
4664
- const path = join5(ARTIFACT_DIR2, `trace-${shortId(targetId)}-${stamp2()}.json`);
5266
+ const path = join6(ARTIFACT_DIR2, `trace-${shortId(targetId)}-${stamp2()}.json`);
4665
5267
  const body = JSON.stringify({ traceEvents: events, metadata: { source: "cdp-toolkit" } });
4666
5268
  await writeFile6(path, body, "utf8");
4667
5269
  const { size } = await stat(path);
@@ -4704,7 +5306,7 @@ async function performanceStopTrace(args = {}) {
4704
5306
  if (!entry) {
4705
5307
  let hint = "";
4706
5308
  try {
4707
- const raw = await readFile6(stateFilePath(), "utf8");
5309
+ const raw = await readFile7(stateFilePath(), "utf8");
4708
5310
  const state = JSON.parse(raw);
4709
5311
  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)`;
4710
5312
  } catch {}
@@ -4834,7 +5436,7 @@ async function performanceAnalyzeInsight(args = {}) {
4834
5436
  }
4835
5437
  let raw;
4836
5438
  try {
4837
- raw = await readFile6(args.tracePath, "utf8");
5439
+ raw = await readFile7(args.tracePath, "utf8");
4838
5440
  } catch (err) {
4839
5441
  throw new CdpError(`cannot read trace file '${args.tracePath}': ${err.message}`);
4840
5442
  }
@@ -4854,7 +5456,7 @@ async function performanceAnalyzeInsight(args = {}) {
4854
5456
  init_client();
4855
5457
  import { spawn } from "node:child_process";
4856
5458
  import { mkdir as mkdir8, rm as rm2, stat as stat2, writeFile as writeFile7 } from "node:fs/promises";
4857
- import { join as join6 } from "node:path";
5459
+ import { join as join7 } from "node:path";
4858
5460
  var ARTIFACT_DIR3 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
4859
5461
  var FFMPEG_BIN = process.env.CDP_FFMPEG ?? "ffmpeg";
4860
5462
  function frameDurationsMs(ledger, stopWallclockMs) {
@@ -4970,6 +5572,22 @@ function selectEncoder(encodersOutput) {
4970
5572
  }
4971
5573
  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).");
4972
5574
  }
5575
+ function supportsFpsMode(versionOutput) {
5576
+ const m = /ffmpeg version n?(\d+)\.(\d+)/.exec(versionOutput);
5577
+ if (!m)
5578
+ return /ffmpeg version N-/.test(versionOutput) ? true : undefined;
5579
+ const major = Number(m[1]);
5580
+ const minor = Number(m[2]);
5581
+ return major > 5 || major === 5 && minor >= 1;
5582
+ }
5583
+ function chooseFpsMode(versionOutput, helpOutput) {
5584
+ const byVersion = versionOutput === undefined ? undefined : supportsFpsMode(versionOutput);
5585
+ if (byVersion !== undefined)
5586
+ return byVersion;
5587
+ if (helpOutput !== undefined && /-vsync\b|-fps_mode\b/.test(helpOutput))
5588
+ return /-fps_mode\b/.test(helpOutput);
5589
+ return true;
5590
+ }
4973
5591
  function buildFfmpegArgs(manifestPath, outPath, choice) {
4974
5592
  return [
4975
5593
  "-hide_banner",
@@ -4982,8 +5600,7 @@ function buildFfmpegArgs(manifestPath, outPath, choice) {
4982
5600
  "0",
4983
5601
  "-i",
4984
5602
  manifestPath,
4985
- "-vsync",
4986
- "vfr",
5603
+ ...choice.fpsMode ? ["-fps_mode", "vfr"] : ["-vsync", "vfr"],
4987
5604
  "-vf",
4988
5605
  "scale=trunc(iw/2)*2:trunc(ih/2)*2",
4989
5606
  "-c:v",
@@ -5025,8 +5642,19 @@ async function probeEncoder() {
5025
5642
  }
5026
5643
  if (res.code !== 0)
5027
5644
  throw new CdpError(`${FFMPEG_MISSING} ('-encoders' exited ${res.code}: ${res.stderr.trim().slice(0, 300)})`);
5028
- return selectEncoder(`${res.stdout}
5645
+ const choice = selectEncoder(`${res.stdout}
5029
5646
  ${res.stderr}`);
5647
+ const output = async (args) => {
5648
+ const r = await run(FFMPEG_BIN, args).catch(() => {
5649
+ return;
5650
+ });
5651
+ return r && r.code === 0 ? `${r.stdout}
5652
+ ${r.stderr}` : undefined;
5653
+ };
5654
+ const version = await output(["-version"]);
5655
+ const byVersion = version === undefined ? undefined : supportsFpsMode(version);
5656
+ const help = byVersion === undefined ? await output(["-hide_banner", "-h", "full"]) : undefined;
5657
+ return { ...choice, fpsMode: chooseFpsMode(version, help) };
5030
5658
  })();
5031
5659
  encoderProbe.catch(() => {
5032
5660
  encoderProbe = undefined;
@@ -5075,7 +5703,7 @@ async function startScreenRecording(args = {}) {
5075
5703
  conn.close();
5076
5704
  throw err;
5077
5705
  }
5078
- const spoolDir = join6(ARTIFACT_DIR3, `screencast-${shortId2(target.id)}-${stamp3()}`);
5706
+ const spoolDir = join7(ARTIFACT_DIR3, `screencast-${shortId2(target.id)}-${stamp3()}`);
5079
5707
  try {
5080
5708
  await mkdir8(spoolDir, { recursive: true });
5081
5709
  } catch (err) {
@@ -5118,7 +5746,7 @@ async function startScreenRecording(args = {}) {
5118
5746
  seq += 1;
5119
5747
  const file = `frame-${String(seq).padStart(6, "0")}.${ext}`;
5120
5748
  rec.ledger.push({ file, timestamp, width: size.width, height: size.height });
5121
- rec.writes = rec.writes.then(() => writeFile7(join6(spoolDir, file), buf)).catch(() => {
5749
+ rec.writes = rec.writes.then(() => writeFile7(join7(spoolDir, file), buf)).catch(() => {
5122
5750
  rec.dropped += 1;
5123
5751
  rec.unwritten.add(file);
5124
5752
  });
@@ -5182,9 +5810,9 @@ async function stopScreenRecording(args = {}) {
5182
5810
  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.`);
5183
5811
  }
5184
5812
  await mkdir8(ARTIFACT_DIR3, { recursive: true });
5185
- const outPath = args.savePath ?? join6(ARTIFACT_DIR3, `screen-recording-${shortId2(rec.target.id)}-${stamp3()}.mp4`);
5813
+ const outPath = args.savePath ?? join7(ARTIFACT_DIR3, `screen-recording-${shortId2(rec.target.id)}-${stamp3()}.mp4`);
5186
5814
  const frames = coalesceToConcatGrid(ledger, stoppedAt);
5187
- const manifestPath = join6(rec.spoolDir, "frames.ffconcat");
5815
+ const manifestPath = join7(rec.spoolDir, "frames.ffconcat");
5188
5816
  await writeFile7(manifestPath, buildConcatManifest(frames), "utf8");
5189
5817
  const durationMs = frames.reduce((total, f) => total + f.durationMs, 0);
5190
5818
  const { width, height } = evenDimensions(ledger[0].width, ledger[0].height);
@@ -5218,7 +5846,7 @@ ffmpeg said: ${res.stderr.trim().slice(0, 800)}`);
5218
5846
  // src/tools/heap.ts
5219
5847
  init_client();
5220
5848
  import { mkdir as mkdir9, writeFile as writeFile8 } from "node:fs/promises";
5221
- import { join as join7 } from "node:path";
5849
+ import { join as join8 } from "node:path";
5222
5850
  var ARTIFACT_DIR4 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
5223
5851
  function stamp4(targetId) {
5224
5852
  const short = targetId.slice(0, 8);
@@ -5244,7 +5872,7 @@ async function takeHeapsnapshot(args = {}) {
5244
5872
  throw new Error("HeapProfiler.takeHeapSnapshot produced no chunks");
5245
5873
  }
5246
5874
  await mkdir9(ARTIFACT_DIR4, { recursive: true });
5247
- const path = args.savePath ? args.savePath.startsWith("/") ? args.savePath : join7(ARTIFACT_DIR4, args.savePath) : join7(ARTIFACT_DIR4, `take_heapsnapshot-${stamp4(target.id)}.heapsnapshot`);
5875
+ const path = args.savePath ? args.savePath.startsWith("/") ? args.savePath : join8(ARTIFACT_DIR4, args.savePath) : join8(ARTIFACT_DIR4, `take_heapsnapshot-${stamp4(target.id)}.heapsnapshot`);
5248
5876
  await writeFile8(path, snapshot, "utf8");
5249
5877
  const bytes = Buffer.byteLength(snapshot, "utf8");
5250
5878
  return {
@@ -5260,7 +5888,7 @@ async function takeHeapsnapshot(args = {}) {
5260
5888
  init_client();
5261
5889
  init_endpoints();
5262
5890
  import { spawn as spawn2 } from "node:child_process";
5263
- import { mkdir as mkdir10, readFile as readFile7, stat as stat3 } from "node:fs/promises";
5891
+ import { mkdir as mkdir10, readFile as readFile8, stat as stat3 } from "node:fs/promises";
5264
5892
  var ARTIFACT_DIR5 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
5265
5893
  function cdpPort() {
5266
5894
  const base = currentEndpoint().base;
@@ -5350,7 +5978,7 @@ async function lighthouseAudit(args) {
5350
5978
  }
5351
5979
  let raw;
5352
5980
  try {
5353
- raw = await readFile7(outPath, "utf8");
5981
+ raw = await readFile8(outPath, "utf8");
5354
5982
  } catch {
5355
5983
  raw = undefined;
5356
5984
  }
@@ -5540,15 +6168,15 @@ async function clickFocusGated(args) {
5540
6168
  // src/tools/downloads.ts
5541
6169
  init_client();
5542
6170
  import { readdir as readdir3, rename as rename2, stat as stat4 } from "node:fs/promises";
5543
- import { basename, extname, join as join9 } from "node:path";
6171
+ import { basename, extname, join as join10 } from "node:path";
5544
6172
 
5545
6173
  // src/tools/browser-session.ts
5546
6174
  init_client();
5547
6175
  init_endpoints();
5548
6176
  import { mkdir as mkdir11 } from "node:fs/promises";
5549
- import { join as join8 } from "node:path";
6177
+ import { join as join9 } from "node:path";
5550
6178
  var ARTIFACT_DIR6 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
5551
- var DOWNLOADS_DIR = join8(ARTIFACT_DIR6, "downloads");
6179
+ var DOWNLOADS_DIR = join9(ARTIFACT_DIR6, "downloads");
5552
6180
  var DOWNLOAD_BUFFER_LIMIT = 50;
5553
6181
  var sessions2 = new Map;
5554
6182
  function sessionKey() {
@@ -5715,7 +6343,7 @@ async function waitForDownload(args = {}) {
5715
6343
  const taken = new Set(await readdir3(DOWNLOADS_DIR).catch(() => []));
5716
6344
  taken.delete(basename(rec.filePath));
5717
6345
  const finalName = nextFreeName(suggestedFilename, taken);
5718
- const path = join9(DOWNLOADS_DIR, finalName);
6346
+ const path = join10(DOWNLOADS_DIR, finalName);
5719
6347
  await rename2(rec.filePath, path);
5720
6348
  const bytes = (await stat4(path)).size;
5721
6349
  return { path, suggestedFilename, bytes, ...rec.url ? { url: rec.url } : {}, target };
@@ -5774,7 +6402,7 @@ async function grantPermissions(args = {}) {
5774
6402
  // src/tools/extract.ts
5775
6403
  init_client();
5776
6404
  import { mkdir as mkdir12, writeFile as writeFile9 } from "node:fs/promises";
5777
- import { dirname as dirname3, join as join10 } from "node:path";
6405
+ import { dirname as dirname3, join as join11 } from "node:path";
5778
6406
  var ARTIFACT_DIR7 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
5779
6407
  var DEFAULT_BASE_URL = "http://127.0.0.1:8090/v1";
5780
6408
  var DEFAULT_MODEL = "schematron";
@@ -6175,7 +6803,7 @@ async function extractPage(driver, args) {
6175
6803
  };
6176
6804
  if (args.savePath === undefined || args.savePath === "")
6177
6805
  return result;
6178
- const path = args.savePath.startsWith("/") ? args.savePath : join10(ARTIFACT_DIR7, args.savePath);
6806
+ const path = args.savePath.startsWith("/") ? args.savePath : join11(ARTIFACT_DIR7, args.savePath);
6179
6807
  await mkdir12(dirname3(path), { recursive: true });
6180
6808
  const json = JSON.stringify(result, null, 2);
6181
6809
  await writeFile9(path, json, "utf8");