waybound 0.2.2__py3-none-any.whl

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.
waybound/__init__.py ADDED
@@ -0,0 +1,38 @@
1
+ """waybound: Ergonomic, out-of-band OS-level browser automation."""
2
+
3
+ from waybound.async_client import AsyncLocator, AsyncPage, AsyncSession, launch_async
4
+ from waybound.client import Locator, Page
5
+ from waybound.session import LaunchOptions, Session, launch
6
+ from waybound.transport import UnixSocketTransport, WayboundDaemonError
7
+ from waybound.types import (
8
+ AccessibilityNode,
9
+ BackendKind,
10
+ Bounds,
11
+ CapturedResponse,
12
+ KeyModifier,
13
+ LocatorQuery,
14
+ Role,
15
+ Transport,
16
+ )
17
+
18
+ __all__ = [
19
+ "AccessibilityNode",
20
+ "AsyncLocator",
21
+ "AsyncPage",
22
+ "AsyncSession",
23
+ "BackendKind",
24
+ "Bounds",
25
+ "CapturedResponse",
26
+ "KeyModifier",
27
+ "LaunchOptions",
28
+ "Locator",
29
+ "LocatorQuery",
30
+ "Page",
31
+ "Role",
32
+ "Session",
33
+ "Transport",
34
+ "UnixSocketTransport",
35
+ "WayboundDaemonError",
36
+ "launch",
37
+ "launch_async",
38
+ ]
@@ -0,0 +1,190 @@
1
+ """First-class asyncio facade (`async with waybound.launch_async(...) as page:`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from dataclasses import dataclass
7
+ from typing import TYPE_CHECKING
8
+
9
+ from waybound.session import BackendName, LaunchOptions, Session
10
+
11
+ if TYPE_CHECKING:
12
+ from pathlib import Path
13
+ from types import TracebackType
14
+
15
+ from waybound.client import Locator, Page
16
+ from waybound.types import AccessibilityNode, CapturedResponse, KeyModifier, Role
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class AsyncLocator:
21
+ """Async handle to a semantic UI element."""
22
+
23
+ _inner: Locator
24
+
25
+ @property
26
+ def first(self) -> AsyncLocator:
27
+ """Return a locator narrowed to the first matching element (`nth(0)`)."""
28
+ return AsyncLocator(self._inner.first)
29
+
30
+ def nth(self, index: int) -> AsyncLocator:
31
+ """Return a locator narrowed to the zero-based `index`-th matching element."""
32
+ return AsyncLocator(self._inner.nth(index))
33
+
34
+ def get_by_role(
35
+ self, role: Role, *, name: str | None = None, exact: bool = False
36
+ ) -> AsyncLocator:
37
+ """Return a child async locator scoped spatially inside this container element."""
38
+ return AsyncLocator(self._inner.get_by_role(role, name=name, exact=exact))
39
+
40
+ def get_by_text(self, text: str, *, exact: bool = False) -> AsyncLocator:
41
+ """Return a child async locator matching accessible text inside this container element."""
42
+ return AsyncLocator(self._inner.get_by_text(text, exact=exact))
43
+
44
+ async def all(self) -> list[AccessibilityNode]:
45
+ """Return all accessibility nodes matching this locator."""
46
+ return await asyncio.to_thread(self._inner.all)
47
+
48
+ async def count(self) -> int:
49
+ """Return the number of accessibility nodes matching this locator."""
50
+ return await asyncio.to_thread(self._inner.count)
51
+
52
+ async def is_visible(self) -> bool:
53
+ """Return `True` if the matched element exists with positive on-screen bounds."""
54
+ return await asyncio.to_thread(self._inner.is_visible)
55
+
56
+ async def hover(self) -> None:
57
+ """Move the pointer over the resolved element without clicking."""
58
+ await asyncio.to_thread(self._inner.hover)
59
+
60
+ async def wait_for(self, *, timeout_ms: int = 10_000) -> AccessibilityNode:
61
+ """Wait until this element appears in the accessibility tree."""
62
+ return await asyncio.to_thread(self._inner.wait_for, timeout_ms=timeout_ms)
63
+
64
+ async def text_content(self, *, timeout_ms: int = 5_000) -> str | None:
65
+ """Return the accessible name or value text of the resolved element."""
66
+ return await asyncio.to_thread(self._inner.text_content, timeout_ms=timeout_ms)
67
+
68
+ async def input_value(self, *, timeout_ms: int = 5_000) -> str:
69
+ """Return the current editable value of a textbox/input element."""
70
+ return await asyncio.to_thread(self._inner.input_value, timeout_ms=timeout_ms)
71
+
72
+ async def click(self) -> None:
73
+ """Click the resolved element using native OS input."""
74
+ await asyncio.to_thread(self._inner.click)
75
+
76
+ async def fill(self, text: str) -> None:
77
+ """Fill the resolved input element using native keyboard events."""
78
+ await asyncio.to_thread(self._inner.fill, text)
79
+
80
+
81
+ class AsyncPage:
82
+ """Async Playwright-style interface to a controlled browser session."""
83
+
84
+ def __init__(self, inner: Page) -> None:
85
+ self._inner = inner
86
+
87
+ async def url(self) -> str | None:
88
+ """Return the active tab URL from the browser's web area, if available."""
89
+ return await asyncio.to_thread(self._inner.url)
90
+
91
+ async def wait_for_url(self, url_contains: str, *, timeout_ms: int = 10_000) -> str:
92
+ """Poll until the active tab URL contains `url_contains` or `timeout_ms` elapses."""
93
+ return await asyncio.to_thread(
94
+ self._inner.wait_for_url, url_contains, timeout_ms=timeout_ms
95
+ )
96
+
97
+ async def goto(self, url: str) -> None:
98
+ """Navigate the active browser tab to `url` via native OS shortcut."""
99
+ await asyncio.to_thread(self._inner.goto, url)
100
+
101
+ async def reload(self) -> None:
102
+ """Reload the active browser tab via native OS shortcut."""
103
+ await asyncio.to_thread(self._inner.reload)
104
+
105
+ async def go_back(self) -> None:
106
+ """Navigate back in browser history via native OS shortcut."""
107
+ await asyncio.to_thread(self._inner.go_back)
108
+
109
+ async def go_forward(self) -> None:
110
+ """Navigate forward in browser history via native OS shortcut."""
111
+ await asyncio.to_thread(self._inner.go_forward)
112
+
113
+ async def scroll(self, *, delta_x: float = 0.0, delta_y: float = -300.0) -> None:
114
+ """Scroll the viewport by `(delta_x, delta_y)` pixels."""
115
+ await asyncio.to_thread(self._inner.scroll, delta_x=delta_x, delta_y=delta_y)
116
+
117
+ async def press(self, key: str, *, modifiers: tuple[KeyModifier, ...] = ()) -> None:
118
+ """Emit a native key press."""
119
+ await asyncio.to_thread(self._inner.press, key, modifiers=modifiers)
120
+
121
+ async def snapshot_tree(self) -> list[AccessibilityNode]:
122
+ """Return a snapshot of the live web-content accessibility tree."""
123
+ return await asyncio.to_thread(self._inner.snapshot_tree)
124
+
125
+ async def captured_responses(
126
+ self, *, url_contains: str | None = None
127
+ ) -> list[CapturedResponse]:
128
+ """Return passively captured HTTP responses, optionally filtered by URL substring."""
129
+ return await asyncio.to_thread(self._inner.captured_responses, url_contains=url_contains)
130
+
131
+ async def wait_for_response(
132
+ self, url_contains: str, *, timeout_ms: int = 10_000
133
+ ) -> CapturedResponse:
134
+ """Wait until a passively decrypted HTTP response matches `url_contains`."""
135
+ return await asyncio.to_thread(
136
+ self._inner.wait_for_response, url_contains, timeout_ms=timeout_ms
137
+ )
138
+
139
+ async def screenshot(self, path: Path | str | None = None) -> bytes:
140
+ """Capture a native OS PNG screenshot of the browser window and return PNG bytes."""
141
+ return await asyncio.to_thread(self._inner.screenshot, path)
142
+
143
+ def get_by_role(
144
+ self, role: Role, *, name: str | None = None, exact: bool = False
145
+ ) -> AsyncLocator:
146
+ """Return an async locator targeting an element by its semantic role."""
147
+ return AsyncLocator(self._inner.get_by_role(role, name=name, exact=exact))
148
+
149
+ def get_by_text(self, text: str, *, exact: bool = False) -> AsyncLocator:
150
+ """Return an async locator matching an element by its accessible text."""
151
+ return AsyncLocator(self._inner.get_by_text(text, exact=exact))
152
+
153
+
154
+ class AsyncSession:
155
+ """Async context manager wrapping [`Session`] without blocking the event loop."""
156
+
157
+ def __init__(self, options: LaunchOptions | None = None) -> None:
158
+ self._session = Session(options)
159
+
160
+ async def __aenter__(self) -> AsyncPage:
161
+ try:
162
+ page = await asyncio.to_thread(self._session.__enter__)
163
+ except BaseException:
164
+ await asyncio.to_thread(self._session.close)
165
+ raise
166
+ return AsyncPage(page)
167
+
168
+ async def __aexit__(
169
+ self,
170
+ exc_type: type[BaseException] | None,
171
+ exc_val: BaseException | None,
172
+ exc_tb: TracebackType | None,
173
+ ) -> None:
174
+ await asyncio.to_thread(self._session.__exit__, exc_type, exc_val, exc_tb)
175
+
176
+
177
+ def launch_async(
178
+ options: LaunchOptions | None = None,
179
+ *,
180
+ backend: BackendName = "mock",
181
+ launch_chrome: bool = False,
182
+ url: str | None = None,
183
+ ) -> AsyncSession:
184
+ """Create an `AsyncSession` context manager for `async with` browser automation."""
185
+ resolved = (
186
+ options
187
+ if options is not None
188
+ else LaunchOptions(backend=backend, launch_chrome=launch_chrome, url=url)
189
+ )
190
+ return AsyncSession(resolved)
waybound/binary.py ADDED
@@ -0,0 +1,182 @@
1
+ """Prebuilt `waybound-daemon` release artifact discovery and SHA-256 verified downloader."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import os
7
+ import platform
8
+ import re
9
+ import sys
10
+ import tarfile
11
+ import tempfile
12
+ import urllib.request
13
+ from pathlib import Path
14
+
15
+ DEFAULT_REPO = "Sekinal/waybound"
16
+ DEFAULT_VERSION = "v0.2.2"
17
+ _SAFE_VERSION_RE = re.compile(r"^[A-Za-z0-9._-]+$")
18
+ _SAFE_REPO_RE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$")
19
+ _SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
20
+ _DOWNLOAD_TIMEOUT_S = 60.0
21
+ _MAX_TARBALL_BYTES = 100 * 1024 * 1024
22
+ _MAX_BINARY_BYTES = 100 * 1024 * 1024
23
+ _MAX_SHA_BYTES = 4096
24
+ _CHUNK_BYTES = 65536
25
+
26
+
27
+ def _daemon_filename() -> str:
28
+ return "waybound-daemon.exe" if sys.platform == "win32" else "waybound-daemon"
29
+
30
+
31
+ def platform_artifact_name() -> str:
32
+ """Return the GitHub Release artifact base name for the current host OS/arch."""
33
+ machine = platform.machine().lower()
34
+ if sys.platform == "darwin" and machine in ("arm64", "aarch64"):
35
+ return "waybound-daemon-macos-arm64"
36
+ if sys.platform.startswith("linux"):
37
+ if machine in ("x86_64", "amd64"):
38
+ return "waybound-daemon-linux-x86_64"
39
+ if machine in ("aarch64", "arm64"):
40
+ return "waybound-daemon-linux-arm64"
41
+ if sys.platform == "win32" and machine in ("x86_64", "amd64"):
42
+ return "waybound-daemon-windows-x86_64"
43
+ msg = (
44
+ f"no prebuilt waybound-daemon binary for {sys.platform}/{machine}; "
45
+ "build with `cargo build --release`"
46
+ )
47
+ raise RuntimeError(msg)
48
+
49
+
50
+ def cached_daemon_path(version: str = DEFAULT_VERSION) -> Path:
51
+ """Return the local user-cache path for a downloaded `waybound-daemon` binary."""
52
+ if not _SAFE_VERSION_RE.match(version) or version in (".", ".."):
53
+ msg = f"invalid version tag: {version!r}"
54
+ raise ValueError(msg)
55
+ return Path.home() / ".cache" / "waybound" / version / _daemon_filename()
56
+
57
+
58
+ def find_cached_daemon() -> Path | None:
59
+ """Locate the default or most recently installed cached `waybound-daemon` binary."""
60
+ default_path = cached_daemon_path()
61
+ if default_path.exists():
62
+ return default_path
63
+
64
+ cache_root = Path.home() / ".cache" / "waybound"
65
+ if not cache_root.is_dir():
66
+ return None
67
+
68
+ bin_name = _daemon_filename()
69
+ candidates = [p for p in cache_root.glob(f"*/{bin_name}") if p.is_file()]
70
+ if not candidates:
71
+ return None
72
+ candidates.sort(key=lambda p: p.stat().st_mtime, reverse=True)
73
+ return candidates[0]
74
+
75
+
76
+ def _download_bounded(url: str, dest: Path, *, max_bytes: int) -> str:
77
+ """Download an HTTPS URL to `dest` with a timeout and size cap; return hex SHA-256."""
78
+ if not url.startswith("https://"):
79
+ msg = f"refusing non-HTTPS download URL: {url!r}"
80
+ raise ValueError(msg)
81
+
82
+ digest = hashlib.sha256()
83
+ total = 0
84
+ with (
85
+ urllib.request.urlopen(url, timeout=_DOWNLOAD_TIMEOUT_S) as resp, # noqa: S310
86
+ dest.open("wb") as out,
87
+ ):
88
+ while True:
89
+ chunk = resp.read(_CHUNK_BYTES)
90
+ if not chunk:
91
+ break
92
+ total += len(chunk)
93
+ if total > max_bytes:
94
+ msg = f"download exceeded maximum allowed size ({max_bytes} bytes): {url}"
95
+ raise RuntimeError(msg)
96
+ digest.update(chunk)
97
+ out.write(chunk)
98
+ return digest.hexdigest().lower()
99
+
100
+
101
+ def _extract_and_install(tar_path: Path, dest: Path) -> None:
102
+ """Extract `waybound-daemon` from `tar_path` and atomically install to `dest`."""
103
+ bin_name = _daemon_filename()
104
+ valid_names = (bin_name, f"./{bin_name}")
105
+ with tarfile.open(tar_path, "r:gz") as archive:
106
+ member = next((m for m in archive.getmembers() if m.name in valid_names), None)
107
+ if member is None or not member.isfile():
108
+ msg = "archive missing regular file waybound-daemon"
109
+ raise RuntimeError(msg)
110
+ if member.size > _MAX_BINARY_BYTES:
111
+ msg = f"extracted binary exceeds size cap ({_MAX_BINARY_BYTES} bytes)"
112
+ raise RuntimeError(msg)
113
+ extracted = archive.extractfile(member)
114
+ if extracted is None:
115
+ msg = "archive missing waybound-daemon binary"
116
+ raise RuntimeError(msg)
117
+ with extracted:
118
+ data = extracted.read(_MAX_BINARY_BYTES + 1)
119
+ if len(data) > _MAX_BINARY_BYTES:
120
+ msg = f"extracted binary exceeds size cap ({_MAX_BINARY_BYTES} bytes)"
121
+ raise RuntimeError(msg)
122
+
123
+ staged_fd, staged_name = tempfile.mkstemp(prefix=".waybound-daemon-", dir=dest.parent)
124
+ staged_path = Path(staged_name)
125
+ try:
126
+ with os.fdopen(staged_fd, "wb") as handle:
127
+ handle.write(data)
128
+ staged_path.chmod(0o755)
129
+ staged_path.replace(dest)
130
+ except BaseException:
131
+ staged_path.unlink(missing_ok=True)
132
+ raise
133
+
134
+
135
+ def download_daemon_binary(
136
+ *,
137
+ version: str = DEFAULT_VERSION,
138
+ repo: str = DEFAULT_REPO,
139
+ force: bool = False,
140
+ ) -> Path:
141
+ """Download, SHA-256 verify, and install the prebuilt `waybound-daemon` binary."""
142
+ if not _SAFE_REPO_RE.match(repo):
143
+ msg = f"invalid GitHub repository slug: {repo!r}"
144
+ raise ValueError(msg)
145
+ owner, repo_name = repo.split("/", 1)
146
+ if owner in (".", "..") or repo_name in (".", ".."):
147
+ msg = f"invalid GitHub repository slug: {repo!r}"
148
+ raise ValueError(msg)
149
+
150
+ dest = cached_daemon_path(version)
151
+ if dest.exists() and not force:
152
+ return dest
153
+
154
+ artifact = platform_artifact_name()
155
+ base_url = f"https://github.com/{repo}/releases/download/{version}"
156
+ tar_url = f"{base_url}/{artifact}.tar.gz"
157
+ sha_url = f"{base_url}/{artifact}.tar.gz.sha256"
158
+
159
+ dest.parent.mkdir(parents=True, exist_ok=True)
160
+ with tempfile.TemporaryDirectory(prefix="waybound-dl-") as tmp:
161
+ tmp_dir = Path(tmp)
162
+ tar_path = tmp_dir / f"{artifact}.tar.gz"
163
+ sha_path = tmp_dir / f"{artifact}.tar.gz.sha256"
164
+
165
+ actual_sha = _download_bounded(tar_url, tar_path, max_bytes=_MAX_TARBALL_BYTES)
166
+ _download_bounded(sha_url, sha_path, max_bytes=_MAX_SHA_BYTES)
167
+
168
+ sha_tokens = sha_path.read_text(encoding="utf-8").strip().split()
169
+ expected_sha = sha_tokens[0].lower() if sha_tokens else ""
170
+ if not _SHA256_RE.match(expected_sha):
171
+ msg = f"invalid SHA-256 checksum file for {artifact}.tar.gz"
172
+ raise RuntimeError(msg)
173
+
174
+ if actual_sha != expected_sha:
175
+ msg = (
176
+ f"SHA-256 mismatch for {artifact}.tar.gz: expected {expected_sha}, got {actual_sha}"
177
+ )
178
+ raise RuntimeError(msg)
179
+
180
+ _extract_and_install(tar_path, dest)
181
+
182
+ return dest
waybound/cli.py ADDED
@@ -0,0 +1,89 @@
1
+ """CLI utilities for `waybound` (`waybound doctor`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import platform
6
+ import shutil
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from waybound.binary import DEFAULT_VERSION, download_daemon_binary
11
+ from waybound.session import _resolve_daemon_binary
12
+
13
+
14
+ def _check_chrome() -> str:
15
+ candidates = (
16
+ [
17
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
18
+ "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
19
+ ]
20
+ if sys.platform == "darwin"
21
+ else ["/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/usr/bin/chromium"]
22
+ )
23
+ for path in candidates:
24
+ if Path(path).exists():
25
+ return f"ok ({path})"
26
+ return "missing (install official Google Chrome or set WAYBOUND_CHROME_BIN)"
27
+
28
+
29
+ def _check_daemon() -> str:
30
+ try:
31
+ resolved = _resolve_daemon_binary(None)
32
+ except FileNotFoundError:
33
+ return "missing (run `cargo build --workspace` or install prebuilt binary)"
34
+ return f"ok ({resolved})"
35
+
36
+
37
+ def _check_tshark() -> str:
38
+ tshark = shutil.which("tshark")
39
+ if tshark is None:
40
+ return "missing (optional: install tshark for passive SSLKEYLOGFILE capture)"
41
+ return f"ok ({tshark})"
42
+
43
+
44
+ def _check_android() -> str:
45
+ adb = shutil.which("adb")
46
+ waydroid = shutil.which("waydroid")
47
+ if adb is None:
48
+ return "missing adb (optional: required only for --backend android)"
49
+ wd_status = f", waydroid={waydroid}" if waydroid else " (waydroid not installed)"
50
+ return f"ok (adb={adb}{wd_status})"
51
+
52
+
53
+ def run_doctor() -> dict[str, str]:
54
+ """Collect environment readiness diagnostics for `waybound`."""
55
+ return {
56
+ "platform": f"{platform.system()} {platform.machine()}",
57
+ "python": platform.python_version(),
58
+ "daemon": _check_daemon(),
59
+ "chrome": _check_chrome(),
60
+ "tshark": _check_tshark(),
61
+ "android": _check_android(),
62
+ }
63
+
64
+
65
+ def main(argv: list[str] | None = None) -> int:
66
+ """Entry point for the `waybound` CLI."""
67
+ args = sys.argv[1:] if argv is None else argv
68
+ if not args or args[0] == "doctor":
69
+ report = run_doctor()
70
+ for key, value in report.items():
71
+ sys.stdout.write(f"{key:>10}: {value}\n")
72
+ return 0
73
+
74
+ if args[0] == "fetch":
75
+ version = args[1] if len(args) > 1 else DEFAULT_VERSION
76
+ try:
77
+ path = download_daemon_binary(version=version)
78
+ except (RuntimeError, ValueError, OSError) as exc:
79
+ sys.stderr.write(f"error: {exc}\n")
80
+ return 1
81
+ sys.stdout.write(f"Installed waybound-daemon ({version}) -> {path}\n")
82
+ return 0
83
+
84
+ sys.stderr.write(f"usage: waybound [doctor|fetch [version]] (unknown command: {args[0]})\n")
85
+ return 2
86
+
87
+
88
+ if __name__ == "__main__":
89
+ raise SystemExit(main())
waybound/client.py ADDED
@@ -0,0 +1,177 @@
1
+ """Ergonomic Playwright-style client facade for waybound."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tempfile
6
+ import time
7
+ from dataclasses import dataclass, replace
8
+ from pathlib import Path
9
+ from typing import TYPE_CHECKING
10
+
11
+ from waybound.transport import WayboundDaemonError
12
+ from waybound.types import AccessibilityNode, CapturedResponse, KeyModifier, LocatorQuery, Role
13
+
14
+ if TYPE_CHECKING:
15
+ from waybound.types import Transport
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class Locator:
20
+ """Lazy handle to a semantic UI element."""
21
+
22
+ _transport: Transport
23
+ query: LocatorQuery
24
+
25
+ @property
26
+ def first(self) -> Locator:
27
+ """Return a locator narrowed to the first matching element (`nth(0)`)."""
28
+ return self.nth(0)
29
+
30
+ def nth(self, index: int) -> Locator:
31
+ """Return a locator narrowed to the zero-based `index`-th matching element."""
32
+ if index < 0:
33
+ msg = f"nth index must be non-negative, got {index}"
34
+ raise ValueError(msg)
35
+ return Locator(_transport=self._transport, query=replace(self.query, nth=index))
36
+
37
+ def get_by_role(self, role: Role, *, name: str | None = None, exact: bool = False) -> Locator:
38
+ """Return a child locator scoped spatially inside this container element."""
39
+ return Locator(
40
+ _transport=self._transport,
41
+ query=LocatorQuery(role=role, name=name, exact=exact, within=self.query),
42
+ )
43
+
44
+ def get_by_text(self, text: str, *, exact: bool = False) -> Locator:
45
+ """Return a child locator matching accessible text inside this container element."""
46
+ return Locator(
47
+ _transport=self._transport,
48
+ query=LocatorQuery(role=None, name=text, exact=exact, within=self.query),
49
+ )
50
+
51
+ def all(self) -> list[AccessibilityNode]:
52
+ """Return all accessibility nodes matching this locator."""
53
+ return self._transport.locate_all(self.query)
54
+
55
+ def count(self) -> int:
56
+ """Return the number of accessibility nodes matching this locator."""
57
+ return len(self.all())
58
+
59
+ def is_visible(self) -> bool:
60
+ """Return `True` if the matched element exists with positive on-screen bounds."""
61
+ matches = self.all()
62
+ if self.query.nth >= len(matches):
63
+ return False
64
+ b = matches[self.query.nth].bounds
65
+ return b.width > 0.0 and b.height > 0.0
66
+
67
+ def hover(self) -> None:
68
+ """Move the pointer over the resolved element using native OS input without clicking."""
69
+ self._transport.hover(self.query)
70
+
71
+ def wait_for(self, *, timeout_ms: int = 10_000) -> AccessibilityNode:
72
+ """Wait until this element appears in the accessibility tree."""
73
+ return self._transport.wait_for(self.query, timeout_ms=timeout_ms)
74
+
75
+ def text_content(self, *, timeout_ms: int = 5_000) -> str | None:
76
+ """Return the accessible name or value text of the resolved element."""
77
+ node = self.wait_for(timeout_ms=timeout_ms)
78
+ return node.name if node.name is not None else node.value
79
+
80
+ def input_value(self, *, timeout_ms: int = 5_000) -> str:
81
+ """Return the current editable value of a textbox/input element."""
82
+ node = self.wait_for(timeout_ms=timeout_ms)
83
+ return node.value or ""
84
+
85
+ def click(self) -> None:
86
+ """Click the resolved element using native OS input."""
87
+ self._transport.click(self.query)
88
+
89
+ def fill(self, text: str) -> None:
90
+ """Fill the resolved input element using native keyboard events."""
91
+ self._transport.fill(self.query, text)
92
+
93
+
94
+ class Page:
95
+ """High-level semantic interface to a controlled browser session."""
96
+
97
+ def __init__(self, transport: Transport) -> None:
98
+ self._transport = transport
99
+
100
+ def url(self) -> str | None:
101
+ """Return the active tab URL from the browser's web area, if available."""
102
+ return self._transport.current_url()
103
+
104
+ def wait_for_url(self, url_contains: str, *, timeout_ms: int = 10_000) -> str:
105
+ """Poll until the active tab URL contains `url_contains` or `timeout_ms` elapses."""
106
+ needle = url_contains.lower()
107
+ deadline = time.monotonic() + max(0, timeout_ms) / 1000.0
108
+ while True:
109
+ current = self._transport.current_url()
110
+ if current is not None and needle in current.lower():
111
+ return current
112
+ if time.monotonic() >= deadline:
113
+ msg = f"timed out after {timeout_ms}ms waiting for URL containing {url_contains!r}"
114
+ raise WayboundDaemonError("timeout", msg)
115
+ time.sleep(0.075)
116
+
117
+ def goto(self, url: str) -> None:
118
+ """Navigate the active browser tab to `url` via native OS shortcut."""
119
+ self._transport.navigate(url)
120
+
121
+ def reload(self) -> None:
122
+ """Reload the active browser tab via native OS shortcut."""
123
+ self._transport.reload()
124
+
125
+ def go_back(self) -> None:
126
+ """Navigate back in browser history via native OS shortcut."""
127
+ self._transport.go_back()
128
+
129
+ def go_forward(self) -> None:
130
+ """Navigate forward in browser history via native OS shortcut."""
131
+ self._transport.go_forward()
132
+
133
+ def scroll(self, *, delta_x: float = 0.0, delta_y: float = -300.0) -> None:
134
+ """Scroll the viewport by `(delta_x, delta_y)` pixels."""
135
+ self._transport.scroll(delta_x, delta_y)
136
+
137
+ def press(self, key: str, *, modifiers: tuple[KeyModifier, ...] = ()) -> None:
138
+ """Emit a native key press (`enter`, `tab`, `escape`, `backspace`, or single char)."""
139
+ self._transport.press(key, modifiers=modifiers)
140
+
141
+ def snapshot_tree(self) -> list[AccessibilityNode]:
142
+ """Return a snapshot of the live web-content accessibility tree."""
143
+ return self._transport.snapshot_tree()
144
+
145
+ def captured_responses(self, *, url_contains: str | None = None) -> list[CapturedResponse]:
146
+ """Return passively captured HTTP responses, optionally filtered by URL substring."""
147
+ return self._transport.captured_responses(url_contains=url_contains)
148
+
149
+ def wait_for_response(self, url_contains: str, *, timeout_ms: int = 10_000) -> CapturedResponse:
150
+ """Wait until a passively decrypted HTTP response matches `url_contains`."""
151
+ return self._transport.wait_for_response(url_contains, timeout_ms=timeout_ms)
152
+
153
+ def screenshot(self, path: Path | str | None = None) -> bytes:
154
+ """Capture a native OS PNG screenshot of the browser window and return PNG bytes."""
155
+ if path is not None:
156
+ out_path = Path(path).resolve()
157
+ self._transport.screenshot(str(out_path))
158
+ return out_path.read_bytes()
159
+
160
+ with tempfile.TemporaryDirectory(prefix="wb-shot-") as tmp_dir:
161
+ out_path = Path(tmp_dir) / "shot.png"
162
+ self._transport.screenshot(str(out_path))
163
+ return out_path.read_bytes()
164
+
165
+ def get_by_role(self, role: Role, *, name: str | None = None, exact: bool = False) -> Locator:
166
+ """Return a locator targeting an element by its semantic accessibility role."""
167
+ return Locator(
168
+ _transport=self._transport,
169
+ query=LocatorQuery(role=role, name=name, exact=exact),
170
+ )
171
+
172
+ def get_by_text(self, text: str, *, exact: bool = False) -> Locator:
173
+ """Return a locator matching an element by its accessible text."""
174
+ return Locator(
175
+ _transport=self._transport,
176
+ query=LocatorQuery(role=None, name=text, exact=exact),
177
+ )