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/cli.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";
@@ -4049,6 +4288,7 @@ var init_driver2 = __esm(() => {
4049
4288
 
4050
4289
  // src/cdp/driver.ts
4051
4290
  init_client();
4291
+ init_session();
4052
4292
  init_leases();
4053
4293
  init_endpoints();
4054
4294
  init_activity();
@@ -5136,9 +5376,17 @@ function beaconKey(targetId) {
5136
5376
  const backend = chromeLeaseBackend(currentEndpoint());
5137
5377
  return backend === "chrome" ? targetId : `${backend}\x00${targetId}`;
5138
5378
  }
5139
- async function targetWsUrl(targetId) {
5379
+ async function openTargetConn(targetId, opts = {}) {
5140
5380
  const hit = (await listTargets()).find((t) => t.id === targetId);
5141
- return hit?.webSocketDebuggerUrl;
5381
+ if (!hit)
5382
+ return;
5383
+ if (!hit.webSocketDebuggerUrl)
5384
+ return openSession(targetId, opts).catch(() => {
5385
+ return;
5386
+ });
5387
+ return new CdpConnection(hit.webSocketDebuggerUrl, opts).connect().catch(() => {
5388
+ return;
5389
+ });
5142
5390
  }
5143
5391
  async function readBeaconOver(conn) {
5144
5392
  try {
@@ -5263,12 +5511,7 @@ class CdpBrowserDriver {
5263
5511
  return true;
5264
5512
  beaconSessions.drop(key);
5265
5513
  }
5266
- const wsUrl = await targetWsUrl(targetId).catch(() => {
5267
- return;
5268
- });
5269
- if (!wsUrl)
5270
- return false;
5271
- const conn = await new CdpConnection(wsUrl).connect().catch(() => {
5514
+ const conn = await openTargetConn(targetId).catch(() => {
5272
5515
  return;
5273
5516
  });
5274
5517
  if (!conn)
@@ -5293,12 +5536,7 @@ class CdpBrowserDriver {
5293
5536
  return value;
5294
5537
  beaconSessions.drop(key);
5295
5538
  }
5296
- const wsUrl = await targetWsUrl(targetId).catch(() => {
5297
- return;
5298
- });
5299
- if (!wsUrl)
5300
- return null;
5301
- const conn = await new CdpConnection(wsUrl).connect().catch(() => {
5539
+ const conn = await openTargetConn(targetId).catch(() => {
5302
5540
  return;
5303
5541
  });
5304
5542
  if (!conn)
@@ -5313,17 +5551,11 @@ class CdpBrowserDriver {
5313
5551
  const held = beaconSessions.get(beaconKey(targetId));
5314
5552
  if (held)
5315
5553
  return probeOver(held, timeoutMs);
5316
- const wsUrl = await targetWsUrl(targetId).catch(() => {
5554
+ const conn = await openTargetConn(targetId, { timeoutMs }).catch(() => {
5317
5555
  return;
5318
5556
  });
5319
- if (!wsUrl)
5320
- return { responsive: false, beaconTs: null };
5321
- const conn = new CdpConnection(wsUrl, { timeoutMs });
5322
- try {
5323
- await conn.connect();
5324
- } catch {
5557
+ if (!conn)
5325
5558
  return { responsive: false, beaconTs: null };
5326
- }
5327
5559
  try {
5328
5560
  return await probeOver(conn, timeoutMs);
5329
5561
  } finally {
@@ -5399,7 +5631,7 @@ async function reapStaleAgentTabs(driver, backend) {
5399
5631
  // src/shared-tools.ts
5400
5632
  init_driver();
5401
5633
  import { mkdir as mkdir5, writeFile as writeFile4 } from "node:fs/promises";
5402
- import { dirname as dirname2, join as join4 } from "node:path";
5634
+ import { dirname as dirname2, join as join5 } from "node:path";
5403
5635
 
5404
5636
  // src/png.ts
5405
5637
  import { once } from "node:events";
@@ -6104,7 +6336,7 @@ async function closePage(driver, args) {
6104
6336
  }
6105
6337
  async function writeSelectedFile(id) {
6106
6338
  await mkdir5(STATE_DIR, { recursive: true });
6107
- await writeFile4(join4(STATE_DIR, "selected"), id, "utf8");
6339
+ await writeFile4(join5(STATE_DIR, "selected"), id, "utf8");
6108
6340
  }
6109
6341
  async function selectPage(driver, args) {
6110
6342
  if (args.target === undefined || args.target === "")
@@ -6168,7 +6400,7 @@ function serializeForSink(value) {
6168
6400
  return json ?? "null";
6169
6401
  }
6170
6402
  async function writeJsonSink(savePath, value) {
6171
- const path = savePath.startsWith("/") ? savePath : join4(ARTIFACT_DIR, savePath);
6403
+ const path = savePath.startsWith("/") ? savePath : join5(ARTIFACT_DIR, savePath);
6172
6404
  await mkdir5(dirname2(path), { recursive: true });
6173
6405
  const json = serializeForSink(value);
6174
6406
  await writeFile4(path, json, "utf8");
@@ -6312,10 +6544,45 @@ async function takeSnapshot(driver, args = {}) {
6312
6544
  `), target: target3(page.info), nodeCount: nodes.length };
6313
6545
  });
6314
6546
  }
6547
+ function describeElementSource() {
6548
+ return `function() {
6549
+ var MAX_NAME_LENGTH = ${MAX_NAME_LENGTH};
6550
+ ${ACCNAME_HELPERS_SOURCE}
6551
+ var el = this;
6552
+ if (!el || el.nodeType !== 1) return null;
6553
+ var role = implicitRole(el);
6554
+ var name = accessibleName(el, !!CONTENT_NAMED_ROLES[role]);
6555
+ if (!name) name = truncate(el.innerText || el.textContent || "");
6556
+ return (role || el.tagName.toLowerCase()) + (name ? " " + JSON.stringify(name) : "");
6557
+ }`;
6558
+ }
6559
+ var DESCRIBE_TIMEOUT_MS = 2000;
6560
+ async function describeElement(page, loc) {
6561
+ let timer;
6562
+ try {
6563
+ const timeout = new Promise((r) => {
6564
+ timer = setTimeout(() => r(undefined), DESCRIBE_TIMEOUT_MS);
6565
+ });
6566
+ const desc = await Promise.race([page.callOnElement(loc, describeElementSource()), timeout]);
6567
+ return typeof desc === "string" && desc.length > 0 ? desc : undefined;
6568
+ } catch {
6569
+ return;
6570
+ } finally {
6571
+ clearTimeout(timer);
6572
+ }
6573
+ }
6574
+ function isElementLocator(d) {
6575
+ return !("x" in d) && !("dx" in d);
6576
+ }
6577
+ function elementField(element) {
6578
+ return element === undefined ? {} : { element };
6579
+ }
6315
6580
  async function click(driver, args) {
6581
+ const loc = locatorOf(args);
6316
6582
  return withPage2(driver, args.target, async (page) => {
6317
- const { x, y } = await page.click(locatorOf(args), { button: args.button ?? "left", clickCount: args.clickCount ?? 1, modifiers: args.modifiers });
6318
- return { clicked: true, x, y };
6583
+ const element = await describeElement(page, loc);
6584
+ const { x, y } = await page.click(loc, { button: args.button ?? "left", clickCount: args.clickCount ?? 1, modifiers: args.modifiers });
6585
+ return { clicked: true, ...elementField(element), x, y };
6319
6586
  });
6320
6587
  }
6321
6588
  function resolveScrollAnchor(args) {
@@ -6351,9 +6618,11 @@ async function scroll(driver, args) {
6351
6618
  });
6352
6619
  }
6353
6620
  async function hover(driver, args) {
6621
+ const loc = locatorOf(args);
6354
6622
  return withPage2(driver, args.target, async (page) => {
6355
- const { x, y } = await page.hover(locatorOf(args));
6356
- return { hovered: true, x, y };
6623
+ const element = await describeElement(page, loc);
6624
+ const { x, y } = await page.hover(loc);
6625
+ return { hovered: true, ...elementField(element), x, y };
6357
6626
  });
6358
6627
  }
6359
6628
  function resolveDragTo(to) {
@@ -6419,16 +6688,29 @@ async function drag(driver, args) {
6419
6688
  const steps = resolveDragSteps(args.steps);
6420
6689
  const mode = resolveDragMode(args.mode, driver.capabilities);
6421
6690
  return withPage2(driver, args.target, async (page) => {
6422
- const { from, to } = await page.drag(locatorOf(args.from), destination, { mode, steps });
6423
- return { dragged: true, mode, steps, from, to };
6691
+ const fromLoc = locatorOf(args.from);
6692
+ const element = await describeElement(page, fromLoc);
6693
+ const targetElement = isElementLocator(destination) ? await describeElement(page, destination) : undefined;
6694
+ const { from, to } = await page.drag(fromLoc, destination, { mode, steps });
6695
+ return {
6696
+ dragged: true,
6697
+ ...elementField(element),
6698
+ ...targetElement === undefined ? {} : { target_element: targetElement },
6699
+ mode,
6700
+ steps,
6701
+ from,
6702
+ to
6703
+ };
6424
6704
  });
6425
6705
  }
6426
6706
  async function fill(driver, args) {
6427
6707
  if (typeof args.value !== "string")
6428
6708
  throw new SharedToolError("fill requires a string { value }");
6709
+ const loc = locatorOf(args);
6429
6710
  return withPage2(driver, args.target, async (page) => {
6430
- await page.setValue(locatorOf(args), args.value);
6431
- return { filled: true, value: args.value };
6711
+ const element = await describeElement(page, loc);
6712
+ await page.setValue(loc, args.value);
6713
+ return { filled: true, ...elementField(element), value: args.value };
6432
6714
  });
6433
6715
  }
6434
6716
  async function fillForm(driver, args) {
@@ -6436,21 +6718,26 @@ async function fillForm(driver, args) {
6436
6718
  throw new SharedToolError("fill_form requires a non-empty { fields } array");
6437
6719
  return withPage2(driver, args.target, async (page) => {
6438
6720
  let filled = 0;
6721
+ const elements = [];
6439
6722
  for (const f of args.fields) {
6440
6723
  if (typeof f.value !== "string")
6441
6724
  throw new SharedToolError("each fill_form field requires a string value");
6442
- await page.setValue(locatorOf(f), f.value);
6725
+ const loc = locatorOf(f);
6726
+ elements.push(await describeElement(page, loc) ?? null);
6727
+ await page.setValue(loc, f.value);
6443
6728
  filled++;
6444
6729
  }
6445
- return { filled, fields: args.fields.length };
6730
+ return { filled, fields: args.fields.length, elements };
6446
6731
  });
6447
6732
  }
6448
6733
  async function typeText(driver, args) {
6449
6734
  if (typeof args.text !== "string")
6450
6735
  throw new SharedToolError("type_text requires a string { text }");
6736
+ const loc = locatorOf(args);
6451
6737
  return withPage2(driver, args.target, async (page) => {
6452
- await page.typeText(locatorOf(args), args.text);
6453
- return { typed: true, text: args.text };
6738
+ const element = await describeElement(page, loc);
6739
+ await page.typeText(loc, args.text);
6740
+ return { typed: true, ...elementField(element), text: args.text };
6454
6741
  });
6455
6742
  }
6456
6743
  async function pressKey(driver, args) {
@@ -6468,8 +6755,10 @@ async function uploadFile(driver, args) {
6468
6755
  throw new SharedToolError("upload_file requires { files } as a non-empty path or array of paths");
6469
6756
  }
6470
6757
  return withPage2(driver, args.target, async (page) => {
6471
- await page.setFiles(locatorOf(args), files);
6472
- return { uploaded: files };
6758
+ const loc = locatorOf(args);
6759
+ const element = await describeElement(page, loc);
6760
+ await page.setFiles(loc, files);
6761
+ return { uploaded: files, ...elementField(element) };
6473
6762
  });
6474
6763
  }
6475
6764
  function stamp() {
@@ -6583,7 +6872,7 @@ async function takeScreenshot(driver, args = {}) {
6583
6872
  return withPage2(driver, args.target, async (page) => {
6584
6873
  const clip = args.uid !== undefined || args.selector ? locatorOf(args) : undefined;
6585
6874
  const ext = format === "jpeg" ? "jpg" : "png";
6586
- const path = args.savePath ?? join4(ARTIFACT_DIR, `screenshot-${page.info.id.slice(0, 8)}-${stamp()}.${ext}`);
6875
+ const path = args.savePath ?? join5(ARTIFACT_DIR, `screenshot-${page.info.id.slice(0, 8)}-${stamp()}.${ext}`);
6587
6876
  const stitch = async (banded) => {
6588
6877
  if (format !== "png")
6589
6878
  throw tiledCaptureRefusal("format", banded);
@@ -6808,7 +7097,7 @@ var LEASE_TOOLS = {
6808
7097
 
6809
7098
  // src/tools/console.ts
6810
7099
  init_client();
6811
- import { readFile as readFile4 } from "node:fs/promises";
7100
+ import { readFile as readFile5 } from "node:fs/promises";
6812
7101
 
6813
7102
  // src/tools/recorder.ts
6814
7103
  init_client();
@@ -7011,7 +7300,7 @@ function lineToEntry(line, index) {
7011
7300
  async function readConsoleEntries(file) {
7012
7301
  let raw;
7013
7302
  try {
7014
- raw = await readFile4(file, "utf8");
7303
+ raw = await readFile5(file, "utf8");
7015
7304
  } catch {
7016
7305
  return [];
7017
7306
  }
@@ -7069,7 +7358,7 @@ async function getConsoleMessage(args = {}) {
7069
7358
 
7070
7359
  // src/tools/network.ts
7071
7360
  init_client();
7072
- import { readFile as readFile5 } from "node:fs/promises";
7361
+ import { readFile as readFile6 } from "node:fs/promises";
7073
7362
  var DEFAULT_CAPTURE_MS2 = 2500;
7074
7363
  function asHeaders(v) {
7075
7364
  if (!v || typeof v !== "object")
@@ -7136,7 +7425,7 @@ function correlate(lines) {
7136
7425
  async function readNetworkRequests(file) {
7137
7426
  let raw;
7138
7427
  try {
7139
- raw = await readFile5(file, "utf8");
7428
+ raw = await readFile6(file, "utf8");
7140
7429
  } catch {
7141
7430
  return [];
7142
7431
  }
@@ -7221,8 +7510,8 @@ async function getNetworkRequest(args = {}) {
7221
7510
 
7222
7511
  // src/tools/performance.ts
7223
7512
  init_client();
7224
- import { mkdir as mkdir7, readFile as readFile6, writeFile as writeFile6, stat, unlink as unlink4 } from "node:fs/promises";
7225
- import { join as join5 } from "node:path";
7513
+ import { mkdir as mkdir7, readFile as readFile7, writeFile as writeFile6, stat, unlink as unlink4 } from "node:fs/promises";
7514
+ import { join as join6 } from "node:path";
7226
7515
  var ARTIFACT_DIR2 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7227
7516
  var STATE_DIR2 = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
7228
7517
  var DEFAULT_CATEGORIES = [
@@ -7240,7 +7529,7 @@ function shortId(id) {
7240
7529
  return id.slice(0, 8);
7241
7530
  }
7242
7531
  function stateFilePath() {
7243
- return join5(STATE_DIR2, "trace-state.json");
7532
+ return join6(STATE_DIR2, "trace-state.json");
7244
7533
  }
7245
7534
  function bufferTraceData(conn, sink) {
7246
7535
  return conn.on("Tracing.dataCollected", (params) => {
@@ -7263,7 +7552,7 @@ async function endTrace(conn, sink, timeoutMs = 30000) {
7263
7552
  }
7264
7553
  async function writeTrace(events, targetId) {
7265
7554
  await mkdir7(ARTIFACT_DIR2, { recursive: true });
7266
- const path = join5(ARTIFACT_DIR2, `trace-${shortId(targetId)}-${stamp2()}.json`);
7555
+ const path = join6(ARTIFACT_DIR2, `trace-${shortId(targetId)}-${stamp2()}.json`);
7267
7556
  const body = JSON.stringify({ traceEvents: events, metadata: { source: "cdp-toolkit" } });
7268
7557
  await writeFile6(path, body, "utf8");
7269
7558
  const { size } = await stat(path);
@@ -7306,7 +7595,7 @@ async function performanceStopTrace(args = {}) {
7306
7595
  if (!entry) {
7307
7596
  let hint = "";
7308
7597
  try {
7309
- const raw = await readFile6(stateFilePath(), "utf8");
7598
+ const raw = await readFile7(stateFilePath(), "utf8");
7310
7599
  const state = JSON.parse(raw);
7311
7600
  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)`;
7312
7601
  } catch {}
@@ -7436,7 +7725,7 @@ async function performanceAnalyzeInsight(args = {}) {
7436
7725
  }
7437
7726
  let raw;
7438
7727
  try {
7439
- raw = await readFile6(args.tracePath, "utf8");
7728
+ raw = await readFile7(args.tracePath, "utf8");
7440
7729
  } catch (err) {
7441
7730
  throw new CdpError(`cannot read trace file '${args.tracePath}': ${err.message}`);
7442
7731
  }
@@ -7456,7 +7745,7 @@ async function performanceAnalyzeInsight(args = {}) {
7456
7745
  init_client();
7457
7746
  import { spawn } from "node:child_process";
7458
7747
  import { mkdir as mkdir8, rm as rm2, stat as stat2, writeFile as writeFile7 } from "node:fs/promises";
7459
- import { join as join6 } from "node:path";
7748
+ import { join as join7 } from "node:path";
7460
7749
  var ARTIFACT_DIR3 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7461
7750
  var FFMPEG_BIN = process.env.CDP_FFMPEG ?? "ffmpeg";
7462
7751
  function frameDurationsMs(ledger, stopWallclockMs) {
@@ -7572,6 +7861,22 @@ function selectEncoder(encodersOutput) {
7572
7861
  }
7573
7862
  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).");
7574
7863
  }
7864
+ function supportsFpsMode(versionOutput) {
7865
+ const m = /ffmpeg version n?(\d+)\.(\d+)/.exec(versionOutput);
7866
+ if (!m)
7867
+ return /ffmpeg version N-/.test(versionOutput) ? true : undefined;
7868
+ const major = Number(m[1]);
7869
+ const minor = Number(m[2]);
7870
+ return major > 5 || major === 5 && minor >= 1;
7871
+ }
7872
+ function chooseFpsMode(versionOutput, helpOutput) {
7873
+ const byVersion = versionOutput === undefined ? undefined : supportsFpsMode(versionOutput);
7874
+ if (byVersion !== undefined)
7875
+ return byVersion;
7876
+ if (helpOutput !== undefined && /-vsync\b|-fps_mode\b/.test(helpOutput))
7877
+ return /-fps_mode\b/.test(helpOutput);
7878
+ return true;
7879
+ }
7575
7880
  function buildFfmpegArgs(manifestPath, outPath, choice) {
7576
7881
  return [
7577
7882
  "-hide_banner",
@@ -7584,8 +7889,7 @@ function buildFfmpegArgs(manifestPath, outPath, choice) {
7584
7889
  "0",
7585
7890
  "-i",
7586
7891
  manifestPath,
7587
- "-vsync",
7588
- "vfr",
7892
+ ...choice.fpsMode ? ["-fps_mode", "vfr"] : ["-vsync", "vfr"],
7589
7893
  "-vf",
7590
7894
  "scale=trunc(iw/2)*2:trunc(ih/2)*2",
7591
7895
  "-c:v",
@@ -7627,8 +7931,19 @@ async function probeEncoder() {
7627
7931
  }
7628
7932
  if (res.code !== 0)
7629
7933
  throw new CdpError(`${FFMPEG_MISSING} ('-encoders' exited ${res.code}: ${res.stderr.trim().slice(0, 300)})`);
7630
- return selectEncoder(`${res.stdout}
7934
+ const choice = selectEncoder(`${res.stdout}
7631
7935
  ${res.stderr}`);
7936
+ const output = async (args) => {
7937
+ const r = await run(FFMPEG_BIN, args).catch(() => {
7938
+ return;
7939
+ });
7940
+ return r && r.code === 0 ? `${r.stdout}
7941
+ ${r.stderr}` : undefined;
7942
+ };
7943
+ const version = await output(["-version"]);
7944
+ const byVersion = version === undefined ? undefined : supportsFpsMode(version);
7945
+ const help = byVersion === undefined ? await output(["-hide_banner", "-h", "full"]) : undefined;
7946
+ return { ...choice, fpsMode: chooseFpsMode(version, help) };
7632
7947
  })();
7633
7948
  encoderProbe.catch(() => {
7634
7949
  encoderProbe = undefined;
@@ -7677,7 +7992,7 @@ async function startScreenRecording(args = {}) {
7677
7992
  conn.close();
7678
7993
  throw err;
7679
7994
  }
7680
- const spoolDir = join6(ARTIFACT_DIR3, `screencast-${shortId2(target.id)}-${stamp3()}`);
7995
+ const spoolDir = join7(ARTIFACT_DIR3, `screencast-${shortId2(target.id)}-${stamp3()}`);
7681
7996
  try {
7682
7997
  await mkdir8(spoolDir, { recursive: true });
7683
7998
  } catch (err) {
@@ -7720,7 +8035,7 @@ async function startScreenRecording(args = {}) {
7720
8035
  seq += 1;
7721
8036
  const file = `frame-${String(seq).padStart(6, "0")}.${ext}`;
7722
8037
  rec.ledger.push({ file, timestamp, width: size.width, height: size.height });
7723
- rec.writes = rec.writes.then(() => writeFile7(join6(spoolDir, file), buf)).catch(() => {
8038
+ rec.writes = rec.writes.then(() => writeFile7(join7(spoolDir, file), buf)).catch(() => {
7724
8039
  rec.dropped += 1;
7725
8040
  rec.unwritten.add(file);
7726
8041
  });
@@ -7784,9 +8099,9 @@ async function stopScreenRecording(args = {}) {
7784
8099
  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.`);
7785
8100
  }
7786
8101
  await mkdir8(ARTIFACT_DIR3, { recursive: true });
7787
- const outPath = args.savePath ?? join6(ARTIFACT_DIR3, `screen-recording-${shortId2(rec.target.id)}-${stamp3()}.mp4`);
8102
+ const outPath = args.savePath ?? join7(ARTIFACT_DIR3, `screen-recording-${shortId2(rec.target.id)}-${stamp3()}.mp4`);
7788
8103
  const frames = coalesceToConcatGrid(ledger, stoppedAt);
7789
- const manifestPath = join6(rec.spoolDir, "frames.ffconcat");
8104
+ const manifestPath = join7(rec.spoolDir, "frames.ffconcat");
7790
8105
  await writeFile7(manifestPath, buildConcatManifest(frames), "utf8");
7791
8106
  const durationMs = frames.reduce((total, f) => total + f.durationMs, 0);
7792
8107
  const { width, height } = evenDimensions(ledger[0].width, ledger[0].height);
@@ -7820,7 +8135,7 @@ ffmpeg said: ${res.stderr.trim().slice(0, 800)}`);
7820
8135
  // src/tools/heap.ts
7821
8136
  init_client();
7822
8137
  import { mkdir as mkdir9, writeFile as writeFile8 } from "node:fs/promises";
7823
- import { join as join7 } from "node:path";
8138
+ import { join as join8 } from "node:path";
7824
8139
  var ARTIFACT_DIR4 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7825
8140
  function stamp4(targetId) {
7826
8141
  const short = targetId.slice(0, 8);
@@ -7846,7 +8161,7 @@ async function takeHeapsnapshot(args = {}) {
7846
8161
  throw new Error("HeapProfiler.takeHeapSnapshot produced no chunks");
7847
8162
  }
7848
8163
  await mkdir9(ARTIFACT_DIR4, { recursive: true });
7849
- const path = args.savePath ? args.savePath.startsWith("/") ? args.savePath : join7(ARTIFACT_DIR4, args.savePath) : join7(ARTIFACT_DIR4, `take_heapsnapshot-${stamp4(target.id)}.heapsnapshot`);
8164
+ const path = args.savePath ? args.savePath.startsWith("/") ? args.savePath : join8(ARTIFACT_DIR4, args.savePath) : join8(ARTIFACT_DIR4, `take_heapsnapshot-${stamp4(target.id)}.heapsnapshot`);
7850
8165
  await writeFile8(path, snapshot, "utf8");
7851
8166
  const bytes = Buffer.byteLength(snapshot, "utf8");
7852
8167
  return {
@@ -7862,7 +8177,7 @@ async function takeHeapsnapshot(args = {}) {
7862
8177
  init_client();
7863
8178
  init_endpoints();
7864
8179
  import { spawn as spawn2 } from "node:child_process";
7865
- import { mkdir as mkdir10, readFile as readFile7, stat as stat3 } from "node:fs/promises";
8180
+ import { mkdir as mkdir10, readFile as readFile8, stat as stat3 } from "node:fs/promises";
7866
8181
  var ARTIFACT_DIR5 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7867
8182
  function cdpPort() {
7868
8183
  const base = currentEndpoint().base;
@@ -7952,7 +8267,7 @@ async function lighthouseAudit(args) {
7952
8267
  }
7953
8268
  let raw;
7954
8269
  try {
7955
- raw = await readFile7(outPath, "utf8");
8270
+ raw = await readFile8(outPath, "utf8");
7956
8271
  } catch {
7957
8272
  raw = undefined;
7958
8273
  }
@@ -8142,15 +8457,15 @@ async function clickFocusGated(args) {
8142
8457
  // src/tools/downloads.ts
8143
8458
  init_client();
8144
8459
  import { readdir as readdir3, rename as rename2, stat as stat4 } from "node:fs/promises";
8145
- import { basename, extname, join as join9 } from "node:path";
8460
+ import { basename, extname, join as join10 } from "node:path";
8146
8461
 
8147
8462
  // src/tools/browser-session.ts
8148
8463
  init_client();
8149
8464
  init_endpoints();
8150
8465
  import { mkdir as mkdir11 } from "node:fs/promises";
8151
- import { join as join8 } from "node:path";
8466
+ import { join as join9 } from "node:path";
8152
8467
  var ARTIFACT_DIR6 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
8153
- var DOWNLOADS_DIR = join8(ARTIFACT_DIR6, "downloads");
8468
+ var DOWNLOADS_DIR = join9(ARTIFACT_DIR6, "downloads");
8154
8469
  var DOWNLOAD_BUFFER_LIMIT = 50;
8155
8470
  var sessions2 = new Map;
8156
8471
  function sessionKey() {
@@ -8317,7 +8632,7 @@ async function waitForDownload(args = {}) {
8317
8632
  const taken = new Set(await readdir3(DOWNLOADS_DIR).catch(() => []));
8318
8633
  taken.delete(basename(rec.filePath));
8319
8634
  const finalName = nextFreeName(suggestedFilename, taken);
8320
- const path = join9(DOWNLOADS_DIR, finalName);
8635
+ const path = join10(DOWNLOADS_DIR, finalName);
8321
8636
  await rename2(rec.filePath, path);
8322
8637
  const bytes = (await stat4(path)).size;
8323
8638
  return { path, suggestedFilename, bytes, ...rec.url ? { url: rec.url } : {}, target };
@@ -8376,7 +8691,7 @@ async function grantPermissions(args = {}) {
8376
8691
  // src/tools/extract.ts
8377
8692
  init_client();
8378
8693
  import { mkdir as mkdir12, writeFile as writeFile9 } from "node:fs/promises";
8379
- import { dirname as dirname3, join as join10 } from "node:path";
8694
+ import { dirname as dirname3, join as join11 } from "node:path";
8380
8695
  var ARTIFACT_DIR7 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
8381
8696
  var DEFAULT_BASE_URL = "http://127.0.0.1:8090/v1";
8382
8697
  var DEFAULT_MODEL = "schematron";
@@ -8777,7 +9092,7 @@ async function extractPage(driver, args) {
8777
9092
  };
8778
9093
  if (args.savePath === undefined || args.savePath === "")
8779
9094
  return result;
8780
- const path = args.savePath.startsWith("/") ? args.savePath : join10(ARTIFACT_DIR7, args.savePath);
9095
+ const path = args.savePath.startsWith("/") ? args.savePath : join11(ARTIFACT_DIR7, args.savePath);
8781
9096
  await mkdir12(dirname3(path), { recursive: true });
8782
9097
  const json = JSON.stringify(result, null, 2);
8783
9098
  await writeFile9(path, json, "utf8");
@@ -8858,7 +9173,7 @@ import { spawn as spawn4 } from "node:child_process";
8858
9173
  import { existsSync as existsSync2, mkdtempSync, readFileSync as readFileSync2, rmSync, writeFileSync } from "node:fs";
8859
9174
  import { createConnection, createServer as createServer2 } from "node:net";
8860
9175
  import { tmpdir } from "node:os";
8861
- import { join as join12 } from "node:path";
9176
+ import { join as join13 } from "node:path";
8862
9177
  function resolveBinary() {
8863
9178
  const candidates = [
8864
9179
  process.env.FIREFOX_BIN,
@@ -8938,7 +9253,7 @@ var LAUNCH_USER_JS_PREFS = {
8938
9253
  "dom.file.createInChild": true
8939
9254
  };
8940
9255
  function writeLaunchUserJs(profilePath) {
8941
- const target = join12(profilePath, "user.js");
9256
+ const target = join13(profilePath, "user.js");
8942
9257
  const existing = existsSync2(target) ? readFileSync2(target, "utf8") : "";
8943
9258
  const present = new Set;
8944
9259
  for (const line of existing.split(`
@@ -8960,7 +9275,7 @@ async function launchFirefox(opts = {}) {
8960
9275
  const binary = resolveBinary();
8961
9276
  const port = await pickPort(opts.port);
8962
9277
  const isThrowaway = opts.profilePath === undefined;
8963
- const profilePath = opts.profilePath ?? mkdtempSync(join12(tmpdir(), "cdp-toolkit-ff-profile-"));
9278
+ const profilePath = opts.profilePath ?? mkdtempSync(join13(tmpdir(), "cdp-toolkit-ff-profile-"));
8964
9279
  if (isThrowaway)
8965
9280
  writeLaunchUserJs(profilePath);
8966
9281
  const args = ["--profile", profilePath, "--remote-debugging-port", String(port), "--no-remote"];
@@ -11252,13 +11567,13 @@ function toolAnnotations(name) {
11252
11567
  // src/install/wizard.ts
11253
11568
  import { createInterface } from "node:readline";
11254
11569
  import { homedir as homedir3 } from "node:os";
11255
- import { join as join15 } from "node:path";
11570
+ import { join as join16 } from "node:path";
11256
11571
 
11257
11572
  // src/install/browser.ts
11258
11573
  import { existsSync as existsSync3 } from "node:fs";
11259
- import { mkdir as mkdir14, readFile as readFile9, writeFile as writeFile11 } from "node:fs/promises";
11574
+ import { mkdir as mkdir14, readFile as readFile10, writeFile as writeFile11 } from "node:fs/promises";
11260
11575
  import { homedir } from "node:os";
11261
- import { delimiter, dirname as dirname4, join as join13 } from "node:path";
11576
+ import { delimiter, dirname as dirname4, join as join14 } from "node:path";
11262
11577
  var CANDIDATE_BUILDERS = {
11263
11578
  chrome: () => [
11264
11579
  process.env.CHROME_BIN,
@@ -11288,7 +11603,7 @@ function existsOnPath(cmd) {
11288
11603
  for (const dir of pathEnv.split(delimiter)) {
11289
11604
  if (!dir)
11290
11605
  continue;
11291
- if (existsSync3(join13(dir, cmd)))
11606
+ if (existsSync3(join14(dir, cmd)))
11292
11607
  return true;
11293
11608
  }
11294
11609
  return false;
@@ -11338,10 +11653,10 @@ function aliasLine(o) {
11338
11653
  function detectShellRc() {
11339
11654
  const shell = process.env.SHELL ?? "";
11340
11655
  if (shell.endsWith("zsh"))
11341
- return join13(homedir(), ".zshrc");
11656
+ return join14(homedir(), ".zshrc");
11342
11657
  if (shell.endsWith("bash"))
11343
- return join13(homedir(), ".bashrc");
11344
- return join13(homedir(), process.platform === "darwin" ? ".zshrc" : ".bashrc");
11658
+ return join14(homedir(), ".bashrc");
11659
+ return join14(homedir(), process.platform === "darwin" ? ".zshrc" : ".bashrc");
11345
11660
  }
11346
11661
  var MARKER_START = "# >>> cdp-toolkit alias >>>";
11347
11662
  var MARKER_END = "# <<< cdp-toolkit alias <<<";
@@ -11353,7 +11668,7 @@ function ensureTrailingNewline(s) {
11353
11668
  async function appendAliasToRc(rcPath, aliasBlockBody) {
11354
11669
  let existing = "";
11355
11670
  try {
11356
- existing = await readFile9(rcPath, "utf8");
11671
+ existing = await readFile10(rcPath, "utf8");
11357
11672
  } catch (err) {
11358
11673
  if (err.code !== "ENOENT")
11359
11674
  throw err;
@@ -11389,9 +11704,9 @@ ${after}`);
11389
11704
 
11390
11705
  // src/install/harness.ts
11391
11706
  import { spawnSync } from "node:child_process";
11392
- import { mkdir as mkdir15, readFile as readFile10, writeFile as writeFile12 } from "node:fs/promises";
11707
+ import { mkdir as mkdir15, readFile as readFile11, writeFile as writeFile12 } from "node:fs/promises";
11393
11708
  import { homedir as homedir2 } from "node:os";
11394
- import { dirname as dirname5, join as join14 } from "node:path";
11709
+ import { dirname as dirname5, join as join15 } from "node:path";
11395
11710
  async function installMcpServer(harness, name, cfg, opts = {}) {
11396
11711
  switch (harness) {
11397
11712
  case "claude":
@@ -11407,11 +11722,11 @@ async function installMcpServer(harness, name, cfg, opts = {}) {
11407
11722
  }
11408
11723
  }
11409
11724
  async function installClaude(name, cfg, opts) {
11410
- const path = opts.configPath ?? join14(opts.homeDir ?? homedir2(), ".claude.json");
11725
+ const path = opts.configPath ?? join15(opts.homeDir ?? homedir2(), ".claude.json");
11411
11726
  let root;
11412
11727
  let fileExisted;
11413
11728
  try {
11414
- const text = await readFile10(path, "utf8");
11729
+ const text = await readFile11(path, "utf8");
11415
11730
  const parsed = JSON.parse(text);
11416
11731
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
11417
11732
  throw new Error(`${path} does not contain a JSON object at its top level`);
@@ -11675,7 +11990,7 @@ async function promptPort(def) {
11675
11990
  }
11676
11991
  function harnessTargetDesc(harness, io) {
11677
11992
  if (harness === "claude") {
11678
- return io.configPath ?? join15(io.homeDir ?? homedir3(), ".claude.json");
11993
+ return io.configPath ?? join16(io.homeDir ?? homedir3(), ".claude.json");
11679
11994
  }
11680
11995
  return `via \`${harness} mcp add\``;
11681
11996
  }