cdp-toolkit 3.3.0 → 3.5.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/CHANGELOG.md +24 -0
- package/CONTRACT.md +1 -1
- package/README.md +20 -4
- package/dist/bidi/mux-daemon.js +231 -10
- package/dist/cli.js +409 -52
- package/dist/index.js +380 -43
- package/dist/mcp.js +433 -67
- package/package.json +1 -1
- package/src/bidi/driver.ts +21 -6
- package/src/cdp/driver.ts +190 -21
- package/src/cdp/hiddenTabs.ts +285 -0
- package/src/client.ts +12 -3
- package/src/driver.ts +26 -5
- package/src/frontApp.ts +62 -0
- package/src/leases-tools.ts +9 -2
- package/src/leases.ts +6 -0
- package/src/manifest.ts +15 -3
- package/src/mcp.ts +4 -0
- package/src/origins.ts +3 -2
- package/src/policy.ts +2 -1
- package/src/shared-tools.ts +79 -26
- package/src/toolDocs.ts +15 -12
- package/src/types.ts +3 -0
- package/src/version.ts +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,30 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [3.5.0] - 2026-11-18
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **Hidden tabs: `new_page` without any flash of the browser (opt-in, `CDP_HIDDEN_TABS=1`).** 3.4.0's restore puts the user's app back, but on macOS the browser still comes forward for a moment: every visible `Target.createTarget` variant activated Vivaldi in a tight `lsappinfo front` sample (`background`, `focus:false`, `newWindow`, a minimized new window, `window.open` from a background tab). Only `hidden:true` targets stayed clean. With `CDP_HIDDEN_TABS=1` in the MCP server, `new_page` and `claim_page` open such a tab on one held owner connection per endpoint, which keeps it alive and sets a 1280x800 viewport at the screen's pixel ratio, so screenshots, clicks and typing work and logins are shared (same browser context). Measured through the MCP server with the restore off: 3/3 `new_page` + `close_page` runs never changed the front app, against a flash on the visible path.
|
|
15
|
+
- `list_pages` marks these tabs `hidden: true` (the user cannot see them) and lists them after visible tabs.
|
|
16
|
+
- `select_page` with `focus:true` on a hidden tab reopens its URL in a visible tab, closes the hidden one, and returns the new id with `revealedFrom`. Page state the URL does not carry (form input, scroll) is lost.
|
|
17
|
+
- At most `CDP_HIDDEN_TABS_MAX` (default 20) hidden tabs; past the cap `new_page` is refused with the open ids. Server shutdown closes them all. A hidden tab dies with the server or the browser and then reports `no-such-target`.
|
|
18
|
+
- Default off, and the one-shot CLI always uses visible tabs (a hidden tab would die when the CLI exits). `focus:true` keeps the visible path.
|
|
19
|
+
|
|
20
|
+
## [3.4.0] - 2026-11-18
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
|
|
24
|
+
- **Nothing the toolkit does implicitly takes focus or switches the user's visible tab any more.** This is a behavior change:
|
|
25
|
+
- `new_page`, and `claim_page` when it opens a fresh tab, now open the tab in the background (CDP `Target.createTarget` `background:true`; Firefox `browsingContext.create` `background:true`). Before, Chromium browsers foregrounded every new tab. New optional `focus` boolean (default false) opens it in the foreground as before. `claim_page` ignores `focus` on takeover.
|
|
26
|
+
- On macOS a background `Target.createTarget` still brings the browser app in front of the user's current app (measured on Vivaldi: the active tab stays put, the window comes forward). `new_page` / `claim_page` (opening a background tab) and `close_page` (closing a tab, which raises the app too) now note the frontmost app first and put it back if it lost the front (`lsappinfo` to read, System Events to restore). `CDP_RESTORE_FRONT_APP=0` turns this off; it never runs off macOS or with `focus:true`.
|
|
27
|
+
- `select_page` now only writes the selected-state file by default and no longer sends `Target.activateTarget` / `browsingContext.activate`. New optional `focus` boolean (default false) raises the tab as before. The result gains `focused`.
|
|
28
|
+
|
|
29
|
+
### Fixed
|
|
30
|
+
|
|
31
|
+
- **Text input on a background tab (Chrome).** A background tab that never had a trusted click receives no trusted keyboard input at all (measured on Vivaldi: `Input.insertText` and `Input.dispatchKeyEvent` changed nothing and fired no keydown, with or without focus emulation), so `fill` reported success while the field stayed empty. `fill`, `fill_form` and `type_text` still try the trusted commit first, then verify it (text changed, or a `beforeinput`/`input` event fired) and fall back in-page: `document.execCommand('insertText')`, else the native value setter plus `input`/`change` events. The result carries `inputPath` (`inputPaths` for `fill_form`) only when the fallback ran or `type_text` skipped the element (disabled, read-only, non-text); a fallback that changes nothing is an error. `press_key` fakes nothing: on a definite miss the result says `delivered:false` with a note. A trusted `click` on the page gives the tab focus, after which trusted keys land (measured). Firefox is unchanged and not measured live.
|
|
32
|
+
- **`fill` / `fill_form` on a disabled or read-only field.** The clear step ran before the edit check, so the field's value was wiped and the result still said `filled:true` (`inputPath:"skipped"`). Both drivers now refuse such a field before touching it, with a `page-error` ("cannot fill a readonly field: it was left unchanged"); `fill_form` stops at that field.
|
|
33
|
+
|
|
10
34
|
## [3.3.0] - 2026-11-16
|
|
11
35
|
|
|
12
36
|
### Added
|
package/CONTRACT.md
CHANGED
|
@@ -166,7 +166,7 @@ A `Uid` **is** a CDP `backendDOMNodeId` (a number). This makes refs stateless:
|
|
|
166
166
|
|
|
167
167
|
| Module file | Tools (MCP name → fn) | Notes |
|
|
168
168
|
|---|---|---|
|
|
169
|
-
| `src/tools/pages.ts` | `list_pages`→`listPages`, `new_page`→`newPage`, `close_page`→`closePage`, `select_page`→`selectPage` | **Browser endpoint** (`openBrowser`, `Target.*`). `new_page`=`Target.createTarget
|
|
169
|
+
| `src/tools/pages.ts` | `list_pages`→`listPages`, `new_page`→`newPage`, `close_page`→`closePage`, `select_page`→`selectPage` | **Browser endpoint** (`openBrowser`, `Target.*`). `new_page`=`Target.createTarget` with `background:true` (foreground only on `focus:true`). `close_page`=`Target.closeTarget`. `select_page`=write selected state file, plus `Target.activateTarget` only on `focus:true`. `list_pages` may reuse `listTargets()`. |
|
|
170
170
|
| `src/tools/navigation.ts` | `navigate_page`→`navigatePage`, `wait_for`→`waitForText` (export as `waitFor` too) | `Page.enable` then `Page.navigate` (or `Page.reload` + `Page.getFrameTree` when `reload:true`; `ignoreCache:true` = hard reload); await `Page.frameStoppedLoading`/`Page.loadEventFired`. `wait_for` polls `Runtime.evaluate` for `document.body.innerText.includes(text)` with timeout, OR waits for a given event. |
|
|
171
171
|
| `src/tools/evaluate.ts` | `evaluate_script`→`evaluateScript` | `Runtime.enable` + `Runtime.evaluate` (`returnByValue`, `awaitPromise`). Support optional `args` via `Runtime.callFunctionOn` on a uid/selector. Surface `exceptionDetails` as thrown error. |
|
|
172
172
|
| `src/tools/snapshot.ts` | `take_snapshot`→`takeSnapshot` **+ export `resolveUid`** | a11y tree + ref scheme above. |
|
package/README.md
CHANGED
|
@@ -243,6 +243,9 @@ await TOOLS.navigate_page({ target: "index:0", url: "https://example.com" });
|
|
|
243
243
|
| `CDP_USER_DATA_DIR` | unset | Profile directory to read `DevToolsActivePort` from, to find that browser socket without naming its uuid. Opt-in on purpose: nothing is scanned unless you name it. |
|
|
244
244
|
| `CDP_ARTIFACT_DIR` | `/tmp/cdp-toolkit` | Screenshots, traces, heap snapshots, lighthouse reports, recorder buffers. |
|
|
245
245
|
| `CDP_STATE_DIR` | `/tmp/cdp-toolkit` | `select_page` selected-target file, in-flight trace state. |
|
|
246
|
+
| `CDP_RESTORE_FRONT_APP` | on (macOS only) | `0` stops `new_page` / `claim_page` / `close_page` from putting the user's frontmost app back after a background tab brings the browser forward. |
|
|
247
|
+
| `CDP_HIDDEN_TABS` | off | `1`: MCP server only, Chrome only. `new_page` / `claim_page` without `focus:true` open a hidden tab (`Target.createTarget {background:true, hidden:true}`), so the browser never flashes in front of the user's app. See "Hidden tabs" below. Ignored by the CLI, where a hidden tab would die at exit. |
|
|
248
|
+
| `CDP_HIDDEN_TABS_MAX` | `20` | Most hidden tabs open at once per endpoint. At the cap `new_page` refuses and names the open hidden ids; it never closes one for you. |
|
|
246
249
|
| `CDP_EXTRACT_BASE_URL` | `http://127.0.0.1:8090/v1` | `extract_page` only. Base URL of the OpenAI-compatible extraction endpoint (the server appends `/chat/completions`). The default is loopback llm-ferry, so page content never leaves the machine; overriding it sends page content wherever the operator points. |
|
|
247
250
|
| `CDP_EXTRACT_MODEL` | `schematron` | `extract_page` only. Model name for the extraction endpoint call. |
|
|
248
251
|
| `CDP_EXTRACT_API_KEY` | unset | `extract_page` only. Bearer token for the endpoint. Never logged and redacted from every error; the response never contains it. |
|
|
@@ -523,10 +526,10 @@ The 29 parity tools are 1:1 with `chrome-devtools-mcp`; the 19 superset tools (`
|
|
|
523
526
|
|
|
524
527
|
| MCP name | CDP method(s) | Parity notes / gaps |
|
|
525
528
|
|---|---|---|
|
|
526
|
-
| `list_pages` | `GET /json/list` | `all` flag also exposes worker/background and out-of-process (OOPIF) iframe targets; MCP lists only page tabs. A non-page targetId from this listing is accepted by any tool's `target` param as a bare id, and `take_snapshot` marks a cross-origin iframe node with `frame:"<targetId>"` (input inside such an iframe is invisible to the activity beacon — see "Staleness" below — but the frame itself is fully driveable as its own target). Each row additionally carries `origin` (`agent` or `unknown`, never `human`) plus `label`/`createdAt` for tabs this toolkit created, and, for a tab under an active lease of this backend, a `lease:{label,pid,idleMs,expiresAt,stale}` field (unconditional on `probe`). `probe:true` pings each page-type target's renderer (one bounded 500ms `Runtime.evaluate`, never more) and adds `responsive:boolean` plus `humanActiveMs` where that round trip found human-attributed input; a wedged/unreachable tab reports `responsive:false`, never an error for the whole call. Under `CDP_REQUIRE_LEASE` also reaps abandoned agent tabs first (destructively, only once a lease is `CDP_REAP_GRACE_MS` past its TTL — see "Staleness" below), reporting closures in an additive `reaped` array. |
|
|
527
|
-
| `new_page` | `Target.createTarget` (+ lease file) | Returns `{targetId,url}`; does not await navigation (use `navigate_page`). `claim:true` also claims the new tab and returns a `lease` token (`label`/`ttlMs` optional). Under `CDP_REQUIRE_LEASE` the tab is claimed and a `lease` returned even without `claim:true`. |
|
|
529
|
+
| `list_pages` | `GET /json/list` | `all` flag also exposes worker/background and out-of-process (OOPIF) iframe targets; MCP lists only page tabs. A non-page targetId from this listing is accepted by any tool's `target` param as a bare id, and `take_snapshot` marks a cross-origin iframe node with `frame:"<targetId>"` (input inside such an iframe is invisible to the activity beacon — see "Staleness" below — but the frame itself is fully driveable as its own target). Each row additionally carries `origin` (`agent` or `unknown`, never `human`) plus `label`/`createdAt` for tabs this toolkit created, and, for a tab under an active lease of this backend, a `lease:{label,pid,idleMs,expiresAt,stale}` field (unconditional on `probe`). `probe:true` pings each page-type target's renderer (one bounded 500ms `Runtime.evaluate`, never more) and adds `responsive:boolean` plus `humanActiveMs` where that round trip found human-attributed input; a wedged/unreachable tab reports `responsive:false`, never an error for the whole call. Under `CDP_REQUIRE_LEASE` also reaps abandoned agent tabs first (destructively, only once a lease is `CDP_REAP_GRACE_MS` past its TTL — see "Staleness" below), reporting closures in an additive `reaped` array. This server's hidden tabs (`CDP_HIDDEN_TABS`) are listed last with `hidden:true`. |
|
|
530
|
+
| `new_page` | `Target.createTarget` (+ lease file) | Opens the tab in the background (`background:true`), so the user's visible tab and focus stay put; `focus:true` opens it in the foreground. Returns `{targetId,url}`; does not await navigation (use `navigate_page`). `claim:true` also claims the new tab and returns a `lease` token (`label`/`ttlMs` optional). Under `CDP_REQUIRE_LEASE` the tab is claimed and a `lease` returned even without `claim:true`. Under `CDP_HIDDEN_TABS=1` (MCP server) a non-focus `new_page` opens a hidden tab instead and returns `hidden:true`; see "Hidden tabs". |
|
|
528
531
|
| `close_page` | `Target.closeTarget` (+ lease file) | Reports `success:true` on the empty result newer Chromium returns. A successful close also releases that tab's lease; a failed close leaves it in place. |
|
|
529
|
-
| `select_page` | `Target.activateTarget`
|
|
532
|
+
| `select_page` | selected-state file (+ `Target.activateTarget` with `focus:true`) | Writes a flat-file selected target and returns `{selected,focused}`; it raises the tab only with `focus:true`; `resolveTarget` does not read it, so `active` still means `index:0` unless a tool opts in. On a hidden tab, `focus:true` reopens its URL in a new visible tab, closes the hidden one, and returns the new id as `selected` plus `revealedFrom`. |
|
|
530
533
|
| `navigate_page` | `Page.navigate` / `Page.reload` + load events, or `history:'back'\|'forward'` (Chrome: `Page.getNavigationHistory` + `Page.navigateToHistoryEntry`; Firefox: `browsingContext.traverseHistory`) | Returns `{url,frameId,waitedFor}` (no auto-snapshot; a history move also returns `traversed:'back'\|'forward'`). `waitUntil` supports `load`/`domcontentloaded`. `reload:true` (+ `ignoreCache:true` for a hard reload). `url`/`reload`/`history` are mutually exclusive; going back from the first entry (or forward from the last) is an error naming the direction, never a silent no-op. Works on both backends. |
|
|
531
534
|
| `wait_for` | `Runtime.evaluate` (poll `innerText`) | Text-substring waiting only; throws on timeout rather than returning `{found:false}`. |
|
|
532
535
|
| `evaluate_script` | `Runtime.evaluate` / `callFunctionOn` | No live `page`/element handle; `args` are plain JSON. Main-world context only. Toolkit addition: optional `savePath` writes the value to a JSON file and keeps it out of the response entirely. If `expression` is missing/empty and the call instead carries `function`/`code`/`js`/`script`/`fn`/`body`, the error names the wrong key and points at `expression`. One of four tools that also accept `target: "worker:<substring>"` (Chrome only, capability `worker.targets`) to reach an MV3 extension's background service worker — see "Driving MV3 extensions" below. |
|
|
@@ -565,7 +568,7 @@ The 29 parity tools are 1:1 with `chrome-devtools-mcp`; the 19 superset tools (`
|
|
|
565
568
|
| `mock_request` *(superset)* | `Fetch.*` (+ `Page.reload`) | **A fake backend.** Registers a rule on a target's persistent session: fulfill with a canned response, fail, or continue (with optional `delayMs`/`failRate`). Persists across reloads until `clear_mocks`. Request-stage only. Cached requests aren't intercepted (use `reload:true`). |
|
|
566
569
|
| `list_mocks` *(superset)* | `Runtime.evaluate` (liveness probe) | Lists active mock sessions with rules + hit counts; prunes sessions whose tab closed. |
|
|
567
570
|
| `clear_mocks` *(superset)* | `Fetch.disable` | Tears down the resolved target's mock session (or all with `all:true`). |
|
|
568
|
-
| `claim_page` *(superset)* | `Target.createTarget` + lease file | Opens a fresh tab and claims it (no `target`/`targetId`), or takes over a tab that is already open (`target`, any selector, or the exact-id `targetId`) and returns an opaque lease token plus `opened` (true only when this call created the tab). Never steals a tab another live process holds. Also returns `humanActiveMs` (ms since input this server did not dispatch; `null` means no data, never "no human") and, on a takeover of a tab a human used within the last 30s, a `contention` warning
|
|
571
|
+
| `claim_page` *(superset)* | `Target.createTarget` + lease file | Opens a fresh tab in the background and claims it (no `target`/`targetId`; `focus:true` opens it in the foreground), or takes over a tab that is already open (`target`, any selector, or the exact-id `targetId`) and returns an opaque lease token plus `opened` (true only when this call created the tab). Never steals a tab another live process holds. Also returns `humanActiveMs` (ms since input this server did not dispatch; `null` means no data, never "no human") and, on a takeover of a tab a human used within the last 30s, a `contention` warning; the claim is never refused for it. MCP only; the CLI refuses it. The `search_tools` and `call_tool` meta-tools are likewise MCP-only. |
|
|
569
572
|
| `release_page` *(superset)* | lease file | Gives a lease back via `lease` (the token) or `target` (a selector, for a lease the gate auto-acquired and so never handed out a token for). Idempotent. Closes the tab by default when this toolkit's creation ledger says it opened it; leaves a merely-claimed tab open. Override either way with `close`. |
|
|
570
573
|
| `list_leases` *(superset)* | lease file | Who holds what, with pid liveness and reclaimability, plus computed `idleMs`/`expiresAt` and, where the tab's beacon answers, `humanActiveMs` (absent, not null, when there's no answer). Needs no token; never returns the nonce. A lease file that could not be read or parsed is reported as an `unreadable` row instead of being skipped (with `idleMs`/`expiresAt` omitted). Under `CDP_REQUIRE_LEASE` also reaps abandoned agent tabs, reporting closures in an additive `reaped` array. |
|
|
571
574
|
| `wait_for_download` *(superset)* | `Browser.setDownloadBehavior` + `Browser.downloadWillBegin`/`downloadProgress` on a standing browser-endpoint connection | Waits for a download to finish and returns it as a real file on disk: `{path,suggestedFilename,bytes,url,target}`. **Ordering rule, not optional:** call `wait_for_download{arm:true}` *before* the click that starts the download, then click, then call `wait_for_download` again to collect it — arming this late is not a preference, it's because Chrome reverts the download-behavior override the instant the arming client disconnects, and denies an unarmed download outright. **Browser-global side effect:** while armed, *every* download in the browser is redirected into the toolkit's downloads directory. **MCP-server only:** the arm lives on a connection this server process holds open; the one-shot CLI's connection dies with the process, so nothing is captured there. Firefox 160+ too (`browser.setDownloadBehavior`), where each call re-arms and the profile's normal download folder is restored when it returns. |
|
|
@@ -716,6 +719,19 @@ So every tab this toolkit creates is written to a creation ledger, and `list_pag
|
|
|
716
719
|
- No protection from humans. The lease is enforced against cdp-toolkit's own tool calls. It cannot stop someone clicking into the tab.
|
|
717
720
|
- Not for the CLI. A CLI invocation is one process per call, so a lease it claimed would be reclaimable immediately by the dead-pid rule. `claim_page` is refused there. CLI calls can still present a token minted by the MCP server with `--lease`. Strict mode (`CDP_REQUIRE_LEASE`) is likewise MCP-only and for the same underlying reason, doubled: an auto-acquired lease would be reclaimable on arrival, worse than no lease at all, and reap would then be free to read that instantly-dead-pid record as an abandoned tab and close it on the next listing.
|
|
718
721
|
|
|
722
|
+
## Hidden tabs: no browser flash (`CDP_HIDDEN_TABS`)
|
|
723
|
+
|
|
724
|
+
A background tab (`Target.createTarget {background:true}`) leaves the user's active tab alone, but on macOS it still brings the browser **app** in front of whatever the user is working in, for a moment. `CDP_RESTORE_FRONT_APP` puts their app back afterwards; it cannot stop the flash. Measured on Vivaldi (Chromium 156) by sampling the frontmost app around each raw CDP call: `{background:true}`, `{background:true, focus:false}`, a background `newWindow` and a minimized new window all flash. `{background:true, hidden:true}` does not, and neither do `Target.closeTarget` or `Page.navigate` on an existing tab.
|
|
725
|
+
|
|
726
|
+
Set `CDP_HIDDEN_TABS=1` on the **MCP server** and `new_page` / `claim_page` without `focus:true` open hidden tabs:
|
|
727
|
+
|
|
728
|
+
- **Fully drivable.** A hidden tab starts with a 0x0 viewport, where screenshots hang and clicks land nowhere, so the server attaches to it, sets a 1280x800 viewport at the screen's own device pixel ratio (read from the tab), and keeps that session open. Snapshots, screenshots, clicks, typing and navigation then work from any call. It shares the normal browser profile, so cookies and logins carry over.
|
|
729
|
+
- **Invisible.** It is in no window. `list_pages` marks it `hidden:true` and lists it after the visible tabs, so `index:` numbers and the default target are unchanged for the visible ones. Every selector (`url:`, `title:`, `label:`, an id) reaches it.
|
|
730
|
+
- **Tied to this server.** A hidden tab lives only while the server's connection that created it is open. A server restart, a browser restart or a dropped socket takes every hidden tab with it; the next `new_page` reconnects, and calls on a dead id fail fast with `no-such-target`. That is also why the CLI ignores the variable: its tab would die when the command exits.
|
|
731
|
+
- **Showing one to the user.** `select_page {focus:true}` cannot raise a hidden tab (Chromium accepts the activate call and shows nothing), so it opens the tab's current URL in a new visible tab (this one flash is the point), closes the hidden tab, and returns `{selected:<new id>, revealedFrom:<old id>}`. The tab's label moves with it; a lease moves too, and its new token comes back as `lease`. State the URL does not carry (form input, scroll position, a POST result) is lost. `new_page {focus:true}` still opens an ordinary visible tab.
|
|
732
|
+
- **Bounded.** The user cannot see or close these tabs, so at most `CDP_HIDDEN_TABS_MAX` (default 20) are open per endpoint. At the cap `new_page` refuses with an error naming the open hidden ids, oldest first; it never closes a tab another call may still be driving. `close_page` frees one, and server shutdown closes them all.
|
|
733
|
+
- **Scope.** Chrome-family browsers over CDP only (Firefox is unchanged). Only hidden tabs this server opened are marked; another server's hidden tabs list with the browser's own type, `"other"`.
|
|
734
|
+
|
|
719
735
|
## Named endpoints: several browsers or apps from one server
|
|
720
736
|
|
|
721
737
|
One server can drive more than one DevTools port: your browser on `9222` and, say, the Microsoft Teams desktop app (WebView2, launched with `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9333`) or an Electron app. Chrome backend only.
|
package/dist/bidi/mux-daemon.js
CHANGED
|
@@ -322,6 +322,9 @@ function leaseTtlMs() {
|
|
|
322
322
|
function markLongLivedProcess(value = true) {
|
|
323
323
|
longLived = value;
|
|
324
324
|
}
|
|
325
|
+
function isLongLivedProcess() {
|
|
326
|
+
return longLived;
|
|
327
|
+
}
|
|
325
328
|
function requireLease() {
|
|
326
329
|
if (!longLived)
|
|
327
330
|
return false;
|
|
@@ -731,6 +734,53 @@ var init_session_lease = __esm(() => {
|
|
|
731
734
|
};
|
|
732
735
|
});
|
|
733
736
|
|
|
737
|
+
// src/frontApp.ts
|
|
738
|
+
import { execFile } from "node:child_process";
|
|
739
|
+
function run(cmd, args) {
|
|
740
|
+
return new Promise((resolve) => {
|
|
741
|
+
execFile(cmd, args, { timeout: 2000 }, (err, stdout) => resolve(err ? "" : String(stdout)));
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
function restoreFrontAppEnabled(platform = process.platform) {
|
|
745
|
+
return platform === "darwin" && (process.env.CDP_RESTORE_FRONT_APP ?? "").trim() !== "0";
|
|
746
|
+
}
|
|
747
|
+
async function keepFrontApp(fn, opts = {}) {
|
|
748
|
+
const enabled = opts.enabled ?? restoreFrontAppEnabled();
|
|
749
|
+
if (!enabled)
|
|
750
|
+
return fn();
|
|
751
|
+
const ops = opts.ops ?? macFrontAppOps;
|
|
752
|
+
const before = await ops.front().catch(() => null);
|
|
753
|
+
const result = await fn();
|
|
754
|
+
if (before === null)
|
|
755
|
+
return result;
|
|
756
|
+
const fix = async () => {
|
|
757
|
+
const now = await ops.front().catch(() => null);
|
|
758
|
+
if (now !== null && now !== before)
|
|
759
|
+
await ops.setFront(before).catch(() => {
|
|
760
|
+
return;
|
|
761
|
+
});
|
|
762
|
+
};
|
|
763
|
+
await fix();
|
|
764
|
+
await new Promise((r) => setTimeout(r, opts.recheckMs ?? 250));
|
|
765
|
+
await fix();
|
|
766
|
+
return result;
|
|
767
|
+
}
|
|
768
|
+
var macFrontAppOps;
|
|
769
|
+
var init_frontApp = __esm(() => {
|
|
770
|
+
macFrontAppOps = {
|
|
771
|
+
async front() {
|
|
772
|
+
const asn = (await run("lsappinfo", ["front"])).trim();
|
|
773
|
+
if (!asn)
|
|
774
|
+
return null;
|
|
775
|
+
const m = /"?pid"?\s*=\s*(\d+)/.exec(await run("lsappinfo", ["info", "-only", "pid", asn]));
|
|
776
|
+
return m ? Number(m[1]) : null;
|
|
777
|
+
},
|
|
778
|
+
async setFront(pid) {
|
|
779
|
+
await run("osascript", ["-e", `tell application "System Events" to set frontmost of (first process whose unix id is ${pid}) to true`]);
|
|
780
|
+
}
|
|
781
|
+
};
|
|
782
|
+
});
|
|
783
|
+
|
|
734
784
|
// src/driver.ts
|
|
735
785
|
import { mkdir as mkdir3, readFile as readFile3, unlink as unlink3, writeFile as writeFile3 } from "node:fs/promises";
|
|
736
786
|
import { join as join3 } from "node:path";
|
|
@@ -903,7 +953,7 @@ async function originIndex(backend, liveIds) {
|
|
|
903
953
|
return index;
|
|
904
954
|
}
|
|
905
955
|
async function newTrackedPage(driver, backend, opts = {}) {
|
|
906
|
-
const page = await driver.newPage(opts.url);
|
|
956
|
+
const page = await driver.newPage(opts.url, { focus: opts.focus === true });
|
|
907
957
|
await recordOrigin(backend, page.id, { label: opts.label });
|
|
908
958
|
return page;
|
|
909
959
|
}
|
|
@@ -2459,6 +2509,165 @@ var init_session = __esm(() => {
|
|
|
2459
2509
|
init_endpoint();
|
|
2460
2510
|
});
|
|
2461
2511
|
|
|
2512
|
+
// src/cdp/hiddenTabs.ts
|
|
2513
|
+
function hiddenTabsRequested() {
|
|
2514
|
+
return TRUTHY.has((process.env.CDP_HIDDEN_TABS ?? "").trim().toLowerCase());
|
|
2515
|
+
}
|
|
2516
|
+
function hiddenTabsMax() {
|
|
2517
|
+
const raw = Number(process.env.CDP_HIDDEN_TABS_MAX);
|
|
2518
|
+
return Number.isFinite(raw) && raw >= 1 ? Math.floor(raw) : DEFAULT_HIDDEN_TABS_MAX;
|
|
2519
|
+
}
|
|
2520
|
+
|
|
2521
|
+
class HiddenTabOwner {
|
|
2522
|
+
deps;
|
|
2523
|
+
conn;
|
|
2524
|
+
connecting;
|
|
2525
|
+
tabs = new Map;
|
|
2526
|
+
reserved = 0;
|
|
2527
|
+
constructor(deps) {
|
|
2528
|
+
this.deps = deps;
|
|
2529
|
+
}
|
|
2530
|
+
sweep() {
|
|
2531
|
+
if (this.conn && !this.conn.isOpen) {
|
|
2532
|
+
this.conn = undefined;
|
|
2533
|
+
this.tabs.clear();
|
|
2534
|
+
}
|
|
2535
|
+
}
|
|
2536
|
+
has(id) {
|
|
2537
|
+
this.sweep();
|
|
2538
|
+
return this.tabs.has(id);
|
|
2539
|
+
}
|
|
2540
|
+
ids() {
|
|
2541
|
+
this.sweep();
|
|
2542
|
+
return [...this.tabs.keys()];
|
|
2543
|
+
}
|
|
2544
|
+
async owner() {
|
|
2545
|
+
this.sweep();
|
|
2546
|
+
if (this.conn)
|
|
2547
|
+
return this.conn;
|
|
2548
|
+
if (!this.connecting) {
|
|
2549
|
+
this.connecting = (async () => {
|
|
2550
|
+
const conn = await this.deps.connect();
|
|
2551
|
+
conn.on("Target.targetDestroyed", (params) => {
|
|
2552
|
+
const id = params.targetId;
|
|
2553
|
+
if (typeof id === "string")
|
|
2554
|
+
this.tabs.delete(id);
|
|
2555
|
+
});
|
|
2556
|
+
this.conn = conn;
|
|
2557
|
+
return conn;
|
|
2558
|
+
})().finally(() => {
|
|
2559
|
+
this.connecting = undefined;
|
|
2560
|
+
});
|
|
2561
|
+
}
|
|
2562
|
+
return this.connecting;
|
|
2563
|
+
}
|
|
2564
|
+
async create(url) {
|
|
2565
|
+
this.sweep();
|
|
2566
|
+
const max = (this.deps.max ?? hiddenTabsMax)();
|
|
2567
|
+
if (this.tabs.size + this.reserved >= max)
|
|
2568
|
+
throw new HiddenTabCapError(max, [...this.tabs.keys()]);
|
|
2569
|
+
this.reserved++;
|
|
2570
|
+
try {
|
|
2571
|
+
const conn = await this.owner();
|
|
2572
|
+
const id = await this.deps.createSettled(conn, url, { hidden: true });
|
|
2573
|
+
try {
|
|
2574
|
+
const { sessionId } = await conn.send("Target.attachToTarget", { targetId: id, flatten: true }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS });
|
|
2575
|
+
const dpr = await conn.send("Runtime.evaluate", { expression: "devicePixelRatio", returnByValue: true }, { sessionId, timeoutMs: OWNER_COMMAND_TIMEOUT_MS }).then((r) => r.result?.value).catch(() => {
|
|
2576
|
+
return;
|
|
2577
|
+
});
|
|
2578
|
+
await conn.send("Emulation.setDeviceMetricsOverride", {
|
|
2579
|
+
width: HIDDEN_TAB_VIEWPORT.width,
|
|
2580
|
+
height: HIDDEN_TAB_VIEWPORT.height,
|
|
2581
|
+
deviceScaleFactor: typeof dpr === "number" && Number.isFinite(dpr) && dpr > 0 ? dpr : FALLBACK_DEVICE_SCALE_FACTOR,
|
|
2582
|
+
mobile: false
|
|
2583
|
+
}, { sessionId, timeoutMs: OWNER_COMMAND_TIMEOUT_MS });
|
|
2584
|
+
this.tabs.set(id, sessionId);
|
|
2585
|
+
return id;
|
|
2586
|
+
} catch (e) {
|
|
2587
|
+
await conn.send("Target.closeTarget", { targetId: id }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS }).catch(() => {
|
|
2588
|
+
return;
|
|
2589
|
+
});
|
|
2590
|
+
throw e;
|
|
2591
|
+
}
|
|
2592
|
+
} finally {
|
|
2593
|
+
this.reserved--;
|
|
2594
|
+
}
|
|
2595
|
+
}
|
|
2596
|
+
async close(id) {
|
|
2597
|
+
this.sweep();
|
|
2598
|
+
const conn = this.conn;
|
|
2599
|
+
const held = this.tabs.delete(id);
|
|
2600
|
+
if (!conn || !held)
|
|
2601
|
+
return { success: false };
|
|
2602
|
+
const res = await conn.send("Target.closeTarget", { targetId: id }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS });
|
|
2603
|
+
return { success: res.success ?? true };
|
|
2604
|
+
}
|
|
2605
|
+
async dispose() {
|
|
2606
|
+
const conn = this.conn;
|
|
2607
|
+
const ids = [...this.tabs.keys()];
|
|
2608
|
+
this.tabs.clear();
|
|
2609
|
+
this.conn = undefined;
|
|
2610
|
+
if (!conn)
|
|
2611
|
+
return;
|
|
2612
|
+
if (conn.isOpen) {
|
|
2613
|
+
await Promise.all(ids.map((targetId) => conn.send("Target.closeTarget", { targetId }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS }).catch(() => {
|
|
2614
|
+
return;
|
|
2615
|
+
})));
|
|
2616
|
+
}
|
|
2617
|
+
conn.close();
|
|
2618
|
+
}
|
|
2619
|
+
}
|
|
2620
|
+
function hiddenTabOwner(base, deps) {
|
|
2621
|
+
let owner = owners.get(base);
|
|
2622
|
+
if (!owner) {
|
|
2623
|
+
owner = new HiddenTabOwner(deps());
|
|
2624
|
+
owners.set(base, owner);
|
|
2625
|
+
}
|
|
2626
|
+
return owner;
|
|
2627
|
+
}
|
|
2628
|
+
function existingHiddenTabOwner(base) {
|
|
2629
|
+
return owners.get(base);
|
|
2630
|
+
}
|
|
2631
|
+
function markHiddenTargets(base, targets) {
|
|
2632
|
+
const owner = owners.get(base);
|
|
2633
|
+
if (!owner)
|
|
2634
|
+
return targets;
|
|
2635
|
+
const hidden = new Set(owner.ids());
|
|
2636
|
+
if (hidden.size === 0)
|
|
2637
|
+
return targets;
|
|
2638
|
+
const visible = [];
|
|
2639
|
+
const marked = [];
|
|
2640
|
+
for (const t of targets) {
|
|
2641
|
+
if (hidden.has(t.id))
|
|
2642
|
+
marked.push({ ...t, type: "page", hidden: true });
|
|
2643
|
+
else
|
|
2644
|
+
visible.push(t);
|
|
2645
|
+
}
|
|
2646
|
+
return marked.length ? [...visible, ...marked] : targets;
|
|
2647
|
+
}
|
|
2648
|
+
async function disposeHiddenTabs() {
|
|
2649
|
+
const all = [...owners.values()];
|
|
2650
|
+
owners.clear();
|
|
2651
|
+
await Promise.all(all.map((o) => o.dispose()));
|
|
2652
|
+
}
|
|
2653
|
+
var DEFAULT_HIDDEN_TABS_MAX = 20, HIDDEN_TAB_VIEWPORT, FALLBACK_DEVICE_SCALE_FACTOR = 2, OWNER_COMMAND_TIMEOUT_MS = 5000, TRUTHY, HiddenTabCapError, owners;
|
|
2654
|
+
var init_hiddenTabs = __esm(() => {
|
|
2655
|
+
HIDDEN_TAB_VIEWPORT = { width: 1280, height: 800 };
|
|
2656
|
+
TRUTHY = new Set(["1", "true", "yes", "on"]);
|
|
2657
|
+
HiddenTabCapError = class HiddenTabCapError extends Error {
|
|
2658
|
+
max;
|
|
2659
|
+
openIds;
|
|
2660
|
+
code = "page-error";
|
|
2661
|
+
constructor(max, openIds) {
|
|
2662
|
+
super(`hidden-tab cap reached: ${openIds.length} hidden tabs are open (CDP_HIDDEN_TABS_MAX=${max}). ` + `Close one with close_page (open hidden tabs, oldest first: ${openIds.join(", ")}), ` + `or pass focus:true to open a visible tab instead.`);
|
|
2663
|
+
this.max = max;
|
|
2664
|
+
this.openIds = openIds;
|
|
2665
|
+
this.name = "HiddenTabCapError";
|
|
2666
|
+
}
|
|
2667
|
+
};
|
|
2668
|
+
owners = new Map;
|
|
2669
|
+
});
|
|
2670
|
+
|
|
2462
2671
|
// src/client.ts
|
|
2463
2672
|
class CdpConnection {
|
|
2464
2673
|
wsUrl;
|
|
@@ -2577,6 +2786,9 @@ class CdpConnection {
|
|
|
2577
2786
|
});
|
|
2578
2787
|
});
|
|
2579
2788
|
}
|
|
2789
|
+
get isOpen() {
|
|
2790
|
+
return !this.closed && this.ws !== undefined;
|
|
2791
|
+
}
|
|
2580
2792
|
close() {
|
|
2581
2793
|
this.closed = true;
|
|
2582
2794
|
this.rejectAll(new CdpError("closed by caller"));
|
|
@@ -2605,11 +2817,11 @@ async function getTargetsOverBrowserWs() {
|
|
|
2605
2817
|
async function listTargets() {
|
|
2606
2818
|
const base = currentEndpoint().base;
|
|
2607
2819
|
if (knownTransports.get(base) === "browser-ws")
|
|
2608
|
-
return getTargetsOverBrowserWs();
|
|
2820
|
+
return markHiddenTargets(base, await getTargetsOverBrowserWs());
|
|
2609
2821
|
try {
|
|
2610
2822
|
const listing = await httpJson("/json/list");
|
|
2611
2823
|
knownTransports.set(base, "http");
|
|
2612
|
-
return listing;
|
|
2824
|
+
return markHiddenTargets(base, listing);
|
|
2613
2825
|
} catch (httpError) {
|
|
2614
2826
|
const detected = await detectEndpoint().catch(() => {
|
|
2615
2827
|
return;
|
|
@@ -2620,7 +2832,7 @@ async function listTargets() {
|
|
|
2620
2832
|
throw httpError;
|
|
2621
2833
|
});
|
|
2622
2834
|
knownTransports.set(base, "browser-ws");
|
|
2623
|
-
return targets;
|
|
2835
|
+
return markHiddenTargets(base, targets);
|
|
2624
2836
|
}
|
|
2625
2837
|
}
|
|
2626
2838
|
async function browserWsUrl() {
|
|
@@ -2733,6 +2945,7 @@ var init_client2 = __esm(() => {
|
|
|
2733
2945
|
init_frames();
|
|
2734
2946
|
init_endpoint();
|
|
2735
2947
|
init_session();
|
|
2948
|
+
init_hiddenTabs();
|
|
2736
2949
|
init_session();
|
|
2737
2950
|
BASE = (() => {
|
|
2738
2951
|
try {
|
|
@@ -3505,6 +3718,9 @@ async function pickContext(conn, contexts, selector) {
|
|
|
3505
3718
|
return exact;
|
|
3506
3719
|
throw driverError("no-such-target", `no context matching '${selector}'`);
|
|
3507
3720
|
}
|
|
3721
|
+
function bidiCreateTabParams(opts) {
|
|
3722
|
+
return { type: "tab", background: opts?.focus !== true };
|
|
3723
|
+
}
|
|
3508
3724
|
|
|
3509
3725
|
class BidiBrowserDriver {
|
|
3510
3726
|
endpoint;
|
|
@@ -3531,12 +3747,13 @@ class BidiBrowserDriver {
|
|
|
3531
3747
|
conn.release();
|
|
3532
3748
|
}
|
|
3533
3749
|
}
|
|
3534
|
-
async newPage(url) {
|
|
3750
|
+
async newPage(url, opts) {
|
|
3535
3751
|
const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
|
|
3536
3752
|
try {
|
|
3537
|
-
const
|
|
3753
|
+
const create = () => conn.send("browsingContext.create", bidiCreateTabParams(opts)).catch((e) => {
|
|
3538
3754
|
throw mapBidiError(e);
|
|
3539
3755
|
});
|
|
3756
|
+
const { context } = opts?.focus === true ? await create() : await keepFrontApp(create);
|
|
3540
3757
|
if (url)
|
|
3541
3758
|
await conn.send("browsingContext.navigate", { context, url, wait: "complete" }).catch((e) => {
|
|
3542
3759
|
throw mapBidiError(e);
|
|
@@ -3549,9 +3766,9 @@ class BidiBrowserDriver {
|
|
|
3549
3766
|
async closePage(id) {
|
|
3550
3767
|
const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
|
|
3551
3768
|
try {
|
|
3552
|
-
await conn.send("browsingContext.close", { context: id }).catch((e) => {
|
|
3769
|
+
await keepFrontApp(() => conn.send("browsingContext.close", { context: id }).catch((e) => {
|
|
3553
3770
|
throw mapBidiError(e);
|
|
3554
|
-
});
|
|
3771
|
+
}));
|
|
3555
3772
|
return { success: true };
|
|
3556
3773
|
} finally {
|
|
3557
3774
|
conn.release();
|
|
@@ -3735,6 +3952,7 @@ function createFirefoxDriverForEndpoint(wsUrl, opts) {
|
|
|
3735
3952
|
}
|
|
3736
3953
|
var LINE_RE, INTERACTIVE_ROLES, STAMP_ONE_SOURCE, KEY_VALUES, MODIFIER_VALUES, BUTTON_CODES, RAW_MOUSE_SOURCE_ID = "cdp-raw-mouse", ARM_SCROLL_SETTLE_WATCH_SOURCE, AWAIT_SCROLL_SETTLE_SOURCE = "function(){return window.__cdpScrollSettle;}", BIDI_CAPABILITY_MIN_FIREFOX, POST_HOC_BODY_MAX_BYTES, BIDI_CAPABILITIES, connections, slotHandles, muxes, joined, connecting, sessionEpochs, connEndpoints, disposeHooks, STALE_ID_HINT, sleep2 = (ms) => new Promise((r) => setTimeout(r, ms)), slotLabelOverride, bidiBeaconScripts, BidiPageDriver;
|
|
3737
3954
|
var init_driver2 = __esm(() => {
|
|
3955
|
+
init_frontApp();
|
|
3738
3956
|
init_driver();
|
|
3739
3957
|
init_leases();
|
|
3740
3958
|
init_origins();
|
|
@@ -4076,8 +4294,11 @@ var init_driver2 = __esm(() => {
|
|
|
4076
4294
|
await this.callFunctionValue(BidiPageDriver.INSERT_TEXT_SOURCE, [value, false], ref);
|
|
4077
4295
|
return;
|
|
4078
4296
|
}
|
|
4079
|
-
const clear = "function(){this.focus&&this.focus();if('value' in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}}";
|
|
4080
|
-
await this.callFunctionValue(clear, [], ref);
|
|
4297
|
+
const clear = "function(){if(this.disabled||this.readOnly)return this.disabled?'disabled':'readonly';this.focus&&this.focus();if('value' in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}return 'ok';}";
|
|
4298
|
+
const state = await this.callFunctionValue(clear, [], ref);
|
|
4299
|
+
if (state === "disabled" || state === "readonly") {
|
|
4300
|
+
throw driverError("page-error", `cannot fill a ${state} field: it was left unchanged`);
|
|
4301
|
+
}
|
|
4081
4302
|
await this.sendKeys(value);
|
|
4082
4303
|
}
|
|
4083
4304
|
async typeText(loc, text) {
|