Stealth Chromium that passes every bot detection test. Drop-in Playwright replacement with source-level fingerprint patches. 50+ tests passed.
Python ai-agentsanti-detectantidetect-browserbot-detectionbrowser-automationcaptcha-bypasschromiumcloudflarecloudflare-bypassfingerprintheadless-browserplaywrightpuppeteerpythonrecaptchaseleniumstealth-browserundetectedweb-scrapingwebscraping
fix(humanize): one engine for every action (Python, JS, .NET) + Puppeteer fixes (#578)
lilosd4924d9575c8
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 1f5aa28..e19e6ea 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -33,6 +33,29 @@ jobs:- name: Run testsrun: cd js && npm test+ javascript-browser:+ # Humanize engine + Puppeteer tests against the real CloakBrowser binary.+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0+ with:+ node-version: 22+ - name: Install and build+ run: cd js && npm install && npm run build+ - name: Download the binary+ run: |+ set -o pipefail+ cd js+ path=$(node -e "import('./dist/index.js').then(async m => console.log(await m.ensureBinary()))" | tail -1)+ # Without a binary the browser suites skip and the job would pass having tested nothing.+ test -x "$path" || { echo "::error::binary download failed (got: '$path')"; exit 1; }+ echo "CLOAKBROWSER_BINARY_PATH=$path" >> "$GITHUB_ENV"+ - name: Install browser system deps+ run: cd js && npx playwright-core install-deps chromium+ - name: Run real-browser tests+ run: cd js && xvfb-run -a npx vitest run tests/humanizeEngine.test.ts tests/humanizePuppeteer.test.ts+dotnet:runs-on: ubuntu-lateststeps:diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 70fd954..ab8ed3a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,20 @@ Changes are tagged: **[wrapper]** for Python/JS wrapper, **[binary]** for Chromi- **[wrapper]** `cloakserve`: a browser launched through `/json/version` or `/json/list` with no WebSocket client attaching now gets idle cleanup, instead of running forever when `--idle-timeout` is set (thanks [@dstosch](https://github.com/dstosch), #558)- **[wrapper]** JavaScript: binary and GeoIP download status messages now go to stderr instead of stdout, so they no longer corrupt MCP stdio servers or tools that parse stdout on first run. Python and .NET already did this.- **[wrapper]** JavaScript: CommonJS `require('cloakbrowser')` now works, including the `cloakbrowser/puppeteer` and `cloakbrowser/human` subpaths. Requires Node 20.19+ or 22.12+ (the npm package's `engines` field now says so).+- **[wrapper]** Python, JavaScript Playwright and .NET: humanized actions now use one engine with full Playwright selector support, for every action on pages, frames, `frame_locator`, locators, element handles, mouse and keyboard (sync and async). `get_by_role`, `>>` chains, `filter(has=/has_text=)`, `:visible`, `nth` and `frame_locator` now work (#522).+- **[wrapper]** Python, JavaScript Playwright and .NET, **behaviour change**: strict mode. An ambiguous locator (`page.locator(".dup").click()`) now raises `strict mode violation` like Playwright instead of silently using the first match. Use `.first` / `.nth()` / a more specific locator.+- **[wrapper]** Python, JavaScript Playwright and .NET, **behaviour change**: errors instead of silent fallbacks. When a humanized action cannot be performed it raises Playwright `Error` / `TimeoutError` with a call log (e.g. `<div id="over"> intercepts pointer events`, `element is outside of the viewport`) instead of falling back to Playwright's own action. Off-viewport elements no longer report the misleading "covered by <none>" (follow-up to #521). The `ActionabilityError` / `Element…Error`, `StealthDomError` and `UnsupportedHumanizeSelectorError` classes stay importable (`cloakbrowser.human`, the JS `human` module, `CloakBrowser.Human`) so existing imports keep working, but actions no longer raise them.+- **[wrapper]** Python and JavaScript Playwright, **behaviour change**: `humanize=True` now requires Playwright 1.53 or newer (Python: `playwright>=1.53`; JS: `playwright-core>=1.53.0`, as before). With an older version, launching with `humanize=True` raises an error that names the installed version instead of running some actions un-humanized.+- **[wrapper]** Python, JavaScript Playwright and .NET: Playwright options are honoured instead of dropped: `button`, `click_count`, `modifiers` (incl. `ControlOrMeta`; held during the move for `hover`), `position`, `delay`, `trial`, `steps`, `scroll="none"`, `force`, `strict`; `mouse.click(button=, click_count=)`, `mouse.move(steps=)`. Timeouts follow `set_default_timeout` / context defaults, and `timeout=0` means no limit.+- **[wrapper]** Python, JavaScript Playwright and .NET, **behaviour change**: value fields and `select_option()` are operated like a person, with trusted input events only. Date/time/datetime-local/month/week inputs are typed part by part in whatever order the browser locale shows; sliders are clicked near the target value and nudged with arrow keys; dropdowns are opened with a click and moved with arrow keys + Enter (on a macOS host, whose native dropdown ignores arrow keys, the option is picked by typing its label); list boxes get option clicks (Ctrl/Cmd to add). `<input type=color>` opens a native colour dialog that cannot be driven, so `fill()` on it raises (use `page._original.fill`; .NET: `Humanize.Unwrap(page).FillAsync`). Checkboxes, radios, files etc. raise `Input of type "…" cannot be filled`; non-numeric text into `type=number` raises. Simulated typos are skipped in number/email/password/tel/url fields, and a typo the page rejects (input masks) is no longer "corrected" by deleting a real character.+- **[wrapper]** Python, JavaScript Playwright and .NET, **behaviour change**: fields are focused by scrolling to them and clicking; an element that can never be brought on screen (e.g. at negative offsets) fails with `element is outside of the viewport`. `press()` / `type()` still send the keys when the click does not move focus (a `<canvas>`, document-level key handlers), like Playwright.+- **[wrapper]** Python, JavaScript Playwright and .NET: select-all, `ControlOrMeta` and the caret follow the browser persona (`--fingerprint-platform=macos` uses Meta), not the host OS, so `fill()` no longer appends under a macOS persona. `type()` / `press_sequentially()` continue at the end of existing text on every persona.+- **[wrapper]** Python, JavaScript Playwright and .NET: frames are scrolled with the wheel (also below an iframe's own fold), clicks in frames are hit-tested through every ancestor `<iframe>`, double clicks emit a real `detail=1, 2` sequence, uppercase typos are typed with Shift, `handle.press()` focuses its element, `check()` keeps the cursor in place and honours `human_config`, a target replaced or removed while the cursor travels is never pressed, an element handle whose page navigated raises `not attached` right away instead of acting on the new page, and element handles work when a parent and child share the same box (a link wrapping an image, a list item filled by its link). `scroll_overshoot_chance` / `scroll_overshoot_px` keep working.+- **[wrapper]** Python, **removed**: `scroll_to_element` and `human_scroll_into_view` (scrolling is part of each action), the `async_human_move` / `async_human_click` / `async_human_idle` / `async_human_type` / `async_scroll_to_element` / `async_human_scroll_into_view` helpers, the `RawMouse` / `RawKeyboard` / `AsyncRawMouse` / `AsyncRawKeyboard` re-exports from `cloakbrowser.human`, and `ensure_actionable` / `ensure_stable` / `check_pointer_events` (+ `_handle` and `async_` variants, `CHECKS_*`). Use the humanized Playwright actions (`page.click()`, `locator.scroll_into_view_if_needed()` …) instead.+- **[wrapper]** JavaScript Playwright: the per-call options use Playwright's names (`clickCount`, `modifiers`, `position`, `trial`, `force`, `steps`, `timeout`); HumanConfig overrides go in `human_config` (flat HumanConfig keys in the options object keep working). **Removed**: `patchSingleElementHandle` (every ElementHandle is humanized automatically), `scrollToElement` and `humanScrollIntoView` (scrolling is part of each action).+- **[wrapper]** .NET: `Humanize = true` now runs on the same engine for `IPage`, `IFrame`, `ILocator` (any shape: `GetByRole`, `>>`, `Filter`, `FrameLocator`, `ContentFrame`), `IElementHandle`, `IMouse` and `IKeyboard`. `FrameLocator()`, `QuerySelector(All)Async`, `WaitForSelectorAsync`, `ElementHandle(s)Async`, `FrameElementAsync`, `ContentFrameAsync` and `OwnerFrameAsync` now return humanized objects. Mouse `DownAsync`/`UpAsync`/`WheelAsync` and keyboard `DownAsync`/`UpAsync`/`PressAsync`/`InsertTextAsync` are passed through 1:1, as in Python/JS. Failures throw `PlaywrightException` / `System.TimeoutException` with a call log. The standalone `Actionability` checks (`EnsureActionableAsync`, `EnsureStableAsync`, `CheckPointerEventsAsync`, `…HandleAsync`, `Checks*`), `HumanScroll` / `ScrollResult` / `IRawScrollPage` and `IsolatedWorld` keep their public signatures; `Actionability` now accepts any Playwright selector and still throws the typed errors. The explicit `HumanPage` API is unchanged and uses the same engine; `HumanActionOptions.Timeout = 0` means no limit. **Removed**: the unused public `CloakBrowser.Human.StealthStatus` enum.+- **[wrapper]** JavaScript Puppeteer and .NET `HumanScroll`: smooth wheel scrolling no longer sends an occasional empty `(0, 0)` wheel event at the end of a scroll.+- **[wrapper]** JavaScript Puppeteer: `frame.click` / `hover` / `type` / `select` / `focus` / `tap` now resolve the selector inside that frame (they used to look it up in the top document and fail) (#184). `page.click`, `elementHandle.click` and `mouse.click` honour `button` (right / middle clicks were sent as left) and `count` / `clickCount` with a real `detail = 1, 2` sequence, and `delay` as the hold time. Uppercase typos are typed with Shift. Known gap: a target below an iframe's own scroll fold is not scrolled into view.---diff --git a/cloakbrowser/human/__init__.py b/cloakbrowser/human/__init__.pyindex 242dbb0..8ccafa9 100644--- a/cloakbrowser/human/__init__.py+++ b/cloakbrowser/human/__init__.py@@ -1,3083 +1,52 @@"""Human-like behavioral layer for cloakbrowser.-Activated via humanize=True in launch() / launch_async().-Patches page methods to use Bezier mouse curves, realistic typing, and smooth scrolling.--Stealth-aware (fixes #110):- - Selector state, geometry, and hit-testing stay in a CDP isolated world- - Shift symbol typing uses CDP Input.dispatchKeyEvent for isTrusted=true events- - Unsupported/unavailable isolated reads fail explicitly without DOM-read fallback--Supports both sync and async Playwright APIs.+Activated via ``humanize=True`` in ``launch()`` / ``launch_async()``.++Every humanized action (page, frame, locator, element handle, mouse,+keyboard; sync and async API) runs through one engine (``engine.py``):++* elements are resolved by Playwright's own selector engine running in a CDP+ isolated world per frame (``world.py`` / ``injected.py``) -- full selector+ syntax (role, label, text, ``>>`` chains, filters, frame locators) and+ strict mode;+* scrolling uses mouse-wheel bursts, pointer movement uses Bezier curves,+ every press is preceded by a hit-target check (also through iframes);+* Playwright's options and timeouts are honoured; failures raise Playwright+ ``Error`` / ``TimeoutError`` instead of falling back to Playwright's stock+ actions."""from __future__ import annotations-import json-import logging-import sys-import time-from typing import Any, Optional--from .config import HumanConfig, HumanPreset, resolve_config, merge_config-from .config import rand, rand_range, sleep_ms, async_sleep_ms-from .mouse import RawMouse, human_move, human_click, click_target, human_idle-from .keyboard import RawKeyboard, human_type-from .scroll import scroll_to_element, human_scroll_into_view-from .mouse_async import AsyncRawMouse, async_human_move, async_human_click, async_human_idle-from .keyboard_async import AsyncRawKeyboard, async_human_type-from .scroll_async import async_scroll_to_element, async_human_scroll_into_view-from .actionability import (- ensure_actionable, ensure_stable, check_pointer_events,- ensure_actionable_handle, check_pointer_events_handle,- ActionabilityError, ElementNotAttachedError, ElementNotVisibleError,- ElementNotStableError, ElementNotEnabledError, ElementNotEditableError,- ElementNotReceivingEventsError,- CHECKS_CLICK, CHECKS_HOVER, CHECKS_INPUT, CHECKS_FOCUS, CHECKS_CHECK,-)-from .actionability_async import (- async_ensure_actionable, async_ensure_stable, async_check_pointer_events,- async_ensure_actionable_handle, async_check_pointer_events_handle,-)-from .stealth_dom import (- async_eval_parsed, build_snapshot_js, eval_parsed,- NOT_FOUND, OK, UNSUPPORTED,- StealthEvaluationError, StealthWorldUnavailableError,+from .config import HumanConfig, HumanPreset, merge_config, resolve_config+from .engine import CursorState, Human+from .errors import (+ ActionabilityError, ElementNotAttachedError, ElementNotEditableError,+ ElementNotEnabledError, ElementNotReceivingEventsError, ElementNotStableError,+ ElementNotVisibleError, ElementTargetChangedError,+ StealthDomError, StealthEvaluationError, StealthWorldUnavailableError,UnsupportedHumanizeSelectorError,)+from .keyboard import human_type+from .mouse import click_target, human_click, human_idle, human_move+from .patch import (+ patch_browser, patch_browser_async, patch_context, patch_context_async,+ patch_page, patch_page_async,+)-_SELECT_ALL = "Meta+a" if sys.platform == "darwin" else "Control+a"---def _keyboard_press_kwargs(kwargs: dict[str, Any], default_delay: Optional[float] = None) -> dict[str, Any]:- """Return only options accepted by Playwright's Keyboard.press()."""- if "delay" in kwargs:- return {"delay": kwargs["delay"]}- if default_delay is not None:- return {"delay": default_delay}- return {}-+# Backwards-compatible name used by callers that build pages manually.+_CursorState = CursorState__all__ = ["patch_browser", "patch_context", "patch_page","patch_browser_async", "patch_context_async", "patch_page_async",- "HumanConfig", "resolve_config", "merge_config",+ "HumanConfig", "HumanPreset", "resolve_config", "merge_config", "CursorState", "Human","human_move", "human_click", "click_target", "human_idle",- "human_type", "scroll_to_element", "human_scroll_into_view",+ "human_type",+ # Error classes kept for API compatibility (actions raise Playwright errors).+ "ActionabilityError", "ElementNotAttachedError", "ElementNotVisibleError",+ "ElementNotStableError", "ElementNotEnabledError", "ElementNotEditableError",+ "ElementNotReceivingEventsError", "ElementTargetChangedError",+ "StealthDomError", "UnsupportedHumanizeSelectorError",+ "StealthWorldUnavailableError", "StealthEvaluationError",]--logger = logging.getLogger("cloakbrowser.human")---# ============================================================================-# CDP Isolated World — stealth DOM evaluation-# ============================================================================--class _SyncIsolatedWorld:- """Manages a CDP isolated execution context for DOM reads (sync).-- Produces clean Error.stack traces (no 'eval at evaluate :302:')- and is invisible to querySelector monkey-patches in the main world.- Context ID is invalidated on navigation and auto-recreated on next call.- """-- __slots__ = ("_page", "_cdp", "_context_id")-- def __init__(self, page: Any):- self._page = page- self._cdp: Any = None- self._context_id: Optional[int] = None-- def _ensure_cdp(self) -> Any:- if self._cdp is None:- self._cdp = self._page.context.new_cdp_session(self._page)- return self._cdp-- def _create_world(self) -> int:- cdp = self._ensure_cdp()- tree = cdp.send("Page.getFrameTree")- frame_id = tree["frameTree"]["frame"]["id"]- result = cdp.send("Page.createIsolatedWorld", {- "frameId": frame_id,- "worldName": "",- "grantUniveralAccess": True,- })- self._context_id = result["executionContextId"]- return self._context_id-- def evaluate(self, expression: str) -> Any:- """Evaluate JS in isolated world. Auto-recreates on stale context."""- if self._context_id is None:- self._create_world()-- for attempt in range(2):- try:- result = self._cdp.send("Runtime.evaluate", {- "expression": expression,- "contextId": self._context_id,- "returnByValue": True,- })- if "exceptionDetails" in result:- if attempt == 0:- self._create_world()- continue- return None- return result.get("result", {}).get("value")- except Exception:- if attempt == 0:- self._context_id = None- try:- self._create_world()- except Exception:- return None- continue- return None- return None-- def invalidate(self) -> None:- """Mark context as stale — call after navigation."""- self._context_id = None-- def get_cdp_session(self) -> Any:- """Get the underlying CDP session (reused for Input.dispatchKeyEvent)."""- return self._ensure_cdp()---class _AsyncIsolatedWorld:- """Manages a CDP isolated execution context for DOM reads (async).-- Same as _SyncIsolatedWorld but uses await for all CDP calls.- """-- __slots__ = ("_page", "_cdp", "_context_id")-- def __init__(self, page: Any):- self._page = page- self._cdp: Any = None- self._context_id: Optional[int] = None-- async def _ensure_cdp(self) -> Any:- if self._cdp is None:- self._cdp = await self._page.context.new_cdp_session(self._page)- return self._cdp-- async def _create_world(self) -> int:- cdp = await self._ensure_cdp()- tree = await cdp.send("Page.getFrameTree")- frame_id = tree["frameTree"]["frame"]["id"]- result = await cdp.send("Page.createIsolatedWorld", {- "frameId": frame_id,- "worldName": "",- "grantUniveralAccess": True,- })- self._context_id = result["executionContextId"]- return self._context_id-- async def evaluate(self, expression: str) -> Any:- """Evaluate JS in isolated world. Auto-recreates on stale context."""- if self._context_id is None:- await self._create_world()-- for attempt in range(2):- try:- result = await self._cdp.send("Runtime.evaluate", {- "expression": expression,- "contextId": self._context_id,- "returnByValue": True,- })- if "exceptionDetails" in result:- if attempt == 0:- await self._create_world()- continue- return None- return result.get("result", {}).get("value")- except Exception:- if attempt == 0:- self._context_id = None- try:- await self._create_world()- except Exception:- return None- continue- return None- return None-- def invalidate(self) -> None:- """Mark context as stale — call after navigation."""- self._context_id = None-- async def get_cdp_session(self) -> Any:- """Get the underlying CDP session (reused for Input.dispatchKeyEvent)."""- return await self._ensure_cdp()---# ============================================================================-# Cursor state-# ============================================================================--class _CursorState:- __slots__ = ("x", "y", "initialized")-- def __init__(self) -> None:- self.x: float = 0- self.y: float = 0- self.initialized: bool = False---# ============================================================================-# Stealth DOM queries — canonical isolated-world snapshot only-# ============================================================================--def _selector_snapshot(page: Any, selector: str) -> dict:- world = getattr(page, "_stealth_world", None)- if world is None:- raise StealthWorldUnavailableError()- status, data = eval_parsed(world, build_snapshot_js(selector))- if status == OK:- return data- if status == NOT_FOUND:- raise ElementNotAttachedError(selector)- if status == UNSUPPORTED:- raise UnsupportedHumanizeSelectorError(selector)- raise StealthEvaluationError(selector)---async def _async_selector_snapshot(page: Any, selector: str) -> dict:- world = getattr(page, "_stealth_world", None)- if world is None:- raise StealthWorldUnavailableError()- status, data = await async_eval_parsed(world, build_snapshot_js(selector))- if status == OK:- return data- if status == NOT_FOUND:- raise ElementNotAttachedError(selector)- if status == UNSUPPORTED:- raise UnsupportedHumanizeSelectorError(selector)- raise StealthEvaluationError(selector)---def _is_input_element(page: Any, selector: str) -> bool:- return bool(_selector_snapshot(page, selector)["isInput"])---async def _async_is_input_element(page: Any, selector: str) -> bool:- return bool((await _async_selector_snapshot(page, selector))["isInput"])---def _is_selector_focused(page: Any, selector: str) -> bool:- return bool(_selector_snapshot(page, selector)["focused"])---async def _async_is_selector_focused(page: Any, selector: str) -> bool:- return bool((await _async_selector_snapshot(page, selector))["focused"])---# ============================================================================-# Locator class-level patching (sync)-# ============================================================================--_locator_sync_patched = False---def _patch_locator_class_sync():- """Patch all Locator interaction methods to go through humanized page methods."""- global _locator_sync_patched- if _locator_sync_patched:- return- _locator_sync_patched = True-- from playwright.sync_api._generated import Locator-- _orig_fill = Locator.fill- _orig_click = Locator.click- _orig_type = Locator.type- _orig_dblclick = Locator.dblclick- _orig_hover = Locator.hover- _orig_check = Locator.check- _orig_uncheck = Locator.uncheck- _orig_set_checked = Locator.set_checked- _orig_select_option = Locator.select_option- _orig_press = Locator.press- _orig_press_sequentially = Locator.press_sequentially- _orig_tap = Locator.tap- _orig_drag_to = Locator.drag_to- _orig_clear = Locator.clear- _orig_scroll_into_view = getattr(Locator, 'scroll_into_view_if_needed', None)-- def _get_selector(self):- return self._impl_obj._selector-- def _is_humanized(self):- return hasattr(self.page, '_original')-- def _get_cfg(self):- return getattr(self.page, '_human_cfg', None)-- def _route_target(self):- """Resolution target for a humanized locator action (#428).-- Main-frame locators return the Page (unchanged behavior). A locator that- belongs to a *sub-frame* returns that frame's humanized wrapper so the- selector resolves in the frame's own document. Returns ``None`` when the- owning sub-frame is known but not yet humanized, so the caller falls back- to the native Playwright locator method (frame-correct, un-humanized).- """- page = self.page- impl_frame = getattr(getattr(self, "_impl_obj", None), "_frame", None)- if impl_frame is None:- return page- try:- if impl_frame is page.main_frame._impl_obj:- return page- for f in page.frames:- if getattr(f, "_impl_obj", None) is impl_frame:- return f if getattr(f, "_human_patched", False) else None- # Frame not among page.frames (unknown/detached) -> legacy Page path.- return page- except Exception:- return page-- def _forward_kwargs(kwargs):- out = {}- if "timeout" in kwargs:- out["timeout"] = kwargs["timeout"]- if "human_config" in kwargs:- out["human_config"] = kwargs["human_config"]- if "force" in kwargs:- out["force"] = kwargs["force"]- return out-- def _humanized_fill(self, value, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- _orig_fill(self, value, **kwargs)- else:- tgt.fill(_get_selector(self), value, **_forward_kwargs(kwargs))- else:- _orig_fill(self, value, **kwargs)-- def _humanized_click(self, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- _orig_click(self, **kwargs)- else:- tgt.click(_get_selector(self), **_forward_kwargs(kwargs))- else:- _orig_click(self, **kwargs)-- def _humanized_type(self, text, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- _orig_type(self, text, **kwargs)- else:- tgt.type(_get_selector(self), text, **_forward_kwargs(kwargs))- else:- _orig_type(self, text, **kwargs)-- def _humanized_dblclick(self, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- _orig_dblclick(self, **kwargs)- else:- tgt.dblclick(_get_selector(self), **_forward_kwargs(kwargs))- else:- _orig_dblclick(self, **kwargs)-- def _humanized_hover(self, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- _orig_hover(self, **kwargs)- else:- tgt.hover(_get_selector(self), **_forward_kwargs(kwargs))- else:- _orig_hover(self, **kwargs)-- def _humanized_scroll_into_view_if_needed(self, **kwargs):- if _is_humanized(self):- page = self.page- cfg = _get_cfg(self)- cursor = getattr(page, '_human_cursor', None)- raw = getattr(page, '_human_raw_mouse', None)- call_cfg = merge_config(cfg, kwargs.get("human_config")) if cfg else None- if call_cfg is None or cursor is None or raw is None:- if _orig_scroll_into_view is not None:- native_kwargs = {k: v for k, v in kwargs.items() if k != "human_config"}- return _orig_scroll_into_view(self, **native_kwargs)- return- timeout = kwargs.get("timeout", 30000)- try:- _, nx, ny, _ = human_scroll_into_view(- page, raw,- lambda: self.bounding_box(timeout=timeout),- cursor.x, cursor.y, call_cfg,- )- cursor.x = nx- cursor.y = ny- except Exception:- if _orig_scroll_into_view is not None:- native_kwargs = {k: v for k, v in kwargs.items() if k != "human_config"}- _orig_scroll_into_view(self, **native_kwargs)- elif _orig_scroll_into_view is not None:- _orig_scroll_into_view(self, **kwargs)-- def _humanized_check(self, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- _orig_check(self, **kwargs)- return- fwd = _forward_kwargs(kwargs)- cfg = _get_cfg(self)- if cfg and cfg.idle_between_actions:- raw = type("_R", (), {"move": self.page._original.mouse_move})()- human_idle(raw, rand(cfg.idle_between_duration[0], cfg.idle_between_duration[1]), 0, 0, cfg)- selector = _get_selector(self)- checked = _selector_snapshot(tgt, selector)["checked"]- if checked is not True:- tgt.click(selector, **fwd)- else:- _orig_check(self, **kwargs)-- def _humanized_uncheck(self, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- _orig_uncheck(self, **kwargs)- return- fwd = _forward_kwargs(kwargs)- cfg = _get_cfg(self)- if cfg and cfg.idle_between_actions:- raw = type("_R", (), {"move": self.page._original.mouse_move})()- human_idle(raw, rand(cfg.idle_between_duration[0], cfg.idle_between_duration[1]), 0, 0, cfg)- selector = _get_selector(self)- checked = _selector_snapshot(tgt, selector)["checked"]- if checked is True:- tgt.click(selector, **fwd)- else:- _orig_uncheck(self, **kwargs)-- def _humanized_set_checked(self, checked, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- _orig_set_checked(self, checked, **kwargs)- return- fwd = _forward_kwargs(kwargs)- selector = _get_selector(self)- current = _selector_snapshot(tgt, selector)["checked"]- if current is not checked:- tgt.click(selector, **fwd)- else:- _orig_set_checked(self, checked, **kwargs)-- def _humanized_select_option(self, value=None, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- _orig_select_option(self, value, **kwargs)- return- fwd = _forward_kwargs(kwargs)- selector = _get_selector(self)- tgt.hover(selector, **fwd)- sleep_ms(rand(100, 300))- _orig_select_option(self, value, **kwargs)- else:- _orig_select_option(self, value, **kwargs)-- def _humanized_press(self, key, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- _orig_press(self, key, **kwargs)- return- fwd = _forward_kwargs(kwargs)- selector = _get_selector(self)- if not _is_selector_focused(tgt, selector):- tgt.click(selector, **fwd)- sleep_ms(rand(50, 150))- self.page.keyboard.press(key, **_keyboard_press_kwargs(kwargs))- else:- _orig_press(self, key, **kwargs)-- def _humanized_press_sequentially(self, text, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- _orig_press_sequentially(self, text, **kwargs)- return- fwd = _forward_kwargs(kwargs)- selector = _get_selector(self)- if not _is_selector_focused(tgt, selector):- tgt.click(selector, **fwd)- sleep_ms(rand(50, 150))- self.page.keyboard.type(text)- else:- _orig_press_sequentially(self, text, **kwargs)-- def _humanized_tap(self, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- _orig_tap(self, **kwargs)- else:- tgt.click(_get_selector(self), **_forward_kwargs(kwargs))- else:- _orig_tap(self, **kwargs)-- def _humanized_drag_to(self, target, **kwargs):- if _is_humanized(self):- page = self.page- originals = getattr(page, '_original', None)- src_box = self.bounding_box()- tgt_box = target.bounding_box()- if src_box and tgt_box and originals:- sx = src_box['x'] + src_box['width'] / 2- sy = src_box['y'] + src_box['height'] / 2- tx = tgt_box['x'] + tgt_box['width'] / 2- ty = tgt_box['y'] + tgt_box['height'] / 2- page.mouse.move(sx, sy)- sleep_ms(rand(100, 200))- originals.mouse_down()- sleep_ms(rand(80, 150))- page.mouse.move(tx, ty)- sleep_ms(rand(80, 150))- originals.mouse_up()- else:- _orig_drag_to(self, target, **kwargs)- else:- _orig_drag_to(self, target, **kwargs)-- def _humanized_clear(self, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- _orig_clear(self, **kwargs)- return- fwd = _forward_kwargs(kwargs)- selector = _get_selector(self)- if not _is_selector_focused(tgt, selector):- tgt.click(selector, **fwd)- sleep_ms(rand(50, 100))- self.page.keyboard.press(_SELECT_ALL)- sleep_ms(rand(30, 80))- self.page.keyboard.press("Backspace")- else:- _orig_clear(self, **kwargs)-- Locator.fill = _humanized_fill- Locator.click = _humanized_click- Locator.type = _humanized_type- Locator.dblclick = _humanized_dblclick- Locator.hover = _humanized_hover- Locator.check = _humanized_check- Locator.uncheck = _humanized_uncheck- Locator.set_checked = _humanized_set_checked- Locator.select_option = _humanized_select_option- Locator.press = _humanized_press- Locator.press_sequentially = _humanized_press_sequentially- Locator.tap = _humanized_tap- Locator.drag_to = _humanized_drag_to- Locator.clear = _humanized_clear- if _orig_scroll_into_view is not None:- Locator.scroll_into_view_if_needed = _humanized_scroll_into_view_if_needed---# ============================================================================-# Locator class-level patching (async)-# ============================================================================--_locator_async_patched = False---def _patch_locator_class_async():- """Patch all async Locator interaction methods to go through humanized page methods."""- global _locator_async_patched- if _locator_async_patched:- return- _locator_async_patched = True-- from playwright.async_api._generated import Locator as AsyncLocator-- _orig_fill = AsyncLocator.fill- _orig_click = AsyncLocator.click- _orig_type = AsyncLocator.type- _orig_dblclick = AsyncLocator.dblclick- _orig_hover = AsyncLocator.hover- _orig_check = AsyncLocator.check- _orig_uncheck = AsyncLocator.uncheck- _orig_set_checked = AsyncLocator.set_checked- _orig_select_option = AsyncLocator.select_option- _orig_press = AsyncLocator.press- _orig_press_sequentially = AsyncLocator.press_sequentially- _orig_tap = AsyncLocator.tap- _orig_drag_to = AsyncLocator.drag_to- _orig_clear = AsyncLocator.clear- _orig_scroll_into_view = getattr(AsyncLocator, 'scroll_into_view_if_needed', None)-- def _get_selector(self):- return self._impl_obj._selector-- def _is_humanized(self):- return hasattr(self.page, '_original')-- def _get_cfg(self):- return getattr(self.page, '_human_cfg', None)-- def _route_target(self):- """Resolution target for a humanized locator action (#428).-- Main-frame locators return the Page (unchanged behavior). A locator that- belongs to a *sub-frame* returns that frame's humanized wrapper so the- selector resolves in the frame's own document. Returns ``None`` when the- owning sub-frame is known but not yet humanized, so the caller falls back- to the native Playwright locator method (frame-correct, un-humanized).- """- page = self.page- impl_frame = getattr(getattr(self, "_impl_obj", None), "_frame", None)- if impl_frame is None:- return page- try:- if impl_frame is page.main_frame._impl_obj:- return page- for f in page.frames:- if getattr(f, "_impl_obj", None) is impl_frame:- return f if getattr(f, "_human_patched", False) else None- # Frame not among page.frames (unknown/detached) -> legacy Page path.- return page- except Exception:- return page-- def _forward_kwargs(kwargs):- out = {}- if "timeout" in kwargs:- out["timeout"] = kwargs["timeout"]- if "human_config" in kwargs:- out["human_config"] = kwargs["human_config"]- if "force" in kwargs:- out["force"] = kwargs["force"]- return out-- async def _humanized_fill(self, value, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- await _orig_fill(self, value, **kwargs)- else:- await tgt.fill(_get_selector(self), value, **_forward_kwargs(kwargs))- else:- await _orig_fill(self, value, **kwargs)-- async def _humanized_click(self, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- await _orig_click(self, **kwargs)- else:- await tgt.click(_get_selector(self), **_forward_kwargs(kwargs))- else:- await _orig_click(self, **kwargs)-- async def _humanized_type(self, text, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- await _orig_type(self, text, **kwargs)- else:- await tgt.type(_get_selector(self), text, **_forward_kwargs(kwargs))- else:- await _orig_type(self, text, **kwargs)-- async def _humanized_dblclick(self, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- await _orig_dblclick(self, **kwargs)- else:- await tgt.dblclick(_get_selector(self), **_forward_kwargs(kwargs))- else:- await _orig_dblclick(self, **kwargs)-- async def _humanized_hover(self, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- await _orig_hover(self, **kwargs)- else:- await tgt.hover(_get_selector(self), **_forward_kwargs(kwargs))- else:- await _orig_hover(self, **kwargs)-- async def _humanized_scroll_into_view_if_needed(self, **kwargs):- if _is_humanized(self):- page = self.page- cfg = _get_cfg(self)- cursor = getattr(page, '_human_cursor', None)- raw = getattr(page, '_human_raw_mouse', None)- call_cfg = merge_config(cfg, kwargs.get("human_config")) if cfg else None- if call_cfg is None or cursor is None or raw is None:- if _orig_scroll_into_view is not None:- native_kwargs = {k: v for k, v in kwargs.items() if k != "human_config"}- await _orig_scroll_into_view(self, **native_kwargs)- return- timeout = kwargs.get("timeout", 30000)-- async def _get_box():- return await self.bounding_box(timeout=timeout)- try:- _, nx, ny, _ = await async_human_scroll_into_view(- page, raw, _get_box,- cursor.x, cursor.y, call_cfg,- )- cursor.x = nx- cursor.y = ny- except Exception:- if _orig_scroll_into_view is not None:- native_kwargs = {k: v for k, v in kwargs.items() if k != "human_config"}- await _orig_scroll_into_view(self, **native_kwargs)- elif _orig_scroll_into_view is not None:- await _orig_scroll_into_view(self, **kwargs)-- async def _humanized_check(self, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- await _orig_check(self, **kwargs)- return- fwd = _forward_kwargs(kwargs)- cfg = _get_cfg(self)- if cfg and cfg.idle_between_actions:- raw = type("_R", (), {"move": self.page._original.mouse_move})()- await async_human_idle(- raw,- rand(cfg.idle_between_duration[0], cfg.idle_between_duration[1]),- 0, 0, cfg,- )- selector = _get_selector(self)- checked = (await _async_selector_snapshot(tgt, selector))["checked"]- if checked is not True:- await tgt.click(selector, **fwd)- else:- await _orig_check(self, **kwargs)-- async def _humanized_uncheck(self, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- await _orig_uncheck(self, **kwargs)- return- fwd = _forward_kwargs(kwargs)- cfg = _get_cfg(self)- if cfg and cfg.idle_between_actions:- raw = type("_R", (), {"move": self.page._original.mouse_move})()- await async_human_idle(- raw,- rand(cfg.idle_between_duration[0], cfg.idle_between_duration[1]),- 0, 0, cfg,- )- selector = _get_selector(self)- checked = (await _async_selector_snapshot(tgt, selector))["checked"]- if checked is True:- await tgt.click(selector, **fwd)- else:- await _orig_uncheck(self, **kwargs)-- async def _humanized_set_checked(self, checked, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- await _orig_set_checked(self, checked, **kwargs)- return- fwd = _forward_kwargs(kwargs)- selector = _get_selector(self)- current = (await _async_selector_snapshot(tgt, selector))["checked"]- if current is not checked:- await tgt.click(selector, **fwd)- else:- await _orig_set_checked(self, checked, **kwargs)-- async def _humanized_select_option(self, value=None, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- await _orig_select_option(self, value, **kwargs)- return- fwd = _forward_kwargs(kwargs)- selector = _get_selector(self)- await tgt.hover(selector, **fwd)- await async_sleep_ms(rand(100, 300))- await _orig_select_option(self, value, **kwargs)- else:- await _orig_select_option(self, value, **kwargs)-- async def _humanized_press(self, key, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- await _orig_press(self, key, **kwargs)- return- fwd = _forward_kwargs(kwargs)- selector = _get_selector(self)- if not await _async_is_selector_focused(tgt, selector):- await tgt.click(selector, **fwd)- await async_sleep_ms(rand(50, 150))- await self.page.keyboard.press(key, **_keyboard_press_kwargs(kwargs))- else:- await _orig_press(self, key, **kwargs)-- async def _humanized_press_sequentially(self, text, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- await _orig_press_sequentially(self, text, **kwargs)- return- fwd = _forward_kwargs(kwargs)- selector = _get_selector(self)- if not await _async_is_selector_focused(tgt, selector):- await tgt.click(selector, **fwd)- await async_sleep_ms(rand(50, 150))- await self.page.keyboard.type(text)- else:- await _orig_press_sequentially(self, text, **kwargs)-- async def _humanized_tap(self, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- await _orig_tap(self, **kwargs)- else:- await tgt.click(_get_selector(self), **_forward_kwargs(kwargs))- else:- await _orig_tap(self, **kwargs)-- async def _humanized_drag_to(self, target, **kwargs):- if _is_humanized(self):- page = self.page- originals = getattr(page, '_original', None)- src_box = await self.bounding_box()- tgt_box = await target.bounding_box()- if src_box and tgt_box and originals:- sx = src_box['x'] + src_box['width'] / 2- sy = src_box['y'] + src_box['height'] / 2- tx = tgt_box['x'] + tgt_box['width'] / 2- ty = tgt_box['y'] + tgt_box['height'] / 2- await page.mouse.move(sx, sy)- await async_sleep_ms(rand(100, 200))- await originals.mouse_down()- await async_sleep_ms(rand(80, 150))- await page.mouse.move(tx, ty)- await async_sleep_ms(rand(80, 150))- await originals.mouse_up()- else:- await _orig_drag_to(self, target, **kwargs)- else:- await _orig_drag_to(self, target, **kwargs)-- async def _humanized_clear(self, **kwargs):- if _is_humanized(self):- tgt = _route_target(self)- if tgt is None:- await _orig_clear(self, **kwargs)- return- fwd = _forward_kwargs(kwargs)- selector = _get_selector(self)- if not await _async_is_selector_focused(tgt, selector):- await tgt.click(selector, **fwd)- await async_sleep_ms(rand(50, 100))- await self.page.keyboard.press(_SELECT_ALL)- await async_sleep_ms(rand(30, 80))- await self.page.keyboard.press("Backspace")- else:- await _orig_clear(self, **kwargs)-- AsyncLocator.fill = _humanized_fill- AsyncLocator.click = _humanized_click- AsyncLocator.type = _humanized_type- AsyncLocator.dblclick = _humanized_dblclick- AsyncLocator.hover = _humanized_hover- AsyncLocator.check = _humanized_check- AsyncLocator.uncheck = _humanized_uncheck- AsyncLocator.set_checked = _humanized_set_checked- AsyncLocator.select_option = _humanized_select_option- AsyncLocator.press = _humanized_press- AsyncLocator.press_sequentially = _humanized_press_sequentially- AsyncLocator.tap = _humanized_tap- AsyncLocator.drag_to = _humanized_drag_to- AsyncLocator.clear = _humanized_clear- if _orig_scroll_into_view is not None:- AsyncLocator.scroll_into_view_if_needed = _humanized_scroll_into_view_if_needed---# ============================================================================-# SYNC patching-# ============================================================================---def patch_page(page: Any, cfg: HumanConfig, cursor: _CursorState) -> None:- """Replace page methods with human-like implementations (sync)."""- originals = type("Originals", (), {- "click": page.click,- "type": page.type,- "fill": page.fill,- "goto": page.goto,- "hover": page.hover,- "dblclick": page.dblclick,- "select_option": page.select_option,- "mouse_move": page.mouse.move,- "mouse_click": page.mouse.click,- "mouse_wheel": page.mouse.wheel,- "mouse_down": page.mouse.down,- "mouse_up": page.mouse.up,- "keyboard_type": page.keyboard.type,- "keyboard_down": page.keyboard.down,- "keyboard_up": page.keyboard.up,- "keyboard_press": page.keyboard.press,- "keyboard_insert_text": page.keyboard.insert_text,- })()-- page._original = originals- page._human_cfg = cfg- page._human_cursor = cursor-- # --- Stealth infrastructure ---- try:- stealth = _SyncIsolatedWorld(page)- page._stealth_world = stealth- cdp_session = stealth.get_cdp_session()- except Exception:- stealth = None- page._stealth_world = None- cdp_session = None- logger.debug("Could not create CDP session — stealth features disabled")-- if stealth is not None:- # Invalidate the isolated world on any main-frame nav, not just goto,- # so click/form navigations don't leave it bound to a stale doc (#507).- try:- page.on(- "framenavigated",- lambda frame: stealth.invalidate() if frame == page.main_frame else None,- )- except Exception:- logger.debug("Could not wire framenavigated invalidation")-- raw_mouse: RawMouse = type("_RawMouse", (), {- "move": originals.mouse_move,- "down": originals.mouse_down,- "up": originals.mouse_up,- "wheel": originals.mouse_wheel,- })()-- raw_keyboard: RawKeyboard = type("_RawKeyboard", (), {- "down": originals.keyboard_down,- "up": originals.keyboard_up,- "type": originals.keyboard_type,- "insert_text": originals.keyboard_insert_text,- })()-- page._human_raw_mouse = raw_mouse-- def _ensure_cursor_init() -> None:- if not cursor.initialized:- cursor.x = rand(cfg.initial_cursor_x[0], cfg.initial_cursor_x[1])- cursor.y = rand(cfg.initial_cursor_y[0], cfg.initial_cursor_y[1])- originals.mouse_move(cursor.x, cursor.y)- cursor.initialized = True-- def _human_goto(url: str, **kwargs: Any) -> Any:- response = originals.goto(url, **kwargs)- # Invalidate isolated world after navigation (context ID becomes stale)- if stealth is not None:- stealth.invalidate()- return response-- def _human_click(selector: str, **kwargs: Any) -> None:- _ensure_cursor_init()- call_cfg = merge_config(cfg, kwargs.get("human_config"))- timeout = kwargs.get("timeout", 30000)- force = kwargs.get("force", False)- skip_checks = kwargs.pop("_skip_checks", False)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force and not skip_checks:- ensure_actionable(page, selector, CHECKS_CLICK, timeout=_remaining_ms(), force=force)- if call_cfg.idle_between_actions:- human_idle(raw_mouse, rand(call_cfg.idle_between_duration[0], call_cfg.idle_between_duration[1]), cursor.x, cursor.y, call_cfg)- box, cx, cy, did_scroll = scroll_to_element(- page, raw_mouse, selector, cursor.x, cursor.y, call_cfg, timeout=_remaining_ms(),- )- cursor.x = cx- cursor.y = cy- is_input = _is_input_element(page, selector)- if not force and did_scroll:- ensure_stable(page, selector, timeout=_remaining_ms())- # Waiting for the reflow to settle can push the element back out of- # view, and scrolling once before the wait is not enough: the click- # coords would land outside the viewport and hit nothing (#329).- box, cx, cy, _ = scroll_to_element(- page, raw_mouse, selector, cursor.x, cursor.y, call_cfg, timeout=_remaining_ms(),- )- cursor.x = cx- cursor.y = cy- target = click_target(box, is_input, call_cfg)- human_move(raw_mouse, cursor.x, cursor.y, target.x, target.y, call_cfg)- cursor.x = target.x- cursor.y = target.y- if not force:- check_pointer_events(- page, selector, box.get("targetId"), box.get("gen"),- target.x, target.y, stealth, timeout=_remaining_ms(),- )- human_click(raw_mouse, is_input, call_cfg)-- def _human_dblclick(selector: str, **kwargs: Any) -> None:- _ensure_cursor_init()- call_cfg = merge_config(cfg, kwargs.get("human_config"))- timeout = kwargs.get("timeout", 30000)- force = kwargs.get("force", False)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force:- ensure_actionable(page, selector, CHECKS_CLICK, timeout=_remaining_ms(), force=force)- if call_cfg.idle_between_actions:- human_idle(raw_mouse, rand(call_cfg.idle_between_duration[0], call_cfg.idle_between_duration[1]), cursor.x, cursor.y, call_cfg)- box, cx, cy, did_scroll = scroll_to_element(- page, raw_mouse, selector, cursor.x, cursor.y, call_cfg, timeout=_remaining_ms(),- )- cursor.x = cx- cursor.y = cy- is_input = _is_input_element(page, selector)- if not force and did_scroll:- ensure_stable(page, selector, timeout=_remaining_ms())- # Waiting for the reflow to settle can push the element back out of- # view, and scrolling once before the wait is not enough: the click- # coords would land outside the viewport and hit nothing (#329).- box, cx, cy, _ = scroll_to_element(- page, raw_mouse, selector, cursor.x, cursor.y, call_cfg, timeout=_remaining_ms(),- )- cursor.x = cx- cursor.y = cy- target = click_target(box, is_input, call_cfg)- human_move(raw_mouse, cursor.x, cursor.y, target.x, target.y, call_cfg)- cursor.x = target.x- cursor.y = target.y- if not force:- check_pointer_events(- page, selector, box.get("targetId"), box.get("gen"),- target.x, target.y, stealth, timeout=_remaining_ms(),- )- raw_mouse.down(click_count=2)- sleep_ms(rand(30, 60))- raw_mouse.up(click_count=2)-- def _human_hover(selector: str, **kwargs: Any) -> None:- _ensure_cursor_init()- call_cfg = merge_config(cfg, kwargs.get("human_config"))- timeout = kwargs.get("timeout", 30000)- force = kwargs.get("force", False)- skip_checks = kwargs.pop("_skip_checks", False)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force and not skip_checks:- ensure_actionable(page, selector, CHECKS_HOVER, timeout=_remaining_ms(), force=force)- if call_cfg.idle_between_actions:- human_idle(raw_mouse, rand(call_cfg.idle_between_duration[0], call_cfg.idle_between_duration[1]), cursor.x, cursor.y, call_cfg)- box, cx, cy, did_scroll = scroll_to_element(- page, raw_mouse, selector, cursor.x, cursor.y, call_cfg, timeout=_remaining_ms(),- )- cursor.x = cx- cursor.y = cy- if not force and did_scroll:- ensure_stable(page, selector, timeout=_remaining_ms())- # Waiting for the reflow to settle can push the element back out of- # view, and scrolling once before the wait is not enough: the click- # coords would land outside the viewport and hit nothing (#329).- box, cx, cy, _ = scroll_to_element(- page, raw_mouse, selector, cursor.x, cursor.y, call_cfg, timeout=_remaining_ms(),- )- cursor.x = cx- cursor.y = cy- target = click_target(box, False, call_cfg)- human_move(raw_mouse, cursor.x, cursor.y, target.x, target.y, call_cfg)- cursor.x = target.x- cursor.y = target.y- if not force:- check_pointer_events(- page, selector, box.get("targetId"), box.get("gen"),- target.x, target.y, stealth, timeout=_remaining_ms(),- )-- def _human_type(selector: str, text: str, **kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- timeout = kwargs.get("timeout", 30000)- force = kwargs.get("force", False)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force:- ensure_actionable(page, selector, CHECKS_INPUT, timeout=_remaining_ms(), force=force)- sleep_ms(rand_range(call_cfg.field_switch_delay))- _human_click(selector, _skip_checks=True, timeout=_remaining_ms(), force=force, human_config=kwargs.get("human_config"))- sleep_ms(rand(100, 250))- human_type(page, raw_keyboard, text, call_cfg, cdp_session=cdp_session)-- def _human_fill(selector: str, value: str, **kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- timeout = kwargs.get("timeout", 30000)- force = kwargs.get("force", False)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force:- ensure_actionable(page, selector, CHECKS_INPUT, timeout=_remaining_ms(), force=force)- sleep_ms(rand_range(call_cfg.field_switch_delay))- _human_click(selector, _skip_checks=True, timeout=_remaining_ms(), force=force, human_config=kwargs.get("human_config"))- sleep_ms(rand(100, 250))- originals.keyboard_press(_SELECT_ALL)- sleep_ms(rand(30, 80))- originals.keyboard_press("Backspace")- sleep_ms(rand(50, 150))- human_type(page, raw_keyboard, value, call_cfg, cdp_session=cdp_session)-- def _human_check(selector: str, **kwargs: Any) -> None:- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force:- ensure_actionable(page, selector, CHECKS_CHECK, timeout=_remaining_ms(), force=force)- checked = _selector_snapshot(page, selector)["checked"]- if checked is not True:- _human_click(selector, _skip_checks=True, timeout=_remaining_ms(), force=force, human_config=kwargs.get("human_config"))-- def _human_uncheck(selector: str, **kwargs: Any) -> None:- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force:- ensure_actionable(page, selector, CHECKS_CHECK, timeout=_remaining_ms(), force=force)- checked = _selector_snapshot(page, selector)["checked"]- if checked is True:- _human_click(selector, _skip_checks=True, timeout=_remaining_ms(), force=force, human_config=kwargs.get("human_config"))-- def _human_select_option(selector: str, value: Any = None, **kwargs: Any) -> Any:- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force:- ensure_actionable(page, selector, CHECKS_FOCUS, timeout=_remaining_ms(), force=force)- _human_hover(selector, _skip_checks=True, timeout=_remaining_ms(), force=force, human_config=kwargs.get("human_config"))- sleep_ms(rand(100, 300))- pw_kwargs = {k: v for k, v in kwargs.items() if k not in ("human_config", "force")}- return originals.select_option(selector, value, **pw_kwargs)-- def _human_press(selector: str, key: str, **kwargs: Any) -> None:- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force:- ensure_actionable(page, selector, CHECKS_FOCUS, timeout=_remaining_ms(), force=force)- if not _is_selector_focused(page, selector):- _human_click(selector, _skip_checks=True, timeout=_remaining_ms(), force=force, human_config=kwargs.get("human_config"))- sleep_ms(rand(50, 150))- originals.keyboard_press(key, **_keyboard_press_kwargs(kwargs))-- def _human_mouse_move(x: float, y: float, **kwargs: Any) -> None:- _ensure_cursor_init()- human_move(raw_mouse, cursor.x, cursor.y, x, y, cfg)- cursor.x = x- cursor.y = y-- def _human_mouse_click(x: float, y: float, **kwargs: Any) -> None:- _ensure_cursor_init()- human_move(raw_mouse, cursor.x, cursor.y, x, y, cfg)- cursor.x = x- cursor.y = y- human_click(raw_mouse, False, cfg)-- def _human_keyboard_type(text: str, **kwargs: Any) -> None:- human_type(page, raw_keyboard, text, cfg, cdp_session=cdp_session)-- page.goto = _human_goto- page.click = _human_click- page.dblclick = _human_dblclick- page.hover = _human_hover- page.type = _human_type- page.fill = _human_fill- page.check = _human_check- page.uncheck = _human_uncheck- page.select_option = _human_select_option- page.press = _human_press- page.mouse.move = _human_mouse_move- page.mouse.click = _human_mouse_click- page.keyboard.type = _human_keyboard_type- # --- Patch Frame-level methods (for sub-frames) ---- _patch_frames_sync(page, cfg, cursor, raw_mouse, raw_keyboard, originals)-- # --- Patch ElementHandle selectors (query_selector, query_selector_all, wait_for_selector) ---- _patch_page_element_handles_sync(page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session)-- # Initialize cursor immediately so it doesn't visibly jump from (0,0)- cursor.x = rand(cfg.initial_cursor_x[0], cfg.initial_cursor_x[1])- cursor.y = rand(cfg.initial_cursor_y[0], cfg.initial_cursor_y[1])- try:- originals.mouse_move(cursor.x, cursor.y)- cursor.initialized = True- except Exception:- pass-- # --- Patch Locator class (class-level, runs once) ---- _patch_locator_class_sync()---# ============================================================================-# SYNC ElementHandle patching-# ============================================================================---def _is_input_element_handle_sync(el: Any) -> bool:- """Check if an ElementHandle is an input/textarea/contenteditable (sync)."""- try:- return el.evaluate(- """(node) => {- const tag = node.tagName ? node.tagName.toLowerCase() : '';- return tag === 'input' || tag === 'textarea'- || node.getAttribute && node.getAttribute('contenteditable') === 'true';- }"""- )- except Exception:- return False---def _patch_single_element_handle_sync(- el: Any, page: Any, cfg: HumanConfig, cursor: _CursorState,- raw_mouse: RawMouse, raw_keyboard: RawKeyboard, originals: Any,- stealth: Any, cdp_session: Any,-) -> None:- """Patch all interaction methods on a sync Playwright ElementHandle."""- if getattr(el, '_human_patched', False):- return- el._human_patched = True-- # Save originals- _orig_click = el.click- _orig_dblclick = el.dblclick- _orig_hover = el.hover- _orig_type = el.type- _orig_fill = el.fill- _orig_press = el.press- _orig_select_option = el.select_option- _orig_check = el.check- _orig_uncheck = el.uncheck- _orig_set_checked = getattr(el, 'set_checked', None)- _orig_tap = el.tap- _orig_focus = el.focus- _orig_scroll_into_view = getattr(el, 'scroll_into_view_if_needed', None)-- # Nested selectors- _orig_qs = el.query_selector- _orig_qsa = el.query_selector_all- _orig_wfs = el.wait_for_selector-- def _patched_qs(selector: str, **kwargs: Any) -> Any:- child = _orig_qs(selector, **kwargs)- if child is not None:- _patch_single_element_handle_sync(- child, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session- )- return child-- def _patched_qsa(selector: str, **kwargs: Any) -> Any:- children = _orig_qsa(selector, **kwargs)- for child in children:- _patch_single_element_handle_sync(- child, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session- )- return children-- def _patched_wfs(selector: str, **kwargs: Any) -> Any:- child = _orig_wfs(selector, **kwargs)- if child is not None:- _patch_single_element_handle_sync(- child, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session- )- return child-- el.query_selector = _patched_qs- el.query_selector_all = _patched_qsa- el.wait_for_selector = _patched_wfs-- # Helper: move cursor to element. Accepts optional ``call_cfg`` so per-call- # ``human_config`` overrides on type/fill carry through to mouse timing.- # Also scrolls into view first so off-screen elements don't silently fall- # back to the unpatched native method (#129, #172 follow-up).- def _move_to_element(call_cfg: HumanConfig = cfg):- if not cursor.initialized:- cursor.x = rand(call_cfg.initial_cursor_x[0], call_cfg.initial_cursor_x[1])- cursor.y = rand(call_cfg.initial_cursor_y[0], call_cfg.initial_cursor_y[1])- originals.mouse_move(cursor.x, cursor.y)- cursor.initialized = True-- # Scroll into view first — best-effort. If the element can't be located- # we fall through to bounding_box() below which returns None and lets- # the caller fall back to the original Playwright method.- try:- _, nx, ny, _ = human_scroll_into_view(- page, raw_mouse, lambda: el.bounding_box(),- cursor.x, cursor.y, call_cfg,- )- cursor.x = nx- cursor.y = ny- except Exception:- pass-- box = el.bounding_box()- if not box:- return None-- is_inp = _is_input_element_handle_sync(el)- target = click_target(box, is_inp, call_cfg)-- if call_cfg.idle_between_actions:- human_idle(raw_mouse, rand(call_cfg.idle_between_duration[0], call_cfg.idle_between_duration[1]), cursor.x, cursor.y, call_cfg)-- human_move(raw_mouse, cursor.x, cursor.y, target.x, target.y, call_cfg)- cursor.x = target.x- cursor.y = target.y- return {'box': box, 'is_inp': is_inp}-- # --- el.click() ---- def _human_el_click(**kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- ensure_actionable_handle(page, el, CHECKS_CLICK, timeout=_remaining_ms(), force=force)- info = _move_to_element(call_cfg)- if info is None:- return _orig_click(**kwargs)- if not force:- check_pointer_events_handle(page, el, cursor.x, cursor.y, timeout=min(_remaining_ms(), 5000))- human_click(raw_mouse, info['is_inp'], call_cfg)-- # --- el.dblclick() ---- def _human_el_dblclick(**kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- ensure_actionable_handle(page, el, CHECKS_CLICK, timeout=_remaining_ms(), force=force)- info = _move_to_element(call_cfg)- if info is None:- return _orig_dblclick(**kwargs)- if not force:- check_pointer_events_handle(page, el, cursor.x, cursor.y, timeout=min(_remaining_ms(), 5000))- raw_mouse.down(click_count=2)- sleep_ms(rand(30, 60))- raw_mouse.up(click_count=2)-- # --- el.hover() ---- def _human_el_hover(**kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- ensure_actionable_handle(page, el, CHECKS_HOVER, timeout=_remaining_ms(), force=force)- info = _move_to_element(call_cfg)- if info is None:- return _orig_hover(**kwargs)-- # --- el.type() ---- def _human_el_type(text: str, **kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- ensure_actionable_handle(page, el, CHECKS_INPUT, timeout=_remaining_ms(), force=force)- info = _move_to_element(call_cfg)- if info is None:- return _orig_type(text, **kwargs)- if not force:- check_pointer_events_handle(page, el, cursor.x, cursor.y, timeout=min(_remaining_ms(), 5000))- human_click(raw_mouse, info['is_inp'], call_cfg)- sleep_ms(rand(100, 250))- human_type(page, raw_keyboard, text, call_cfg, cdp_session=cdp_session)-- # --- el.fill() ---- def _human_el_fill(value: str, **kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- ensure_actionable_handle(page, el, CHECKS_INPUT, timeout=_remaining_ms(), force=force)- info = _move_to_element(call_cfg)- if info is None:- return _orig_fill(value, **kwargs)- if not force:- check_pointer_events_handle(page, el, cursor.x, cursor.y, timeout=min(_remaining_ms(), 5000))- human_click(raw_mouse, info['is_inp'], call_cfg)- sleep_ms(rand(100, 250))- originals.keyboard_press(_SELECT_ALL)- sleep_ms(rand(30, 80))- originals.keyboard_press("Backspace")- sleep_ms(rand(50, 150))- human_type(page, raw_keyboard, value, call_cfg, cdp_session=cdp_session)-- # --- el.scroll_into_view_if_needed() ---- # Playwright's native version snaps the page — a strong bot signal.- # Replace with the same accelerate → cruise → decelerate → overshoot wheel- # sequence used by page.click(). Falls back to the native method if the- # element is detached or scrolling fails.- def _human_el_scroll_into_view_if_needed(**kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- if not cursor.initialized:- cursor.x = rand(call_cfg.initial_cursor_x[0], call_cfg.initial_cursor_x[1])- cursor.y = rand(call_cfg.initial_cursor_y[0], call_cfg.initial_cursor_y[1])- try:- originals.mouse_move(cursor.x, cursor.y)- cursor.initialized = True- except Exception:- pass- try:- _, nx, ny, _ = human_scroll_into_view(- page, raw_mouse, lambda: el.bounding_box(),- cursor.x, cursor.y, call_cfg,- )- cursor.x = nx- cursor.y = ny- except Exception:- if _orig_scroll_into_view is not None:- native_kwargs = {k: v for k, v in kwargs.items() if k != "human_config"}- _orig_scroll_into_view(**native_kwargs)-- # --- el.press() ---- def _human_el_press(key: str, **kwargs: Any) -> None:- sleep_ms(rand(20, 60))- originals.keyboard_press(- key,- **_keyboard_press_kwargs(kwargs, default_delay=rand_range(cfg.key_hold)),- )-- # --- el.select_option() ---- def _human_el_select_option(value: Any = None, **kwargs: Any) -> Any:- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- ensure_actionable_handle(page, el, CHECKS_FOCUS, timeout=_remaining_ms(), force=force)- info = _move_to_element()- if info is None:- return _orig_select_option(value, **kwargs)- human_click(raw_mouse, False, cfg)- sleep_ms(rand(100, 300))- return _orig_select_option(value, **kwargs)-- # --- el.check() ---- def _human_el_check(**kwargs: Any) -> None:- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- ensure_actionable_handle(page, el, CHECKS_CHECK, timeout=_remaining_ms(), force=force)- try:- if el.is_checked():- return- except Exception:- pass- info = _move_to_element()- if info is None:- return _orig_check(**kwargs)- if not force:- check_pointer_events_handle(page, el, cursor.x, cursor.y, timeout=min(_remaining_ms(), 5000))- human_click(raw_mouse, info['is_inp'], cfg)-- # --- el.uncheck() ---- def _human_el_uncheck(**kwargs: Any) -> None:- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- ensure_actionable_handle(page, el, CHECKS_CHECK, timeout=_remaining_ms(), force=force)- try:- if not el.is_checked():- return- except Exception:- pass- info = _move_to_element()- if info is None:- return _orig_uncheck(**kwargs)- if not force:- check_pointer_events_handle(page, el, cursor.x, cursor.y, timeout=min(_remaining_ms(), 5000))- human_click(raw_mouse, info['is_inp'], cfg)-- # --- el.set_checked() ---- def _human_el_set_checked(checked: bool, **kwargs: Any) -> None:- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- ensure_actionable_handle(page, el, CHECKS_CHECK, timeout=_remaining_ms(), force=force)- try:- current = el.is_checked()- if current == checked:- return- except Exception:- pass- info = _move_to_element()- if info is None and _orig_set_checked:- return _orig_set_checked(checked, **kwargs)- if info:- if not force:- check_pointer_events_handle(page, el, cursor.x, cursor.y, timeout=min(_remaining_ms(), 5000))- human_click(raw_mouse, info['is_inp'], cfg)-- # --- el.tap() ---- def _human_el_tap(**kwargs: Any) -> None:- info = _move_to_element()- if info is None:- return _orig_tap(**kwargs)- human_click(raw_mouse, info['is_inp'], cfg)-- # --- el.focus() ---- # FIX: move cursor humanly but use programmatic focus (no click side-effects).- # Stock Playwright el.focus() never clicks — it just calls element.focus() in JS.- # Clicking would trigger onclick, submit forms, navigate links, etc.- def _human_el_focus() -> None:- _move_to_element() # human-like cursor movement (Bézier)- _orig_focus() # programmatic focus, no click side-effects-- el.click = _human_el_click- el.dblclick = _human_el_dblclick- el.hover = _human_el_hover- el.type = _human_el_type- el.fill = _human_el_fill- el.press = _human_el_press- el.select_option = _human_el_select_option- el.check = _human_el_check- el.uncheck = _human_el_uncheck- if _orig_set_checked is not None:- el.set_checked = _human_el_set_checked- el.tap = _human_el_tap- el.focus = _human_el_focus- if _orig_scroll_into_view is not None:- el.scroll_into_view_if_needed = _human_el_scroll_into_view_if_needed---def _patch_page_element_handles_sync(- page: Any, cfg: HumanConfig, cursor: _CursorState,- raw_mouse: RawMouse, raw_keyboard: RawKeyboard, originals: Any,- stealth: Any, cdp_session: Any,-) -> None:- """Patch page.query_selector, query_selector_all, wait_for_selector to return humanized ElementHandles (sync)."""- _orig_qs = page.query_selector- _orig_qsa = page.query_selector_all- _orig_wfs = page.wait_for_selector-- def _patched_qs(selector: str, **kwargs: Any) -> Any:- el = _orig_qs(selector, **kwargs)- if el is not None:- _patch_single_element_handle_sync(- el, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session- )- return el-- def _patched_qsa(selector: str, **kwargs: Any) -> Any:- els = _orig_qsa(selector, **kwargs)- for el in els:- _patch_single_element_handle_sync(- el, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session- )- return els-- def _patched_wfs(selector: str, **kwargs: Any) -> Any:- el = _orig_wfs(selector, **kwargs)- if el is not None:- _patch_single_element_handle_sync(- el, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session- )- return el-- page.query_selector = _patched_qs- page.query_selector_all = _patched_qsa- page.wait_for_selector = _patched_wfs---def _patch_frames_sync(- page: Any, cfg: HumanConfig, cursor: _CursorState,- raw_mouse: RawMouse, raw_keyboard: RawKeyboard, originals: Any,-) -> None:- def _on_frame_attached(frame: Any) -> None:- try:- _patch_single_frame_sync(frame, page, cfg, cursor, raw_mouse, raw_keyboard, originals)- except Exception:- logger.exception("Failed to humanize dynamically attached frame")-- # Register before enumerating so frames attached during the initial scan- # cannot escape humanization. Playwright emits this for nested frames too.- if not getattr(page, "_human_frame_listener_attached", False):- page.on("frameattached", _on_frame_attached)- page._human_frame_listener_attached = True-- for frame in _iter_frames(page):- _patch_single_frame_sync(frame, page, cfg, cursor, raw_mouse, raw_keyboard, originals)-- orig_main_frame = getattr(page, "_original_main_frame", None)- if orig_main_frame is None:- try:- _orig_goto = originals.goto-- def _frame_aware_goto(url: str, **kwargs: Any) -> Any:- response = _orig_goto(url, **kwargs)- # Invalidate isolated world after navigation- stealth_world = getattr(page, '_stealth_world', None)- if stealth_world is not None:- stealth_world.invalidate()- for frame in _iter_frames(page):- if not getattr(frame, "_human_patched", False):- _patch_single_frame_sync(frame, page, cfg, cursor, raw_mouse, raw_keyboard, originals)- return response-- page.goto = _frame_aware_goto- page._original_main_frame = True- except Exception:- pass---def _patch_single_frame_sync(- frame: Any, page: Any, cfg: HumanConfig, cursor: _CursorState,- raw_mouse: RawMouse, raw_keyboard: RawKeyboard, originals: Any,-) -> None:- if getattr(frame, "_human_patched", False):- return-- # Frame-scoped resolution: humanize via ``frame.locator(selector)`` so the- # selector resolves in the sub-frame's own document, while the mouse stays- # page-level (bounding_box() is already page/viewport-space). Mirrors the JS- # wrapper's patchSingleFrame/moveToFrameSelector. #428.- _orig_frame_click = frame.click- _orig_frame_dblclick = frame.dblclick- _orig_frame_hover = frame.hover- _orig_frame_type = frame.type- _orig_frame_fill = frame.fill- _orig_frame_check = frame.check- _orig_frame_uncheck = frame.uncheck- _orig_frame_select_option = frame.select_option- _orig_frame_press = frame.press- _orig_frame_drag_and_drop = getattr(frame, 'drag_and_drop', None)-- stealth_world = getattr(page, '_stealth_world', None)- cdp_session = None- if stealth_world is not None:- try:- cdp_session = stealth_world.get_cdp_session()- except Exception:- pass-- def _native_kwargs(kwargs: dict) -> dict:- # Native Playwright frame methods don't accept our ``human_config`` kwarg.- return {k: v for k, v in kwargs.items() if k != "human_config"}-- def _deadline_remaining(kwargs: dict):- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- return lambda: max(0.0, (deadline - time.monotonic()) * 1000)-- def _frame_is_input(selector: str) -> bool:- try:- return bool(frame.locator(selector).first.evaluate(- "el => { const t = el.tagName.toLowerCase();"- " return t === 'input' || t === 'textarea'"- " || el.getAttribute('contenteditable') === 'true'; }"- ))- except Exception:- return False-- def _frame_is_focused(selector: str) -> bool:- try:- return bool(frame.locator(selector).first.evaluate(- "el => el === document.activeElement"- ))- except Exception:- return False-- def _move_to_frame_selector(selector: str, kwargs: dict, input_bias: bool, remaining_ms):- call_cfg = merge_config(cfg, kwargs.get("human_config"))- if call_cfg.idle_between_actions:- human_idle(raw_mouse, rand(call_cfg.idle_between_duration[0], call_cfg.idle_between_duration[1]), cursor.x, cursor.y, call_cfg)- loc = frame.locator(selector).first- try:- loc.scroll_into_view_if_needed(timeout=max(1, remaining_ms()))- except Exception:- pass- try:- box = loc.bounding_box(timeout=max(1, remaining_ms()))- except Exception:- box = None- if not box:- return None- is_input = input_bias or _frame_is_input(selector)- target = click_target(box, is_input, call_cfg)- human_move(raw_mouse, cursor.x, cursor.y, target.x, target.y, call_cfg)- cursor.x = target.x- cursor.y = target.y- return call_cfg, is_input-- def _frame_click(selector: str, **kwargs: Any) -> None:- remaining_ms = _deadline_remaining(kwargs)- moved = _move_to_frame_selector(selector, kwargs, False, remaining_ms)- if moved is None:- _orig_frame_click(selector, **_native_kwargs(kwargs))- return- human_click(raw_mouse, moved[1], moved[0])-- def _frame_dblclick(selector: str, **kwargs: Any) -> None:- remaining_ms = _deadline_remaining(kwargs)- moved = _move_to_frame_selector(selector, kwargs, False, remaining_ms)- if moved is None:- _orig_frame_dblclick(selector, **_native_kwargs(kwargs))- return- raw_mouse.down(click_count=2)- sleep_ms(rand(30, 60))- raw_mouse.up(click_count=2)-- def _frame_hover(selector: str, **kwargs: Any) -> None:- remaining_ms = _deadline_remaining(kwargs)- moved = _move_to_frame_selector(selector, kwargs, False, remaining_ms)- if moved is None:- _orig_frame_hover(selector, **_native_kwargs(kwargs))-- def _frame_type(selector: str, text: str, **kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- sleep_ms(rand_range(call_cfg.field_switch_delay))- _frame_click(selector, **kwargs)- sleep_ms(rand(100, 250))- try:- human_type(page, raw_keyboard, text, call_cfg, cdp_session=cdp_session)- except Exception:- _orig_frame_type(selector, text, **_native_kwargs(kwargs))-- def _frame_fill(selector: str, value: str, **kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- sleep_ms(rand_range(call_cfg.field_switch_delay))- _frame_click(selector, **kwargs)- sleep_ms(rand(100, 250))- originals.keyboard_press(_SELECT_ALL)- sleep_ms(rand(30, 80))- originals.keyboard_press("Backspace")- sleep_ms(rand(50, 150))- try:- human_type(page, raw_keyboard, value, call_cfg, cdp_session=cdp_session)- except Exception:- _orig_frame_fill(selector, value, **_native_kwargs(kwargs))-- def _frame_check(selector: str, **kwargs: Any) -> None:- try:- checked = frame.locator(selector).first.is_checked()- except Exception:- _orig_frame_check(selector, **_native_kwargs(kwargs))- return- if not checked:- try:- _frame_click(selector, **kwargs)- except Exception:- _orig_frame_check(selector, **_native_kwargs(kwargs))-- def _frame_uncheck(selector: str, **kwargs: Any) -> None:- try:- checked = frame.locator(selector).first.is_checked()- except Exception:- _orig_frame_uncheck(selector, **_native_kwargs(kwargs))- return- if checked:- try:- _frame_click(selector, **kwargs)- except Exception:- _orig_frame_uncheck(selector, **_native_kwargs(kwargs))-- def _frame_select_option(selector: str, value: Any = None, **kwargs: Any) -> Any:- _frame_hover(selector, **kwargs)- sleep_ms(rand(100, 300))- return _orig_frame_select_option(selector, value, **_native_kwargs(kwargs))-- def _frame_press(selector: str, key: str, **kwargs: Any) -> None:- if not _frame_is_focused(selector):- _frame_click(selector, **kwargs)- sleep_ms(rand(50, 150))- originals.keyboard_press(key, **_keyboard_press_kwargs(kwargs))-- def _frame_clear(selector: str, **kwargs: Any) -> None:- if not _frame_is_focused(selector):- _frame_click(selector, **kwargs)- sleep_ms(rand(50, 100))- originals.keyboard_press(_SELECT_ALL)- sleep_ms(rand(30, 80))- originals.keyboard_press("Backspace")-- def _frame_drag_and_drop(source: str, target: str, **kwargs: Any) -> None:- try:- src_box = frame.locator(source).bounding_box()- tgt_box = frame.locator(target).bounding_box()- except Exception:- src_box = tgt_box = None- if src_box and tgt_box:- sx = src_box['x'] + src_box['width'] / 2- sy = src_box['y'] + src_box['height'] / 2- tx = tgt_box['x'] + tgt_box['width'] / 2- ty = tgt_box['y'] + tgt_box['height'] / 2- page.mouse.move(sx, sy)- sleep_ms(rand(100, 200))- originals.mouse_down()- sleep_ms(rand(80, 150))- page.mouse.move(tx, ty)- sleep_ms(rand(80, 150))- originals.mouse_up()- elif _orig_frame_drag_and_drop:- _orig_frame_drag_and_drop(source, target, **kwargs)-- frame.click = _frame_click- frame.dblclick = _frame_dblclick- frame.hover = _frame_hover- frame.type = _frame_type- frame.fill = _frame_fill- frame.check = _frame_check- frame.uncheck = _frame_uncheck- frame.select_option = _frame_select_option- frame.press = _frame_press- frame.clear = _frame_clear- frame.drag_and_drop = _frame_drag_and_drop-- # --- Patch frame-level ElementHandle selectors ---- _patch_frame_element_handles_sync(- frame, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth_world, cdp_session- )- frame._human_patched = True---def _patch_frame_element_handles_sync(- frame: Any, page: Any, cfg: HumanConfig, cursor: _CursorState,- raw_mouse: RawMouse, raw_keyboard: RawKeyboard, originals: Any,- stealth: Any, cdp_session: Any,-) -> None:- """Patch frame.query_selector, query_selector_all, wait_for_selector (sync)."""- _orig_qs = frame.query_selector- _orig_qsa = frame.query_selector_all- _orig_wfs = frame.wait_for_selector-- def _patched_qs(selector: str, **kwargs: Any) -> Any:- el = _orig_qs(selector, **kwargs)- if el is not None:- _patch_single_element_handle_sync(- el, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session- )- return el-- def _patched_qsa(selector: str, **kwargs: Any) -> Any:- els = _orig_qsa(selector, **kwargs)- for el in els:- _patch_single_element_handle_sync(- el, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session- )- return els-- def _patched_wfs(selector: str, **kwargs: Any) -> Any:- el = _orig_wfs(selector, **kwargs)- if el is not None:- _patch_single_element_handle_sync(- el, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session- )- return el-- frame.query_selector = _patched_qs- frame.query_selector_all = _patched_qsa- frame.wait_for_selector = _patched_wfs----def _iter_frames(page: Any):- def _walk(frame: Any):- yield frame- for child in frame.child_frames:- yield from _walk(child)-- try:- yield from _walk(page.main_frame)- except Exception:- pass---def patch_context(context: Any, cfg: HumanConfig) -> None:- cursor = _CursorState()- for page in context.pages:- patch_page(page, cfg, cursor)- context.on("page", lambda p: patch_page(p, cfg, _CursorState()) if not hasattr(p, '_original') else None)-- orig_new_page = context.new_page-- def _patched_new_page(**kwargs: Any) -> Any:- page = orig_new_page(**kwargs)- if not hasattr(page, '_original'):- patch_page(page, cfg, _CursorState())- return page-- context.new_page = _patched_new_page---def patch_browser(browser: Any, cfg: HumanConfig) -> None:- for context in browser.contexts:- patch_context(context, cfg)-- orig_new_context = browser.new_context-- def _patched_new_context(**kwargs: Any) -> Any:- context = orig_new_context(**kwargs)- patch_context(context, cfg)- return context-- browser.new_context = _patched_new_context-- orig_new_page = browser.new_page-- def _patched_new_page(**kwargs: Any) -> Any:- page = orig_new_page(**kwargs)- if not hasattr(page, '_original'):- patch_page(page, cfg, _CursorState())- return page-- browser.new_page = _patched_new_page---# ============================================================================-# ASYNC patching-# ============================================================================---def patch_page_async(page: Any, cfg: HumanConfig, cursor: _CursorState) -> None:- """Replace page methods with human-like implementations (async)."""- originals = type("Originals", (), {- "click": page.click,- "type": page.type,- "fill": page.fill,- "goto": page.goto,- "hover": page.hover,- "dblclick": page.dblclick,- "select_option": page.select_option,- "mouse_move": page.mouse.move,- "mouse_click": page.mouse.click,- "mouse_wheel": page.mouse.wheel,- "mouse_down": page.mouse.down,- "mouse_up": page.mouse.up,- "keyboard_type": page.keyboard.type,- "keyboard_down": page.keyboard.down,- "keyboard_up": page.keyboard.up,- "keyboard_press": page.keyboard.press,- "keyboard_insert_text": page.keyboard.insert_text,- })()-- page._original = originals- page._human_cfg = cfg- page._human_cursor = cursor-- # --- Stealth infrastructure (lazy-initialized, async) ---- stealth = _AsyncIsolatedWorld(page)- page._stealth_world = stealth- cdp_session_holder: list[Any] = [None] # mutable container for closure- page._cdp_session_holder = cdp_session_holder # expose for frame-level patching-- # Invalidate the isolated world on any main-frame nav, not just goto, so- # click/form navigations don't leave it bound to a stale doc (#507).- try:- page.on(- "framenavigated",- lambda frame: stealth.invalidate() if frame == page.main_frame else None,- )- except Exception:- logger.debug("Could not wire framenavigated invalidation")-- async def _ensure_cdp() -> Any:- if cdp_session_holder[0] is None:- try:- cdp_session_holder[0] = await stealth.get_cdp_session()- except Exception:- logger.debug("Could not create async CDP session")- return cdp_session_holder[0]-- raw_mouse: AsyncRawMouse = type("_AsyncRawMouse", (), {- "move": originals.mouse_move,- "down": originals.mouse_down,- "up": originals.mouse_up,- "wheel": originals.mouse_wheel,- })()-- raw_keyboard: AsyncRawKeyboard = type("_AsyncRawKeyboard", (), {- "down": originals.keyboard_down,- "up": originals.keyboard_up,- "type": originals.keyboard_type,- "insert_text": originals.keyboard_insert_text,- })()-- page._human_raw_mouse = raw_mouse-- async def _ensure_cursor_init() -> None:- if not cursor.initialized:- cursor.x = rand(cfg.initial_cursor_x[0], cfg.initial_cursor_x[1])- cursor.y = rand(cfg.initial_cursor_y[0], cfg.initial_cursor_y[1])- await originals.mouse_move(cursor.x, cursor.y)- cursor.initialized = True-- async def _human_goto(url: str, **kwargs: Any) -> Any:- response = await originals.goto(url, **kwargs)- # Invalidate isolated world after navigation- stealth.invalidate()- return response-- async def _human_click(selector: str, **kwargs: Any) -> None:- await _ensure_cursor_init()- call_cfg = merge_config(cfg, kwargs.get("human_config"))- timeout = kwargs.get("timeout", 30000)- force = kwargs.get("force", False)- skip_checks = kwargs.pop("_skip_checks", False)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force and not skip_checks:- await async_ensure_actionable(page, selector, CHECKS_CLICK, timeout=_remaining_ms(), force=force)- if call_cfg.idle_between_actions:- await async_human_idle(raw_mouse, rand(call_cfg.idle_between_duration[0], call_cfg.idle_between_duration[1]), cursor.x, cursor.y, call_cfg)- box, cx, cy, did_scroll = await async_scroll_to_element(- page, raw_mouse, selector, cursor.x, cursor.y, call_cfg, timeout=_remaining_ms(),- )- cursor.x = cx- cursor.y = cy- is_input = await _async_is_input_element(page, selector)- if not force and did_scroll:- await async_ensure_stable(page, selector, timeout=_remaining_ms())- # See the sync path: settling can move the element off-screen again,- # so re-scroll before computing click coords (#329).- box, cx, cy, _ = await async_scroll_to_element(- page, raw_mouse, selector, cursor.x, cursor.y, call_cfg, timeout=_remaining_ms(),- )- cursor.x = cx- cursor.y = cy- target = click_target(box, is_input, call_cfg)- await async_human_move(raw_mouse, cursor.x, cursor.y, target.x, target.y, call_cfg)- cursor.x = target.x- cursor.y = target.y- if not force:- await async_check_pointer_events(- page, selector, box.get("targetId"), box.get("gen"),- target.x, target.y, stealth, timeout=_remaining_ms(),- )- await async_human_click(raw_mouse, is_input, call_cfg)-- async def _human_dblclick(selector: str, **kwargs: Any) -> None:- await _ensure_cursor_init()- call_cfg = merge_config(cfg, kwargs.get("human_config"))- timeout = kwargs.get("timeout", 30000)- force = kwargs.get("force", False)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force:- await async_ensure_actionable(page, selector, CHECKS_CLICK, timeout=_remaining_ms(), force=force)- if call_cfg.idle_between_actions:- await async_human_idle(raw_mouse, rand(call_cfg.idle_between_duration[0], call_cfg.idle_between_duration[1]), cursor.x, cursor.y, call_cfg)- box, cx, cy, did_scroll = await async_scroll_to_element(- page, raw_mouse, selector, cursor.x, cursor.y, call_cfg, timeout=_remaining_ms(),- )- cursor.x = cx- cursor.y = cy- is_input = await _async_is_input_element(page, selector)- if not force and did_scroll:- await async_ensure_stable(page, selector, timeout=_remaining_ms())- # See the sync path: settling can move the element off-screen again,- # so re-scroll before computing click coords (#329).- box, cx, cy, _ = await async_scroll_to_element(- page, raw_mouse, selector, cursor.x, cursor.y, call_cfg, timeout=_remaining_ms(),- )- cursor.x = cx- cursor.y = cy- target = click_target(box, is_input, call_cfg)- await async_human_move(raw_mouse, cursor.x, cursor.y, target.x, target.y, call_cfg)- cursor.x = target.x- cursor.y = target.y- if not force:- await async_check_pointer_events(- page, selector, box.get("targetId"), box.get("gen"),- target.x, target.y, stealth, timeout=_remaining_ms(),- )- await raw_mouse.down(click_count=2)- await async_sleep_ms(rand(30, 60))- await raw_mouse.up(click_count=2)-- async def _human_hover(selector: str, **kwargs: Any) -> None:- await _ensure_cursor_init()- call_cfg = merge_config(cfg, kwargs.get("human_config"))- timeout = kwargs.get("timeout", 30000)- force = kwargs.get("force", False)- skip_checks = kwargs.pop("_skip_checks", False)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force and not skip_checks:- await async_ensure_actionable(page, selector, CHECKS_HOVER, timeout=_remaining_ms(), force=force)- if call_cfg.idle_between_actions:- await async_human_idle(raw_mouse, rand(call_cfg.idle_between_duration[0], call_cfg.idle_between_duration[1]), cursor.x, cursor.y, call_cfg)- box, cx, cy, did_scroll = await async_scroll_to_element(- page, raw_mouse, selector, cursor.x, cursor.y, call_cfg, timeout=_remaining_ms(),- )- cursor.x = cx- cursor.y = cy- if not force and did_scroll:- await async_ensure_stable(page, selector, timeout=_remaining_ms())- # See the sync path: settling can move the element off-screen again,- # so re-scroll before computing click coords (#329).- box, cx, cy, _ = await async_scroll_to_element(- page, raw_mouse, selector, cursor.x, cursor.y, call_cfg, timeout=_remaining_ms(),- )- cursor.x = cx- cursor.y = cy- target = click_target(box, False, call_cfg)- await async_human_move(raw_mouse, cursor.x, cursor.y, target.x, target.y, call_cfg)- cursor.x = target.x- cursor.y = target.y- if not force:- await async_check_pointer_events(- page, selector, box.get("targetId"), box.get("gen"),- target.x, target.y, stealth, timeout=_remaining_ms(),- )-- async def _human_type(selector: str, text: str, **kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- timeout = kwargs.get("timeout", 30000)- force = kwargs.get("force", False)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force:- await async_ensure_actionable(page, selector, CHECKS_INPUT, timeout=_remaining_ms(), force=force)- await async_sleep_ms(rand_range(call_cfg.field_switch_delay))- await _human_click(selector, _skip_checks=True, timeout=_remaining_ms(), force=force, human_config=kwargs.get("human_config"))- await async_sleep_ms(rand(100, 250))- cdp = await _ensure_cdp()- await async_human_type(page, raw_keyboard, text, call_cfg, cdp_session=cdp)-- async def _human_fill(selector: str, value: str, **kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- timeout = kwargs.get("timeout", 30000)- force = kwargs.get("force", False)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force:- await async_ensure_actionable(page, selector, CHECKS_INPUT, timeout=_remaining_ms(), force=force)- await async_sleep_ms(rand_range(call_cfg.field_switch_delay))- await _human_click(selector, _skip_checks=True, timeout=_remaining_ms(), force=force, human_config=kwargs.get("human_config"))- await async_sleep_ms(rand(100, 250))- await originals.keyboard_press(_SELECT_ALL)- await async_sleep_ms(rand(30, 80))- await originals.keyboard_press("Backspace")- await async_sleep_ms(rand(50, 150))- cdp = await _ensure_cdp()- await async_human_type(page, raw_keyboard, value, call_cfg, cdp_session=cdp)-- async def _human_check(selector: str, **kwargs: Any) -> None:- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force:- await async_ensure_actionable(page, selector, CHECKS_CHECK, timeout=_remaining_ms(), force=force)- checked = (await _async_selector_snapshot(page, selector))["checked"]- if checked is not True:- await _human_click(selector, _skip_checks=True, timeout=_remaining_ms(), force=force, human_config=kwargs.get("human_config"))-- async def _human_uncheck(selector: str, **kwargs: Any) -> None:- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force:- await async_ensure_actionable(page, selector, CHECKS_CHECK, timeout=_remaining_ms(), force=force)- checked = (await _async_selector_snapshot(page, selector))["checked"]- if checked is True:- await _human_click(selector, _skip_checks=True, timeout=_remaining_ms(), force=force, human_config=kwargs.get("human_config"))-- async def _human_press(selector: str, key: str, **kwargs: Any) -> None:- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force:- await async_ensure_actionable(page, selector, CHECKS_FOCUS, timeout=_remaining_ms(), force=force)- if not await _async_is_selector_focused(page, selector):- await _human_click(selector, _skip_checks=True, timeout=_remaining_ms(), force=force, human_config=kwargs.get("human_config"))- await async_sleep_ms(rand(50, 150))- await originals.keyboard_press(key, **_keyboard_press_kwargs(kwargs))-- async def _human_select_option(selector: str, value: Any = None, **kwargs: Any) -> Any:- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0-- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)-- if not force:- await async_ensure_actionable(page, selector, CHECKS_FOCUS, timeout=_remaining_ms(), force=force)- await _human_hover(selector, _skip_checks=True, timeout=_remaining_ms(), force=force, human_config=kwargs.get("human_config"))- await async_sleep_ms(rand(100, 300))- pw_kwargs = {k: v for k, v in kwargs.items() if k not in ("human_config", "force")}- return await originals.select_option(selector, value, **pw_kwargs)-- async def _human_mouse_move(x: float, y: float, **kwargs: Any) -> None:- await _ensure_cursor_init()- await async_human_move(raw_mouse, cursor.x, cursor.y, x, y, cfg)- cursor.x = x- cursor.y = y-- async def _human_mouse_click(x: float, y: float, **kwargs: Any) -> None:- await _ensure_cursor_init()- await async_human_move(raw_mouse, cursor.x, cursor.y, x, y, cfg)- cursor.x = x- cursor.y = y- await async_human_click(raw_mouse, False, cfg)-- async def _human_keyboard_type(text: str, **kwargs: Any) -> None:- cdp = await _ensure_cdp()- await async_human_type(page, raw_keyboard, text, cfg, cdp_session=cdp)-- page.goto = _human_goto- page.click = _human_click- page.dblclick = _human_dblclick- page.hover = _human_hover- page.type = _human_type- page.fill = _human_fill- page.check = _human_check- page.uncheck = _human_uncheck- page.select_option = _human_select_option- page.press = _human_press- page.mouse.move = _human_mouse_move- page.mouse.click = _human_mouse_click- page.keyboard.type = _human_keyboard_type-- # --- Patch Frame-level methods (for sub-frames) ---- _patch_frames_async(page, cfg, cursor, raw_mouse, raw_keyboard, originals)-- # --- Patch ElementHandle selectors (query_selector, query_selector_all, wait_for_selector) ---- _patch_page_element_handles_async(page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session_holder)-- # --- Patch async Locator class (class-level, runs once) ---- _patch_locator_class_async()---# ============================================================================-# ASYNC ElementHandle patching-# ============================================================================---async def _async_is_input_element_handle(el: Any) -> bool:- """Check if an ElementHandle is an input/textarea/contenteditable (async)."""- try:- return await el.evaluate(- """(node) => {- const tag = node.tagName ? node.tagName.toLowerCase() : '';- return tag === 'input' || tag === 'textarea'- || node.getAttribute && node.getAttribute('contenteditable') === 'true';- }"""- )- except Exception:- return False---def _patch_single_element_handle_async(- el: Any, page: Any, cfg: HumanConfig, cursor: _CursorState,- raw_mouse: AsyncRawMouse, raw_keyboard: AsyncRawKeyboard, originals: Any,- stealth: Any, cdp_session_holder: Any,-) -> None:- """Patch all interaction methods on an async Playwright ElementHandle."""- if getattr(el, '_human_patched', False):- return- el._human_patched = True-- # Save originals- _orig_click = el.click- _orig_dblclick = el.dblclick- _orig_hover = el.hover- _orig_type = el.type- _orig_fill = el.fill- _orig_press = el.press- _orig_select_option = el.select_option- _orig_check = el.check- _orig_uncheck = el.uncheck- _orig_set_checked = getattr(el, 'set_checked', None)- _orig_tap = el.tap- _orig_focus = el.focus- _orig_scroll_into_view = getattr(el, 'scroll_into_view_if_needed', None)-- # Nested selectors- _orig_qs = el.query_selector- _orig_qsa = el.query_selector_all- _orig_wfs = el.wait_for_selector-- async def _patched_qs(selector: str, **kwargs: Any) -> Any:- child = await _orig_qs(selector, **kwargs)- if child is not None:- _patch_single_element_handle_async(- child, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session_holder- )- return child-- async def _patched_qsa(selector: str, **kwargs: Any) -> Any:- children = await _orig_qsa(selector, **kwargs)- for child in children:- _patch_single_element_handle_async(- child, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session_holder- )- return children-- async def _patched_wfs(selector: str, **kwargs: Any) -> Any:- child = await _orig_wfs(selector, **kwargs)- if child is not None:- _patch_single_element_handle_async(- child, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session_holder- )- return child-- el.query_selector = _patched_qs- el.query_selector_all = _patched_qsa- el.wait_for_selector = _patched_wfs-- # Helper: move cursor to element (async). Accepts optional ``call_cfg`` so- # per-call ``human_config`` overrides on type/fill carry through to mouse- # timing. Also scrolls into view first so off-screen elements work- # (#129, #172 follow-up).- async def _move_to_element(call_cfg: HumanConfig = cfg):- if not cursor.initialized:- cursor.x = rand(call_cfg.initial_cursor_x[0], call_cfg.initial_cursor_x[1])- cursor.y = rand(call_cfg.initial_cursor_y[0], call_cfg.initial_cursor_y[1])- await originals.mouse_move(cursor.x, cursor.y)- cursor.initialized = True-- # Scroll into view first — best-effort.- async def _get_box():- return await el.bounding_box()- try:- _, nx, ny, _ = await async_human_scroll_into_view(- page, raw_mouse, _get_box,- cursor.x, cursor.y, call_cfg,- )- cursor.x = nx- cursor.y = ny- except Exception:- pass-- box = await el.bounding_box()- if not box:- return None-- is_inp = await _async_is_input_element_handle(el)- target = click_target(box, is_inp, call_cfg)-- if call_cfg.idle_between_actions:- await async_human_idle(raw_mouse, rand(call_cfg.idle_between_duration[0], call_cfg.idle_between_duration[1]), cursor.x, cursor.y, call_cfg)-- await async_human_move(raw_mouse, cursor.x, cursor.y, target.x, target.y, call_cfg)- cursor.x = target.x- cursor.y = target.y- return {'box': box, 'is_inp': is_inp}-- async def _get_cdp():- if cdp_session_holder[0] is None:- try:- cdp_session_holder[0] = await stealth.get_cdp_session()- except Exception:- pass- return cdp_session_holder[0]-- # --- el.click() ---- async def _human_el_click(**kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- await async_ensure_actionable_handle(page, el, CHECKS_CLICK, timeout=_remaining_ms(), force=force)- info = await _move_to_element(call_cfg)- if info is None:- return await _orig_click(**kwargs)- if not force:- await async_check_pointer_events_handle(page, el, cursor.x, cursor.y, timeout=min(_remaining_ms(), 5000))- await async_human_click(raw_mouse, info['is_inp'], call_cfg)-- # --- el.dblclick() ---- async def _human_el_dblclick(**kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- await async_ensure_actionable_handle(page, el, CHECKS_CLICK, timeout=_remaining_ms(), force=force)- info = await _move_to_element(call_cfg)- if info is None:- return await _orig_dblclick(**kwargs)- if not force:- await async_check_pointer_events_handle(page, el, cursor.x, cursor.y, timeout=min(_remaining_ms(), 5000))- await raw_mouse.down(click_count=2)- await async_sleep_ms(rand(30, 60))- await raw_mouse.up(click_count=2)-- # --- el.hover() ---- async def _human_el_hover(**kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- await async_ensure_actionable_handle(page, el, CHECKS_HOVER, timeout=_remaining_ms(), force=force)- info = await _move_to_element(call_cfg)- if info is None:- return await _orig_hover(**kwargs)-- # --- el.type() ---- async def _human_el_type(text: str, **kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- await async_ensure_actionable_handle(page, el, CHECKS_INPUT, timeout=_remaining_ms(), force=force)- info = await _move_to_element(call_cfg)- if info is None:- return await _orig_type(text, **kwargs)- if not force:- await async_check_pointer_events_handle(page, el, cursor.x, cursor.y, timeout=min(_remaining_ms(), 5000))- await async_human_click(raw_mouse, info['is_inp'], call_cfg)- await async_sleep_ms(rand(100, 250))- cdp = await _get_cdp()- await async_human_type(page, raw_keyboard, text, call_cfg, cdp_session=cdp)-- # --- el.fill() ---- async def _human_el_fill(value: str, **kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- await async_ensure_actionable_handle(page, el, CHECKS_INPUT, timeout=_remaining_ms(), force=force)- info = await _move_to_element(call_cfg)- if info is None:- return await _orig_fill(value, **kwargs)- if not force:- await async_check_pointer_events_handle(page, el, cursor.x, cursor.y, timeout=min(_remaining_ms(), 5000))- await async_human_click(raw_mouse, info['is_inp'], call_cfg)- await async_sleep_ms(rand(100, 250))- await originals.keyboard_press(_SELECT_ALL)- await async_sleep_ms(rand(30, 80))- await originals.keyboard_press("Backspace")- await async_sleep_ms(rand(50, 150))- cdp = await _get_cdp()- await async_human_type(page, raw_keyboard, value, call_cfg, cdp_session=cdp)-- # --- el.scroll_into_view_if_needed() ---- async def _human_el_scroll_into_view_if_needed(**kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- if not cursor.initialized:- cursor.x = rand(call_cfg.initial_cursor_x[0], call_cfg.initial_cursor_x[1])- cursor.y = rand(call_cfg.initial_cursor_y[0], call_cfg.initial_cursor_y[1])- try:- await originals.mouse_move(cursor.x, cursor.y)- cursor.initialized = True- except Exception:- pass-- async def _get_box():- return await el.bounding_box()- try:- _, nx, ny, _ = await async_human_scroll_into_view(- page, raw_mouse, _get_box,- cursor.x, cursor.y, call_cfg,- )- cursor.x = nx- cursor.y = ny- except Exception:- if _orig_scroll_into_view is not None:- native_kwargs = {k: v for k, v in kwargs.items() if k != "human_config"}- await _orig_scroll_into_view(**native_kwargs)-- # --- el.press() ---- async def _human_el_press(key: str, **kwargs: Any) -> None:- await async_sleep_ms(rand(20, 60))- await originals.keyboard_press(- key,- **_keyboard_press_kwargs(kwargs, default_delay=rand_range(cfg.key_hold)),- )-- # --- el.select_option() ---- async def _human_el_select_option(value: Any = None, **kwargs: Any) -> Any:- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- await async_ensure_actionable_handle(page, el, CHECKS_FOCUS, timeout=_remaining_ms(), force=force)- info = await _move_to_element()- if info is None:- return await _orig_select_option(value, **kwargs)- await async_human_click(raw_mouse, False, cfg)- await async_sleep_ms(rand(100, 300))- return await _orig_select_option(value, **kwargs)-- # --- el.check() ---- async def _human_el_check(**kwargs: Any) -> None:- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- await async_ensure_actionable_handle(page, el, CHECKS_CHECK, timeout=_remaining_ms(), force=force)- try:- if await el.is_checked():- return- except Exception:- pass- info = await _move_to_element()- if info is None:- return await _orig_check(**kwargs)- if not force:- await async_check_pointer_events_handle(page, el, cursor.x, cursor.y, timeout=min(_remaining_ms(), 5000))- await async_human_click(raw_mouse, info['is_inp'], cfg)-- # --- el.uncheck() ---- async def _human_el_uncheck(**kwargs: Any) -> None:- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- await async_ensure_actionable_handle(page, el, CHECKS_CHECK, timeout=_remaining_ms(), force=force)- try:- if not await el.is_checked():- return- except Exception:- pass- info = await _move_to_element()- if info is None:- return await _orig_uncheck(**kwargs)- if not force:- await async_check_pointer_events_handle(page, el, cursor.x, cursor.y, timeout=min(_remaining_ms(), 5000))- await async_human_click(raw_mouse, info['is_inp'], cfg)-- # --- el.set_checked() ---- async def _human_el_set_checked(checked: bool, **kwargs: Any) -> None:- force = kwargs.get("force", False)- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- def _remaining_ms():- return max(0, (deadline - time.monotonic()) * 1000)- if not force:- await async_ensure_actionable_handle(page, el, CHECKS_CHECK, timeout=_remaining_ms(), force=force)- try:- current = await el.is_checked()- if current == checked:- return- except Exception:- pass- info = await _move_to_element()- if info is None and _orig_set_checked:- return await _orig_set_checked(checked, **kwargs)- if info:- if not force:- await async_check_pointer_events_handle(page, el, cursor.x, cursor.y, timeout=min(_remaining_ms(), 5000))- await async_human_click(raw_mouse, info['is_inp'], cfg)-- # --- el.tap() ---- async def _human_el_tap(**kwargs: Any) -> None:- info = await _move_to_element()- if info is None:- return await _orig_tap(**kwargs)- await async_human_click(raw_mouse, info['is_inp'], cfg)-- # --- el.focus() ---- # FIX: move cursor humanly but use programmatic focus (no click side-effects).- # Stock Playwright el.focus() never clicks — it just calls element.focus() in JS.- # Clicking would trigger onclick, submit forms, navigate links, etc.- async def _human_el_focus() -> None:- await _move_to_element() # human-like cursor movement (Bézier)- await _orig_focus() # programmatic focus, no click side-effects-- el.click = _human_el_click- el.dblclick = _human_el_dblclick- el.hover = _human_el_hover- el.type = _human_el_type- el.fill = _human_el_fill- el.press = _human_el_press- el.select_option = _human_el_select_option- el.check = _human_el_check- el.uncheck = _human_el_uncheck- if _orig_set_checked is not None:- el.set_checked = _human_el_set_checked- el.tap = _human_el_tap- el.focus = _human_el_focus- if _orig_scroll_into_view is not None:- el.scroll_into_view_if_needed = _human_el_scroll_into_view_if_needed---def _patch_page_element_handles_async(- page: Any, cfg: HumanConfig, cursor: _CursorState,- raw_mouse: AsyncRawMouse, raw_keyboard: AsyncRawKeyboard, originals: Any,- stealth: Any, cdp_session_holder: Any,-) -> None:- """Patch page.query_selector, query_selector_all, wait_for_selector to return humanized ElementHandles (async)."""- _orig_qs = page.query_selector- _orig_qsa = page.query_selector_all- _orig_wfs = page.wait_for_selector-- async def _patched_qs(selector: str, **kwargs: Any) -> Any:- el = await _orig_qs(selector, **kwargs)- if el is not None:- _patch_single_element_handle_async(- el, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session_holder- )- return el-- async def _patched_qsa(selector: str, **kwargs: Any) -> Any:- els = await _orig_qsa(selector, **kwargs)- for el in els:- _patch_single_element_handle_async(- el, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session_holder- )- return els-- async def _patched_wfs(selector: str, **kwargs: Any) -> Any:- el = await _orig_wfs(selector, **kwargs)- if el is not None:- _patch_single_element_handle_async(- el, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session_holder- )- return el-- page.query_selector = _patched_qs- page.query_selector_all = _patched_qsa- page.wait_for_selector = _patched_wfs---def _patch_frames_async(- page: Any, cfg: HumanConfig, cursor: _CursorState,- raw_mouse: AsyncRawMouse, raw_keyboard: AsyncRawKeyboard, originals: Any,-) -> None:- def _on_frame_attached(frame: Any) -> None:- try:- _patch_single_frame_async(frame, page, cfg, cursor, raw_mouse, raw_keyboard, originals)- except Exception:- logger.exception("Failed to humanize dynamically attached frame")-- # Async Playwright events accept a regular callback; patching only replaces- # methods, so no task or await is needed here.- if not getattr(page, "_human_frame_listener_attached", False):- page.on("frameattached", _on_frame_attached)- page._human_frame_listener_attached = True-- for frame in _iter_frames(page):- _patch_single_frame_async(frame, page, cfg, cursor, raw_mouse, raw_keyboard, originals)-- orig_main_frame = getattr(page, "_original_main_frame", None)- if orig_main_frame is None:- try:- _orig_goto = originals.goto-- async def _frame_aware_goto(url: str, **kwargs: Any) -> Any:- response = await _orig_goto(url, **kwargs)- # Invalidate isolated world after navigation- stealth_world = getattr(page, '_stealth_world', None)- if stealth_world is not None:- stealth_world.invalidate()- for frame in _iter_frames(page):- if not getattr(frame, "_human_patched", False):- _patch_single_frame_async(frame, page, cfg, cursor, raw_mouse, raw_keyboard, originals)- return response-- page.goto = _frame_aware_goto- page._original_main_frame = True- except Exception:- pass---def _patch_single_frame_async(- frame: Any, page: Any, cfg: HumanConfig, cursor: _CursorState,- raw_mouse: AsyncRawMouse, raw_keyboard: AsyncRawKeyboard, originals: Any,-) -> None:- if getattr(frame, "_human_patched", False):- return-- # Frame-scoped resolution (async): humanize via ``frame.locator(selector)`` so- # the selector resolves in the sub-frame's own document, while the mouse stays- # page-level. Mirrors the sync patcher / JS moveToFrameSelector. #428.- _orig_frame_click = frame.click- _orig_frame_dblclick = frame.dblclick- _orig_frame_hover = frame.hover- _orig_frame_type = frame.type- _orig_frame_fill = frame.fill- _orig_frame_check = frame.check- _orig_frame_uncheck = frame.uncheck- _orig_frame_select_option = frame.select_option- _orig_frame_press = frame.press- _orig_frame_drag_and_drop = getattr(frame, 'drag_and_drop', None)-- stealth_world = getattr(page, '_stealth_world', None)- cdp_session_holder = getattr(page, '_cdp_session_holder', [None])-- async def _get_cdp():- if cdp_session_holder[0] is None and stealth_world is not None:- try:- cdp_session_holder[0] = await stealth_world.get_cdp_session()- except Exception:- cdp_session_holder[0] = None- return cdp_session_holder[0]-- def _native_kwargs(kwargs: dict) -> dict:- return {k: v for k, v in kwargs.items() if k != "human_config"}-- def _deadline_remaining(kwargs: dict):- timeout = kwargs.get("timeout", 30000)- deadline = time.monotonic() + timeout / 1000.0- return lambda: max(0.0, (deadline - time.monotonic()) * 1000)-- async def _frame_is_input(selector: str) -> bool:- try:- return bool(await frame.locator(selector).first.evaluate(- "el => { const t = el.tagName.toLowerCase();"- " return t === 'input' || t === 'textarea'"- " || el.getAttribute('contenteditable') === 'true'; }"- ))- except Exception:- return False-- async def _frame_is_focused(selector: str) -> bool:- try:- return bool(await frame.locator(selector).first.evaluate(- "el => el === document.activeElement"- ))- except Exception:- return False-- async def _move_to_frame_selector(selector: str, kwargs: dict, input_bias: bool, remaining_ms):- call_cfg = merge_config(cfg, kwargs.get("human_config"))- if call_cfg.idle_between_actions:- await async_human_idle(raw_mouse, rand(call_cfg.idle_between_duration[0], call_cfg.idle_between_duration[1]), cursor.x, cursor.y, call_cfg)- loc = frame.locator(selector).first- try:- await loc.scroll_into_view_if_needed(timeout=max(1, remaining_ms()))- except Exception:- pass- try:- box = await loc.bounding_box(timeout=max(1, remaining_ms()))- except Exception:- box = None- if not box:- return None- is_input = input_bias or await _frame_is_input(selector)- target = click_target(box, is_input, call_cfg)- await async_human_move(raw_mouse, cursor.x, cursor.y, target.x, target.y, call_cfg)- cursor.x = target.x- cursor.y = target.y- return call_cfg, is_input-- async def _frame_click(selector: str, **kwargs: Any) -> None:- remaining_ms = _deadline_remaining(kwargs)- moved = await _move_to_frame_selector(selector, kwargs, False, remaining_ms)- if moved is None:- await _orig_frame_click(selector, **_native_kwargs(kwargs))- return- await async_human_click(raw_mouse, moved[1], moved[0])-- async def _frame_dblclick(selector: str, **kwargs: Any) -> None:- remaining_ms = _deadline_remaining(kwargs)- moved = await _move_to_frame_selector(selector, kwargs, False, remaining_ms)- if moved is None:- await _orig_frame_dblclick(selector, **_native_kwargs(kwargs))- return- await raw_mouse.down(click_count=2)- await async_sleep_ms(rand(30, 60))- await raw_mouse.up(click_count=2)-- async def _frame_hover(selector: str, **kwargs: Any) -> None:- remaining_ms = _deadline_remaining(kwargs)- moved = await _move_to_frame_selector(selector, kwargs, False, remaining_ms)- if moved is None:- await _orig_frame_hover(selector, **_native_kwargs(kwargs))-- async def _frame_type(selector: str, text: str, **kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- await async_sleep_ms(rand_range(call_cfg.field_switch_delay))- await _frame_click(selector, **kwargs)- await async_sleep_ms(rand(100, 250))- try:- cdp = await _get_cdp()- await async_human_type(page, raw_keyboard, text, call_cfg, cdp_session=cdp)- except Exception:- await _orig_frame_type(selector, text, **_native_kwargs(kwargs))-- async def _frame_fill(selector: str, value: str, **kwargs: Any) -> None:- call_cfg = merge_config(cfg, kwargs.get("human_config"))- await async_sleep_ms(rand_range(call_cfg.field_switch_delay))- await _frame_click(selector, **kwargs)- await async_sleep_ms(rand(100, 250))- await originals.keyboard_press(_SELECT_ALL)- await async_sleep_ms(rand(30, 80))- await originals.keyboard_press("Backspace")- await async_sleep_ms(rand(50, 150))- try:- cdp = await _get_cdp()- await async_human_type(page, raw_keyboard, value, call_cfg, cdp_session=cdp)- except Exception:- await _orig_frame_fill(selector, value, **_native_kwargs(kwargs))-- async def _frame_check(selector: str, **kwargs: Any) -> None:- try:- checked = await frame.locator(selector).first.is_checked()- except Exception:- await _orig_frame_check(selector, **_native_kwargs(kwargs))- return- if not checked:- try:- await _frame_click(selector, **kwargs)- except Exception:- await _orig_frame_check(selector, **_native_kwargs(kwargs))-- async def _frame_uncheck(selector: str, **kwargs: Any) -> None:- try:- checked = await frame.locator(selector).first.is_checked()- except Exception:- await _orig_frame_uncheck(selector, **_native_kwargs(kwargs))- return- if checked:- try:- await _frame_click(selector, **kwargs)- except Exception:- await _orig_frame_uncheck(selector, **_native_kwargs(kwargs))-- async def _frame_select_option(selector: str, value: Any = None, **kwargs: Any) -> Any:- await _frame_hover(selector, **kwargs)- await async_sleep_ms(rand(100, 300))- return await _orig_frame_select_option(selector, value, **_native_kwargs(kwargs))-- async def _frame_press(selector: str, key: str, **kwargs: Any) -> None:- if not await _frame_is_focused(selector):- await _frame_click(selector, **kwargs)- await async_sleep_ms(rand(50, 150))- await originals.keyboard_press(key, **_keyboard_press_kwargs(kwargs))-- async def _frame_clear(selector: str, **kwargs: Any) -> None:- if not await _frame_is_focused(selector):- await _frame_click(selector, **kwargs)- await async_sleep_ms(rand(50, 100))- await originals.keyboard_press(_SELECT_ALL)- await async_sleep_ms(rand(30, 80))- await originals.keyboard_press("Backspace")-- async def _frame_drag_and_drop(source: str, target: str, **kwargs: Any) -> None:- try:- src_box = await frame.locator(source).bounding_box()- tgt_box = await frame.locator(target).bounding_box()- except Exception:- src_box = tgt_box = None- if src_box and tgt_box:- sx = src_box['x'] + src_box['width'] / 2- sy = src_box['y'] + src_box['height'] / 2- tx = tgt_box['x'] + tgt_box['width'] / 2- ty = tgt_box['y'] + tgt_box['height'] / 2- await page.mouse.move(sx, sy)- await async_sleep_ms(rand(100, 200))- await originals.mouse_down()- await async_sleep_ms(rand(80, 150))- await page.mouse.move(tx, ty)- await async_sleep_ms(rand(80, 150))- await originals.mouse_up()- elif _orig_frame_drag_and_drop:- await _orig_frame_drag_and_drop(source, target, **kwargs)-- frame.click = _frame_click- frame.dblclick = _frame_dblclick- frame.hover = _frame_hover- frame.type = _frame_type- frame.fill = _frame_fill- frame.check = _frame_check- frame.uncheck = _frame_uncheck- frame.select_option = _frame_select_option- frame.press = _frame_press- frame.clear = _frame_clear- frame.drag_and_drop = _frame_drag_and_drop-- # --- Patch frame-level ElementHandle selectors (async) ---- _patch_frame_element_handles_async(- frame, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth_world, cdp_session_holder- )- frame._human_patched = True---def _patch_frame_element_handles_async(- frame: Any, page: Any, cfg: HumanConfig, cursor: _CursorState,- raw_mouse: AsyncRawMouse, raw_keyboard: AsyncRawKeyboard, originals: Any,- stealth: Any, cdp_session_holder: Any,-) -> None:- """Patch frame.query_selector, query_selector_all, wait_for_selector (async)."""- _orig_qs = frame.query_selector- _orig_qsa = frame.query_selector_all- _orig_wfs = frame.wait_for_selector-- async def _patched_qs(selector: str, **kwargs: Any) -> Any:- el = await _orig_qs(selector, **kwargs)- if el is not None:- _patch_single_element_handle_async(- el, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session_holder- )- return el-- async def _patched_qsa(selector: str, **kwargs: Any) -> Any:- els = await _orig_qsa(selector, **kwargs)- for el in els:- _patch_single_element_handle_async(- el, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session_holder- )- return els-- async def _patched_wfs(selector: str, **kwargs: Any) -> Any:- el = await _orig_wfs(selector, **kwargs)- if el is not None:- _patch_single_element_handle_async(- el, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, cdp_session_holder- )- return el-- frame.query_selector = _patched_qs- frame.query_selector_all = _patched_qsa- frame.wait_for_selector = _patched_wfs----def patch_context_async(context: Any, cfg: HumanConfig) -> None:- cursor = _CursorState()- for page in context.pages:- patch_page_async(page, cfg, cursor)- context.on("page", lambda p: patch_page_async(p, cfg, _CursorState()) if not hasattr(p, '_original') else None)-- orig_new_page = context.new_page-- async def _patched_new_page(**kwargs: Any) -> Any:- page = await orig_new_page(**kwargs)- if not hasattr(page, '_original'):- patch_page_async(page, cfg, _CursorState())- return page-- context.new_page = _patched_new_page---def patch_browser_async(browser: Any, cfg: HumanConfig) -> None:- for context in browser.contexts:- patch_context_async(context, cfg)-- orig_new_context = browser.new_context-- async def _patched_new_context(**kwargs: Any) -> Any:- context = await orig_new_context(**kwargs)- patch_context_async(context, cfg)- return context-- browser.new_context = _patched_new_context-- orig_new_page = browser.new_page-- async def _patched_new_page(**kwargs: Any) -> Any:- page = await orig_new_page(**kwargs)- if not hasattr(page, '_original'):- patch_page_async(page, cfg, _CursorState())- return page-- browser.new_page = _patched_new_pagediff --git a/cloakbrowser/human/actionability.py b/cloakbrowser/human/actionability.pydeleted file mode 100644index 3890fc6..0000000--- a/cloakbrowser/human/actionability.py+++ /dev/null@@ -1,384 +0,0 @@-"""Playwright-style actionability checks for the humanize layer (sync).--Checks: attached, visible, stable, enabled, editable, receives pointer events.-Retry loop with backoff matching Playwright internals: [100, 250, 500, 1000]ms.-"""--from __future__ import annotations--import time-from typing import Any, FrozenSet, Optional--from .stealth_dom import (- build_actionable_js, build_box_js, build_validate_js, eval_parsed,- EVALUATION_FAILED, NOT_FOUND, OK, STALE, UNSUPPORTED,- StealthEvaluationError, StealthWorldUnavailableError,- UnsupportedHumanizeSelectorError,-)--# ----------------------------------------------------------------------------# Error hierarchy — all subclass RuntimeError for backward compat-# -----------------------------------------------------------------------------class ActionabilityError(RuntimeError):- """Base for all actionability failures."""-- def __init__(self, selector: str, check: str, message: str):- self.selector = selector- self.check = check- super().__init__(f"Element {selector!r} failed {check} check: {message}")---class ElementNotAttachedError(ActionabilityError):- def __init__(self, selector: str):- super().__init__(selector, "attached", "element not found in DOM")---class ElementNotVisibleError(ActionabilityError):- def __init__(self, selector: str):- super().__init__(selector, "visible", "element is not visible")---class ElementNotStableError(ActionabilityError):- def __init__(self, selector: str):- super().__init__(selector, "stable", "element position is still changing")---class ElementNotEnabledError(ActionabilityError):- def __init__(self, selector: str):- super().__init__(selector, "enabled", "element is disabled")---class ElementNotEditableError(ActionabilityError):- def __init__(self, selector: str):- super().__init__(selector, "editable", "element is not editable")---class ElementNotReceivingEventsError(ActionabilityError):- def __init__(self, selector: str, covering_tag: str = "unknown"):- super().__init__(- selector,- "pointer_events",- f"element is covered by <{covering_tag}>",- )---class ElementTargetChangedError(ActionabilityError):- def __init__(self, selector: str):- super().__init__(- selector,- "target_identity",- "resolved element changed before pointer dispatch",- )---# ----------------------------------------------------------------------------# Check-set constants-# -----------------------------------------------------------------------------CHECKS_CLICK: FrozenSet[str] = frozenset({"attached", "visible", "enabled", "pointer_events"})-CHECKS_HOVER: FrozenSet[str] = frozenset({"attached", "visible", "pointer_events"})-CHECKS_INPUT: FrozenSet[str] = frozenset({"attached", "visible", "enabled", "editable", "pointer_events"})-CHECKS_FOCUS: FrozenSet[str] = frozenset({"attached", "visible", "enabled"})-CHECKS_CHECK: FrozenSet[str] = frozenset({"attached", "visible", "enabled", "pointer_events"})--_BACKOFF_MS = [100, 250, 500, 1000]---def _backoff_sleep(attempt: int) -> None:- idx = min(attempt, len(_BACKOFF_MS) - 1)- time.sleep(_BACKOFF_MS[idx] / 1000.0)---# ----------------------------------------------------------------------------# Pre-scroll actionability: attached, visible, enabled, editable-# -----------------------------------------------------------------------------def _stealth_actionable(page: Any, selector: str, checks: FrozenSet[str]) -> None:- """Run actionability checks exclusively through the isolated world."""- world = getattr(page, "_stealth_world", None)- if world is None:- raise StealthWorldUnavailableError()- status, data = eval_parsed(world, build_actionable_js(selector))- if status == UNSUPPORTED:- raise UnsupportedHumanizeSelectorError(selector)- if status == EVALUATION_FAILED:- raise StealthEvaluationError(selector)- if status == NOT_FOUND:- # Every check-set includes 'attached'; not present yet -> raise so the- # retry loop backs off and re-reads in-world (mirrors wait_for(attached)).- raise ElementNotAttachedError(selector)- if "visible" in checks and not data.get("visible"):- raise ElementNotVisibleError(selector)- if "enabled" in checks and not data.get("enabled"):- raise ElementNotEnabledError(selector)- if "editable" in checks and not data.get("editable"):- raise ElementNotEditableError(selector)---def _read_box(page: Any, selector: str, remaining_ms: float) -> Optional[dict]:- """Read geometry exclusively through the isolated world."""- world = getattr(page, "_stealth_world", None)- if world is None:- raise StealthWorldUnavailableError()- status, data = eval_parsed(world, build_box_js(selector))- if status == OK:- return data["box"]- if status == NOT_FOUND:- return None- if status == UNSUPPORTED:- raise UnsupportedHumanizeSelectorError(selector)- raise StealthEvaluationError(selector)---def ensure_actionable(- page: Any,- selector: str,- checks: FrozenSet[str],- timeout: float = 30000,- force: bool = False,-) -> None:- """Wait for element to pass actionability checks (pre-scroll).-- Retries with backoff until *timeout* ms elapsed.- Raises a specific ``ActionabilityError`` subclass on failure.- If *force* is True, returns immediately.- """- if force:- return-- deadline = time.monotonic() + timeout / 1000.0- attempt = 0- last_error: Optional[ActionabilityError] = None-- while True:- remaining_ms = max(0, (deadline - time.monotonic()) * 1000)- if remaining_ms <= 0:- if last_error is not None:- raise last_error- raise ActionabilityError(selector, "timeout", "timeout expired before first check")-- try:- _stealth_actionable(page, selector, checks)- return-- except (ActionabilityError, StealthEvaluationError) as e:- last_error = e- if time.monotonic() >= deadline:- raise last_error- _backoff_sleep(attempt)- attempt += 1---# ----------------------------------------------------------------------------# Post-scroll stability check-# -----------------------------------------------------------------------------def _boxes_differ(a: dict, b: dict) -> bool:- return (- abs(a["x"] - b["x"]) > 1- or abs(a["y"] - b["y"]) > 1- or abs(a["width"] - b["width"]) > 1- or abs(a["height"] - b["height"]) > 1- )---def ensure_stable(- page: Any,- selector: str,- timeout: float = 5000,-) -> None:- """Wait for element position to stabilize (two samples 100ms apart).-- Only call after scroll — skip if element was already in viewport.- """- deadline = time.monotonic() + timeout / 1000.0- attempt = 0-- while True:- remaining_ms = max(0, (deadline - time.monotonic()) * 1000)- if remaining_ms <= 0:- raise ElementNotStableError(selector)-- try:- box1 = _read_box(page, selector, remaining_ms)- if box1 is None:- raise ElementNotAttachedError(selector)-- time.sleep(0.1)-- box2 = _read_box(page, selector, remaining_ms)- if box2 is None:- raise ElementNotAttachedError(selector)- except StealthEvaluationError:- if time.monotonic() >= deadline:- raise- _backoff_sleep(attempt)- attempt += 1- continue-- if not _boxes_differ(box1, box2):- return-- if time.monotonic() >= deadline:- raise ElementNotStableError(selector)-- _backoff_sleep(attempt)- attempt += 1---# ----------------------------------------------------------------------------# Pointer-events check (post-scroll, at actual click coordinates)-# -----------------------------------------------------------------------------# Legacy ElementHandle paths cannot use selector-based isolated-world identity.-_POINTER_EVENTS_HANDLE_JS = """(expected, data) => {- const rect = expected.getBoundingClientRect();- const frameOffsetX = data.box ? data.box.x - rect.x : 0;- const frameOffsetY = data.box ? data.box.y - rect.y : 0;- const target = document.elementFromPoint(data.x - frameOffsetX, data.y - frameOffsetY);- if (!target) return { hit: false, reason: 'no_element_at_point', covering: 'none' };- let node = target;- while (node) { if (node === expected) return { hit: true }; node = node.parentNode; }- if (expected.contains(target)) return { hit: true };- return { hit: false, reason: 'covered', covering: target.tagName || 'unknown' };-}"""---def check_pointer_events(- page: Any,- selector: str,- target_id: int,- gen: int,- x: float,- y: float,- stealth: Any = None,- timeout: float = 5000,-) -> None:- """Revalidate that the click point still hits the same resolved element.-- Callers skip this entirely when ``force=True`` (matching Playwright, where- ``force`` bypasses all actionability checks).- """- deadline = time.monotonic() + timeout / 1000.0- attempt = 0- last_miss: Optional[str] = None- world = stealth if stealth is not None else getattr(page, "_stealth_world", None)- if world is None:- raise StealthWorldUnavailableError()- if not isinstance(target_id, int) or not isinstance(gen, int):- raise StealthEvaluationError(selector)-- while True:- status, data = eval_parsed(- world, build_validate_js(selector, target_id, gen, x, y)- )- if status == UNSUPPORTED:- raise UnsupportedHumanizeSelectorError(selector)- if status == STALE:- raise ElementTargetChangedError(selector)- if status == NOT_FOUND:- raise ElementNotAttachedError(selector)- if status == EVALUATION_FAILED:- if time.monotonic() >= deadline:- raise StealthEvaluationError(selector)- elif data.get("hit", False):- return- else:- last_miss = data.get("covering", "unknown")- if time.monotonic() >= deadline:- raise ElementNotReceivingEventsError(selector, last_miss)-- _backoff_sleep(attempt)- attempt += 1---# ----------------------------------------------------------------------------# ElementHandle variant-# -----------------------------------------------------------------------------def ensure_actionable_handle(- page: Any,- el: Any,- checks: FrozenSet[str],- timeout: float = 30000,- force: bool = False,-) -> None:- """Actionability checks for ElementHandle (no selector needed).-- Uses Playwright's wait_for_element_state where available.- """- if force:- return-- deadline = time.monotonic() + timeout / 1000.0- attempt = 0- last_error: Optional[ActionabilityError] = None- label = "<ElementHandle>"-- while True:- remaining_ms = max(0, (deadline - time.monotonic()) * 1000)- if remaining_ms <= 0:- if last_error is not None:- raise last_error- raise ActionabilityError(label, "timeout", "timeout expired before first check")-- try:- if "visible" in checks:- try:- el.wait_for_element_state("visible", timeout=max(1, min(remaining_ms, 2000)))- except Exception:- raise ElementNotVisibleError(label)-- if "enabled" in checks:- try:- el.wait_for_element_state("enabled", timeout=max(1, min(remaining_ms, 2000)))- except Exception:- raise ElementNotEnabledError(label)-- if "editable" in checks:- try:- el.wait_for_element_state("editable", timeout=max(1, min(remaining_ms, 2000)))- except Exception:- raise ElementNotEditableError(label)-- return-- except ActionabilityError as e:- last_error = e- if time.monotonic() >= deadline:- raise last_error- _backoff_sleep(attempt)- attempt += 1---def check_pointer_events_handle(- page: Any,- el: Any,- x: float,- y: float,- timeout: float = 5000,-) -> None:- """Pointer-events check for ElementHandle."""- deadline = time.monotonic() + timeout / 1000.0- attempt = 0-- while True:- try:- box = el.bounding_box()- result = el.evaluate(_POINTER_EVENTS_HANDLE_JS, {"x": x, "y": y, "box": box})- except Exception:- result = None-- # Proceed if the check confirms a hit, or if it could not be determined- # (None) — failing closed would block legitimate clicks.- if result is None or result.get("hit", False):- return-- covering = (result or {}).get("covering", "unknown")-- if time.monotonic() >= deadline:- raise ElementNotReceivingEventsError("<ElementHandle>", covering)-- _backoff_sleep(attempt)- attempt += 1diff --git a/cloakbrowser/human/actionability_async.py b/cloakbrowser/human/actionability_async.pydeleted file mode 100644index b64e7ce..0000000--- a/cloakbrowser/human/actionability_async.py+++ /dev/null@@ -1,284 +0,0 @@-"""Playwright-style actionability checks for the humanize layer (async).--Async mirror of actionability.py — same logic, uses asyncio.sleep and await.-"""--from __future__ import annotations--import asyncio-import time-from typing import Any, FrozenSet, Optional--from .actionability import (- ActionabilityError,- ElementNotAttachedError,- ElementNotVisibleError,- ElementNotStableError,- ElementNotEnabledError,- ElementNotEditableError,- ElementNotReceivingEventsError,- ElementTargetChangedError,- _BACKOFF_MS,- _boxes_differ,- _POINTER_EVENTS_HANDLE_JS,-)-from .stealth_dom import (- build_actionable_js, build_box_js, build_validate_js, async_eval_parsed,- EVALUATION_FAILED, NOT_FOUND, OK, STALE, UNSUPPORTED,- StealthEvaluationError, StealthWorldUnavailableError,- UnsupportedHumanizeSelectorError,-)---async def _async_backoff_sleep(attempt: int) -> None:- idx = min(attempt, len(_BACKOFF_MS) - 1)- await asyncio.sleep(_BACKOFF_MS[idx] / 1000.0)---# ----------------------------------------------------------------------------# Pre-scroll actionability-# -----------------------------------------------------------------------------async def _async_stealth_actionable(page: Any, selector: str, checks: FrozenSet[str]) -> None:- """Async isolated-world actionability read with no Playwright fallback."""- world = getattr(page, "_stealth_world", None)- if world is None:- raise StealthWorldUnavailableError()- status, data = await async_eval_parsed(world, build_actionable_js(selector))- if status == UNSUPPORTED:- raise UnsupportedHumanizeSelectorError(selector)- if status == EVALUATION_FAILED:- raise StealthEvaluationError(selector)- if status == NOT_FOUND:- raise ElementNotAttachedError(selector)- if "visible" in checks and not data.get("visible"):- raise ElementNotVisibleError(selector)- if "enabled" in checks and not data.get("enabled"):- raise ElementNotEnabledError(selector)- if "editable" in checks and not data.get("editable"):- raise ElementNotEditableError(selector)---async def _async_read_box(page: Any, selector: str, remaining_ms: float) -> Optional[dict]:- """Async isolated-world geometry read with no Playwright fallback."""- world = getattr(page, "_stealth_world", None)- if world is None:- raise StealthWorldUnavailableError()- status, data = await async_eval_parsed(world, build_box_js(selector))- if status == OK:- return data["box"]- if status == NOT_FOUND:- return None- if status == UNSUPPORTED:- raise UnsupportedHumanizeSelectorError(selector)- raise StealthEvaluationError(selector)---async def async_ensure_actionable(- page: Any,- selector: str,- checks: FrozenSet[str],- timeout: float = 30000,- force: bool = False,-) -> None:- if force:- return-- deadline = time.monotonic() + timeout / 1000.0- attempt = 0- last_error: Optional[ActionabilityError] = None-- while True:- remaining_ms = max(0, (deadline - time.monotonic()) * 1000)- if remaining_ms <= 0:- if last_error is not None:- raise last_error- raise ActionabilityError(selector, "timeout", "timeout expired before first check")-- try:- await _async_stealth_actionable(page, selector, checks)- return-- except (ActionabilityError, StealthEvaluationError) as e:- last_error = e- if time.monotonic() >= deadline:- raise last_error- await _async_backoff_sleep(attempt)- attempt += 1---# ----------------------------------------------------------------------------# Post-scroll stability check-# -----------------------------------------------------------------------------async def async_ensure_stable(- page: Any,- selector: str,- timeout: float = 5000,-) -> None:- deadline = time.monotonic() + timeout / 1000.0- attempt = 0-- while True:- remaining_ms = max(0, (deadline - time.monotonic()) * 1000)- if remaining_ms <= 0:- raise ElementNotStableError(selector)-- try:- box1 = await _async_read_box(page, selector, remaining_ms)- if box1 is None:- raise ElementNotAttachedError(selector)-- await asyncio.sleep(0.1)-- box2 = await _async_read_box(page, selector, remaining_ms)- if box2 is None:- raise ElementNotAttachedError(selector)- except StealthEvaluationError:- if time.monotonic() >= deadline:- raise- await _async_backoff_sleep(attempt)- attempt += 1- continue-- if not _boxes_differ(box1, box2):- return-- if time.monotonic() >= deadline:- raise ElementNotStableError(selector)-- await _async_backoff_sleep(attempt)- attempt += 1---# ----------------------------------------------------------------------------# Pointer-events check-# -----------------------------------------------------------------------------async def async_check_pointer_events(- page: Any,- selector: str,- target_id: int,- gen: int,- x: float,- y: float,- stealth: Any = None,- timeout: float = 5000,-) -> None:- deadline = time.monotonic() + timeout / 1000.0- attempt = 0- last_miss: Optional[str] = None- world = stealth if stealth is not None else getattr(page, "_stealth_world", None)- if world is None:- raise StealthWorldUnavailableError()- if not isinstance(target_id, int) or not isinstance(gen, int):- raise StealthEvaluationError(selector)-- while True:- status, data = await async_eval_parsed(- world, build_validate_js(selector, target_id, gen, x, y)- )- if status == UNSUPPORTED:- raise UnsupportedHumanizeSelectorError(selector)- if status == STALE:- raise ElementTargetChangedError(selector)- if status == NOT_FOUND:- raise ElementNotAttachedError(selector)- if status == EVALUATION_FAILED:- if time.monotonic() >= deadline:- raise StealthEvaluationError(selector)- elif data.get("hit", False):- return- else:- last_miss = data.get("covering", "unknown")- if time.monotonic() >= deadline:- raise ElementNotReceivingEventsError(selector, last_miss)-- await _async_backoff_sleep(attempt)- attempt += 1---# ----------------------------------------------------------------------------# ElementHandle variant-# -----------------------------------------------------------------------------async def async_ensure_actionable_handle(- page: Any,- el: Any,- checks: FrozenSet[str],- timeout: float = 30000,- force: bool = False,-) -> None:- if force:- return-- deadline = time.monotonic() + timeout / 1000.0- attempt = 0- last_error: Optional[ActionabilityError] = None- label = "<ElementHandle>"-- while True:- remaining_ms = max(0, (deadline - time.monotonic()) * 1000)- if remaining_ms <= 0:- if last_error is not None:- raise last_error- raise ActionabilityError(label, "timeout", "timeout expired before first check")-- try:- if "visible" in checks:- try:- await el.wait_for_element_state("visible", timeout=max(1, min(remaining_ms, 2000)))- except Exception:- raise ElementNotVisibleError(label)-- if "enabled" in checks:- try:- await el.wait_for_element_state("enabled", timeout=max(1, min(remaining_ms, 2000)))- except Exception:- raise ElementNotEnabledError(label)-- if "editable" in checks:- try:- await el.wait_for_element_state("editable", timeout=max(1, min(remaining_ms, 2000)))- except Exception:- raise ElementNotEditableError(label)-- return-- except ActionabilityError as e:- last_error = e- if time.monotonic() >= deadline:- raise last_error- await _async_backoff_sleep(attempt)- attempt += 1---async def async_check_pointer_events_handle(- page: Any,- el: Any,- x: float,- y: float,- timeout: float = 5000,-) -> None:- deadline = time.monotonic() + timeout / 1000.0- attempt = 0-- while True:- try:- box = await el.bounding_box()- result = await el.evaluate(_POINTER_EVENTS_HANDLE_JS, {"x": x, "y": y, "box": box})- except Exception:- result = None-- # Proceed if the check confirms a hit, or if it could not be determined- # (None) — failing closed would block legitimate clicks.- if result is None or result.get("hit", False):- return-- covering = (result or {}).get("covering", "unknown")-- if time.monotonic() >= deadline:- raise ElementNotReceivingEventsError("<ElementHandle>", covering)-- await _async_backoff_sleep(attempt)- attempt += 1diff --git a/cloakbrowser/human/engine.py b/cloakbrowser/human/engine.pynew file mode 100644index 0000000..bf38d95--- /dev/null+++ b/cloakbrowser/human/engine.py@@ -0,0 +1,1099 @@+"""Unified humanized action pipeline (async core, Playwright impl objects).++One implementation drives page / frame / locator / element-handle actions for+both the sync and the async Playwright API:++ resolve (isolated world, Playwright selector engine, strict mode)+ -> wait for element states (visible / enabled / editable / stable)+ -> scroll into view with mouse-wheel bursts (page, iframes, containers)+ -> Bezier move to a point inside the visible part of the element+ -> hit-target check (element itself, and every ancestor <iframe>)+ -> press / type++Nothing falls back to Playwright's stock actions, and failures raise+Playwright ``Error`` / ``TimeoutError``.+"""++from __future__ import annotations++import re+import sys++import asyncio+import math+import random+import time+from typing import Any, Awaitable, Callable, Dict, List, Optional, Sequence, Tuple++from playwright._impl._errors import Error, TimeoutError++from . import fields+from .config import HumanConfig, merge_config, rand, rand_int_range, rand_range+from .keyboard import NEARBY_KEYS, SHIFT_SYMBOLS, _SHIFT_SYMBOL_CODES, _SHIFT_SYMBOL_KEYCODES+from .mouse import Point, _bezier, _ease_in_out, _random_control_points, click_target+from .world import HELPERS, StaleElement, Worlds, intersect++ENTER_FRAME = " >> internal:control=enter-frame >> "+_ENTER_FRAME_SPLIT = re.compile(r"\s*>>\s*internal:control=enter-frame\s*>>\s*")++CLICK_STATES = ["visible", "enabled", "stable"]+HOVER_STATES = ["visible", "stable"]+INPUT_STATES = ["visible", "enabled", "editable"]+FOCUS_STATES = ["visible", "enabled"]++_RETRY_MS = [0, 20, 100, 100, 500]+++class CursorState:+ __slots__ = ("x", "y", "initialized")++ def __init__(self) -> None:+ self.x: float = 0+ self.y: float = 0+ self.initialized: bool = False+++async def sleep_ms(ms: float) -> None:+ if ms > 0:+ await asyncio.sleep(ms / 1000.0)+++# ---------------------------------------------------------------------------+# Targets+# ---------------------------------------------------------------------------++class Target:+ """What an action is aimed at: a selector in a frame, or an ElementHandle."""++ __slots__ = ("frame", "selector", "strict", "handle", "description")++ def __init__(self, frame: Any, selector: Optional[str] = None, strict: bool = False,+ handle: Any = None) -> None:+ self.frame = frame+ self.selector = selector+ self.strict = strict+ self.handle = handle+ self.description = f"locator({selector!r})" if selector is not None else "element handle"+++class Resolved:+ __slots__ = ("frame", "id")++ def __init__(self, frame: Any, element_id: int) -> None:+ self.frame = frame+ self.id = element_id+++class _Deadline:+ def __init__(self, timeout_ms: float) -> None:+ self.timeout = timeout_ms+ self._end = None if not timeout_ms else time.monotonic() + timeout_ms / 1000.0++ def remaining(self) -> float:+ if self._end is None:+ return math.inf+ return max(0.0, (self._end - time.monotonic()) * 1000.0)++ def left(self) -> float:+ """Remaining budget as a Playwright timeout value (0 = no limit)."""+ return 0 if self._end is None else max(1.0, self.remaining())++ def expired(self) -> bool:+ return self._end is not None and time.monotonic() >= self._end+++class _Retry(Exception):+ """Internal: the current attempt failed for ``reason``; retry until timeout."""++ def __init__(self, reason: str) -> None:+ super().__init__(reason)+ self.reason = reason+++# ---------------------------------------------------------------------------+# Human+# ---------------------------------------------------------------------------++class Human:+ """Humanized input for one Playwright impl page."""++ def __init__(self, page: Any, cfg: HumanConfig, cursor: CursorState) -> None:+ self.page = page+ self.cfg = cfg+ self.cursor = cursor+ self.worlds = Worlds(page)+ self.mouse = page.mouse+ self.keyboard = page.keyboard+ self._platform: Optional[str] = None+ self._handle_ids: Dict[str, Tuple[Any, int, int]] = {}+ self._buttons_down: set = set()++ # -- configuration ------------------------------------------------------++ def call_cfg(self, overrides: Optional[dict]) -> HumanConfig:+ return merge_config(self.cfg, overrides)++ def timeout(self, frame: Any, timeout: Optional[float]) -> float:+ return float(frame._timeout(timeout))++ def deadline(self, target: Target, opts: dict) -> "_Deadline":+ """Deadline for an action; nested sub-actions share their caller's."""+ d = opts.get("_deadline")+ return d if d is not None else _Deadline(self.timeout(target.frame, opts.get("timeout")))++ async def platform(self) -> str:+ """Persona platform (``navigator.platform`` read in the isolated world)."""+ if self._platform is None:+ try:+ self._platform = str(await self.worlds.call(self.page.main_frame, "platform"))+ except Error:+ self._platform = ""+ return self._platform++ async def is_mac(self) -> bool:+ return (await self.platform()).lower().startswith("mac")++ async def select_all_key(self) -> str:+ return "Meta+a" if await self.is_mac() else "Control+a"++ async def _modifier(self, key: str) -> str:+ if key == "ControlOrMeta":+ return "Meta" if await self.is_mac() else "Control"+ return key++ # -- cursor -------------------------------------------------------------++ async def ensure_cursor(self, cfg: Optional[HumanConfig] = None) -> None:+ if not self.cursor.initialized:+ cfg = cfg or self.cfg+ self.cursor.x = rand(*cfg.initial_cursor_x)+ self.cursor.y = rand(*cfg.initial_cursor_y)+ await self.mouse.move(self.cursor.x, self.cursor.y)+ self.cursor.initialized = True++ async def move_to(self, x: float, y: float, cfg: HumanConfig) -> None:+ """Bezier move from the current cursor position to (x, y)."""+ await self.ensure_cursor(cfg)+ sx, sy = self.cursor.x, self.cursor.y+ dist = math.hypot(x - sx, y - sy)+ if dist >= 1:+ steps = max(cfg.mouse_min_steps, min(cfg.mouse_max_steps, round(dist / cfg.mouse_steps_divisor)))+ start, end = Point(sx, sy), Point(x, y)+ cp1, cp2 = _random_control_points(start, end)+ burst, burst_size = 0, rand_int_range(cfg.mouse_burst_size)+ for i in range(1, steps + 1):+ progress = i / steps+ pt = _bezier(start, cp1, cp2, end, _ease_in_out(progress))+ wobble = math.sin(math.pi * progress) * cfg.mouse_wobble_max+ if i == steps:+ await self.mouse.move(x, y) # exact end point (position= offsets)+ continue+ else:+ wx = pt.x + (random.random() - 0.5) * 2 * wobble+ wy = pt.y + (random.random() - 0.5) * 2 * wobble+ await self.mouse.move(round(wx), round(wy))+ burst += 1+ if burst >= burst_size and i < steps:+ await sleep_ms(rand_range(cfg.mouse_burst_pause))+ burst = 0+ if random.random() < cfg.mouse_overshoot_chance:+ angle = math.atan2(y - sy, x - sx)+ over = rand_range(cfg.mouse_overshoot_px)+ await self.mouse.move(round(x + math.cos(angle) * over), round(y + math.sin(angle) * over))+ await sleep_ms(rand(30, 70))+ await self.mouse.move(x, y)+ self.cursor.x, self.cursor.y = x, y++ async def idle(self, cfg: HumanConfig) -> None:+ if not cfg.idle_between_actions:+ return+ await self.ensure_cursor(cfg)+ end = time.monotonic() + rand(*cfg.idle_between_duration)+ x, y = self.cursor.x, self.cursor.y+ while time.monotonic() < end:+ x += (random.random() - 0.5) * 2 * cfg.idle_drift_px+ y += (random.random() - 0.5) * 2 * cfg.idle_drift_px+ await self.mouse.move(round(x), round(y))+ await sleep_ms(min(rand_range(cfg.idle_pause_range), max(0.0, (end - time.monotonic()) * 1000)))+ # Drift is noise around the resting point, not a new position.+ await self.mouse.move(self.cursor.x, self.cursor.y)++ # -- resolution ---------------------------------------------------------++ async def resolve(self, target: Target, deadline: _Deadline) -> Resolved:+ """Resolve once. Raises ``_Retry`` (not yet there) or ``Error`` (final)."""+ if target.handle is not None:+ return await self._resolve_handle(target.handle, deadline)+ frame = target.frame+ parts = _ENTER_FRAME_SPLIT.split(target.selector)+ for i, part in enumerate(parts):+ res = await self.worlds.call(frame, "resolve", part, bool(target.strict), 0)+ status = res["status"]+ if status == "none":+ raise _Retry(f"waiting for {target.description}")+ if status == "strict":+ raise Error(res["message"])+ if status == "error":+ raise Error(res["message"])+ if i == len(parts) - 1:+ return Resolved(frame, res["id"])+ child = await self.worlds.content_frame(frame, res["id"])+ if child is None:+ raise _Retry(f"waiting for the frame of {target.description}")+ frame = child+ raise Error("unreachable") # pragma: no cover++ async def _resolve_handle(self, handle: Any, deadline: _Deadline) -> Resolved:+ frame = handle._frame+ rec = await self.worlds._ready(frame)+ cached = self._handle_ids.get(handle._guid)+ if cached and cached[0] is frame and cached[1] == rec.ctx:+ return Resolved(frame, cached[2])+ # An ElementHandle carries no identity our context can read, so find+ # the element with exactly its border box.+ box = await handle.bounding_box()+ if box is None:+ if cached and cached[0] is frame:+ # Resolved in an earlier document of this frame and gone now+ # (a same-document navigation keeps the element, and its box).+ raise Error("Element is not attached to the DOM")+ raise _Retry("element is not visible")+ ox, oy, _ = await self.worlds.frame_geometry(frame)+ res = await self.worlds.call(frame, "matchRect", box["x"] - ox, box["y"] - oy,+ box["width"], box["height"])+ if res.get("count") != 1:+ raise Error(+ "cloakbrowser humanize: cannot identify the element behind this ElementHandle "+ "inside the isolated world (it shares its box with another element); "+ "use a Locator instead"+ )+ self._handle_ids[handle._guid] = (frame, rec.ctx, res["id"])+ return Resolved(frame, res["id"])++ async def wait_for(self, target: Target, states: Sequence[str], deadline: _Deadline,+ api: str, force: bool = False) -> Resolved:+ """Resolve and wait for ``states``; Playwright-style retry + timeout."""+ return await self.retry(api, target, deadline, lambda: self._attempt_states(target, states, deadline, force))++ async def _attempt_states(self, target: Target, states: Sequence[str], deadline: _Deadline,+ force: bool) -> Resolved:+ r = await self.resolve(target, deadline)+ if force:+ return r+ res = await self.worlds.call(r.frame, "states", r.id, list(states))+ if res is None:+ return r+ if "error" in res:+ raise Error(res["error"])+ missing = res["missing"]+ if missing == "attached":+ if target.handle is not None:+ raise Error("Element is not attached to the DOM")+ raise _Retry("element was detached from the DOM, retrying")+ raise _Retry(f"element is not {missing}")++ async def retry(self, api: str, target: Target, deadline: _Deadline,+ attempt: Callable[[], Awaitable[Any]]) -> Any:+ reasons: List[str] = []+ n = 0+ while True:+ try:+ return await attempt()+ except StaleElement:+ if target.handle is not None:+ raise Error(f"{api}: Element is not attached to the DOM") from None+ self._note(reasons, "element was detached from the DOM, retrying")+ except _Retry as r:+ self._note(reasons, r.reason)+ except Error as exc:+ msg = str(exc)+ if msg.startswith(api):+ raise+ raise type(exc)(f"{api}: {msg}") from None+ if deadline.expired():+ log = "\n".join(f" - {r}" for r in [f"waiting for {target.description}"] + reasons[-5:])+ raise TimeoutError(f"{api}: Timeout {deadline.timeout:.0f}ms exceeded.\nCall log:\n{log}")+ wait = _RETRY_MS[min(n, len(_RETRY_MS) - 1)]+ n += 1+ await sleep_ms(min(wait, deadline.remaining()))++ @staticmethod+ def _note(reasons: List[str], reason: str) -> None:+ if not reasons or reasons[-1] != reason:+ reasons.append(reason)++ # -- geometry -----------------------------------------------------------++ async def element_box(self, r: Resolved) -> Optional[Dict[str, float]]:+ """Element border box in viewport coordinates plus its visible clip."""+ g = await self.worlds.call(r.frame, "geometry", r.id)+ if g is None:+ raise StaleElement()+ ox, oy, clip = await self.worlds.frame_geometry(r.frame)+ box = {"x": g["x"] + ox, "y": g["y"] + oy, "width": g["width"], "height": g["height"],+ "bl": g["bl"], "bt": g["bt"]}+ scroller = await self.worlds.call(r.frame, "scroller", r.id)+ if scroller:+ sc = {"x": scroller["x"] + ox, "y": scroller["y"] + oy,+ "width": scroller["width"], "height": scroller["height"]}+ clip = intersect(clip, sc)+ box["scroller"] = sc+ box["clip"] = clip+ box["visible"] = intersect(clip, box)+ return box++ # -- scrolling ----------------------------------------------------------++ async def scroll_into_view(self, r: Resolved, cfg: HumanConfig, deadline: _Deadline) -> Dict[str, Any]:+ """Wheel-scroll until the element sits inside its visible clip (and, for+ the main document, inside ``scroll_target_zone`` when the page can+ still scroll that way). Returns the final box."""+ box = await self.element_box(r)+ vp = await self.worlds.viewport()+ stalled = rounds = 0+ overshot = False+ while stalled < 2 and rounds < 40 and not deadline.expired():+ dx, dy = await self._needed_scroll(r, box, vp, cfg)+ if abs(dx) < 1 and abs(dy) < 1:+ break+ rounds += 1+ area = box["clip"] if box["clip"]["width"] > 4 and box["clip"]["height"] > 4 else \+ {"x": 0.0, "y": 0.0, "width": float(vp["width"]), "height": float(vp["height"])}+ if not self._inside(area, self.cursor):+ await self.move_to(area["x"] + area["width"] * rand(0.3, 0.7),+ area["y"] + area["height"] * rand(0.3, 0.7), cfg)+ await sleep_ms(rand_range(cfg.scroll_pre_move_delay))+ before = (box["x"], box["y"])+ if abs(dy) >= 1:+ await self._wheel_burst(0, dy, cfg, deadline)+ if not overshot:+ overshot = True+ await self._overshoot(dy, cfg, deadline)+ if abs(dx) >= 1:+ await self._wheel_burst(dx, 0, cfg, deadline)+ await sleep_ms(min(rand_range(cfg.scroll_settle_delay), deadline.remaining()))+ box = await self.element_box(r)+ moved = abs(box["x"] - before[0]) + abs(box["y"] - before[1])+ stalled = stalled + 1 if moved < 1 else 0+ return box++ @staticmethod+ def _inside(area: Dict[str, float], c: CursorState) -> bool:+ return area["x"] <= c.x <= area["x"] + area["width"] and area["y"] <= c.y <= area["y"] + area["height"]++ async def _needed_scroll(self, r: Resolved, box: Dict[str, Any], vp: Dict[str, float],+ cfg: HumanConfig) -> Tuple[float, float]:+ clip = box["clip"]+ if clip["width"] <= 0 or clip["height"] <= 0:+ # The frame (or container) itself is out of view: bring it in first.+ return 0.0, (box["y"] + box["height"] / 2) - vp["height"] / 2+ dy = dx = 0.0+ # Vertical+ top, bottom = box["y"], box["y"] + box["height"]+ main_doc = r.frame.parent_frame is None and not box.get("scroller")+ if main_doc and box["height"] <= vp["height"] * (cfg.scroll_target_zone[1] - cfg.scroll_target_zone[0]):+ zt, zb = vp["height"] * cfg.scroll_target_zone[0], vp["height"] * cfg.scroll_target_zone[1]+ if top < zt or bottom > zb:+ dy = (top + box["height"] / 2) - vp["height"] * rand(*cfg.scroll_target_zone)+ if top >= clip["y"] - 1 and bottom <= clip["y"] + clip["height"] + 1:+ # Fully visible but off-centre: only if the page can scroll that way.+ doc = await self.worlds.call(self.page.main_frame, "doc")+ if (dy < 0 and doc["y"] <= 0) or (dy > 0 and doc["y"] >= doc["maxY"]):+ dy = 0.0+ elif box["height"] <= clip["height"]:+ if top < clip["y"] - 1 or bottom > clip["y"] + clip["height"] + 1:+ dy = (top + box["height"] / 2) - (clip["y"] + clip["height"] / 2)+ elif box["visible"]["height"] < clip["height"] * 0.5:+ dy = top - clip["y"] - clip["height"] * 0.1+ # Horizontal (#521): containment only.+ left, right = box["x"], box["x"] + box["width"]+ if box["width"] <= clip["width"]:+ if left < clip["x"] - 1 or right > clip["x"] + clip["width"] + 1:+ dx = (left + box["width"] / 2) - (clip["x"] + clip["width"] / 2)+ elif box["visible"]["width"] <= 0:+ dx = left - clip["x"]+ return dx, dy++ async def _overshoot(self, dy: float, cfg: HumanConfig, deadline: _Deadline) -> None:+ """Sometimes scroll a little past the target, pause, and wheel back+ (``scroll_overshoot_chance`` / ``scroll_overshoot_px``). The next+ round of :meth:`scroll_into_view` fixes whatever is left."""+ if random.random() >= cfg.scroll_overshoot_chance or deadline.expired():+ return+ sign = 1 if dy > 0 else -1+ await self._wheel_burst(0, round(rand_range(cfg.scroll_overshoot_px)) * sign, cfg, deadline)+ await sleep_ms(min(rand_range(cfg.scroll_settle_delay), deadline.remaining()))+ for _ in range(rand_int_range((1, 2))):+ if deadline.expired():+ break+ await self._wheel_burst(0, round(rand(40, 80)) * -sign, cfg, deadline)+ await sleep_ms(min(rand(100, 250), deadline.remaining()))++ async def _wheel_burst(self, dx: float, dy: float, cfg: HumanConfig,+ deadline: Optional[_Deadline] = None) -> None:+ """One logical scroll: accelerate -> cruise -> decelerate in wheel ticks."""+ total = abs(dy) if dy else abs(dx)+ sign = 1 if (dy or dx) > 0 else -1+ accel, decel = rand_int_range(cfg.scroll_accel_steps), rand_int_range(cfg.scroll_decel_steps)+ avg = (cfg.scroll_delta_base[0] + cfg.scroll_delta_base[1]) / 2+ ticks = max(1, math.ceil(total / avg))+ sent = 0.0+ for i in range(ticks):+ if sent >= total or (deadline is not None and deadline.expired()):+ break+ if i < accel or i >= ticks - decel:+ pause = rand_range(cfg.scroll_pause_slow)+ else:+ pause = rand_range(cfg.scroll_pause_fast)+ tick = min(total - sent, rand_range(cfg.scroll_delta_base) *+ (1 + (random.random() - 0.5) * 2 * cfg.scroll_delta_variance))+ # Split each tick into small wheel events like real inertia.+ left = tick+ while left > 0.5:+ chunk = min(left, rand(20, 40))+ step = round(chunk) * sign+ if step:+ await self.mouse.wheel(step if dx else 0, step if dy else 0)+ left -= chunk+ await sleep_ms(rand(8, 20))+ sent += tick+ await sleep_ms(pause)++ # -- pointer ------------------------------------------------------------++ async def _point(self, box: Dict[str, Any], position: Optional[dict], is_input: bool,+ cfg: HumanConfig) -> Tuple[float, float]:+ if position is not None:+ return box["x"] + box["bl"] + position["x"], box["y"] + box["bt"] + position["y"]+ vis = box["visible"]+ if vis["width"] <= 0 or vis["height"] <= 0:+ raise _Retry("element is outside of the viewport")+ # Aim inside the visible part, keep the input bias for text fields.+ full = click_target(box, is_input, cfg)+ x = min(max(full.x, vis["x"] + 1), vis["x"] + vis["width"] - 1)+ y = min(max(full.y, vis["y"] + 1), vis["y"] + vis["height"] - 1)+ return x, y++ @staticmethod+ def _aim_point(box: Dict[str, Any], aim: tuple) -> Tuple[float, float]:+ """Exact aim points: a date-editor segment, or a fraction along a slider."""+ if aim[0] == "segment":+ seg = aim[1]+ x, y = box["x"] + seg["dx"] + rand(-2, 2), box["y"] + seg["dy"] + rand(-2, 2)+ else:+ frac, vertical = aim[1], aim[2]+ # Native thumbs are inset by about half their width (~8px) at both ends.+ if vertical:+ inset = min(8.0, box["height"] / 4)+ y = box["y"] + box["height"] - inset - frac * (box["height"] - 2 * inset)+ x = box["x"] + box["width"] / 2+ else:+ inset = min(8.0, box["width"] / 4)+ x = box["x"] + inset + frac * (box["width"] - 2 * inset)+ y = box["y"] + box["height"] / 2 + rand(-1.5, 1.5)+ vis = box["visible"]+ if not (vis["x"] <= x <= vis["x"] + vis["width"] and vis["y"] <= y <= vis["y"] + vis["height"]):+ raise _Retry("element is outside of the viewport")+ return x, y++ async def _hit(self, r: Resolved, x: float, y: float) -> None:+ ox, oy, clip = await self.worlds.frame_geometry(r.frame)+ if not (clip["x"] <= x <= clip["x"] + clip["width"] and clip["y"] <= y <= clip["y"] + clip["height"]):+ raise _Retry("element is outside of the viewport")+ desc = await self.worlds.call(r.frame, "hit", r.id, x - ox, y - oy)+ if desc is None and r.frame.parent_frame is not None:+ desc = await self.worlds.owners_hit(r.frame, x, y)+ if desc:+ raise _Retry(f"{desc} intercepts pointer events")++ async def pointer_action(self, api: str, target: Target, opts: dict,+ states: Sequence[str], is_input_hint: Optional[bool] = None,+ action: Optional[Callable[[Resolved, float, float, HumanConfig], Awaitable[None]]] = None,+ hold: Optional[Sequence[str]] = None,+ ) -> Resolved:+ """Shared scroll -> move -> hit-check -> ``action`` sequence.++ ``hold``: modifier names (``Shift``, ``ControlOrMeta``...) held down while+ the cursor travels to the target, as Playwright's ``hover(modifiers=)``."""+ cfg = self.call_cfg(opts.get("human_config"))+ if opts.get("steps"):+ cfg = merge_config(cfg, {"mouse_min_steps": int(opts["steps"]), "mouse_max_steps": int(opts["steps"]),+ "mouse_overshoot_chance": 0.0})+ deadline = self.deadline(target, opts)+ force = bool(opts.get("force"))+ trial = bool(opts.get("trial"))+ position = opts.get("position")+ no_scroll = opts.get("scroll") == "none"+ await self.ensure_cursor(cfg)+ if not (opts.get("_nested") or opts.get("_deadline")):+ await self.idle(cfg)+ done: Dict[str, Any] = {}++ async def attempt() -> Resolved:+ r = await self._attempt_states(target, states, deadline, force)+ box = await self.element_box(r) if no_scroll else await self.scroll_into_view(r, cfg, deadline)+ if is_input_hint is None:+ info = await self.worlds.call(r.frame, "info", r.id)+ is_input = info["tag"] in ("input", "textarea") or info["editable"]+ else:+ is_input = is_input_hint+ aim = opts.get("_aim")+ if aim is not None:+ x, y = self._aim_point(box, aim)+ else:+ x, y = await self._point(box, position, is_input, cfg)+ if not force:+ await self._hit(r, x, y)+ if trial:+ return r+ keys = [await self._modifier(m) for m in (hold or [])]+ for k in keys:+ await self.keyboard.down(k)+ try:+ await self.move_to(x, y, cfg)+ finally:+ for k in reversed(keys):+ await self.keyboard.up(k)+ # The page may replace or remove the target while the cursor+ # travels; never press on whatever is under it now (even with+ # force). Locators re-resolve and run the whole move again.+ if not await self.worlds.call(r.frame, "connected", r.id):+ raise StaleElement()+ if not force:+ await self._hit(r, self.cursor.x, self.cursor.y)+ done["is_input"] = is_input+ if action is not None:+ await action(r, self.cursor.x, self.cursor.y, cfg)+ return r++ return await self.retry(api, target, deadline, attempt)++ async def press_mouse(self, cfg: HumanConfig, is_input: bool, button: str = "left",+ click_count: int = 1, delay: Optional[float] = None,+ modifiers: Optional[Sequence[str]] = None) -> None:+ mods = [await self._modifier(m) for m in (modifiers or [])]+ await sleep_ms(rand_range(cfg.click_aim_delay_input if is_input else cfg.click_aim_delay_button))+ for m in mods:+ await self.keyboard.down(m)+ try:+ for n in range(1, max(1, int(click_count)) + 1):+ hold = delay if delay is not None else rand_range(cfg.click_hold_input if is_input else cfg.click_hold_button)+ await self.mouse.down(button=button, clickCount=n)+ await sleep_ms(hold)+ await self.mouse.up(button=button, clickCount=n)+ if n < click_count:+ await sleep_ms(delay if delay is not None else rand(60, 140))+ finally:+ for m in reversed(mods):+ await self.keyboard.up(m)++ # -- public actions -----------------------------------------------------++ async def click(self, target: Target, opts: dict, api: str = "click", click_count: Optional[int] = None) -> None:+ count = click_count if click_count is not None else int(opts.get("click_count") or 1)++ async def act(r: Resolved, x: float, y: float, cfg: HumanConfig) -> None:+ info = await self.worlds.call(r.frame, "info", r.id)+ is_input = info["tag"] in ("input", "textarea") or info["editable"]+ await self.press_mouse(cfg, is_input, opts.get("button") or "left", count,+ opts.get("delay"), opts.get("modifiers"))++ await self.pointer_action(api, target, opts, CLICK_STATES, action=act)++ async def hover(self, target: Target, opts: dict, api: str = "hover") -> None:+ # Playwright holds the modifiers while the mouse moves onto the target.+ await self.pointer_action(api, target, opts, HOVER_STATES, is_input_hint=False,+ hold=opts.get("modifiers"))++ async def tap(self, target: Target, opts: dict) -> None:+ await self.click(target, {k: v for k, v in opts.items() if k != "click_count"}, api="tap")++ async def focus_element(self, target: Target, opts: dict, api: str, cfg: HumanConfig,+ deadline: _Deadline, require_focus: bool = True) -> Tuple[Resolved, bool]:+ """Focus by a human click unless already focused.++ Returns ``(r, clicked_in)``: ``clicked_in`` is true when this call+ clicked and focus landed in the target (the caret then sits wherever the+ click put it). With ``require_focus=False`` (press / type) a click that+ does not move focus is fine, as in Playwright: the keys then go to+ whatever handles them (a <canvas>, document-level key handlers)."""+ r = await self.wait_for(target, FOCUS_STATES, deadline, api, bool(opts.get("force")))+ info = await self.worlds.call(r.frame, "info", r.id)+ if info["focused"]:+ return r, False+ # A person focuses a field by clicking it: scroll it into view with the+ # wheel and click. When it cannot be brought on screen at all (e.g.+ # positioned at negative offsets) the click times out with "element is+ # outside of the viewport" -- no silent programmatic focus.+ await self.click(target, {"_deadline": deadline, "force": opts.get("force"),+ "human_config": opts.get("human_config")}, api=api)+ info = await self.worlds.call(r.frame, "info", r.id)+ if info["focused"] or await self._focus_by_tab(r, info):+ return r, True+ if require_focus:+ raise Error(f"{api}: Error: element did not receive focus when clicked "+ f"(it may not be focusable): {info['preview']}")+ return r, False++ async def _focus_by_tab(self, r: Resolved, info: dict) -> bool:+ """The click landed but focus went elsewhere (a focusable child or a+ label-less wrapper). Accept focus that moved into the target."""+ act = await self.worlds.call(r.frame, "activeValue")+ return bool(act.get("tag")) and await self.worlds.evaluate(+ r.frame, f"(() => {{ const e = {HELPERS}.el({r.id}); const a = document.activeElement;"+ f" return !!a && (e === a || e.contains(a)); }})()")++ async def caret_to_end(self, r: Resolved) -> None:+ info = await self.worlds.call(r.frame, "info", r.id)+ if info["tag"] == "input":+ if not await self.worlds.call(r.frame, "caretAtEnd", r.id):+ await self.keyboard.press("End")+ else:+ await self.keyboard.press("Control+End")+ await sleep_ms(rand(20, 60))++ async def press(self, target: Target, key: str, opts: dict, api: str = "press") -> None:+ cfg = self.call_cfg(opts.get("human_config"))+ deadline = self.deadline(target, opts)+ await self.focus_element(target, opts, api, cfg, deadline, require_focus=False)+ await sleep_ms(rand(50, 150))+ await self.keyboard.press(await self._keys(key), delay=opts.get("delay"))++ async def _keys(self, key: str) -> str:+ if "ControlOrMeta" in key:+ return key.replace("ControlOrMeta", await self._modifier("ControlOrMeta"))+ return key++ async def type(self, target: Target, text: str, opts: dict, api: str = "type") -> None:+ cfg = self.call_cfg(opts.get("human_config"))+ deadline = self.deadline(target, opts)+ await sleep_ms(rand_range(cfg.field_switch_delay))+ r, clicked_in = await self.focus_element(target, opts, api, cfg, deadline, require_focus=False)+ if clicked_in:+ await self.caret_to_end(r)+ await sleep_ms(rand(100, 250))+ info = await self.worlds.call(r.frame, "info", r.id)+ await self.type_text(text, cfg, r.frame, info, opts.get("delay"))++ async def fill(self, target: Target, value: str, opts: dict, api: str = "fill") -> None:+ cfg = self.call_cfg(opts.get("human_config"))+ deadline = self.deadline(target, opts)+ force = bool(opts.get("force"))+ r = await self.wait_for(target, INPUT_STATES, deadline, api, force)+ info = await self.worlds.call(r.frame, "info", r.id)+ kind = fields.classify(info["tag"], info["type"], info["editable"])+ if kind == fields.NOT_FILLABLE:+ raise Error(f"{api}: Error: {fields.not_fillable_message(info['tag'], info['type'])}")+ if info["type"] == "number":+ try:+ value = fields.validate_number(value)+ except fields.FieldKindError as exc:+ raise Error(f"{api}: Error: {exc}") from None+ if kind == fields.SET:+ value = fields.normalize_set_value(info["type"], value)+ await sleep_ms(rand_range(cfg.field_switch_delay))+ if info["type"] == "range":+ await self.set_range(target, r, value, opts, api, cfg, deadline)+ elif info["type"] == "color":+ await self.set_color(target, r, value, opts, api, cfg, deadline)+ else:+ await self.set_datetime(target, r, info["type"], value, opts, api, cfg, deadline)+ return+ await sleep_ms(rand_range(cfg.field_switch_delay))+ r, _ = await self.focus_element(target, opts, api, cfg, deadline)+ await sleep_ms(rand(100, 250))+ info = await self.worlds.call(r.frame, "info", r.id)+ if info["value"]:+ await self.keyboard.press(await self.select_all_key())+ await sleep_ms(rand(30, 80))+ await self.keyboard.press("Backspace")+ await sleep_ms(rand(50, 150))+ info = await self.worlds.call(r.frame, "info", r.id)+ if info["value"]:+ # Some widgets ignore select-all; clear what is left by keys.+ await self.caret_to_end(r)+ for _ in range(len(info["value"])):+ await self.keyboard.press("Backspace")+ await sleep_ms(rand(15, 40))+ if value:+ await self.type_text(value, cfg, r.frame, info, None)++ async def clear(self, target: Target, opts: dict) -> None:+ await self.fill(target, "", opts, api="clear")++ async def set_checked(self, target: Target, checked: bool, opts: dict, api: str) -> None:+ cfg = self.call_cfg(opts.get("human_config"))+ deadline = self.deadline(target, opts)+ r = await self.wait_for(target, CLICK_STATES, deadline, api, bool(opts.get("force")))+ state = await self.worlds.call(r.frame, "checked", r.id)+ if "error" in state:+ raise Error(f"{api}: Error: {state['error']}")+ if state["checked"] == checked:+ return+ if state["radio"] and not checked:+ raise Error(f"{api}: Error: Cannot uncheck radio button. Radio buttons can only be unchecked "+ "by selecting another radio button in the same group.")+ sub = {k: opts.get(k) for k in ("force", "position", "trial", "human_config")}+ sub["_deadline"] = deadline+ await self.click(target, sub, api=api)+ if opts.get("trial"):+ return+ state = await self.worlds.call(r.frame, "checked", r.id)+ if state.get("checked") != checked:+ raise Error(f"{api}: Error: Clicking the checkbox did not change its state")++ # -- value inputs: what a person does --------------------------------++ async def set_datetime(self, target: Target, r: Resolved, input_type: str, value: str, opts: dict,+ api: str, cfg: HumanConfig, deadline: _Deadline) -> None:+ """date / time / datetime-local / month / week: click the first segment+ of the native editor and type each part with the keyboard, the way a+ person fills these fields. Segment order comes from the editor itself,+ so any locale works."""+ parts = fields.datetime_parts(input_type, value)+ if parts is None:+ raise Error(f"{api}: Error: Malformed value")+ segs = await self.worlds.editor_fields(r.frame, r.id)+ kinds = [f["kind"] for f in segs]+ parts = fields.use_24h(parts, "ampm" in kinds)+ if not segs or any(k not in parts and k != "ampm" for k in kinds):+ raise Error(f"{api}: Error: unsupported date/time editor layout {kinds}")+ await self.pointer_action(api, target, {**opts, "_deadline": deadline, "position": None,+ "_aim": ("segment", segs[0])},+ INPUT_STATES, is_input_hint=True,+ action=lambda rr, x, y, c: self.press_mouse(c, True))+ await sleep_ms(rand(80, 200))+ current = fields.datetime_parts(input_type, await self.worlds.call(r.frame, "value", r.id) or "")+ for i, seg in enumerate(segs):+ kind = seg["kind"]+ if input_type == "month" and kind == "month" and current:+ # Shown as a month name; over an existing month Chromium's digit+ # matching is unreliable, so step with the arrow keys like a+ # person scrolling through the names.+ diff = int(parts["month"]) - int(current["month"])+ for _ in range(abs(diff)):+ await self.keyboard.press("ArrowUp" if diff > 0 else "ArrowDown")+ await sleep_ms(rand(60, 140))+ elif kind == "ampm":+ await self._type_char("P" if parts["hour24"] >= 12 else "A", cfg)+ else:+ digits = parts[kind]+ for j, ch in enumerate(digits):+ await self._type_char(ch, cfg)+ if j < len(digits) - 1:+ # The editor forgets a partial entry after ~1 s without+ # a key; people type a number in one go, so keep the+ # gap inside a segment short (pauses go between parts).+ await sleep_ms(min(450.0, max(40.0, cfg.typing_delay ++ (random.random() - 0.5) * 2 * cfg.typing_delay_spread)))+ if i < len(segs) - 1 and not fields.segment_auto_advances(kind, parts, input_type):+ await self.keyboard.press("ArrowRight")+ await sleep_ms(rand(60, 160))+ got = await self.worlds.call(r.frame, "value", r.id)+ if got != value:+ raise Error(f"{api}: Error: the date/time editor produced {got!r} instead of {value!r}")++ async def set_range(self, target: Target, r: Resolved, value: str, opts: dict, api: str,+ cfg: HumanConfig, deadline: _Deadline) -> None:+ """Slider: click on the track near the wanted value, then nudge with+ arrow keys until it is exact."""+ info = await self.worlds.call(r.frame, "rangeInfo", r.id)+ try:+ want = float(value)+ except ValueError:+ raise Error(f"{api}: Error: Malformed value") from None+ span = info["max"] - info["min"]+ frac = 0.5 if span <= 0 else min(1.0, max(0.0, (want - info["min"]) / span))+ if info["rtl"] and not info["vertical"]:+ frac = 1 - frac+ await self.pointer_action(api, target, {**opts, "_deadline": deadline, "position": None,+ "_aim": ("fraction", frac, info["vertical"])},+ INPUT_STATES, is_input_hint=False,+ action=lambda rr, x, y, c: self.press_mouse(c, False))+ for _ in range(400):+ cur = float(await self.worlds.call(r.frame, "value", r.id))+ if abs(cur - want) < 1e-9 or (info["step"] and abs(cur - want) < info["step"] / 2):+ break+ up = cur < want+ key = ("ArrowRight" if up else "ArrowLeft") if not info["rtl"] else ("ArrowLeft" if up else "ArrowRight")+ await self.keyboard.press(key)+ await sleep_ms(rand(40, 110))+ if float(await self.worlds.call(r.frame, "value", r.id)) == cur:+ break # cannot move further (min/max reached)+ got = await self.worlds.call(r.frame, "value", r.id)+ if float(got) != float(await self._range_snap(r, want)):+ raise Error(f"{api}: Error: slider stopped at {got} instead of {value}")++ async def _range_snap(self, r: Resolved, want: float) -> float:+ info = await self.worlds.call(r.frame, "rangeInfo", r.id)+ v = min(info["max"], max(info["min"], want))+ if info["step"]:+ v = info["min"] + round((v - info["min"]) / info["step"]) * info["step"]+ v = min(info["max"], v)+ return v++ async def set_color(self, target: Target, r: Resolved, value: str, opts: dict, api: str,+ cfg: HumanConfig, deadline: _Deadline) -> None:+ """<input type=color> opens an OS colour dialog that page input cannot+ drive. Playwright sets the value; doing that silently would hide a+ robot-only path, so refuse instead."""+ raise Error(f"{api}: Error: <input type=color> opens a native colour picker that cannot be "+ "operated with human input; set it with page._original.fill(...) if a programmatic "+ "value is acceptable")++ async def select_option(self, target: Target, options: List[dict], element_handles: List[Any],+ opts: dict, api: str = "select_option") -> List[str]:+ """Pick options like a person: a dropdown is opened with a click and+ moved with arrow keys + Enter; a list box gets clicks on the options+ (Ctrl/Cmd-click to add more in a multi-select)."""+ cfg = self.call_cfg(opts.get("human_config"))+ deadline = self.deadline(target, opts)+ force = bool(opts.get("force"))++ async def plan() -> Tuple[Resolved, dict]:+ r = await self._attempt_states(target, ["visible", "enabled"], deadline, force)+ ids = [(await self._resolve_handle(h, deadline)).id for h in element_handles]+ res = await self.worlds.call(r.frame, "selectPlan", r.id, options, ids)+ if "error" in res:+ raise Error(res["error"])+ if "retry" in res:+ raise _Retry(res["retry"])+ return r, res++ r, p = await self.retry(api, target, deadline, plan)+ if not p["listbox"]:+ await self._select_dropdown(target, r, p["targets"][0] if p["targets"] else None, p, opts, api,+ cfg, deadline)+ else:+ await self._select_listbox(target, r, p, opts, api, cfg, deadline)+ state = await self.worlds.call(r.frame, "selectState", r.id)+ if sorted(state["selected"]) != sorted(p["targets"]):+ raise Error(f"{api}: Error: selection ended as {state['values']} instead of {p['values']}")+ return state["values"]++ async def _select_dropdown(self, target: Target, r: Resolved, index: Optional[int], p: dict, opts: dict,+ api: str, cfg: HumanConfig, deadline: _Deadline) -> None:+ if index is None:+ raise Error(f"{api}: Error: a dropdown always keeps one option selected")+ state = await self.worlds.call(r.frame, "selectState", r.id)+ if state["current"] == index:+ await self.hover(target, {"_deadline": deadline, "human_config": opts.get("human_config")}, api=api)+ return+ await self.click(target, {"_deadline": deadline, "force": opts.get("force"),+ "human_config": opts.get("human_config")}, api=api)+ await sleep_ms(rand(200, 450)) # popup opens; eyes find the option+ if sys.platform == "darwin":+ # macOS shows a native popup that ignores arrow keys sent as page+ # input; type-ahead on the option's label still selects it.+ for ch in p["labels"][0]:+ if ch.isascii():+ await self._type_char(ch, cfg)+ else: # no US-layout key: send the character itself, like a native layout does+ session = await self.worlds.session()+ await session.send("Input.dispatchKeyEvent",+ {"type": "keyDown", "key": ch, "text": ch, "unmodifiedText": ch})+ await sleep_ms(rand_range(cfg.key_hold))+ await session.send("Input.dispatchKeyEvent", {"type": "keyUp", "key": ch})+ await sleep_ms(rand(60, 140)) # type-ahead resets after ~1s of silence+ await self.keyboard.press("Enter")+ await sleep_ms(rand(80, 160))+ return+ nav = p["navigable"]+ cur = state["current"]+ for _ in range(len(nav) + 1):+ if cur == index:+ break+ step = 1 if index > cur else -1+ nxt = cur + step+ while 0 <= nxt < len(nav) and not nav[nxt]:+ nxt += step+ if not (0 <= nxt < len(nav)):+ break+ await self.keyboard.press("ArrowDown" if step > 0 else "ArrowUp")+ await sleep_ms(rand(70, 180))+ cur = nxt+ await sleep_ms(rand(100, 250))+ await self.keyboard.press("Enter")+ await sleep_ms(rand(80, 160))++ async def _select_listbox(self, target: Target, r: Resolved, p: dict, opts: dict, api: str,+ cfg: HumanConfig, deadline: _Deadline) -> None:+ state = await self.worlds.call(r.frame, "selectState", r.id)+ want = list(p["targets"])+ if sorted(state["selected"]) == sorted(want):+ await self.hover(target, {"_deadline": deadline, "human_config": opts.get("human_config")}, api=api)+ return+ add_key = "Meta" if await self.is_mac() else "Control"+ first = True+ if not want:+ raise Error(f"{api}: Error: deselecting every option is not something a click can do")+ for idx in want:+ oid = await self.worlds.call(r.frame, "optionId", r.id, idx)+ opt = Target(r.frame, None)+ opt.description = f"option #{idx}"+ res = Resolved(r.frame, oid)+ # Plain click on the first option replaces the selection; further+ # options are added with Ctrl/Cmd held, as a person does.+ mods = [] if first else [add_key]+ await self._click_resolved(res, opt, cfg, deadline, api, mods)+ first = False+ await sleep_ms(rand(120, 300))++ async def _click_resolved(self, r: Resolved, label: Target, cfg: HumanConfig, deadline: _Deadline,+ api: str, modifiers: Sequence[str]) -> None:+ """Scroll / move / hit-check / click an already resolved element."""+ async def attempt() -> None:+ box = await self.scroll_into_view(r, cfg, deadline)+ x, y = await self._point(box, None, False, cfg)+ await self._hit(r, x, y)+ await self.move_to(x, y, cfg)+ await self._hit(r, self.cursor.x, self.cursor.y)+ await self.press_mouse(cfg, False, "left", 1, None, modifiers)++ await self.retry(api, label, deadline, attempt)++ async def drag(self, source: Target, dest: Target, opts: dict, api: str = "drag_and_drop") -> None:+ sub = {"_deadline": self.deadline(source, opts), "force": opts.get("force"), "human_config": opts.get("human_config"),+ "position": opts.get("source_position"), "trial": opts.get("trial")}+ await self.idle(self.call_cfg(opts.get("human_config")))+ await self.hover(source, sub, api=api)+ if opts.get("trial"):+ await self.hover(dest, {**sub, "position": opts.get("target_position"), "_nested": True}, api=api)+ return+ await sleep_ms(rand(100, 200))+ await self.mouse.down()+ try:+ await sleep_ms(rand(80, 150))+ await self.hover(dest, {**sub, "position": opts.get("target_position"), "force": True, "_nested": True},+ api=api)+ await sleep_ms(rand(80, 150))+ finally:+ await self.mouse.up()++ async def focus(self, target: Target, opts: dict, api: str = "focus", move: bool = False) -> None:+ deadline = self.deadline(target, opts)+ if move:+ await self.hover(target, {"timeout": opts.get("timeout"), "human_config": opts.get("human_config")}, api=api)+ r = await self.retry(api, target, deadline, lambda: self.resolve(target, deadline))+ await self.worlds.call(r.frame, "focus", r.id)++ async def scroll_into_view_if_needed(self, target: Target, opts: dict) -> None:+ cfg = self.call_cfg(opts.get("human_config"))+ deadline = self.deadline(target, opts)+ await self.ensure_cursor(cfg)++ async def attempt() -> None:+ r = await self._attempt_states(target, ["visible", "stable"], deadline, False)+ await self.scroll_into_view(r, cfg, deadline)++ await self.retry("scroll_into_view_if_needed", target, deadline, attempt)++ # -- keyboard -----------------------------------------------------------++ async def type_text(self, text: str, cfg: HumanConfig, frame: Any, info: Optional[dict],+ delay: Optional[float]) -> None:+ """Type ``text`` key by key into the focused element of ``frame``."""+ tag = info.get("tag") if info else None+ mistypes = cfg.mistype_chance > 0 and tag is not None and fields.allows_mistype(tag, info.get("type"))+ for i, ch in enumerate(text):+ if not ch.isascii():+ await sleep_ms(rand_range(cfg.key_hold))+ await self.keyboard.insert_text(ch)+ else:+ if mistypes and ch.isalnum() and random.random() < cfg.mistype_chance:+ await self._typo(ch, cfg, frame)+ await self._type_char(ch, cfg)+ if i < len(text) - 1:+ await self._between_keys(cfg, delay)++ async def _typo(self, ch: str, cfg: HumanConfig, frame: Any) -> None:+ lower = ch.lower()+ if lower not in NEARBY_KEYS:+ return+ wrong = random.choice(NEARBY_KEYS[lower])+ if ch.isupper():+ wrong = wrong.upper()+ before = await self._active_value(frame)+ await self._type_char(wrong, cfg)+ await sleep_ms(rand_range(cfg.mistype_delay_notice))+ after = await self._active_value(frame)+ if before is not None and after == before:+ # The page rejected the wrong key (mask / filter): nothing to undo.+ await sleep_ms(rand_range(cfg.mistype_delay_correct))+ return+ await self.keyboard.down("Backspace")+ await sleep_ms(rand_range(cfg.key_hold))+ await self.keyboard.up("Backspace")+ await sleep_ms(rand_range(cfg.mistype_delay_correct))++ async def _active_value(self, frame: Any) -> Optional[str]:+ try:+ return (await self.worlds.call(frame, "activeValue")).get("value")+ except Error:+ return None++ async def _type_char(self, ch: str, cfg: HumanConfig) -> None:+ if ch.isalpha() and ch.isupper():+ await self.keyboard.down("Shift")+ await sleep_ms(rand_range(cfg.shift_down_delay))+ await self.keyboard.down(ch)+ await sleep_ms(rand_range(cfg.key_hold))+ await self.keyboard.up(ch)+ await sleep_ms(rand_range(cfg.shift_up_delay))+ await self.keyboard.up("Shift")+ elif ch in SHIFT_SYMBOLS:+ session = await self.worlds.session()+ code = _SHIFT_SYMBOL_CODES.get(ch, "")+ vk = _SHIFT_SYMBOL_KEYCODES.get(ch, 0)+ await self.keyboard.down("Shift")+ await sleep_ms(rand_range(cfg.shift_down_delay))+ await session.send("Input.dispatchKeyEvent", {+ "type": "keyDown", "modifiers": 8, "key": ch, "code": code,+ "windowsVirtualKeyCode": vk, "text": ch, "unmodifiedText": ch,+ })+ await sleep_ms(rand_range(cfg.key_hold))+ await session.send("Input.dispatchKeyEvent", {+ "type": "keyUp", "modifiers": 8, "key": ch, "code": code, "windowsVirtualKeyCode": vk,+ })+ await sleep_ms(rand_range(cfg.shift_up_delay))+ await self.keyboard.up("Shift")+ else:+ await self.keyboard.down(ch)+ await sleep_ms(rand_range(cfg.key_hold))+ await self.keyboard.up(ch)++ async def _between_keys(self, cfg: HumanConfig, delay: Optional[float]) -> None:+ if delay is not None:+ await sleep_ms(delay)+ elif random.random() < cfg.typing_pause_chance:+ await sleep_ms(rand_range(cfg.typing_pause_range))+ else:+ await sleep_ms(max(10, cfg.typing_delay + (random.random() - 0.5) * 2 * cfg.typing_delay_spread))++ async def keyboard_type(self, text: str, delay: Optional[float] = None) -> None:+ """``page.keyboard.type``: no target; mistypes only where safe."""+ frame = self.page.main_frame+ try:+ info = await self.worlds.call(frame, "activeValue")+ except Error:+ info = None+ if info and info.get("tag") == "iframe":+ info = None # focus is inside a child frame: value checks impossible+ await self.type_text(text, self.cfg, frame, info if info and info.get("tag") else None, delay)++ # -- raw mouse API ------------------------------------------------------++ async def mouse_move(self, x: float, y: float, steps: Optional[int] = None) -> None:+ if steps is not None:+ await self.ensure_cursor()+ await self.mouse.move(x, y, steps=steps)+ self.cursor.x, self.cursor.y = x, y+ return+ await self.move_to(x, y, self.cfg)+ self.cursor.x, self.cursor.y = x, y++ async def mouse_click(self, x: float, y: float, delay: Optional[float] = None,+ button: Optional[str] = None, click_count: Optional[int] = None) -> None:+ await self.move_to(x, y, self.cfg)+ self.cursor.x, self.cursor.y = x, y+ await self.press_mouse(self.cfg, False, button or "left", click_count or 1, delay)diff --git a/cloakbrowser/human/errors.py b/cloakbrowser/human/errors.pynew file mode 100644index 0000000..a107121--- /dev/null+++ b/cloakbrowser/human/errors.py@@ -0,0 +1,87 @@+"""Error classes kept for API compatibility.++The unified engine raises Playwright ``Error`` / ``TimeoutError`` (with a call+log) instead; these classes stay importable from ``cloakbrowser.human`` so+existing ``except`` clauses and imports keep working. Same set as the JS+(``js/src/human/errors.ts``) and .NET (``Human/Actionability.cs``) ports.+"""++from __future__ import annotations+++class ActionabilityError(RuntimeError):+ """Base for all actionability failures."""++ def __init__(self, selector: str, check: str, message: str):+ self.selector = selector+ self.check = check+ super().__init__(f"Element {selector!r} failed {check} check: {message}")+++class ElementNotAttachedError(ActionabilityError):+ def __init__(self, selector: str):+ super().__init__(selector, "attached", "element not found in DOM")+++class ElementNotVisibleError(ActionabilityError):+ def __init__(self, selector: str):+ super().__init__(selector, "visible", "element is not visible")+++class ElementNotStableError(ActionabilityError):+ def __init__(self, selector: str):+ super().__init__(selector, "stable", "element position is still changing")+++class ElementNotEnabledError(ActionabilityError):+ def __init__(self, selector: str):+ super().__init__(selector, "enabled", "element is disabled")+++class ElementNotEditableError(ActionabilityError):+ def __init__(self, selector: str):+ super().__init__(selector, "editable", "element is not editable")+++class ElementNotReceivingEventsError(ActionabilityError):+ def __init__(self, selector: str, covering_tag: str = "unknown"):+ self.covering_tag = covering_tag+ super().__init__(selector, "pointer_events", f"element is covered by <{covering_tag}>")+++class ElementTargetChangedError(ActionabilityError):+ def __init__(self, selector: str):+ super().__init__(+ selector, "target_identity",+ "selector resolved to a different element before input dispatch",+ )+++# Raised by the previous humanize layer; the engine no longer raises them.++class StealthDomError(RuntimeError):+ """Base for isolated-world DOM helper failures."""+++class UnsupportedHumanizeSelectorError(StealthDomError):+ def __init__(self, selector: str):+ super().__init__(f"Humanized selector {selector!r} is not supported")+++class StealthWorldUnavailableError(StealthDomError):+ def __init__(self):+ super().__init__("Humanized DOM read requires an active isolated world")+++class StealthEvaluationError(StealthDomError):+ def __init__(self, selector: str):+ super().__init__(f"Isolated-world DOM evaluation failed for {selector!r}")+++__all__ = [+ "ActionabilityError", "ElementNotAttachedError", "ElementNotVisibleError",+ "ElementNotStableError", "ElementNotEnabledError", "ElementNotEditableError",+ "ElementNotReceivingEventsError", "ElementTargetChangedError",+ "StealthDomError", "UnsupportedHumanizeSelectorError",+ "StealthWorldUnavailableError", "StealthEvaluationError",+]diff --git a/cloakbrowser/human/fields.py b/cloakbrowser/human/fields.pynew file mode 100644index 0000000..dedce4c--- /dev/null+++ b/cloakbrowser/human/fields.py@@ -0,0 +1,145 @@+"""Field classification for humanized text input.++Mirrors Playwright's ``InjectedScript.fill`` rules (playwright-core 1.63) so+the humanize layer accepts and rejects the same targets Playwright does:++* text-like inputs are *typed into* key by key;+* value inputs (date, range, color, ...) get their value *set*, like+ Playwright, because a human does not type into a date picker either;+* everything else (checkbox, file, hidden, radio, ...) cannot be filled.++Mistypes are only simulated where a human plausibly makes and corrects them+and where the correction is safe: never in number/email/password/tel/url.+"""++from __future__ import annotations++from typing import Optional++# Playwright: kInputTypesToTypeInto+TYPE_INTO = frozenset({"", "email", "number", "password", "search", "tel", "text", "url"})+# Playwright: kInputTypesToSetValue+SET_VALUE = frozenset({"color", "date", "time", "datetime-local", "month", "range", "week"})+# Fields where a simulated typo is either unsafe (rejected chars, #573) or+# unrealistic (people type passwords, phones and addresses carefully).+NO_MISTYPE = frozenset({"number", "email", "password", "tel", "url"})++TYPE = "type" # type key by key+SET = "set" # set value directly+NOT_FILLABLE = "reject" # raise like Playwright+++class FieldKindError(RuntimeError):+ """Raised for targets Playwright refuses to fill."""+++def classify(tag: str, input_type: Optional[str], editable_content: bool) -> str:+ """Return ``TYPE``, ``SET`` or ``NOT_FILLABLE`` for a fill target.++ ``tag`` is the lower-case tag name, ``input_type`` the lower-case+ ``input.type`` (``None`` for non-inputs), ``editable_content`` whether the+ element is contenteditable.+ """+ tag = (tag or "").lower()+ if tag == "input":+ t = (input_type or "").lower()+ if t in TYPE_INTO:+ return TYPE+ if t in SET_VALUE:+ return SET+ return NOT_FILLABLE+ if tag == "textarea" or editable_content:+ return TYPE+ return NOT_FILLABLE+++def allows_mistype(tag: str, input_type: Optional[str]) -> bool:+ """Whether simulated typos are allowed for this field."""+ if (tag or "").lower() != "input":+ return True+ return (input_type or "").lower() not in NO_MISTYPE+++def normalize_set_value(input_type: str, value: str) -> str:+ """Playwright's value normalization for ``SET_VALUE`` inputs."""+ value = value.strip()+ if (input_type or "").lower() == "color":+ value = value.lower()+ return value+++def validate_number(value: str) -> str:+ """Playwright rejects non-numeric text for ``input[type=number]``."""+ v = value.strip()+ try:+ float(v)+ except ValueError:+ if v not in ("",):+ raise FieldKindError("Cannot type text into input[type=number]") from None+ return v+++def not_fillable_message(tag: str, input_type: Optional[str]) -> str:+ if (tag or "").lower() == "input":+ return f'Input of type "{(input_type or "").lower()}" cannot be filled'+ return "Element is not an <input>, <textarea> or [contenteditable] element"+++# ---------------------------------------------------------------------------+# Native date/time editors+# ---------------------------------------------------------------------------++import re as _re++_DT_PATTERNS = {+ "date": r"(?P<year>\d{4,6})-(?P<month>\d{2})-(?P<day>\d{2})",+ "month": r"(?P<year>\d{4,6})-(?P<month>\d{2})",+ "week": r"(?P<year>\d{4,6})-W(?P<week>\d{2})",+ "time": r"(?P<hour>\d{2}):(?P<minute>\d{2})(?::(?P<second>\d{2})(?:\.(?P<millisecond>\d{1,3}))?)?",+}+_DT_PATTERNS["datetime-local"] = _DT_PATTERNS["date"] + "T" + _DT_PATTERNS["time"]++# Digits after which Chromium's editor moves to the next segment by itself.+_FULL_WIDTH = {"month": 2, "day": 2, "week": 2, "hour": 2, "minute": 2, "second": 2, "millisecond": 3}+++def datetime_parts(input_type: str, value: str) -> "dict | None":+ """Split an HTML date/time value into the keystrokes per editor segment.++ Returns ``None`` for a malformed value. ``hour`` is given in the 12-hour+ form the editor shows next to an AM/PM segment; ``hour24`` keeps the+ original hour. Callers that see no ``ampm`` segment use ``hour24``.+ """+ m = _re.fullmatch(_DT_PATTERNS.get(input_type, "$^"), value)+ if not m:+ return None+ g = {k: v for k, v in m.groupdict().items() if v is not None}+ parts: dict = dict(g)+ if "hour" in g:+ h = int(g["hour"])+ parts["hour24"] = h+ parts["hour12"] = f"{(h % 12) or 12:02d}"+ parts["hour"] = parts["hour12"]+ if "millisecond" in g:+ parts["millisecond"] = g["millisecond"].ljust(3, "0")+ return parts+++def use_24h(parts: dict, has_ampm: bool) -> dict:+ """Pick the hour digits matching the editor (with or without AM/PM)."""+ if "hour24" in parts and not has_ampm:+ parts = dict(parts)+ parts["hour"] = f"{parts['hour24']:02d}"+ return parts+++def segment_auto_advances(kind: str, parts: dict, input_type: str = "") -> bool:+ """Whether typing this segment's digits moves focus to the next segment.++ Two-digit segments advance after two digits. The year segment never+ does (it accepts up to six digits), so an ArrowRight follows it.+ """+ if input_type == "month" and kind == "month":+ return False # shown as a month *name* ("January"): digits select it but do not advance+ width = _FULL_WIDTH.get(kind)+ return width is not None and len(parts.get(kind, "")) >= widthdiff --git a/cloakbrowser/human/injected.py b/cloakbrowser/human/injected.pynew file mode 100644index 0000000..3a8624e--- /dev/null+++ b/cloakbrowser/human/injected.py@@ -0,0 +1,112 @@+"""Loads Playwright's selector / actionability engine for the humanize layer.++Playwright ships its InjectedScript (selector engines for role, label, text,+test-id, ``>>`` chains, ``has`` / ``has-text`` filters, ``nth``, ``visible``,+plus ``checkElementStates`` / ``expectHitTarget`` / ``fill`` rules) as a string+literal inside the driver bundle. The humanize layer evaluates that same+source in its own execution context, so it gets exact Playwright selector+semantics (#522) and strict mode instead of re-implementing accessible-name+computation.++The literal is extracted per installed Playwright version, so selector syntax+always matches the client that produced the selector string.+"""++from __future__ import annotations++import json+import re+from pathlib import Path+from typing import Optional++_LITERAL_START = re.compile(r"""\bsource\d*\s*[=:]\s*(['"`])""")+_cache: dict[str, str] = {}++# Global name inside the isolated world. Isolated-world globals are invisible+# to page scripts, so the name only has to avoid our own collisions.+GLOBAL = "__cloakInjected"+++def _driver_lib_dirs() -> list[Path]:+ import playwright++ root = Path(playwright.__file__).parent / "driver" / "package" / "lib"+ return [root] if root.is_dir() else []+++def _read_literal(text: str, start: int) -> str:+ """Return the JS string literal starting at ``text[start]`` (quotes included)."""+ quote = text[start]+ i = start + 1+ while text[i] != quote:+ i += 2 if text[i] == "\\" else 1+ return text[start:i + 1]+++def find_injected_literal(lib_dirs: Optional[list[Path]] = None) -> str:+ """Locate the InjectedScript source literal in a Playwright driver.++ Supports the bundled layout (``coreBundle.js``, Playwright >= 1.55) and the+ older per-file layout (``generated/injectedScriptSource.js``).+ """+ dirs = lib_dirs if lib_dirs is not None else _driver_lib_dirs()+ key = "|".join(str(d) for d in dirs)+ if key in _cache:+ return _cache[key]+ for d in dirs:+ bundle = d / "coreBundle.js"+ if bundle.is_file():+ text = bundle.read_text("utf-8")+ pos = text.find("generated/injectedScriptSource.ts")+ if pos >= 0:+ m = _LITERAL_START.search(text, pos)+ if m:+ _cache[key] = _read_literal(text, m.start(1))+ return _cache[key]+ for f in sorted(d.rglob("injectedScriptSource.js")):+ text = f.read_text("utf-8")+ m = _LITERAL_START.search(text)+ if m:+ _cache[key] = _read_literal(text, m.start(1))+ return _cache[key]+ raise RuntimeError(+ "cloakbrowser humanize: Playwright's InjectedScript source was not found in "+ f"{[str(d) for d in dirs]}; the installed Playwright layout is not supported"+ )+++def build_install_js(source: str, sdk_language: str = "python",+ test_id_attribute: str = "data-testid") -> str:+ """Expression that installs the engine in the current (isolated) world.++ ``source`` is the *decoded* InjectedScript module text. Idempotent: a+ second evaluation in the same world is a no-op. Works with both the+ options-object constructor (>= 1.47) and the older positional one.+ """+ opts = json.dumps({+ "isUnderTest": False,+ "sdkLanguage": sdk_language,+ "testIdAttributeName": test_id_attribute,+ "stableRafCount": 1,+ "browserName": "chromium",+ "isUtilityWorld": True,+ "customEngines": [],+ })+ return (+ "(() => {\n"+ f"if (globalThis.{GLOBAL}) return true;\n"+ "const module = { exports: {} }; const exports = module.exports;\n"+ f"{source}\n"+ ";const exp = module.exports.InjectedScript;\n"+ "const C = (exp && exp.prototype && exp.prototype.querySelectorAll) ? exp : exp();\n"+ # Both hooks register listeners / dispatch events on the shared window.+ "C.prototype._setupGlobalListenersRemovalDetection = function () {};\n"+ "C.prototype._setupHitTargetInterceptors = function () {};\n"+ f"const o = {opts};\n"+ "const inj = C.length > 2\n"+ " ? new C(globalThis, o.isUnderTest, o.sdkLanguage, o.testIdAttributeName,"+ " o.stableRafCount, o.browserName, o.customEngines)\n"+ " : new C(globalThis, o);\n"+ f"Object.defineProperty(globalThis, {json.dumps(GLOBAL)}, {{ value: inj }});\n"+ "return true; })()"+ )diff --git a/cloakbrowser/human/keyboard_async.py b/cloakbrowser/human/keyboard_async.pydeleted file mode 100644index 0854925..0000000--- a/cloakbrowser/human/keyboard_async.py+++ /dev/null@@ -1,150 +0,0 @@-"""cloakbrowser-human — Async human-like keyboard input.--Mirrors keyboard.py but uses ``await`` for all Playwright calls and-``async_sleep_ms`` instead of ``sleep_ms``.--Stealth-aware: when a CDP session is provided, shift symbols are typed-via CDP Input.dispatchKeyEvent (isTrusted=true, no evaluate stack trace).-"""--from __future__ import annotations--import random-from typing import Any, Optional, Protocol--from .config import HumanConfig, rand, rand_range, async_sleep_ms-from .keyboard import SHIFT_SYMBOLS, NEARBY_KEYS, _get_nearby_key-from .keyboard import _SHIFT_SYMBOL_CODES, _SHIFT_SYMBOL_KEYCODES---class AsyncRawKeyboard(Protocol):- async def down(self, key: str) -> None: ...- async def up(self, key: str) -> None: ...- async def type(self, text: str) -> None: ...- async def insert_text(self, text: str) -> None: ...---async def async_human_type(- page: Any, raw: AsyncRawKeyboard, text: str, cfg: HumanConfig,- cdp_session: Any = None,-) -> None:- """Type text with human-like per-character timing (async).-- Args:- cdp_session: If provided, shift symbols use CDP Input.dispatchKeyEvent- producing isTrusted=true events with no evaluate stack trace.- If None, falls back to page.evaluate (detectable).- """- for i, ch in enumerate(text):- # Non-ASCII characters (Cyrillic, CJK, emoji) — use insertText- if not ch.isascii():- await async_sleep_ms(rand_range(cfg.key_hold))- await raw.insert_text(ch)- if i < len(text) - 1:- await _inter_char_delay(cfg)- continue-- # Mistype chance — only for ASCII alphanumeric- if random.random() < cfg.mistype_chance and ch.isalnum():- wrong = _get_nearby_key(ch)- await _type_normal_char(raw, wrong, cfg)- await async_sleep_ms(rand_range(cfg.mistype_delay_notice))- await raw.down("Backspace")- await async_sleep_ms(rand_range(cfg.key_hold))- await raw.up("Backspace")- await async_sleep_ms(rand_range(cfg.mistype_delay_correct))-- if ch.isupper() and ch.isalpha():- await _type_shifted_char(page, raw, ch, cfg)- elif ch in SHIFT_SYMBOLS:- await _type_shift_symbol(page, raw, ch, cfg, cdp_session)- else:- await _type_normal_char(raw, ch, cfg)-- if i < len(text) - 1:- await _inter_char_delay(cfg)---async def _type_normal_char(raw: AsyncRawKeyboard, ch: str, cfg: HumanConfig) -> None:- await raw.down(ch)- await async_sleep_ms(rand_range(cfg.key_hold))- await raw.up(ch)---async def _type_shifted_char(page: Any, raw: AsyncRawKeyboard, ch: str, cfg: HumanConfig) -> None:- await raw.down("Shift")- await async_sleep_ms(rand_range(cfg.shift_down_delay))- await raw.down(ch)- await async_sleep_ms(rand_range(cfg.key_hold))- await raw.up(ch)- await async_sleep_ms(rand_range(cfg.shift_up_delay))- await raw.up("Shift")---async def _type_shift_symbol(- page: Any, raw: AsyncRawKeyboard, ch: str, cfg: HumanConfig,- cdp_session: Any = None,-) -> None:- """Type a shift symbol character (async).-- Stealth path (cdp_session provided):- Uses CDP Input.dispatchKeyEvent → isTrusted=true, clean stack.-- Fallback path (no cdp_session):- Uses raw.insertText + page.evaluate to dispatch synthetic KeyboardEvent.- Detectable via isTrusted=false and evaluate stack frame.- """- if cdp_session is not None:- # --- Stealth path: CDP Input.dispatchKeyEvent ---- code = _SHIFT_SYMBOL_CODES.get(ch, '')- key_code = _SHIFT_SYMBOL_KEYCODES.get(ch, 0)-- await raw.down("Shift")- await async_sleep_ms(rand_range(cfg.shift_down_delay))-- await cdp_session.send("Input.dispatchKeyEvent", {- "type": "keyDown",- "modifiers": 8, # Shift modifier flag- "key": ch,- "code": code,- "windowsVirtualKeyCode": key_code,- "text": ch,- "unmodifiedText": ch,- })- await async_sleep_ms(rand_range(cfg.key_hold))-- await cdp_session.send("Input.dispatchKeyEvent", {- "type": "keyUp",- "modifiers": 8,- "key": ch,- "code": code,- "windowsVirtualKeyCode": key_code,- })-- await async_sleep_ms(rand_range(cfg.shift_up_delay))- await raw.up("Shift")- else:- # --- Fallback path: page.evaluate (detectable) ---- await raw.down("Shift")- await async_sleep_ms(rand_range(cfg.shift_down_delay))- await raw.insert_text(ch)- await page.evaluate(- """(key) => {- const el = document.activeElement;- if (el) {- el.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true }));- el.dispatchEvent(new KeyboardEvent('keyup', { key, bubbles: true }));- }- }""",- ch,- )- await async_sleep_ms(rand_range(cfg.shift_up_delay))- await raw.up("Shift")---async def _inter_char_delay(cfg: HumanConfig) -> None:- if random.random() < cfg.typing_pause_chance:- await async_sleep_ms(rand_range(cfg.typing_pause_range))- else:- delay = cfg.typing_delay + (random.random() - 0.5) * 2 * cfg.typing_delay_spread- await async_sleep_ms(max(10, delay))diff --git a/cloakbrowser/human/mouse_async.py b/cloakbrowser/human/mouse_async.pydeleted file mode 100644index 750d197..0000000--- a/cloakbrowser/human/mouse_async.py+++ /dev/null@@ -1,87 +0,0 @@-"""cloakbrowser-human — Async human-like mouse movement and clicking.--Mirrors mouse.py but uses ``await`` for all Playwright calls and-``async_sleep_ms`` instead of ``sleep_ms``.-"""--from __future__ import annotations--import math-import random-from typing import Any, Protocol--from .config import HumanConfig, rand, rand_range, rand_int_range, async_sleep_ms-from .mouse import Point, _ease_in_out, _bezier, _random_control_points, click_target # noqa: reuse pure math---class AsyncRawMouse(Protocol):- async def move(self, x: float, y: float) -> None: ...- async def down(self) -> None: ...- async def up(self) -> None: ...- async def wheel(self, delta_x: float, delta_y: float) -> None: ...---async def async_human_move(- raw: AsyncRawMouse,- start_x: float, start_y: float,- end_x: float, end_y: float,- cfg: HumanConfig,-) -> None:- dist = math.hypot(end_x - start_x, end_y - start_y)- if dist < 1:- return-- steps = max(cfg.mouse_min_steps, min(cfg.mouse_max_steps, round(dist / cfg.mouse_steps_divisor)))- start = Point(start_x, start_y)- end = Point(end_x, end_y)- cp1, cp2 = _random_control_points(start, end)-- burst_counter = 0- burst_size = rand_int_range(cfg.mouse_burst_size)-- for i in range(steps + 1):- progress = i / steps- eased_t = _ease_in_out(progress)- pt = _bezier(start, cp1, cp2, end, eased_t)-- wobble_amp = math.sin(math.pi * progress) * cfg.mouse_wobble_max- wx = pt.x + (random.random() - 0.5) * 2 * wobble_amp- wy = pt.y + (random.random() - 0.5) * 2 * wobble_amp-- await raw.move(round(wx), round(wy))-- burst_counter += 1- if burst_counter >= burst_size and i < steps:- await async_sleep_ms(rand_range(cfg.mouse_burst_pause))- burst_counter = 0-- if random.random() < cfg.mouse_overshoot_chance:- overshoot_dist = rand_range(cfg.mouse_overshoot_px)- angle = math.atan2(end_y - start_y, end_x - start_x)- await raw.move(round(end_x + math.cos(angle) * overshoot_dist),- round(end_y + math.sin(angle) * overshoot_dist))- await async_sleep_ms(rand(30, 70))- await raw.move(round(end_x + (random.random() - 0.5) * 4),- round(end_y + (random.random() - 0.5) * 4))---async def async_human_click(raw: AsyncRawMouse, is_input: bool, cfg: HumanConfig) -> None:- aim_delay = rand_range(cfg.click_aim_delay_input) if is_input else rand_range(cfg.click_aim_delay_button)- await async_sleep_ms(aim_delay)- hold_time = rand_range(cfg.click_hold_input) if is_input else rand_range(cfg.click_hold_button)- await raw.down()- await async_sleep_ms(hold_time)- await raw.up()---async def async_human_idle(raw: AsyncRawMouse, seconds: float, cx: float, cy: float, cfg: HumanConfig) -> None:- import time as _time- end_time = _time.monotonic() + seconds- x, y = cx, cy- while _time.monotonic() < end_time:- dx = (random.random() - 0.5) * 2 * cfg.idle_drift_px- dy = (random.random() - 0.5) * 2 * cfg.idle_drift_px- x += dx- y += dy- await raw.move(round(x), round(y))- await async_sleep_ms(rand_range(cfg.idle_pause_range))diff --git a/cloakbrowser/human/patch.py b/cloakbrowser/human/patch.pynew file mode 100644index 0000000..19cfc7f--- /dev/null+++ b/cloakbrowser/human/patch.py@@ -0,0 +1,452 @@+"""Wire the humanize engine into Playwright's sync and async APIs.++Patching is class-level and idempotent: Page, Frame, Locator, ElementHandle,+Mouse and Keyboard methods check whether their page was humanized+(``patch_page`` / ``patch_page_async``) and otherwise call the original+Playwright method. Every humanized method:++* accepts exactly the arguments the original accepts (validated against the+ original signature, so typos still raise ``TypeError``) plus+ ``human_config`` for per-call overrides;+* honours Playwright's semantics for the options it accepts (``button``,+ ``click_count``, ``modifiers``, ``position``, ``trial``, ``force``,+ ``timeout`` including page defaults and ``0`` = no limit, ``strict``);+* raises Playwright ``Error`` / ``TimeoutError`` instead of silently falling+ back to Playwright's stock implementation.+"""++from __future__ import annotations++import datetime+import functools+import inspect+from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple++from .config import HumanConfig, rand+from .engine import CursorState, Human, Target++_PATCHED = {"sync": False, "async": False}+# (class, method name) -> original function+_ORIG: Dict[Tuple[type, str], Callable[..., Any]] = {}++Handler = Callable[[Human, Any, Dict[str, Any]], Awaitable[Any]]+++# ---------------------------------------------------------------------------+# helpers+# ---------------------------------------------------------------------------++def _impl_page(kind: str, impl: Any) -> Any:+ if kind == "Page":+ return impl+ if kind == "Frame":+ return impl._page+ if kind in ("Locator", "ElementHandle"):+ return impl._frame._page+ if kind in ("Mouse", "Keyboard"):+ return impl._channel._object+ return None # pragma: no cover+++def _human_for(kind: str, wrapper: Any) -> Optional[Human]:+ # No try/except: on a supported Playwright the internals below always exist+ # (checked once in _check_playwright). Swallowing an AttributeError here would+ # silently run Playwright's stock action on a humanized page.+ page = _impl_page(kind, wrapper._impl_obj)+ return getattr(page, "_cloak_human", None) if page is not None else None+++# Oldest Playwright whose client internals the engine relies on+# (Frame._timeout, ElementHandle._frame; both added in 1.53).+MIN_PLAYWRIGHT = (1, 53)+++def _check_playwright() -> None:+ """Fail loudly on a Playwright the engine cannot drive, instead of letting a+ humanized page fall back to Playwright's stock actions."""+ from importlib.metadata import PackageNotFoundError, version++ try:+ installed = version("playwright")+ except PackageNotFoundError: # pragma: no cover - vendored / editable installs+ installed = "unknown"+ parts = tuple(int(x) for x in installed.split(".")[:2] if x.isdigit())+ from playwright._impl._element_handle import ElementHandle+ from playwright._impl._frame import Frame++ missing = [n for n, ok in (("Frame._timeout", hasattr(Frame, "_timeout")),+ ("ElementHandle._frame", "_frame" in ElementHandle.__init__.__code__.co_names))+ if not ok]+ if (len(parts) == 2 and parts < MIN_PLAYWRIGHT) or missing:+ raise RuntimeError(+ f"cloakbrowser humanize requires playwright>={'.'.join(map(str, MIN_PLAYWRIGHT))} "+ f"(installed: {installed}"+ + (f"; missing internals: {', '.join(missing)}" if missing else "")+ + "). Upgrade with: pip install -U playwright"+ )+++def _normalize(args: Dict[str, Any]) -> Dict[str, Any]:+ out: Dict[str, Any] = {}+ for k, v in args.items():+ if k == "kwargs":+ continue+ if isinstance(v, datetime.timedelta):+ v = v.total_seconds() * 1000.0+ out[k] = v+ return out+++def _impl(obj: Any) -> Any:+ return getattr(obj, "_impl_obj", obj)+++def _select_options(a: Dict[str, Any]) -> Tuple[List[dict], List[Any]]:+ options: List[dict] = []+ value, index, label, element = a.get("value"), a.get("index"), a.get("label"), a.get("element")+ if value is not None:+ options += [{"valueOrLabel": v} for v in ([value] if isinstance(value, str) else value)]+ if index is not None:+ options += [{"index": i} for i in ([index] if isinstance(index, int) else index)]+ if label is not None:+ options += [{"label": v} for v in ([label] if isinstance(label, str) else label)]+ elements: List[Any] = []+ if element is not None:+ elements = [_impl(e) for e in (element if isinstance(element, (list, tuple)) else [element])]+ return options, elements+++# ---------------------------------------------------------------------------+# targets+# ---------------------------------------------------------------------------++def _selector_target(kind: str, impl: Any, a: Dict[str, Any], key: str = "selector") -> Target:+ frame = impl.main_frame if kind == "Page" else impl+ return Target(frame, a.pop(key), strict=bool(a.get("strict")))+++def _locator_target(impl: Any) -> Target:+ return Target(impl._frame, impl._selector, strict=True)+++def _handle_target(impl: Any) -> Target:+ return Target(impl._frame, handle=impl)+++def _target(kind: str, impl: Any, a: Dict[str, Any]) -> Target:+ if kind in ("Page", "Frame"):+ return _selector_target(kind, impl, a)+ if kind == "Locator":+ return _locator_target(impl)+ return _handle_target(impl)+++# ---------------------------------------------------------------------------+# handlers: (human, impl, args) -> awaitable+# ---------------------------------------------------------------------------++def _handlers(kind: str) -> Dict[str, Handler]:+ api = kind++ async def click(h: Human, impl: Any, a: dict) -> None:+ await h.click(_target(kind, impl, a), a, api=f"{api}.click")++ async def dblclick(h: Human, impl: Any, a: dict) -> None:+ await h.click(_target(kind, impl, a), a, api=f"{api}.dblclick", click_count=2)++ async def hover(h: Human, impl: Any, a: dict) -> None:+ await h.hover(_target(kind, impl, a), a, api=f"{api}.hover")++ async def tap(h: Human, impl: Any, a: dict) -> None:+ await h.click(_target(kind, impl, a), {**a, "click_count": 1}, api=f"{api}.tap")++ async def fill(h: Human, impl: Any, a: dict) -> None:+ t = _target(kind, impl, a)+ await h.fill(t, a.pop("value"), a, api=f"{api}.fill")++ async def clear(h: Human, impl: Any, a: dict) -> None:+ await h.fill(_target(kind, impl, a), "", a, api=f"{api}.clear")++ async def type_(h: Human, impl: Any, a: dict) -> None:+ t = _target(kind, impl, a)+ await h.type(t, a.pop("text"), a, api=f"{api}.type")++ async def press_sequentially(h: Human, impl: Any, a: dict) -> None:+ t = _target(kind, impl, a)+ await h.type(t, a.pop("text"), a, api=f"{api}.press_sequentially")++ async def press(h: Human, impl: Any, a: dict) -> None:+ t = _target(kind, impl, a)+ await h.press(t, a.pop("key"), a, api=f"{api}.press")++ async def check(h: Human, impl: Any, a: dict) -> None:+ await h.set_checked(_target(kind, impl, a), True, a, api=f"{api}.check")++ async def uncheck(h: Human, impl: Any, a: dict) -> None:+ await h.set_checked(_target(kind, impl, a), False, a, api=f"{api}.uncheck")++ async def set_checked(h: Human, impl: Any, a: dict) -> None:+ t = _target(kind, impl, a)+ await h.set_checked(t, bool(a.pop("checked")), a, api=f"{api}.set_checked")++ async def select_option(h: Human, impl: Any, a: dict) -> List[str]:+ t = _target(kind, impl, a)+ options, elements = _select_options(a)+ return await h.select_option(t, options, elements, a, api=f"{api}.select_option")++ async def focus(h: Human, impl: Any, a: dict) -> None:+ await h.focus(_target(kind, impl, a), a, api=f"{api}.focus", move=kind == "ElementHandle")++ async def scroll_into_view_if_needed(h: Human, impl: Any, a: dict) -> None:+ await h.scroll_into_view_if_needed(_target(kind, impl, a), a)++ async def drag_and_drop(h: Human, impl: Any, a: dict) -> None:+ frame = impl.main_frame if kind == "Page" else impl+ strict = bool(a.get("strict"))+ src = Target(frame, a.pop("source"), strict=strict)+ dst = Target(frame, a.pop("target"), strict=strict)+ await h.drag(src, dst, a, api=f"{api}.drag_and_drop")++ async def drag_to(h: Human, impl: Any, a: dict) -> None:+ other = _impl(a.pop("target"))+ await h.drag(_locator_target(impl), _locator_target(other), a, api=f"{api}.drag_to")++ common = {+ "click": click, "dblclick": dblclick, "hover": hover, "tap": tap, "fill": fill,+ "type": type_, "press": press, "check": check, "uncheck": uncheck,+ "set_checked": set_checked, "select_option": select_option, "focus": focus,+ }+ if kind in ("Page", "Frame"):+ return {**common, "drag_and_drop": drag_and_drop}+ if kind == "Locator":+ return {**common, "clear": clear, "press_sequentially": press_sequentially,+ "drag_to": drag_to, "scroll_into_view_if_needed": scroll_into_view_if_needed}+ return {**common, "scroll_into_view_if_needed": scroll_into_view_if_needed}+++async def _mouse_move(h: Human, impl: Any, a: dict) -> None:+ await h.mouse_move(a["x"], a["y"], a.get("steps"))+++async def _mouse_click(h: Human, impl: Any, a: dict) -> None:+ await h.mouse_click(a["x"], a["y"], a.get("delay"), a.get("button"), a.get("click_count"))+++async def _mouse_dblclick(h: Human, impl: Any, a: dict) -> None:+ await h.mouse_click(a["x"], a["y"], a.get("delay"), a.get("button"), 2)+++async def _keyboard_type(h: Human, impl: Any, a: dict) -> None:+ await h.keyboard_type(a["text"], a.get("delay"))+++_INPUT_HANDLERS: Dict[str, Dict[str, Handler]] = {+ "Mouse": {"move": _mouse_move, "click": _mouse_click, "dblclick": _mouse_dblclick},+ "Keyboard": {"type": _keyboard_type},+}+++# ---------------------------------------------------------------------------+# class patching+# ---------------------------------------------------------------------------++def _wrap(kind: str, cls: type, name: str, handler: Handler, is_async: bool) -> None:+ orig = cls.__dict__.get(name)+ if orig is None:+ return+ _ORIG[(cls, name)] = orig+ sig = inspect.signature(orig)++ def bind(self: Any, args: tuple, kwargs: dict, human_config: Optional[dict]) -> Dict[str, Any]:+ bound = sig.bind(self, *args, **kwargs)+ a = dict(bound.arguments)+ a.pop("self", None)+ a = _normalize(a)+ a["human_config"] = human_config+ return a++ if is_async:+ @functools.wraps(orig)+ async def wrapper(self: Any, *args: Any, human_config: Optional[dict] = None, **kwargs: Any) -> Any:+ h = _human_for(kind, self)+ if h is None:+ return await orig(self, *args, **kwargs)+ return await handler(h, self._impl_obj, bind(self, args, kwargs, human_config))+ else:+ @functools.wraps(orig)+ def wrapper(self: Any, *args: Any, human_config: Optional[dict] = None, **kwargs: Any) -> Any:+ h = _human_for(kind, self)+ if h is None:+ return orig(self, *args, **kwargs)+ return self._sync(handler(h, self._impl_obj, bind(self, args, kwargs, human_config)))++ wrapper.__cloak_humanized__ = True # type: ignore[attr-defined]+ setattr(cls, name, wrapper)+++def _install(api: str) -> None:+ if _PATCHED[api]:+ return+ _check_playwright()+ if api == "sync":+ from playwright.sync_api import _generated as g+ else:+ from playwright.async_api import _generated as g+ is_async = api == "async"+ for kind in ("Page", "Frame", "Locator", "ElementHandle"):+ cls = getattr(g, kind)+ for name, handler in _handlers(kind).items():+ _wrap(kind, cls, name, handler, is_async)+ for kind, table in _INPUT_HANDLERS.items():+ cls = getattr(g, kind)+ for name, handler in table.items():+ _wrap(kind, cls, name, handler, is_async)+ _PATCHED[api] = True+++def original(cls: type, name: str) -> Callable[..., Any]:+ """The unpatched Playwright method ``cls.name``."""+ return _ORIG.get((cls, name)) or getattr(cls, name)+++class _Originals:+ """``page._original``: raw, un-humanized Playwright calls for this page."""++ _PAGE = ("click", "type", "fill", "hover", "dblclick", "select_option", "check", "uncheck",+ "press", "tap", "focus", "set_checked", "drag_and_drop", "goto")++ def __init__(self, page: Any) -> None:+ cls, mouse, kb = type(page), page.mouse, page.keyboard+ for name in self._PAGE:+ setattr(self, name, functools.partial(original(cls, name), page))+ for name in ("move", "click", "dblclick", "wheel", "down", "up"):+ setattr(self, f"mouse_{name}", functools.partial(original(type(mouse), name), mouse))+ for name in ("type", "down", "up", "press", "insert_text"):+ setattr(self, f"keyboard_{name}", functools.partial(original(type(kb), name), kb))+++class _StealthWorld:+ """``page._stealth_world``: evaluate an expression in the main frame's+ isolated world (the same world the humanize engine uses)."""++ def __init__(self, page: Any, human: Human, is_async: bool) -> None:+ self._page, self._human, self._async = page, human, is_async++ def evaluate(self, expression: str) -> Any:+ coro = self._human.worlds.evaluate(self._human.page.main_frame, expression)+ return coro if self._async else self._page._sync(coro)++ def invalidate(self) -> None:+ self._human.worlds.invalidate()+++def _attach(page: Any, cfg: HumanConfig, cursor: CursorState, api: str) -> Human:+ _install(api)+ impl = page._impl_obj+ human = getattr(impl, "_cloak_human", None)+ if human is None:+ human = Human(impl, cfg, cursor)+ impl._cloak_human = human+ page._original = _Originals(page)+ page._human_cfg = cfg+ page._human_cursor = cursor+ page._stealth_world = _StealthWorld(page, human, api == "async")+ return human+++def patch_page(page: Any, cfg: HumanConfig, cursor: Optional[CursorState] = None) -> None:+ """Humanize a sync Playwright page."""+ cursor = cursor if cursor is not None else CursorState()+ _attach(page, cfg, cursor, "sync")+ if not cursor.initialized:+ # Start near the address bar instead of (0, 0).+ cursor.x = rand(*cfg.initial_cursor_x)+ cursor.y = rand(*cfg.initial_cursor_y)+ try:+ page._original.mouse_move(cursor.x, cursor.y)+ cursor.initialized = True+ except Exception: # e.g. called from an event handler; done lazily+ pass+++def patch_page_async(page: Any, cfg: HumanConfig, cursor: Optional[CursorState] = None) -> None:+ """Humanize an async Playwright page (cursor is placed on first action)."""+ _attach(page, cfg, cursor if cursor is not None else CursorState(), "async")+++def patch_context(context: Any, cfg: HumanConfig) -> None:+ # Install class patches before any page exists: wrappers that capture+ # bound methods at page creation (license guard) must see the humanized ones.+ _install("sync")+ cursor = CursorState()+ for page in context.pages:+ patch_page(page, cfg, cursor)+ context.on("page", lambda p: None if hasattr(p, "_original") else patch_page(p, cfg, CursorState()))+ orig_new_page = context.new_page++ def new_page(*args: Any, **kwargs: Any) -> Any:+ page = orig_new_page(*args, **kwargs)+ if not hasattr(page, "_original"):+ patch_page(page, cfg, CursorState())+ return page++ context.new_page = new_page+++def patch_browser(browser: Any, cfg: HumanConfig) -> None:+ _install("sync")+ for context in browser.contexts:+ patch_context(context, cfg)+ orig_new_context, orig_new_page = browser.new_context, browser.new_page++ def new_context(*args: Any, **kwargs: Any) -> Any:+ context = orig_new_context(*args, **kwargs)+ patch_context(context, cfg)+ return context++ def new_page(*args: Any, **kwargs: Any) -> Any:+ page = orig_new_page(*args, **kwargs)+ if not hasattr(page, "_original"):+ patch_page(page, cfg, CursorState())+ return page++ browser.new_context = new_context+ browser.new_page = new_page+++def patch_context_async(context: Any, cfg: HumanConfig) -> None:+ _install("async")+ cursor = CursorState()+ for page in context.pages:+ patch_page_async(page, cfg, cursor)+ context.on("page", lambda p: None if hasattr(p, "_original") else patch_page_async(p, cfg, CursorState()))+ orig_new_page = context.new_page++ async def new_page(*args: Any, **kwargs: Any) -> Any:+ page = await orig_new_page(*args, **kwargs)+ if not hasattr(page, "_original"):+ patch_page_async(page, cfg, CursorState())+ return page++ context.new_page = new_page+++def patch_browser_async(browser: Any, cfg: HumanConfig) -> None:+ _install("async")+ for context in browser.contexts:+ patch_context_async(context, cfg)+ orig_new_context, orig_new_page = browser.new_context, browser.new_page++ async def new_context(*args: Any, **kwargs: Any) -> Any:+ context = await orig_new_context(*args, **kwargs)+ patch_context_async(context, cfg)+ return context++ async def new_page(*args: Any, **kwargs: Any) -> Any:+ page = await orig_new_page(*args, **kwargs)+ if not hasattr(page, "_original"):+ patch_page_async(page, cfg, CursorState())+ return page++ browser.new_context = new_context+ browser.new_page = new_pagediff --git a/cloakbrowser/human/scroll.py b/cloakbrowser/human/scroll.pydeleted file mode 100644index 448f276..0000000--- a/cloakbrowser/human/scroll.py+++ /dev/null@@ -1,299 +0,0 @@-"""cloakbrowser-human — Human-like scrolling via mouse wheel events."""--from __future__ import annotations--import math-import random-import time-from typing import Any, Callable, Optional, Tuple--from .config import HumanConfig, rand, rand_range, rand_int_range, sleep_ms-from .mouse import RawMouse, human_move-from .stealth_dom import (- build_box_js, eval_parsed, EVALUATION_FAILED, NOT_FOUND, OK, UNSUPPORTED,- StealthEvaluationError, StealthWorldUnavailableError,- UnsupportedHumanizeSelectorError, _VIEWPORT_JS,-)---def _is_in_viewport(bounds: dict, viewport_height: int, cfg: HumanConfig) -> bool:- top_edge = bounds["y"]- bottom_edge = bounds["y"] + bounds["height"]- zone_top = viewport_height * cfg.scroll_target_zone[0]- zone_bottom = viewport_height * cfg.scroll_target_zone[1]- return top_edge >= zone_top and bottom_edge <= zone_bottom---def _is_in_viewport_x(bounds: dict, viewport_width: int) -> bool:- return bounds["x"] >= 0 and bounds["x"] + bounds["width"] <= viewport_width---def _get_element_box(page: Any, selector: str, timeout: float = 30000) -> Optional[dict]:- """Locate ``selector`` and read geometry only in the isolated world."""- world = getattr(page, "_stealth_world", None)- if world is None:- raise StealthWorldUnavailableError()- deadline = time.monotonic() + max(0, timeout) / 1000.0- status, data = eval_parsed(world, build_box_js(selector))- while status in (NOT_FOUND, EVALUATION_FAILED) and time.monotonic() < deadline:- time.sleep(0.05)- status, data = eval_parsed(world, build_box_js(selector))- if status == OK:- box = dict(data["box"])- box["targetId"] = data["targetId"]- box["gen"] = data["gen"]- return box- if status == NOT_FOUND:- return None- if status == UNSUPPORTED:- raise UnsupportedHumanizeSelectorError(selector)- raise StealthEvaluationError(selector)---# In RTL documents Chrome's scrollX runs from 0 down to -range, and the-# viewport takes its direction from <body> when there is one.-_SCROLL_JS = (- "(() => { const e = document.scrollingElement || document.documentElement;"- " const rangeX = Math.max(0, e.scrollWidth - e.clientWidth);"- " const rtl = getComputedStyle(document.body || e).direction === 'rtl';"- " return { y: window.scrollY, maxY: Math.max(0, e.scrollHeight - e.clientHeight),"- " x: window.scrollX, minX: rtl ? -rangeX : 0, maxX: rtl ? 0 : rangeX }; })()"-)---def _read_scroll_state(page: Any) -> dict:- """Read scroll state only through the isolated world."""- world = getattr(page, "_stealth_world", None)- if world is None:- raise StealthWorldUnavailableError()- try:- state = world.evaluate(_SCROLL_JS)- except Exception as exc:- raise StealthEvaluationError("<scroll-state>") from exc- if not isinstance(state, dict):- raise StealthEvaluationError("<scroll-state>")- return state---def _smooth_wheel(raw: RawMouse, delta: int, cfg: HumanConfig, axis: str = "y") -> None:- """Send one logical scroll as a burst of small wheel events (like real inertia)."""- abs_d = abs(delta)- sign = 1 if delta > 0 else -1- sent = 0- while sent < abs_d:- step_size = rand(20, 40)- chunk = min(step_size, abs_d - sent)- step = round(chunk) * sign- if axis == "x":- raw.wheel(step, 0)- else:- raw.wheel(0, step)- sent += chunk- sleep_ms(rand(8, 20))---def human_scroll_into_view(- page: Any,- raw: RawMouse,- get_box: Callable[[], Optional[dict]],- cursor_x: float, cursor_y: float,- cfg: HumanConfig,-) -> Tuple[dict, float, float, bool]:- """Humanized scrolling that uses an arbitrary ``get_box`` callable- instead of a CSS selector.-- Used both by ``scroll_to_element`` (selector-based) and by- ``ElementHandle.scroll_into_view_if_needed`` / ``Locator.scroll_into_view_if_needed``- (handle-based) so the same accelerate \u2192 cruise \u2192 decelerate \u2192 overshoot- behavior runs everywhere.-- Returns ``(box, cursor_x, cursor_y, did_scroll)`` \u2014 *did_scroll* is False- when the element was already in the viewport.- """- viewport = page.viewport_size- if not viewport:- # Headed launches default to no_viewport so the page tracks the real OS- # window; page.viewport_size is then None. Read the live window dimensions- # through the isolated world, consistent with the other geometry reads here.- world = getattr(page, "_stealth_world", None)- if world is None:- raise StealthWorldUnavailableError()- try:- viewport = world.evaluate(_VIEWPORT_JS)- except Exception as exc:- raise StealthEvaluationError("<viewport>") from exc- if not viewport or not viewport.get("height"):- raise RuntimeError("Viewport size not available")-- viewport_height = viewport["height"]- viewport_width = viewport["width"]-- box, cursor_x, cursor_y, did_scroll_y = _scroll_y_into_view(- page, raw, get_box, viewport_width, viewport_height, cursor_x, cursor_y, cfg,- )- box, cursor_x, cursor_y, did_scroll_x = _scroll_x_into_view(- page, raw, get_box, box, viewport_width, viewport_height, cursor_x, cursor_y, cfg,- )- return box, cursor_x, cursor_y, did_scroll_y or did_scroll_x---def _scroll_y_into_view(- page: Any,- raw: RawMouse,- get_box: Callable[[], Optional[dict]],- viewport_width: int, viewport_height: int,- cursor_x: float, cursor_y: float,- cfg: HumanConfig,-) -> Tuple[dict, float, float, bool]:- """Vertical pass: bring the box into ``scroll_target_zone``."""- box = get_box()- if box is None:- raise RuntimeError("Element not found while scrolling into view")-- if _is_in_viewport(box, viewport_height, cfg):- return box, cursor_x, cursor_y, False-- # Already fully visible but off-center, with the page pinned at the boundary- # in the needed direction: scrolling can't help, so don't waste the budget.- # 1px slack: layout can report a top edge of -1/64 px on an unscrolled page.- fully_visible = box["y"] >= -1 and box["y"] + box["height"] <= viewport_height + 1- if fully_visible:- zone_mid = viewport_height * (cfg.scroll_target_zone[0] + cfg.scroll_target_zone[1]) / 2- need_up = box["y"] + box["height"] / 2 < zone_mid- scroll = _read_scroll_state(page)- if (scroll["y"] <= 0) if need_up else (scroll["y"] >= scroll["maxY"]):- return box, cursor_x, cursor_y, False-- # Move cursor into scroll area- scroll_area_x = round(viewport_width * rand(0.3, 0.7))- scroll_area_y = round(viewport_height * rand(0.3, 0.7))- human_move(raw, cursor_x, cursor_y, scroll_area_x, scroll_area_y, cfg)- cursor_x = scroll_area_x- cursor_y = scroll_area_y- sleep_ms(rand_range(cfg.scroll_pre_move_delay))-- # Calculate scroll distance- target_y = viewport_height * rand(cfg.scroll_target_zone[0], cfg.scroll_target_zone[1])- element_center = box["y"] + box["height"] / 2- distance_to_scroll = element_center - target_y-- direction = 1 if distance_to_scroll > 0 else -1- abs_distance = abs(distance_to_scroll)- avg_delta = (cfg.scroll_delta_base[0] + cfg.scroll_delta_base[1]) / 2- total_clicks = max(3, math.ceil(abs_distance / avg_delta))- accel_steps = rand_int_range(cfg.scroll_accel_steps)- decel_steps = rand_int_range(cfg.scroll_decel_steps)-- # Scroll loop: accelerate → cruise → decelerate- scrolled = 0- for i in range(total_clicks):- if i < accel_steps:- delta = rand(80, 100)- pause = rand_range(cfg.scroll_pause_slow)- elif i >= total_clicks - decel_steps:- delta = rand(60, 90)- pause = rand_range(cfg.scroll_pause_slow)- else:- delta = rand_range(cfg.scroll_delta_base)- pause = rand_range(cfg.scroll_pause_fast)-- delta *= 1 + (random.random() - 0.5) * 2 * cfg.scroll_delta_variance- delta = round(delta) * direction-- _smooth_wheel(raw, delta, cfg)- scrolled += abs(delta)- sleep_ms(pause)-- # Check visibility every 3 steps- if i % 3 == 2 or i == total_clicks - 1:- box = get_box()- if box and _is_in_viewport(box, viewport_height, cfg):- break- if scrolled >= abs_distance * 1.1:- break-- # Optional overshoot + correction- if random.random() < cfg.scroll_overshoot_chance:- overshoot_px = round(rand_range(cfg.scroll_overshoot_px)) * direction- _smooth_wheel(raw, overshoot_px, cfg)- sleep_ms(rand_range(cfg.scroll_settle_delay))- corrections = rand_int_range((1, 2))- for _ in range(corrections):- corr_delta = round(rand(40, 80)) * -direction- _smooth_wheel(raw, corr_delta, cfg)- sleep_ms(rand(100, 250))-- # Settle- sleep_ms(rand_range(cfg.scroll_settle_delay))-- box = get_box()- if box is None:- raise RuntimeError("Element lost after scrolling into view")-- return box, cursor_x, cursor_y, True---def _scroll_x_into_view(- page: Any,- raw: RawMouse,- get_box: Callable[[], Optional[dict]],- box: dict,- viewport_width: int, viewport_height: int,- cursor_x: float, cursor_y: float,- cfg: HumanConfig,-) -> Tuple[dict, float, float, bool]:- """Horizontal pass: bring the box inside the viewport width (#521).-- Only containment is checked here, not ``scroll_target_zone``: the zone is- a vertical reading position, and horizontal overflow is the exception.- """- if _is_in_viewport_x(box, viewport_width):- return box, cursor_x, cursor_y, False-- distance_to_scroll = box["x"] + box["width"] / 2 - viewport_width / 2- # A box wider than the viewport is never contained; once centred, skip the near-zero wheel.- if abs(distance_to_scroll) < 1:- return box, cursor_x, cursor_y, False-- # Page pinned at the boundary in the needed direction: scrolling can't help.- scroll = _read_scroll_state(page)- if (scroll["x"] <= scroll["minX"]) if distance_to_scroll < 0 else (scroll["x"] >= scroll["maxX"]):- return box, cursor_x, cursor_y, False-- scroll_area_x = round(viewport_width * rand(0.3, 0.7))- scroll_area_y = round(viewport_height * rand(0.3, 0.7))- human_move(raw, cursor_x, cursor_y, scroll_area_x, scroll_area_y, cfg)- cursor_x = scroll_area_x- cursor_y = scroll_area_y- sleep_ms(rand_range(cfg.scroll_pre_move_delay))-- _smooth_wheel(raw, round(distance_to_scroll), cfg, axis="x")- sleep_ms(rand_range(cfg.scroll_settle_delay))-- box = get_box()- if box is None:- raise RuntimeError("Element lost after scrolling into view")-- return box, cursor_x, cursor_y, True---def scroll_to_element(- page: Any,- raw: RawMouse,- selector: str,- cursor_x: float, cursor_y: float,- cfg: HumanConfig,- timeout: float = 30000,-) -> Tuple[dict, float, float, bool]:- """Selector-based humanized scroll.-- ``timeout`` bounds isolated-world geometry polling so callers such as- ``page.click('#x', timeout=5000)`` can wait for slow elements (#172).-- Returns ``(box, cursor_x, cursor_y, did_scroll)``.- """- return human_scroll_into_view(- page, raw,- lambda: _get_element_box(page, selector, timeout),- cursor_x, cursor_y, cfg,- )diff --git a/cloakbrowser/human/scroll_async.py b/cloakbrowser/human/scroll_async.pydeleted file mode 100644index a60d5ef..0000000--- a/cloakbrowser/human/scroll_async.py+++ /dev/null@@ -1,285 +0,0 @@-"""cloakbrowser-human — Async human-like scrolling via mouse wheel events.--Mirrors scroll.py but uses ``await`` for all Playwright calls and-``async_sleep_ms`` instead of ``sleep_ms``.-"""--from __future__ import annotations--import asyncio-import math-import random-import time-from typing import Any, Awaitable, Callable, Optional, Tuple--from .config import HumanConfig, rand, rand_range, rand_int_range, async_sleep_ms-from .mouse_async import AsyncRawMouse, async_human_move-from .scroll import _is_in_viewport, _is_in_viewport_x, _SCROLL_JS-from .stealth_dom import (- build_box_js, async_eval_parsed, EVALUATION_FAILED, NOT_FOUND, OK, UNSUPPORTED,- StealthEvaluationError, StealthWorldUnavailableError,- UnsupportedHumanizeSelectorError, _VIEWPORT_JS,-)---async def _get_element_box_async(- page: Any, selector: str, timeout: float = 30000,-) -> Optional[dict]:- """Async isolated-world geometry read with no Playwright fallback."""- world = getattr(page, "_stealth_world", None)- if world is None:- raise StealthWorldUnavailableError()- deadline = time.monotonic() + max(0, timeout) / 1000.0- status, data = await async_eval_parsed(world, build_box_js(selector))- while status in (NOT_FOUND, EVALUATION_FAILED) and time.monotonic() < deadline:- await asyncio.sleep(0.05)- status, data = await async_eval_parsed(world, build_box_js(selector))- if status == OK:- box = dict(data["box"])- box["targetId"] = data["targetId"]- box["gen"] = data["gen"]- return box- if status == NOT_FOUND:- return None- if status == UNSUPPORTED:- raise UnsupportedHumanizeSelectorError(selector)- raise StealthEvaluationError(selector)---async def _async_read_scroll_state(page: Any) -> dict:- """Read scroll state only through the isolated world."""- world = getattr(page, "_stealth_world", None)- if world is None:- raise StealthWorldUnavailableError()- try:- state = await world.evaluate(_SCROLL_JS)- except Exception as exc:- raise StealthEvaluationError("<scroll-state>") from exc- if not isinstance(state, dict):- raise StealthEvaluationError("<scroll-state>")- return state---async def _async_smooth_wheel(- raw: AsyncRawMouse, delta: int, cfg: HumanConfig, axis: str = "y",-) -> None:- """Send one logical scroll as a burst of small wheel events (like real inertia)."""- abs_d = abs(delta)- sign = 1 if delta > 0 else -1- sent = 0- while sent < abs_d:- step_size = rand(20, 40)- chunk = min(step_size, abs_d - sent)- step = round(chunk) * sign- if axis == "x":- await raw.wheel(step, 0)- else:- await raw.wheel(0, step)- sent += chunk- await async_sleep_ms(rand(8, 20))---async def async_human_scroll_into_view(- page: Any,- raw: AsyncRawMouse,- get_box: Callable[[], Awaitable[Optional[dict]]],- cursor_x: float, cursor_y: float,- cfg: HumanConfig,-) -> Tuple[dict, float, float, bool]:- """Humanized scrolling using an arbitrary async ``get_box`` callable.-- Used by both ``async_scroll_to_element`` (selector-based) and the- ElementHandle / Locator ``scroll_into_view_if_needed`` patches so all- scrolling paths share the same accelerate \u2192 cruise \u2192 decelerate- \u2192 overshoot behavior.-- Returns ``(box, cursor_x, cursor_y, did_scroll)`` \u2014 *did_scroll* is False- when the element was already in the viewport.- """- viewport = page.viewport_size- if not viewport:- # Headed launches default to no_viewport so the page tracks the real OS- # window; page.viewport_size is then None. Read the live window dimensions- # through the isolated world, consistent with the other geometry reads here.- world = getattr(page, "_stealth_world", None)- if world is None:- raise StealthWorldUnavailableError()- try:- viewport = await world.evaluate(_VIEWPORT_JS)- except Exception as exc:- raise StealthEvaluationError("<viewport>") from exc- if not viewport or not viewport.get("height"):- raise RuntimeError("Viewport size not available")-- viewport_height = viewport["height"]- viewport_width = viewport["width"]-- box, cursor_x, cursor_y, did_scroll_y = await _async_scroll_y_into_view(- page, raw, get_box, viewport_width, viewport_height, cursor_x, cursor_y, cfg,- )- box, cursor_x, cursor_y, did_scroll_x = await _async_scroll_x_into_view(- page, raw, get_box, box, viewport_width, viewport_height, cursor_x, cursor_y, cfg,- )- return box, cursor_x, cursor_y, did_scroll_y or did_scroll_x---async def _async_scroll_y_into_view(- page: Any,- raw: AsyncRawMouse,- get_box: Callable[[], Awaitable[Optional[dict]]],- viewport_width: int, viewport_height: int,- cursor_x: float, cursor_y: float,- cfg: HumanConfig,-) -> Tuple[dict, float, float, bool]:- """Vertical pass: bring the box into ``scroll_target_zone``."""- box = await get_box()- if box is None:- raise RuntimeError("Element not found while scrolling into view")-- if _is_in_viewport(box, viewport_height, cfg):- return box, cursor_x, cursor_y, False-- # Already fully visible but off-center, with the page pinned at the boundary- # in the needed direction: scrolling can't help, so don't waste the budget.- # 1px slack: layout can report a top edge of -1/64 px on an unscrolled page.- fully_visible = box["y"] >= -1 and box["y"] + box["height"] <= viewport_height + 1- if fully_visible:- zone_mid = viewport_height * (cfg.scroll_target_zone[0] + cfg.scroll_target_zone[1]) / 2- need_up = box["y"] + box["height"] / 2 < zone_mid- scroll = await _async_read_scroll_state(page)- if (scroll["y"] <= 0) if need_up else (scroll["y"] >= scroll["maxY"]):- return box, cursor_x, cursor_y, False-- # Move cursor into scroll area- scroll_area_x = round(viewport_width * rand(0.3, 0.7))- scroll_area_y = round(viewport_height * rand(0.3, 0.7))- await async_human_move(raw, cursor_x, cursor_y, scroll_area_x, scroll_area_y, cfg)- cursor_x = scroll_area_x- cursor_y = scroll_area_y- await async_sleep_ms(rand_range(cfg.scroll_pre_move_delay))-- # Calculate scroll distance- target_y = viewport_height * rand(cfg.scroll_target_zone[0], cfg.scroll_target_zone[1])- element_center = box["y"] + box["height"] / 2- distance_to_scroll = element_center - target_y-- direction = 1 if distance_to_scroll > 0 else -1- abs_distance = abs(distance_to_scroll)- avg_delta = (cfg.scroll_delta_base[0] + cfg.scroll_delta_base[1]) / 2- total_clicks = max(3, math.ceil(abs_distance / avg_delta))- accel_steps = rand_int_range(cfg.scroll_accel_steps)- decel_steps = rand_int_range(cfg.scroll_decel_steps)-- # Scroll loop: accelerate → cruise → decelerate- scrolled = 0- for i in range(total_clicks):- if i < accel_steps:- delta = rand(80, 100)- pause = rand_range(cfg.scroll_pause_slow)- elif i >= total_clicks - decel_steps:- delta = rand(60, 90)- pause = rand_range(cfg.scroll_pause_slow)- else:- delta = rand_range(cfg.scroll_delta_base)- pause = rand_range(cfg.scroll_pause_fast)-- delta *= 1 + (random.random() - 0.5) * 2 * cfg.scroll_delta_variance- delta = round(delta) * direction-- await _async_smooth_wheel(raw, delta, cfg)- scrolled += abs(delta)- await async_sleep_ms(pause)-- # Check visibility every 3 steps- if i % 3 == 2 or i == total_clicks - 1:- box = await get_box()- if box and _is_in_viewport(box, viewport_height, cfg):- break- if scrolled >= abs_distance * 1.1:- break-- # Optional overshoot + correction- if random.random() < cfg.scroll_overshoot_chance:- overshoot_px = round(rand_range(cfg.scroll_overshoot_px)) * direction- await _async_smooth_wheel(raw, overshoot_px, cfg)- await async_sleep_ms(rand_range(cfg.scroll_settle_delay))- corrections = rand_int_range((1, 2))- for _ in range(corrections):- corr_delta = round(rand(40, 80)) * -direction- await _async_smooth_wheel(raw, corr_delta, cfg)- await async_sleep_ms(rand(100, 250))-- # Settle- await async_sleep_ms(rand_range(cfg.scroll_settle_delay))-- box = await get_box()- if box is None:- raise RuntimeError("Element lost after scrolling into view")-- return box, cursor_x, cursor_y, True---async def _async_scroll_x_into_view(- page: Any,- raw: AsyncRawMouse,- get_box: Callable[[], Awaitable[Optional[dict]]],- box: dict,- viewport_width: int, viewport_height: int,- cursor_x: float, cursor_y: float,- cfg: HumanConfig,-) -> Tuple[dict, float, float, bool]:- """Horizontal pass: bring the box inside the viewport width (#521).-- Only containment is checked here, not ``scroll_target_zone``: the zone is- a vertical reading position, and horizontal overflow is the exception.- """- if _is_in_viewport_x(box, viewport_width):- return box, cursor_x, cursor_y, False-- distance_to_scroll = box["x"] + box["width"] / 2 - viewport_width / 2- # A box wider than the viewport is never contained; once centred, skip the near-zero wheel.- if abs(distance_to_scroll) < 1:- return box, cursor_x, cursor_y, False-- # Page pinned at the boundary in the needed direction: scrolling can't help.- scroll = await _async_read_scroll_state(page)- if (scroll["x"] <= scroll["minX"]) if distance_to_scroll < 0 else (scroll["x"] >= scroll["maxX"]):- return box, cursor_x, cursor_y, False-- scroll_area_x = round(viewport_width * rand(0.3, 0.7))- scroll_area_y = round(viewport_height * rand(0.3, 0.7))- await async_human_move(raw, cursor_x, cursor_y, scroll_area_x, scroll_area_y, cfg)- cursor_x = scroll_area_x- cursor_y = scroll_area_y- await async_sleep_ms(rand_range(cfg.scroll_pre_move_delay))-- await _async_smooth_wheel(raw, round(distance_to_scroll), cfg, axis="x")- await async_sleep_ms(rand_range(cfg.scroll_settle_delay))-- box = await get_box()- if box is None:- raise RuntimeError("Element lost after scrolling into view")-- return box, cursor_x, cursor_y, True---async def async_scroll_to_element(- page: Any,- raw: AsyncRawMouse,- selector: str,- cursor_x: float, cursor_y: float,- cfg: HumanConfig,- timeout: float = 30000,-) -> Tuple[dict, float, float, bool]:- """Selector-based humanized scroll (async).-- ``timeout`` bounds isolated-world geometry polling so callers such as- ``page.click('#x', timeout=5000)`` can wait for slow elements (#172).-- Returns ``(box, cursor_x, cursor_y, did_scroll)``.- """- async def _get():- return await _get_element_box_async(page, selector, timeout)- return await async_human_scroll_into_view(- page, raw, _get, cursor_x, cursor_y, cfg,- )diff --git a/cloakbrowser/human/stealth_dom.py b/cloakbrowser/human/stealth_dom.pydeleted file mode 100644index 1084ca3..0000000--- a/cloakbrowser/human/stealth_dom.py+++ /dev/null@@ -1,917 +0,0 @@-"""Isolated-world DOM reads for the humanize layer.--The pre-click helpers (``ensure_actionable``, ``scroll_to_element`` geometry,-``check_pointer_events``) read element state and geometry. This module performs-those reads inside the CDP isolated execution context (``page._stealth_world``,-created via ``Page.createIsolatedWorld``) rather than through Playwright's-selector/evaluate machinery.--The isolated world resolves elements with plain DOM APIs (``document.querySelector``-etc.), so this module reimplements the subset of Playwright's selector grammar the-humanize layer commonly receives:-- * plain CSS / ``css=`` — including the ``:has-text("...")`` pseudo- * ``text=`` engine (quoted = exact, unquoted = case-insensitive substring)- * ``xpath=`` / leading ``//``- * ``internal:testid=`` / ``internal:attr=`` (``get_by_test_id``,- ``get_by_placeholder``, ``get_by_alt_text``, ``get_by_title``)- * ``internal:text=`` / ``internal:label=`` (``get_by_text``, ``get_by_label``)- * a trailing ``>> nth=N`` (what ``.first`` / ``.nth(k)`` / ``.last`` append)--Anything richer returns ``unsupported`` and the caller raises a typed error:-``>>`` chaining (so ``.filter()``, ``.and_()``, ``.or_()`` and chained locators),-``internal:role=`` (``get_by_role`` — a faithful port needs Playwright's whole-accessible-name algorithm), ``internal:has*``, ``internal:control=``-(``frame_locator``), ``:visible``, ``:nth-match``, and layout pseudos.-Correctness and stealth win on ties: uncertain grammar never falls back to-Playwright DOM reads, because a mis-resolved element means clicking the wrong-coordinates.--The JS builders and :func:`parse_result` are pure and shared by the sync and-async call sites; only the ``world.evaluate`` await differs.-"""--from __future__ import annotations--import json-from typing import Any, Optional, Tuple--# Versioned protocol returned by the isolated-world DOM helper.-PROTOCOL_VERSION = 2--# Status returned to callers.-OK = "ok"-NOT_FOUND = "not_found"-UNSUPPORTED = "unsupported"-STALE = "stale"-EVALUATION_FAILED = "evaluation_failed"---class StealthDomError(RuntimeError):- """Base for isolated-world DOM helper failures."""---class UnsupportedHumanizeSelectorError(StealthDomError):- """Raised for selector grammar the isolated-world resolver cannot resolve.-- The humanize layer resolves selectors inside the isolated world so page- scripts cannot observe the read. Grammar it cannot resolve is refused rather- than handed back to Playwright, whose locator predicates run in the page's- main world and are observable.- """-- def __init__(self, selector: str):- super().__init__(- f"Humanized selector {selector!r} is not supported by the isolated-world "- f"resolver. Supported: CSS, text=, xpath=, get_by_test_id, "- f"get_by_placeholder, get_by_alt_text, get_by_title, get_by_text, "- f"get_by_label, and a trailing .first/.nth()/.last. Not supported: "- f"get_by_role, chained locators (a >> b, .filter(), .and_(), .or_()), "- f"frame_locator, :visible and :nth-match. Use a CSS or text= selector "- f"for this action, or humanize=False to fall back to Playwright."- )---class StealthWorldUnavailableError(StealthDomError):- def __init__(self):- super().__init__("Humanized DOM read requires an active isolated world")---class StealthEvaluationError(StealthDomError):- def __init__(self, selector: str):- super().__init__(f"Isolated-world DOM evaluation failed for {selector!r}")--# ----------------------------------------------------------------------------# JS: selector resolution inside the isolated world-# ----------------------------------------------------------------------------# Defines ``__resolve(sel)`` returning the matched Element, ``null`` (no match),-# or the string ``'UNSUPPORTED'`` (grammar we don't reimplement). ``__SEL`` is-# inlined by the Python builders below.--_RESOLVER_BODY = r"""-const __UNS = 'UNSUPPORTED';-const __V = 2;-const __STATE_KEY = '__cloakHumanDomV1';-function __state(){- let s = globalThis[__STATE_KEY];- if (!s) {- // Element ids restart at 1 in every new world, and the world is recreated on- // navigation (#507), so an id alone can name a different element after a nav.- // The generation makes that cross-world reuse detectable as 'stale'.- // 11 bits of wall clock + 20 bits of randomness. The maximum is exactly- // Int32.MaxValue, because the .NET wrapper carries the value as an Int32.- s = { ids: new WeakMap(), nextId: 1,- gen: (Date.now() & 2047) * 1048576 + Math.floor(Math.random() * 1048576) };- Object.defineProperty(globalThis, __STATE_KEY, { value: s, configurable: false, enumerable: false });- }- return s;-}-function __gen(){ return __state().gen; }-function __targetId(el){- const s = __state();- let id = s.ids.get(el);- if (!id) { id = s.nextId++; s.ids.set(el, id); }- return id;-}-function __visibleTextNode(node){- const range = node.ownerDocument.createRange();- range.selectNode(node);- const rect = range.getBoundingClientRect();- return rect.width > 0 && rect.height > 0;-}-function __isVisible(el){- const style = getComputedStyle(el);- if (!style) return true;- if (style.display === 'contents') {- for (let child = el.firstChild; child; child = child.nextSibling) {- if (child.nodeType === 1 && __isVisible(child)) return true;- if (child.nodeType === 3 && style.visibility === 'visible' && __visibleTextNode(child)) return true;- }- return false;- }- try {- if (typeof el.checkVisibility === 'function' && !el.checkVisibility()) return false;- } catch (e) {- // Older engines fall through to computed style + geometry.- }- if (style.visibility !== 'visible') return false;- const rect = el.getBoundingClientRect();- return rect.width > 0 && rect.height > 0;-}-function __visBox(el){- const style = getComputedStyle(el);- if (style && style.display === 'contents') {- let x1 = Infinity, y1 = Infinity, x2 = -Infinity, y2 = -Infinity;- let found = false;- for (let child = el.firstChild; child; child = child.nextSibling) {- let box = null;- if (child.nodeType === 1 && __isVisible(child)) {- box = __visBox(child);- } else if (child.nodeType === 3 && style.visibility === 'visible' &&- __normWS(child.nodeValue)) {- const range = child.ownerDocument.createRange();- range.selectNode(child);- const rect = range.getBoundingClientRect();- if (rect.width > 0 && rect.height > 0) {- box = { x: rect.x, y: rect.y, width: rect.width, height: rect.height };- }- }- if (!box) continue;- found = true;- x1 = Math.min(x1, box.x);- y1 = Math.min(y1, box.y);- x2 = Math.max(x2, box.x + box.width);- y2 = Math.max(y2, box.y + box.height);- }- return found ? { x: x1, y: y1, width: x2 - x1, height: y2 - y1 } : null;- }- const rect = el.getBoundingClientRect();- return rect.width > 0 && rect.height > 0- ? { x: rect.x, y: rect.y, width: rect.width, height: rect.height }- : null;-}-const __ARIA_DISABLED_ROLES = new Set([- 'application','button','composite','gridcell','group','input','link','menuitem',- 'scrollbar','separator','tab','checkbox','columnheader','combobox','grid','listbox',- 'menu','menubar','menuitemcheckbox','menuitemradio','option','radio','radiogroup',- 'row','rowheader','searchbox','select','slider','spinbutton','switch','tablist',- 'textbox','toolbar','tree','treegrid','treeitem'-]);-const __ARIA_READONLY_ROLES = new Set([- 'checkbox','combobox','grid','gridcell','listbox','radiogroup','slider','spinbutton',- 'textbox','columnheader','rowheader','searchbox','switch','treegrid'-]);-function __role(el){- const explicit = (el.getAttribute('role') || '').trim().split(/\s+/)[0];- if (explicit) return explicit;- const tag = el.tagName.toLowerCase();- if (tag === 'button') return 'button';- if (tag === 'textarea') return 'textbox';- if (tag === 'select') return el.multiple ? 'listbox' : 'combobox';- if (tag === 'option') return 'option';- if ((tag === 'a' || tag === 'area') && el.hasAttribute('href')) return 'link';- if (tag === 'input') {- const type = (el.type || 'text').toLowerCase();- if (['button','submit','reset','image'].includes(type)) return 'button';- if (type === 'checkbox') return 'checkbox';- if (type === 'radio') return 'radio';- if (type === 'range') return 'slider';- if (type === 'number') return 'spinbutton';- if (type === 'search') return 'searchbox';- if (!['hidden','file','color'].includes(type)) return 'textbox';- }- return '';-}-function __nativeDisabled(el){- const tag = el.tagName.toLowerCase();- if (!['button','input','select','textarea','option','optgroup'].includes(tag)) return false;- if (el.hasAttribute('disabled')) return true;- if (tag === 'option' && el.closest('optgroup[disabled]')) return true;- const fieldset = el.closest('fieldset[disabled]');- if (!fieldset) return false;- const legend = fieldset.querySelector(':scope > legend');- return !legend || !legend.contains(el);-}-function __ariaDisabled(el){- if (!__ARIA_DISABLED_ROLES.has(__role(el))) return false;- let current = el;- while (current) {- const value = (current.getAttribute('aria-disabled') || '').toLowerCase();- if (value === 'true') return true;- if (value === 'false') return false;- current = __composedParent(current);- }- return false;-}-function __isEnabled(el){ return !(__nativeDisabled(el) || __ariaDisabled(el)); }-function __readonly(el){- const tag = el.tagName.toLowerCase();- if (tag === 'input' || tag === 'textarea' || tag === 'select') return el.hasAttribute('readonly');- if (__ARIA_READONLY_ROLES.has(__role(el))) return el.getAttribute('aria-readonly') === 'true';- if (el.isContentEditable) return false;- return null;-}-function __isEditable(el, enabled){- const readonly = __readonly(el);- return readonly === null ? false : enabled && !readonly;-}-function __normWS(s){- return (s || '').replace(/[\u200b\u00ad]/g, '').replace(/\s+/g, ' ').trim();-}-function __skipText(el){- const tag = el && el.tagName ? el.tagName.toLowerCase() : '';- return tag === 'script' || tag === 'style' || tag === 'noscript' ||- (document.head && document.head.contains(el));-}-function __elementText(el, cache){- if (cache.has(el)) return cache.get(el);- let out = { full: '', normalized: '', immediate: [] };- cache.set(el, out);- if (__skipText(el)) return out;- const tag = el.tagName ? el.tagName.toLowerCase() : '';- if (tag === 'input' && ['button', 'submit', 'reset'].includes((el.type || '').toLowerCase())) {- const value = el.value || '';- out = { full: value, normalized: __normWS(value), immediate: [value] };- cache.set(el, out);- return out;- }- if (!el.childNodes) {- const value = el.textContent || '';- out = { full: value, normalized: __normWS(value), immediate: value ? [value] : [] };- cache.set(el, out);- return out;- }- let full = '', immediate = '';- const fragments = [];- for (const child of el.childNodes) {- if (child.nodeType === 3) {- const value = child.nodeValue || '';- full += value;- immediate += value;- } else if (child.nodeType === 8) {- continue;- } else {- if (immediate) { fragments.push(immediate); immediate = ''; }- if (child.nodeType === 1) full += __elementText(child, cache).full;- }- }- if (immediate) fragments.push(immediate);- if (el.shadowRoot) full += __elementText(el.shadowRoot, cache).full;- out = { full: full, normalized: __normWS(full), immediate: fragments };- cache.set(el, out);- return out;-}-function __byXPath(xp){- try {- const r = document.evaluate(xp, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);- const out = [];- for (let i = 0; i < r.snapshotLength; i++) { out.push(r.snapshotItem(i)); }- return out;- } catch (e) { return __UNS; }-}-function __parseTextMatcher(arg){- arg = arg.trim();- if (arg.charAt(0) === '/') {- let end = -1, escaped = false;- for (let i = 1; i < arg.length; i++) {- const ch = arg.charAt(i);- if (!escaped && ch === '/') end = i;- escaped = !escaped && ch === '\\';- if (ch !== '\\') escaped = false;- }- if (end > 0) {- try { return { kind: 'regex', regex: new RegExp(arg.slice(1, end), arg.slice(end + 1)) }; }- catch (e) { return __UNS; }- }- }- const q = arg.charAt(0);- if ((q === '"' || q === "'") && arg.charAt(arg.length - 1) === q) {- let value;- try {- value = q === '"' ? JSON.parse(arg) : arg.slice(1, -1).replace(/\\(['"\\])/g, '$1');- } catch (e) { return __UNS; }- return { kind: 'exact', value: __normWS(value) };- }- return { kind: 'lax', value: __normWS(arg).toLowerCase() };-}-function __matchTextValue(text, matcher){- if (matcher.kind === 'regex') { matcher.regex.lastIndex = 0; return matcher.regex.test(text.full); }- // The public engine's exact rule compares immediate text-node runs, unlike- // internal:text which compares the full normalized subtree text.- if (matcher.kind === 'exact') return text.immediate.some(x => __normWS(x) === matcher.value);- return text.normalized.toLowerCase().includes(matcher.value);-}-function __matchText(el, matcher, cache){- return __matchTextValue(__elementText(el, cache), matcher);-}-function __publicTextMatches(el, matcher, cache){- // Playwright's elementMatchesText for the public text= engine.- if (__skipText(el)) return 'none';- if (!__matchText(el, matcher, cache)) return 'none';- for (const child of el.children || []) {- if (__matchText(child, matcher, cache)) return 'selfAndChildren';- }- // A host whose shadow content also matches is not the smallest match. This- // cannot be expressed with contains(), which does not pierce shadow roots.- if (el.shadowRoot && __matchTextValue(__elementText(el.shadowRoot, cache), matcher))- return 'selfAndChildren';- return 'self';-}-function __byText(arg){- const matcher = __parseTextMatcher(arg);- if (matcher === __UNS) return __UNS;- const out = [], cache = new Map();- let lastMiss = null;- for (const el of __allElements()) {- // Nothing under a non-matching ancestor can match in lax mode.- if (matcher.kind === 'lax' && lastMiss && lastMiss.contains(el)) continue;- const m = __publicTextMatches(el, matcher, cache);- if (m === 'none') lastMiss = el;- // The public engine also keeps an ancestor when the match is exact.- if (m === 'self' || (m === 'selfAndChildren' && matcher.kind === 'exact')) out.push(el);- }- return out;-}-function __attrUnquote(s, i){- // parseAttributeSelector.readQuotedString: a backslash is dropped and the next- // character taken verbatim -- NOT JSON escapes, so "a\\nb" decodes to 'anb'.- const quote = s.charAt(i);- if (quote !== '"' && quote !== "'") return __UNS;- let out = '';- i++;- while (i < s.length && s.charAt(i) !== quote) {- if (s.charAt(i) === '\\') {- i++;- if (i >= s.length) return __UNS;- }- out += s.charAt(i++);- }- if (s.charAt(i) !== quote) return __UNS;- return { value: out, end: i + 1 };-}-function __parseAttrBody(body){- // [name="value"i] | [name="value"s] | [name=/re/flags]- body = body.trim();- if (body.charAt(0) !== '[' || body.charAt(body.length - 1) !== ']') return __UNS;- const inner = body.slice(1, -1);- const eq = inner.indexOf('=');- if (eq <= 0) return __UNS;- let name = inner.slice(0, eq).trim();- if (name.charAt(0) === '"' || name.charAt(0) === "'") {- const un = __attrUnquote(name, 0);- if (un === __UNS || un.end !== name.length) return __UNS;- name = un.value;- }- // isCSSNameChar, plus ',' for the comma-joined test-id name list. Also rejects- // the *= ^= $= |= ~= operators, whose extra character lands in the name.- if (!/^[\w\u0080-\uFFFF,-]+$/.test(name)) return __UNS;- const rest = inner.slice(eq + 1);- let j = 0;- while (j < rest.length && /\s/.test(rest.charAt(j))) j++;- if (rest.charAt(j) === '/') {- const end = rest.lastIndexOf('/');- if (end <= j) return __UNS;- const flags = rest.slice(end + 1).trim();- if (!/^[dgimsuvy]*$/.test(flags)) return __UNS;- try { return { name: name, regex: new RegExp(rest.slice(j + 1, end), flags), value: null, caseSensitive: true }; }- catch (e) { return __UNS; }- }- const un = __attrUnquote(rest, j);- if (un === __UNS) return __UNS;- let k = un.end, caseSensitive = true;- const flag = rest.charAt(k);- if (flag === 'i' || flag === 'I') { caseSensitive = false; k++; }- else if (flag === 's' || flag === 'S') { caseSensitive = true; k++; }- while (k < rest.length && /\s/.test(rest.charAt(k))) k++;- if (k !== rest.length) return __UNS;- return { name: name, regex: null, value: un.value, caseSensitive: caseSensitive };-}-function __byAttr(body){- // Serves internal:attr (placeholder/alt/title) AND internal:testid -- the- // attribute name comes from the selector. The 'i' flag means case-insensitive- // SUBSTRING, and the RAW attribute value is compared: no trim, no whitespace- // normalization. get_by_test_id always emits 's', so it is strict equality.- const parsed = __parseAttrBody(body);- if (parsed === __UNS) return __UNS;- const names = parsed.name.split(',');- const lower = (parsed.regex || parsed.caseSensitive) ? null : parsed.value.toLowerCase();- const out = [];- try {- for (const el of __allElements()) {- if (!el.getAttribute) continue;- for (const name of names) {- const actual = el.getAttribute(name);- if (actual === null || actual === undefined) continue;- let hit;- if (parsed.regex) { parsed.regex.lastIndex = 0; hit = !!String(actual).match(parsed.regex); }- else if (parsed.caseSensitive) hit = actual === parsed.value;- else hit = String(actual).toLowerCase().indexOf(lower) !== -1;- if (hit) { out.push(el); break; }- }- }- } catch (e) { return __UNS; }- return out;-}-function __parseInternalTextMatcher(arg){- // createTextMatcher(selector, internal=true). Playwright does not trim here.- if (arg.charAt(0) === '/' && arg.lastIndexOf('/') > 0) {- const end = arg.lastIndexOf('/');- try { return { kind: 'regex', regex: new RegExp(arg.slice(1, end), arg.slice(end + 1)) }; }- catch (e) { return __UNS; }- }- if (arg.length > 1 && arg.charAt(0) === '"') {- let body = null, strict = false;- const last = arg.charAt(arg.length - 1);- if (last === '"') { body = arg; strict = true; }- else if (arg.charAt(arg.length - 2) === '"' && (last === 's' || last === 'i')) {- body = arg.slice(0, -1); strict = last === 's';- } else return __UNS;- let value;- try { value = JSON.parse(body); } catch (e) { return __UNS; }- if (typeof value !== 'string') return __UNS;- const norm = __normWS(value);- return strict ? { kind: 'strict', value: norm } : { kind: 'lax', value: norm.toLowerCase() };- }- // A single-quoted body reaches unquote=JSON.parse in Playwright and throws.- if (arg.length > 1 && arg.charAt(0) === "'" && arg.charAt(arg.length - 1) === "'") return __UNS;- return { kind: 'lax', value: __normWS(arg).toLowerCase() };-}-function __matchInternalText(text, matcher){- if (matcher.kind === 'regex') { matcher.regex.lastIndex = 0; return matcher.regex.test(text.full); }- // strict compares the FULL normalized subtree text. The public text= engine- // compares immediate fragments instead (__matchText) -- genuinely different.- if (matcher.kind === 'strict') return text.normalized === matcher.value;- return text.normalized.toLowerCase().indexOf(matcher.value) !== -1;-}-function __internalTextMatches(el, matcher, cache){- if (__skipText(el)) return 'none';- if (!__matchInternalText(__elementText(el, cache), matcher)) return 'none';- // Direct children only, plus the shadow-root probe -- NOT contains() over the- // match set, which would drop an outer element matched only via a grandchild.- for (const child of el.children || []) {- if (__matchInternalText(__elementText(child, cache), matcher)) return 'selfAndChildren';- }- if (el.shadowRoot && __matchInternalText(__elementText(el.shadowRoot, cache), matcher)) return 'selfAndChildren';- return 'self';-}-function __byInternalText(arg){- const matcher = __parseInternalTextMatcher(arg);- if (matcher === __UNS) return __UNS;- const cache = new Map(), out = [];- let lastMiss = null;- for (const el of __allElements()) {- // lastDidNotMatchSelf: in lax mode nothing under a non-matching ancestor matches.- if (matcher.kind === 'lax' && lastMiss && lastMiss.contains(el)) continue;- const m = __internalTextMatches(el, matcher, cache);- if (m === 'none') lastMiss = el;- if (m === 'self') out.push(el);- }- return out;-}-function __idRefRoot(el){- const root = el.getRootNode ? el.getRootNode() : null;- return (root && typeof root.getElementById === 'function') ? root : document;-}-function __labelledByElements(el){- const ref = el.getAttribute ? el.getAttribute('aria-labelledby') : null;- if (ref === null || ref === undefined) return null;- const root = __idRefRoot(el), out = [];- for (const id of ref.split(/\s+/)) {- if (!id) continue;- const target = root.getElementById(id);- if (target && out.indexOf(target) === -1) out.push(target);- }- return out.length ? out : null;-}-function __elementLabels(el, cache){- // First non-empty source wins: aria-labelledby, then aria-label, then .labels.- const refs = __labelledByElements(el);- if (refs) return refs.map(function(x){ return __elementText(x, cache); });- const aria = el.getAttribute ? el.getAttribute('aria-label') : null;- if (aria !== null && aria !== undefined && aria.trim())- return [{ full: aria, normalized: __normWS(aria), immediate: [aria] }];- const tag = el.tagName ? el.tagName.toUpperCase() : '';- const nonHiddenInput = tag === 'INPUT' && String(el.type || '').toLowerCase() !== 'hidden';- if (nonHiddenInput || ['BUTTON','METER','OUTPUT','PROGRESS','SELECT','TEXTAREA'].indexOf(tag) !== -1) {- // Native .labels already resolves both for/id and a wrapping <label>.- const labels = el.labels;- if (labels) return Array.prototype.slice.call(labels).map(function(x){ return __elementText(x, cache); });- }- return [];-}-function __byLabel(arg){- const matcher = __parseInternalTextMatcher(arg);- if (matcher === __UNS) return __UNS;- const cache = new Map(), out = [];- try {- for (const el of __allElements()) {- const labels = __elementLabels(el, cache);- for (const label of labels) {- if (__matchInternalText(label, matcher)) { out.push(el); break; }- }- }- } catch (e) { return __UNS; }- return out;-}-function __allElements(){- if (!document.children && document.querySelectorAll)- return Array.prototype.slice.call(document.querySelectorAll('*'));- const out = [];- function visitRoot(root){- const light = [];- function collectLight(parent){- for (const el of parent.children || []) {- out.push(el);- light.push(el);- collectLight(el);- }- }- collectLight(root);- for (const host of light) {- if (host.shadowRoot) visitRoot(host.shadowRoot);- }- }- visitRoot(document);- return out;-}-function __readQuoted(value){- value = value.trim();- const q = value.charAt(0);- if ((q !== '"' && q !== "'") || value.charAt(value.length - 1) !== q) return __UNS;- try {- return q === '"' ? JSON.parse(value) : value.slice(1, -1).replace(/\\(['"\\])/g, '$1');- } catch (e) { return __UNS; }-}-function __parseCompound(compound){- let css = '', i = 0;- const texts = [];- while (i < compound.length) {- if (compound.slice(i, i + 10) !== ':has-text(') { css += compound.charAt(i++); continue; }- let j = i + 10, quote = '', escaped = false, depth = 1;- for (; j < compound.length; j++) {- const ch = compound.charAt(j);- if (quote) {- if (!escaped && ch === quote) quote = '';- escaped = !escaped && ch === '\\';- if (ch !== '\\') escaped = false;- continue;- }- if (ch === '"' || ch === "'") { quote = ch; continue; }- if (ch === '(') depth++;- else if (ch === ')' && --depth === 0) break;- }- if (depth !== 0) return __UNS;- const text = __readQuoted(compound.slice(i + 10, j));- if (text === __UNS) return __UNS;- texts.push(__normWS(text).toLowerCase());- i = j + 1;- }- css = css.trim() || '*';- if (css.includes(':has-text') || /:(?:text|text-is|text-matches|visible|nth-match)\b/.test(css)) return __UNS;- return { css: css, texts: texts };-}-function __splitSelectorList(css){- const parts = [];- let buf = '', quote = '', escaped = false, brackets = 0, parens = 0;- for (let i = 0; i < css.length; i++) {- const ch = css.charAt(i);- if (escaped) { buf += ch; escaped = false; continue; }- if (ch === '\\') { buf += ch; escaped = true; continue; }- if (quote) {- buf += ch;- if (ch === quote) quote = '';- continue;- }- if (ch === '"' || ch === "'") { quote = ch; buf += ch; continue; }- if (ch === '[') brackets++;- else if (ch === ']') brackets--;- else if (ch === '(') parens++;- else if (ch === ')') parens--;- if (ch === ',' && brackets === 0 && parens === 0) {- if (!buf.trim()) return __UNS;- parts.push(buf.trim()); buf = ''; continue;- }- buf += ch;- }- if (quote || brackets !== 0 || parens !== 0 || !buf.trim()) return __UNS;- parts.push(buf.trim());- return parts;-}-function __parseCss(css){- const compounds = [], combinators = [];- let buf = '', quote = '', escaped = false, brackets = 0, parens = 0;- function pushCompound(){- const value = buf.trim();- if (!value) return false;- const parsed = __parseCompound(value);- if (parsed === __UNS) return __UNS;- compounds.push(parsed); buf = ''; return true;- }- for (let i = 0; i < css.length; i++) {- const ch = css.charAt(i);- if (quote) {- buf += ch;- if (!escaped && ch === quote) quote = '';- escaped = !escaped && ch === '\\';- if (ch !== '\\') escaped = false;- continue;- }- if (ch === '"' || ch === "'") { quote = ch; buf += ch; continue; }- if (ch === '[') { brackets++; buf += ch; continue; }- if (ch === ']') { brackets--; buf += ch; continue; }- if (ch === '(') { parens++; buf += ch; continue; }- if (ch === ')') { parens--; buf += ch; continue; }- if (brackets === 0 && parens === 0 && (ch === '>' || ch === '+' || ch === '~')) {- const pushed = pushCompound();- if (pushed === __UNS || !pushed) return __UNS;- combinators.push(ch);- while (i + 1 < css.length && /\s/.test(css.charAt(i + 1))) i++;- continue;- }- if (brackets === 0 && parens === 0 && /\s/.test(ch)) {- let j = i;- while (j + 1 < css.length && /\s/.test(css.charAt(j + 1))) j++;- const next = css.charAt(j + 1);- if (buf.trim() && next !== '>' && next !== '+' && next !== '~') {- const pushed = pushCompound();- if (pushed === __UNS) return __UNS;- combinators.push(' ');- }- i = j;- continue;- }- buf += ch;- }- const pushed = pushCompound();- if (pushed === __UNS) return __UNS;- if (!compounds.length || combinators.length !== compounds.length - 1) return __UNS;- return { compounds: compounds, combinators: combinators };-}-function __composedParent(el){- if (el.parentElement) return el.parentElement;- const root = el.getRootNode ? el.getRootNode() : null;- return root && root.host ? root.host : null;-}-function __matchesCompound(el, compound, cache){- try { if (typeof el.matches === 'function' && !el.matches(compound.css)) return false; }- catch (e) { return false; }- if (!compound.texts.length) return true;- const text = __elementText(el, cache).normalized.toLowerCase();- return compound.texts.every(x => text.includes(x));-}-function __matchesCss(el, parsed, cache){- let idx = parsed.compounds.length - 1, current = el;- if (!__matchesCompound(current, parsed.compounds[idx], cache)) return false;- while (idx > 0) {- const comb = parsed.combinators[idx - 1];- idx--;- if (comb === '>') {- current = __composedParent(current);- if (!current || !__matchesCompound(current, parsed.compounds[idx], cache)) return false;- } else if (comb === ' ') {- let parent = __composedParent(current), found = null;- while (parent) {- if (__matchesCompound(parent, parsed.compounds[idx], cache)) { found = parent; break; }- parent = __composedParent(parent);- }- if (!found) return false;- current = found;- } else {- let sibling = current.previousElementSibling;- if (comb === '+') {- if (!sibling || !__matchesCompound(sibling, parsed.compounds[idx], cache)) return false;- current = sibling;- } else {- let found = null;- while (sibling) {- if (__matchesCompound(sibling, parsed.compounds[idx], cache)) { found = sibling; break; }- sibling = sibling.previousElementSibling;- }- if (!found) return false;- current = found;- }- }- }- return true;-}-function __byCss(css){- if (css.includes(':scope')) return __UNS;- const branches = __splitSelectorList(css);- if (branches === __UNS) return __UNS;- const parsed = branches.map(__parseCss);- if (parsed.some(x => x === __UNS)) return __UNS;- const cache = new Map();- return __allElements().filter(- el => parsed.some(branch => __matchesCss(el, branch, cache))- );-}-function __deepElementFromPoint(x, y){- let target = document.elementFromPoint(x, y);- while (target && target.shadowRoot &&- typeof target.shadowRoot.elementFromPoint === 'function') {- const inner = target.shadowRoot.elementFromPoint(x, y);- if (!inner || inner === target) break;- target = inner;- }- return target;-}-function __deepActiveElement(){- let active = document.activeElement;- while (active && active.shadowRoot && active.shadowRoot.activeElement) {- active = active.shadowRoot.activeElement;- }- return active;-}-function __resolve(sel){- sel = sel.trim();- // Trailing ">> nth=N" (.first => nth=0, .last => nth=-1, .nth(k) => nth=k).- let nth = 0, hasNth = false;- const m = sel.match(/^([\s\S]*?)\s*>>\s*nth=(-?\d+)\s*$/);- if (m) { sel = m[1].trim(); nth = parseInt(m[2], 10); hasNth = true; }- if (sel.indexOf('>>') !== -1) return __UNS; // chaining we don't reimplement- let list;- // get_by_* engines we reimplement. Anything else under internal: (role, has,- // has-text, and, or, chain, control, describe) stays unsupported.- if (sel.indexOf('internal:testid=') === 0) { list = __byAttr(sel.slice(16)); }- else if (sel.indexOf('internal:attr=') === 0) { list = __byAttr(sel.slice(14)); }- else if (sel.indexOf('internal:text=') === 0) { list = __byInternalText(sel.slice(14)); }- else if (sel.indexOf('internal:label=') === 0) { list = __byLabel(sel.slice(15)); }- else if (sel.indexOf('internal:') !== -1) return __UNS;- else if (sel.indexOf('xpath=') === 0) { list = __byXPath(sel.slice(6)); }- else if (sel.indexOf('//') === 0 || sel.indexOf('(//') === 0 || sel.indexOf('..') === 0) { list = __byXPath(sel); }- else if (sel.indexOf('text=') === 0) { list = __byText(sel.slice(5)); }- else {- const css = (sel.indexOf('css=') === 0) ? sel.slice(4) : sel;- list = __byCss(css);- }- if (list === __UNS) return __UNS;- if (!list || !list.length) return null;- let idx = hasNth ? (nth < 0 ? list.length + nth : nth) : 0;- if (idx < 0 || idx >= list.length) return null;- return list[idx];-}-"""--# ----------------------------------------------------------------------------# JS: per-operation reads (versioned payload; DOM semantics evolve below)-# -----------------------------------------------------------------------------_SNAPSHOT_OP = r"""-const __el = __resolve(__SEL);-if (__el === 'UNSUPPORTED') return { v: __V, r: 'unsupported' };-if (!__el) return { v: __V, r: 'not_found' };-const __box = __visBox(__el);-const __hasBox = __box !== null;-const __tag = __el.tagName.toLowerCase();-const __enabled = __isEnabled(__el);-const __editable = __isEditable(__el, __enabled);-return {- v: __V,- r: 'ok',- targetId: __targetId(__el),- gen: __gen(),- attached: __el.isConnected === true,- visible: __isVisible(__el),- enabled: __enabled,- editable: __editable,- isInput: __tag === 'input' || __tag === 'textarea' || __el.isContentEditable === true,- focused: __deepActiveElement() === __el,- checked: typeof __el.checked === 'boolean' ? __el.checked : null,- box: __box-};-"""--_VIEWPORT_JS = "(() => ({ width: window.innerWidth, height: window.innerHeight }))()"---def _wrap(selector: str, op: str) -> str:- """Assemble a full isolated-world expression: resolver + one op."""- return (- "(() => {\n"- "const __SEL = " + json.dumps(selector) + ";\n"- + _RESOLVER_BODY + "\n" + op + "\n})()"- )---def build_snapshot_js(selector: str) -> str:- """JS resolving one element into the versioned isolated-world payload."""- return _wrap(selector, _SNAPSHOT_OP)---def build_box_js(selector: str) -> str:- """JS reading the element's bounding box (getBoundingClientRect, viewport-space)."""- op = _SNAPSHOT_OP.replace(- "return {\n v: __V,\n r: 'ok',",- "return {\n v: __V,\n r: __hasBox ? 'ok' : 'not_found',",- )- return _wrap(selector, op)---def build_actionable_js(selector: str) -> str:- """JS reading visible/enabled/editable for the element."""- return build_snapshot_js(selector)---def build_validate_js(- selector: str, target_id: int, gen: int, x: float, y: float-) -> str:- """Revalidate the same isolated-world element identity at a click point.-- ``gen`` pins the isolated world the ``target_id`` was minted in. The world is- recreated on navigation and its id counter restarts at 1, so without this a- *different* element could answer to the same id and pass the identity check.- """- op = (- "const __el = __resolve(__SEL);\n"- "if (__el === 'UNSUPPORTED') return { v: __V, r: 'unsupported' };\n"- "if (!__el) return { v: __V, r: 'not_found' };\n"- "const __g = __gen();\n"- "const __id = __targetId(__el);\n"- "if (__g !== " + repr(int(gen)) + ") return { v: __V, r: 'stale', targetId: __id, gen: __g };\n"- "if (__id !== " + repr(int(target_id)) + ") return { v: __V, r: 'stale', targetId: __id, gen: __g };\n"- "if (__el.isConnected !== true) return { v: __V, r: 'stale', targetId: __id, gen: __g };\n"- "const __t = __deepElementFromPoint(" + repr(float(x)) + ", " + repr(float(y)) + ");\n"- "let __n = __t;\n"- "while (__n) { if (__n === __el) return { v: __V, r: 'ok', targetId: __id, gen: __g, hit: true }; __n = __composedParent(__n); }\n"- "if (__t && __el.contains(__t)) return { v: __V, r: 'ok', targetId: __id, gen: __g, hit: true };\n"- "return { v: __V, r: 'ok', targetId: __id, gen: __g, hit: false, covering: __t ? (__t.tagName || 'unknown') : 'none' };\n"- )- return _wrap(selector, op)---def build_pointer_js(selector: str, x: float, y: float) -> str:- """JS hit-testing elementFromPoint(x, y) against the resolved element.-- ``x``/``y`` are viewport coordinates (same space as getBoundingClientRect and- the CDP mouse), so no iframe offset is needed — the isolated world runs in the- main frame's document.- """- op = (- "const __el = __resolve(__SEL);\n"- "if (__el === 'UNSUPPORTED') return { v: __V, r: 'unsupported' };\n"- "if (!__el) return { v: __V, r: 'not_found' };\n"- "const __id = __targetId(__el);\n"- "const __t = __deepElementFromPoint(" + repr(float(x)) + ", " + repr(float(y)) + ");\n"- "if (!__t) return { v: __V, r: 'ok', targetId: __id, gen: __gen(), hit: false, covering: 'none' };\n"- "let __n = __t;\n"- "while (__n) { if (__n === __el) return { v: __V, r: 'ok', targetId: __id, gen: __gen(), hit: true }; __n = __composedParent(__n); }\n"- "if (__el.contains(__t)) return { v: __V, r: 'ok', targetId: __id, gen: __gen(), hit: true };\n"- "return { v: __V, r: 'ok', targetId: __id, gen: __gen(), hit: false, covering: __t.tagName || 'unknown' };\n"- )- return _wrap(selector, op)---def parse_result(raw: Any) -> Tuple[str, Optional[dict]]:- """Validate and normalize one versioned isolated-world payload."""- if not isinstance(raw, dict) or raw.get("v") != PROTOCOL_VERSION:- return (EVALUATION_FAILED, None)- r = raw.get("r")- if r == OK:- if not isinstance(raw.get("targetId"), int) or not isinstance(raw.get("gen"), int):- return (EVALUATION_FAILED, None)- return (OK, raw)- if r == NOT_FOUND:- return (NOT_FOUND, None)- if r == STALE:- if not isinstance(raw.get("targetId"), int) or not isinstance(raw.get("gen"), int):- return (EVALUATION_FAILED, None)- return (STALE, raw)- if r == UNSUPPORTED:- return (UNSUPPORTED, None)- return (EVALUATION_FAILED, None)---def eval_parsed(world: Any, expression: str) -> Tuple[str, Optional[dict]]:- """Evaluate and validate a payload; evaluation errors fail explicitly."""- try:- return parse_result(world.evaluate(expression))- except Exception:- return (EVALUATION_FAILED, None)---async def async_eval_parsed(world: Any, expression: str) -> Tuple[str, Optional[dict]]:- """Async variant of :func:`eval_parsed`."""- try:- return parse_result(await world.evaluate(expression))- except Exception:- return (EVALUATION_FAILED, None)diff --git a/cloakbrowser/human/world.py b/cloakbrowser/human/world.pynew file mode 100644index 0000000..978d06c--- /dev/null+++ b/cloakbrowser/human/world.py@@ -0,0 +1,631 @@+"""CDP isolated worlds for every frame of a page (main, same-process, OOPIF).++Each frame gets one isolated world per document, created through+``Page.createIsolatedWorld`` on the CDP session that owns the frame. Into+that world we install Playwright's InjectedScript (see ``injected.py``) and a+small helper object:++* frame <-> CDP frame id mapping uses ``Page.getFrameTree`` only;+* iframe owner elements are reached via ``DOM.getFrameOwner`` ++ ``DOM.resolveNode`` straight into the parent frame's isolated world;+* elements are kept in a world-local registry and addressed by integer ids.++Everything is async and works on Playwright *impl* objects; the sync API calls+into it through ``SyncBase._sync``.+"""++from __future__ import annotations++import asyncio+import json+from typing import Any, Dict, List, Optional, Tuple++from playwright._impl._errors import Error++from .injected import GLOBAL, build_install_js, find_injected_literal++HELPERS = "__cloakH"++_decoded_source: Optional[str] = None+++class StealthWorldError(Error):+ """An isolated-world evaluation failed (never falls back to the page)."""+++# Helper library evaluated after the InjectedScript in every world.+_HELPERS_JS = r"""(() => {+if (globalThis.__cloakH) return true;+const I = globalThis.__cloakInjected;+const els = new Map(); let seq = 0;+const put = (e) => { const id = ++seq; els.set(id, e); return id; };+const get = (id) => { const e = els.get(id); if (!e) throw new Error('cloak:stale-element'); return e; };+const textValue = (t) => t.isContentEditable ? t.textContent : ('value' in t ? String(t.value) : null);+// display:contents elements have no box: use the union of what they render.+const contentsBox = (root) => {+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;+ const add = (r) => { if (!r.width && !r.height) return;+ x0 = Math.min(x0, r.left); y0 = Math.min(y0, r.top); x1 = Math.max(x1, r.right); y1 = Math.max(y1, r.bottom); };+ const walk = (n) => {+ for (const c of n.childNodes) {+ if (c.nodeType === 3) {+ if (!c.textContent.trim()) continue;+ const p = c.parentElement;+ if (p && getComputedStyle(p).visibility !== 'visible') continue;+ const rg = document.createRange(); rg.selectNodeContents(c);+ for (const r of rg.getClientRects()) add(r);+ } else if (c.nodeType === 1) {+ const s = getComputedStyle(c);+ if (s.display === 'contents') { walk(c); continue; }+ if (s.visibility !== 'visible' || s.display === 'none') continue;+ add(c.getBoundingClientRect());+ }+ }+ };+ walk(root);+ return x0 === Infinity ? null : { left: x0, top: y0, width: x1 - x0, height: y1 - y0 };+};+const parentOrHost = (n) => n.parentElement || (n.parentNode && n.parentNode.host) || null;+const H = {+ el: (id) => get(id),+ adopt() { return put(this); },+ matchRect(x, y, w, h) {+ // An ElementHandle carries no identity this context can read, but+ // Playwright reports its border box. Find the element with exactly that box.+ const out = [];+ const visit = (root) => {+ for (const e of root.querySelectorAll('*')) {+ if (e.shadowRoot) visit(e.shadowRoot);+ const b = e.getBoundingClientRect();+ if (Math.abs(b.left - x) < 0.6 && Math.abs(b.top - y) < 0.6 &&+ Math.abs(b.width - w) < 0.6 && Math.abs(b.height - h) < 0.6) out.push(e);+ }+ };+ visit(document);+ if (out.length < 2) return out.length ? { count: 1, id: put(out[0]) } : { count: 0 };+ // A wrapper and its same-size descendants form one nested chain: a click+ // lands the same on any of them. Take the element a real click would focus+ // (the deepest focusable one), else the outermost. Unrelated elements that+ // share the box stay ambiguous and the caller raises.+ const depth = (e) => { let d = 0; for (let n = e; n; n = parentOrHost(n)) d++; return d; };+ const within = (a, e) => { for (let n = e; n; n = parentOrHost(n)) if (n === a) return true; return false; };+ const chain = out.map((e) => [depth(e), e]).sort((a, b) => a[0] - b[0]).map((p) => p[1]);+ for (let i = 1; i < chain.length; i++) if (!within(chain[i - 1], chain[i])) return { count: out.length };+ const focusable = chain.filter((e) => !e.disabled && e.matches('a[href], area[href], button, input:not([type="hidden"]), '+ + 'select, textarea, iframe, summary, [tabindex], [contenteditable]:not([contenteditable="false"])'));+ return { count: 1, id: put(focusable.length ? focusable[focusable.length - 1] : chain[0]) };+ },+ release(ids) { for (const id of ids) els.delete(id); },+ resolve(selector, strict, rootId) {+ const root = rootId ? get(rootId) : document;+ let parsed, all;+ try { parsed = I.parseSelector(selector); all = I.querySelectorAll(parsed, root); }+ catch (e) { return { status: 'error', message: e.message }; }+ if (!all.length) return { status: 'none' };+ if (strict && all.length > 1)+ return { status: 'strict', message: I.strictModeViolationError(parsed, all).message };+ return { status: 'ok', id: put(all[0]), count: all.length };+ },+ fromPath(path) {+ let cur = document;+ for (const step of path) {+ if (step === 'S') { cur = cur.shadowRoot; if (!cur) return { status: 'closed-shadow' }; continue; }+ cur = cur.childNodes[step];+ if (!cur) return { status: 'none' };+ }+ if (cur.nodeType !== 1) return { status: 'none' };+ return { status: 'ok', id: put(cur) };+ },+ retarget(id, behavior) { const t = I.retarget(get(id), behavior); return t ? put(t) : 0; },+ info(id) {+ const e = get(id);+ const t = I.retarget(e, 'follow-label') || e;+ const root = t.getRootNode();+ return {+ connected: e.isConnected,+ tag: t.nodeName.toLowerCase(),+ type: t.nodeName === 'INPUT' ? String(t.type).toLowerCase() : null,+ editable: !!t.isContentEditable,+ focused: !!root && root.activeElement === t,+ value: textValue(t),+ preview: I.previewNode(e),+ };+ },+ connected(id) { return get(id).isConnected; },+ value(id) { const e = get(id); return textValue(I.retarget(e, 'follow-label') || e); },+ activeValue() {+ const a = document.activeElement;+ if (!a || a === document.body) return { tag: null };+ return { tag: a.nodeName.toLowerCase(), type: a.nodeName === 'INPUT' ? String(a.type).toLowerCase() : null,+ editable: !!a.isContentEditable, value: textValue(a) };+ },+ async states(id, states) {+ const e = get(id);+ try {+ if (I.checkElementStates) {+ const r = await I.checkElementStates(e, states);+ if (r === undefined) return null;+ if (r === 'error:notconnected') return { missing: 'attached' };+ return { missing: r.missingState };+ }+ for (const s of states) {+ if (s === 'stable') continue;+ const r = I.elementState(e, s);+ if (r === 'error:notconnected' || r.received === 'error:notconnected') return { missing: 'attached' };+ if (!(r.matches !== undefined ? r.matches : r)) return { missing: s };+ }+ return null;+ } catch (err) { return { error: err.message }; }+ },+ checked(id) {+ try {+ const e = get(id), r = I.elementState(e, 'checked');+ if (typeof r === 'object') return { checked: r.received === 'checked', radio: !!r.isRadio };+ // Playwright < 1.50 returns a boolean here.+ const t = I.retarget(e, 'follow-label');+ return { checked: r === true, radio: !!t && t.nodeName === 'INPUT' && t.type === 'radio' };+ }+ catch (err) { return { error: err.message }; }+ },+ geometry(id) {+ const e = get(id);+ if (!e.isConnected) return null;+ let b = e.getBoundingClientRect();+ const st = getComputedStyle(e);+ if (st.display === 'contents') b = contentsBox(e) || b;+ return { x: b.left, y: b.top, width: b.width, height: b.height,+ bl: parseFloat(st.borderLeftWidth) || 0, bt: parseFloat(st.borderTopWidth) || 0 };+ },+ scroller(id) {+ const e = get(id);+ const b = e.getBoundingClientRect();+ const top = document.scrollingElement || document.documentElement;+ for (let p = parentOrHost(e); p && p !== top && p !== document.body; p = parentOrHost(p)) {+ const s = getComputedStyle(p);+ const sy = /(auto|scroll|overlay)/.test(s.overflowY) && p.scrollHeight > p.clientHeight;+ const sx = /(auto|scroll|overlay)/.test(s.overflowX) && p.scrollWidth > p.clientWidth;+ if (!sy && !sx) continue;+ const r = p.getBoundingClientRect();+ const x = r.left + p.clientLeft, y = r.top + p.clientTop, w = p.clientWidth, h = p.clientHeight;+ if ((sy && (b.top < y || b.bottom > y + h)) || (sx && (b.left < x || b.right > x + w)))+ return { x, y, width: w, height: h };+ }+ return null;+ },+ doc() {+ const e = document.scrollingElement || document.documentElement;+ const rangeX = Math.max(0, e.scrollWidth - e.clientWidth);+ const rtl = getComputedStyle(document.body || e).direction === 'rtl';+ return { y: scrollY, maxY: Math.max(0, e.scrollHeight - e.clientHeight), x: scrollX,+ minX: rtl ? -rangeX : 0, maxX: rtl ? 0 : rangeX, width: innerWidth, height: innerHeight };+ },+ hit(id, x, y) {+ const r = I.expectHitTarget({ x, y }, get(id));+ return r === 'done' ? null : r.hitTargetDescription;+ },+ fill(id, value) {+ try { return { result: I.fill(get(id), value) }; } catch (err) { return { error: err.message }; }+ },+ select(id, options, elementIds) {+ const opts = options.concat(elementIds.map(get));+ try {+ const r = I.selectOptions(get(id), opts);+ return Array.isArray(r) ? { values: r } : { error: String(r) };+ } catch (err) { return { error: err.message }; }+ },+ focus(id) { const e = I.retarget(get(id), 'follow-label') || get(id); I.focusNode(e, false); return true; },+ caretAtEnd(id) {+ const t = I.retarget(get(id), 'follow-label') || get(id);+ if ('selectionStart' in t && t.selectionStart !== null) return t.selectionStart === String(t.value).length;+ return false;+ },+ platform() { return navigator.platform || ''; },+ rangeInfo(id) {+ const e = I.retarget(get(id), 'follow-label') || get(id);+ const n = (v, d) => { const x = parseFloat(v); return Number.isFinite(x) ? x : d; };+ const min = n(e.min, 0), max = Math.max(n(e.max, 100), n(e.min, 0));+ const step = e.step === 'any' ? 0 : n(e.step, 1);+ const st = getComputedStyle(e);+ const vertical = st.writingMode.startsWith('vertical') || st.appearance === 'slider-vertical';+ return { min, max, step, value: n(e.value, min), vertical, rtl: st.direction === 'rtl' };+ },+ // The options a select_option() call targets, without changing anything.+ selectPlan(id, options, elementIds) {+ const sel = I.retarget(get(id), 'follow-label') || get(id);+ if (sel.nodeName !== 'SELECT') return { error: 'Element is not a <select> element' };+ const opts = [...sel.options];+ const wanted = options.concat(elementIds.map(get));+ const norm = (s) => s.replace(/\s+/g, ' ').trim();+ const match = (o, i, w) => {+ if (w instanceof Node) return o === w;+ const lbl = (l) => l === o.label || norm(l) === norm(o.label);+ let ok = true;+ if (w.valueOrLabel !== undefined) ok = ok && (w.valueOrLabel === o.value || lbl(w.valueOrLabel));+ if (w.value !== undefined) ok = ok && w.value === o.value;+ if (w.label !== undefined) ok = ok && lbl(w.label);+ if (w.index !== undefined) ok = ok && w.index === i;+ return ok;+ };+ const enabled = (o) => !o.disabled && !(o.parentElement && o.parentElement.nodeName === 'OPTGROUP' && o.parentElement.disabled);+ let remaining = wanted.slice(); const targets = [];+ for (let i = 0; i < opts.length && remaining.length; i++) {+ if (!remaining.some(w => match(opts[i], i, w))) continue;+ if (!enabled(opts[i])) return { retry: 'option being selected is not enabled' };+ targets.push(i);+ remaining = sel.multiple ? remaining.filter(w => !match(opts[i], i, w)) : [];+ }+ if (remaining.length) return { retry: 'did not find some options' };+ return { targets, multiple: sel.multiple, listbox: sel.multiple || sel.size > 1,+ navigable: opts.map(o => enabled(o) && !o.hidden && getComputedStyle(o).display !== 'none'),+ values: targets.map(i => opts[i].value), labels: targets.map(i => norm(opts[i].label)) };+ },+ optionId(id, index) { const sel = I.retarget(get(id), 'follow-label') || get(id); return put(sel.options[index]); },+ selectState(id) {+ const sel = I.retarget(get(id), 'follow-label') || get(id);+ return { current: sel.selectedIndex, selected: [...sel.options].map((o, i) => o.selected ? i : -1).filter(i => i >= 0),+ values: [...sel.selectedOptions].map(o => o.value) };+ },+ ownerContent() {+ // Runs with this = the <iframe> owner element: viewport-relative content box.+ const r = this.getBoundingClientRect(); const s = getComputedStyle(this);+ const bl = parseFloat(s.borderLeftWidth) || 0, bt = parseFloat(s.borderTopWidth) || 0;+ const pl = parseFloat(s.paddingLeft) || 0, pt = parseFloat(s.paddingTop) || 0;+ const pr = parseFloat(s.paddingRight) || 0, pb = parseFloat(s.paddingBottom) || 0;+ return { x: r.left + bl + pl, y: r.top + bt + pt,+ width: Math.max(0, this.clientWidth - pl - pr), height: Math.max(0, this.clientHeight - pt - pb) };+ },+};+Object.defineProperty(globalThis, '__cloakH', { value: H });+return true;+})()"""+++def _stale(exc: BaseException) -> bool:+ msg = str(exc)+ return any(s in msg for s in (+ "Cannot find context", "Execution context was destroyed", "Inspected target navigated",+ "cloak:stale-world", "Cannot find default execution context",+ ))+++class _FrameRec:+ __slots__ = ("session", "cdp_id", "ctx")++ def __init__(self, session: Any, cdp_id: str) -> None:+ self.session = session+ self.cdp_id = cdp_id+ self.ctx: Optional[int] = None+++class Worlds:+ """Isolated worlds for all frames of one Playwright (impl) page."""++ def __init__(self, page: Any) -> None:+ self.page = page+ self._session: Any = None+ self._frames: Dict[Any, _FrameRec] = {}+ self._lock: Optional[asyncio.Lock] = None+ try:+ page.on("framenavigated", self.invalidate)+ page.on("framedetached", self.invalidate)+ except Exception: # pragma: no cover - emitter missing in mocks+ pass++ # -- sessions / frame mapping -------------------------------------------++ async def session(self) -> Any:+ if self._session is None:+ self._session = await self.page.context.new_cdp_session(self.page)+ return self._session++ def invalidate(self, frame: Any = None) -> None:+ """Forget worlds of ``frame`` and its descendants (all when None)."""+ if frame is None:+ self._frames.clear()+ return+ doomed = [f for f in self._frames if f is frame or _is_descendant(f, frame)]+ for f in doomed:+ self._frames.pop(f, None)++ async def _locate(self, frame: Any) -> _FrameRec:+ rec = self._frames.get(frame)+ if rec is not None:+ return rec+ if frame.is_detached():+ raise Error("Frame was detached")+ parent = frame.parent_frame+ if parent is None:+ session = await self.session()+ tree = await session.send("Page.getFrameTree")+ rec = _FrameRec(session, tree["frameTree"]["frame"]["id"])+ else:+ rec = await self._locate_child(frame, parent)+ self._frames[frame] = rec+ return rec++ async def _locate_child(self, frame: Any, parent: Any) -> _FrameRec:+ try: # out-of-process iframe: it has its own target/session+ own = await self.page.context.new_cdp_session(frame)+ except Error:+ own = None+ if own is not None:+ tree = await own.send("Page.getFrameTree")+ return _FrameRec(own, tree["frameTree"]["frame"]["id"])+ prec = await self._locate(parent)+ tree = await prec.session.send("Page.getFrameTree")+ node = _find_node(tree["frameTree"], prec.cdp_id)+ kids = [k["frame"] for k in (node or {}).get("childFrames", [])]+ cdp_id = _match_child(frame, parent, kids)+ if cdp_id is None:+ raise Error("cloakbrowser humanize: could not map the frame to a CDP frame")+ return _FrameRec(prec.session, cdp_id)++ async def cdp_frame_id(self, frame: Any) -> str:+ return (await self._locate(frame)).cdp_id++ async def frame_for_cdp_id(self, parent: Any, cdp_id: str) -> Optional[Any]:+ for child in parent.child_frames:+ try:+ if (await self._locate(child)).cdp_id == cdp_id:+ return child+ except Error:+ continue+ return None++ # -- world lifecycle ----------------------------------------------------++ async def _ready(self, frame: Any) -> _FrameRec:+ rec = await self._locate(frame)+ if rec.ctx is not None:+ return rec+ if self._lock is None:+ self._lock = asyncio.Lock()+ async with self._lock:+ if rec.ctx is not None:+ return rec+ res = await rec.session.send("Page.createIsolatedWorld", {+ "frameId": rec.cdp_id, "worldName": "", "grantUniveralAccess": True,+ })+ ctx = res["executionContextId"]+ await self._install(rec.session, ctx)+ rec.ctx = ctx+ return rec++ async def _install(self, session: Any, ctx: int) -> None:+ global _decoded_source+ if _decoded_source is None:+ _decoded_source = await self._raw_eval(session, ctx, find_injected_literal())+ await self._raw_eval(session, ctx, build_install_js(_decoded_source))+ await self._raw_eval(session, ctx, _HELPERS_JS)++ @staticmethod+ async def _raw_eval(session: Any, ctx: int, expression: str, by_value: bool = True,+ await_promise: bool = True) -> Any:+ res = await session.send("Runtime.evaluate", {+ "expression": expression, "contextId": ctx,+ "returnByValue": by_value, "awaitPromise": await_promise,+ })+ if "exceptionDetails" in res:+ det = res["exceptionDetails"]+ desc = (det.get("exception") or {}).get("description") or det.get("text", "")+ if "cloak:stale-element" in desc:+ raise StaleElement()+ raise StealthWorldError(f"cloakbrowser humanize: isolated-world script failed: {desc.splitlines()[0]}")+ return res["result"].get("value") if by_value else res["result"]++ # -- evaluation -----------------------------------------------------------++ async def evaluate(self, frame: Any, expression: str, by_value: bool = True) -> Any:+ """Evaluate in ``frame``'s isolated world; recreate the world once if stale."""+ for attempt in (0, 1):+ rec = await self._ready(frame)+ try:+ return await self._raw_eval(rec.session, rec.ctx, expression, by_value)+ except StaleElement:+ raise+ except Error as exc:+ if attempt == 0 and _stale(exc):+ rec.ctx = None+ continue+ raise+ raise StealthWorldError("cloakbrowser humanize: isolated world unavailable") # pragma: no cover++ async def call(self, frame: Any, method: str, *args: Any) -> Any:+ return await self.evaluate(frame, f"{HELPERS}.{method}({', '.join(json.dumps(a) for a in args)})")++ async def element_object_id(self, frame: Any, element_id: int) -> Tuple[Any, str]:+ rec = await self._ready(frame)+ obj = await self._raw_eval(rec.session, rec.ctx, f"{HELPERS}.el({int(element_id)})", by_value=False)+ return rec.session, obj["objectId"]++ async def adopt(self, frame: Any, backend_node_id: int) -> int:+ """Register the DOM node ``backend_node_id`` in ``frame``'s world."""+ rec = await self._ready(frame)+ try:+ obj = (await rec.session.send("DOM.resolveNode", {+ "backendNodeId": backend_node_id, "executionContextId": rec.ctx,+ }))["object"]+ except Error as exc:+ raise StaleElement() from exc+ try:+ res = await rec.session.send("Runtime.callFunctionOn", {+ "objectId": obj["objectId"], "returnByValue": True,+ "functionDeclaration": f"function () {{ return globalThis.{HELPERS}.adopt.call(this); }}",+ })+ finally:+ await _release(rec.session, obj["objectId"])+ if "exceptionDetails" in res:+ raise StaleElement()+ return res["result"]["value"]++ async def editor_fields(self, frame: Any, element_id: int) -> List[Dict[str, Any]]:+ """Segments of a native date/time editor (``<input type=date>`` ...) in+ visual order, with centres relative to the input's border box.++ The segments live in the input's closed user-agent shadow root, which+ neither page scripts nor our isolated world can see. CDP's DOM domain+ can (``pierce``), and reading it runs no script in the page.+ """+ session, object_id = await self.element_object_id(frame, element_id)+ try:+ node = (await session.send("DOM.describeNode", {"objectId": object_id, "depth": -1, "pierce": True}))["node"]+ own = (await session.send("DOM.getBoxModel", {"objectId": object_id}))["model"]["border"]+ finally:+ await _release(session, object_id)+ out: List[Dict[str, Any]] = []++ async def walk(n: Dict[str, Any]) -> None:+ attrs = n.get("attributes") or []+ pseudo = dict(zip(attrs[::2], attrs[1::2])).get("pseudo", "")+ if pseudo.startswith("-webkit-datetime-edit-") and pseudo.endswith("-field") and "wrapper" not in pseudo:+ quad = (await session.send("DOM.getBoxModel", {"backendNodeId": n["backendNodeId"]}))["model"]["border"]+ out.append({"kind": pseudo[len("-webkit-datetime-edit-"):-len("-field")],+ "dx": (quad[0] + quad[2]) / 2 - own[0], "dy": (quad[1] + quad[5]) / 2 - own[1]})+ for c in (n.get("children") or []) + (n.get("shadowRoots") or []):+ await walk(c)++ await walk(node)+ out.sort(key=lambda f: (round(f["dy"] / 4), f["dx"]))+ return out++ async def owner_element(self, frame: Any) -> int:+ """Register ``frame``'s <iframe> element in the parent frame's world."""+ rec = await self._locate(frame)+ prec = await self._ready(frame.parent_frame)+ owner = await prec.session.send("DOM.getFrameOwner", {"frameId": rec.cdp_id})+ return await self.adopt(frame.parent_frame, owner["backendNodeId"])++ async def content_frame(self, frame: Any, element_id: int) -> Optional[Any]:+ """Child frame owned by the <iframe> element ``element_id`` in ``frame``."""+ session, object_id = await self.element_object_id(frame, element_id)+ try:+ node = (await session.send("DOM.describeNode", {"objectId": object_id}))["node"]+ finally:+ await _release(session, object_id)+ cdp_id = node.get("frameId")+ if not cdp_id:+ return None+ return await self.frame_for_cdp_id(frame, cdp_id)++ # -- geometry across frames ---------------------------------------------++ async def _owner_call(self, frame: Any, declaration: str, *args: Any) -> Any:+ """Call ``declaration`` with ``this`` = the frame's <iframe> element,+ inside the parent frame's isolated world."""+ parent = frame.parent_frame+ rec = await self._locate(frame)+ prec = await self._ready(parent)+ owner = await prec.session.send("DOM.getFrameOwner", {"frameId": rec.cdp_id})+ obj = (await prec.session.send("DOM.resolveNode", {+ "backendNodeId": owner["backendNodeId"], "executionContextId": prec.ctx,+ }))["object"]+ try:+ res = await prec.session.send("Runtime.callFunctionOn", {+ "objectId": obj["objectId"], "functionDeclaration": declaration,+ "arguments": [{"value": a} for a in args], "returnByValue": True,+ })+ finally:+ await _release(prec.session, obj["objectId"])+ if "exceptionDetails" in res:+ raise StealthWorldError("cloakbrowser humanize: frame owner evaluation failed")+ return res["result"].get("value")++ async def viewport(self) -> Dict[str, float]:+ size = getattr(self.page, "_viewport_size", None)+ if size and size.get("width"):+ return {"width": size["width"], "height": size["height"]}+ doc = await self.call(self.page.main_frame, "doc")+ return {"width": doc["width"], "height": doc["height"]}++ async def frame_geometry(self, frame: Any) -> Tuple[float, float, Dict[str, float]]:+ """``(offset_x, offset_y, clip)``: the frame's origin in viewport+ coordinates and the visible part of it (intersection of all ancestor+ iframe content boxes and the viewport)."""+ parent = frame.parent_frame+ if parent is None:+ vp = await self.viewport()+ return 0.0, 0.0, {"x": 0.0, "y": 0.0, "width": float(vp["width"]), "height": float(vp["height"])}+ px, py, pclip = await self.frame_geometry(parent)+ box = await self._owner_call(frame, f"function () {{ return {HELPERS}.ownerContent.call(this); }}")+ ox, oy = px + box["x"], py + box["y"]+ clip = intersect(pclip, {"x": ox, "y": oy, "width": box["width"], "height": box["height"]})+ return ox, oy, clip++ async def owners_hit(self, frame: Any, vx: float, vy: float) -> Optional[str]:+ """Check that the viewport point hits each ancestor <iframe> owner."""+ child = frame+ while child.parent_frame is not None:+ px, py, _ = await self.frame_geometry(child.parent_frame)+ desc = await self._owner_call(+ child,+ "function (x, y) { const r = globalThis.%s.expectHitTarget({ x, y }, this);"+ " return r === 'done' ? null : r.hitTargetDescription; }" % GLOBAL,+ vx - px, vy - py,+ )+ if desc:+ return desc+ child = child.parent_frame+ return None+++class StaleElement(Error):+ def __init__(self) -> None:+ super().__init__("element is not attached to the DOM")+++async def _release(session: Any, object_id: str) -> None:+ try:+ await session.send("Runtime.releaseObject", {"objectId": object_id})+ except Error:+ pass+++def intersect(a: Dict[str, float], b: Dict[str, float]) -> Dict[str, float]:+ x0, y0 = max(a["x"], b["x"]), max(a["y"], b["y"])+ x1 = min(a["x"] + a["width"], b["x"] + b["width"])+ y1 = min(a["y"] + a["height"], b["y"] + b["height"])+ return {"x": x0, "y": y0, "width": max(0.0, x1 - x0), "height": max(0.0, y1 - y0)}+++def _is_descendant(frame: Any, ancestor: Any) -> bool:+ p = getattr(frame, "parent_frame", None)+ while p is not None:+ if p is ancestor:+ return True+ p = p.parent_frame+ return False+++def _find_node(tree: Dict[str, Any], cdp_id: str) -> Optional[Dict[str, Any]]:+ if tree["frame"]["id"] == cdp_id:+ return tree+ for child in tree.get("childFrames", []):+ found = _find_node(child, cdp_id)+ if found is not None:+ return found+ return None+++def _match_child(frame: Any, parent: Any, kids: List[Dict[str, Any]]) -> Optional[str]:+ """Pick the CDP child frame for a Playwright frame.++ Playwright and CDP list child frames in attach order; frames sharing the+ same (name, url) are matched by their position within that group.+ """+ def key_pw(f: Any) -> Tuple[str, str]:+ return f.name, f.url++ def key_cdp(k: Dict[str, Any]) -> Tuple[str, str]:+ return k.get("name", ""), k.get("url", "") + k.get("urlFragment", "")++ want = key_pw(frame)+ cands = [k for k in kids if key_cdp(k) == want]+ peers = [f for f in parent.child_frames if key_pw(f) == want]+ if cands and frame in peers and len(cands) == len(peers):+ return cands[peers.index(frame)]["id"]+ if len(cands) == 1:+ return cands[0]["id"]+ siblings = list(parent.child_frames)+ if len(kids) == len(siblings) and frame in siblings:+ return kids[siblings.index(frame)]["id"]+ return Nonediff --git a/dotnet/README.md b/dotnet/README.mdindex 56d77a1..7b83f74 100644--- a/dotnet/README.md+++ b/dotnet/README.md@@ -32,9 +32,8 @@ paths match the Python and JavaScript clients exactly.- [Human typing & the CDP stealth path](#human-typing--the-cdp-stealth-path)- [Non-ASCII input](#non-ascii-input)- [Scrolling](#scrolling)- - [Actionability checks](#actionability-checks)- - [Shared timeout budget (#307)](#shared-timeout-budget-307)- - [Focus-aware press / clear](#focus-aware-press--clear)+ - [Actionability, errors and timeouts](#actionability-errors-and-timeouts)+ - [Fields: focus, caret, value inputs](#fields-focus-caret-value-inputs)- [Proxy, GeoIP & WebRTC](#proxy-geoip--webrtc)- [CLI](#cli)- [Environment variables](#environment-variables)@@ -126,16 +125,21 @@ dotnet/│ │ │ ├── HumanConfig.cs # <- human/config.py (HumanConfig + merge)│ │ │ ├── HumanRandom.cs # <- human/config.py (rand/sleep helpers)│ │ │ ├── HumanMouse.cs # <- human/mouse.py (Bezier engine)-│ │ │ ├── HumanKeyboard.cs # <- human/keyboard.py (typing + CDP stealth)-│ │ │ ├── HumanScroll.cs # <- human/scroll.py-│ │ │ ├── Actionability.cs # <- human/actionability.py-│ │ │ ├── IsolatedWorld.cs # <- _AsyncIsolatedWorld-│ │ │ ├── PlaywrightAdapters.cs # IMouse/IKeyboard/ICDPSession -> raw protocols-│ │ │ └── HumanPage.cs # <- patch_page flows (explicit engine)+│ │ │ ├── HumanKeyboard.cs # <- human/keyboard.py (key tables, typo neighbours)+│ │ │ ├── HumanEngine.cs # <- human/engine.py (resolve, wait, scroll, move, hit-test)+│ │ │ ├── HumanEngine.Actions.cs # <- human/engine.py (click/fill/type/check/select/drag/...)+│ │ │ ├── HumanWorld.cs # <- human/world.py (per-frame execution contexts)+│ │ │ ├── WorldHelpers.cs # <- human/world.py (shared helper library)+│ │ │ ├── InjectedSource.cs # <- human/injected.py (selector engine loader)+│ │ │ ├── Fields.cs # <- human/fields.py (fill classification, date parts)+│ │ │ ├── Actionability.cs # error classes + standalone checks (public, on the engine)+│ │ │ ├── HumanScroll.cs # standalone wheel scroll helper (public, kept for compatibility)+│ │ │ ├── IsolatedWorld.cs # single-world CDP evaluator (public, kept for compatibility)+│ │ │ └── HumanPage.cs # explicit API over the engine│ │ └── Wrappers/ # transparent humanize decorators (Humanize=true)│ │ ├── Humanize.cs # wrap entry points + helpers (idempotent)-│ │ ├── HumanCursor.cs # shared per-page cursor / CDP stealth state-│ │ ├── LocatorHumanizer.cs # locator-based humanize engine+│ │ ├── HumanCursor.cs # per-page engine host (cursor, worlds)+│ │ ├── HumanizedFrameLocator.cs # IFrameLocator decorator│ │ ├── HumanizedBrowser.cs # IBrowser decorator│ │ ├── HumanizedBrowserContext.cs # IBrowserContext decorator│ │ ├── HumanizedPage.cs # IPage decorator@@ -194,7 +198,7 @@ await page.GotoAsync("https://example.com/login");await page.FillAsync("#username", "alice"); // per-character human typingawait page.FillAsync("#password", "s3cr3t!"); // (variable delays, thinking pauses, typos+fixes)await page.ClickAsync("button[type=submit]"); // Bezier mouse curve to a realistic aim point-await page.Mouse.WheelAsync(0, 600); // accelerate -> cruise -> decelerate scroll+await page.ClickAsync("#footer-link"); // wheel-scrolls it into view first, like a person```The wrapping is **complete and transitive** - anything you reach through the page@@ -212,23 +216,24 @@ foreach (var frame in page.Frames) { /* wrapped IFrame */ }| Member | `Humanize = false` (default) | `Humanize = true` || --- | --- | --- |-| `IPage` / `ILocator` `ClickAsync`, `DblClickAsync`, `HoverAsync`, `TapAsync` | direct Playwright dispatch | Bezier-curve mouse move to a randomized in-element aim point, then click |-| `IPage` / `ILocator` `FillAsync`, `TypeAsync` / `PressSequentiallyAsync` | instant value set / fast type | per-character typing with variable delays, thinking pauses, occasional typos that self-correct |-| `IPage` / `ILocator` `PressAsync` | direct | human key timing; clicks to focus first only if not already focused |-| `ILocator` `CheckAsync`, `UncheckAsync`, `SetCheckedAsync`, `DragToAsync` | direct | humanized click / curved drag |-| `ILocator` `SelectOptionAsync` (all overloads) | instant native select | curved hover to the `<select>` + pause, then native select |-| `ILocator` `ClearAsync` | instant value reset | focus (humanized click if needed) + select-all + Backspace |-| `IMouse` `MoveAsync`, `ClickAsync`, `DblClickAsync`, `DownAsync`, `UpAsync` | direct | curved, eased motion with overshoot |-| `IMouse` `WheelAsync` | single event | accelerate-cruise-decelerate microsteps |-| `IKeyboard` `TypeAsync`, `PressAsync`, `InsertTextAsync` | direct | human-timed CDP key events |-| `page.Mouse`, `page.Keyboard`, `page.Locator(...)`, `page.GetBy*`, `page.Frames`, `QuerySelectorAsync`, `IBrowser.NewPageAsync/NewContextAsync`, `IBrowserContext.NewPageAsync` | raw Playwright objects | the same call returns a **wrapped** object so humanization stays transitive |+| `ClickAsync`, `DblClickAsync`, `HoverAsync`, `TapAsync` on `IPage` / `IFrame` / `ILocator` / `IElementHandle` | direct Playwright dispatch | wheel-scroll into view, Bezier move to an in-element aim point, hit-test, press; `Button`, `ClickCount`, `Modifiers`, `Position`, `Delay`, `Trial`, `Force` honoured |+| `FillAsync`, `TypeAsync` / `PressSequentiallyAsync`, `ClearAsync` | instant value set / fast type | click into the field, select-all (persona-aware), per-character typing with variable delays, pauses and self-corrected typos; text continues at the end |+| `FillAsync` on date/time/range, `SelectOptionAsync` | programmatic value | operated like a person with trusted events (segments typed, slider clicked + arrow keys, dropdown opened + arrows + Enter); `type=color` throws |+| `PressAsync` | direct | clicks to focus first if needed, human key timing, `Delay` honoured |+| `CheckAsync`, `UncheckAsync`, `SetCheckedAsync`, `DragToAsync` / `DragAndDropAsync`, `FocusAsync`, `ScrollIntoViewIfNeededAsync` | direct | humanized click / curved drag / wheel scroll |+| `IMouse` `MoveAsync`, `ClickAsync`, `DblClickAsync` | direct | curved, eased motion (`Steps` = exact raw steps), real `detail=1,2` sequence |+| `IMouse` `DownAsync`, `UpAsync`, `WheelAsync`; `IKeyboard` `DownAsync`, `UpAsync`, `PressAsync`, `InsertTextAsync` | direct | passed through 1:1 (they already are single human inputs) |+| `IKeyboard` `TypeAsync` | fast type | human typing into the focused element |+| `page.Mouse`, `page.Keyboard`, `Locator(...)`, `GetBy*`, `FrameLocator(...)`, `ContentFrame`, `Frames`, `QuerySelector(All)Async`, `WaitForSelectorAsync`, `ElementHandle(s)Async`, `IBrowser.NewPageAsync/NewContextAsync` | raw Playwright objects | the same call returns a **wrapped** object so humanization stays transitive || every **other** member (navigation, waits, evaluation, screenshots, network, etc.) | - | **delegated verbatim** to Playwright (identical signatures, return types, exceptions, and `CancellationToken` support) |-| escape hatch | n/a | `((HumanizedPage)page).Original` (also `.Inner`) returns the raw, un-wrapped object; `browser.RawBrowser` on the handle |+| escape hatch | n/a | `Humanize.Unwrap(page)` / `((HumanizedPage)page).Original` returns the raw object; `browser.RawBrowser` on the handle |-Per-call overrides are honored - e.g.-`await page.ClickAsync("#x", new() { Force = true })` still works and is-humanized. `ElementHandle` interactions are humanized too, but prefer `ILocator`-(Playwright's recommendation) for the most reliable aiming.+Every locator shape works: CSS, `text=`, `xpath=`, `GetByRole`, `GetBy*`, `>>`+chains, `Filter(...)`, `:visible`, `Nth`, `FrameLocator(...)`. Locators are+**strict** like Playwright: an ambiguous `Locator(".dup").ClickAsync()` throws+`strict mode violation` (use `.First` / `.Nth()`). Element handles are humanized+too; prefer `ILocator` (Playwright's recommendation): a handle is matched by its exact+bounding box, and an action raises when two elements share that box.### Calling the original Playwright methods (escape hatch)@@ -274,7 +279,9 @@ await human.FillAsync("#username", "alice");await human.ClickAsync("button[type=submit]");```-`HumanPage` methods (all take an optional `HumanActionOptions { Timeout, Force }`):+`HumanPage` runs on the same engine as the transparent layer (selectors resolve+in the main frame, non-strict like `page.ClickAsync`). All methods take an optional+`HumanActionOptions { Timeout, Force, Delay, HumanConfig }` (`Timeout = 0` = no limit):| Method | Description || --- | --- |@@ -283,15 +290,15 @@ await human.ClickAsync("button[type=submit]");| `DblClickAsync(selector)` | move + double click || `HoverAsync(selector)` | curved move, no click || `TapAsync(selector)` | same motion as click |-| `TypeAsync(selector, text)` | focus + per-character typing |-| `FillAsync(selector, value)` | click + select-all + clear + type |+| `TypeAsync(selector, text)` | focus + per-character typing at the end of the text |+| `FillAsync(selector, value)` | click + select-all + clear + type (value inputs like a person) || `PressAsync(selector, key)` | focus-aware single key press |-| `PressSequentiallyAsync(selector, text)` | focus + per-character typing |+| `PressSequentiallyAsync(selector, text)` | same as `TypeAsync` || `ClearAsync(selector)` | focus + select-all + Backspace || `CheckAsync` / `UncheckAsync` / `SetCheckedAsync(selector, state)` | humanized toggle via click |-| `SelectOptionAsync(selector, values)` | curved hover + native select |-| `FocusAsync(selector)` | curved move + **programmatic** focus (no click side-effects) |-| `ScrollIntoViewIfNeededAsync(selector)` | humanized accelerate->cruise->decelerate->overshoot scroll |+| `SelectOptionAsync(selector, values)` | dropdown: click + arrow keys + Enter; list box: option clicks |+| `FocusAsync(selector)` | curved move + focus without a click (like Playwright's `FocusAsync`) |+| `ScrollIntoViewIfNeededAsync(selector)` | wheel scroll; returns true when the element moved || `DragAndDropAsync(src, dst)` | curved press-drag-release || `MouseMoveAsync(x, y)` / `MouseClickAsync(x, y)` | low-level curved motion || `KeyboardTypeAsync(text)` | low-level human typing at the focused element |@@ -498,16 +505,15 @@ and wide Y band; buttons get a centered cluster.### Human typing & the CDP stealth path-`HumanKeyboard.HumanTypeAsync` types one character at a time with variable delays-and occasional "thinking" pauses. ASCII alphanumeric characters can trigger a-**fat-finger typo** (a nearby QWERTY key) that is then noticed and corrected with-Backspace.+Typing goes one character at a time with variable delays and occasional+"thinking" pauses. ASCII letters/digits can trigger a **fat-finger typo** (a nearby+QWERTY key, a digit for digits) that is noticed and corrected with Backspace;+uppercase letters and typos are typed with Shift. Typos are skipped in+number/email/password/tel/url fields, and a typo the page rejected (input masks)+is not "corrected" by deleting a real character.-Shift symbols (`@ # ! $ ...`) are the tricky case for stealth. When a **CDP-session** is available, they are dispatched through-`Input.dispatchKeyEvent` - producing `isTrusted = true` events with **no-`evaluate` stack trace** for detectors to find. Without CDP, it falls back to a-(detectable) `page.evaluate` path.+Shift symbols (`@ # ! $ ...`) are dispatched through CDP `Input.dispatchKeyEvent`,+producing `isTrusted = true` events with no script on the page.### Non-ASCII input@@ -523,52 +529,48 @@ mixed string like `"Hi Мир"`:### Scrolling-`HumanScroll` performs an **accelerate -> cruise -> decelerate** wheel sequence in-microsteps, with an optional overshoot-and-settle, landing the element in a-natural viewport band (`ScrollTargetZone`).--### Actionability checks--Before interacting, the humanize layer runs Playwright-style **actionability-checks** (`Actionability.cs`), with a retry/backoff loop `[100, 250, 500, 1000]`-ms:--| Check | Meaning | Error on failure |-| --- | --- | --- |-| `attached` | element exists in the DOM | `ElementNotAttachedError` |-| `visible` | element is visible | `ElementNotVisibleError` |-| `stable` | bounding box stopped moving (post-scroll) | `ElementNotStableError` |-| `enabled` | element is enabled | `ElementNotEnabledError` |-| `editable` | element is editable | `ElementNotEditableError` |-| `pointer_events` | the click point actually hits the element | `ElementNotReceivingEventsError` |--Action presets: `ChecksClick`, `ChecksHover`, `ChecksInput`, `ChecksFocus`,-`ChecksCheck`.--**Fail-open pointer check.** The `pointer_events` probe uses-`document.elementFromPoint`. If it *cannot run* (stale handle, execution context-destroyed - `EvaluateAsync` throws), the check **fails open** and returns-promptly rather than blocking until timeout - failing closed would wrongly block-legitimate clicks. But an explicit `{ hit: false }` (the element is genuinely-*covered*) still raises `ElementNotReceivingEventsError`.--### Shared timeout budget (#307)--All sequential steps of one action share a **single deadline** rather than each-restarting the full timeout. The helper-`Actionability.RemainingMs(deadline)` returns the milliseconds left (clamped at-zero, never negative). Because every step subtracts from the *same* budget, the-total wall-clock time can never multiply across steps - the bug fixed in-upstream issue **#307**.--### Focus-aware press / clear--`PressAsync` and `ClearAsync` first probe focus with-`EvaluateAsync<bool>("el => el === document.activeElement")`. If the element is-**already focused**, they **skip the humanized click** entirely (the cursor does-not move) and go straight to the keystrokes; otherwise they perform a humanized-focus-click first. This avoids pointless mouse motion on an already-focused-field.+Targets are brought on screen with **mouse-wheel bursts** (accelerate -> cruise ->+decelerate, optional overshoot), scrolling the page, scrollable containers and+iframes (also below an iframe's own fold), and settling the element in a natural+band (`ScrollTargetZone`). The cursor first moves into the area being scrolled.++### Actionability, errors and timeouts++Like Playwright, an action waits until its element is attached, visible,+enabled, editable (for input) and stable, then checks that the aim point really+hits it, through every ancestor `<iframe>`. Retries back off 0/20/100/100/500 ms.+There are **no silent fallbacks** to Playwright's own actions:+failures throw `PlaywrightException`, and timeouts throw `System.TimeoutException`+with a call log, e.g. `<div id="over"> intercepts pointer events` or+`element is outside of the viewport`.++All steps of one action share **one deadline** (#307). The timeout is the+option's `Timeout`, else the page/context default (`SetDefaultTimeout`), else+30 s; `Timeout = 0` means no limit. A target removed or replaced while the cursor+travels is never pressed (locators re-resolve).++The checks are also callable on their own, with the pre-engine signatures:+`Actionability.EnsureActionableAsync(page, selector, Actionability.ChecksClick)`,+`EnsureStableAsync`, `CheckPointerEventsAsync(page, selector, x, y)` and the+`…HandleAsync` variants. They run on the same engine (any Playwright selector) and+throw the typed `ElementNotVisibleError`,+`ElementNotEnabledError`, `ElementNotEditableError`, `ElementNotAttachedError`,+`ElementNotStableError` and `ElementNotReceivingEventsError`. `HumanScroll`+(`HumanScrollIntoViewAsync`, `SmoothWheelAsync`) and `IsolatedWorld` stay public as+standalone helpers; humanized actions do not use them.++### Fields: focus, caret, value inputs++There is **no programmatic focus**: a field is focused by scrolling to it and+clicking; one that can never be brought on screen fails with+`element is outside of the viewport`. `TypeAsync` / `PressSequentiallyAsync`+continue at the end of existing text. Select-all and `ControlOrMeta` follow the+browser persona (`--fingerprint-platform=macos` uses Meta), not the host OS.+Date/time inputs are typed segment by segment in the locale's order, sliders are+clicked near the value and nudged with arrow keys, `<select>` is driven with+clicks and arrow keys. `<input type=color>` opens a native dialog that cannot be+driven, so `FillAsync` on it throws; use `Humanize.Unwrap(page).FillAsync` if a+programmatic value is acceptable.---@@ -649,24 +651,24 @@ dotnet run --project examples/CloakBrowser.Examples -- proxy-geoip### Test suite map-All tests are **browser-free**: production wrappers are exercised through-`DispatchProxy`-backed Playwright fakes (`Wrappers/FakeProxy.cs`,-`Fake.Of<T>()`), and `InternalsVisibleTo` lets the tests reach internal types.-A handful of genuinely browser-dependent timing tests are marked-`[Fact(Skip = "requires browser")]` rather than faked.+Unit tests run without a browser (`DispatchProxy`-backed Playwright fakes,+`Wrappers/FakeProxy.cs`). Real-browser tests run when `CLOAKBROWSER_BINARY_PATH`+points at a CloakBrowser binary, against a local test page served by+`HumanEngine/SiteServer.cs` (the same page as the Python and JS tests). Real-browser+classes share one serial xunit collection (`RealBrowser`).| Area | File(s) | What it proves || --- | --- | --- || Version / download | `ConfigTests.cs`, `DownloadConfigTests.cs` | version compare, archive names, checksum parsing, **zip-slip** path guard || Launch args | `BuildArgsTests.cs`, `MiscTests.cs` | stealth args, `build_args` dedup || Proxy | `ProxyResolverTests.cs` | URL resolution / encoding |-| Bezier math | `BezierMathTests.cs` | curve produces many points, ends near target, no big jumps, deviates from a straight line |-| Humanize config | `HumanConfigTests.cs` | presets, snake/Pascal overrides, range coercion, **merge never mutates base**, null/empty/unknown-key handling |-| Transparent layer | `Wrappers/*.cs` | non-intercepted members delegate verbatim; intercepted members humanize; nested objects come back wrapped; exceptions & `CancellationToken`s propagate |-| Non-ASCII keyboard | `Human/NonAsciiKeyboardTests.cs` | Cyrillic/CJK go via `InsertText`; ASCII via key presses; mixed strings route per-character |-| Pointer-events fail-open | `Human/PointerEventsFailOpenTests.cs` | throwing probe returns fast (`< 500ms`); explicit "covered" raises `ElementNotReceivingEventsError` |-| Timeout budget (#307) | `Human/TimeoutBudgetTests.cs` | `RemainingMs` never negative, decreases over time, shared (not multiplied) |-| Focus check | `Wrappers/FocusCheckTests.cs` | focused element -> no humanized click (cursor doesn't move); non-focused -> click happens |+| Bezier math | `BezierMathTests.cs` | curve shape and end point |+| Humanize config | `HumanConfigTests.cs` | presets, snake/Pascal overrides, merge never mutates base |+| Transparent layer | `Wrappers/*.cs` | delegation, re-wrapping of every handle/frame/locator-returning member, exceptions & `CancellationToken`s propagate |+| Engine (real browser) | `HumanEngine/HumanEngineBrowserTests.cs`, `HumanEngine/WorldSmokeTests.cs` | options, strict mode, timeouts, locators, fields, frames, handles, mouse, persona select-all |+| Standalone checks (real browser) | `HumanEngine/ActionabilityApiTests.cs`, `ScrollFallbackTests.cs` | public `Actionability` checks throw the typed errors; `HumanScroll` / `IsolatedWorld` keep working |+| Selector parity (real browser) | `Human/SelectorParityBrowserTests.cs`, `tests/test_resolver_sources_match.py` | actions land on the element Playwright resolves; Python/JS/.NET helper copies stay byte-identical |+| Timeout budget (#307) | `Human/TimeoutBudgetTests.cs` | one shared deadline, `0` = no limit |---@@ -682,9 +684,11 @@ A handful of genuinely browser-dependent timing tests are marked| `Human/HumanConfig.cs` | `cloakbrowser/human/config.py` || `Human/HumanMouse.cs` | `cloakbrowser/human/mouse.py` || `Human/HumanKeyboard.cs` | `cloakbrowser/human/keyboard.py` |-| `Human/HumanScroll.cs` | `cloakbrowser/human/scroll.py` |-| `Human/Actionability.cs` | `cloakbrowser/human/actionability.py` |-| `Human/HumanPage.cs` | `cloakbrowser/human/__init__.py` (`patch_page`) |+| `Human/HumanEngine*.cs` | `cloakbrowser/human/engine.py` |+| `Human/HumanWorld.cs`, `Human/WorldHelpers.cs` | `cloakbrowser/human/world.py` |+| `Human/InjectedSource.cs` | `cloakbrowser/human/injected.py` |+| `Human/Fields.cs` | `cloakbrowser/human/fields.py` |+| `Wrappers/*.cs` | `cloakbrowser/human/patch.py` || `CloakBrowser.Cli/` | `cloakbrowser/__main__.py` |---diff --git a/dotnet/src/CloakBrowser/Human/Actionability.cs b/dotnet/src/CloakBrowser/Human/Actionability.csindex 945cf12..33c6663 100644--- a/dotnet/src/CloakBrowser/Human/Actionability.cs+++ b/dotnet/src/CloakBrowser/Human/Actionability.cs@@ -1,3 +1,4 @@+using System.Linq;using Microsoft.Playwright;namespace CloakBrowser.Human;@@ -72,15 +73,47 @@ public sealed class ElementTargetChangedError : ActionabilityError: base(selector, "target_identity", "selector resolved to a different element before input dispatch") { }}+// Raised by the previous humanize layer; the engine no longer throws them.++/// <summary>Base for isolated-world DOM helper failures.</summary>+public class StealthDomError : Exception+{+ public StealthDomError(string message) : base(message) { }+}++public sealed class UnsupportedHumanizeSelectorError : StealthDomError+{+ public UnsupportedHumanizeSelectorError(string selector)+ : base($"Humanized selector '{selector}' is not supported") { }+}++public sealed class StealthWorldUnavailableError : StealthDomError+{+ public StealthWorldUnavailableError() : base("Humanized DOM read requires an active isolated world") { }+}++public sealed class StealthEvaluationError : StealthDomError+{+ public StealthEvaluationError(string selector)+ : base($"Isolated-world DOM evaluation failed for '{selector}'") { }+}+// ----------------------------------------------------------------------------// Checks+// Checks (public compatibility facade over the humanize engine)// ---------------------------------------------------------------------------/// <summary>-/// Playwright-style actionability checks for the humanize layer.-/// Direct port of Python <c>cloakbrowser/human/actionability.py</c>.-/// Checks: attached, visible, stable, enabled, editable, receives pointer events.-/// Retry loop with backoff matching Playwright internals: [100, 250, 500, 1000]ms.+/// Playwright-style actionability checks, callable on their own.+///+/// Kept with the pre-engine signatures so existing callers keep compiling and+/// working. Humanized actions no longer call this class: they run the same checks+/// inside <c>HumanEngine</c> and raise Playwright errors. Here the checks run on that+/// engine too, so they accept every Playwright selector (<c>GetByRole</c>,+/// <c>>></c> chains, filters, frame locators). Failures raise the+/// typed <see cref="ActionabilityError"/> subclasses, as before.+///+/// The optional <see cref="IsolatedWorld"/> arguments are accepted for source+/// compatibility and ignored: the engine manages its own per-frame worlds./// </summary>public static class Actionability{@@ -104,203 +137,157 @@ public static class Actionabilitypublic static readonly IReadOnlySet<string> ChecksCheck =new HashSet<string> { "attached", "visible", "enabled", "pointer_events" };+ private const string HandleLabel = "<ElementHandle>";private static readonly int[] BackoffMs = { 100, 250, 500, 1000 };-- private static Task BackoffSleepAsync(int attempt)- {- int idx = Math.Min(attempt, BackoffMs.Length - 1);- return Task.Delay(BackoffMs[idx]);- }+ private static readonly string[] StateChecks = { "visible", "enabled", "editable" };+ private static readonly System.Runtime.CompilerServices.ConditionalWeakTable<IPage, HumanEngine> Engines = new();private static double NowMs() => Environment.TickCount64;/// <summary>/// Milliseconds left until <paramref name="deadline"/> (an <see cref="Environment.TickCount64"/>- /// timestamp), clamped at zero. Sequential operations share one deadline so the total- /// timeout budget is never multiplied (issue #307). Never returns a negative value.+ /// timestamp), clamped at zero (issue #307)./// </summary>internal static double RemainingMs(double deadline) => Math.Max(0, deadline - NowMs());- // ------------------------------------------------------------------------ // Pre-scroll actionability: attached, visible, enabled, editable- // -----------------------------------------------------------------------+ private static Task BackoffAsync(int attempt, double deadline) =>+ Task.Delay(TimeSpan.FromMilliseconds(Math.Min(BackoffMs[Math.Min(attempt, BackoffMs.Length - 1)],+ Math.Max(1, RemainingMs(deadline)))));- /// <summary>- /// Wait for the element to pass actionability checks (pre-scroll). Retries- /// with backoff until <paramref name="timeoutMs"/> elapsed. Throws a specific- /// <see cref="ActionabilityError"/> subclass on failure. Returns immediately- /// when <paramref name="force"/> is true.- /// </summary>- public static async Task EnsureActionableAsync(- IPage page,- string selector,- IReadOnlySet<string> checks,- double timeoutMs = 30000,- bool force = false,- IsolatedWorld? stealth = null)+ /// <summary>The engine of a page: the humanized page's own one (shared cursor and+ /// worlds), or a private one for a page that was never humanized.</summary>+ private static HumanEngine EngineOf(IPage page){- if (force)- return;- if (stealth == null)- throw new StealthWorldUnavailableError();+ var raw = page is CloakBrowser.Wrappers.HumanizedPage hp ? hp.Original : page;+ if (CloakBrowser.Wrappers.Humanize.TryGetCursor(raw, out var cursor)) return cursor.Engine;+ return Engines.GetValue(raw, p => new HumanEngine(p, new HumanConfig(), new CursorPosition()));+ }- double deadline = NowMs() + timeoutMs;- int attempt = 0;- Exception? lastError = null;+ private static (HumanEngine Engine, Target Target) ForSelector(IPage page, string selector)+ {+ var engine = EngineOf(page);+ return (engine, new Target(engine.Page.MainFrame, selector));+ }- while (true)- {- double remainingMs = Math.Max(0, deadline - NowMs());- if (remainingMs <= 0)- {- if (lastError != null)- throw lastError;- throw new ActionabilityError(selector, "timeout", "timeout expired before first check");- }+ private static (HumanEngine Engine, Target Target) ForHandle(IElementHandle el)+ {+ var raw = el is CloakBrowser.Wrappers.HumanizedElementHandle h ? h.Original : el;+ var frame = PlaywrightInternals.HandleFrame(raw);+ return (EngineOf(frame.Page), new Target(frame, null, handle: raw));+ }+ /// <summary>Map the engine's last retry reason to the typed error of this API.</summary>+ private static ActionabilityError Typed(string label, string? reason) => reason switch+ {+ null => new ActionabilityError(label, "timeout", "timeout expired before first check"),+ _ when reason.StartsWith("waiting for", StringComparison.Ordinal) => new ElementNotAttachedError(label),+ _ when reason.Contains("detached", StringComparison.Ordinal) => new ElementNotAttachedError(label),+ "element is not visible" => new ElementNotVisibleError(label),+ "element is not enabled" => new ElementNotEnabledError(label),+ "element is not editable" => new ElementNotEditableError(label),+ "element is not attached" => new ElementNotAttachedError(label),+ _ => new ActionabilityError(label, "timeout", reason),+ };++ /// <summary>Run <paramref name="attempt"/> until it succeeds or the budget is spent+ /// (at least once). Retryable failures surface as <paramref name="fail"/>(last reason).</summary>+ private static async Task<T> RetryAsync<T>(double timeoutMs, Func<Task<T>> attempt, Func<string?, Exception> fail)+ {+ double deadline = NowMs() + Math.Max(0, timeoutMs);+ string? reason = null;+ for (int n = 0; ; n++)+ {try{- var (status, snapshot) = await StealthDom.ActionableAsync(- stealth, selector).ConfigureAwait(false);- if (status == StealthStatus.Unsupported)- throw new UnsupportedHumanizeSelectorError(selector);- if (status == StealthStatus.EvaluationFailed)- throw new StealthEvaluationError(selector);- if (status == StealthStatus.NotFound)- throw new ElementNotAttachedError(selector);- if (status != StealthStatus.Ok || snapshot == null)- throw new StealthEvaluationError(selector);-- var value = snapshot.Value;- if (checks.Contains("visible") && !value.Visible)- throw new ElementNotVisibleError(selector);- if (checks.Contains("enabled") && !value.Enabled)- throw new ElementNotEnabledError(selector);- if (checks.Contains("editable") && !value.Editable)- throw new ElementNotEditableError(selector);- return;- }- catch (Exception error) when (error is ActionabilityError or StealthEvaluationError)- {- lastError = error;- if (NowMs() >= deadline)- throw;- await BackoffSleepAsync(attempt).ConfigureAwait(false);- attempt++;+ return await attempt().ConfigureAwait(false);}+ catch (RetryException r) { reason = r.Message; }+ catch (StaleElementException) { reason = "element was detached from the DOM"; }+ if (NowMs() >= deadline) throw fail(reason);+ await BackoffAsync(n, deadline).ConfigureAwait(false);}}+ private static string[] States(IReadOnlySet<string> checks) => StateChecks.Where(checks.Contains).ToArray();+// ------------------------------------------------------------------------ // Post-scroll stability check+ // Element states: attached, visible, enabled, editable// ------------------------------------------------------------------------ private static bool BoxesDiffer(BoundingBox a, BoundingBox b) =>- Math.Abs(a.X - b.X) > 1- || Math.Abs(a.Y - b.Y) > 1- || Math.Abs(a.Width - b.Width) > 1- || Math.Abs(a.Height - b.Height) > 1;-- /// <summary>Bounding box via the isolated world only.</summary>- private static async Task<BoundingBox?> ReadBoxAsync(- IPage page, string selector, IsolatedWorld? stealth, double remainingMs)- {- if (stealth == null)- throw new StealthWorldUnavailableError();-- var (status, target) = await StealthDom.BoxAsync(stealth, selector).ConfigureAwait(false);- return status switch- {- StealthStatus.Ok when target != null => target.Value.Box,- StealthStatus.NotFound => null,- StealthStatus.Unsupported => throw new UnsupportedHumanizeSelectorError(selector),- _ => throw new StealthEvaluationError(selector),- };- }-/// <summary>- /// Wait for the element's position to stabilize (two samples 100ms apart).- /// Only call after a scroll - skip if the element was already in the viewport.+ /// Wait for the element to be attached and to pass <paramref name="checks"/>+ /// (<c>visible</c>, <c>enabled</c>, <c>editable</c>; <c>pointer_events</c> is checked+ /// at the click point by <see cref="CheckPointerEventsAsync(IPage, string, double, double, double, IsolatedWorld?)"/>).+ /// Throws an <see cref="ActionabilityError"/> subclass when the budget is spent.+ /// Returns immediately when <paramref name="force"/> is true./// </summary>- public static async Task EnsureStableAsync(IPage page, string selector, double timeoutMs = 5000, IsolatedWorld? stealth = null)+ public static Task EnsureActionableAsync(+ IPage page,+ string selector,+ IReadOnlySet<string> checks,+ double timeoutMs = 30000,+ bool force = false,+ IsolatedWorld? stealth = null){- double deadline = NowMs() + timeoutMs;- int attempt = 0;-- while (true)- {- double remainingMs = Math.Max(0, deadline - NowMs());- if (remainingMs <= 0)- throw new ElementNotStableError(selector);-- try- {- var box1 = await ReadBoxAsync(page, selector, stealth, remainingMs).ConfigureAwait(false);- if (box1 == null)- throw new ElementNotAttachedError(selector);-- await Task.Delay(100).ConfigureAwait(false);-- var box2 = await ReadBoxAsync(page, selector, stealth, remainingMs).ConfigureAwait(false);- if (box2 == null)- throw new ElementNotAttachedError(selector);-- if (!BoxesDiffer(box1.Value, box2.Value))- return;- }- catch (StealthEvaluationError)- {- if (NowMs() >= deadline)- throw;- await BackoffSleepAsync(attempt).ConfigureAwait(false);- attempt++;- continue;- }-- if (NowMs() >= deadline)- throw new ElementNotStableError(selector);+ if (force) return Task.CompletedTask;+ var (engine, target) = ForSelector(page, selector);+ var states = States(checks);+ return RetryAsync(timeoutMs, () => engine.AttemptStatesAsync(target, states, false),+ reason => Typed(selector, reason));+ }- await BackoffSleepAsync(attempt).ConfigureAwait(false);- attempt++;- }+ /// <summary>Element-state checks for an <see cref="IElementHandle"/>.</summary>+ public static Task EnsureActionableHandleAsync(+ IElementHandle el,+ IReadOnlySet<string> checks,+ double timeoutMs = 30000,+ bool force = false)+ {+ if (force) return Task.CompletedTask;+ var (engine, target) = ForHandle(el);+ var states = States(checks);+ return RetryAsync(timeoutMs, () => engine.AttemptStatesAsync(target, states, false),+ reason => Typed(HandleLabel, reason));}// ------------------------------------------------------------------------ // Pointer-events check (post-scroll, at actual click coordinates)+ // Stability// ------------------------------------------------------------------------ // data.box is page-space (from boundingBox); rect is frame-local. Their delta- // is the iframe offset, needed to map page-space click coords into the frame's- // own viewport before elementFromPoint. For main-frame elements the offset is 0.- internal const string PointerEventsJs = @"(expected, data) => {- const rect = expected.getBoundingClientRect();- const frameOffsetX = data.box ? data.box.x - rect.x : 0;- const frameOffsetY = data.box ? data.box.y - rect.y : 0;- const target = document.elementFromPoint(data.x - frameOffsetX, data.y - frameOffsetY);- if (!target) return { hit: false, reason: 'no_element_at_point', covering: 'none' };- let node = target;- while (node) { if (node === expected) return { hit: true }; node = node.parentNode; }- if (expected.contains(target)) return { hit: true };- return { hit: false, reason: 'covered', covering: target.tagName || 'unknown' };-}";-/// <summary>- /// Result of the <c>elementFromPoint</c> pointer-events probe. Internal (not private)- /// so unit tests can construct a "covered" result without a live browser.+ /// Wait until the element's box stops moving (two reads 100 ms apart differ by at+ /// most 1 px). Throws <see cref="ElementNotStableError"/> when the budget is spent,+ /// <see cref="ElementNotAttachedError"/> if the element never appears./// </summary>- internal sealed class PointerResult+ public static Task EnsureStableAsync(IPage page, string selector, double timeoutMs = 5000, IsolatedWorld? stealth = null){- public bool Hit { get; set; }- public string? Reason { get; set; }- public string? Covering { get; set; }+ var (engine, target) = ForSelector(page, selector);+ bool found = false;+ return RetryAsync(timeoutMs, async () =>+ {+ var r = await engine.ResolveAsync(target).ConfigureAwait(false);+ found = true;+ var a = await engine.ElementBoxAsync(r).ConfigureAwait(false);+ await Task.Delay(100).ConfigureAwait(false);+ var b = await engine.ElementBoxAsync(r).ConfigureAwait(false);+ if (Math.Abs(a.X - b.X) > 1 || Math.Abs(a.Y - b.Y) > 1 ||+ Math.Abs(a.Width - b.Width) > 1 || Math.Abs(a.Height - b.Height) > 1)+ throw new RetryException("element is not stable");+ return true;+ }, reason => found ? new ElementNotStableError(selector) : new ElementNotAttachedError(selector));}+ // -----------------------------------------------------------------------+ // Pointer events at the actual click point+ // -----------------------------------------------------------------------+/// <summary>- /// Compatibility overload for callers that do not yet carry a canonical target ID.- /// It snapshots the target in the isolated world, then delegates to identity-aware- /// revalidation. New interaction paths should pass the original target ID directly.+ /// Wait until a click at viewport point (<paramref name="x"/>, <paramref name="y"/>)+ /// would land on the element: Playwright's hit-target check, also through every+ /// ancestor <c><iframe></c>. Throws <see cref="ElementNotReceivingEventsError"/>+ /// naming the covering element when the budget is spent./// </summary>- public static async Task CheckPointerEventsAsync(+ public static Task CheckPointerEventsAsync(IPage page,string selector,double x,@@ -308,27 +295,16 @@ public static class Actionabilitydouble timeoutMs = 5000,IsolatedWorld? stealth = null){- if (stealth == null)- throw new StealthWorldUnavailableError();-- var (status, snapshot) = await StealthDom.SnapshotAsync(stealth, selector).ConfigureAwait(false);- var resolved = status switch- {- StealthStatus.Ok when snapshot != null => snapshot.Value,- StealthStatus.NotFound => throw new ElementNotAttachedError(selector),- StealthStatus.Unsupported => throw new UnsupportedHumanizeSelectorError(selector),- _ => throw new StealthEvaluationError(selector),- };- await CheckPointerEventsAsync(- page, selector, resolved.TargetId, resolved.Gen, x, y, timeoutMs, stealth).ConfigureAwait(false);+ var (engine, target) = ForSelector(page, selector);+ return PointerAsync(engine, target, selector, x, y, timeoutMs);}/// <summary>- /// Revalidate that the click point still hits the same resolved element.- /// Callers skip this entirely when force is set (matching Playwright, where- /// force bypasses all actionability checks).+ /// Overload kept for source compatibility. <paramref name="targetId"/> and+ /// <paramref name="gen"/> identified elements in the old resolver and are ignored;+ /// the element is re-resolved from <paramref name="selector"/>./// </summary>- public static async Task CheckPointerEventsAsync(+ public static Task CheckPointerEventsAsync(IPage page,string selector,int targetId,@@ -336,179 +312,39 @@ public static class Actionabilitydouble x,double y,double timeoutMs = 5000,- IsolatedWorld? stealth = null)- {- if (stealth == null)- throw new StealthWorldUnavailableError();-- double deadline = NowMs() + timeoutMs;- int attempt = 0;-- while (true)- {- var (status, hit, covering, _) = await StealthDom.ValidateAsync(- stealth, selector, targetId, gen, x, y).ConfigureAwait(false);-- if (status == StealthStatus.Unsupported)- throw new UnsupportedHumanizeSelectorError(selector);- if (status == StealthStatus.Stale)- throw new ElementTargetChangedError(selector);- if (status == StealthStatus.NotFound)- throw new ElementNotAttachedError(selector);- if (status == StealthStatus.EvaluationFailed)- {- if (NowMs() >= deadline)- throw new StealthEvaluationError(selector);- }- else if (status == StealthStatus.Ok && hit)- {- return;- }- else if (status == StealthStatus.Ok)- {- if (NowMs() >= deadline)- throw new ElementNotReceivingEventsError(selector, covering);- }- else- {- throw new StealthEvaluationError(selector);- }-- await BackoffSleepAsync(attempt).ConfigureAwait(false);- attempt++;- }- }-- // ------------------------------------------------------------------------ // ElementHandle variants- // ------------------------------------------------------------------------- /// <summary>Actionability checks for an <see cref="IElementHandle"/> (no selector needed).</summary>- public static async Task EnsureActionableHandleAsync(- IElementHandle el,- IReadOnlySet<string> checks,- double timeoutMs = 30000,- bool force = false)- {- if (force)- return;-- double deadline = NowMs() + timeoutMs;- int attempt = 0;- ActionabilityError? lastError = null;- const string label = "<ElementHandle>";-- while (true)- {- double remainingMs = Math.Max(0, deadline - NowMs());- if (remainingMs <= 0)- {- if (lastError != null)- throw lastError;- throw new ActionabilityError(label, "timeout", "timeout expired before first check");- }-- try- {- if (checks.Contains("visible"))- {- try- {- await el.WaitForElementStateAsync(ElementState.Visible, new ElementHandleWaitForElementStateOptions- {- Timeout = (float)Math.Max(1, Math.Min(remainingMs, 2000)),- }).ConfigureAwait(false);- }- catch (Exception) { throw new ElementNotVisibleError(label); }- }-- if (checks.Contains("enabled"))- {- try- {- await el.WaitForElementStateAsync(ElementState.Enabled, new ElementHandleWaitForElementStateOptions- {- Timeout = (float)Math.Max(1, Math.Min(remainingMs, 2000)),- }).ConfigureAwait(false);- }- catch (Exception) { throw new ElementNotEnabledError(label); }- }-- if (checks.Contains("editable"))- {- try- {- await el.WaitForElementStateAsync(ElementState.Editable, new ElementHandleWaitForElementStateOptions- {- Timeout = (float)Math.Max(1, Math.Min(remainingMs, 2000)),- }).ConfigureAwait(false);- }- catch (Exception) { throw new ElementNotEditableError(label); }- }-- return;- }- catch (ActionabilityError e)- {- lastError = e;- if (NowMs() >= deadline)- throw;- await BackoffSleepAsync(attempt).ConfigureAwait(false);- attempt++;- }- }- }+ IsolatedWorld? stealth = null) =>+ CheckPointerEventsAsync(page, selector, x, y, timeoutMs, stealth);/// <summary>Pointer-events check for an <see cref="IElementHandle"/>.</summary>- public static async Task CheckPointerEventsHandleAsync(+ public static Task CheckPointerEventsHandleAsync(IElementHandle el,double x,double y,double timeoutMs = 5000){- double deadline = NowMs() + timeoutMs;- int attempt = 0;- string? lastMiss = null;-- while (true)- {- PointerResult? result = null;- try- {- var box = await el.BoundingBoxAsync().ConfigureAwait(false);- var data = new- {- x,- y,- box = box == null ? null : new { x = box.X, y = box.Y, width = box.Width, height = box.Height },- };- result = await el.EvaluateAsync<PointerResult?>(PointerEventsJs, data).ConfigureAwait(false);- }- catch (Exception)- {- result = null;- }-- // See the locator variant: an indeterminate result fails open, but a- // miss that was already determined must not be laundered into a pass- // by a late attempt that merely errored (#329).- if (result == null)- {- if (lastMiss != null && NowMs() >= deadline)- throw new ElementNotReceivingEventsError("<ElementHandle>", lastMiss);- return;- }- if (result.Hit)- return;-- string covering = result.Covering ?? "unknown";- lastMiss = covering;+ var (engine, target) = ForHandle(el);+ return PointerAsync(engine, target, HandleLabel, x, y, timeoutMs);+ }- if (NowMs() >= deadline)- throw new ElementNotReceivingEventsError("<ElementHandle>", covering);+ private const string Intercepts = " intercepts pointer events";- await BackoffSleepAsync(attempt).ConfigureAwait(false);- attempt++;- }+ private static Task PointerAsync(HumanEngine engine, Target target, string label, double x, double y, double timeoutMs)+ {+ bool found = false;+ return RetryAsync(timeoutMs, async () =>+ {+ var r = await engine.ResolveAsync(target).ConfigureAwait(false);+ found = true;+ await engine.HitAsync(r, x, y).ConfigureAwait(false);+ return true;+ }, reason =>+ {+ if (!found) return Typed(label, reason);+ if (reason != null && reason.EndsWith(Intercepts, StringComparison.Ordinal))+ return new ElementNotReceivingEventsError(label, reason[..^Intercepts.Length]);+ if (reason == "element is outside of the viewport")+ return new ElementNotReceivingEventsError(label, "nothing: the point is outside the viewport");+ return Typed(label, reason);+ });}}diff --git a/dotnet/src/CloakBrowser/Human/Fields.cs b/dotnet/src/CloakBrowser/Human/Fields.csnew file mode 100644index 0000000..e0cb5b1--- /dev/null+++ b/dotnet/src/CloakBrowser/Human/Fields.cs@@ -0,0 +1,127 @@+using System.Text.RegularExpressions;++namespace CloakBrowser.Human;++/// <summary>+/// Field classification for humanized text input. Port of+/// <c>cloakbrowser/human/fields.py</c>; mirrors Playwright's <c>InjectedScript.fill</c>+/// rules so the humanize layer accepts and rejects the same targets Playwright does:+/// text-like inputs are typed into key by key, value inputs (date, range, ...) are+/// operated through their native widget the way a person does it, everything else+/// (checkbox, file, hidden, radio, ...) cannot be filled.+/// Mistypes are only simulated where a correction is safe: never in+/// number/email/password/tel/url fields.+/// </summary>+internal static class Fields+{+ public static readonly IReadOnlySet<string> TypeInto =+ new HashSet<string> { "", "email", "number", "password", "search", "tel", "text", "url" };+ public static readonly IReadOnlySet<string> SetValue =+ new HashSet<string> { "color", "date", "time", "datetime-local", "month", "range", "week" };+ public static readonly IReadOnlySet<string> NoMistype =+ new HashSet<string> { "number", "email", "password", "tel", "url" };++ public enum Kind { Type, Set, NotFillable }++ public static Kind Classify(string? tag, string? inputType, bool editable)+ {+ var t = (tag ?? "").ToLowerInvariant();+ if (t == "input")+ {+ var it = (inputType ?? "").ToLowerInvariant();+ if (TypeInto.Contains(it)) return Kind.Type;+ if (SetValue.Contains(it)) return Kind.Set;+ return Kind.NotFillable;+ }+ return t == "textarea" || editable ? Kind.Type : Kind.NotFillable;+ }++ public static bool AllowsMistype(string? tag, string? inputType) =>+ (tag ?? "").ToLowerInvariant() != "input" || !NoMistype.Contains((inputType ?? "").ToLowerInvariant());++ public static string NormalizeSetValue(string? inputType, string value)+ {+ var v = value.Trim();+ return (inputType ?? "").ToLowerInvariant() == "color" ? v.ToLowerInvariant() : v;+ }++ /// <summary>Playwright rejects non-numeric text for input[type=number]; null = invalid.</summary>+ public static string? ValidateNumber(string value)+ {+ var v = value.Trim();+ if (v.Length == 0) return v;+ return double.TryParse(v, System.Globalization.NumberStyles.Float,+ System.Globalization.CultureInfo.InvariantCulture, out _) ? v : null;+ }++ public static string NotFillableMessage(string? tag, string? inputType) =>+ (tag ?? "").ToLowerInvariant() == "input"+ ? $"Input of type \"{(inputType ?? "").ToLowerInvariant()}\" cannot be filled"+ : "Element is not an <input>, <textarea> or [contenteditable] element";++ // -----------------------------------------------------------------------+ // Native date/time editors+ // -----------------------------------------------------------------------++ private const string Date = @"(?<year>\d{4,6})-(?<month>\d{2})-(?<day>\d{2})";+ private const string Time = @"(?<hour>\d{2}):(?<minute>\d{2})(?::(?<second>\d{2})(?:\.(?<millisecond>\d{1,3}))?)?";++ private static readonly Dictionary<string, Regex> DtPatterns = new()+ {+ ["date"] = new Regex("^" + Date + "$"),+ ["month"] = new Regex(@"^(?<year>\d{4,6})-(?<month>\d{2})$"),+ ["week"] = new Regex(@"^(?<year>\d{4,6})-W(?<week>\d{2})$"),+ ["time"] = new Regex("^" + Time + "$"),+ ["datetime-local"] = new Regex("^" + Date + "T" + Time + "$"),+ };++ private static readonly Dictionary<string, int> FullWidth = new()+ {+ ["month"] = 2, ["day"] = 2, ["week"] = 2, ["hour"] = 2, ["minute"] = 2, ["second"] = 2, ["millisecond"] = 3,+ };++ private static readonly string[] Groups = { "year", "month", "day", "week", "hour", "minute", "second", "millisecond" };++ /// <summary>Editor segment keystrokes of an HTML date/time value (null when malformed).+ /// <c>hour</c> is the 12-hour form shown next to an AM/PM segment; <see cref="DateTimeParts.Hour24"/>+ /// keeps the original hour.</summary>+ public static DateTimeParts? ParseDateTime(string inputType, string value)+ {+ if (!DtPatterns.TryGetValue(inputType, out var re)) return null;+ var m = re.Match(value);+ if (!m.Success) return null;+ var parts = new Dictionary<string, string>();+ foreach (var g in Groups)+ if (m.Groups[g].Success) parts[g] = m.Groups[g].Value;+ int? hour24 = null;+ if (parts.TryGetValue("hour", out var h))+ {+ hour24 = int.Parse(h);+ parts["hour"] = (hour24.Value % 12 == 0 ? 12 : hour24.Value % 12).ToString("00");+ }+ if (parts.TryGetValue("millisecond", out var ms)) parts["millisecond"] = ms.PadRight(3, '0');+ return new DateTimeParts(parts, hour24);+ }++ /// <summary>Pick the hour digits matching the editor (with or without AM/PM).</summary>+ public static DateTimeParts Use24h(DateTimeParts p, bool hasAmpm)+ {+ if (p.Hour24 == null || hasAmpm) return p;+ var d = new Dictionary<string, string>(p.Values) { ["hour"] = p.Hour24.Value.ToString("00") };+ return new DateTimeParts(d, p.Hour24);+ }++ /// <summary>Whether typing this segment's digits moves focus to the next segment.+ /// Two-digit segments advance; the year segment never does (up to six digits).</summary>+ public static bool SegmentAutoAdvances(string kind, DateTimeParts p, string inputType = "")+ {+ if (inputType == "month" && kind == "month") return false; // shown as a month name+ return FullWidth.TryGetValue(kind, out var w) && p.Values.TryGetValue(kind, out var v) && v.Length >= w;+ }+}++internal sealed record DateTimeParts(IReadOnlyDictionary<string, string> Values, int? Hour24)+{+ public bool Has(string kind) => Values.ContainsKey(kind);+ public string this[string kind] => Values[kind];+}diff --git a/dotnet/src/CloakBrowser/Human/HumanEngine.Actions.cs b/dotnet/src/CloakBrowser/Human/HumanEngine.Actions.csnew file mode 100644index 0000000..aa5ddcb--- /dev/null+++ b/dotnet/src/CloakBrowser/Human/HumanEngine.Actions.cs@@ -0,0 +1,553 @@+using System.Text.Json;+using Microsoft.Playwright;++namespace CloakBrowser.Human;++/// <summary>Public actions of the unified engine (port of the action half of+/// <c>cloakbrowser/human/engine.py</c>).</summary>+internal sealed partial class HumanEngine+{+ private static MouseButton Btn(ActOpts o) => o.Button ?? MouseButton.Left;++ public async Task ClickAsync(Target t, ActOpts o, string api, int? clickCount = null)+ {+ int count = clickCount ?? o.ClickCount ?? 1;+ await PointerActionAsync(api, t, o, ClickStates, null, async (r, _, _, cfg) =>+ {+ bool isInput = await IsInputAsync(r).ConfigureAwait(false);+ await PressMouseAsync(cfg, isInput, Btn(o), count, o.Delay, o.Modifiers).ConfigureAwait(false);+ }).ConfigureAwait(false);+ }++ public async Task HoverAsync(Target t, ActOpts o, string api)+ {+ // Playwright holds the modifiers while the mouse moves onto the target.+ await PointerActionAsync(api, t, o, HoverStates, false, hold: o.Modifiers).ConfigureAwait(false);+ }++ public Task TapAsync(Target t, ActOpts o, string api) => ClickAsync(t, o.With(c => c.ClickCount = 1), api);++ private async Task<JsonElement> InfoAsync(Resolved r) =>+ (await World.CallAsync(r.Frame, "info", r.Id).ConfigureAwait(false))!.Value;++ private static string? S(JsonElement e, string p) =>+ e.TryGetProperty(p, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null;++ /// <summary>+ /// Focus by a human click unless already focused. Returns (r, clickedIn): clickedIn is+ /// true when this call clicked and focus landed in the target. With+ /// <paramref name="requireFocus"/> false (press / type) a click that does not move focus+ /// is fine, as in Playwright: the keys go to whatever handles them (a <canvas>,+ /// document-level key handlers).+ /// </summary>+ public async Task<(Resolved R, bool Clicked)> FocusElementAsync(Target t, ActOpts o, string api, Deadline d,+ bool requireFocus = true)+ {+ var r = await WaitForAsync(t, FocusStates, d, api, o.Force).ConfigureAwait(false);+ var info = await InfoAsync(r).ConfigureAwait(false);+ if (info.GetProperty("focused").GetBoolean()) return (r, false);+ // A person focuses a field by clicking it: scroll it into view with the wheel and+ // click. When it cannot be brought on screen at all the click times out with+ // "element is outside of the viewport" -- no silent programmatic focus.+ await ClickAsync(t, new ActOpts { Deadline = d, Force = o.Force, HumanConfig = o.HumanConfig }, api).ConfigureAwait(false);+ info = await InfoAsync(r).ConfigureAwait(false);+ if (info.GetProperty("focused").GetBoolean() || await FocusMovedIntoAsync(r).ConfigureAwait(false))+ return (r, true);+ if (requireFocus)+ throw Err($"{api}: Error: element did not receive focus when clicked (it may not be focusable): {S(info, "preview")}");+ return (r, false);+ }++ private async Task<bool> FocusMovedIntoAsync(Resolved r)+ {+ var act = await World.CallAsync(r.Frame, "activeValue").ConfigureAwait(false);+ if (act is not JsonElement a || S(a, "tag") == null) return false;+ var v = await World.EvaluateAsync(r.Frame,+ $"(() => {{ const e = {WorldHelpers.Name}.el({r.Id}); const a = document.activeElement; return !!a && (e === a || e.contains(a)); }})()").ConfigureAwait(false);+ return v is { ValueKind: JsonValueKind.True };+ }++ public async Task CaretToEndAsync(Resolved r)+ {+ var info = await InfoAsync(r).ConfigureAwait(false);+ if (S(info, "tag") == "input")+ {+ if (await World.CallAsync(r.Frame, "caretAtEnd", r.Id).ConfigureAwait(false) is not { ValueKind: JsonValueKind.True })+ await _raw.KeyPressAsync("End").ConfigureAwait(false);+ }+ else+ {+ await _raw.KeyPressAsync("Control+End").ConfigureAwait(false);+ }+ await Sleep(R(20, 60)).ConfigureAwait(false);+ }++ public async Task PressAsync(Target t, string key, ActOpts o, string api)+ {+ var d = DeadlineFor(t, o);+ await FocusElementAsync(t, o, api, d, requireFocus: false).ConfigureAwait(false);+ await Sleep(R(50, 150)).ConfigureAwait(false);+ await _raw.KeyPressAsync(await KeysAsync(key).ConfigureAwait(false), o.Delay).ConfigureAwait(false);+ }++ public async Task TypeAsync(Target t, string text, ActOpts o, string api)+ {+ var cfg = CallCfg(o.HumanConfig);+ var d = DeadlineFor(t, o);+ await Sleep(RR(cfg.FieldSwitchDelay)).ConfigureAwait(false);+ var (r, clicked) = await FocusElementAsync(t, o, api, d, requireFocus: false).ConfigureAwait(false);+ if (clicked) await CaretToEndAsync(r).ConfigureAwait(false);+ await Sleep(R(100, 250)).ConfigureAwait(false);+ await TypeTextAsync(text, cfg, r.Frame, await InfoAsync(r).ConfigureAwait(false), o.Delay).ConfigureAwait(false);+ }++ public async Task FillAsync(Target t, string value, ActOpts o, string api)+ {+ var cfg = CallCfg(o.HumanConfig);+ var d = DeadlineFor(t, o);+ var r = await WaitForAsync(t, InputStates, d, api, o.Force).ConfigureAwait(false);+ var info = await InfoAsync(r).ConfigureAwait(false);+ string? tag = S(info, "tag"), type = S(info, "type");+ var kind = Fields.Classify(tag, type, info.GetProperty("editable").GetBoolean());+ if (kind == Fields.Kind.NotFillable) throw Err($"{api}: Error: {Fields.NotFillableMessage(tag, type)}");+ if (type == "number")+ value = Fields.ValidateNumber(value) ?? throw Err($"{api}: Error: Cannot type text into input[type=number]");+ if (kind == Fields.Kind.Set)+ {+ value = Fields.NormalizeSetValue(type, value);+ await Sleep(RR(cfg.FieldSwitchDelay)).ConfigureAwait(false);+ if (type == "range") await SetRangeAsync(t, r, value, o, api, d).ConfigureAwait(false);+ else if (type == "color")+ throw Err($"{api}: Error: <input type=color> opens a native colour picker that cannot be operated with " ++ "human input; set it on the original page (Humanize.Unwrap(page).FillAsync) if a programmatic value is acceptable");+ else await SetDateTimeAsync(t, r, type!, value, o, api, cfg, d).ConfigureAwait(false);+ return;+ }+ await Sleep(RR(cfg.FieldSwitchDelay)).ConfigureAwait(false);+ (r, _) = await FocusElementAsync(t, o, api, d).ConfigureAwait(false);+ await Sleep(R(100, 250)).ConfigureAwait(false);+ info = await InfoAsync(r).ConfigureAwait(false);+ if (!string.IsNullOrEmpty(S(info, "value")))+ {+ await _raw.KeyPressAsync(await SelectAllKeyAsync().ConfigureAwait(false)).ConfigureAwait(false);+ await Sleep(R(30, 80)).ConfigureAwait(false);+ await _raw.KeyPressAsync("Backspace").ConfigureAwait(false);+ await Sleep(R(50, 150)).ConfigureAwait(false);+ info = await InfoAsync(r).ConfigureAwait(false);+ var left = S(info, "value");+ if (!string.IsNullOrEmpty(left))+ {+ // Some widgets ignore select-all; clear what is left by keys.+ await CaretToEndAsync(r).ConfigureAwait(false);+ for (int i = 0; i < left.Length; i++)+ {+ await _raw.KeyPressAsync("Backspace").ConfigureAwait(false);+ await Sleep(R(15, 40)).ConfigureAwait(false);+ }+ }+ }+ if (value.Length > 0) await TypeTextAsync(value, cfg, r.Frame, info, null).ConfigureAwait(false);+ }++ public async Task SetCheckedAsync(Target t, bool want, ActOpts o, string api)+ {+ var d = DeadlineFor(t, o);+ var r = await WaitForAsync(t, ClickStates, d, api, o.Force).ConfigureAwait(false);+ var state = (await World.CallAsync(r.Frame, "checked", r.Id).ConfigureAwait(false))!.Value;+ if (state.TryGetProperty("error", out var e)) throw Err($"{api}: Error: {e.GetString()}");+ if (state.GetProperty("checked").GetBoolean() == want) return;+ if (state.GetProperty("radio").GetBoolean() && !want)+ throw Err($"{api}: Error: Cannot uncheck radio button. Radio buttons can only be unchecked by selecting another radio button in the same group.");+ await ClickAsync(t, new ActOpts { Force = o.Force, Position = o.Position, Trial = o.Trial, HumanConfig = o.HumanConfig, Deadline = d }, api).ConfigureAwait(false);+ if (o.Trial) return;+ state = (await World.CallAsync(r.Frame, "checked", r.Id).ConfigureAwait(false))!.Value;+ if (!state.TryGetProperty("checked", out var c) || c.GetBoolean() != want)+ throw Err($"{api}: Error: Clicking the checkbox did not change its state");+ }++ // -- value inputs: what a person does --------------------------------++ private async Task<string?> ValueAsync(Resolved r) =>+ (await World.CallAsync(r.Frame, "value", r.Id).ConfigureAwait(false)) is { ValueKind: JsonValueKind.String } v ? v.GetString() : null;++ /// <summary>date / time / datetime-local / month / week: click the first segment of the+ /// native editor and type each part, in the order the locale shows them.</summary>+ private async Task SetDateTimeAsync(Target t, Resolved r, string inputType, string value, ActOpts o, string api,+ HumanConfig cfg, Deadline d)+ {+ var parts = Fields.ParseDateTime(inputType, value) ?? throw Err($"{api}: Error: Malformed value");+ var segs = await World.EditorFieldsAsync(r.Frame, r.Id).ConfigureAwait(false);+ var kinds = segs.Select(s => s.Kind).ToList();+ parts = Fields.Use24h(parts, kinds.Contains("ampm"));+ if (segs.Count == 0 || kinds.Any(k => k != "ampm" && !parts.Has(k)))+ throw Err($"{api}: Error: unsupported date/time editor layout [{string.Join(", ", kinds)}]");+ await PointerActionAsync(api, t, o.With(c => { c.Deadline = d; c.Position = null; c.Aim = new object[] { "segment", segs[0] }; }),+ InputStates, true, (_, _, _, c) => PressMouseAsync(c, true)).ConfigureAwait(false);+ await Sleep(R(80, 200)).ConfigureAwait(false);+ var current = Fields.ParseDateTime(inputType, await ValueAsync(r).ConfigureAwait(false) ?? "");+ for (int i = 0; i < segs.Count; i++)+ {+ var kind = segs[i].Kind;+ if (inputType == "month" && kind == "month" && current != null)+ {+ // Shown as a month name; over an existing month Chromium's digit matching+ // is unreliable, so step with the arrow keys.+ int diff = int.Parse(parts["month"]) - int.Parse(current["month"]);+ for (int k = 0; k < Math.Abs(diff); k++)+ {+ await _raw.KeyPressAsync(diff > 0 ? "ArrowUp" : "ArrowDown").ConfigureAwait(false);+ await Sleep(R(60, 140)).ConfigureAwait(false);+ }+ }+ else if (kind == "ampm")+ {+ await TypeCharAsync((parts.Hour24 ?? 0) >= 12 ? 'P' : 'A', cfg).ConfigureAwait(false);+ }+ else+ {+ var digits = parts[kind];+ for (int j = 0; j < digits.Length; j++)+ {+ await TypeCharAsync(digits[j], cfg).ConfigureAwait(false);+ // The editor forgets a partial entry after ~1 s without a key.+ if (j < digits.Length - 1)+ await Sleep(Math.Min(450, Math.Max(40, cfg.TypingDelay + (HumanRandom.NextDouble() - 0.5) * 2 * cfg.TypingDelaySpread))).ConfigureAwait(false);+ }+ }+ if (i < segs.Count - 1 && !Fields.SegmentAutoAdvances(kind, parts, inputType))+ await _raw.KeyPressAsync("ArrowRight").ConfigureAwait(false);+ await Sleep(R(60, 160)).ConfigureAwait(false);+ }+ var got = await ValueAsync(r).ConfigureAwait(false);+ if (got != value) throw Err($"{api}: Error: the date/time editor produced '{got}' instead of '{value}'");+ }++ /// <summary>Slider: click on the track near the wanted value, then nudge with arrow keys.</summary>+ private async Task SetRangeAsync(Target t, Resolved r, string value, ActOpts o, string api, Deadline d)+ {+ var info = (await World.CallAsync(r.Frame, "rangeInfo", r.Id).ConfigureAwait(false))!.Value;+ if (!double.TryParse(value, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var want))+ throw Err($"{api}: Error: Malformed value");+ double min = D(info, "min"), max = D(info, "max"), step = D(info, "step");+ bool vertical = info.GetProperty("vertical").GetBoolean(), rtl = info.GetProperty("rtl").GetBoolean();+ double span = max - min;+ double frac = span <= 0 ? 0.5 : Math.Min(1, Math.Max(0, (want - min) / span));+ if (rtl && !vertical) frac = 1 - frac;+ await PointerActionAsync(api, t, o.With(c => { c.Deadline = d; c.Position = null; c.Aim = new object[] { "fraction", frac, vertical }; }),+ InputStates, false, (_, _, _, c) => PressMouseAsync(c, false)).ConfigureAwait(false);+ async Task<double> Read() => double.Parse(await ValueAsync(r).ConfigureAwait(false) ?? "0", System.Globalization.CultureInfo.InvariantCulture);+ for (int k = 0; k < 400; k++)+ {+ double cur = await Read().ConfigureAwait(false);+ if (Math.Abs(cur - want) < 1e-9 || (step > 0 && Math.Abs(cur - want) < step / 2)) break;+ bool up = cur < want;+ await _raw.KeyPressAsync(!rtl ? (up ? "ArrowRight" : "ArrowLeft") : (up ? "ArrowLeft" : "ArrowRight")).ConfigureAwait(false);+ await Sleep(R(40, 110)).ConfigureAwait(false);+ if (await Read().ConfigureAwait(false) == cur) break; // min/max reached+ }+ double snap = Math.Min(max, Math.Max(min, want));+ if (step > 0) snap = Math.Min(max, min + Math.Round((snap - min) / step) * step);+ var got = await Read().ConfigureAwait(false);+ if (got != snap) throw Err($"{api}: Error: slider stopped at {got} instead of {value}");+ }++ /// <summary>Pick options like a person: a dropdown is opened with a click and moved with+ /// arrow keys + Enter; a list box gets clicks on the options (Ctrl/Cmd to add).</summary>+ public async Task<IReadOnlyList<string>> SelectOptionAsync(Target t, IReadOnlyList<object> options,+ IReadOnlyList<IElementHandle> handles, ActOpts o, string api)+ {+ var cfg = CallCfg(o.HumanConfig);+ var d = DeadlineFor(t, o);+ var (r, plan) = await RetryAsync(api, t, d, async () =>+ {+ var rr = await AttemptStatesAsync(t, new[] { "visible", "enabled" }, o.Force).ConfigureAwait(false);+ var ids = new List<int>();+ foreach (var h in handles) ids.Add((await ResolveHandleAsync(h).ConfigureAwait(false)).Id);+ var res = (await World.CallAsync(rr.Frame, "selectPlan", rr.Id, options, ids).ConfigureAwait(false))!.Value;+ if (res.TryGetProperty("error", out var e)) throw Err(e.GetString() ?? "select failed");+ if (res.TryGetProperty("retry", out var re)) throw new RetryException(re.GetString() ?? "retry");+ return (rr, res);+ }).ConfigureAwait(false);+ var targets = plan.GetProperty("targets").EnumerateArray().Select(x => x.GetInt32()).ToList();+ var values = plan.GetProperty("values").EnumerateArray().Select(x => x.GetString()!).ToList();+ if (!plan.GetProperty("listbox").GetBoolean())+ await SelectDropdownAsync(t, r, targets.Count > 0 ? targets[0] : null, plan, o, api, d).ConfigureAwait(false);+ else+ await SelectListboxAsync(t, r, targets, o, api, cfg, d).ConfigureAwait(false);+ var state = (await World.CallAsync(r.Frame, "selectState", r.Id).ConfigureAwait(false))!.Value;+ var selected = state.GetProperty("selected").EnumerateArray().Select(x => x.GetInt32()).OrderBy(x => x).ToList();+ var got = state.GetProperty("values").EnumerateArray().Select(x => x.GetString()!).ToList();+ if (!selected.SequenceEqual(targets.OrderBy(x => x)))+ throw Err($"{api}: Error: selection ended as [{string.Join(", ", got)}] instead of [{string.Join(", ", values)}]");+ return got;+ }++ private async Task SelectDropdownAsync(Target t, Resolved r, int? index, JsonElement plan, ActOpts o, string api, Deadline d)+ {+ if (index == null) throw Err($"{api}: Error: a dropdown always keeps one option selected");+ var state = (await World.CallAsync(r.Frame, "selectState", r.Id).ConfigureAwait(false))!.Value;+ int cur = state.GetProperty("current").GetInt32();+ if (cur == index)+ {+ await HoverAsync(t, new ActOpts { Deadline = d, HumanConfig = o.HumanConfig }, api).ConfigureAwait(false);+ return;+ }+ await ClickAsync(t, new ActOpts { Deadline = d, Force = o.Force, HumanConfig = o.HumanConfig }, api).ConfigureAwait(false);+ await Sleep(R(200, 450)).ConfigureAwait(false); // popup opens; eyes find the option+ if (OperatingSystem.IsMacOS())+ {+ // macOS shows a native popup that ignores arrow keys sent as page+ // input; type-ahead on the option's label still selects it.+ var cfg = CallCfg(o.HumanConfig);+ foreach (var ch in plan.GetProperty("labels")[0].GetString()!)+ {+ if (ch < 128)+ {+ await TypeCharAsync(ch, cfg).ConfigureAwait(false);+ }+ else // no US-layout key: send the character itself, like a native layout does+ {+ var session = await World.SessionAsync().ConfigureAwait(false);+ await session.SendAsync("Input.dispatchKeyEvent", new()+ {+ ["type"] = "keyDown", ["key"] = ch.ToString(), ["text"] = ch.ToString(), ["unmodifiedText"] = ch.ToString(),+ }).ConfigureAwait(false);+ await Sleep(RR(cfg.KeyHold)).ConfigureAwait(false);+ await session.SendAsync("Input.dispatchKeyEvent", new() { ["type"] = "keyUp", ["key"] = ch.ToString() }).ConfigureAwait(false);+ }+ await Sleep(R(60, 140)).ConfigureAwait(false); // type-ahead resets after ~1s of silence+ }+ await _raw.KeyPressAsync("Enter").ConfigureAwait(false);+ await Sleep(R(80, 160)).ConfigureAwait(false);+ return;+ }+ var nav = plan.GetProperty("navigable").EnumerateArray().Select(x => x.GetBoolean()).ToList();+ for (int k = 0; k <= nav.Count && cur != index; k++)+ {+ int step = index > cur ? 1 : -1, nxt = cur + step;+ while (nxt >= 0 && nxt < nav.Count && !nav[nxt]) nxt += step;+ if (nxt < 0 || nxt >= nav.Count) break;+ await _raw.KeyPressAsync(step > 0 ? "ArrowDown" : "ArrowUp").ConfigureAwait(false);+ await Sleep(R(70, 180)).ConfigureAwait(false);+ cur = nxt;+ }+ await Sleep(R(100, 250)).ConfigureAwait(false);+ await _raw.KeyPressAsync("Enter").ConfigureAwait(false);+ await Sleep(R(80, 160)).ConfigureAwait(false);+ }++ private async Task SelectListboxAsync(Target t, Resolved r, List<int> want, ActOpts o, string api, HumanConfig cfg, Deadline d)+ {+ var state = (await World.CallAsync(r.Frame, "selectState", r.Id).ConfigureAwait(false))!.Value;+ var selected = state.GetProperty("selected").EnumerateArray().Select(x => x.GetInt32()).OrderBy(x => x);+ if (selected.SequenceEqual(want.OrderBy(x => x)))+ {+ await HoverAsync(t, new ActOpts { Deadline = d, HumanConfig = o.HumanConfig }, api).ConfigureAwait(false);+ return;+ }+ if (want.Count == 0) throw Err($"{api}: Error: deselecting every option is not something a click can do");+ string addKey = await IsMacAsync().ConfigureAwait(false) ? "Meta" : "Control";+ bool first = true;+ foreach (var idx in want)+ {+ int oid = (await World.CallAsync(r.Frame, "optionId", r.Id, idx).ConfigureAwait(false))!.Value.GetInt32();+ var label = new Target(r.Frame, null) { Description = $"option #{idx}" };+ var option = new Resolved(r.Frame, oid);+ var mods = first ? Array.Empty<string>() : new[] { addKey };+ // A plain click on the first option replaces the selection; further options are+ // added with Ctrl/Cmd held, as a person does.+ await RetryAsync(api, label, d, async () =>+ {+ var box = await ScrollIntoViewAsync(option, cfg, d).ConfigureAwait(false);+ var (x, y) = PointIn(box, null, false, cfg);+ await HitAsync(option, x, y).ConfigureAwait(false);+ await MoveToAsync(x, y, cfg).ConfigureAwait(false);+ await HitAsync(option, Cursor.X, Cursor.Y).ConfigureAwait(false);+ await PressMouseAsync(cfg, false, MouseButton.Left, 1, null, mods).ConfigureAwait(false);+ }).ConfigureAwait(false);+ first = false;+ await Sleep(R(120, 300)).ConfigureAwait(false);+ }+ }++ public async Task DragAsync(Target source, Target dest, ActOpts o, string api)+ {+ var sub = new ActOpts { Deadline = DeadlineFor(source, o), Force = o.Force, HumanConfig = o.HumanConfig, Position = o.SourcePosition, Trial = o.Trial };+ await IdleAsync(CallCfg(o.HumanConfig)).ConfigureAwait(false);+ await HoverAsync(source, sub, api).ConfigureAwait(false);+ if (o.Trial)+ {+ await HoverAsync(dest, sub.With(c => { c.Position = o.TargetPosition; c.Nested = true; }), api).ConfigureAwait(false);+ return;+ }+ await Sleep(R(100, 200)).ConfigureAwait(false);+ await _raw.DownAsync().ConfigureAwait(false);+ try+ {+ await Sleep(R(80, 150)).ConfigureAwait(false);+ await HoverAsync(dest, sub.With(c => { c.Position = o.TargetPosition; c.Force = true; c.Nested = true; }), api).ConfigureAwait(false);+ await Sleep(R(80, 150)).ConfigureAwait(false);+ }+ finally { await _raw.UpAsync().ConfigureAwait(false); }+ }++ /// <summary>Focus without a click (Playwright's focus() is itself programmatic); the+ /// ElementHandle variant moves the cursor over the element first.</summary>+ public async Task FocusAsync(Target t, ActOpts o, string api, bool move = false)+ {+ var d = DeadlineFor(t, o);+ if (move) await HoverAsync(t, new ActOpts { Timeout = o.Timeout, HumanConfig = o.HumanConfig }, api).ConfigureAwait(false);+ var r = await RetryAsync(api, t, d, () => ResolveAsync(t)).ConfigureAwait(false);+ await World.CallAsync(r.Frame, "focus", r.Id).ConfigureAwait(false);+ }++ public async Task ScrollIntoViewIfNeededAsync(Target t, ActOpts o, string api)+ {+ var cfg = CallCfg(o.HumanConfig);+ var d = DeadlineFor(t, o);+ await EnsureCursorAsync(cfg).ConfigureAwait(false);+ await RetryAsync(api, t, d, async () =>+ {+ var r = await AttemptStatesAsync(t, new[] { "visible", "stable" }, false).ConfigureAwait(false);+ await ScrollIntoViewAsync(r, cfg, d).ConfigureAwait(false);+ }).ConfigureAwait(false);+ }++ // -- keyboard -----------------------------------------------------------++ private static bool IsAscii(string s) => s.Length > 0 && s.All(c => c <= 0x7F);+ private static bool IsUpper(char c) => c is >= 'A' and <= 'Z';++ /// <summary>Type <paramref name="text"/> key by key into the focused element of the frame.</summary>+ public async Task TypeTextAsync(string text, HumanConfig cfg, IFrame frame, JsonElement? info, float? delay)+ {+ string? tag = info is JsonElement i ? S(i, "tag") : null;+ bool mistypes = cfg.MistypeChance > 0 && tag != null && Fields.AllowsMistype(tag, S(info!.Value, "type"));+ var elements = System.Globalization.StringInfo.GetTextElementEnumerator(text);+ var chars = new List<string>();+ while (elements.MoveNext()) chars.Add((string)elements.Current);+ for (int k = 0; k < chars.Count; k++)+ {+ var ch = chars[k];+ if (!IsAscii(ch) || ch.Length != 1)+ {+ await Sleep(RR(cfg.KeyHold)).ConfigureAwait(false);+ await _raw.InsertTextAsync(ch).ConfigureAwait(false);+ }+ else+ {+ char c = ch[0];+ if (mistypes && char.IsLetterOrDigit(c) && HumanRandom.NextDouble() < cfg.MistypeChance)+ await TypoAsync(c, cfg, frame).ConfigureAwait(false);+ await TypeCharAsync(c, cfg).ConfigureAwait(false);+ }+ if (k < chars.Count - 1) await BetweenKeysAsync(cfg, delay).ConfigureAwait(false);+ }+ }++ private async Task TypoAsync(char ch, HumanConfig cfg, IFrame frame)+ {+ if (!HumanKeyboard.NearbyKeys.TryGetValue(char.ToLowerInvariant(ch), out var near) || near.Length == 0) return;+ char wrong = HumanRandom.Choice(near);+ if (IsUpper(ch)) wrong = char.ToUpperInvariant(wrong);+ var before = await ActiveValueAsync(frame).ConfigureAwait(false);+ await TypeCharAsync(wrong, cfg).ConfigureAwait(false);+ await Sleep(RR(cfg.MistypeDelayNotice)).ConfigureAwait(false);+ var after = await ActiveValueAsync(frame).ConfigureAwait(false);+ if (before != null && after == before)+ {+ // The page rejected the wrong key (mask / filter): nothing to undo.+ await Sleep(RR(cfg.MistypeDelayCorrect)).ConfigureAwait(false);+ return;+ }+ await _raw.KeyDownAsync("Backspace").ConfigureAwait(false);+ await Sleep(RR(cfg.KeyHold)).ConfigureAwait(false);+ await _raw.KeyUpAsync("Backspace").ConfigureAwait(false);+ await Sleep(RR(cfg.MistypeDelayCorrect)).ConfigureAwait(false);+ }++ private async Task<string?> ActiveValueAsync(IFrame frame)+ {+ try { return (await World.CallAsync(frame, "activeValue").ConfigureAwait(false)) is JsonElement v ? S(v, "value") : null; }+ catch (PlaywrightException) { return null; }+ }++ public async Task TypeCharAsync(char ch, HumanConfig cfg)+ {+ var key = ch.ToString();+ if (IsUpper(ch))+ {+ await _raw.KeyDownAsync("Shift").ConfigureAwait(false);+ await Sleep(RR(cfg.ShiftDownDelay)).ConfigureAwait(false);+ await _raw.KeyDownAsync(key).ConfigureAwait(false);+ await Sleep(RR(cfg.KeyHold)).ConfigureAwait(false);+ await _raw.KeyUpAsync(key).ConfigureAwait(false);+ await Sleep(RR(cfg.ShiftUpDelay)).ConfigureAwait(false);+ await _raw.KeyUpAsync("Shift").ConfigureAwait(false);+ }+ else if (HumanKeyboard.ShiftSymbols.Contains(ch))+ {+ var session = await World.SessionAsync().ConfigureAwait(false);+ var (code, vk) = HumanKeyboard.ShiftSymbolKey(ch);+ await _raw.KeyDownAsync("Shift").ConfigureAwait(false);+ await Sleep(RR(cfg.ShiftDownDelay)).ConfigureAwait(false);+ await session.SendAsync("Input.dispatchKeyEvent", new()+ {+ ["type"] = "keyDown", ["modifiers"] = 8, ["key"] = key, ["code"] = code,+ ["windowsVirtualKeyCode"] = vk, ["text"] = key, ["unmodifiedText"] = key,+ }).ConfigureAwait(false);+ await Sleep(RR(cfg.KeyHold)).ConfigureAwait(false);+ await session.SendAsync("Input.dispatchKeyEvent", new()+ {+ ["type"] = "keyUp", ["modifiers"] = 8, ["key"] = key, ["code"] = code, ["windowsVirtualKeyCode"] = vk,+ }).ConfigureAwait(false);+ await Sleep(RR(cfg.ShiftUpDelay)).ConfigureAwait(false);+ await _raw.KeyUpAsync("Shift").ConfigureAwait(false);+ }+ else+ {+ await _raw.KeyDownAsync(key).ConfigureAwait(false);+ await Sleep(RR(cfg.KeyHold)).ConfigureAwait(false);+ await _raw.KeyUpAsync(key).ConfigureAwait(false);+ }+ }++ private static Task BetweenKeysAsync(HumanConfig cfg, float? delay)+ {+ if (delay != null) return Sleep(delay.Value);+ if (HumanRandom.NextDouble() < cfg.TypingPauseChance) return Sleep(RR(cfg.TypingPauseRange));+ return Sleep(Math.Max(10, cfg.TypingDelay + (HumanRandom.NextDouble() - 0.5) * 2 * cfg.TypingDelaySpread));+ }++ /// <summary><c>page.Keyboard.TypeAsync</c>: no target; mistypes only where safe.</summary>+ public async Task KeyboardTypeAsync(string text, float? delay = null)+ {+ JsonElement? info = null;+ try { info = await World.CallAsync(_page.MainFrame, "activeValue").ConfigureAwait(false); }+ catch (PlaywrightException) { }+ if (info is JsonElement i && (S(i, "tag") == null || S(i, "tag") == "iframe")) info = null;+ await TypeTextAsync(text, Config, _page.MainFrame, info, delay).ConfigureAwait(false);+ }++ // -- raw mouse API ------------------------------------------------------++ public async Task MouseMoveAsync(double x, double y, int? steps = null)+ {+ if (steps != null)+ {+ await EnsureCursorAsync().ConfigureAwait(false);+ await _raw.MoveAsync(x, y, steps).ConfigureAwait(false);+ }+ else+ {+ await MoveToAsync(x, y, Config).ConfigureAwait(false);+ }+ Cursor.X = x; Cursor.Y = y;+ }++ public async Task MouseClickAsync(double x, double y, float? delay = null, MouseButton? button = null, int? clickCount = null)+ {+ await MoveToAsync(x, y, Config).ConfigureAwait(false);+ await PressMouseAsync(Config, false, button ?? MouseButton.Left, clickCount ?? 1, delay).ConfigureAwait(false);+ }+}diff --git a/dotnet/src/CloakBrowser/Human/HumanEngine.cs b/dotnet/src/CloakBrowser/Human/HumanEngine.csnew file mode 100644index 0000000..a54c887--- /dev/null+++ b/dotnet/src/CloakBrowser/Human/HumanEngine.cs@@ -0,0 +1,703 @@+using System.Reflection;+using System.Text.Json;+using Microsoft.Playwright;++namespace CloakBrowser.Human;++/// <summary>What an action is aimed at: a selector in a frame, or an element handle.</summary>+internal sealed class Target+{+ public Target(IFrame frame, string? selector, bool strict = false, IElementHandle? handle = null)+ {+ Frame = frame; Selector = selector; Strict = strict; Handle = handle;+ Description = selector != null ? $"locator({JsonSerializer.Serialize(selector)})" : "element handle";+ }++ public IFrame Frame { get; }+ public string? Selector { get; }+ public bool Strict { get; }+ public IElementHandle? Handle { get; }+ public string Description { get; set; }+}++internal readonly record struct Resolved(IFrame Frame, int Id);++internal sealed class Deadline+{+ private readonly long? _end;+ public Deadline(double timeoutMs)+ {+ Timeout = timeoutMs;+ _end = timeoutMs > 0 ? Environment.TickCount64 + (long)timeoutMs : null;+ }+ public double Timeout { get; }+ public double Remaining => _end == null ? double.PositiveInfinity : Math.Max(0, _end.Value - Environment.TickCount64);+ public bool Expired => _end != null && Environment.TickCount64 >= _end.Value;+}++/// <summary>Internal: the current attempt failed for a reason; retry until timeout.</summary>+internal sealed class RetryException : Exception+{+ public RetryException(string reason) : base(reason) { }+}++/// <summary>Options every humanized action understands (Playwright names + ours).</summary>+internal sealed class ActOpts+{+ public float? Timeout { get; set; }+ public bool Force { get; set; }+ public bool Trial { get; set; }+ public bool Strict { get; set; }+ public (double X, double Y)? Position { get; set; }+ public MouseButton? Button { get; set; }+ public int? ClickCount { get; set; }+ public float? Delay { get; set; }+ public IReadOnlyList<string>? Modifiers { get; set; }+ public (double X, double Y)? SourcePosition { get; set; }+ public (double X, double Y)? TargetPosition { get; set; }+ public IReadOnlyDictionary<string, object>? HumanConfig { get; set; }+ // internal+ public Deadline? Deadline { get; set; }+ public bool Nested { get; set; }+ public object[]? Aim { get; set; }++ public ActOpts With(Action<ActOpts> change)+ {+ var c = (ActOpts)MemberwiseClone();+ change(c);+ return c;+ }++ /// <summary>Read the Playwright options object of any action (they share property+ /// names but no base type).</summary>+ public static ActOpts From(object? o, IReadOnlyDictionary<string, object>? humanConfig = null)+ {+ var a = new ActOpts { HumanConfig = humanConfig };+ if (o == null) return a;+ object? P(string n) => o.GetType().GetProperty(n)?.GetValue(o);+ a.Timeout = P("Timeout") as float?;+ a.Force = P("Force") as bool? ?? false;+ a.Trial = P("Trial") as bool? ?? false;+ a.Strict = P("Strict") as bool? ?? false;+ a.Button = P("Button") as MouseButton?;+ a.ClickCount = P("ClickCount") as int?;+ a.Delay = P("Delay") as float?;+ if (P("Modifiers") is IEnumerable<KeyboardModifier> mods) a.Modifiers = mods.Select(m => m.ToString()).ToList();+ if (P("Position") is Position pos) a.Position = (pos.X, pos.Y);+ if (P("SourcePosition") is SourcePosition sp) a.SourcePosition = (sp.X, sp.Y);+ if (P("TargetPosition") is TargetPosition tp) a.TargetPosition = (tp.X, tp.Y);+ return a;+ }+}++internal sealed class Box+{+ public Rect Rect;+ public double Bl, Bt;+ public Rect Clip;+ public Rect Visible;+ public Rect? Scroller;+ public double X => Rect.X; public double Y => Rect.Y; public double Width => Rect.Width; public double Height => Rect.Height;+}++/// <summary>Original (un-humanized) input primitives of one page.</summary>+internal interface IRawInput+{+ Task MoveAsync(double x, double y, int? steps = null);+ Task DownAsync(MouseButton button = MouseButton.Left, int clickCount = 1);+ Task UpAsync(MouseButton button = MouseButton.Left, int clickCount = 1);+ Task WheelAsync(double dx, double dy);+ Task KeyDownAsync(string key);+ Task KeyUpAsync(string key);+ Task KeyPressAsync(string key, float? delay = null);+ Task InsertTextAsync(string text);+}++internal sealed class PlaywrightRawInput : IRawInput+{+ private readonly IMouse _m;+ private readonly IKeyboard _k;+ public PlaywrightRawInput(IMouse mouse, IKeyboard keyboard) { _m = mouse; _k = keyboard; }+ public Task MoveAsync(double x, double y, int? steps = null) =>+ _m.MoveAsync((float)x, (float)y, steps == null ? null : new MouseMoveOptions { Steps = steps });+ public Task DownAsync(MouseButton button = MouseButton.Left, int clickCount = 1) =>+ _m.DownAsync(new MouseDownOptions { Button = button, ClickCount = clickCount });+ public Task UpAsync(MouseButton button = MouseButton.Left, int clickCount = 1) =>+ _m.UpAsync(new MouseUpOptions { Button = button, ClickCount = clickCount });+ public Task WheelAsync(double dx, double dy) => _m.WheelAsync((float)dx, (float)dy);+ public Task KeyDownAsync(string key) => _k.DownAsync(key);+ public Task KeyUpAsync(string key) => _k.UpAsync(key);+ public Task KeyPressAsync(string key, float? delay = null) =>+ _k.PressAsync(key, delay == null ? null : new KeyboardPressOptions { Delay = delay });+ public Task InsertTextAsync(string text) => _k.InsertTextAsync(text);+}++/// <summary>Reads client-side Playwright .NET internals:+/// a locator's frame and selector string, and the page's default-timeout settings.</summary>+internal static class PlaywrightInternals+{+ private const BindingFlags Inst = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;++ public static (IFrame Frame, string Selector) LocatorParts(ILocator locator)+ {+ var t = locator.GetType();+ var frame = t.GetField("_frame", Inst)?.GetValue(locator) as IFrame;+ var selector = t.GetField("_selector", Inst)?.GetValue(locator) as string;+ if (frame == null || selector == null)+ throw new PlaywrightException(+ $"cloakbrowser humanize: unsupported locator implementation {t.FullName}; Microsoft.Playwright layout changed");+ return (frame, selector);+ }++ /// <summary>Playwright's effective timeout for an action: the explicit option, else+ /// the page / context default, else 30 s. 0 means no limit.</summary>+ public static double Timeout(IFrame frame, float? explicitTimeout)+ {+ if (explicitTimeout != null) return explicitTimeout.Value;+ var page = frame.Page;+ var ts = page.GetType().GetField("_timeoutSettings", Inst)?.GetValue(page);+ var m = ts?.GetType().GetMethod("Timeout", Inst, null, new[] { typeof(float?) }, null);+ if (m != null) return Convert.ToDouble(m.Invoke(ts, new object?[] { null }));+ return 30000;+ }++ public static IFrame HandleFrame(IElementHandle handle)+ {+ // An ElementHandle's parent object is its frame.+ var parent = handle.GetType().GetProperty("Parent", Inst)?.GetValue(handle);+ return parent as IFrame+ ?? throw new PlaywrightException("cloakbrowser humanize: cannot determine the frame of this element handle");+ }++ public static string HandleGuid(IElementHandle handle) =>+ handle.GetType().GetProperty("Guid", Inst)?.GetValue(handle) as string ?? handle.GetHashCode().ToString();+}++/// <summary>+/// Unified humanized action pipeline. Port of <c>cloakbrowser/human/engine.py</c>+/// (and <c>js/src/human/engine.ts</c>).+///+/// One implementation drives page / frame / locator / element-handle actions:+/// resolve (isolated world, Playwright selector engine, strict mode) -> wait for element+/// states -> scroll into view with mouse-wheel bursts (page, iframes, containers) ->+/// Bezier move to a point inside the visible part of the element -> hit-target check+/// (element and every ancestor iframe) -> press / type. Nothing falls back to+/// Playwright's stock actions, and failures throw+/// <see cref="PlaywrightException"/> / <see cref="System.TimeoutException"/>.+/// </summary>+internal sealed partial class HumanEngine+{+ public const string EnterFrame = " >> internal:control=enter-frame >> ";+ // Microsoft.Playwright .NET joins FrameLocator parts with an extra space+ // ("enter-frame >> "), so split on the marker with any surrounding whitespace.+ private static readonly System.Text.RegularExpressions.Regex EnterFrameSplit =+ new(@"\s*>>\s*internal:control=enter-frame\s*>>\s*", System.Text.RegularExpressions.RegexOptions.Compiled);+ private static readonly string[] ClickStates = { "visible", "enabled", "stable" };+ private static readonly string[] HoverStates = { "visible", "stable" };+ private static readonly string[] InputStates = { "visible", "enabled", "editable" };+ private static readonly string[] FocusStates = { "visible", "enabled" };+ private static readonly int[] RetryMs = { 0, 20, 100, 100, 500 };++ private readonly IPage _page;+ private readonly IRawInput _raw;+ private string? _platform;+ private readonly Dictionary<string, (IFrame Frame, int Ctx, int Id)> _handleIds = new();++ public HumanEngine(IPage page, HumanConfig cfg, CursorPosition cursor, IRawInput? raw = null)+ {+ _page = page;+ Config = cfg;+ Cursor = cursor;+ _raw = raw ?? new PlaywrightRawInput(page.Mouse, page.Keyboard);+ World = new HumanWorld(page);+ }++ public HumanConfig Config { get; }+ public CursorPosition Cursor { get; }+ public HumanWorld World { get; }+ public IRawInput Raw => _raw;+ public IPage Page => _page;++ private static Task Sleep(double ms) => ms > 0 ? Task.Delay(TimeSpan.FromMilliseconds(ms)) : Task.CompletedTask;+ private static double R(double lo, double hi) => HumanRandom.Rand(lo, hi);+ private static double RR(Range r) => HumanRandom.RandRange(r);++ public HumanConfig CallCfg(IReadOnlyDictionary<string, object>? overrides) =>+ overrides == null || overrides.Count == 0 ? Config : Config.With(overrides);++ public Deadline DeadlineFor(Target t, ActOpts o) =>+ o.Deadline ?? new Deadline(PlaywrightInternals.Timeout(t.Frame, o.Timeout));++ private static PlaywrightException Err(string msg) => new(msg);++ // -- persona ------------------------------------------------------------++ public async Task<string> PlatformAsync()+ {+ if (_platform == null)+ {+ try { _platform = (await World.CallAsync(_page.MainFrame, "platform").ConfigureAwait(false))?.GetString() ?? ""; }+ catch (PlaywrightException) { _platform = ""; }+ }+ return _platform;+ }++ public async Task<bool> IsMacAsync() => (await PlatformAsync().ConfigureAwait(false)).StartsWith("mac", StringComparison.OrdinalIgnoreCase);+ public async Task<string> SelectAllKeyAsync() => await IsMacAsync().ConfigureAwait(false) ? "Meta+a" : "Control+a";++ private async Task<string> ModifierAsync(string key) =>+ key == "ControlOrMeta" ? (await IsMacAsync().ConfigureAwait(false) ? "Meta" : "Control") : key;++ private async Task<string> KeysAsync(string key) =>+ key.Contains("ControlOrMeta") ? key.Replace("ControlOrMeta", await ModifierAsync("ControlOrMeta").ConfigureAwait(false)) : key;++ // -- cursor -------------------------------------------------------------++ public async Task EnsureCursorAsync(HumanConfig? cfg = null)+ {+ if (Cursor.Initialized) return;+ var c = cfg ?? Config;+ Cursor.X = RR(c.InitialCursorX);+ Cursor.Y = RR(c.InitialCursorY);+ await _raw.MoveAsync(Cursor.X, Cursor.Y).ConfigureAwait(false);+ Cursor.Initialized = true;+ }++ /// <summary>Bezier move from the current cursor position to (x, y), ending exactly there.</summary>+ public async Task MoveToAsync(double x, double y, HumanConfig cfg)+ {+ await EnsureCursorAsync(cfg).ConfigureAwait(false);+ double sx = Cursor.X, sy = Cursor.Y;+ double dist = Math.Sqrt((x - sx) * (x - sx) + (y - sy) * (y - sy));+ if (dist >= 1)+ {+ int steps = (int)Math.Max(cfg.MouseMinSteps, Math.Min(cfg.MouseMaxSteps, Math.Round(dist / cfg.MouseStepsDivisor)));+ var (cp1, cp2) = HumanMouse.RandomControlPoints(new Point(sx, sy), new Point(x, y));+ int burst = 0, burstSize = HumanRandom.RandIntRange(cfg.MouseBurstSize);+ for (int i = 1; i <= steps; i++)+ {+ double progress = (double)i / steps;+ if (i == steps) { await _raw.MoveAsync(x, y).ConfigureAwait(false); continue; }+ var pt = HumanMouse.Bezier(new Point(sx, sy), cp1, cp2, new Point(x, y), HumanMouse.EaseInOut(progress));+ double wobble = Math.Sin(Math.PI * progress) * cfg.MouseWobbleMax;+ await _raw.MoveAsync(Math.Round(pt.X + (HumanRandom.NextDouble() - 0.5) * 2 * wobble),+ Math.Round(pt.Y + (HumanRandom.NextDouble() - 0.5) * 2 * wobble)).ConfigureAwait(false);+ if (++burst >= burstSize) { await Sleep(RR(cfg.MouseBurstPause)).ConfigureAwait(false); burst = 0; }+ }+ if (HumanRandom.NextDouble() < cfg.MouseOvershootChance)+ {+ double angle = Math.Atan2(y - sy, x - sx), over = RR(cfg.MouseOvershootPx);+ await _raw.MoveAsync(Math.Round(x + Math.Cos(angle) * over), Math.Round(y + Math.Sin(angle) * over)).ConfigureAwait(false);+ await Sleep(R(30, 70)).ConfigureAwait(false);+ await _raw.MoveAsync(x, y).ConfigureAwait(false);+ }+ }+ Cursor.X = x; Cursor.Y = y;+ }++ public async Task IdleAsync(HumanConfig cfg)+ {+ if (!cfg.IdleBetweenActions) return;+ await EnsureCursorAsync(cfg).ConfigureAwait(false);+ long end = Environment.TickCount64 + (long)(R(cfg.IdleBetweenDuration.Min, cfg.IdleBetweenDuration.Max) * 1000);+ double x = Cursor.X, y = Cursor.Y;+ while (Environment.TickCount64 < end)+ {+ x += (HumanRandom.NextDouble() - 0.5) * 2 * cfg.IdleDriftPx;+ y += (HumanRandom.NextDouble() - 0.5) * 2 * cfg.IdleDriftPx;+ await _raw.MoveAsync(Math.Round(x), Math.Round(y)).ConfigureAwait(false);+ await Sleep(Math.Min(RR(cfg.IdlePauseRange), Math.Max(0, end - Environment.TickCount64))).ConfigureAwait(false);+ }+ await _raw.MoveAsync(Cursor.X, Cursor.Y).ConfigureAwait(false); // drift is noise, not a new position+ }++ // -- resolution ---------------------------------------------------------++ /// <summary>Resolve once. Throws <see cref="RetryException"/> (not yet there) or a final error.</summary>+ public async Task<Resolved> ResolveAsync(Target t)+ {+ if (t.Handle != null) return await ResolveHandleAsync(t.Handle).ConfigureAwait(false);+ var frame = t.Frame;+ var parts = EnterFrameSplit.Split(t.Selector!);+ for (int i = 0; i < parts.Length; i++)+ {+ var res = (await World.CallAsync(frame, "resolve", parts[i], t.Strict, 0).ConfigureAwait(false))!.Value;+ var status = res.GetProperty("status").GetString();+ if (status == "none") throw new RetryException($"waiting for {t.Description}");+ if (status is "strict" or "error") throw Err(res.GetProperty("message").GetString() ?? status);+ int id = res.GetProperty("id").GetInt32();+ if (i == parts.Length - 1) return new Resolved(frame, id);+ frame = await World.ContentFrameAsync(frame, id).ConfigureAwait(false)+ ?? throw new RetryException($"waiting for the frame of {t.Description}");+ }+ throw Err("unreachable");+ }++ public async Task<Resolved> ResolveHandleAsync(IElementHandle handle)+ {+ var frame = PlaywrightInternals.HandleFrame(handle);+ var guid = PlaywrightInternals.HandleGuid(handle);+ // Element ids are local to one isolated world, and a new document gets a new+ // world: an id cached before a navigation may now name a different element.+ int ctx = await World.ContextIdAsync(frame).ConfigureAwait(false);+ if (_handleIds.TryGetValue(guid, out var cached) && cached.Frame == frame && cached.Ctx == ctx &&+ await World.CallAsync(frame, "connected", cached.Id).ConfigureAwait(false) is { ValueKind: JsonValueKind.True })+ return new Resolved(frame, cached.Id);+ // An ElementHandle carries no identity our context can read, so find the element+ // with exactly its border box.+ var box = await handle.BoundingBoxAsync().ConfigureAwait(false);+ if (box == null)+ {+ // Resolved in an earlier document of this frame and gone now+ // (a same-document navigation keeps the element, and its box).+ if (_handleIds.TryGetValue(guid, out var old) && old.Frame == frame) throw Err("Element is not attached to the DOM");+ throw new RetryException("element is not visible");+ }+ var (ox, oy, _) = await World.FrameGeometryAsync(frame).ConfigureAwait(false);+ var res = (await World.CallAsync(frame, "matchRect", box.X - ox, box.Y - oy, box.Width, box.Height).ConfigureAwait(false))!.Value;+ if (res.GetProperty("count").GetInt32() != 1)+ throw Err("cloakbrowser humanize: cannot identify the element behind this ElementHandle inside the isolated " ++ "world (it shares its box with another element); use a Locator instead");+ int id = res.GetProperty("id").GetInt32();+ _handleIds[guid] = (frame, ctx, id);+ return new Resolved(frame, id);+ }++ public Task<Resolved> WaitForAsync(Target t, string[] states, Deadline d, string api, bool force = false) =>+ RetryAsync(api, t, d, () => AttemptStatesAsync(t, states, force));++ public async Task<Resolved> AttemptStatesAsync(Target t, string[] states, bool force)+ {+ var r = await ResolveAsync(t).ConfigureAwait(false);+ if (force) return r;+ var res = await World.CallAsync(r.Frame, "states", r.Id, states).ConfigureAwait(false);+ if (res == null || res.Value.ValueKind == JsonValueKind.Null) return r;+ if (res.Value.TryGetProperty("error", out var e)) throw Err(e.GetString() ?? "state check failed");+ var missing = res.Value.GetProperty("missing").GetString();+ if (missing == "attached")+ {+ if (t.Handle != null) throw Err("Element is not attached to the DOM");+ throw new RetryException("element was detached from the DOM, retrying");+ }+ throw new RetryException($"element is not {missing}");+ }++ public async Task<T> RetryAsync<T>(string api, Target t, Deadline d, Func<Task<T>> attempt)+ {+ var reasons = new List<string>();+ void Note(string r) { if (reasons.Count == 0 || reasons[^1] != r) reasons.Add(r); }+ for (int n = 0; ; n++)+ {+ try+ {+ return await attempt().ConfigureAwait(false);+ }+ catch (StaleElementException)+ {+ if (t.Handle != null) throw Err($"{api}: Element is not attached to the DOM");+ Note("element was detached from the DOM, retrying");+ }+ catch (RetryException r)+ {+ Note(r.Message);+ }+ catch (PlaywrightException e) when (!e.Message.StartsWith(api, StringComparison.Ordinal))+ {+ throw new PlaywrightException($"{api}: {e.Message}", e);+ }+ if (d.Expired)+ {+ var log = string.Join("\n", new[] { $"waiting for {t.Description}" }.Concat(reasons.TakeLast(5)).Select(r => $" - {r}"));+ throw new System.TimeoutException($"{api}: Timeout {Math.Round(d.Timeout)}ms exceeded.\nCall log:\n{log}");+ }+ await Sleep(Math.Min(RetryMs[Math.Min(n, RetryMs.Length - 1)], d.Remaining)).ConfigureAwait(false);+ }+ }++ public Task RetryAsync(string api, Target t, Deadline d, Func<Task> attempt) =>+ RetryAsync<bool>(api, t, d, async () => { await attempt().ConfigureAwait(false); return true; });++ // -- geometry -----------------------------------------------------------++ private static double D(JsonElement e, string p) => e.GetProperty(p).GetDouble();++ /// <summary>Element border box in viewport coordinates plus its visible clip.</summary>+ public async Task<Box> ElementBoxAsync(Resolved r)+ {+ var g = await World.CallAsync(r.Frame, "geometry", r.Id).ConfigureAwait(false);+ if (g == null || g.Value.ValueKind == JsonValueKind.Null) throw new StaleElementException();+ var (ox, oy, clip) = await World.FrameGeometryAsync(r.Frame).ConfigureAwait(false);+ var gv = g.Value;+ var box = new Box+ {+ Rect = new Rect(D(gv, "x") + ox, D(gv, "y") + oy, D(gv, "width"), D(gv, "height")),+ Bl = D(gv, "bl"), Bt = D(gv, "bt"),+ };+ var sc = await World.CallAsync(r.Frame, "scroller", r.Id).ConfigureAwait(false);+ if (sc is JsonElement s && s.ValueKind == JsonValueKind.Object)+ {+ var srect = new Rect(D(s, "x") + ox, D(s, "y") + oy, D(s, "width"), D(s, "height"));+ clip = Rect.Intersect(clip, srect);+ box.Scroller = srect;+ }+ box.Clip = clip;+ box.Visible = Rect.Intersect(clip, box.Rect);+ return box;+ }++ // -- scrolling ----------------------------------------------------------++ /// <summary>Wheel-scroll until the element sits inside its visible clip (and, for the+ /// main document, inside <c>ScrollTargetZone</c> when the page can still scroll that way).</summary>+ public async Task<Box> ScrollIntoViewAsync(Resolved r, HumanConfig cfg, Deadline d)+ {+ var box = await ElementBoxAsync(r).ConfigureAwait(false);+ var (vw, vh) = await World.ViewportAsync().ConfigureAwait(false);+ int stalled = 0, rounds = 0;+ bool overshot = false;+ while (stalled < 2 && rounds < 40 && !d.Expired)+ {+ var (dx, dy) = await NeededScrollAsync(r, box, vw, vh, cfg).ConfigureAwait(false);+ if (Math.Abs(dx) < 1 && Math.Abs(dy) < 1) break;+ rounds++;+ var area = box.Clip.Width > 4 && box.Clip.Height > 4 ? box.Clip : new Rect(0, 0, vw, vh);+ if (!area.Contains(Cursor.X, Cursor.Y))+ {+ await MoveToAsync(area.X + area.Width * R(0.3, 0.7), area.Y + area.Height * R(0.3, 0.7), cfg).ConfigureAwait(false);+ await Sleep(RR(cfg.ScrollPreMoveDelay)).ConfigureAwait(false);+ }+ double bx = box.X, by = box.Y;+ if (Math.Abs(dy) >= 1)+ {+ await WheelBurstAsync(0, dy, cfg, d).ConfigureAwait(false);+ if (!overshot)+ {+ overshot = true;+ await OvershootAsync(dy, cfg, d).ConfigureAwait(false);+ }+ }+ if (Math.Abs(dx) >= 1) await WheelBurstAsync(dx, 0, cfg, d).ConfigureAwait(false);+ await Sleep(Math.Min(RR(cfg.ScrollSettleDelay), d.Remaining)).ConfigureAwait(false);+ box = await ElementBoxAsync(r).ConfigureAwait(false);+ stalled = Math.Abs(box.X - bx) + Math.Abs(box.Y - by) < 1 ? stalled + 1 : 0;+ }+ return box;+ }++ private async Task<(double Dx, double Dy)> NeededScrollAsync(Resolved r, Box box, double vw, double vh, HumanConfig cfg)+ {+ var clip = box.Clip;+ if (clip.Width <= 0 || clip.Height <= 0)+ return (0, box.Y + box.Height / 2 - vh / 2); // the frame/container itself is out of view+ double dx = 0, dy = 0, top = box.Y, bottom = box.Y + box.Height;+ var zone = cfg.ScrollTargetZone;+ bool mainDoc = r.Frame.ParentFrame == null && box.Scroller == null;+ if (mainDoc && box.Height <= vh * (zone.Max - zone.Min))+ {+ if (top < vh * zone.Min || bottom > vh * zone.Max)+ {+ dy = top + box.Height / 2 - vh * R(zone.Min, zone.Max);+ if (top >= clip.Y - 1 && bottom <= clip.Y + clip.Height + 1)+ {+ // Fully visible but off-centre: only if the page can scroll that way.+ var doc = (await World.CallAsync(_page.MainFrame, "doc").ConfigureAwait(false))!.Value;+ if ((dy < 0 && D(doc, "y") <= 0) || (dy > 0 && D(doc, "y") >= D(doc, "maxY"))) dy = 0;+ }+ }+ }+ else if (box.Height <= clip.Height)+ {+ if (top < clip.Y - 1 || bottom > clip.Y + clip.Height + 1) dy = top + box.Height / 2 - (clip.Y + clip.Height / 2);+ }+ else if (box.Visible.Height < clip.Height * 0.5)+ {+ dy = top - clip.Y - clip.Height * 0.1;+ }+ // Horizontal (#521): containment only.+ double left = box.X, right = box.X + box.Width;+ if (box.Width <= clip.Width)+ {+ if (left < clip.X - 1 || right > clip.X + clip.Width + 1) dx = left + box.Width / 2 - (clip.X + clip.Width / 2);+ }+ else if (box.Visible.Width <= 0)+ {+ dx = left - clip.X;+ }+ return (dx, dy);+ }++ /// <summary>Sometimes scroll a little past the target, pause, and wheel back+ /// (<c>ScrollOvershootChance</c> / <c>ScrollOvershootPx</c>). The next round of+ /// <see cref="ScrollIntoViewAsync"/> fixes whatever is left.</summary>+ private async Task OvershootAsync(double dy, HumanConfig cfg, Deadline d)+ {+ if (HumanRandom.NextDouble() >= cfg.ScrollOvershootChance || d.Expired) return;+ int sign = dy > 0 ? 1 : -1;+ await WheelBurstAsync(0, Math.Round(RR(cfg.ScrollOvershootPx)) * sign, cfg, d).ConfigureAwait(false);+ await Sleep(Math.Min(RR(cfg.ScrollSettleDelay), d.Remaining)).ConfigureAwait(false);+ int corrections = HumanRandom.RandInt(1, 2);+ for (int i = 0; i < corrections && !d.Expired; i++)+ {+ await WheelBurstAsync(0, Math.Round(R(40, 80)) * -sign, cfg, d).ConfigureAwait(false);+ await Sleep(Math.Min(R(100, 250), d.Remaining)).ConfigureAwait(false);+ }+ }++ /// <summary>One logical scroll: accelerate -> cruise -> decelerate in wheel ticks.</summary>+ public async Task WheelBurstAsync(double dx, double dy, HumanConfig cfg, Deadline? d = null)+ {+ double total = dy != 0 ? Math.Abs(dy) : Math.Abs(dx);+ int sign = (dy != 0 ? dy : dx) > 0 ? 1 : -1;+ int accel = HumanRandom.RandIntRange(cfg.ScrollAccelSteps), decel = HumanRandom.RandIntRange(cfg.ScrollDecelSteps);+ double avg = (cfg.ScrollDeltaBase.Min + cfg.ScrollDeltaBase.Max) / 2;+ int ticks = Math.Max(1, (int)Math.Ceiling(total / avg));+ double sent = 0;+ for (int i = 0; i < ticks; i++)+ {+ if (sent >= total || (d?.Expired ?? false)) break;+ double pause = i < accel || i >= ticks - decel ? RR(cfg.ScrollPauseSlow) : RR(cfg.ScrollPauseFast);+ double tick = Math.Min(total - sent, RR(cfg.ScrollDeltaBase) * (1 + (HumanRandom.NextDouble() - 0.5) * 2 * cfg.ScrollDeltaVariance));+ double left = tick;+ while (left > 0.5)+ {+ double chunk = Math.Min(left, R(20, 40));+ double step = Math.Round(chunk) * sign;+ if (step != 0) await _raw.WheelAsync(dx != 0 ? step : 0, dy != 0 ? step : 0).ConfigureAwait(false);+ left -= chunk;+ await Sleep(R(8, 20)).ConfigureAwait(false);+ }+ sent += tick;+ await Sleep(pause).ConfigureAwait(false);+ }+ }++ // -- pointer ------------------------------------------------------------++ private static (double X, double Y) PointIn(Box box, (double X, double Y)? position, bool isInput, HumanConfig cfg)+ {+ if (position is { } p) return (box.X + box.Bl + p.X, box.Y + box.Bt + p.Y);+ var vis = box.Visible;+ if (vis.Width <= 0 || vis.Height <= 0) throw new RetryException("element is outside of the viewport");+ var full = HumanMouse.ClickTarget(new BoundingBox(box.X, box.Y, box.Width, box.Height), isInput, cfg);+ return (Math.Min(Math.Max(full.X, vis.X + 1), vis.X + vis.Width - 1),+ Math.Min(Math.Max(full.Y, vis.Y + 1), vis.Y + vis.Height - 1));+ }++ /// <summary>Exact aim points: a date-editor segment, or a fraction along a slider.</summary>+ private static (double X, double Y) AimPoint(Box box, object[] aim)+ {+ double x, y;+ if ((string)aim[0] == "segment")+ {+ var seg = (EditorField)aim[1];+ x = box.X + seg.Dx + R(-2, 2); y = box.Y + seg.Dy + R(-2, 2);+ }+ else+ {+ double frac = (double)aim[1]; bool vertical = (bool)aim[2];+ if (vertical)+ {+ double inset = Math.Min(8, box.Height / 4);+ y = box.Y + box.Height - inset - frac * (box.Height - 2 * inset); x = box.X + box.Width / 2;+ }+ else+ {+ double inset = Math.Min(8, box.Width / 4);+ x = box.X + inset + frac * (box.Width - 2 * inset); y = box.Y + box.Height / 2 + R(-1.5, 1.5);+ }+ }+ if (!box.Visible.Contains(x, y)) throw new RetryException("element is outside of the viewport");+ return (x, y);+ }++ internal async Task HitAsync(Resolved r, double x, double y)+ {+ var (ox, oy, clip) = await World.FrameGeometryAsync(r.Frame).ConfigureAwait(false);+ if (!clip.Contains(x, y)) throw new RetryException("element is outside of the viewport");+ var desc = await World.CallAsync(r.Frame, "hit", r.Id, x - ox, y - oy).ConfigureAwait(false);+ string? d = desc is { ValueKind: JsonValueKind.String } s ? s.GetString() : null;+ if (d == null && r.Frame.ParentFrame != null) d = await World.OwnersHitAsync(r.Frame, x, y).ConfigureAwait(false);+ if (d != null) throw new RetryException($"{d} intercepts pointer events");+ }++ private async Task<bool> IsInputAsync(Resolved r)+ {+ var info = (await World.CallAsync(r.Frame, "info", r.Id).ConfigureAwait(false))!.Value;+ var tag = info.GetProperty("tag").GetString();+ return tag is "input" or "textarea" || info.GetProperty("editable").GetBoolean();+ }++ public delegate Task PointerAct(Resolved r, double x, double y, HumanConfig cfg);++ /// <summary>Shared scroll -> move -> hit-check -> action sequence. <paramref name="hold"/>:+ /// modifier names held down while the cursor travels to the target (Playwright's hover+ /// modifiers).</summary>+ public async Task<Resolved> PointerActionAsync(string api, Target t, ActOpts o, string[] states,+ bool? isInputHint = null, PointerAct? action = null, IReadOnlyList<string>? hold = null)+ {+ var cfg = CallCfg(o.HumanConfig);+ var d = DeadlineFor(t, o);+ await EnsureCursorAsync(cfg).ConfigureAwait(false);+ if (!(o.Nested || o.Deadline != null)) await IdleAsync(cfg).ConfigureAwait(false);+ return await RetryAsync(api, t, d, async () =>+ {+ var r = await AttemptStatesAsync(t, states, o.Force).ConfigureAwait(false);+ var box = await ScrollIntoViewAsync(r, cfg, d).ConfigureAwait(false);+ bool isInput = isInputHint ?? await IsInputAsync(r).ConfigureAwait(false);+ var (x, y) = o.Aim != null ? AimPoint(box, o.Aim) : PointIn(box, o.Position, isInput, cfg);+ if (!o.Force) await HitAsync(r, x, y).ConfigureAwait(false);+ if (o.Trial) return r;+ var keys = new List<string>();+ foreach (var m in hold ?? Array.Empty<string>()) keys.Add(await ModifierAsync(m).ConfigureAwait(false));+ foreach (var k in keys) await _raw.KeyDownAsync(k).ConfigureAwait(false);+ try+ {+ await MoveToAsync(x, y, cfg).ConfigureAwait(false);+ }+ finally+ {+ for (int i = keys.Count - 1; i >= 0; i--) await _raw.KeyUpAsync(keys[i]).ConfigureAwait(false);+ }+ // The page may replace or remove the target while the cursor travels; never+ // press on whatever is under it now (even with force). Locators re-resolve.+ if (await World.CallAsync(r.Frame, "connected", r.Id).ConfigureAwait(false) is not { ValueKind: JsonValueKind.True })+ throw new StaleElementException();+ if (!o.Force) await HitAsync(r, Cursor.X, Cursor.Y).ConfigureAwait(false);+ if (action != null) await action(r, Cursor.X, Cursor.Y, cfg).ConfigureAwait(false);+ return r;+ }).ConfigureAwait(false);+ }++ public async Task PressMouseAsync(HumanConfig cfg, bool isInput, MouseButton button = MouseButton.Left,+ int clickCount = 1, float? delay = null, IReadOnlyList<string>? modifiers = null)+ {+ var mods = new List<string>();+ foreach (var m in modifiers ?? Array.Empty<string>()) mods.Add(await ModifierAsync(m).ConfigureAwait(false));+ await Sleep(RR(isInput ? cfg.ClickAimDelayInput : cfg.ClickAimDelayButton)).ConfigureAwait(false);+ foreach (var m in mods) await _raw.KeyDownAsync(m).ConfigureAwait(false);+ try+ {+ int count = Math.Max(1, clickCount);+ for (int n = 1; n <= count; n++)+ {+ double hold = delay ?? RR(isInput ? cfg.ClickHoldInput : cfg.ClickHoldButton);+ await _raw.DownAsync(button, n).ConfigureAwait(false);+ await Sleep(hold).ConfigureAwait(false);+ await _raw.UpAsync(button, n).ConfigureAwait(false);+ if (n < count) await Sleep(delay ?? R(60, 140)).ConfigureAwait(false);+ }+ }+ finally+ {+ for (int i = mods.Count - 1; i >= 0; i--) await _raw.KeyUpAsync(mods[i]).ConfigureAwait(false);+ }+ }+}++/// <summary>Shared virtual cursor position of one page.</summary>+internal sealed class CursorPosition+{+ public double X;+ public double Y;+ public bool Initialized;+}diff --git a/dotnet/src/CloakBrowser/Human/HumanKeyboard.cs b/dotnet/src/CloakBrowser/Human/HumanKeyboard.csindex a19796d..fac0809 100644--- a/dotnet/src/CloakBrowser/Human/HumanKeyboard.cs+++ b/dotnet/src/CloakBrowser/Human/HumanKeyboard.cs@@ -88,6 +88,10 @@ public static class HumanKeyboard['~'] = 192,};+ /// <summary>CDP <c>code</c> and Windows virtual key code of a shift symbol's physical key.</summary>+ internal static (string Code, int KeyCode) ShiftSymbolKey(char ch) =>+ (ShiftSymbolCodes.TryGetValue(ch, out var c) ? c : "", ShiftSymbolKeyCodes.TryGetValue(ch, out var k) ? k : 0);+private static bool IsAscii(char c) => c <= 0x7F;private static bool IsAlnum(char c) => char.IsLetterOrDigit(c) && IsAscii(c);diff --git a/dotnet/src/CloakBrowser/Human/HumanMouse.cs b/dotnet/src/CloakBrowser/Human/HumanMouse.csindex e11ea06..edb3bc1 100644--- a/dotnet/src/CloakBrowser/Human/HumanMouse.cs+++ b/dotnet/src/CloakBrowser/Human/HumanMouse.cs@@ -25,7 +25,7 @@ public interface IRawMousepublic static class HumanMouse{/// <summary>Cubic ease-in-out, matching the Python implementation.</summary>- private static double EaseInOut(double t)+ internal static double EaseInOut(double t){if (t < 0.5)return 4 * t * t * t;@@ -33,7 +33,7 @@ public static class HumanMouse}/// <summary>Cubic Bezier interpolation between four control points.</summary>- private static Point Bezier(Point p0, Point p1, Point p2, Point p3, double t)+ internal static Point Bezier(Point p0, Point p1, Point p2, Point p3, double t){double u = 1 - t;double uu = u * u;@@ -46,7 +46,7 @@ public static class HumanMouse}/// <summary>Generate two random control points biased perpendicular to the path.</summary>- private static (Point, Point) RandomControlPoints(Point start, Point end)+ internal static (Point, Point) RandomControlPoints(Point start, Point end){double dx = end.X - start.X;double dy = end.Y - start.Y;diff --git a/dotnet/src/CloakBrowser/Human/HumanPage.cs b/dotnet/src/CloakBrowser/Human/HumanPage.csindex ba63e0d..a10ff13 100644--- a/dotnet/src/CloakBrowser/Human/HumanPage.cs+++ b/dotnet/src/CloakBrowser/Human/HumanPage.cs@@ -1,4 +1,3 @@-using System.Runtime.InteropServices;using Microsoft.Playwright;namespace CloakBrowser.Human;@@ -6,10 +5,10 @@ namespace CloakBrowser.Human;/// <summary>Options accepted by the humanized action methods on <see cref="HumanPage"/>.</summary>public sealed class HumanActionOptions{- /// <summary>Overall timeout in milliseconds (default 30000).</summary>+ /// <summary>Overall timeout in milliseconds (default 30000; 0 = no limit).</summary>public double Timeout { get; set; } = 30000;- /// <summary>Skip pre-actionability and coverage rejection; exact target identity remains enforced.</summary>+ /// <summary>Skip actionability waits and the hit-target check (like Playwright's <c>Force</c>).</summary>public bool Force { get; set; }/// <summary>Delay in milliseconds between keydown and keyup for press actions.</summary>@@ -20,673 +19,143 @@ public sealed class HumanActionOptions}/// <summary>-/// A human-like wrapper around a Playwright <see cref="IPage"/>.+/// Explicit human-like API over a Playwright <see cref="IPage"/>.///-/// .NET's Playwright exposes sealed interfaces (<see cref="IPage"/>, <see cref="ILocator"/>,-/// etc.) that cannot be monkey-patched the way the Python/JS implementations replace-/// methods at runtime. Instead, this wrapper exposes the same humanized behaviors as-/// explicit methods. The underlying real page is always available via <see cref="Page"/>-/// for anything not covered here.-///-/// Direct behavioral port of <c>patch_page</c> in <c>cloakbrowser/human/__init__.py</c>:-/// every action runs Playwright-style actionability checks, a Bezier-curve mouse-/// approach with optional scroll-into-view, pointer-events verification, and human-/// typing through the CDP isolated world / dispatchKeyEvent stealth path.+/// The transparent wrappers (<c>Humanize.PageAsync</c>, <c>LaunchAsync(Humanize = true)</c>)+/// are the recommended way to humanize; this class exposes the same engine as explicit+/// methods for code that prefers to keep the raw <see cref="IPage"/> untouched. Every call+/// goes through the unified humanize engine: Playwright's selector engine in an isolated+/// world, actionability waits, wheel scrolling, Bezier mouse motion, a hit-target check+/// and human typing. Selectors are resolved in the main frame, non-strict (like+/// <c>page.ClickAsync</c>)./// </summary>public sealed class HumanPage{- private static readonly bool IsMac = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);- private static readonly string SelectAll = IsMac ? "Meta+a" : "Control+a";-private readonly IPage _page;- private readonly HumanConfig _cfg;- private readonly CursorState _cursor = new();-- private readonly IRawMouse _rawMouse;- private readonly IRawKeyboard _rawKeyboard;- private readonly IRawScrollPage _scrollPage;- private readonly IRawEvaluator _evaluator;+ private readonly HumanEngine _engine;- private IsolatedWorld? _stealth;- private IRawCdpSession? _cdpSession;- private bool _stealthInitialized;-- /// <summary>The underlying real Playwright page.</summary>+ /// <summary>The underlying raw Playwright page.</summary>public IPage Page => _page;- /// <summary>The resolved behavior configuration for this page.</summary>- public HumanConfig Config => _cfg;+ /// <summary>The page-level humanize config.</summary>+ public HumanConfig Config => _engine.Config;- /// <summary>The current virtual cursor position (x, y).</summary>- public (double X, double Y) Cursor => (_cursor.X, _cursor.Y);+ /// <summary>Current virtual cursor position.</summary>+ public (double X, double Y) Cursor => (_engine.Cursor.X, _engine.Cursor.Y);- /// <summary>Create a humanized wrapper. Use <see cref="CreateAsync(IPage, HumanConfig?)"/> for the- /// stealth-enabled variant (recommended).</summary>+ /// <summary>Wrap <paramref name="page"/>. Prefer <see cref="CreateAsync"/>, which also+ /// places the virtual cursor.</summary>public HumanPage(IPage page, HumanConfig? cfg = null){- _page = page;- _cfg = cfg ?? new HumanConfig();- _rawMouse = new PlaywrightRawMouse(page.Mouse);- _rawKeyboard = new PlaywrightRawKeyboard(page.Keyboard);- _scrollPage = new PlaywrightScrollPage(page, GetStealthRequiredAsync);- _evaluator = new PlaywrightEvaluator(page);-- // Invalidate the isolated world on any main-frame nav, not just goto, so- // click/form navigations don't leave it bound to a stale doc (#507).- _page.FrameNavigated += (_, frame) =>- {- if (frame == _page.MainFrame) _stealth?.Invalidate();- };+ _page = page ?? throw new ArgumentNullException(nameof(page));+ _engine = new HumanEngine(page, cfg ?? new HumanConfig(), new CursorPosition());}- /// <summary>- /// Create a humanized page and initialize the CDP isolated world + dispatchKeyEvent- /// stealth path. Selector DOM reads fail explicitly when the isolated world is unavailable.- /// </summary>+ /// <summary>Create a <see cref="HumanPage"/> and place the virtual cursor.</summary>public static async Task<HumanPage> CreateAsync(IPage page, HumanConfig? cfg = null){var hp = new HumanPage(page, cfg);- await hp.InitStealthAsync().ConfigureAwait(false);- await hp.InitCursorAsync().ConfigureAwait(false);+ try { await hp._engine.EnsureCursorAsync().ConfigureAwait(false); }+ catch (PlaywrightException) { /* viewport not ready yet; done on the first action */ }return hp;}- private async Task InitStealthAsync()- {- if (_stealthInitialized) return;- _stealthInitialized = true;- try- {- _stealth = new IsolatedWorld(_page);- var session = await _stealth.GetCdpSessionAsync().ConfigureAwait(false);- _cdpSession = new PlaywrightCdpSession(session);- }- catch (Exception)- {- _stealth = null;- _cdpSession = null;- CloakLog.Debug("Could not create CDP session - stealth features disabled");- }- }-- private async Task InitCursorAsync()- {- // Initialize cursor immediately so it doesn't visibly jump from (0,0).- _cursor.X = HumanRandom.Rand(_cfg.InitialCursorX.Min, _cfg.InitialCursorX.Max);- _cursor.Y = HumanRandom.Rand(_cfg.InitialCursorY.Min, _cfg.InitialCursorY.Max);- try- {- await _rawMouse.MoveAsync(_cursor.X, _cursor.Y).ConfigureAwait(false);- _cursor.Initialized = true;- }- catch (Exception) { /* viewport may not be ready yet */ }- }-- private async Task EnsureCursorInitAsync()- {- if (!_cursor.Initialized)- {- _cursor.X = HumanRandom.Rand(_cfg.InitialCursorX.Min, _cfg.InitialCursorX.Max);- _cursor.Y = HumanRandom.Rand(_cfg.InitialCursorY.Min, _cfg.InitialCursorY.Max);- await _rawMouse.MoveAsync(_cursor.X, _cursor.Y).ConfigureAwait(false);- _cursor.Initialized = true;- }- }-- private HumanConfig MergeCfg(HumanActionOptions? opts) =>- opts?.HumanConfig == null ? _cfg : _cfg.With(opts.HumanConfig);+ private Target T(string selector) => new(_page.MainFrame, selector);- private static double RemainingMs(double deadline) => Actionability.RemainingMs(deadline);+ private static ActOpts O(HumanActionOptions? o) => o == null+ ? new ActOpts()+ : new ActOpts { Timeout = (float)o.Timeout, Force = o.Force, Delay = o.Delay, HumanConfig = o.HumanConfig };- private async Task<IsolatedWorld> GetStealthRequiredAsync()- {- await InitStealthAsync().ConfigureAwait(false);- return _stealth ?? throw new StealthWorldUnavailableError();- }+ // -- navigation ---------------------------------------------------------- private async Task<StealthSnapshot> SelectorSnapshotAsync(string selector)- {- var world = await GetStealthRequiredAsync().ConfigureAwait(false);- var (status, snapshot) = await StealthDom.SnapshotAsync(world, selector).ConfigureAwait(false);- return status switch- {- StealthStatus.Ok when snapshot != null => snapshot.Value,- StealthStatus.NotFound => throw new ElementNotAttachedError(selector),- StealthStatus.Unsupported => throw new UnsupportedHumanizeSelectorError(selector),- _ => throw new StealthEvaluationError(selector),- };- }+ /// <summary>Navigate to a URL (isolated worlds are re-created per document automatically).</summary>+ public Task<IResponse?> GotoAsync(string url, PageGotoOptions? options = null) => _page.GotoAsync(url, options);- private async Task<bool> IsSelectorFocusedAsync(string selector) =>- (await SelectorSnapshotAsync(selector).ConfigureAwait(false)).Focused;-- private async Task<BoundingBox?> GetBoxAsync(string selector, double timeoutMs)- {- var world = await GetStealthRequiredAsync().ConfigureAwait(false);- double deadline = Environment.TickCount64 + Math.Max(0, timeoutMs);- var result = await StealthDom.BoxAsync(world, selector).ConfigureAwait(false);- while ((result.Status == StealthStatus.NotFound || result.Status == StealthStatus.EvaluationFailed)- && Environment.TickCount64 < deadline)- {- await Task.Delay(50).ConfigureAwait(false);- result = await StealthDom.BoxAsync(world, selector).ConfigureAwait(false);- }-- return result.Status switch- {- StealthStatus.Ok when result.Target != null => result.Target.Value.Box,- StealthStatus.NotFound => null,- StealthStatus.Unsupported => throw new UnsupportedHumanizeSelectorError(selector),- _ => throw new StealthEvaluationError(selector),- };- }-- // Thread the page's isolated world into the shared actionability helpers.- private async Task EnsureActionableWorldAsync(- string selector, IReadOnlySet<string> checks, double timeoutMs, bool force)- {- var world = await GetStealthRequiredAsync().ConfigureAwait(false);- await Actionability.EnsureActionableAsync(- _page, selector, checks, timeoutMs, force, world).ConfigureAwait(false);- }-- private async Task EnsureStableWorldAsync(string selector, double timeoutMs)- {- var world = await GetStealthRequiredAsync().ConfigureAwait(false);- await Actionability.EnsureStableAsync(_page, selector, timeoutMs, world).ConfigureAwait(false);- }-- private async Task CheckPointerEventsWorldAsync(- string selector, int targetId, int gen, double x, double y, double timeoutMs, bool force)- {- if (force)- return;- var world = await GetStealthRequiredAsync().ConfigureAwait(false);- await Actionability.CheckPointerEventsAsync(- _page, selector, targetId, gen, x, y, timeoutMs, world).ConfigureAwait(false);- }-- // ------------------------------------------------------------------------ // Navigation- // ------------------------------------------------------------------------- /// <summary>Navigate to a URL and invalidate the isolated world afterward.</summary>- public async Task<IResponse?> GotoAsync(string url, PageGotoOptions? options = null)- {- var response = await _page.GotoAsync(url, options).ConfigureAwait(false);- _stealth?.Invalidate();- return response;- }-- // ------------------------------------------------------------------------ // Click- // -----------------------------------------------------------------------+ // -- pointer ------------------------------------------------------------/// <summary>Human-like click on <paramref name="selector"/>.</summary>public Task ClickAsync(string selector, HumanActionOptions? options = null) =>- ClickInternalAsync(selector, options, skipChecks: false);-- private async Task ClickInternalAsync(string selector, HumanActionOptions? options, bool skipChecks)- {- await EnsureCursorInitAsync().ConfigureAwait(false);- var callCfg = MergeCfg(options);- double timeout = options?.Timeout ?? 30000;- bool force = options?.Force ?? false;- double deadline = Environment.TickCount64 + timeout;-- if (!force && !skipChecks)- await EnsureActionableWorldAsync(selector, Actionability.ChecksClick, RemainingMs(deadline), force).ConfigureAwait(false);- if (callCfg.IdleBetweenActions)- await HumanMouse.HumanIdleAsync(_rawMouse, HumanRandom.Rand(callCfg.IdleBetweenDuration.Min, callCfg.IdleBetweenDuration.Max), _cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);-- var scroll = await HumanScroll.HumanScrollIntoViewAsync(- _scrollPage, _rawMouse, () => GetBoxAsync(selector, RemainingMs(deadline)),- _cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);- _cursor.X = scroll.CursorX;- _cursor.Y = scroll.CursorY;-- if (!force && scroll.DidScroll)- {- await EnsureStableWorldAsync(selector, RemainingMs(deadline)).ConfigureAwait(false);- // Waiting for the reflow to settle can push the element back out of- // view, and scrolling once before the wait is not enough: the click- // coords would land outside the viewport and hit nothing (#329).- var rescroll = await HumanScroll.HumanScrollIntoViewAsync(- _scrollPage, _rawMouse, () => GetBoxAsync(selector, RemainingMs(deadline)),- _cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);- _cursor.X = rescroll.CursorX;- _cursor.Y = rescroll.CursorY;- }-- var snapshot = await SelectorSnapshotAsync(selector).ConfigureAwait(false);- var box = snapshot.Box ?? throw new ElementNotVisibleError(selector);- var target = HumanMouse.ClickTarget(box, snapshot.IsInput, callCfg);- await HumanMouse.HumanMoveAsync(- _rawMouse, _cursor.X, _cursor.Y, target.X, target.Y, callCfg).ConfigureAwait(false);- _cursor.X = target.X;- _cursor.Y = target.Y;- await CheckPointerEventsWorldAsync(- selector, snapshot.TargetId, snapshot.Gen, target.X, target.Y,- RemainingMs(deadline), force).ConfigureAwait(false);- await HumanMouse.HumanClickAsync(_rawMouse, snapshot.IsInput, callCfg).ConfigureAwait(false);- }-- // ------------------------------------------------------------------------ // Double-click- // -----------------------------------------------------------------------+ _engine.ClickAsync(T(selector), O(options), "HumanPage.ClickAsync");- /// <summary>Human-like double-click on <paramref name="selector"/>.</summary>- public async Task DblClickAsync(string selector, HumanActionOptions? options = null)- {- await EnsureCursorInitAsync().ConfigureAwait(false);- var callCfg = MergeCfg(options);- double timeout = options?.Timeout ?? 30000;- bool force = options?.Force ?? false;- double deadline = Environment.TickCount64 + timeout;-- if (!force)- await EnsureActionableWorldAsync(selector, Actionability.ChecksClick, RemainingMs(deadline), force).ConfigureAwait(false);- if (callCfg.IdleBetweenActions)- await HumanMouse.HumanIdleAsync(_rawMouse, HumanRandom.Rand(callCfg.IdleBetweenDuration.Min, callCfg.IdleBetweenDuration.Max), _cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);-- var scroll = await HumanScroll.HumanScrollIntoViewAsync(- _scrollPage, _rawMouse, () => GetBoxAsync(selector, RemainingMs(deadline)),- _cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);- _cursor.X = scroll.CursorX;- _cursor.Y = scroll.CursorY;-- if (!force && scroll.DidScroll)- {- await EnsureStableWorldAsync(selector, RemainingMs(deadline)).ConfigureAwait(false);- // Waiting for the reflow to settle can push the element back out of- // view, and scrolling once before the wait is not enough: the click- // coords would land outside the viewport and hit nothing (#329).- var rescroll = await HumanScroll.HumanScrollIntoViewAsync(- _scrollPage, _rawMouse, () => GetBoxAsync(selector, RemainingMs(deadline)),- _cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);- _cursor.X = rescroll.CursorX;- _cursor.Y = rescroll.CursorY;- }-- var snapshot = await SelectorSnapshotAsync(selector).ConfigureAwait(false);- var box = snapshot.Box ?? throw new ElementNotVisibleError(selector);- var target = HumanMouse.ClickTarget(box, snapshot.IsInput, callCfg);- await HumanMouse.HumanMoveAsync(- _rawMouse, _cursor.X, _cursor.Y, target.X, target.Y, callCfg).ConfigureAwait(false);- _cursor.X = target.X;- _cursor.Y = target.Y;- await CheckPointerEventsWorldAsync(- selector, snapshot.TargetId, snapshot.Gen, target.X, target.Y,- RemainingMs(deadline), force).ConfigureAwait(false);- // Two presses for a double-click via Playwright IMouse click count.- await _page.Mouse.DownAsync(new MouseDownOptions { ClickCount = 2 }).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(30, 60)).ConfigureAwait(false);- await _page.Mouse.UpAsync(new MouseUpOptions { ClickCount = 2 }).ConfigureAwait(false);- }-- // ------------------------------------------------------------------------ // Hover- // -----------------------------------------------------------------------+ /// <summary>Human-like double click (a real mousedown/up x2 sequence).</summary>+ public Task DblClickAsync(string selector, HumanActionOptions? options = null) =>+ _engine.ClickAsync(T(selector), O(options), "HumanPage.DblClickAsync", 2);- /// <summary>Human-like hover over <paramref name="selector"/>.</summary>+ /// <summary>Human-like hover.</summary>public Task HoverAsync(string selector, HumanActionOptions? options = null) =>- HoverInternalAsync(selector, options, skipChecks: false);+ _engine.HoverAsync(T(selector), O(options), "HumanPage.HoverAsync");- private async Task HoverInternalAsync(string selector, HumanActionOptions? options, bool skipChecks)- {- await EnsureCursorInitAsync().ConfigureAwait(false);- var callCfg = MergeCfg(options);- double timeout = options?.Timeout ?? 30000;- bool force = options?.Force ?? false;- double deadline = Environment.TickCount64 + timeout;-- if (!force && !skipChecks)- await EnsureActionableWorldAsync(selector, Actionability.ChecksHover, RemainingMs(deadline), force).ConfigureAwait(false);- if (callCfg.IdleBetweenActions)- await HumanMouse.HumanIdleAsync(_rawMouse, HumanRandom.Rand(callCfg.IdleBetweenDuration.Min, callCfg.IdleBetweenDuration.Max), _cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);-- var scroll = await HumanScroll.HumanScrollIntoViewAsync(- _scrollPage, _rawMouse, () => GetBoxAsync(selector, RemainingMs(deadline)),- _cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);- _cursor.X = scroll.CursorX;- _cursor.Y = scroll.CursorY;-- if (!force && scroll.DidScroll)- {- await EnsureStableWorldAsync(selector, RemainingMs(deadline)).ConfigureAwait(false);- // Waiting for the reflow to settle can push the element back out of- // view, and scrolling once before the wait is not enough: the click- // coords would land outside the viewport and hit nothing (#329).- var rescroll = await HumanScroll.HumanScrollIntoViewAsync(- _scrollPage, _rawMouse, () => GetBoxAsync(selector, RemainingMs(deadline)),- _cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);- _cursor.X = rescroll.CursorX;- _cursor.Y = rescroll.CursorY;- }-- var snapshot = await SelectorSnapshotAsync(selector).ConfigureAwait(false);- var box = snapshot.Box ?? throw new ElementNotVisibleError(selector);- var target = HumanMouse.ClickTarget(box, false, callCfg);- await HumanMouse.HumanMoveAsync(- _rawMouse, _cursor.X, _cursor.Y, target.X, target.Y, callCfg).ConfigureAwait(false);- _cursor.X = target.X;- _cursor.Y = target.Y;- await CheckPointerEventsWorldAsync(- selector, snapshot.TargetId, snapshot.Gen, target.X, target.Y,- RemainingMs(deadline), force).ConfigureAwait(false);- }-- // ------------------------------------------------------------------------ // Type (append) and Fill (clear + type)- // ------------------------------------------------------------------------- /// <summary>Human-like typing into <paramref name="selector"/> (appends to existing value).</summary>- public async Task TypeAsync(string selector, string text, HumanActionOptions? options = null)- {- var callCfg = MergeCfg(options);- double timeout = options?.Timeout ?? 30000;- bool force = options?.Force ?? false;- double deadline = Environment.TickCount64 + timeout;-- if (!force)- await EnsureActionableWorldAsync(selector, Actionability.ChecksInput, RemainingMs(deadline), force).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.RandRange(callCfg.FieldSwitchDelay)).ConfigureAwait(false);- await ClickInternalAsync(selector, new HumanActionOptions { Timeout = RemainingMs(deadline), Force = force, HumanConfig = options?.HumanConfig }, skipChecks: true).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(100, 250)).ConfigureAwait(false);- await HumanKeyboard.HumanTypeAsync(_evaluator, _rawKeyboard, text, callCfg, _cdpSession).ConfigureAwait(false);- }-- /// <summary>Human-like fill of <paramref name="selector"/> (selects all, deletes, then types).</summary>- public async Task FillAsync(string selector, string value, HumanActionOptions? options = null)- {- var callCfg = MergeCfg(options);- double timeout = options?.Timeout ?? 30000;- bool force = options?.Force ?? false;- double deadline = Environment.TickCount64 + timeout;-- if (!force)- await EnsureActionableWorldAsync(selector, Actionability.ChecksInput, RemainingMs(deadline), force).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.RandRange(callCfg.FieldSwitchDelay)).ConfigureAwait(false);- await ClickInternalAsync(selector, new HumanActionOptions { Timeout = RemainingMs(deadline), Force = force, HumanConfig = options?.HumanConfig }, skipChecks: true).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(100, 250)).ConfigureAwait(false);- await _page.Keyboard.PressAsync(SelectAll).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(30, 80)).ConfigureAwait(false);- await _page.Keyboard.PressAsync("Backspace").ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(50, 150)).ConfigureAwait(false);- await HumanKeyboard.HumanTypeAsync(_evaluator, _rawKeyboard, value, callCfg, _cdpSession).ConfigureAwait(false);- }-- // ------------------------------------------------------------------------ // Check / Uncheck- // -----------------------------------------------------------------------+ /// <summary>Human-like tap (same motion as a click).</summary>+ public Task TapAsync(string selector, HumanActionOptions? options = null) =>+ _engine.TapAsync(T(selector), O(options), "HumanPage.TapAsync");/// <summary>Human-like check of a checkbox/radio (no-op if already checked).</summary>- public async Task CheckAsync(string selector, HumanActionOptions? options = null)- {- bool force = options?.Force ?? false;- double timeout = options?.Timeout ?? 30000;- double deadline = Environment.TickCount64 + timeout;-- if (!force)- await EnsureActionableWorldAsync(selector, Actionability.ChecksCheck, RemainingMs(deadline), force).ConfigureAwait(false);- bool checked_ = (await SelectorSnapshotAsync(selector).ConfigureAwait(false)).Checked == true;- if (!checked_)- await ClickInternalAsync(selector, new HumanActionOptions { Timeout = RemainingMs(deadline), Force = force, HumanConfig = options?.HumanConfig }, skipChecks: true).ConfigureAwait(false);- }-- /// <summary>Human-like uncheck of a checkbox (no-op if already unchecked).</summary>- public async Task UncheckAsync(string selector, HumanActionOptions? options = null)- {- bool force = options?.Force ?? false;- double timeout = options?.Timeout ?? 30000;- double deadline = Environment.TickCount64 + timeout;-- if (!force)- await EnsureActionableWorldAsync(selector, Actionability.ChecksCheck, RemainingMs(deadline), force).ConfigureAwait(false);- bool checked_ = (await SelectorSnapshotAsync(selector).ConfigureAwait(false)).Checked == true;- if (checked_)- await ClickInternalAsync(selector, new HumanActionOptions { Timeout = RemainingMs(deadline), Force = force, HumanConfig = options?.HumanConfig }, skipChecks: true).ConfigureAwait(false);- }-- // ------------------------------------------------------------------------ // Select option- // ------------------------------------------------------------------------- /// <summary>Human-like select of a dropdown option (hovers, then uses Playwright's selectOption).</summary>- public async Task<IReadOnlyList<string>> SelectOptionAsync(string selector, string[] values, HumanActionOptions? options = null)- {- bool force = options?.Force ?? false;- double timeout = options?.Timeout ?? 30000;- double deadline = Environment.TickCount64 + timeout;-- if (!force)- await EnsureActionableWorldAsync(selector, Actionability.ChecksFocus, RemainingMs(deadline), force).ConfigureAwait(false);- await HoverInternalAsync(selector, new HumanActionOptions { Timeout = RemainingMs(deadline), Force = force, HumanConfig = options?.HumanConfig }, skipChecks: true).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(100, 300)).ConfigureAwait(false);- return await _page.SelectOptionAsync(selector, values).ConfigureAwait(false);- }-- // ------------------------------------------------------------------------ // Press a key while a selector is focused- // ------------------------------------------------------------------------- /// <summary>Human-like press of <paramref name="key"/> after focusing <paramref name="selector"/>.</summary>- public async Task PressAsync(string selector, string key, HumanActionOptions? options = null)- {- bool force = options?.Force ?? false;- double timeout = options?.Timeout ?? 30000;- double deadline = Environment.TickCount64 + timeout;-- if (!force)- await EnsureActionableWorldAsync(selector, Actionability.ChecksFocus, RemainingMs(deadline), force).ConfigureAwait(false);- if (!await IsSelectorFocusedAsync(selector).ConfigureAwait(false))- await ClickInternalAsync(selector, new HumanActionOptions { Timeout = RemainingMs(deadline), Force = force, HumanConfig = options?.HumanConfig }, skipChecks: true).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(50, 150)).ConfigureAwait(false);- await HumanKeyboard.PressAsync(_page.Keyboard, key, options?.Delay).ConfigureAwait(false);- }+ public Task CheckAsync(string selector, HumanActionOptions? options = null) =>+ _engine.SetCheckedAsync(T(selector), true, O(options), "HumanPage.CheckAsync");- // ------------------------------------------------------------------------ // Set-checked (drives state to the requested value)- // -----------------------------------------------------------------------+ /// <summary>Human-like uncheck (no-op if already unchecked).</summary>+ public Task UncheckAsync(string selector, HumanActionOptions? options = null) =>+ _engine.SetCheckedAsync(T(selector), false, O(options), "HumanPage.UncheckAsync");- /// <summary>Human-like set-checked: clicks only when the current state differs from- /// the requested <paramref name="checked_"/> value. Port of <c>_humanized_set_checked</c>.</summary>- public async Task SetCheckedAsync(string selector, bool checked_, HumanActionOptions? options = null)- {- bool force = options?.Force ?? false;- double timeout = options?.Timeout ?? 30000;- double deadline = Environment.TickCount64 + timeout;-- if (!force)- await EnsureActionableWorldAsync(selector, Actionability.ChecksCheck, RemainingMs(deadline), force).ConfigureAwait(false);- bool current = (await SelectorSnapshotAsync(selector).ConfigureAwait(false)).Checked == true;- if (current != checked_)- await ClickInternalAsync(selector, new HumanActionOptions { Timeout = RemainingMs(deadline), Force = force, HumanConfig = options?.HumanConfig }, skipChecks: true).ConfigureAwait(false);- }+ /// <summary>Click only when the current state differs from <paramref name="checked_"/>.</summary>+ public Task SetCheckedAsync(string selector, bool checked_, HumanActionOptions? options = null) =>+ _engine.SetCheckedAsync(T(selector), checked_, O(options), "HumanPage.SetCheckedAsync");- // ------------------------------------------------------------------------ // Tap (humanized click; mobile gesture maps to the same motion)- // -----------------------------------------------------------------------+ /// <summary>Pick options like a person (dropdown: click + arrow keys + Enter; list box: clicks).</summary>+ public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, string[] values, HumanActionOptions? options = null) =>+ _engine.SelectOptionAsync(T(selector),+ values.Select(v => (object)new Dictionary<string, object> { ["valueOrLabel"] = v }).ToList(),+ Array.Empty<IElementHandle>(), O(options), "HumanPage.SelectOptionAsync");- /// <summary>Human-like tap. Port of <c>_humanized_tap</c> - same motion as a click.</summary>- public Task TapAsync(string selector, HumanActionOptions? options = null) =>- ClickAsync(selector, options);+ /// <summary>Human-like drag from the source element to the target element.</summary>+ public Task DragAndDropAsync(string sourceSelector, string targetSelector, HumanActionOptions? options = null) =>+ _engine.DragAsync(T(sourceSelector), T(targetSelector), O(options), "HumanPage.DragAndDropAsync");- // ------------------------------------------------------------------------ // Press sequentially (focus then human-type, no clear)- // -----------------------------------------------------------------------+ // -- keyboard ------------------------------------------------------------ /// <summary>Human-like press-sequentially: focuses (via click if needed) then types the- /// text with human timing, without clearing. Port of <c>_humanized_press_sequentially</c>.</summary>- public async Task PressSequentiallyAsync(string selector, string text, HumanActionOptions? options = null)- {- bool force = options?.Force ?? false;- double timeout = options?.Timeout ?? 30000;- double deadline = Environment.TickCount64 + timeout;-- if (!force)- await EnsureActionableWorldAsync(selector, Actionability.ChecksInput, RemainingMs(deadline), force).ConfigureAwait(false);- if (!await IsSelectorFocusedAsync(selector).ConfigureAwait(false))- await ClickInternalAsync(selector, new HumanActionOptions { Timeout = RemainingMs(deadline), Force = force, HumanConfig = options?.HumanConfig }, skipChecks: true).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(50, 150)).ConfigureAwait(false);- await HumanKeyboard.HumanTypeAsync(_evaluator, _rawKeyboard, text, MergeCfg(options), _cdpSession).ConfigureAwait(false);- }+ /// <summary>Human-like typing into <paramref name="selector"/>; text continues at the end.</summary>+ public Task TypeAsync(string selector, string text, HumanActionOptions? options = null) =>+ _engine.TypeAsync(T(selector), text, O(options), "HumanPage.TypeAsync");- // ------------------------------------------------------------------------ // Clear (focus, select-all, backspace)- // -----------------------------------------------------------------------+ /// <summary>Same as <see cref="TypeAsync"/> (Playwright's <c>PressSequentially</c>).</summary>+ public Task PressSequentiallyAsync(string selector, string text, HumanActionOptions? options = null) =>+ _engine.TypeAsync(T(selector), text, O(options), "HumanPage.PressSequentiallyAsync");- /// <summary>Human-like clear: focuses (via click if needed), selects all, deletes.- /// Port of <c>_humanized_clear</c>.</summary>- public async Task ClearAsync(string selector, HumanActionOptions? options = null)- {- bool force = options?.Force ?? false;- double timeout = options?.Timeout ?? 30000;- double deadline = Environment.TickCount64 + timeout;-- if (!force)- await EnsureActionableWorldAsync(selector, Actionability.ChecksInput, RemainingMs(deadline), force).ConfigureAwait(false);- if (!await IsSelectorFocusedAsync(selector).ConfigureAwait(false))- await ClickInternalAsync(selector, new HumanActionOptions { Timeout = RemainingMs(deadline), Force = force, HumanConfig = options?.HumanConfig }, skipChecks: true).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(50, 100)).ConfigureAwait(false);- await _page.Keyboard.PressAsync(SelectAll).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(30, 80)).ConfigureAwait(false);- await _page.Keyboard.PressAsync("Backspace").ConfigureAwait(false);- }+ /// <summary>Human-like fill: click into the field, select all, delete, type. Date / range /+ /// select-like inputs are set the way a person would; <c>type=color</c> throws.</summary>+ public Task FillAsync(string selector, string value, HumanActionOptions? options = null) =>+ _engine.FillAsync(T(selector), value, O(options), "HumanPage.FillAsync");- // ------------------------------------------------------------------------ // Focus (human cursor move, then programmatic focus - NO click side-effects)- // -----------------------------------------------------------------------+ /// <summary>Human-like clear (fill with an empty string).</summary>+ public Task ClearAsync(string selector, HumanActionOptions? options = null) =>+ _engine.FillAsync(T(selector), "", O(options), "HumanPage.ClearAsync");- /// <summary>Human-like focus: moves the cursor over the element with a Bezier curve,- /// then focuses it programmatically (no click, so no onclick/submit/navigation).- /// Port of <c>_human_el_focus</c> applied to a selector.</summary>- public async Task FocusAsync(string selector, HumanActionOptions? options = null)- {- await EnsureCursorInitAsync().ConfigureAwait(false);- var callCfg = MergeCfg(options);- double timeout = options?.Timeout ?? 30000;- bool force = options?.Force ?? false;- double deadline = Environment.TickCount64 + timeout;-- if (!force)- await EnsureActionableWorldAsync(selector, Actionability.ChecksFocus, RemainingMs(deadline), force).ConfigureAwait(false);-- var scroll = await HumanScroll.HumanScrollIntoViewAsync(- _scrollPage, _rawMouse, () => GetBoxAsync(selector, RemainingMs(deadline)),- _cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);- _cursor.X = scroll.CursorX;- _cursor.Y = scroll.CursorY;- var box = scroll.Box;- if (!force && scroll.DidScroll)- {- await EnsureStableWorldAsync(selector, RemainingMs(deadline)).ConfigureAwait(false);- // Waiting for the reflow to settle can push the element back out of- // view, and scrolling once before the wait is not enough: the click- // coords would land outside the viewport and hit nothing (#329).- var rescroll = await HumanScroll.HumanScrollIntoViewAsync(- _scrollPage, _rawMouse, () => GetBoxAsync(selector, RemainingMs(deadline)),- _cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);- _cursor.X = rescroll.CursorX;- _cursor.Y = rescroll.CursorY;- box = rescroll.Box;- }- var target = HumanMouse.ClickTarget(box, false, callCfg);- await HumanMouse.HumanMoveAsync(_rawMouse, _cursor.X, _cursor.Y, target.X, target.Y, callCfg).ConfigureAwait(false);- _cursor.X = target.X;- _cursor.Y = target.Y;- // Programmatic focus - never clicks (mirrors stock Playwright el.focus()).- await _page.FocusAsync(selector).ConfigureAwait(false);- }+ /// <summary>Focus the element by clicking it if needed, then press <paramref name="key"/>.</summary>+ public Task PressAsync(string selector, string key, HumanActionOptions? options = null) =>+ _engine.PressAsync(T(selector), key, O(options), "HumanPage.PressAsync");- // ------------------------------------------------------------------------ // Scroll into view (humanized accelerate->cruise->decelerate->overshoot)- // -----------------------------------------------------------------------+ /// <summary>Move the cursor over the element, then focus it without a click.</summary>+ public Task FocusAsync(string selector, HumanActionOptions? options = null) =>+ _engine.FocusAsync(T(selector), O(options), "HumanPage.FocusAsync", move: true);- /// <summary>Human-like scroll-into-view. Port of <c>_humanized_scroll_into_view_if_needed</c>.- /// Returns true if a scroll was performed (false when already in viewport).</summary>+ /// <summary>Wheel-scroll the element into view. Returns true when the element moved.</summary>public async Task<bool> ScrollIntoViewIfNeededAsync(string selector, HumanActionOptions? options = null){- await EnsureCursorInitAsync().ConfigureAwait(false);- var callCfg = MergeCfg(options);- double timeout = options?.Timeout ?? 30000;- var scroll = await HumanScroll.HumanScrollIntoViewAsync(- _scrollPage, _rawMouse, () => GetBoxAsync(selector, timeout),- _cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);- _cursor.X = scroll.CursorX;- _cursor.Y = scroll.CursorY;- return scroll.DidScroll;+ var before = await _page.MainFrame.Locator(selector).First.BoundingBoxAsync(+ new() { Timeout = (float)(options?.Timeout ?? 30000) }).ConfigureAwait(false);+ await _engine.ScrollIntoViewIfNeededAsync(T(selector), O(options), "HumanPage.ScrollIntoViewIfNeededAsync").ConfigureAwait(false);+ var after = await _page.MainFrame.Locator(selector).First.BoundingBoxAsync().ConfigureAwait(false);+ return before != null && after != null && (Math.Abs(before.X - after.X) >= 1 || Math.Abs(before.Y - after.Y) >= 1);}- // ------------------------------------------------------------------------ // Drag-and-drop (humanized: move to source center, down, move to target, up)- // -----------------------------------------------------------------------+ // -- low level ----------------------------------------------------------- /// <summary>Human-like drag from <paramref name="sourceSelector"/> to- /// <paramref name="targetSelector"/>. Port of <c>_frame_drag_and_drop</c> / <c>_humanized_drag_to</c>:- /// moves to the source center, presses, moves to the target center, releases.</summary>- public async Task DragAndDropAsync(string sourceSelector, string targetSelector, HumanActionOptions? options = null)- {- await EnsureCursorInitAsync().ConfigureAwait(false);- double timeout = options?.Timeout ?? 30000;-- var srcBox = await GetBoxAsync(sourceSelector, timeout).ConfigureAwait(false);- var tgtBox = await GetBoxAsync(targetSelector, timeout).ConfigureAwait(false);- if (srcBox == null)- throw new ElementNotAttachedError(sourceSelector);- if (tgtBox == null)- throw new ElementNotAttachedError(targetSelector);-- BoundingBox src = srcBox.Value;- BoundingBox tgt = tgtBox.Value;- double sx = src.X + src.Width / 2;- double sy = src.Y + src.Height / 2;- double tx = tgt.X + tgt.Width / 2;- double ty = tgt.Y + tgt.Height / 2;-- await HumanMouse.HumanMoveAsync(_rawMouse, _cursor.X, _cursor.Y, sx, sy, _cfg).ConfigureAwait(false);- _cursor.X = sx; _cursor.Y = sy;- await HumanRandom.SleepMsAsync(HumanRandom.Rand(100, 200)).ConfigureAwait(false);- await _rawMouse.DownAsync().ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(80, 150)).ConfigureAwait(false);- await HumanMouse.HumanMoveAsync(_rawMouse, _cursor.X, _cursor.Y, tx, ty, _cfg).ConfigureAwait(false);- _cursor.X = tx; _cursor.Y = ty;- await HumanRandom.SleepMsAsync(HumanRandom.Rand(80, 150)).ConfigureAwait(false);- await _rawMouse.UpAsync().ConfigureAwait(false);- }-- // ------------------------------------------------------------------------ // Low-level mouse / keyboard- // ------------------------------------------------------------------------- /// <summary>Move the virtual cursor to absolute (x, y) with a human-like curve.</summary>- public async Task MouseMoveAsync(double x, double y)- {- await EnsureCursorInitAsync().ConfigureAwait(false);- await HumanMouse.HumanMoveAsync(_rawMouse, _cursor.X, _cursor.Y, x, y, _cfg).ConfigureAwait(false);- _cursor.X = x;- _cursor.Y = y;- }+ /// <summary>Move the virtual cursor to absolute (x, y) along a human-like curve.</summary>+ public Task MouseMoveAsync(double x, double y) => _engine.MouseMoveAsync(x, y);- /// <summary>Move to absolute (x, y) and perform a human-like click there.</summary>- public async Task MouseClickAsync(double x, double y)- {- await EnsureCursorInitAsync().ConfigureAwait(false);- await HumanMouse.HumanMoveAsync(_rawMouse, _cursor.X, _cursor.Y, x, y, _cfg).ConfigureAwait(false);- _cursor.X = x;- _cursor.Y = y;- await HumanMouse.HumanClickAsync(_rawMouse, false, _cfg).ConfigureAwait(false);- }-- /// <summary>Type text into whatever element currently has focus, with human timing.</summary>- public Task KeyboardTypeAsync(string text) =>- HumanKeyboard.HumanTypeAsync(_evaluator, _rawKeyboard, text, _cfg, _cdpSession);+ /// <summary>Move to absolute (x, y) and click there like a person.</summary>+ public Task MouseClickAsync(double x, double y) => _engine.MouseClickAsync(x, y);- /// <summary>Mutable cursor position used across actions.</summary>- private sealed class CursorState- {- public double X;- public double Y;- public bool Initialized;- }+ /// <summary>Type into whatever element currently has focus, with human timing.</summary>+ public Task KeyboardTypeAsync(string text) => _engine.KeyboardTypeAsync(text);}diff --git a/dotnet/src/CloakBrowser/Human/HumanScroll.cs b/dotnet/src/CloakBrowser/Human/HumanScroll.csindex 38b2147..3efe121 100644--- a/dotnet/src/CloakBrowser/Human/HumanScroll.cs+++ b/dotnet/src/CloakBrowser/Human/HumanScroll.cs@@ -66,6 +66,10 @@ public static class HumanScroll{double stepSize = HumanRandom.Rand(20, 40);double chunk = Math.Min(stepSize, absD - sent);+ // Fold a sub-pixel tail into this step: on its own it would round to a+ // (0, 0) wheel event, which no real wheel sends.+ if (absD - sent - chunk < 0.5)+ chunk = absD - sent;double step = Math.Round(chunk) * sign;if (horizontal)await raw.WheelAsync(step, 0).ConfigureAwait(false);diff --git a/dotnet/src/CloakBrowser/Human/HumanWorld.cs b/dotnet/src/CloakBrowser/Human/HumanWorld.csnew file mode 100644index 0000000..ca3786e--- /dev/null+++ b/dotnet/src/CloakBrowser/Human/HumanWorld.cs@@ -0,0 +1,401 @@+using System.Text.Json;+using Microsoft.Playwright;++namespace CloakBrowser.Human;++/// <summary>An isolated-world evaluation failed (never falls back to the page).</summary>+public sealed class StealthWorldException : PlaywrightException+{+ public StealthWorldException(string message) : base(message) { }+}++/// <summary>The element behind an id is no longer in the isolated-world registry.</summary>+internal sealed class StaleElementException : PlaywrightException+{+ public StaleElementException() : base("element is not attached to the DOM") { }+}++internal readonly record struct Rect(double X, double Y, double Width, double Height)+{+ public static Rect Intersect(Rect a, Rect b)+ {+ double x0 = Math.Max(a.X, b.X), y0 = Math.Max(a.Y, b.Y);+ double x1 = Math.Min(a.X + a.Width, b.X + b.Width), y1 = Math.Min(a.Y + a.Height, b.Y + b.Height);+ return new Rect(x0, y0, Math.Max(0, x1 - x0), Math.Max(0, y1 - y0));+ }++ public bool Contains(double x, double y) => X <= x && x <= X + Width && Y <= y && y <= Y + Height;+}++internal readonly record struct EditorField(string Kind, double Dx, double Dy);++/// <summary>+/// CDP isolated worlds for every frame of a page (main, same-process, OOPIF).+/// Port of <c>cloakbrowser/human/world.py</c>.+///+/// Each frame gets one isolated world per document, created through+/// <c>Page.createIsolatedWorld</c> on the CDP session that owns the frame. Into that+/// world we install Playwright's InjectedScript and a small helper object. Frame mapping uses+/// <c>Page.getFrameTree</c>, iframe owners are reached via <c>DOM.getFrameOwner</c>+/// + <c>DOM.resolveNode</c>, elements live in a world-local registry of integer ids.+/// </summary>+internal sealed class HumanWorld+{+ private sealed class FrameRec+ {+ public FrameRec(ICDPSession session, string cdpId) { Session = session; CdpId = cdpId; }+ public ICDPSession Session { get; }+ public string CdpId { get; }+ public int? Ctx { get; set; }+ }++ private static string? _decodedSource;+ private static readonly string[] StaleMarkers =+ {+ "Cannot find context", "Execution context was destroyed", "Inspected target navigated",+ "cloak:stale-world", "Cannot find default execution context",+ };++ private readonly IPage _page;+ private ICDPSession? _session;+ private readonly Dictionary<IFrame, FrameRec> _frames = new();+ private readonly SemaphoreSlim _lock = new(1, 1);++ public HumanWorld(IPage page)+ {+ _page = page;+ try+ {+ page.FrameNavigated += (_, f) => Invalidate(f);+ page.FrameDetached += (_, f) => Invalidate(f);+ }+ catch (Exception) { /* fakes without events */ }+ }++ public IPage Page => _page;++ // -- sessions / frame mapping -------------------------------------------++ public async Task<ICDPSession> SessionAsync()+ {+ _session ??= await _page.Context.NewCDPSessionAsync(_page).ConfigureAwait(false);+ return _session;+ }++ /// <summary>Forget worlds of <paramref name="frame"/> and its descendants (all when null).</summary>+ public void Invalidate(IFrame? frame = null)+ {+ lock (_frames)+ {+ if (frame == null) { _frames.Clear(); return; }+ foreach (var f in _frames.Keys.Where(f => f == frame || IsDescendant(f, frame)).ToList())+ _frames.Remove(f);+ }+ }++ private static bool IsDescendant(IFrame frame, IFrame ancestor)+ {+ for (var p = frame.ParentFrame; p != null; p = p.ParentFrame)+ if (p == ancestor) return true;+ return false;+ }++ private async Task<FrameRec> LocateAsync(IFrame frame)+ {+ lock (_frames) { if (_frames.TryGetValue(frame, out var r)) return r; }+ if (frame.IsDetached) throw new PlaywrightException("Frame was detached");+ FrameRec rec;+ var parent = frame.ParentFrame;+ if (parent == null)+ {+ var session = await SessionAsync().ConfigureAwait(false);+ var tree = await session.SendAsync("Page.getFrameTree").ConfigureAwait(false);+ rec = new FrameRec(session, tree!.Value.GetProperty("frameTree").GetProperty("frame").GetProperty("id").GetString()!);+ }+ else+ {+ rec = await LocateChildAsync(frame, parent).ConfigureAwait(false);+ }+ lock (_frames)+ {+ if (_frames.TryGetValue(frame, out var existing)) return existing;+ _frames[frame] = rec;+ }+ return rec;+ }++ private async Task<FrameRec> LocateChildAsync(IFrame frame, IFrame parent)+ {+ ICDPSession? own = null;+ try { own = await _page.Context.NewCDPSessionAsync(frame).ConfigureAwait(false); } // OOPIF: own target+ catch (Exception) { own = null; }+ if (own != null)+ {+ var t = await own.SendAsync("Page.getFrameTree").ConfigureAwait(false);+ return new FrameRec(own, t!.Value.GetProperty("frameTree").GetProperty("frame").GetProperty("id").GetString()!);+ }+ var prec = await LocateAsync(parent).ConfigureAwait(false);+ var tree = await prec.Session.SendAsync("Page.getFrameTree").ConfigureAwait(false);+ var node = FindNode(tree!.Value.GetProperty("frameTree"), prec.CdpId);+ var kids = new List<JsonElement>();+ if (node is JsonElement n && n.TryGetProperty("childFrames", out var cf))+ foreach (var k in cf.EnumerateArray()) kids.Add(k.GetProperty("frame"));+ var cdpId = MatchChild(frame, parent, kids)+ ?? throw new PlaywrightException("cloakbrowser humanize: could not map the frame to a CDP frame");+ return new FrameRec(prec.Session, cdpId);+ }++ private static JsonElement? FindNode(JsonElement tree, string cdpId)+ {+ if (tree.GetProperty("frame").GetProperty("id").GetString() == cdpId) return tree;+ if (tree.TryGetProperty("childFrames", out var kids))+ foreach (var c in kids.EnumerateArray())+ if (FindNode(c, cdpId) is JsonElement found) return found;+ return null;+ }++ /// <summary>Playwright and CDP list child frames in attach order; frames sharing the+ /// same (name, url) are matched by their position within that group.</summary>+ internal static string? MatchChild(IFrame frame, IFrame parent, IReadOnlyList<JsonElement> kids)+ {+ static string KeyPw(IFrame f) => f.Name + "\u0000" + f.Url;+ static string KeyCdp(JsonElement k) =>+ (k.TryGetProperty("name", out var n) ? n.GetString() : "") + "\u0000" ++ (k.TryGetProperty("url", out var u) ? u.GetString() : "") ++ (k.TryGetProperty("urlFragment", out var uf) ? uf.GetString() : "");+ var want = KeyPw(frame);+ var cands = kids.Where(k => KeyCdp(k) == want).ToList();+ var siblings = parent.ChildFrames.ToList();+ var peers = siblings.Where(f => KeyPw(f) == want).ToList();+ int pi = peers.IndexOf(frame);+ if (cands.Count > 0 && pi >= 0 && cands.Count == peers.Count) return cands[pi].GetProperty("id").GetString();+ if (cands.Count == 1) return cands[0].GetProperty("id").GetString();+ int si = siblings.IndexOf(frame);+ if (kids.Count == siblings.Count && si >= 0) return kids[si].GetProperty("id").GetString();+ return null;+ }++ public async Task<IFrame?> FrameForCdpIdAsync(IFrame parent, string cdpId)+ {+ foreach (var child in parent.ChildFrames)+ {+ try { if ((await LocateAsync(child).ConfigureAwait(false)).CdpId == cdpId) return child; }+ catch (PlaywrightException) { }+ }+ return null;+ }++ // -- world lifecycle ----------------------------------------------------++ /// <summary>Execution context of the frame's isolated world (created if needed). It+ /// changes on every new document, so element ids cached against it go stale with it.</summary>+ public async Task<int> ContextIdAsync(IFrame frame) => (await ReadyAsync(frame).ConfigureAwait(false)).Ctx!.Value;++ private async Task<FrameRec> ReadyAsync(IFrame frame)+ {+ var rec = await LocateAsync(frame).ConfigureAwait(false);+ if (rec.Ctx != null) return rec;+ await _lock.WaitAsync().ConfigureAwait(false);+ try+ {+ if (rec.Ctx != null) return rec;+ var res = await rec.Session.SendAsync("Page.createIsolatedWorld", new Dictionary<string, object>+ {+ ["frameId"] = rec.CdpId, ["worldName"] = "", ["grantUniveralAccess"] = true,+ }).ConfigureAwait(false);+ int ctx = res!.Value.GetProperty("executionContextId").GetInt32();+ await InstallAsync(rec.Session, ctx).ConfigureAwait(false);+ rec.Ctx = ctx;+ }+ finally { _lock.Release(); }+ return rec;+ }++ private static async Task InstallAsync(ICDPSession session, int ctx)+ {+ if (_decodedSource == null)+ {+ var v = await RawEvalAsync(session, ctx, InjectedSource.FindLiteral()).ConfigureAwait(false);+ _decodedSource = v!.Value.GetString();+ }+ await RawEvalAsync(session, ctx, InjectedSource.BuildInstallJs(_decodedSource!)).ConfigureAwait(false);+ await RawEvalAsync(session, ctx, WorldHelpers.Js).ConfigureAwait(false);+ }++ private static async Task<JsonElement?> RawEvalAsync(ICDPSession session, int ctx, string expression, bool byValue = true)+ {+ var res = (await session.SendAsync("Runtime.evaluate", new Dictionary<string, object>+ {+ ["expression"] = expression, ["contextId"] = ctx, ["returnByValue"] = byValue, ["awaitPromise"] = true,+ }).ConfigureAwait(false))!.Value;+ if (res.TryGetProperty("exceptionDetails", out var det))+ {+ string desc = det.TryGetProperty("exception", out var ex) && ex.TryGetProperty("description", out var d)+ ? d.GetString() ?? "" : det.TryGetProperty("text", out var t) ? t.GetString() ?? "" : "";+ if (desc.Contains("cloak:stale-element")) throw new StaleElementException();+ throw new StealthWorldException($"cloakbrowser humanize: isolated-world script failed: {desc.Split('\n')[0]}");+ }+ var result = res.GetProperty("result");+ if (!byValue) return result.Clone();+ return result.TryGetProperty("value", out var value) ? value.Clone() : null;+ }++ // -- evaluation ---------------------------------------------------------++ /// <summary>Evaluate in the frame's isolated world; recreate the world once if stale.</summary>+ public async Task<JsonElement?> EvaluateAsync(IFrame frame, string expression, bool byValue = true)+ {+ for (int attempt = 0; ; attempt++)+ {+ var rec = await ReadyAsync(frame).ConfigureAwait(false);+ try+ {+ return await RawEvalAsync(rec.Session, rec.Ctx!.Value, expression, byValue).ConfigureAwait(false);+ }+ catch (StaleElementException) { throw; }+ catch (Exception e) when (attempt == 0 && StaleMarkers.Any(m => e.Message.Contains(m)))+ {+ rec.Ctx = null;+ }+ }+ }++ public static string Arg(object? a) => JsonSerializer.Serialize(a);++ public Task<JsonElement?> CallAsync(IFrame frame, string method, params object?[] args) =>+ EvaluateAsync(frame, $"{WorldHelpers.Name}.{method}({string.Join(", ", args.Select(Arg))})");++ public async Task<(ICDPSession Session, string ObjectId)> ElementObjectIdAsync(IFrame frame, int id)+ {+ var rec = await ReadyAsync(frame).ConfigureAwait(false);+ var obj = await RawEvalAsync(rec.Session, rec.Ctx!.Value, $"{WorldHelpers.Name}.el({id})", byValue: false).ConfigureAwait(false);+ return (rec.Session, obj!.Value.GetProperty("objectId").GetString()!);+ }++ private static async Task ReleaseAsync(ICDPSession session, string objectId)+ {+ try { await session.SendAsync("Runtime.releaseObject", new() { ["objectId"] = objectId }).ConfigureAwait(false); }+ catch (Exception) { }+ }++ /// <summary>Segments of a native date/time editor in visual order, with centres relative+ /// to the input's border box. They live in the input's closed user-agent shadow root;+ /// CDP's DOM domain (<c>pierce</c>) reads them without running any script in the page.</summary>+ public async Task<List<EditorField>> EditorFieldsAsync(IFrame frame, int id)+ {+ var (session, objectId) = await ElementObjectIdAsync(frame, id).ConfigureAwait(false);+ JsonElement node, own;+ try+ {+ node = (await session.SendAsync("DOM.describeNode", new() { ["objectId"] = objectId, ["depth"] = -1, ["pierce"] = true }).ConfigureAwait(false))!.Value.GetProperty("node").Clone();+ own = (await session.SendAsync("DOM.getBoxModel", new() { ["objectId"] = objectId }).ConfigureAwait(false))!.Value.GetProperty("model").GetProperty("border").Clone();+ }+ finally { await ReleaseAsync(session, objectId).ConfigureAwait(false); }+ double ox = own[0].GetDouble(), oy = own[1].GetDouble();+ var output = new List<EditorField>();++ async Task Walk(JsonElement n)+ {+ string pseudo = "";+ if (n.TryGetProperty("attributes", out var attrs))+ for (int i = 0; i + 1 < attrs.GetArrayLength(); i += 2)+ if (attrs[i].GetString() == "pseudo") pseudo = attrs[i + 1].GetString() ?? "";+ if (pseudo.StartsWith("-webkit-datetime-edit-") && pseudo.EndsWith("-field") && !pseudo.Contains("wrapper"))+ {+ var q = (await session.SendAsync("DOM.getBoxModel", new() { ["backendNodeId"] = n.GetProperty("backendNodeId").GetInt32() }).ConfigureAwait(false))!+ .Value.GetProperty("model").GetProperty("border");+ output.Add(new EditorField(+ pseudo["-webkit-datetime-edit-".Length..^"-field".Length],+ (q[0].GetDouble() + q[2].GetDouble()) / 2 - ox, (q[1].GetDouble() + q[5].GetDouble()) / 2 - oy));+ }+ foreach (var key in new[] { "children", "shadowRoots" })+ if (n.TryGetProperty(key, out var kids))+ foreach (var c in kids.EnumerateArray()) await Walk(c).ConfigureAwait(false);+ }++ await Walk(node).ConfigureAwait(false);+ return output.OrderBy(f => Math.Round(f.Dy / 4)).ThenBy(f => f.Dx).ToList();+ }++ /// <summary>Child frame owned by the <iframe> element <paramref name="id"/> in <paramref name="frame"/>.</summary>+ public async Task<IFrame?> ContentFrameAsync(IFrame frame, int id)+ {+ var (session, objectId) = await ElementObjectIdAsync(frame, id).ConfigureAwait(false);+ JsonElement node;+ try { node = (await session.SendAsync("DOM.describeNode", new() { ["objectId"] = objectId }).ConfigureAwait(false))!.Value.GetProperty("node").Clone(); }+ finally { await ReleaseAsync(session, objectId).ConfigureAwait(false); }+ if (!node.TryGetProperty("frameId", out var fid) || string.IsNullOrEmpty(fid.GetString())) return null;+ return await FrameForCdpIdAsync(frame, fid.GetString()!).ConfigureAwait(false);+ }++ // -- geometry across frames ---------------------------------------------++ /// <summary>Call <paramref name="declaration"/> with <c>this</c> = the frame's+ /// <iframe> element, inside the parent frame's isolated world.</summary>+ private async Task<JsonElement?> OwnerCallAsync(IFrame frame, string declaration, params object[] args)+ {+ var parent = frame.ParentFrame!;+ var rec = await LocateAsync(frame).ConfigureAwait(false);+ var prec = await ReadyAsync(parent).ConfigureAwait(false);+ var owner = await prec.Session.SendAsync("DOM.getFrameOwner", new() { ["frameId"] = rec.CdpId }).ConfigureAwait(false);+ var obj = (await prec.Session.SendAsync("DOM.resolveNode", new()+ {+ ["backendNodeId"] = owner!.Value.GetProperty("backendNodeId").GetInt32(), ["executionContextId"] = prec.Ctx!.Value,+ }).ConfigureAwait(false))!.Value.GetProperty("object");+ var objectId = obj.GetProperty("objectId").GetString()!;+ JsonElement res;+ try+ {+ res = (await prec.Session.SendAsync("Runtime.callFunctionOn", new()+ {+ ["objectId"] = objectId, ["functionDeclaration"] = declaration,+ ["arguments"] = args.Select(a => new Dictionary<string, object> { ["value"] = a }).ToArray(),+ ["returnByValue"] = true,+ }).ConfigureAwait(false))!.Value.Clone();+ }+ finally { await ReleaseAsync(prec.Session, objectId).ConfigureAwait(false); }+ if (res.TryGetProperty("exceptionDetails", out _))+ throw new StealthWorldException("cloakbrowser humanize: frame owner evaluation failed");+ return res.GetProperty("result").TryGetProperty("value", out var v) ? v.Clone() : null;+ }++ public async Task<(double Width, double Height)> ViewportAsync()+ {+ var size = _page.ViewportSize;+ if (size != null && size.Width > 0) return (size.Width, size.Height);+ var doc = (await CallAsync(_page.MainFrame, "doc").ConfigureAwait(false))!.Value;+ return (doc.GetProperty("width").GetDouble(), doc.GetProperty("height").GetDouble());+ }++ /// <summary>The frame's origin in viewport coordinates and its visible clip (intersection+ /// of all ancestor iframe content boxes and the viewport).</summary>+ public async Task<(double Ox, double Oy, Rect Clip)> FrameGeometryAsync(IFrame frame)+ {+ var parent = frame.ParentFrame;+ if (parent == null)+ {+ var (w, h) = await ViewportAsync().ConfigureAwait(false);+ return (0, 0, new Rect(0, 0, w, h));+ }+ var (px, py, pclip) = await FrameGeometryAsync(parent).ConfigureAwait(false);+ var box = (await OwnerCallAsync(frame, $"function () {{ return {WorldHelpers.Name}.ownerContent.call(this); }}").ConfigureAwait(false))!.Value;+ double ox = px + box.GetProperty("x").GetDouble(), oy = py + box.GetProperty("y").GetDouble();+ return (ox, oy, Rect.Intersect(pclip, new Rect(ox, oy, box.GetProperty("width").GetDouble(), box.GetProperty("height").GetDouble())));+ }++ /// <summary>Check that the viewport point hits each ancestor <iframe> owner.</summary>+ public async Task<string?> OwnersHitAsync(IFrame frame, double vx, double vy)+ {+ var child = frame;+ while (child.ParentFrame != null)+ {+ var (px, py, _) = await FrameGeometryAsync(child.ParentFrame).ConfigureAwait(false);+ var desc = await OwnerCallAsync(child,+ $"function (x, y) {{ const r = globalThis.{InjectedSource.Global}.expectHitTarget({{ x, y }}, this);" ++ " return r === 'done' ? null : r.hitTargetDescription; }", vx - px, vy - py).ConfigureAwait(false);+ if (desc is JsonElement d && d.ValueKind == JsonValueKind.String) return d.GetString();+ child = child.ParentFrame;+ }+ return null;+ }+}diff --git a/dotnet/src/CloakBrowser/Human/InjectedSource.cs b/dotnet/src/CloakBrowser/Human/InjectedSource.csnew file mode 100644index 0000000..c659f53--- /dev/null+++ b/dotnet/src/CloakBrowser/Human/InjectedSource.cs@@ -0,0 +1,124 @@+using System.Text;+using System.Text.Json;+using System.Text.RegularExpressions;++namespace CloakBrowser.Human;++/// <summary>+/// Loads Playwright's selector / actionability engine for the humanize layer.+/// Port of <c>cloakbrowser/human/injected.py</c>.+///+/// Playwright ships its InjectedScript (selector engines for role, label, text,+/// test-id, <c>>></c> chains, <c>has</c> / <c>has-text</c> filters, <c>nth</c>,+/// <c>visible</c>, plus <c>checkElementStates</c> / <c>expectHitTarget</c>) as a string+/// literal in its driver package (<c>.playwright/package/lib/generated/injectedScriptSource.js</c>,+/// copied next to the app by the Microsoft.Playwright NuGet package). The humanize+/// layer evaluates it in its own execution context. The literal comes from the+/// installed driver, so selector syntax always matches+/// the client that produced the selector string.+/// </summary>+internal static class InjectedSource+{+ /// <summary>Global name inside the isolated world (invisible to page scripts).</summary>+ public const string Global = "__cloakInjected";++ private static readonly Regex LiteralStart = new(@"\bsource\d*\s*[=:]\s*(['""`])", RegexOptions.Compiled);+ private static string? _literal;+ private static readonly object Lock = new();++ /// <summary>Driver lib directories to search (app base dir first, then the NuGet cache).</summary>+ internal static IEnumerable<string> LibDirs()+ {+ var env = Environment.GetEnvironmentVariable("PLAYWRIGHT_DRIVER_SEARCH_PATH");+ if (!string.IsNullOrEmpty(env)) yield return Path.Combine(env, ".playwright", "package", "lib");+ yield return Path.Combine(AppContext.BaseDirectory, ".playwright", "package", "lib");+ var asmDir = Path.GetDirectoryName(typeof(Microsoft.Playwright.IPage).Assembly.Location);+ if (!string.IsNullOrEmpty(asmDir))+ {+ yield return Path.Combine(asmDir, ".playwright", "package", "lib");+ // NuGet cache layout: <pkg>/<ver>/lib/netstandard2.0/Microsoft.Playwright.dll+ yield return Path.GetFullPath(Path.Combine(asmDir, "..", "..", ".playwright", "package", "lib"));+ }+ }++ /// <summary>The JS string literal starting at <paramref name="start"/> (quotes included).</summary>+ internal static string ReadLiteral(string text, int start)+ {+ char quote = text[start];+ int i = start + 1;+ while (text[i] != quote) i += text[i] == '\\' ? 2 : 1;+ return text.Substring(start, i + 1 - start);+ }++ /// <summary>Locate the InjectedScript source literal (bundled or per-file layout).</summary>+ public static string FindLiteral(IEnumerable<string>? dirs = null)+ {+ lock (Lock)+ {+ if (_literal != null && dirs == null) return _literal;+ var searched = new List<string>();+ foreach (var d in dirs ?? LibDirs())+ {+ searched.Add(d);+ if (!Directory.Exists(d)) continue;+ var bundle = Path.Combine(d, "coreBundle.js");+ if (File.Exists(bundle))+ {+ var text = File.ReadAllText(bundle, Encoding.UTF8);+ int pos = text.IndexOf("generated/injectedScriptSource.ts", StringComparison.Ordinal);+ if (pos >= 0)+ {+ var m = LiteralStart.Match(text, pos);+ if (m.Success) return Remember(ReadLiteral(text, m.Groups[1].Index), dirs);+ }+ }+ foreach (var f in Directory.EnumerateFiles(d, "injectedScriptSource.js", SearchOption.AllDirectories).OrderBy(x => x, StringComparer.Ordinal))+ {+ var text = File.ReadAllText(f, Encoding.UTF8);+ var m = LiteralStart.Match(text);+ if (m.Success) return Remember(ReadLiteral(text, m.Groups[1].Index), dirs);+ }+ }+ throw new InvalidOperationException(+ "cloakbrowser humanize: Playwright's InjectedScript source was not found in " ++ string.Join(", ", searched) + "; the installed Microsoft.Playwright layout is not supported");+ }+ }++ private static string Remember(string lit, IEnumerable<string>? dirs)+ {+ if (dirs == null) _literal = lit;+ return lit;+ }++ /// <summary>Expression that installs the engine in the current (isolated) world.+ /// <paramref name="source"/> is the decoded module text. Idempotent; supports the+ /// positional (< 1.47) and options-object constructors.</summary>+ public static string BuildInstallJs(string source, string sdkLanguage = "csharp", string testIdAttribute = "data-testid")+ {+ var opts = JsonSerializer.Serialize(new Dictionary<string, object>+ {+ ["isUnderTest"] = false,+ ["sdkLanguage"] = sdkLanguage,+ ["testIdAttributeName"] = testIdAttribute,+ ["stableRafCount"] = 1,+ ["browserName"] = "chromium",+ ["isUtilityWorld"] = true,+ ["customEngines"] = Array.Empty<object>(),+ });+ return "(() => {\n" ++ $"if (globalThis.{Global}) return true;\n" ++ "const module = { exports: {} }; const exports = module.exports;\n" ++ source + "\n" ++ ";const exp = module.exports.InjectedScript;\n" ++ "const C = (exp && exp.prototype && exp.prototype.querySelectorAll) ? exp : exp();\n" ++ "C.prototype._setupGlobalListenersRemovalDetection = function () {};\n" ++ "C.prototype._setupHitTargetInterceptors = function () {};\n" ++ $"const o = {opts};\n" ++ "const inj = C.length > 2\n" ++ " ? new C(globalThis, o.isUnderTest, o.sdkLanguage, o.testIdAttributeName, o.stableRafCount, o.browserName, o.customEngines)\n" ++ " : new C(globalThis, o);\n" ++ $"Object.defineProperty(globalThis, {JsonSerializer.Serialize(Global)}, {{ value: inj }});\n" ++ "return true; })()";+ }+}diff --git a/dotnet/src/CloakBrowser/Human/PlaywrightAdapters.cs b/dotnet/src/CloakBrowser/Human/PlaywrightAdapters.csdeleted file mode 100644index 5cdf2a4..0000000--- a/dotnet/src/CloakBrowser/Human/PlaywrightAdapters.cs+++ /dev/null@@ -1,138 +0,0 @@-using System.Text.Json.Nodes;-using Microsoft.Playwright;--namespace CloakBrowser.Human;--/// <summary>Adapts Playwright's <see cref="IMouse"/> to <see cref="IRawMouse"/>.</summary>-internal sealed class PlaywrightRawMouse : IRawMouse-{- private readonly IMouse _mouse;- public PlaywrightRawMouse(IMouse mouse) => _mouse = mouse;-- public Task MoveAsync(double x, double y) => _mouse.MoveAsync((float)x, (float)y);- public Task DownAsync() => _mouse.DownAsync();- public Task UpAsync() => _mouse.UpAsync();- public Task WheelAsync(double deltaX, double deltaY) => _mouse.WheelAsync((float)deltaX, (float)deltaY);-}--/// <summary>Adapts Playwright's <see cref="IKeyboard"/> to <see cref="IRawKeyboard"/>.</summary>-internal sealed class PlaywrightRawKeyboard : IRawKeyboard-{- private readonly IKeyboard _keyboard;- public PlaywrightRawKeyboard(IKeyboard keyboard) => _keyboard = keyboard;-- public Task DownAsync(string key) => _keyboard.DownAsync(key);- public Task UpAsync(string key) => _keyboard.UpAsync(key);- public Task TypeAsync(string text) => _keyboard.TypeAsync(text);- public Task InsertTextAsync(string text) => _keyboard.InsertTextAsync(text);-}--/// <summary>Adapts a Playwright <see cref="ICDPSession"/> to <see cref="IRawCdpSession"/>.</summary>-internal sealed class PlaywrightCdpSession : IRawCdpSession-{- private readonly ICDPSession _session;- public PlaywrightCdpSession(ICDPSession session) => _session = session;-- public async Task SendAsync(string method, JsonObject? args = null)- {- if (args == null)- {- await _session.SendAsync(method).ConfigureAwait(false);- return;- }- var dict = new Dictionary<string, object>();- foreach (var kv in args)- {- if (kv.Value is JsonValue jv)- {- if (jv.TryGetValue<int>(out var i)) dict[kv.Key] = i;- else if (jv.TryGetValue<double>(out var d)) dict[kv.Key] = d;- else if (jv.TryGetValue<bool>(out var b)) dict[kv.Key] = b;- else dict[kv.Key] = jv.ToString();- }- else if (kv.Value != null)- {- dict[kv.Key] = kv.Value;- }- }- await _session.SendAsync(method, dict).ConfigureAwait(false);- }-}--/// <summary>Adapts a Playwright <see cref="IPage"/> to <see cref="IRawEvaluator"/> (fallback shift-symbol path).</summary>-internal sealed class PlaywrightEvaluator : IRawEvaluator-{- private readonly IPage _page;- public PlaywrightEvaluator(IPage page) => _page = page;-- public async Task EvaluateAsync(string expression, object? arg)- {- await _page.EvaluateAsync(expression, arg).ConfigureAwait(false);- }-}--/// <summary>Adapts a Playwright <see cref="IPage"/> to <see cref="IRawScrollPage"/>.</summary>-internal sealed class PlaywrightScrollPage : IRawScrollPage-{- private readonly IPage _page;- private readonly Func<Task<IsolatedWorld>> _getStealthAsync;-- public PlaywrightScrollPage(IPage page, Func<Task<IsolatedWorld>> getStealthAsync)- {- _page = page;- _getStealthAsync = getStealthAsync;- }-- public (int Width, int Height)? ViewportSize- {- get- {- var vs = _page.ViewportSize;- return vs == null ? null : (vs.Width, vs.Height);- }- }-- public async Task<(int Width, int Height)?> GetLiveWindowSizeAsync()- {- var world = await _getStealthAsync().ConfigureAwait(false);- var value = await world.EvaluateAsync(StealthDom.ViewportJs).ConfigureAwait(false);- if (value == null || value.Value.ValueKind != System.Text.Json.JsonValueKind.Object- || !value.Value.TryGetProperty("width", out var width)- || !value.Value.TryGetProperty("height", out var height))- throw new StealthEvaluationError("<viewport>");-- int resolvedWidth = (int)width.GetDouble();- int resolvedHeight = (int)height.GetDouble();- if (resolvedWidth <= 0 || resolvedHeight <= 0)- throw new StealthEvaluationError("<viewport>");- return (resolvedWidth, resolvedHeight);- }-- public async Task<(double Y, double MaxY, double X, double MaxX)?> GetScrollStateAsync()- {- var world = await _getStealthAsync().ConfigureAwait(false);- // In RTL documents Chrome's scrollX runs from 0 down to -range, and the- // viewport takes its direction from <body> when there is one.- var value = await world.EvaluateAsync(- "(() => { const e = document.scrollingElement || document.documentElement;" +- " const rangeX = Math.max(0, e.scrollWidth - e.clientWidth);" +- " const rtl = getComputedStyle(document.body || e).direction === 'rtl';" +- " return { y: window.scrollY, maxY: Math.max(0, e.scrollHeight - e.clientHeight)," +- " x: window.scrollX, minX: rtl ? -rangeX : 0, maxX: rtl ? 0 : rangeX }; })()")- .ConfigureAwait(false);- return ParseScrollState(value);- }-- /// <summary>Shifts X and MaxX by minX so X runs from 0 at the leftmost position in LTR and RTL alike.</summary>- internal static (double Y, double MaxY, double X, double MaxX) ParseScrollState(System.Text.Json.JsonElement? value)- {- if (value == null || value.Value.ValueKind != System.Text.Json.JsonValueKind.Object- || !value.Value.TryGetProperty("y", out var y)- || !value.Value.TryGetProperty("maxY", out var maxY)- || !value.Value.TryGetProperty("x", out var x)- || !value.Value.TryGetProperty("minX", out var minX)- || !value.Value.TryGetProperty("maxX", out var maxX))- throw new StealthEvaluationError("<scroll-state>");- return (y.GetDouble(), maxY.GetDouble(), x.GetDouble() - minX.GetDouble(), maxX.GetDouble() - minX.GetDouble());- }-}diff --git a/dotnet/src/CloakBrowser/Human/StealthDom.cs b/dotnet/src/CloakBrowser/Human/StealthDom.csdeleted file mode 100644index 1316534..0000000--- a/dotnet/src/CloakBrowser/Human/StealthDom.cs+++ /dev/null@@ -1,766 +0,0 @@-using System;-using System.Globalization;-using System.Text.Json;-using System.Threading.Tasks;-namespace CloakBrowser.Human;-public enum StealthStatus { Ok, NotFound, Unsupported, Stale, EvaluationFailed }-public class StealthDomError : Exception { public StealthDomError(string m):base(m){} }-public sealed class UnsupportedHumanizeSelectorError : StealthDomError { public UnsupportedHumanizeSelectorError(string s):base($"Humanized selector '{s}' is not supported by the isolated-world resolver. Supported: CSS, text=, xpath=, GetByTestId, GetByPlaceholder, GetByAltText, GetByTitle, GetByText, GetByLabel, and a trailing First/Nth/Last. Not supported: GetByRole, chained locators (a >> b, Filter, And, Or), FrameLocator, :visible and :nth-match. Use a CSS or text= selector for this action, or disable humanize to fall back to Playwright."){} }-public sealed class StealthWorldUnavailableError : StealthDomError { public StealthWorldUnavailableError():base("Humanized DOM read requires an active isolated world"){} }-public sealed class StealthEvaluationError : StealthDomError { public StealthEvaluationError(string s):base($"Isolated-world DOM evaluation failed for '{s}'"){} }-internal readonly record struct StealthSnapshot(int TargetId,int Gen,bool Attached,bool Visible,bool Enabled,bool Editable,bool IsInput,bool Focused,bool? Checked,BoundingBox? Box);-internal readonly record struct StealthTargetBox(BoundingBox Box,int TargetId,int Gen);-internal readonly record struct StealthBoxRead(StealthStatus Status,StealthTargetBox? Target)-{- public BoundingBox? Box => Target?.Box;- public int? TargetId => Target?.TargetId;- public void Deconstruct(out StealthStatus status, out StealthTargetBox? target) { status = Status; target = Target; }-}-internal readonly record struct StealthActionableRead(StealthStatus Status,StealthSnapshot? Snapshot)-{- public void Deconstruct(out StealthStatus status, out StealthSnapshot? snapshot) { status = Status; snapshot = Snapshot; }-}-internal readonly record struct StealthValidateRead(StealthStatus Status,bool Hit,string Covering,int? CurrentTargetId);-internal static class StealthDom {-private const string ResolverBody = """-const __UNS = 'UNSUPPORTED';-const __V = 2;-const __STATE_KEY = '__cloakHumanDomV1';-function __state(){- let s = globalThis[__STATE_KEY];- if (!s) {- // Element ids restart at 1 in every new world, and the world is recreated on- // navigation (#507), so an id alone can name a different element after a nav.- // The generation makes that cross-world reuse detectable as 'stale'.- // 11 bits of wall clock + 20 bits of randomness. The maximum is exactly- // Int32.MaxValue, because the .NET wrapper carries the value as an Int32.- s = { ids: new WeakMap(), nextId: 1,- gen: (Date.now() & 2047) * 1048576 + Math.floor(Math.random() * 1048576) };- Object.defineProperty(globalThis, __STATE_KEY, { value: s, configurable: false, enumerable: false });- }- return s;-}-function __gen(){ return __state().gen; }-function __targetId(el){- const s = __state();- let id = s.ids.get(el);- if (!id) { id = s.nextId++; s.ids.set(el, id); }- return id;-}-function __visibleTextNode(node){- const range = node.ownerDocument.createRange();- range.selectNode(node);- const rect = range.getBoundingClientRect();- return rect.width > 0 && rect.height > 0;-}-function __isVisible(el){- const style = getComputedStyle(el);- if (!style) return true;- if (style.display === 'contents') {- for (let child = el.firstChild; child; child = child.nextSibling) {- if (child.nodeType === 1 && __isVisible(child)) return true;- if (child.nodeType === 3 && style.visibility === 'visible' && __visibleTextNode(child)) return true;- }- return false;- }- try {- if (typeof el.checkVisibility === 'function' && !el.checkVisibility()) return false;- } catch (e) {- // Older engines fall through to computed style + geometry.- }- if (style.visibility !== 'visible') return false;- const rect = el.getBoundingClientRect();- return rect.width > 0 && rect.height > 0;-}-function __visBox(el){- const style = getComputedStyle(el);- if (style && style.display === 'contents') {- let x1 = Infinity, y1 = Infinity, x2 = -Infinity, y2 = -Infinity;- let found = false;- for (let child = el.firstChild; child; child = child.nextSibling) {- let box = null;- if (child.nodeType === 1 && __isVisible(child)) {- box = __visBox(child);- } else if (child.nodeType === 3 && style.visibility === 'visible' &&- __normWS(child.nodeValue)) {- const range = child.ownerDocument.createRange();- range.selectNode(child);- const rect = range.getBoundingClientRect();- if (rect.width > 0 && rect.height > 0) {- box = { x: rect.x, y: rect.y, width: rect.width, height: rect.height };- }- }- if (!box) continue;- found = true;- x1 = Math.min(x1, box.x);- y1 = Math.min(y1, box.y);- x2 = Math.max(x2, box.x + box.width);- y2 = Math.max(y2, box.y + box.height);- }- return found ? { x: x1, y: y1, width: x2 - x1, height: y2 - y1 } : null;- }- const rect = el.getBoundingClientRect();- return rect.width > 0 && rect.height > 0- ? { x: rect.x, y: rect.y, width: rect.width, height: rect.height }- : null;-}-const __ARIA_DISABLED_ROLES = new Set([- 'application','button','composite','gridcell','group','input','link','menuitem',- 'scrollbar','separator','tab','checkbox','columnheader','combobox','grid','listbox',- 'menu','menubar','menuitemcheckbox','menuitemradio','option','radio','radiogroup',- 'row','rowheader','searchbox','select','slider','spinbutton','switch','tablist',- 'textbox','toolbar','tree','treegrid','treeitem'-]);-const __ARIA_READONLY_ROLES = new Set([- 'checkbox','combobox','grid','gridcell','listbox','radiogroup','slider','spinbutton',- 'textbox','columnheader','rowheader','searchbox','switch','treegrid'-]);-function __role(el){- const explicit = (el.getAttribute('role') || '').trim().split(/\s+/)[0];- if (explicit) return explicit;- const tag = el.tagName.toLowerCase();- if (tag === 'button') return 'button';- if (tag === 'textarea') return 'textbox';- if (tag === 'select') return el.multiple ? 'listbox' : 'combobox';- if (tag === 'option') return 'option';- if ((tag === 'a' || tag === 'area') && el.hasAttribute('href')) return 'link';- if (tag === 'input') {- const type = (el.type || 'text').toLowerCase();- if (['button','submit','reset','image'].includes(type)) return 'button';- if (type === 'checkbox') return 'checkbox';- if (type === 'radio') return 'radio';- if (type === 'range') return 'slider';- if (type === 'number') return 'spinbutton';- if (type === 'search') return 'searchbox';- if (!['hidden','file','color'].includes(type)) return 'textbox';- }- return '';-}-function __nativeDisabled(el){- const tag = el.tagName.toLowerCase();- if (!['button','input','select','textarea','option','optgroup'].includes(tag)) return false;- if (el.hasAttribute('disabled')) return true;- if (tag === 'option' && el.closest('optgroup[disabled]')) return true;- const fieldset = el.closest('fieldset[disabled]');- if (!fieldset) return false;- const legend = fieldset.querySelector(':scope > legend');- return !legend || !legend.contains(el);-}-function __ariaDisabled(el){- if (!__ARIA_DISABLED_ROLES.has(__role(el))) return false;- let current = el;- while (current) {- const value = (current.getAttribute('aria-disabled') || '').toLowerCase();- if (value === 'true') return true;- if (value === 'false') return false;- current = __composedParent(current);- }- return false;-}-function __isEnabled(el){ return !(__nativeDisabled(el) || __ariaDisabled(el)); }-function __readonly(el){- const tag = el.tagName.toLowerCase();- if (tag === 'input' || tag === 'textarea' || tag === 'select') return el.hasAttribute('readonly');- if (__ARIA_READONLY_ROLES.has(__role(el))) return el.getAttribute('aria-readonly') === 'true';- if (el.isContentEditable) return false;- return null;-}-function __isEditable(el, enabled){- const readonly = __readonly(el);- return readonly === null ? false : enabled && !readonly;-}-function __normWS(s){- return (s || '').replace(/[\u200b\u00ad]/g, '').replace(/\s+/g, ' ').trim();-}-function __skipText(el){- const tag = el && el.tagName ? el.tagName.toLowerCase() : '';- return tag === 'script' || tag === 'style' || tag === 'noscript' ||- (document.head && document.head.contains(el));-}-function __elementText(el, cache){- if (cache.has(el)) return cache.get(el);- let out = { full: '', normalized: '', immediate: [] };- cache.set(el, out);- if (__skipText(el)) return out;- const tag = el.tagName ? el.tagName.toLowerCase() : '';- if (tag === 'input' && ['button', 'submit', 'reset'].includes((el.type || '').toLowerCase())) {- const value = el.value || '';- out = { full: value, normalized: __normWS(value), immediate: [value] };- cache.set(el, out);- return out;- }- if (!el.childNodes) {- const value = el.textContent || '';- out = { full: value, normalized: __normWS(value), immediate: value ? [value] : [] };- cache.set(el, out);- return out;- }- let full = '', immediate = '';- const fragments = [];- for (const child of el.childNodes) {- if (child.nodeType === 3) {- const value = child.nodeValue || '';- full += value;- immediate += value;- } else if (child.nodeType === 8) {- continue;- } else {- if (immediate) { fragments.push(immediate); immediate = ''; }- if (child.nodeType === 1) full += __elementText(child, cache).full;- }- }- if (immediate) fragments.push(immediate);- if (el.shadowRoot) full += __elementText(el.shadowRoot, cache).full;- out = { full: full, normalized: __normWS(full), immediate: fragments };- cache.set(el, out);- return out;-}-function __byXPath(xp){- try {- const r = document.evaluate(xp, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);- const out = [];- for (let i = 0; i < r.snapshotLength; i++) { out.push(r.snapshotItem(i)); }- return out;- } catch (e) { return __UNS; }-}-function __parseTextMatcher(arg){- arg = arg.trim();- if (arg.charAt(0) === '/') {- let end = -1, escaped = false;- for (let i = 1; i < arg.length; i++) {- const ch = arg.charAt(i);- if (!escaped && ch === '/') end = i;- escaped = !escaped && ch === '\\';- if (ch !== '\\') escaped = false;- }- if (end > 0) {- try { return { kind: 'regex', regex: new RegExp(arg.slice(1, end), arg.slice(end + 1)) }; }- catch (e) { return __UNS; }- }- }- const q = arg.charAt(0);- if ((q === '"' || q === "'") && arg.charAt(arg.length - 1) === q) {- let value;- try {- value = q === '"' ? JSON.parse(arg) : arg.slice(1, -1).replace(/\\(['"\\])/g, '$1');- } catch (e) { return __UNS; }- return { kind: 'exact', value: __normWS(value) };- }- return { kind: 'lax', value: __normWS(arg).toLowerCase() };-}-function __matchTextValue(text, matcher){- if (matcher.kind === 'regex') { matcher.regex.lastIndex = 0; return matcher.regex.test(text.full); }- // The public engine's exact rule compares immediate text-node runs, unlike- // internal:text which compares the full normalized subtree text.- if (matcher.kind === 'exact') return text.immediate.some(x => __normWS(x) === matcher.value);- return text.normalized.toLowerCase().includes(matcher.value);-}-function __matchText(el, matcher, cache){- return __matchTextValue(__elementText(el, cache), matcher);-}-function __publicTextMatches(el, matcher, cache){- // Playwright's elementMatchesText for the public text= engine.- if (__skipText(el)) return 'none';- if (!__matchText(el, matcher, cache)) return 'none';- for (const child of el.children || []) {- if (__matchText(child, matcher, cache)) return 'selfAndChildren';- }- // A host whose shadow content also matches is not the smallest match. This- // cannot be expressed with contains(), which does not pierce shadow roots.- if (el.shadowRoot && __matchTextValue(__elementText(el.shadowRoot, cache), matcher))- return 'selfAndChildren';- return 'self';-}-function __byText(arg){- const matcher = __parseTextMatcher(arg);- if (matcher === __UNS) return __UNS;- const out = [], cache = new Map();- let lastMiss = null;- for (const el of __allElements()) {- // Nothing under a non-matching ancestor can match in lax mode.- if (matcher.kind === 'lax' && lastMiss && lastMiss.contains(el)) continue;- const m = __publicTextMatches(el, matcher, cache);- if (m === 'none') lastMiss = el;- // The public engine also keeps an ancestor when the match is exact.- if (m === 'self' || (m === 'selfAndChildren' && matcher.kind === 'exact')) out.push(el);- }- return out;-}-function __attrUnquote(s, i){- // parseAttributeSelector.readQuotedString: a backslash is dropped and the next- // character taken verbatim -- NOT JSON escapes, so "a\\nb" decodes to 'anb'.- const quote = s.charAt(i);- if (quote !== '"' && quote !== "'") return __UNS;- let out = '';- i++;- while (i < s.length && s.charAt(i) !== quote) {- if (s.charAt(i) === '\\') {- i++;- if (i >= s.length) return __UNS;- }- out += s.charAt(i++);- }- if (s.charAt(i) !== quote) return __UNS;- return { value: out, end: i + 1 };-}-function __parseAttrBody(body){- // [name="value"i] | [name="value"s] | [name=/re/flags]- body = body.trim();- if (body.charAt(0) !== '[' || body.charAt(body.length - 1) !== ']') return __UNS;- const inner = body.slice(1, -1);- const eq = inner.indexOf('=');- if (eq <= 0) return __UNS;- let name = inner.slice(0, eq).trim();- if (name.charAt(0) === '"' || name.charAt(0) === "'") {- const un = __attrUnquote(name, 0);- if (un === __UNS || un.end !== name.length) return __UNS;- name = un.value;- }- // isCSSNameChar, plus ',' for the comma-joined test-id name list. Also rejects- // the *= ^= $= |= ~= operators, whose extra character lands in the name.- if (!/^[\w\u0080-\uFFFF,-]+$/.test(name)) return __UNS;- const rest = inner.slice(eq + 1);- let j = 0;- while (j < rest.length && /\s/.test(rest.charAt(j))) j++;- if (rest.charAt(j) === '/') {- const end = rest.lastIndexOf('/');- if (end <= j) return __UNS;- const flags = rest.slice(end + 1).trim();- if (!/^[dgimsuvy]*$/.test(flags)) return __UNS;- try { return { name: name, regex: new RegExp(rest.slice(j + 1, end), flags), value: null, caseSensitive: true }; }- catch (e) { return __UNS; }- }- const un = __attrUnquote(rest, j);- if (un === __UNS) return __UNS;- let k = un.end, caseSensitive = true;- const flag = rest.charAt(k);- if (flag === 'i' || flag === 'I') { caseSensitive = false; k++; }- else if (flag === 's' || flag === 'S') { caseSensitive = true; k++; }- while (k < rest.length && /\s/.test(rest.charAt(k))) k++;- if (k !== rest.length) return __UNS;- return { name: name, regex: null, value: un.value, caseSensitive: caseSensitive };-}-function __byAttr(body){- // Serves internal:attr (placeholder/alt/title) AND internal:testid -- the- // attribute name comes from the selector. The 'i' flag means case-insensitive- // SUBSTRING, and the RAW attribute value is compared: no trim, no whitespace- // normalization. get_by_test_id always emits 's', so it is strict equality.- const parsed = __parseAttrBody(body);- if (parsed === __UNS) return __UNS;- const names = parsed.name.split(',');- const lower = (parsed.regex || parsed.caseSensitive) ? null : parsed.value.toLowerCase();- const out = [];- try {- for (const el of __allElements()) {- if (!el.getAttribute) continue;- for (const name of names) {- const actual = el.getAttribute(name);- if (actual === null || actual === undefined) continue;- let hit;- if (parsed.regex) { parsed.regex.lastIndex = 0; hit = !!String(actual).match(parsed.regex); }- else if (parsed.caseSensitive) hit = actual === parsed.value;- else hit = String(actual).toLowerCase().indexOf(lower) !== -1;- if (hit) { out.push(el); break; }- }- }- } catch (e) { return __UNS; }- return out;-}-function __parseInternalTextMatcher(arg){- // createTextMatcher(selector, internal=true). Playwright does not trim here.- if (arg.charAt(0) === '/' && arg.lastIndexOf('/') > 0) {- const end = arg.lastIndexOf('/');- try { return { kind: 'regex', regex: new RegExp(arg.slice(1, end), arg.slice(end + 1)) }; }- catch (e) { return __UNS; }- }- if (arg.length > 1 && arg.charAt(0) === '"') {- let body = null, strict = false;- const last = arg.charAt(arg.length - 1);- if (last === '"') { body = arg; strict = true; }- else if (arg.charAt(arg.length - 2) === '"' && (last === 's' || last === 'i')) {- body = arg.slice(0, -1); strict = last === 's';- } else return __UNS;- let value;- try { value = JSON.parse(body); } catch (e) { return __UNS; }- if (typeof value !== 'string') return __UNS;- const norm = __normWS(value);- return strict ? { kind: 'strict', value: norm } : { kind: 'lax', value: norm.toLowerCase() };- }- // A single-quoted body reaches unquote=JSON.parse in Playwright and throws.- if (arg.length > 1 && arg.charAt(0) === "'" && arg.charAt(arg.length - 1) === "'") return __UNS;- return { kind: 'lax', value: __normWS(arg).toLowerCase() };-}-function __matchInternalText(text, matcher){- if (matcher.kind === 'regex') { matcher.regex.lastIndex = 0; return matcher.regex.test(text.full); }- // strict compares the FULL normalized subtree text. The public text= engine- // compares immediate fragments instead (__matchText) -- genuinely different.- if (matcher.kind === 'strict') return text.normalized === matcher.value;- return text.normalized.toLowerCase().indexOf(matcher.value) !== -1;-}-function __internalTextMatches(el, matcher, cache){- if (__skipText(el)) return 'none';- if (!__matchInternalText(__elementText(el, cache), matcher)) return 'none';- // Direct children only, plus the shadow-root probe -- NOT contains() over the- // match set, which would drop an outer element matched only via a grandchild.- for (const child of el.children || []) {- if (__matchInternalText(__elementText(child, cache), matcher)) return 'selfAndChildren';- }- if (el.shadowRoot && __matchInternalText(__elementText(el.shadowRoot, cache), matcher)) return 'selfAndChildren';- return 'self';-}-function __byInternalText(arg){- const matcher = __parseInternalTextMatcher(arg);- if (matcher === __UNS) return __UNS;- const cache = new Map(), out = [];- let lastMiss = null;- for (const el of __allElements()) {- // lastDidNotMatchSelf: in lax mode nothing under a non-matching ancestor matches.- if (matcher.kind === 'lax' && lastMiss && lastMiss.contains(el)) continue;- const m = __internalTextMatches(el, matcher, cache);- if (m === 'none') lastMiss = el;- if (m === 'self') out.push(el);- }- return out;-}-function __idRefRoot(el){- const root = el.getRootNode ? el.getRootNode() : null;- return (root && typeof root.getElementById === 'function') ? root : document;-}-function __labelledByElements(el){- const ref = el.getAttribute ? el.getAttribute('aria-labelledby') : null;- if (ref === null || ref === undefined) return null;- const root = __idRefRoot(el), out = [];- for (const id of ref.split(/\s+/)) {- if (!id) continue;- const target = root.getElementById(id);- if (target && out.indexOf(target) === -1) out.push(target);- }- return out.length ? out : null;-}-function __elementLabels(el, cache){- // First non-empty source wins: aria-labelledby, then aria-label, then .labels.- const refs = __labelledByElements(el);- if (refs) return refs.map(function(x){ return __elementText(x, cache); });- const aria = el.getAttribute ? el.getAttribute('aria-label') : null;- if (aria !== null && aria !== undefined && aria.trim())- return [{ full: aria, normalized: __normWS(aria), immediate: [aria] }];- const tag = el.tagName ? el.tagName.toUpperCase() : '';- const nonHiddenInput = tag === 'INPUT' && String(el.type || '').toLowerCase() !== 'hidden';- if (nonHiddenInput || ['BUTTON','METER','OUTPUT','PROGRESS','SELECT','TEXTAREA'].indexOf(tag) !== -1) {- // Native .labels already resolves both for/id and a wrapping <label>.- const labels = el.labels;- if (labels) return Array.prototype.slice.call(labels).map(function(x){ return __elementText(x, cache); });- }- return [];-}-function __byLabel(arg){- const matcher = __parseInternalTextMatcher(arg);- if (matcher === __UNS) return __UNS;- const cache = new Map(), out = [];- try {- for (const el of __allElements()) {- const labels = __elementLabels(el, cache);- for (const label of labels) {- if (__matchInternalText(label, matcher)) { out.push(el); break; }- }- }- } catch (e) { return __UNS; }- return out;-}-function __allElements(){- if (!document.children && document.querySelectorAll)- return Array.prototype.slice.call(document.querySelectorAll('*'));- const out = [];- function visitRoot(root){- const light = [];- function collectLight(parent){- for (const el of parent.children || []) {- out.push(el);- light.push(el);- collectLight(el);- }- }- collectLight(root);- for (const host of light) {- if (host.shadowRoot) visitRoot(host.shadowRoot);- }- }- visitRoot(document);- return out;-}-function __readQuoted(value){- value = value.trim();- const q = value.charAt(0);- if ((q !== '"' && q !== "'") || value.charAt(value.length - 1) !== q) return __UNS;- try {- return q === '"' ? JSON.parse(value) : value.slice(1, -1).replace(/\\(['"\\])/g, '$1');- } catch (e) { return __UNS; }-}-function __parseCompound(compound){- let css = '', i = 0;- const texts = [];- while (i < compound.length) {- if (compound.slice(i, i + 10) !== ':has-text(') { css += compound.charAt(i++); continue; }- let j = i + 10, quote = '', escaped = false, depth = 1;- for (; j < compound.length; j++) {- const ch = compound.charAt(j);- if (quote) {- if (!escaped && ch === quote) quote = '';- escaped = !escaped && ch === '\\';- if (ch !== '\\') escaped = false;- continue;- }- if (ch === '"' || ch === "'") { quote = ch; continue; }- if (ch === '(') depth++;- else if (ch === ')' && --depth === 0) break;- }- if (depth !== 0) return __UNS;- const text = __readQuoted(compound.slice(i + 10, j));- if (text === __UNS) return __UNS;- texts.push(__normWS(text).toLowerCase());- i = j + 1;- }- css = css.trim() || '*';- if (css.includes(':has-text') || /:(?:text|text-is|text-matches|visible|nth-match)\b/.test(css)) return __UNS;- return { css: css, texts: texts };-}-function __splitSelectorList(css){- const parts = [];- let buf = '', quote = '', escaped = false, brackets = 0, parens = 0;- for (let i = 0; i < css.length; i++) {- const ch = css.charAt(i);- if (escaped) { buf += ch; escaped = false; continue; }- if (ch === '\\') { buf += ch; escaped = true; continue; }- if (quote) {- buf += ch;- if (ch === quote) quote = '';- continue;- }- if (ch === '"' || ch === "'") { quote = ch; buf += ch; continue; }- if (ch === '[') brackets++;- else if (ch === ']') brackets--;- else if (ch === '(') parens++;- else if (ch === ')') parens--;- if (ch === ',' && brackets === 0 && parens === 0) {- if (!buf.trim()) return __UNS;- parts.push(buf.trim()); buf = ''; continue;- }- buf += ch;- }- if (quote || brackets !== 0 || parens !== 0 || !buf.trim()) return __UNS;- parts.push(buf.trim());- return parts;-}-function __parseCss(css){- const compounds = [], combinators = [];- let buf = '', quote = '', escaped = false, brackets = 0, parens = 0;- function pushCompound(){- const value = buf.trim();- if (!value) return false;- const parsed = __parseCompound(value);- if (parsed === __UNS) return __UNS;- compounds.push(parsed); buf = ''; return true;- }- for (let i = 0; i < css.length; i++) {- const ch = css.charAt(i);- if (quote) {- buf += ch;- if (!escaped && ch === quote) quote = '';- escaped = !escaped && ch === '\\';- if (ch !== '\\') escaped = false;- continue;- }- if (ch === '"' || ch === "'") { quote = ch; buf += ch; continue; }- if (ch === '[') { brackets++; buf += ch; continue; }- if (ch === ']') { brackets--; buf += ch; continue; }- if (ch === '(') { parens++; buf += ch; continue; }- if (ch === ')') { parens--; buf += ch; continue; }- if (brackets === 0 && parens === 0 && (ch === '>' || ch === '+' || ch === '~')) {- const pushed = pushCompound();- if (pushed === __UNS || !pushed) return __UNS;- combinators.push(ch);- while (i + 1 < css.length && /\s/.test(css.charAt(i + 1))) i++;- continue;- }- if (brackets === 0 && parens === 0 && /\s/.test(ch)) {- let j = i;- while (j + 1 < css.length && /\s/.test(css.charAt(j + 1))) j++;- const next = css.charAt(j + 1);- if (buf.trim() && next !== '>' && next !== '+' && next !== '~') {- const pushed = pushCompound();- if (pushed === __UNS) return __UNS;- combinators.push(' ');- }- i = j;- continue;- }- buf += ch;- }- const pushed = pushCompound();- if (pushed === __UNS) return __UNS;- if (!compounds.length || combinators.length !== compounds.length - 1) return __UNS;- return { compounds: compounds, combinators: combinators };-}-function __composedParent(el){- if (el.parentElement) return el.parentElement;- const root = el.getRootNode ? el.getRootNode() : null;- return root && root.host ? root.host : null;-}-function __matchesCompound(el, compound, cache){- try { if (typeof el.matches === 'function' && !el.matches(compound.css)) return false; }- catch (e) { return false; }- if (!compound.texts.length) return true;- const text = __elementText(el, cache).normalized.toLowerCase();- return compound.texts.every(x => text.includes(x));-}-function __matchesCss(el, parsed, cache){- let idx = parsed.compounds.length - 1, current = el;- if (!__matchesCompound(current, parsed.compounds[idx], cache)) return false;- while (idx > 0) {- const comb = parsed.combinators[idx - 1];- idx--;- if (comb === '>') {- current = __composedParent(current);- if (!current || !__matchesCompound(current, parsed.compounds[idx], cache)) return false;- } else if (comb === ' ') {- let parent = __composedParent(current), found = null;- while (parent) {- if (__matchesCompound(parent, parsed.compounds[idx], cache)) { found = parent; break; }- parent = __composedParent(parent);- }- if (!found) return false;- current = found;- } else {- let sibling = current.previousElementSibling;- if (comb === '+') {- if (!sibling || !__matchesCompound(sibling, parsed.compounds[idx], cache)) return false;- current = sibling;- } else {- let found = null;- while (sibling) {- if (__matchesCompound(sibling, parsed.compounds[idx], cache)) { found = sibling; break; }- sibling = sibling.previousElementSibling;- }- if (!found) return false;- current = found;- }- }- }- return true;-}-function __byCss(css){- if (css.includes(':scope')) return __UNS;- const branches = __splitSelectorList(css);- if (branches === __UNS) return __UNS;- const parsed = branches.map(__parseCss);- if (parsed.some(x => x === __UNS)) return __UNS;- const cache = new Map();- return __allElements().filter(- el => parsed.some(branch => __matchesCss(el, branch, cache))- );-}-function __deepElementFromPoint(x, y){- let target = document.elementFromPoint(x, y);- while (target && target.shadowRoot &&- typeof target.shadowRoot.elementFromPoint === 'function') {- const inner = target.shadowRoot.elementFromPoint(x, y);- if (!inner || inner === target) break;- target = inner;- }- return target;-}-function __deepActiveElement(){- let active = document.activeElement;- while (active && active.shadowRoot && active.shadowRoot.activeElement) {- active = active.shadowRoot.activeElement;- }- return active;-}-function __resolve(sel){- sel = sel.trim();- // Trailing ">> nth=N" (.first => nth=0, .last => nth=-1, .nth(k) => nth=k).- let nth = 0, hasNth = false;- const m = sel.match(/^([\s\S]*?)\s*>>\s*nth=(-?\d+)\s*$/);- if (m) { sel = m[1].trim(); nth = parseInt(m[2], 10); hasNth = true; }- if (sel.indexOf('>>') !== -1) return __UNS; // chaining we don't reimplement- let list;- // get_by_* engines we reimplement. Anything else under internal: (role, has,- // has-text, and, or, chain, control, describe) stays unsupported.- if (sel.indexOf('internal:testid=') === 0) { list = __byAttr(sel.slice(16)); }- else if (sel.indexOf('internal:attr=') === 0) { list = __byAttr(sel.slice(14)); }- else if (sel.indexOf('internal:text=') === 0) { list = __byInternalText(sel.slice(14)); }- else if (sel.indexOf('internal:label=') === 0) { list = __byLabel(sel.slice(15)); }- else if (sel.indexOf('internal:') !== -1) return __UNS;- else if (sel.indexOf('xpath=') === 0) { list = __byXPath(sel.slice(6)); }- else if (sel.indexOf('//') === 0 || sel.indexOf('(//') === 0 || sel.indexOf('..') === 0) { list = __byXPath(sel); }- else if (sel.indexOf('text=') === 0) { list = __byText(sel.slice(5)); }- else {- const css = (sel.indexOf('css=') === 0) ? sel.slice(4) : sel;- list = __byCss(css);- }- if (list === __UNS) return __UNS;- if (!list || !list.length) return null;- let idx = hasNth ? (nth < 0 ? list.length + nth : nth) : 0;- if (idx < 0 || idx >= list.length) return null;- return list[idx];-}-""";-private const string SnapshotOp = """-const __el=__resolve(__SEL);if(__el==='UNSUPPORTED')return {v:__V,r:'unsupported'};if(!__el)return {v:__V,r:'not_found'};const __box=__visBox(__el),__hasBox=__box!==null,__tag=__el.tagName.toLowerCase(),__enabled=__isEnabled(__el),__editable=__isEditable(__el,__enabled);return {v:__V,r:'ok',targetId:__targetId(__el),gen:__gen(),attached:__el.isConnected===true,visible:__isVisible(__el),enabled:__enabled,editable:__editable,isInput:__tag==='input'||__tag==='textarea'||__el.isContentEditable===true,focused:__deepActiveElement()===__el,checked:typeof __el.checked==='boolean'?__el.checked:null,box:__box};-""";-public const string ViewportJs="(() => ({ width: window.innerWidth, height: window.innerHeight }))()";-private static string Wrap(string s,string op)=>"(() => {\nconst __SEL = "+IsolatedWorld.JsonEncode(s)+";\n"+ResolverBody+"\n"+op+"\n})()";-public static string BuildSnapshotJs(string s)=>Wrap(s,SnapshotOp); public static string BuildBoxJs(string s)=>Wrap(s,SnapshotOp.Replace("r:'ok'","r:__hasBox?'ok':'not_found'",StringComparison.Ordinal)); public static string BuildActionableJs(string s)=>BuildSnapshotJs(s);-private static string Pointer(string s,int id,int gen,double x,double y,bool validate){var c=validate?"if(__g!=="+gen.ToString(CultureInfo.InvariantCulture)+")return {v:__V,r:'stale',targetId:__id,gen:__g};if(__id!=="+id.ToString(CultureInfo.InvariantCulture)+")return {v:__V,r:'stale',targetId:__id,gen:__g};if(__el.isConnected!==true)return {v:__V,r:'stale',targetId:__id,gen:__g};":"";return Wrap(s,"const __el=__resolve(__SEL);if(__el==='UNSUPPORTED')return {v:__V,r:'unsupported'};if(!__el)return {v:__V,r:'not_found'};const __g=__gen();const __id=__targetId(__el);"+c+"const __t=__deepElementFromPoint("+x.ToString(CultureInfo.InvariantCulture)+", "+y.ToString(CultureInfo.InvariantCulture)+");let __n=__t;while(__n){if(__n===__el)return {v:__V,r:'ok',targetId:__id,gen:__g,hit:true};__n=__composedParent(__n);}if(__t&&__el.contains(__t))return {v:__V,r:'ok',targetId:__id,gen:__g,hit:true};return {v:__V,r:'ok',targetId:__id,gen:__g,hit:false,covering:__t?(__t.tagName||'unknown'):'none'};");} public static string BuildValidateJs(string s,int id,int gen,double x,double y)=>Pointer(s,id,gen,x,y,true); public static string BuildPointerJs(string s,double x,double y)=>Pointer(s,0,0,x,y,false);-internal static (StealthStatus Status, JsonElement? Data) ParseResult(JsonElement? raw)-{- if (raw is not { ValueKind: JsonValueKind.Object } data- || !data.TryGetProperty("v", out var version)- || !version.TryGetInt32(out var versionNumber)- || versionNumber != 2- || !data.TryGetProperty("r", out var result)- || result.ValueKind != JsonValueKind.String)- return (StealthStatus.EvaluationFailed, null);-- var status = result.GetString() switch- {- "ok" => StealthStatus.Ok,- "not_found" => StealthStatus.NotFound,- "unsupported" => StealthStatus.Unsupported,- "stale" => StealthStatus.Stale,- _ => StealthStatus.EvaluationFailed,- };- if ((status is StealthStatus.Ok or StealthStatus.Stale)- && (!data.TryGetProperty("targetId", out var targetId)- || targetId.ValueKind != JsonValueKind.Number- || !targetId.TryGetInt32(out _)- || !data.TryGetProperty("gen", out var generation)- || generation.ValueKind != JsonValueKind.Number- || !generation.TryGetInt32(out _)))- return (StealthStatus.EvaluationFailed, null);-- return (status, status is StealthStatus.Ok or StealthStatus.Stale ? data : null);-}--private static async Task<(StealthStatus Status, JsonElement? Data)> Eval(IsolatedWorld world, string js)-{- try { return ParseResult(await world.EvaluateAsync(js).ConfigureAwait(false)); }- catch { return (StealthStatus.EvaluationFailed, null); }-}--private static bool B(JsonElement data, string name, out bool value)-{- value = false;- if (!data.TryGetProperty(name, out var element)- || element.ValueKind is not (JsonValueKind.True or JsonValueKind.False))- return false;- value = element.GetBoolean();- return true;-}--private static bool Snap(JsonElement d,out StealthSnapshot? s){s=null;if(!d.TryGetProperty("targetId",out var i)||!i.TryGetInt32(out var id)||!d.TryGetProperty("gen",out var gj)||!gj.TryGetInt32(out var gen)||!B(d,"attached",out var a)||!B(d,"visible",out var v)||!B(d,"enabled",out var e)||!B(d,"editable",out var ed)||!B(d,"isInput",out var inp)||!B(d,"focused",out var f)||!d.TryGetProperty("checked",out var ch)||ch.ValueKind is not(JsonValueKind.Null or JsonValueKind.True or JsonValueKind.False)||!d.TryGetProperty("box",out var z))return false;BoundingBox? box=null;if(z.ValueKind!=JsonValueKind.Null){if(z.ValueKind!=JsonValueKind.Object||!z.TryGetProperty("x",out var x)||!z.TryGetProperty("y",out var y)||!z.TryGetProperty("width",out var w)||!z.TryGetProperty("height",out var h)||x.ValueKind!=JsonValueKind.Number||y.ValueKind!=JsonValueKind.Number||w.ValueKind!=JsonValueKind.Number||h.ValueKind!=JsonValueKind.Number)return false;box=new(x.GetDouble(),y.GetDouble(),w.GetDouble(),h.GetDouble());}s=new(id,gen,a,v,e,ed,inp,f,ch.ValueKind==JsonValueKind.Null?null:ch.GetBoolean(),box);return true;}-public static async Task<(StealthStatus Status,StealthSnapshot? Snapshot)> SnapshotAsync(IsolatedWorld w,string s){var(r,d)=await Eval(w,BuildSnapshotJs(s));return r==StealthStatus.Ok&&Snap(d!.Value,out var p)?(r,p):r==StealthStatus.Ok?(StealthStatus.EvaluationFailed,null):(r,null);} public static async Task<StealthBoxRead> BoxAsync(IsolatedWorld w,string s){var(r,d)=await Eval(w,BuildBoxJs(s));return r==StealthStatus.Ok&&Snap(d!.Value,out var p)&&p!.Value.Box != null?new(r,new StealthTargetBox(p.Value.Box.Value,p.Value.TargetId,p.Value.Gen)):new(r==StealthStatus.Ok?StealthStatus.EvaluationFailed:r,null);} public static async Task<StealthActionableRead> ActionableAsync(IsolatedWorld w,string s){var r=await SnapshotAsync(w,s);return new(r.Status,r.Snapshot);}-public static async Task<(StealthStatus Status,bool Value)> IsInputAsync(IsolatedWorld w,string s){var r=await SnapshotAsync(w,s);return(r.Status,r.Snapshot?.IsInput??false);} public static async Task<(StealthStatus Status,bool Value)> IsFocusedAsync(IsolatedWorld w,string s){var r=await SnapshotAsync(w,s);return(r.Status,r.Snapshot?.Focused??false);} public static async Task<(StealthStatus Status,bool Value)> IsCheckedAsync(IsolatedWorld w,string s){var r=await SnapshotAsync(w,s);return(r.Status,r.Snapshot?.Checked??false);}-public static async Task<StealthValidateRead> ValidateAsync(IsolatedWorld w,string s,int id,int gen,double x,double y){var(r,d)=await Eval(w,BuildValidateJs(s,id,gen,x,y));if(r is not(StealthStatus.Ok or StealthStatus.Stale))return new(r,false,"unknown",null);var e=d!.Value;if(!e.GetProperty("targetId").TryGetInt32(out var actual))return new(StealthStatus.EvaluationFailed,false,"unknown",null);if(r==StealthStatus.Stale)return new(r,false,"unknown",actual);if(!e.TryGetProperty("hit",out var hit)||(hit.ValueKind is not(JsonValueKind.True or JsonValueKind.False)))return new(StealthStatus.EvaluationFailed,false,"unknown",null);return new(r,hit.GetBoolean(),e.TryGetProperty("covering",out var c)&&c.ValueKind==JsonValueKind.String?c.GetString()!:"unknown",actual);}-public static async Task<(StealthStatus Status,bool Hit,string Covering)> PointerAsync(IsolatedWorld w,string s,double x,double y){var(r,d)=await Eval(w,BuildPointerJs(s,x,y));if(r!=StealthStatus.Ok)return(r,false,"unknown");var e=d!.Value;if(!e.TryGetProperty("hit",out var hit)||(hit.ValueKind is not(JsonValueKind.True or JsonValueKind.False)))return(StealthStatus.EvaluationFailed,false,"unknown");return(r,hit.GetBoolean(),e.TryGetProperty("covering",out var c)&&c.ValueKind==JsonValueKind.String?c.GetString()!:"unknown");}-}diff --git a/dotnet/src/CloakBrowser/Human/WorldHelpers.cs b/dotnet/src/CloakBrowser/Human/WorldHelpers.csnew file mode 100644index 0000000..fccb622--- /dev/null+++ b/dotnet/src/CloakBrowser/Human/WorldHelpers.cs@@ -0,0 +1,259 @@+namespace CloakBrowser.Human;++/// <summary>+/// Helper library evaluated after the InjectedScript in every isolated world.+/// Byte-identical copy of <c>cloakbrowser/human/world.py</c> (<c>_HELPERS_JS</c>) and+/// <c>js/src/human/worldHelpers.ts</c>; checked by tests/test_resolver_sources_match.py.+/// Edit all three together.+/// </summary>+internal static class WorldHelpers+{+ public const string Name = "__cloakH";++ public const string Js = """+(() => {+if (globalThis.__cloakH) return true;+const I = globalThis.__cloakInjected;+const els = new Map(); let seq = 0;+const put = (e) => { const id = ++seq; els.set(id, e); return id; };+const get = (id) => { const e = els.get(id); if (!e) throw new Error('cloak:stale-element'); return e; };+const textValue = (t) => t.isContentEditable ? t.textContent : ('value' in t ? String(t.value) : null);+// display:contents elements have no box: use the union of what they render.+const contentsBox = (root) => {+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;+ const add = (r) => { if (!r.width && !r.height) return;+ x0 = Math.min(x0, r.left); y0 = Math.min(y0, r.top); x1 = Math.max(x1, r.right); y1 = Math.max(y1, r.bottom); };+ const walk = (n) => {+ for (const c of n.childNodes) {+ if (c.nodeType === 3) {+ if (!c.textContent.trim()) continue;+ const p = c.parentElement;+ if (p && getComputedStyle(p).visibility !== 'visible') continue;+ const rg = document.createRange(); rg.selectNodeContents(c);+ for (const r of rg.getClientRects()) add(r);+ } else if (c.nodeType === 1) {+ const s = getComputedStyle(c);+ if (s.display === 'contents') { walk(c); continue; }+ if (s.visibility !== 'visible' || s.display === 'none') continue;+ add(c.getBoundingClientRect());+ }+ }+ };+ walk(root);+ return x0 === Infinity ? null : { left: x0, top: y0, width: x1 - x0, height: y1 - y0 };+};+const parentOrHost = (n) => n.parentElement || (n.parentNode && n.parentNode.host) || null;+const H = {+ el: (id) => get(id),+ adopt() { return put(this); },+ matchRect(x, y, w, h) {+ // An ElementHandle carries no identity this context can read, but+ // Playwright reports its border box. Find the element with exactly that box.+ const out = [];+ const visit = (root) => {+ for (const e of root.querySelectorAll('*')) {+ if (e.shadowRoot) visit(e.shadowRoot);+ const b = e.getBoundingClientRect();+ if (Math.abs(b.left - x) < 0.6 && Math.abs(b.top - y) < 0.6 &&+ Math.abs(b.width - w) < 0.6 && Math.abs(b.height - h) < 0.6) out.push(e);+ }+ };+ visit(document);+ if (out.length < 2) return out.length ? { count: 1, id: put(out[0]) } : { count: 0 };+ // A wrapper and its same-size descendants form one nested chain: a click+ // lands the same on any of them. Take the element a real click would focus+ // (the deepest focusable one), else the outermost. Unrelated elements that+ // share the box stay ambiguous and the caller raises.+ const depth = (e) => { let d = 0; for (let n = e; n; n = parentOrHost(n)) d++; return d; };+ const within = (a, e) => { for (let n = e; n; n = parentOrHost(n)) if (n === a) return true; return false; };+ const chain = out.map((e) => [depth(e), e]).sort((a, b) => a[0] - b[0]).map((p) => p[1]);+ for (let i = 1; i < chain.length; i++) if (!within(chain[i - 1], chain[i])) return { count: out.length };+ const focusable = chain.filter((e) => !e.disabled && e.matches('a[href], area[href], button, input:not([type="hidden"]), '+ + 'select, textarea, iframe, summary, [tabindex], [contenteditable]:not([contenteditable="false"])'));+ return { count: 1, id: put(focusable.length ? focusable[focusable.length - 1] : chain[0]) };+ },+ release(ids) { for (const id of ids) els.delete(id); },+ resolve(selector, strict, rootId) {+ const root = rootId ? get(rootId) : document;+ let parsed, all;+ try { parsed = I.parseSelector(selector); all = I.querySelectorAll(parsed, root); }+ catch (e) { return { status: 'error', message: e.message }; }+ if (!all.length) return { status: 'none' };+ if (strict && all.length > 1)+ return { status: 'strict', message: I.strictModeViolationError(parsed, all).message };+ return { status: 'ok', id: put(all[0]), count: all.length };+ },+ fromPath(path) {+ let cur = document;+ for (const step of path) {+ if (step === 'S') { cur = cur.shadowRoot; if (!cur) return { status: 'closed-shadow' }; continue; }+ cur = cur.childNodes[step];+ if (!cur) return { status: 'none' };+ }+ if (cur.nodeType !== 1) return { status: 'none' };+ return { status: 'ok', id: put(cur) };+ },+ retarget(id, behavior) { const t = I.retarget(get(id), behavior); return t ? put(t) : 0; },+ info(id) {+ const e = get(id);+ const t = I.retarget(e, 'follow-label') || e;+ const root = t.getRootNode();+ return {+ connected: e.isConnected,+ tag: t.nodeName.toLowerCase(),+ type: t.nodeName === 'INPUT' ? String(t.type).toLowerCase() : null,+ editable: !!t.isContentEditable,+ focused: !!root && root.activeElement === t,+ value: textValue(t),+ preview: I.previewNode(e),+ };+ },+ connected(id) { return get(id).isConnected; },+ value(id) { const e = get(id); return textValue(I.retarget(e, 'follow-label') || e); },+ activeValue() {+ const a = document.activeElement;+ if (!a || a === document.body) return { tag: null };+ return { tag: a.nodeName.toLowerCase(), type: a.nodeName === 'INPUT' ? String(a.type).toLowerCase() : null,+ editable: !!a.isContentEditable, value: textValue(a) };+ },+ async states(id, states) {+ const e = get(id);+ try {+ if (I.checkElementStates) {+ const r = await I.checkElementStates(e, states);+ if (r === undefined) return null;+ if (r === 'error:notconnected') return { missing: 'attached' };+ return { missing: r.missingState };+ }+ for (const s of states) {+ if (s === 'stable') continue;+ const r = I.elementState(e, s);+ if (r === 'error:notconnected' || r.received === 'error:notconnected') return { missing: 'attached' };+ if (!(r.matches !== undefined ? r.matches : r)) return { missing: s };+ }+ return null;+ } catch (err) { return { error: err.message }; }+ },+ checked(id) {+ try {+ const e = get(id), r = I.elementState(e, 'checked');+ if (typeof r === 'object') return { checked: r.received === 'checked', radio: !!r.isRadio };+ // Playwright < 1.50 returns a boolean here.+ const t = I.retarget(e, 'follow-label');+ return { checked: r === true, radio: !!t && t.nodeName === 'INPUT' && t.type === 'radio' };+ }+ catch (err) { return { error: err.message }; }+ },+ geometry(id) {+ const e = get(id);+ if (!e.isConnected) return null;+ let b = e.getBoundingClientRect();+ const st = getComputedStyle(e);+ if (st.display === 'contents') b = contentsBox(e) || b;+ return { x: b.left, y: b.top, width: b.width, height: b.height,+ bl: parseFloat(st.borderLeftWidth) || 0, bt: parseFloat(st.borderTopWidth) || 0 };+ },+ scroller(id) {+ const e = get(id);+ const b = e.getBoundingClientRect();+ const top = document.scrollingElement || document.documentElement;+ for (let p = parentOrHost(e); p && p !== top && p !== document.body; p = parentOrHost(p)) {+ const s = getComputedStyle(p);+ const sy = /(auto|scroll|overlay)/.test(s.overflowY) && p.scrollHeight > p.clientHeight;+ const sx = /(auto|scroll|overlay)/.test(s.overflowX) && p.scrollWidth > p.clientWidth;+ if (!sy && !sx) continue;+ const r = p.getBoundingClientRect();+ const x = r.left + p.clientLeft, y = r.top + p.clientTop, w = p.clientWidth, h = p.clientHeight;+ if ((sy && (b.top < y || b.bottom > y + h)) || (sx && (b.left < x || b.right > x + w)))+ return { x, y, width: w, height: h };+ }+ return null;+ },+ doc() {+ const e = document.scrollingElement || document.documentElement;+ const rangeX = Math.max(0, e.scrollWidth - e.clientWidth);+ const rtl = getComputedStyle(document.body || e).direction === 'rtl';+ return { y: scrollY, maxY: Math.max(0, e.scrollHeight - e.clientHeight), x: scrollX,+ minX: rtl ? -rangeX : 0, maxX: rtl ? 0 : rangeX, width: innerWidth, height: innerHeight };+ },+ hit(id, x, y) {+ const r = I.expectHitTarget({ x, y }, get(id));+ return r === 'done' ? null : r.hitTargetDescription;+ },+ fill(id, value) {+ try { return { result: I.fill(get(id), value) }; } catch (err) { return { error: err.message }; }+ },+ select(id, options, elementIds) {+ const opts = options.concat(elementIds.map(get));+ try {+ const r = I.selectOptions(get(id), opts);+ return Array.isArray(r) ? { values: r } : { error: String(r) };+ } catch (err) { return { error: err.message }; }+ },+ focus(id) { const e = I.retarget(get(id), 'follow-label') || get(id); I.focusNode(e, false); return true; },+ caretAtEnd(id) {+ const t = I.retarget(get(id), 'follow-label') || get(id);+ if ('selectionStart' in t && t.selectionStart !== null) return t.selectionStart === String(t.value).length;+ return false;+ },+ platform() { return navigator.platform || ''; },+ rangeInfo(id) {+ const e = I.retarget(get(id), 'follow-label') || get(id);+ const n = (v, d) => { const x = parseFloat(v); return Number.isFinite(x) ? x : d; };+ const min = n(e.min, 0), max = Math.max(n(e.max, 100), n(e.min, 0));+ const step = e.step === 'any' ? 0 : n(e.step, 1);+ const st = getComputedStyle(e);+ const vertical = st.writingMode.startsWith('vertical') || st.appearance === 'slider-vertical';+ return { min, max, step, value: n(e.value, min), vertical, rtl: st.direction === 'rtl' };+ },+ // The options a select_option() call targets, without changing anything.+ selectPlan(id, options, elementIds) {+ const sel = I.retarget(get(id), 'follow-label') || get(id);+ if (sel.nodeName !== 'SELECT') return { error: 'Element is not a <select> element' };+ const opts = [...sel.options];+ const wanted = options.concat(elementIds.map(get));+ const norm = (s) => s.replace(/\s+/g, ' ').trim();+ const match = (o, i, w) => {+ if (w instanceof Node) return o === w;+ const lbl = (l) => l === o.label || norm(l) === norm(o.label);+ let ok = true;+ if (w.valueOrLabel !== undefined) ok = ok && (w.valueOrLabel === o.value || lbl(w.valueOrLabel));+ if (w.value !== undefined) ok = ok && w.value === o.value;+ if (w.label !== undefined) ok = ok && lbl(w.label);+ if (w.index !== undefined) ok = ok && w.index === i;+ return ok;+ };+ const enabled = (o) => !o.disabled && !(o.parentElement && o.parentElement.nodeName === 'OPTGROUP' && o.parentElement.disabled);+ let remaining = wanted.slice(); const targets = [];+ for (let i = 0; i < opts.length && remaining.length; i++) {+ if (!remaining.some(w => match(opts[i], i, w))) continue;+ if (!enabled(opts[i])) return { retry: 'option being selected is not enabled' };+ targets.push(i);+ remaining = sel.multiple ? remaining.filter(w => !match(opts[i], i, w)) : [];+ }+ if (remaining.length) return { retry: 'did not find some options' };+ return { targets, multiple: sel.multiple, listbox: sel.multiple || sel.size > 1,+ navigable: opts.map(o => enabled(o) && !o.hidden && getComputedStyle(o).display !== 'none'),+ values: targets.map(i => opts[i].value), labels: targets.map(i => norm(opts[i].label)) };+ },+ optionId(id, index) { const sel = I.retarget(get(id), 'follow-label') || get(id); return put(sel.options[index]); },+ selectState(id) {+ const sel = I.retarget(get(id), 'follow-label') || get(id);+ return { current: sel.selectedIndex, selected: [...sel.options].map((o, i) => o.selected ? i : -1).filter(i => i >= 0),+ values: [...sel.selectedOptions].map(o => o.value) };+ },+ ownerContent() {+ // Runs with this = the <iframe> owner element: viewport-relative content box.+ const r = this.getBoundingClientRect(); const s = getComputedStyle(this);+ const bl = parseFloat(s.borderLeftWidth) || 0, bt = parseFloat(s.borderTopWidth) || 0;+ const pl = parseFloat(s.paddingLeft) || 0, pt = parseFloat(s.paddingTop) || 0;+ const pr = parseFloat(s.paddingRight) || 0, pb = parseFloat(s.paddingBottom) || 0;+ return { x: r.left + bl + pl, y: r.top + bt + pt,+ width: Math.max(0, this.clientWidth - pl - pr), height: Math.max(0, this.clientHeight - pt - pb) };+ },+};+Object.defineProperty(globalThis, '__cloakH', { value: H });+return true;+})()+""";+}diff --git a/dotnet/src/CloakBrowser/Wrappers/HumanCursor.cs b/dotnet/src/CloakBrowser/Wrappers/HumanCursor.csindex 7bc84e1..f666022 100644--- a/dotnet/src/CloakBrowser/Wrappers/HumanCursor.cs+++ b/dotnet/src/CloakBrowser/Wrappers/HumanCursor.cs@@ -1,102 +1,72 @@-using System.Runtime.InteropServices;using CloakBrowser.Human;using Microsoft.Playwright;namespace CloakBrowser.Wrappers;/// <summary>-/// Per-page shared humanize state: the virtual cursor position, the raw mouse /-/// keyboard adapters, and the CDP typing stealth path. A single instance is shared-/// by a <see cref="HumanizedPage"/>, its <see cref="HumanizedMouse"/>,-/// <see cref="HumanizedKeyboard"/>, and every <see cref="HumanizedLocator"/> it-/// produces, so cursor motion is continuous across them (no jumps).-///-/// This mirrors the cursor/stealth bookkeeping inside <see cref="HumanPage"/>, exposed-/// in a form the wrappers can share.+/// Per-page shared humanize state: one <see cref="HumanEngine"/> (virtual cursor,+/// per-frame isolated worlds, raw input) shared by a <see cref="HumanizedPage"/>, its+/// <see cref="HumanizedMouse"/> / <see cref="HumanizedKeyboard"/>, and every frame,+/// locator and element handle it produces, so cursor motion is continuous across them./// </summary>internal sealed class HumanCursor{- private static readonly bool IsMac = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);- private static readonly string SelectAll = IsMac ? "Meta+a" : "Control+a";-private readonly IPage _page;- private readonly IRawMouse _rawMouse;- private readonly IRawKeyboard _rawKeyboard;- private readonly IRawEvaluator _evaluator;-- private IsolatedWorld? _stealth;- private IRawCdpSession? _cdpSession;- private bool _stealthInitialized;- private bool _initialized;-- public double X { get; private set; }- public double Y { get; private set; }- public IRawMouse RawMouse => _rawMouse;- internal IPage Page => _page;public HumanCursor(IPage page){_page = page;- _rawMouse = new PlaywrightRawMouse(page.Mouse);- _rawKeyboard = new PlaywrightRawKeyboard(page.Keyboard);- _evaluator = new PlaywrightEvaluator(page);+ Engine = new HumanEngine(page, new HumanConfig(), new CursorPosition());}- public void Set(double x, double y) { X = x; Y = y; }+ internal HumanEngine Engine { get; private set; }+ internal IPage Page => _page;++ public double X => Engine.Cursor.X;+ public double Y => Engine.Cursor.Y;- public async Task InitStealthAsync()+ /// <summary>Bind the page config (first wrap wins; per-call overrides go through <c>HumanConfig</c>).</summary>+ internal HumanEngine EngineFor(HumanConfig cfg){- if (_stealthInitialized) return;- _stealthInitialized = true;- try- {- _stealth = new IsolatedWorld(_page);- var session = await _stealth.GetCdpSessionAsync().ConfigureAwait(false);- _cdpSession = new PlaywrightCdpSession(session);- }- catch (System.Exception)- {- _stealth = null;- _cdpSession = null;- CloakLog.Debug("Could not create CDP session - stealth features disabled");- }+ if (!ReferenceEquals(Engine.Config, cfg) && !_configured)+ Engine = new HumanEngine(_page, cfg, Engine.Cursor);+ _configured = true;+ return Engine;}- public void InvalidateStealth() => _stealth?.Invalidate();+ private bool _configured;- /// <summary>The isolated world for stealth DOM reads, initializing it on first use.- /// Returns null when the CDP session could not be created.</summary>- internal async Task<IsolatedWorld?> GetStealthAsync()- {- if (!_stealthInitialized)- await InitStealthAsync().ConfigureAwait(false);- return _stealth;- }+ /// <summary>Kept for API compatibility: worlds are created lazily per frame.</summary>+ public Task InitStealthAsync() => Task.CompletedTask;++ public void InvalidateStealth() => Engine.World.Invalidate();public async Task EnsureInitializedAsync(HumanConfig cfg){- if (_initialized) return;- X = HumanRandom.Rand(cfg.InitialCursorX.Min, cfg.InitialCursorX.Max);- Y = HumanRandom.Rand(cfg.InitialCursorY.Min, cfg.InitialCursorY.Max);- try- {- await _rawMouse.MoveAsync(X, Y).ConfigureAwait(false);- _initialized = true;- }- catch (System.Exception) { /* viewport may not be ready yet */ }+ try { await EngineFor(cfg).EnsureCursorAsync(cfg).ConfigureAwait(false); }+ catch (PlaywrightException) { /* viewport may not be ready yet; done on first action */ }}+}- public Task RawMouseDownAsync(int clickCount = 1) =>- _page.Mouse.DownAsync(new MouseDownOptions { ClickCount = clickCount });-- public Task RawMouseUpAsync(int clickCount = 1) =>- _page.Mouse.UpAsync(new MouseUpOptions { ClickCount = clickCount });+/// <summary>SelectOption arguments in the shape the engine's selectPlan understands+/// (Playwright's convertSelectOptionValues).</summary>+internal sealed record SelectValues(IReadOnlyList<object> Options, IReadOnlyList<IElementHandle> Handles)+{+ private static IElementHandle Raw(IElementHandle h) => h is HumanizedElementHandle w ? w.Original : h;- public Task SelectAllAsync() => _page.Keyboard.PressAsync(SelectAll);+ public static SelectValues Of(IEnumerable<string> values) =>+ new(values.Select(v => (object)new Dictionary<string, object> { ["valueOrLabel"] = v }).ToList(), Array.Empty<IElementHandle>());- public Task PressAsync(string key, float? delay = null) =>- HumanKeyboard.PressAsync(_page.Keyboard, key, delay);+ public static SelectValues Of(IEnumerable<IElementHandle> handles) =>+ new(Array.Empty<object>(), handles.Select(Raw).ToList());- public Task HumanTypeAsync(string text, HumanConfig cfg) =>- HumanKeyboard.HumanTypeAsync(_evaluator, _rawKeyboard, text, cfg, _cdpSession);+ public static SelectValues Of(IEnumerable<SelectOptionValue> values) =>+ new(values.Select(v =>+ {+ var o = new Dictionary<string, object>();+ if (v.Value != null) o["value"] = v.Value;+ if (v.Label != null) o["label"] = v.Label;+ if (v.Index != null) o["index"] = v.Index.Value;+ return (object)o;+ }).ToList(), Array.Empty<IElementHandle>());}diff --git a/dotnet/src/CloakBrowser/Wrappers/Humanize.cs b/dotnet/src/CloakBrowser/Wrappers/Humanize.csindex d51b76d..8df6d64 100644--- a/dotnet/src/CloakBrowser/Wrappers/Humanize.cs+++ b/dotnet/src/CloakBrowser/Wrappers/Humanize.cs@@ -87,6 +87,9 @@ public static class Humanizeinternal static ILocator WrapLocator(ILocator locator, HumanCursor cursor, HumanConfig cfg, string? selector = null) =>locator is HumanizedLocator ? locator : new HumanizedLocator(locator, cursor, cfg, selector);+ internal static IFrameLocator WrapFrameLocator(IFrameLocator frameLocator, HumanCursor cursor, HumanConfig cfg) =>+ frameLocator is HumanizedFrameLocator ? frameLocator : new HumanizedFrameLocator(frameLocator, cursor, cfg);+internal static IFrame WrapFrame(IFrame frame, HumanCursor cursor, HumanConfig cfg) =>frame is HumanizedFrame ? frame : new HumanizedFrame(frame, cursor, cfg);@@ -102,6 +105,10 @@ public static class Humanize/// <summary>Per-page cursor cache so pages from a context/browser share state across re-wraps.</summary>private static readonly System.Runtime.CompilerServices.ConditionalWeakTable<IPage, HumanCursor> CursorCache = new();+ /// <summary>The shared humanize state of an already-humanized raw page, if any.</summary>+ internal static bool TryGetCursor(IPage page, out HumanCursor cursor) =>+ CursorCache.TryGetValue(page, out cursor!);+internal static async Task<IPage> WrapPageAsync(IPage page, HumanConfig cfg){if (page is HumanizedPage) return page;diff --git a/dotnet/src/CloakBrowser/Wrappers/HumanizedElementHandle.cs b/dotnet/src/CloakBrowser/Wrappers/HumanizedElementHandle.csindex 5040da9..b8123ad 100644--- a/dotnet/src/CloakBrowser/Wrappers/HumanizedElementHandle.cs+++ b/dotnet/src/CloakBrowser/Wrappers/HumanizedElementHandle.cs@@ -6,15 +6,11 @@ namespace CloakBrowser.Wrappers;/// <summary>/// Transparent humanizing decorator over Playwright's <see cref="IElementHandle"/>.///-/// ElementHandle is a legacy, lower-level surface (Playwright itself recommends-/// <see cref="ILocator"/>). For completeness this wrapper humanizes the common-/// interaction methods (click/dblclick/hover/tap/fill/type/press/check/uncheck) by-/// driving the shared cursor to the handle's bounding box, so the ElementHandle path-/// does NOT silently bypass humanization. Handle-returning queries are re-wrapped;-/// everything else is delegated by the generator.-///-/// Recommendation: prefer Locator / selector-based methods - they get the full-/// actionability + isolated-world stealth path.+/// Interaction methods run through the unified <see cref="HumanEngine"/>: the handle is+/// identified inside the isolated world by its protocol-level bounding box (no page+/// script runs); when two elements share that exact box the action raises and asks for a+/// Locator instead. Handle-returning queries are re-wrapped; everything else is delegated+/// by the generator./// </summary>[GenerateInterfaceDelegation(typeof(IElementHandle))]public sealed partial class HumanizedElementHandle : IElementHandle@@ -36,111 +32,30 @@ public sealed partial class HumanizedElementHandle : IElementHandle/// <summary>Alias of <see cref="Original"/>.</summary>public IElementHandle Inner => _inner;- private async Task<(double X, double Y, bool IsInput)> MoveToAsync(double timeout, bool force)- {- await _cursor.EnsureInitializedAsync(_cfg).ConfigureAwait(false);- if (!force)- {- try { await _inner.ScrollIntoViewIfNeededAsync(new ElementHandleScrollIntoViewIfNeededOptions { Timeout = (float)timeout }).ConfigureAwait(false); }- catch (System.Exception) { /* best effort */ }- }- var box = await _inner.BoundingBoxAsync().ConfigureAwait(false);- bool isInput;- try- {- isInput = await _inner.EvaluateAsync<bool>(- @"el => { const t = el.tagName.toLowerCase();- return t==='input'||t==='textarea'||el.getAttribute('contenteditable')==='true'; }")- .ConfigureAwait(false);- }- catch (System.Exception) { isInput = false; }-- var bb = box == null ? new BoundingBox(_cursor.X, _cursor.Y, 1, 1)- : new BoundingBox(box.X, box.Y, box.Width, box.Height);- var target = HumanMouse.ClickTarget(bb, isInput, _cfg);- await HumanMouse.HumanMoveAsync(_cursor.RawMouse, _cursor.X, _cursor.Y, target.X, target.Y, _cfg).ConfigureAwait(false);- _cursor.Set(target.X, target.Y);- return (target.X, target.Y, isInput);- }-- public async Task ClickAsync(ElementHandleClickOptions? options = null)- {- var t = await MoveToAsync(OptionReader.Timeout(options), OptionReader.Force(options)).ConfigureAwait(false);- await HumanMouse.HumanClickAsync(_cursor.RawMouse, t.IsInput, _cfg).ConfigureAwait(false);- }-- public async Task DblClickAsync(ElementHandleDblClickOptions? options = null)- {- await MoveToAsync(OptionReader.Timeout(options), OptionReader.Force(options)).ConfigureAwait(false);- await _cursor.RawMouseDownAsync(2).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(30, 60)).ConfigureAwait(false);- await _cursor.RawMouseUpAsync(2).ConfigureAwait(false);- }-- public Task HoverAsync(ElementHandleHoverOptions? options = null) =>- MoveToAsync(OptionReader.Timeout(options), OptionReader.Force(options));-- public Task TapAsync(ElementHandleTapOptions? options = null) =>- ClickAsync(new ElementHandleClickOptions- {- Force = OptionReader.Force(options),- Timeout = (float)OptionReader.Timeout(options),- });-- public async Task FillAsync(string value, ElementHandleFillOptions? options = null)- {- await ClickAsync(new ElementHandleClickOptions { Force = OptionReader.Force(options), Timeout = (float)OptionReader.Timeout(options) }).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(100, 250)).ConfigureAwait(false);- await _cursor.SelectAllAsync().ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(30, 80)).ConfigureAwait(false);- await _cursor.PressAsync("Backspace").ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(50, 150)).ConfigureAwait(false);- await _cursor.HumanTypeAsync(value, _cfg).ConfigureAwait(false);- }-- public async Task TypeAsync(string text, ElementHandleTypeOptions? options = null)- {- await _inner.FocusAsync().ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(50, 150)).ConfigureAwait(false);- await _cursor.HumanTypeAsync(text, _cfg).ConfigureAwait(false);- }-- public async Task PressAsync(string key, ElementHandlePressOptions? options = null)- {- await _inner.FocusAsync().ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(50, 150)).ConfigureAwait(false);- await _cursor.PressAsync(key, OptionReader.Delay(options)).ConfigureAwait(false);- }-- public async Task CheckAsync(ElementHandleCheckOptions? options = null)- {- if (!await _inner.IsCheckedAsync().ConfigureAwait(false))- await ClickAsync(new ElementHandleClickOptions { Force = OptionReader.Force(options), Timeout = (float)OptionReader.Timeout(options) }).ConfigureAwait(false);- }-- public async Task UncheckAsync(ElementHandleUncheckOptions? options = null)- {- if (await _inner.IsCheckedAsync().ConfigureAwait(false))- await ClickAsync(new ElementHandleClickOptions { Force = OptionReader.Force(options), Timeout = (float)OptionReader.Timeout(options) }).ConfigureAwait(false);- }-- public async Task SetCheckedAsync(bool checkedState, ElementHandleSetCheckedOptions? options = null)- {- bool current;- try { current = await _inner.IsCheckedAsync().ConfigureAwait(false); }- catch (System.Exception) { current = !checkedState; }- if (current != checkedState)- await ClickAsync(new ElementHandleClickOptions { Force = OptionReader.Force(options), Timeout = (float)OptionReader.Timeout(options) }).ConfigureAwait(false);- }-// ------------------------------------------------------------------------ // SelectOptionAsync (all 6 IElementHandle overloads) - humanized pre-roll.- // Mirrors Python _human_el_select_option: move the cursor to the <select>- // (curved), click, pause, then delegate the real select (native popups can't- // be mouse-driven). Unwrap any HumanizedElementHandle args.+ // Humanized actions. The handle is located inside the isolated world by its+ // protocol-level bounding box (no page script); an ambiguous box raises.// ------------------------------------------------------------------------ private static IElementHandle Unwrap(IElementHandle h) => h is HumanizedElementHandle w ? w.Original : h;+ private HumanEngine E => _cursor.EngineFor(_cfg);+ private Target T() => new(PlaywrightInternals.HandleFrame(_inner), null, false, _inner);+ private static ActOpts Opt(object? options) => ActOpts.From(options);++ public Task ClickAsync(ElementHandleClickOptions? options = null) => E.ClickAsync(T(), Opt(options), "ElementHandle.ClickAsync");+ public Task DblClickAsync(ElementHandleDblClickOptions? options = null) => E.ClickAsync(T(), Opt(options), "ElementHandle.DblClickAsync", 2);+ public Task HoverAsync(ElementHandleHoverOptions? options = null) => E.HoverAsync(T(), Opt(options), "ElementHandle.HoverAsync");+ public Task TapAsync(ElementHandleTapOptions? options = null) => E.TapAsync(T(), Opt(options), "ElementHandle.TapAsync");+ public Task FillAsync(string value, ElementHandleFillOptions? options = null) => E.FillAsync(T(), value, Opt(options), "ElementHandle.FillAsync");+ public Task TypeAsync(string text, ElementHandleTypeOptions? options = null) => E.TypeAsync(T(), text, Opt(options), "ElementHandle.TypeAsync");+ public Task PressAsync(string key, ElementHandlePressOptions? options = null) => E.PressAsync(T(), key, Opt(options), "ElementHandle.PressAsync");+ public Task CheckAsync(ElementHandleCheckOptions? options = null) => E.SetCheckedAsync(T(), true, Opt(options), "ElementHandle.CheckAsync");+ public Task UncheckAsync(ElementHandleUncheckOptions? options = null) => E.SetCheckedAsync(T(), false, Opt(options), "ElementHandle.UncheckAsync");+ public Task SetCheckedAsync(bool checkedState, ElementHandleSetCheckedOptions? options = null) =>+ E.SetCheckedAsync(T(), checkedState, Opt(options), "ElementHandle.SetCheckedAsync");+ public Task FocusAsync() => E.FocusAsync(T(), new ActOpts(), "ElementHandle.FocusAsync", move: true);+ public Task ScrollIntoViewIfNeededAsync(ElementHandleScrollIntoViewIfNeededOptions? options = null) =>+ E.ScrollIntoViewIfNeededAsync(T(), Opt(options), "ElementHandle.ScrollIntoViewIfNeededAsync");+private static ILocator Unwrap(ILocator l) => l is HumanizedLocator w ? w.Original : l;// #549: unwrap masked locators in place (rebuilding options would drop future fields).@@ -151,48 +66,21 @@ public sealed partial class HumanizedElementHandle : IElementHandlereturn _inner.ScreenshotAsync(options);}- private async Task SelectPrologueAsync(ElementHandleSelectOptionOptions? options)- {- var t = await MoveToAsync(OptionReader.Timeout(options), OptionReader.Force(options)).ConfigureAwait(false);- await HumanMouse.HumanClickAsync(_cursor.RawMouse, t.IsInput, _cfg).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(100, 300)).ConfigureAwait(false);- }-- public async Task<IReadOnlyList<string>> SelectOptionAsync(string values, ElementHandleSelectOptionOptions? options = null)- {- await SelectPrologueAsync(options).ConfigureAwait(false);- return await _inner.SelectOptionAsync(values, options).ConfigureAwait(false);- }-- public async Task<IReadOnlyList<string>> SelectOptionAsync(IElementHandle values, ElementHandleSelectOptionOptions? options = null)- {- await SelectPrologueAsync(options).ConfigureAwait(false);- return await _inner.SelectOptionAsync(Unwrap(values), options).ConfigureAwait(false);- }-- public async Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<string> values, ElementHandleSelectOptionOptions? options = null)- {- await SelectPrologueAsync(options).ConfigureAwait(false);- return await _inner.SelectOptionAsync(values, options).ConfigureAwait(false);- }-- public async Task<IReadOnlyList<string>> SelectOptionAsync(SelectOptionValue values, ElementHandleSelectOptionOptions? options = null)- {- await SelectPrologueAsync(options).ConfigureAwait(false);- return await _inner.SelectOptionAsync(values, options).ConfigureAwait(false);- }+ private Task<IReadOnlyList<string>> Select(SelectValues v, ElementHandleSelectOptionOptions? options) =>+ E.SelectOptionAsync(T(), v.Options, v.Handles, Opt(options), "ElementHandle.SelectOptionAsync");- public async Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<IElementHandle> values, ElementHandleSelectOptionOptions? options = null)- {- await SelectPrologueAsync(options).ConfigureAwait(false);- return await _inner.SelectOptionAsync(values.Select(Unwrap), options).ConfigureAwait(false);- }-- public async Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<SelectOptionValue> values, ElementHandleSelectOptionOptions? options = null)- {- await SelectPrologueAsync(options).ConfigureAwait(false);- return await _inner.SelectOptionAsync(values, options).ConfigureAwait(false);- }+ public Task<IReadOnlyList<string>> SelectOptionAsync(string values, ElementHandleSelectOptionOptions? options = null) =>+ Select(SelectValues.Of(new[] { values }), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(IElementHandle values, ElementHandleSelectOptionOptions? options = null) =>+ Select(SelectValues.Of(new[] { values }), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<string> values, ElementHandleSelectOptionOptions? options = null) =>+ Select(SelectValues.Of(values), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(SelectOptionValue values, ElementHandleSelectOptionOptions? options = null) =>+ Select(SelectValues.Of(new[] { values }), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<IElementHandle> values, ElementHandleSelectOptionOptions? options = null) =>+ Select(SelectValues.Of(values), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<SelectOptionValue> values, ElementHandleSelectOptionOptions? options = null) =>+ Select(SelectValues.Of(values), options);// -----------------------------------------------------------------------// Handle-returning members - re-wrap.@@ -215,4 +103,16 @@ public sealed partial class HumanizedElementHandle : IElementHandlevar h = await _inner.WaitForSelectorAsync(selector, options).ConfigureAwait(false);return h == null ? null : Humanize.WrapElementHandle(h, _cursor, _cfg);}++ public async Task<IFrame?> ContentFrameAsync()+ {+ var f = await _inner.ContentFrameAsync().ConfigureAwait(false);+ return f == null ? null : Humanize.WrapFrame(f, _cursor, _cfg);+ }++ public async Task<IFrame?> OwnerFrameAsync()+ {+ var f = await _inner.OwnerFrameAsync().ConfigureAwait(false);+ return f == null ? null : Humanize.WrapFrame(f, _cursor, _cfg);+ }}diff --git a/dotnet/src/CloakBrowser/Wrappers/HumanizedFrame.cs b/dotnet/src/CloakBrowser/Wrappers/HumanizedFrame.csindex af28e27..cf33b57 100644--- a/dotnet/src/CloakBrowser/Wrappers/HumanizedFrame.cs+++ b/dotnet/src/CloakBrowser/Wrappers/HumanizedFrame.cs@@ -7,10 +7,11 @@ namespace CloakBrowser.Wrappers;/// <summary>/// Transparent humanizing decorator over Playwright's <see cref="IFrame"/>.///-/// Frames have no Mouse/Keyboard of their own (those belong to the page), so the-/// selector actions are humanized by resolving <c>frame.Locator(selector)</c> and-/// running the shared locator humanizer with the page's cursor. Locator/frame-/// returning members are re-wrapped; everything else is delegated by the generator.+/// Frames have no Mouse/Keyboard of their own (those belong to the page): selector+/// actions run through the page's <see cref="HumanEngine"/>, resolved in this frame's+/// own isolated world, with wheel scrolling and hit-tests through every ancestor+/// iframe. Locator/frame returning members are re-wrapped; everything else is+/// delegated by the generator./// </summary>[GenerateInterfaceDelegation(typeof(IFrame))]public sealed partial class HumanizedFrame : IFrame@@ -35,149 +36,51 @@ public sealed partial class HumanizedFrame : IFrameprivate ILocator Wrap(ILocator l) => Humanize.WrapLocator(l, _cursor, _cfg);private ILocator Wrap(ILocator l, string? selector) => Humanize.WrapLocator(l, _cursor, _cfg, selector);private IFrame Wrap(IFrame f) => Humanize.WrapFrame(f, _cursor, _cfg);- private ILocator Loc(string selector) => _inner.Locator(selector);// ------------------------------------------------------------------------ // Humanized selector actions (routed through the locator humanizer).+ // Humanized selector actions: resolved in THIS frame's isolated world.// ------------------------------------------------------------------------ public Task ClickAsync(string selector, FrameClickOptions? options = null) =>- LocatorHumanizer.ClickAsync(Loc(selector), _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options));-- public Task DblClickAsync(string selector, FrameDblClickOptions? options = null) =>- LocatorHumanizer.DblClickAsync(Loc(selector), _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options));-- public Task HoverAsync(string selector, FrameHoverOptions? options = null) =>- LocatorHumanizer.HoverAsync(Loc(selector), _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options));-- public Task TapAsync(string selector, FrameTapOptions? options = null) =>- LocatorHumanizer.TapAsync(Loc(selector), _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options));-- public Task FillAsync(string selector, string value, FrameFillOptions? options = null) =>- LocatorHumanizer.FillAsync(Loc(selector), _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), value);-- public Task TypeAsync(string selector, string text, FrameTypeOptions? options = null) =>- LocatorHumanizer.TypeAsync(Loc(selector), _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), text);-- public Task PressAsync(string selector, string key, FramePressOptions? options = null) =>- LocatorHumanizer.PressAsync(- Loc(selector), _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options),- key, OptionReader.Delay(options));-- public async Task CheckAsync(string selector, FrameCheckOptions? options = null)- {- if (!await _inner.IsCheckedAsync(selector).ConfigureAwait(false))- await LocatorHumanizer.ClickAsync(Loc(selector), _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options)).ConfigureAwait(false);- }-- public async Task UncheckAsync(string selector, FrameUncheckOptions? options = null)- {- if (await _inner.IsCheckedAsync(selector).ConfigureAwait(false))- await LocatorHumanizer.ClickAsync(Loc(selector), _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options)).ConfigureAwait(false);- }-- public async Task SetCheckedAsync(string selector, bool checkedState, FrameSetCheckedOptions? options = null)- {- bool current;- try { current = await _inner.IsCheckedAsync(selector).ConfigureAwait(false); }- catch (System.Exception) { current = !checkedState; }- if (current != checkedState)- await LocatorHumanizer.ClickAsync(Loc(selector), _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options)).ConfigureAwait(false);- }-- // ------------------------------------------------------------------------ // SelectOptionAsync (all 6 IFrame overloads) - humanized pre-roll.- // Mirrors Python _frame_select_option: hover the <select> (curved move) +- // pause, then delegate the real select (native popups can't be mouse-driven).- // Unwrap any HumanizedElementHandle args so Playwright sees raw handles.- // ------------------------------------------------------------------------- private static IElementHandle Unwrap(IElementHandle h) => h is HumanizedElementHandle w ? w.Original : h;-- private Task SelectPrologueAsync(string selector, FrameSelectOptionOptions? options) =>- LocatorHumanizer.SelectOptionPrologueAsync(Loc(selector), _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options));-- public async Task<IReadOnlyList<string>> SelectOptionAsync(string selector, string values, FrameSelectOptionOptions? options = null)- {- await SelectPrologueAsync(selector, options).ConfigureAwait(false);- return await _inner.SelectOptionAsync(selector, values, options).ConfigureAwait(false);- }-- public async Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IElementHandle values, FrameSelectOptionOptions? options = null)- {- await SelectPrologueAsync(selector, options).ConfigureAwait(false);- return await _inner.SelectOptionAsync(selector, Unwrap(values), options).ConfigureAwait(false);- }-- public async Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<string> values, FrameSelectOptionOptions? options = null)- {- await SelectPrologueAsync(selector, options).ConfigureAwait(false);- return await _inner.SelectOptionAsync(selector, values, options).ConfigureAwait(false);- }-- public async Task<IReadOnlyList<string>> SelectOptionAsync(string selector, SelectOptionValue values, FrameSelectOptionOptions? options = null)- {- await SelectPrologueAsync(selector, options).ConfigureAwait(false);- return await _inner.SelectOptionAsync(selector, values, options).ConfigureAwait(false);- }-- public async Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<IElementHandle> values, FrameSelectOptionOptions? options = null)- {- await SelectPrologueAsync(selector, options).ConfigureAwait(false);- return await _inner.SelectOptionAsync(selector, values.Select(Unwrap), options).ConfigureAwait(false);- }-- public async Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<SelectOptionValue> values, FrameSelectOptionOptions? options = null)- {- await SelectPrologueAsync(selector, options).ConfigureAwait(false);- return await _inner.SelectOptionAsync(selector, values, options).ConfigureAwait(false);- }-- // ------------------------------------------------------------------------ // DragAndDropAsync - humanized drag. Mirrors Python _frame_drag_and_drop:- // resolve source/target boxes via frame locators; if both present, drive a- // curved press-move-release with the page cursor; else delegate raw.- // ------------------------------------------------------------------------- public async Task DragAndDropAsync(string source, string target, FrameDragAndDropOptions? options = null)- {- LocatorBoundingBoxResult? srcBox, tgtBox;- try- {- srcBox = await _inner.Locator(source).BoundingBoxAsync().ConfigureAwait(false);- tgtBox = await _inner.Locator(target).BoundingBoxAsync().ConfigureAwait(false);- }- catch (System.Exception)- {- srcBox = tgtBox = null;- }-- if (srcBox == null || tgtBox == null)- {- await _inner.DragAndDropAsync(source, target, options).ConfigureAwait(false);- return;- }-- await _cursor.EnsureInitializedAsync(_cfg).ConfigureAwait(false);- double sx = srcBox.X + srcBox.Width / 2, sy = srcBox.Y + srcBox.Height / 2;- double tx = tgtBox.X + tgtBox.Width / 2, ty = tgtBox.Y + tgtBox.Height / 2;- await HumanMouse.HumanMoveAsync(_cursor.RawMouse, _cursor.X, _cursor.Y, sx, sy, _cfg).ConfigureAwait(false);- _cursor.Set(sx, sy);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(100, 200)).ConfigureAwait(false);- await _cursor.RawMouseDownAsync().ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(80, 150)).ConfigureAwait(false);- await HumanMouse.HumanMoveAsync(_cursor.RawMouse, _cursor.X, _cursor.Y, tx, ty, _cfg).ConfigureAwait(false);- _cursor.Set(tx, ty);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(80, 150)).ConfigureAwait(false);- await _cursor.RawMouseUpAsync().ConfigureAwait(false);- }+ private HumanEngine E => _cursor.EngineFor(_cfg);+ private static ActOpts Opt(object? options) => ActOpts.From(options);+ private Target T(string selector, object? options) => new(_inner, selector, ActOpts.From(options).Strict);++ public Task ClickAsync(string selector, FrameClickOptions? options = null) => E.ClickAsync(T(selector, options), Opt(options), "Frame.ClickAsync");+ public Task DblClickAsync(string selector, FrameDblClickOptions? options = null) => E.ClickAsync(T(selector, options), Opt(options), "Frame.DblClickAsync", 2);+ public Task HoverAsync(string selector, FrameHoverOptions? options = null) => E.HoverAsync(T(selector, options), Opt(options), "Frame.HoverAsync");+ public Task TapAsync(string selector, FrameTapOptions? options = null) => E.TapAsync(T(selector, options), Opt(options), "Frame.TapAsync");+ public Task FillAsync(string selector, string value, FrameFillOptions? options = null) => E.FillAsync(T(selector, options), value, Opt(options), "Frame.FillAsync");+ public Task TypeAsync(string selector, string text, FrameTypeOptions? options = null) => E.TypeAsync(T(selector, options), text, Opt(options), "Frame.TypeAsync");+ public Task PressAsync(string selector, string key, FramePressOptions? options = null) => E.PressAsync(T(selector, options), key, Opt(options), "Frame.PressAsync");+ public Task CheckAsync(string selector, FrameCheckOptions? options = null) => E.SetCheckedAsync(T(selector, options), true, Opt(options), "Frame.CheckAsync");+ public Task UncheckAsync(string selector, FrameUncheckOptions? options = null) => E.SetCheckedAsync(T(selector, options), false, Opt(options), "Frame.UncheckAsync");+ public Task SetCheckedAsync(string selector, bool checkedState, FrameSetCheckedOptions? options = null) =>+ E.SetCheckedAsync(T(selector, options), checkedState, Opt(options), "Frame.SetCheckedAsync");+ public Task FocusAsync(string selector, FrameFocusOptions? options = null) => E.FocusAsync(T(selector, options), Opt(options), "Frame.FocusAsync");+ public Task DragAndDropAsync(string source, string target, FrameDragAndDropOptions? options = null) =>+ E.DragAsync(T(source, options), T(target, options), Opt(options), "Frame.DragAndDropAsync");++ private Task<IReadOnlyList<string>> Select(string selector, SelectValues v, FrameSelectOptionOptions? options) =>+ E.SelectOptionAsync(T(selector, options), v.Options, v.Handles, Opt(options), "Frame.SelectOptionAsync");++ public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, string values, FrameSelectOptionOptions? options = null) =>+ Select(selector, SelectValues.Of(new[] { values }), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IElementHandle values, FrameSelectOptionOptions? options = null) =>+ Select(selector, SelectValues.Of(new[] { values }), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<string> values, FrameSelectOptionOptions? options = null) =>+ Select(selector, SelectValues.Of(values), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, SelectOptionValue values, FrameSelectOptionOptions? options = null) =>+ Select(selector, SelectValues.Of(new[] { values }), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<IElementHandle> values, FrameSelectOptionOptions? options = null) =>+ Select(selector, SelectValues.Of(values), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<SelectOptionValue> values, FrameSelectOptionOptions? options = null) =>+ Select(selector, SelectValues.Of(values), options);// -----------------------------------------------------------------------// Locator-returning members - re-wrap.// ------------------------------------------------------------------------ // Frame selectors belong to that frame's document; the cursor's isolated world is- // main-frame-only, so frame locators deliberately retain the legacy locator path.+ public IFrameLocator FrameLocator(string selector) => Humanize.WrapFrameLocator(_inner.FrameLocator(selector), _cursor, _cfg);public ILocator Locator(string selector, FrameLocatorOptions? options = null) => Wrap(_inner.Locator(selector, options));public ILocator GetByAltText(string text, FrameGetByAltTextOptions? options = null) => Wrap(_inner.GetByAltText(text, options));public ILocator GetByAltText(Regex text, FrameGetByAltTextOptions? options = null) => Wrap(_inner.GetByAltText(text, options));@@ -199,4 +102,22 @@ public sealed partial class HumanizedFrame : IFramepublic IReadOnlyList<IFrame> ChildFrames => Humanize.WrapFrames(_inner.ChildFrames, _cursor, _cfg);public IFrame? ParentFrame { get { var f = _inner.ParentFrame; return f == null ? null : Wrap(f); } }++ // -----------------------------------------------------------------------+ // Handle-returning members - re-wrap so handle actions stay humanized.+ // -----------------------------------------------------------------------++ private IElementHandle? H(IElementHandle? h) => h == null ? null : Humanize.WrapElementHandle(h, _cursor, _cfg);++ public async Task<IElementHandle?> QuerySelectorAsync(string selector, FrameQuerySelectorOptions? options = null) =>+ H(await _inner.QuerySelectorAsync(selector, options).ConfigureAwait(false));++ public async Task<IReadOnlyList<IElementHandle>> QuerySelectorAllAsync(string selector) =>+ Humanize.WrapHandles(await _inner.QuerySelectorAllAsync(selector).ConfigureAwait(false), _cursor, _cfg);++ public async Task<IElementHandle?> WaitForSelectorAsync(string selector, FrameWaitForSelectorOptions? options = null) =>+ H(await _inner.WaitForSelectorAsync(selector, options).ConfigureAwait(false));++ public async Task<IElementHandle> FrameElementAsync() =>+ H(await _inner.FrameElementAsync().ConfigureAwait(false))!;}diff --git a/dotnet/src/CloakBrowser/Wrappers/HumanizedFrameLocator.cs b/dotnet/src/CloakBrowser/Wrappers/HumanizedFrameLocator.csnew file mode 100644index 0000000..88dc2b8--- /dev/null+++ b/dotnet/src/CloakBrowser/Wrappers/HumanizedFrameLocator.cs@@ -0,0 +1,61 @@+using System.Text.RegularExpressions;+using CloakBrowser.Human;+using Microsoft.Playwright;++namespace CloakBrowser.Wrappers;++/// <summary>+/// Humanizing decorator over Playwright's <see cref="IFrameLocator"/>. A frame locator+/// performs no actions itself; every member returns a locator (or another frame locator),+/// which is re-wrapped so actions inside the frame stay humanized.+/// </summary>+public sealed class HumanizedFrameLocator : IFrameLocator+{+ private readonly IFrameLocator _inner;+ private readonly HumanCursor _cursor;+ private readonly HumanConfig _cfg;++ internal HumanizedFrameLocator(IFrameLocator inner, HumanCursor cursor, HumanConfig cfg)+ {+ _inner = inner;+ _cursor = cursor;+ _cfg = cfg;+ }++ /// <summary>The original, un-humanized Playwright frame locator.</summary>+ public IFrameLocator Original => _inner;++ private ILocator L(ILocator l) => Humanize.WrapLocator(l, _cursor, _cfg);+ private IFrameLocator F(IFrameLocator f) => Humanize.WrapFrameLocator(f, _cursor, _cfg);+ private static ILocator Raw(ILocator l) => l is HumanizedLocator h ? h.Original : l;++ // Obsolete in Playwright but still part of IFrameLocator.+#pragma warning disable CS0612, CS0618+ public IFrameLocator First => F(_inner.First);+ public IFrameLocator Last => F(_inner.Last);+ public IFrameLocator Nth(int index) => F(_inner.Nth(index));+#pragma warning restore CS0612, CS0618+ public IFrameLocator FrameLocator(string selector) => F(_inner.FrameLocator(selector));+ public ILocator Owner => L(_inner.Owner);++ public ILocator Locator(string selectorOrLocator, FrameLocatorLocatorOptions? options = null) =>+ L(_inner.Locator(selectorOrLocator, options));+ public ILocator Locator(ILocator selectorOrLocator, FrameLocatorLocatorOptions? options = null) =>+ L(_inner.Locator(Raw(selectorOrLocator), options));++ public ILocator GetByAltText(string text, FrameLocatorGetByAltTextOptions? options = null) => L(_inner.GetByAltText(text, options));+ public ILocator GetByAltText(Regex text, FrameLocatorGetByAltTextOptions? options = null) => L(_inner.GetByAltText(text, options));+ public ILocator GetByLabel(string text, FrameLocatorGetByLabelOptions? options = null) => L(_inner.GetByLabel(text, options));+ public ILocator GetByLabel(Regex text, FrameLocatorGetByLabelOptions? options = null) => L(_inner.GetByLabel(text, options));+ public ILocator GetByPlaceholder(string text, FrameLocatorGetByPlaceholderOptions? options = null) => L(_inner.GetByPlaceholder(text, options));+ public ILocator GetByPlaceholder(Regex text, FrameLocatorGetByPlaceholderOptions? options = null) => L(_inner.GetByPlaceholder(text, options));+ public ILocator GetByRole(AriaRole role, FrameLocatorGetByRoleOptions? options = null) => L(_inner.GetByRole(role, options));+ public ILocator GetByTestId(string testId) => L(_inner.GetByTestId(testId));+ public ILocator GetByTestId(Regex testId) => L(_inner.GetByTestId(testId));+ public ILocator GetByText(string text, FrameLocatorGetByTextOptions? options = null) => L(_inner.GetByText(text, options));+ public ILocator GetByText(Regex text, FrameLocatorGetByTextOptions? options = null) => L(_inner.GetByText(text, options));+ public ILocator GetByTitle(string text, FrameLocatorGetByTitleOptions? options = null) => L(_inner.GetByTitle(text, options));+ public ILocator GetByTitle(Regex text, FrameLocatorGetByTitleOptions? options = null) => L(_inner.GetByTitle(text, options));++ public override string? ToString() => _inner.ToString();+}diff --git a/dotnet/src/CloakBrowser/Wrappers/HumanizedKeyboard.cs b/dotnet/src/CloakBrowser/Wrappers/HumanizedKeyboard.csindex 4dd28ac..594c0c1 100644--- a/dotnet/src/CloakBrowser/Wrappers/HumanizedKeyboard.cs+++ b/dotnet/src/CloakBrowser/Wrappers/HumanizedKeyboard.cs@@ -6,9 +6,9 @@ namespace CloakBrowser.Wrappers;/// <summary>/// Transparent humanizing decorator over Playwright's <see cref="IKeyboard"/>.///-/// Intercepted (humanized): <c>TypeAsync</c>, <c>PressAsync</c>, <c>InsertTextAsync</c>.-/// Low-level <c>DownAsync</c>/<c>UpAsync</c> are delegated to the inner keyboard by the-/// source generator (they are deliberate single key transitions, not "typing").+/// Intercepted (humanized): <c>TypeAsync</c> (per-key timing, safe mistypes, Shift for+/// uppercase and symbols). <c>PressAsync</c>, <c>InsertTextAsync</c>, <c>DownAsync</c> and+/// <c>UpAsync</c> are deliberate primitives and are delegated unchanged by the generator./// </summary>[GenerateInterfaceDelegation(typeof(IKeyboard))]public sealed partial class HumanizedKeyboard : IKeyboard@@ -31,17 +31,5 @@ public sealed partial class HumanizedKeyboard : IKeyboardpublic IKeyboard Inner => _inner;public Task TypeAsync(string text, KeyboardTypeOptions? options = null) =>- _cursor.HumanTypeAsync(text, _cfg);-- public async Task PressAsync(string key, KeyboardPressOptions? options = null)- {- // A single human key press: brief aim delay, then the inner press (which- // already presses down + up). Mirrors the press timing used elsewhere.- await HumanRandom.SleepMsAsync(HumanRandom.Rand(50, 150)).ConfigureAwait(false);- await _inner.PressAsync(key, options).ConfigureAwait(false);- }-- public Task InsertTextAsync(string text) =>- // InsertText is an atomic IME-style insertion; humanize it as paced typing.- _cursor.HumanTypeAsync(text, _cfg);+ _cursor.EngineFor(_cfg).KeyboardTypeAsync(text, options?.Delay);}diff --git a/dotnet/src/CloakBrowser/Wrappers/HumanizedLocator.cs b/dotnet/src/CloakBrowser/Wrappers/HumanizedLocator.csindex 9467a3d..7980811 100644--- a/dotnet/src/CloakBrowser/Wrappers/HumanizedLocator.cs+++ b/dotnet/src/CloakBrowser/Wrappers/HumanizedLocator.cs@@ -7,10 +7,11 @@ namespace CloakBrowser.Wrappers;/// <summary>/// Transparent humanizing decorator over Playwright's <see cref="ILocator"/>.///-/// Intercepted (humanized): Click/DblClick/Hover/Tap/Fill/Type/PressSequentially/Press-/// and Check/Uncheck/SetChecked (which route through a humanized click). All other-/// members - assertions, queries, waits, getters - are delegated to the inner locator-/// by the source generator. Locator-returning members are re-wrapped so chaining stays+/// Intercepted (humanized, unified engine, strict mode): Click/DblClick/Hover/Tap/Fill/+/// Clear/Type/PressSequentially/Press/Check/Uncheck/SetChecked/SelectOption/Focus/DragTo/+/// ScrollIntoViewIfNeeded, for every locator shape (GetBy*, chains, Filter, FrameLocator).+/// All other members - assertions, queries, waits, getters - are delegated to the inner+/// locator by the source generator. Locator-returning members are re-wrapped so chaining stays/// humanized./// </summary>[GenerateInterfaceDelegation(typeof(ILocator))]@@ -29,9 +30,9 @@ public sealed partial class HumanizedLocator : ILocator_selector = selector;}- /// <summary>The CSS/XPath selector this locator was built from (page.Locator(selector)),- /// or null for chained/GetBy* locators. Drives the isolated-world pre-click reads.</summary>- internal string? Selector => _selector;+ /// <summary>The Playwright selector string of this locator (any shape: GetBy*, chains,+ /// filters, frame locators).</summary>+ internal string? Selector => _selector ?? PlaywrightInternals.LocatorParts(_inner).Selector;/// <summary>The original, un-humanized Playwright locator (escape hatch for raw speed).</summary>public ILocator Original => _inner;@@ -43,161 +44,60 @@ public sealed partial class HumanizedLocator : ILocatorHumanize.WrapLocator(l, _cursor, _cfg, selector);// ------------------------------------------------------------------------ // Humanized actions+ // Humanized actions: the locator's own frame + selector string, strict mode,+ // resolved by Playwright's engine in the isolated world.// ------------------------------------------------------------------------ public Task ClickAsync(LocatorClickOptions? options = null) =>- LocatorHumanizer.ClickAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), _selector);+ private HumanEngine E => _cursor.EngineFor(_cfg);- public Task DblClickAsync(LocatorDblClickOptions? options = null) =>- LocatorHumanizer.DblClickAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), _selector);-- public Task HoverAsync(LocatorHoverOptions? options = null) =>- LocatorHumanizer.HoverAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), _selector);-- public Task TapAsync(LocatorTapOptions? options = null) =>- LocatorHumanizer.TapAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), _selector);-- public Task FillAsync(string value, LocatorFillOptions? options = null) =>- LocatorHumanizer.FillAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), value, _selector);-- public Task TypeAsync(string text, LocatorTypeOptions? options = null) =>- LocatorHumanizer.TypeAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), text, _selector);-- public Task PressSequentiallyAsync(string text, LocatorPressSequentiallyOptions? options = null) =>- LocatorHumanizer.PressSequentiallyAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), text, _selector);-- public Task PressAsync(string key, LocatorPressOptions? options = null) =>- LocatorHumanizer.PressAsync(- _inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options),- key, OptionReader.Delay(options), _selector);-- public async Task CheckAsync(LocatorCheckOptions? options = null)- {- if (_selector == null)- {- if (!await _inner.IsCheckedAsync().ConfigureAwait(false))- await LocatorHumanizer.ClickAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), null).ConfigureAwait(false);- return;- }- var timeout = OptionReader.Timeout(options); var force = OptionReader.Force(options);- var deadline = Environment.TickCount64 + timeout;- await LocatorHumanizer.EnsureActionableAsync(_cursor, _selector, Actionability.ChecksCheck,- Actionability.RemainingMs(deadline), force).ConfigureAwait(false);- if ((await LocatorHumanizer.SnapshotAsync(_cursor, _selector).ConfigureAwait(false)).Checked != true)- await LocatorHumanizer.ClickAfterPrecheckAsync(_inner, _cursor, _cfg,- Actionability.RemainingMs(deadline), force, _selector).ConfigureAwait(false);- }-- public async Task UncheckAsync(LocatorUncheckOptions? options = null)- {- if (_selector == null)- {- if (await _inner.IsCheckedAsync().ConfigureAwait(false))- await LocatorHumanizer.ClickAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), null).ConfigureAwait(false);- return;- }- var timeout = OptionReader.Timeout(options); var force = OptionReader.Force(options);- var deadline = Environment.TickCount64 + timeout;- await LocatorHumanizer.EnsureActionableAsync(_cursor, _selector, Actionability.ChecksCheck,- Actionability.RemainingMs(deadline), force).ConfigureAwait(false);- if ((await LocatorHumanizer.SnapshotAsync(_cursor, _selector).ConfigureAwait(false)).Checked == true)- await LocatorHumanizer.ClickAfterPrecheckAsync(_inner, _cursor, _cfg,- Actionability.RemainingMs(deadline), force, _selector).ConfigureAwait(false);- }-- public async Task SetCheckedAsync(bool checkedState, LocatorSetCheckedOptions? options = null)- {- if (_selector == null)- {- bool current;- try { current = await _inner.IsCheckedAsync().ConfigureAwait(false); }- catch (System.Exception) { current = !checkedState; }- if (current != checkedState)- await LocatorHumanizer.ClickAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), null).ConfigureAwait(false);- return;- }- var timeout = OptionReader.Timeout(options); var force = OptionReader.Force(options);- var deadline = Environment.TickCount64 + timeout;- await LocatorHumanizer.EnsureActionableAsync(_cursor, _selector, Actionability.ChecksCheck,- Actionability.RemainingMs(deadline), force).ConfigureAwait(false);- var directCurrent = (await LocatorHumanizer.SnapshotAsync(_cursor, _selector).ConfigureAwait(false)).Checked == true;- if (directCurrent != checkedState)- await LocatorHumanizer.ClickAfterPrecheckAsync(_inner, _cursor, _cfg,- Actionability.RemainingMs(deadline), force, _selector).ConfigureAwait(false);- }-- public async Task DragToAsync(ILocator target, LocatorDragToOptions? options = null)+ private Target T(){- var realTarget = target is HumanizedLocator h ? h.Original : target;- var srcBox = await _inner.BoundingBoxAsync().ConfigureAwait(false);- var tgtBox = await realTarget.BoundingBoxAsync().ConfigureAwait(false);- if (srcBox == null || tgtBox == null)- {- await _inner.DragToAsync(realTarget, options).ConfigureAwait(false);- return;- }- await _cursor.EnsureInitializedAsync(_cfg).ConfigureAwait(false);- double sx = srcBox.X + srcBox.Width / 2, sy = srcBox.Y + srcBox.Height / 2;- double tx = tgtBox.X + tgtBox.Width / 2, ty = tgtBox.Y + tgtBox.Height / 2;- await HumanMouse.HumanMoveAsync(_cursor.RawMouse, _cursor.X, _cursor.Y, sx, sy, _cfg).ConfigureAwait(false);- _cursor.Set(sx, sy);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(100, 200)).ConfigureAwait(false);- await _cursor.RawMouseDownAsync().ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(80, 150)).ConfigureAwait(false);- await HumanMouse.HumanMoveAsync(_cursor.RawMouse, _cursor.X, _cursor.Y, tx, ty, _cfg).ConfigureAwait(false);- _cursor.Set(tx, ty);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(80, 150)).ConfigureAwait(false);- await _cursor.RawMouseUpAsync().ConfigureAwait(false);+ var (frame, selector) = PlaywrightInternals.LocatorParts(_inner);+ return new Target(frame, selector, strict: true);}- // --- SelectOptionAsync (all ILocator overloads) -------------------------- // Human pre-roll = curved hover + pause, then delegate the real select (native- // <select> popups can't be driven by synthetic mouse events). Unwrap any- // HumanizedElementHandle args so Playwright sees the raw handles.-- public async Task<IReadOnlyList<string>> SelectOptionAsync(string values, LocatorSelectOptionOptions? options = null)- {- await LocatorHumanizer.SelectOptionPrologueAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), _selector).ConfigureAwait(false);- return await _inner.SelectOptionAsync(values, options).ConfigureAwait(false);- }+ private static ActOpts Opt(object? options) => ActOpts.From(options);- public async Task<IReadOnlyList<string>> SelectOptionAsync(IElementHandle values, LocatorSelectOptionOptions? options = null)- {- await LocatorHumanizer.SelectOptionPrologueAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), _selector).ConfigureAwait(false);- return await _inner.SelectOptionAsync(Unwrap(values), options).ConfigureAwait(false);- }-- public async Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<string> values, LocatorSelectOptionOptions? options = null)- {- await LocatorHumanizer.SelectOptionPrologueAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), _selector).ConfigureAwait(false);- return await _inner.SelectOptionAsync(values, options).ConfigureAwait(false);- }-- public async Task<IReadOnlyList<string>> SelectOptionAsync(SelectOptionValue values, LocatorSelectOptionOptions? options = null)- {- await LocatorHumanizer.SelectOptionPrologueAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), _selector).ConfigureAwait(false);- return await _inner.SelectOptionAsync(values, options).ConfigureAwait(false);- }-- public async Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<IElementHandle> values, LocatorSelectOptionOptions? options = null)- {- await LocatorHumanizer.SelectOptionPrologueAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), _selector).ConfigureAwait(false);- return await _inner.SelectOptionAsync(values.Select(Unwrap), options).ConfigureAwait(false);- }-- public async Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<SelectOptionValue> values, LocatorSelectOptionOptions? options = null)+ public Task ClickAsync(LocatorClickOptions? options = null) => E.ClickAsync(T(), Opt(options), "Locator.ClickAsync");+ public Task DblClickAsync(LocatorDblClickOptions? options = null) => E.ClickAsync(T(), Opt(options), "Locator.DblClickAsync", 2);+ public Task HoverAsync(LocatorHoverOptions? options = null) => E.HoverAsync(T(), Opt(options), "Locator.HoverAsync");+ public Task TapAsync(LocatorTapOptions? options = null) => E.TapAsync(T(), Opt(options), "Locator.TapAsync");+ public Task FillAsync(string value, LocatorFillOptions? options = null) => E.FillAsync(T(), value, Opt(options), "Locator.FillAsync");+ public Task ClearAsync(LocatorClearOptions? options = null) => E.FillAsync(T(), "", Opt(options), "Locator.ClearAsync");+ public Task TypeAsync(string text, LocatorTypeOptions? options = null) => E.TypeAsync(T(), text, Opt(options), "Locator.TypeAsync");+ public Task PressSequentiallyAsync(string text, LocatorPressSequentiallyOptions? options = null) =>+ E.TypeAsync(T(), text, Opt(options), "Locator.PressSequentiallyAsync");+ public Task PressAsync(string key, LocatorPressOptions? options = null) => E.PressAsync(T(), key, Opt(options), "Locator.PressAsync");+ public Task CheckAsync(LocatorCheckOptions? options = null) => E.SetCheckedAsync(T(), true, Opt(options), "Locator.CheckAsync");+ public Task UncheckAsync(LocatorUncheckOptions? options = null) => E.SetCheckedAsync(T(), false, Opt(options), "Locator.UncheckAsync");+ public Task SetCheckedAsync(bool checkedState, LocatorSetCheckedOptions? options = null) =>+ E.SetCheckedAsync(T(), checkedState, Opt(options), "Locator.SetCheckedAsync");+ public Task FocusAsync(LocatorFocusOptions? options = null) => E.FocusAsync(T(), Opt(options), "Locator.FocusAsync");+ public Task ScrollIntoViewIfNeededAsync(LocatorScrollIntoViewIfNeededOptions? options = null) =>+ E.ScrollIntoViewIfNeededAsync(T(), Opt(options), "Locator.ScrollIntoViewIfNeededAsync");++ public Task DragToAsync(ILocator target, LocatorDragToOptions? options = null){- await LocatorHumanizer.SelectOptionPrologueAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), _selector).ConfigureAwait(false);- return await _inner.SelectOptionAsync(values, options).ConfigureAwait(false);+ var other = target is HumanizedLocator h ? h.Original : target;+ var (frame, selector) = PlaywrightInternals.LocatorParts(other);+ return E.DragAsync(T(), new Target(frame, selector, strict: true), Opt(options), "Locator.DragToAsync");}- // --- ClearAsync ---------------------------------------------------------- // Human path: focus (humanized click if needed) + select-all + Backspace,- // instead of an instant value reset.-- public Task ClearAsync(LocatorClearOptions? options = null) =>- LocatorHumanizer.ClearAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), _selector);+ private Task<IReadOnlyList<string>> Select(SelectValues v, LocatorSelectOptionOptions? options) =>+ E.SelectOptionAsync(T(), v.Options, v.Handles, Opt(options), "Locator.SelectOptionAsync");++ public Task<IReadOnlyList<string>> SelectOptionAsync(string values, LocatorSelectOptionOptions? options = null) =>+ Select(SelectValues.Of(new[] { values }), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(IElementHandle values, LocatorSelectOptionOptions? options = null) =>+ Select(SelectValues.Of(new[] { values }), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<string> values, LocatorSelectOptionOptions? options = null) =>+ Select(SelectValues.Of(values), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(SelectOptionValue values, LocatorSelectOptionOptions? options = null) =>+ Select(SelectValues.Of(new[] { values }), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<IElementHandle> values, LocatorSelectOptionOptions? options = null) =>+ Select(SelectValues.Of(values), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<SelectOptionValue> values, LocatorSelectOptionOptions? options = null) =>+ Select(SelectValues.Of(values), options);private static IElementHandle Unwrap(IElementHandle handle) =>handle is HumanizedElementHandle h ? h.Original : handle;@@ -230,6 +130,8 @@ public sealed partial class HumanizedLocator : ILocatorreturn Wrap(_inner.Filter(options));}+ public IFrameLocator FrameLocator(string selector) => Humanize.WrapFrameLocator(_inner.FrameLocator(selector), _cursor, _cfg);+ public IFrameLocator ContentFrame => Humanize.WrapFrameLocator(_inner.ContentFrame, _cursor, _cfg);public ILocator Locator(string selectorOrLocator, LocatorLocatorOptions? options = null) =>Wrap(_inner.Locator(selectorOrLocator, options));public ILocator Locator(ILocator selectorOrLocator, LocatorLocatorOptions? options = null) =>@@ -248,4 +150,14 @@ public sealed partial class HumanizedLocator : ILocatorpublic ILocator GetByText(Regex text, LocatorGetByTextOptions? options = null) => Wrap(_inner.GetByText(text, options));public ILocator GetByTitle(string text, LocatorGetByTitleOptions? options = null) => Wrap(_inner.GetByTitle(text, options));public ILocator GetByTitle(Regex text, LocatorGetByTitleOptions? options = null) => Wrap(_inner.GetByTitle(text, options));++ // -----------------------------------------------------------------------+ // Handle-returning members - re-wrap so handle actions stay humanized.+ // -----------------------------------------------------------------------++ public async Task<IElementHandle> ElementHandleAsync(LocatorElementHandleOptions? options = null) =>+ Humanize.WrapElementHandle(await _inner.ElementHandleAsync(options).ConfigureAwait(false), _cursor, _cfg);++ public async Task<IReadOnlyList<IElementHandle>> ElementHandlesAsync() =>+ Humanize.WrapHandles(await _inner.ElementHandlesAsync().ConfigureAwait(false), _cursor, _cfg);}diff --git a/dotnet/src/CloakBrowser/Wrappers/HumanizedMouse.cs b/dotnet/src/CloakBrowser/Wrappers/HumanizedMouse.csindex 6c7f66f..8400552 100644--- a/dotnet/src/CloakBrowser/Wrappers/HumanizedMouse.cs+++ b/dotnet/src/CloakBrowser/Wrappers/HumanizedMouse.cs@@ -6,9 +6,10 @@ namespace CloakBrowser.Wrappers;/// <summary>/// Transparent humanizing decorator over Playwright's <see cref="IMouse"/>.///-/// Intercepted (humanized): <c>MoveAsync</c>, <c>ClickAsync</c>, <c>DblClickAsync</c>,-/// <c>DownAsync</c>, <c>UpAsync</c>, <c>WheelAsync</c>. Everything else is delegated-/// to the inner mouse by the source generator.+/// Intercepted (humanized): <c>MoveAsync</c> (Bezier path; <c>Steps</c> is honoured as a+/// straight Playwright move), <c>ClickAsync</c> / <c>DblClickAsync</c> (curve + real+/// press sequence, <c>Button</c> / <c>ClickCount</c> / <c>Delay</c> honoured). Down/Up/Wheel+/// are deliberate low-level primitives and are delegated unchanged by the generator./// </summary>[GenerateInterfaceDelegation(typeof(IMouse))]public sealed partial class HumanizedMouse : IMouse@@ -30,45 +31,13 @@ public sealed partial class HumanizedMouse : IMouse/// <summary>Alias of <see cref="Original"/>.</summary>public IMouse Inner => _inner;- public async Task MoveAsync(float x, float y, MouseMoveOptions? options = null)- {- await _cursor.EnsureInitializedAsync(_cfg).ConfigureAwait(false);- await HumanMouse.HumanMoveAsync(_cursor.RawMouse, _cursor.X, _cursor.Y, x, y, _cfg).ConfigureAwait(false);- _cursor.Set(x, y);- }-- public async Task ClickAsync(float x, float y, MouseClickOptions? options = null)- {- await _cursor.EnsureInitializedAsync(_cfg).ConfigureAwait(false);- await HumanMouse.HumanMoveAsync(_cursor.RawMouse, _cursor.X, _cursor.Y, x, y, _cfg).ConfigureAwait(false);- _cursor.Set(x, y);- await HumanMouse.HumanClickAsync(_cursor.RawMouse, isInput: false, _cfg).ConfigureAwait(false);- }-- public async Task DblClickAsync(float x, float y, MouseDblClickOptions? options = null)- {- await _cursor.EnsureInitializedAsync(_cfg).ConfigureAwait(false);- await HumanMouse.HumanMoveAsync(_cursor.RawMouse, _cursor.X, _cursor.Y, x, y, _cfg).ConfigureAwait(false);- _cursor.Set(x, y);- await _cursor.RawMouseDownAsync(2).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(30, 60)).ConfigureAwait(false);- await _cursor.RawMouseUpAsync(2).ConfigureAwait(false);- }+ private HumanEngine E => _cursor.EngineFor(_cfg);- public async Task DownAsync(MouseDownOptions? options = null)- {- await HumanRandom.SleepMsAsync(HumanRandom.RandRange(_cfg.ClickHoldButton)).ConfigureAwait(false);- await _inner.DownAsync(options).ConfigureAwait(false);- }+ public Task MoveAsync(float x, float y, MouseMoveOptions? options = null) => E.MouseMoveAsync(x, y, options?.Steps);- public async Task UpAsync(MouseUpOptions? options = null)- {- await HumanRandom.SleepMsAsync(HumanRandom.RandRange(_cfg.ClickHoldButton)).ConfigureAwait(false);- await _inner.UpAsync(options).ConfigureAwait(false);- }+ public Task ClickAsync(float x, float y, MouseClickOptions? options = null) =>+ E.MouseClickAsync(x, y, options?.Delay, options?.Button, options?.ClickCount);- public async Task WheelAsync(float deltaX, float deltaY)- {- await HumanScroll.SmoothWheelAsync(_cursor.RawMouse, deltaX, deltaY, _cfg).ConfigureAwait(false);- }+ public Task DblClickAsync(float x, float y, MouseDblClickOptions? options = null) =>+ E.MouseClickAsync(x, y, options?.Delay, options?.Button, 2);}diff --git a/dotnet/src/CloakBrowser/Wrappers/HumanizedPage.cs b/dotnet/src/CloakBrowser/Wrappers/HumanizedPage.csindex 414620b..5bdb242 100644--- a/dotnet/src/CloakBrowser/Wrappers/HumanizedPage.cs+++ b/dotnet/src/CloakBrowser/Wrappers/HumanizedPage.cs@@ -8,7 +8,7 @@ namespace CloakBrowser.Wrappers;/// Transparent humanizing decorator over Playwright's <see cref="IPage"/>.////// Selector-based interaction methods (Click/Fill/Type/Hover/Press/Tap/Check/...) are-/// routed through the selector-driven <see cref="HumanPage"/> engine. <c>Mouse</c> and+/// routed through the unified <see cref="HumanEngine"/>. <c>Mouse</c> and/// <c>Keyboard</c> return humanized wrappers; <c>Locator</c>/<c>GetBy*</c>/frames return/// re-wrapped objects so the whole chain stays humanized. Everything else is delegated/// to the inner page by the source generator.@@ -19,7 +19,7 @@ public sealed partial class HumanizedPage : IPageprivate readonly IPage _inner;private readonly HumanCursor _cursor;private readonly HumanConfig _cfg;- private readonly HumanPage _human;+ private readonly HumanEngine _engine;private readonly HumanizedMouse _mouse;private readonly HumanizedKeyboard _keyboard;private readonly object _frameEventLock = new();@@ -32,16 +32,12 @@ public sealed partial class HumanizedPage : IPage_inner = inner;_cursor = cursor;_cfg = cfg;- _human = new HumanPage(inner, cfg);+ _engine = cursor.EngineFor(cfg);_mouse = new HumanizedMouse(inner.Mouse, cursor, cfg);_keyboard = new HumanizedKeyboard(inner.Keyboard, cursor, cfg);- // Invalidate the isolated world on any main-frame nav, not just goto, so- // click/form navigations don't leave it bound to a stale doc (#507).- _inner.FrameNavigated += (_, frame) =>- {- if (frame == _inner.MainFrame) _cursor.InvalidateStealth();- };+ // Isolated worlds are dropped per frame on navigation / detach by HumanWorld+ // itself, so click/form navigations never leave a stale document (#507).}/// <summary>The original, un-humanized Playwright page (escape hatch for raw speed).</summary>@@ -50,12 +46,9 @@ public sealed partial class HumanizedPage : IPage/// <summary>Alias of <see cref="Original"/>.</summary>public IPage Inner => _inner;- private HumanActionOptions Opt(object? options) => new()- {- Timeout = OptionReader.Timeout(options),- Force = OptionReader.Force(options),- Delay = OptionReader.Delay(options),- };+ private static ActOpts Opt(object? options) => ActOpts.From(options);+ private Target T(string selector, object? options) =>+ new(_inner.MainFrame, selector, ActOpts.From(options).Strict);private ILocator Wrap(ILocator l) => Humanize.WrapLocator(l, _cursor, _cfg);private ILocator Wrap(ILocator l, string? selector) => Humanize.WrapLocator(l, _cursor, _cfg, selector);@@ -113,72 +106,56 @@ public sealed partial class HumanizedPage : IPage// -----------------------------------------------------------------------public Task ClickAsync(string selector, PageClickOptions? options = null) =>- _human.ClickAsync(selector, Opt(options));+ _engine.ClickAsync(T(selector, options), Opt(options), "Page.ClickAsync");public Task DblClickAsync(string selector, PageDblClickOptions? options = null) =>- _human.DblClickAsync(selector, Opt(options));+ _engine.ClickAsync(T(selector, options), Opt(options), "Page.DblClickAsync", 2);public Task HoverAsync(string selector, PageHoverOptions? options = null) =>- _human.HoverAsync(selector, Opt(options));+ _engine.HoverAsync(T(selector, options), Opt(options), "Page.HoverAsync");public Task TapAsync(string selector, PageTapOptions? options = null) =>- _human.TapAsync(selector, Opt(options));+ _engine.TapAsync(T(selector, options), Opt(options), "Page.TapAsync");public Task FillAsync(string selector, string value, PageFillOptions? options = null) =>- _human.FillAsync(selector, value, Opt(options));+ _engine.FillAsync(T(selector, options), value, Opt(options), "Page.FillAsync");public Task TypeAsync(string selector, string text, PageTypeOptions? options = null) =>- _human.TypeAsync(selector, text, Opt(options));+ _engine.TypeAsync(T(selector, options), text, Opt(options), "Page.TypeAsync");public Task PressAsync(string selector, string key, PagePressOptions? options = null) =>- _human.PressAsync(selector, key, Opt(options));+ _engine.PressAsync(T(selector, options), key, Opt(options), "Page.PressAsync");public Task CheckAsync(string selector, PageCheckOptions? options = null) =>- _human.CheckAsync(selector, Opt(options));+ _engine.SetCheckedAsync(T(selector, options), true, Opt(options), "Page.CheckAsync");public Task UncheckAsync(string selector, PageUncheckOptions? options = null) =>- _human.UncheckAsync(selector, Opt(options));+ _engine.SetCheckedAsync(T(selector, options), false, Opt(options), "Page.UncheckAsync");public Task SetCheckedAsync(string selector, bool checkedState, PageSetCheckedOptions? options = null) =>- _human.SetCheckedAsync(selector, checkedState, Opt(options));+ _engine.SetCheckedAsync(T(selector, options), checkedState, Opt(options), "Page.SetCheckedAsync");public Task FocusAsync(string selector, PageFocusOptions? options = null) =>- _human.FocusAsync(selector, Opt(options));+ _engine.FocusAsync(T(selector, options), Opt(options), "Page.FocusAsync");public Task DragAndDropAsync(string source, string target, PageDragAndDropOptions? options = null) =>- _human.DragAndDropAsync(source, target, Opt(options));+ _engine.DragAsync(T(source, options), T(target, options), Opt(options), "Page.DragAndDropAsync");- public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, string values, PageSelectOptionOptions? options = null) =>- _human.SelectOptionAsync(selector, new[] { values }, Opt(options));+ private Task<IReadOnlyList<string>> Select(string selector, SelectValues v, PageSelectOptionOptions? options) =>+ _engine.SelectOptionAsync(T(selector, options), v.Options, v.Handles, Opt(options), "Page.SelectOptionAsync");+ public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, string values, PageSelectOptionOptions? options = null) =>+ Select(selector, SelectValues.Of(new[] { values }), options);public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<string> values, PageSelectOptionOptions? options = null) =>- _human.SelectOptionAsync(selector, values.ToArray(), Opt(options));-- // SelectOption overloads taking handles / SelectOptionValue have no humanized- // analogue; hover then delegate so the dropdown still gets a human approach.- public async Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IElementHandle values, PageSelectOptionOptions? options = null)- {- await _human.HoverAsync(selector, Opt(options)).ConfigureAwait(false);- return await _inner.SelectOptionAsync(selector, Unwrap(values), options).ConfigureAwait(false);- }-- public async Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<IElementHandle> values, PageSelectOptionOptions? options = null)- {- await _human.HoverAsync(selector, Opt(options)).ConfigureAwait(false);- return await _inner.SelectOptionAsync(selector, values.Select(Unwrap), options).ConfigureAwait(false);- }-- public async Task<IReadOnlyList<string>> SelectOptionAsync(string selector, SelectOptionValue values, PageSelectOptionOptions? options = null)- {- await _human.HoverAsync(selector, Opt(options)).ConfigureAwait(false);- return await _inner.SelectOptionAsync(selector, values, options).ConfigureAwait(false);- }-- public async Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<SelectOptionValue> values, PageSelectOptionOptions? options = null)- {- await _human.HoverAsync(selector, Opt(options)).ConfigureAwait(false);- return await _inner.SelectOptionAsync(selector, values, options).ConfigureAwait(false);- }+ Select(selector, SelectValues.Of(values), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IElementHandle values, PageSelectOptionOptions? options = null) =>+ Select(selector, SelectValues.Of(new[] { values }), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<IElementHandle> values, PageSelectOptionOptions? options = null) =>+ Select(selector, SelectValues.Of(values), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, SelectOptionValue values, PageSelectOptionOptions? options = null) =>+ Select(selector, SelectValues.Of(new[] { values }), options);+ public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<SelectOptionValue> values, PageSelectOptionOptions? options = null) =>+ Select(selector, SelectValues.Of(values), options);private static IElementHandle Unwrap(IElementHandle h) => h is HumanizedElementHandle hh ? hh.Original : h;private static ILocator Unwrap(ILocator l) => l is HumanizedLocator hl ? hl.Original : l;@@ -208,6 +185,7 @@ public sealed partial class HumanizedPage : IPage// Locator options can change which element Playwright resolves. Preserve raw// selector metadata only when it completely describes the locator semantics.+ public IFrameLocator FrameLocator(string selector) => Humanize.WrapFrameLocator(_inner.FrameLocator(selector), _cursor, _cfg);public ILocator Locator(string selector, PageLocatorOptions? options = null) =>Wrap(_inner.Locator(selector, options), options == null ? selector : null);public ILocator GetByAltText(string text, PageGetByAltTextOptions? options = null) => Wrap(_inner.GetByAltText(text, options));@@ -257,13 +235,17 @@ public sealed partial class HumanizedPage : IPagepublic IFrame? FrameByUrl(System.Func<string, bool> url) { var f = _inner.FrameByUrl(url); return f == null ? null : Wrap(f); }// ------------------------------------------------------------------------ // Navigation - invalidate the isolated world after a navigation.+ // Handle-returning members - re-wrap so handle actions stay humanized.// ------------------------------------------------------------------------ public async Task<IResponse?> GotoAsync(string url, PageGotoOptions? options = null)- {- var resp = await _inner.GotoAsync(url, options).ConfigureAwait(false);- _cursor.InvalidateStealth();- return resp;- }+ private IElementHandle? H(IElementHandle? h) => h == null ? null : Humanize.WrapElementHandle(h, _cursor, _cfg);++ public async Task<IElementHandle?> QuerySelectorAsync(string selector, PageQuerySelectorOptions? options = null) =>+ H(await _inner.QuerySelectorAsync(selector, options).ConfigureAwait(false));++ public async Task<IReadOnlyList<IElementHandle>> QuerySelectorAllAsync(string selector) =>+ Humanize.WrapHandles(await _inner.QuerySelectorAllAsync(selector).ConfigureAwait(false), _cursor, _cfg);++ public async Task<IElementHandle?> WaitForSelectorAsync(string selector, PageWaitForSelectorOptions? options = null) =>+ H(await _inner.WaitForSelectorAsync(selector, options).ConfigureAwait(false));}diff --git a/dotnet/src/CloakBrowser/Wrappers/LocatorHumanizer.cs b/dotnet/src/CloakBrowser/Wrappers/LocatorHumanizer.csdeleted file mode 100644index 8240010..0000000--- a/dotnet/src/CloakBrowser/Wrappers/LocatorHumanizer.cs+++ /dev/null@@ -1,233 +0,0 @@-using CloakBrowser.Human;-using Microsoft.Playwright;--namespace CloakBrowser.Wrappers;--/// <summary>Humanized locator actions. Direct page.Locator selectors use the canonical isolated DOM world; unknown locator shapes retain the legacy Playwright path.</summary>-internal static class LocatorHumanizer-{- private static double RemainingMs(double deadline) => Actionability.RemainingMs(deadline);-- private static async Task<IsolatedWorld> WorldAsync(HumanCursor cursor) =>- await cursor.GetStealthAsync().ConfigureAwait(false) ?? throw new StealthWorldUnavailableError();-- internal static async Task<StealthSnapshot> SnapshotAsync(HumanCursor cursor, string selector)- {- var (status, snapshot) = await StealthDom.SnapshotAsync(await WorldAsync(cursor).ConfigureAwait(false), selector).ConfigureAwait(false);- return status switch- {- StealthStatus.Ok when snapshot != null => snapshot.Value,- StealthStatus.NotFound => throw new ElementNotAttachedError(selector),- StealthStatus.Unsupported => throw new UnsupportedHumanizeSelectorError(selector),- _ => throw new StealthEvaluationError(selector),- };- }-- internal static async Task EnsureActionableAsync(HumanCursor cursor, string selector,- IReadOnlySet<string> checks, double timeout, bool force)- {- var world = await WorldAsync(cursor).ConfigureAwait(false);- await Actionability.EnsureActionableAsync(cursor.Page, selector, checks, timeout, force, world).ConfigureAwait(false);- }-- private static async Task<BoundingBox?> GetBoxAsync(- IsolatedWorld world, string selector, double timeoutMs)- {- double deadline = System.Environment.TickCount64 + System.Math.Max(0, timeoutMs);- var result = await StealthDom.BoxAsync(world, selector).ConfigureAwait(false);- while ((result.Status == StealthStatus.NotFound || result.Status == StealthStatus.EvaluationFailed)- && System.Environment.TickCount64 < deadline)- {- await Task.Delay(50).ConfigureAwait(false);- result = await StealthDom.BoxAsync(world, selector).ConfigureAwait(false);- }-- return result.Status switch- {- StealthStatus.Ok when result.Target != null => result.Target.Value.Box,- StealthStatus.NotFound => null,- StealthStatus.Unsupported => throw new UnsupportedHumanizeSelectorError(selector),- _ => throw new StealthEvaluationError(selector),- };- }-- // Share the canonical page-selector scroll flow: target zone, boundary checks,- // stability wait and rescroll all remain isolated-world-only.- private static async Task<StealthSnapshot> EnsureInViewAsync(- HumanCursor cursor, IsolatedWorld world, string selector,- HumanConfig cfg, double deadline, bool force)- {- var scrollPage = new PlaywrightScrollPage(- cursor.Page, () => Task.FromResult(world));- var scroll = await HumanScroll.HumanScrollIntoViewAsync(- scrollPage, cursor.RawMouse,- () => GetBoxAsync(world, selector, RemainingMs(deadline)),- cursor.X, cursor.Y, cfg).ConfigureAwait(false);- cursor.Set(scroll.CursorX, scroll.CursorY);-- if (!force && scroll.DidScroll)- {- await Actionability.EnsureStableAsync(- cursor.Page, selector, RemainingMs(deadline), world).ConfigureAwait(false);- var rescroll = await HumanScroll.HumanScrollIntoViewAsync(- scrollPage, cursor.RawMouse,- () => GetBoxAsync(world, selector, RemainingMs(deadline)),- cursor.X, cursor.Y, cfg).ConfigureAwait(false);- cursor.Set(rescroll.CursorX, rescroll.CursorY);- }-- return await SnapshotAsync(cursor, selector).ConfigureAwait(false);- }-- private static async Task<BoundingBox?> GetBoxPlaywrightAsync(ILocator locator, double timeoutMs)- {- try- {- var box = await locator.First.BoundingBoxAsync(new LocatorBoundingBoxOptions { Timeout = (float)System.Math.Max(1, timeoutMs) }).ConfigureAwait(false);- return box == null ? null : new BoundingBox(box.X, box.Y, box.Width, box.Height);- }- catch (System.Exception) { return null; }- }-- private static async Task<bool> IsInputPlaywrightAsync(ILocator locator)- {- try { return await locator.First.EvaluateAsync<bool>(@"el => { const tag = el.tagName.toLowerCase(); return tag === 'input' || tag === 'textarea' || el.getAttribute('contenteditable') === 'true'; }").ConfigureAwait(false); }- catch (System.Exception) { return false; }- }-- private static async Task<bool> IsFocusedLegacyAsync(ILocator locator)- {- try { return await locator.First.EvaluateAsync<bool>("el => el === document.activeElement").ConfigureAwait(false); }- catch (System.Exception) { return false; }- }-- private static async Task<(double X, double Y, bool IsInput)> MoveLegacyAsync(ILocator locator,- HumanCursor cursor, HumanConfig cfg, double deadline, bool force)- {- await cursor.EnsureInitializedAsync(cfg).ConfigureAwait(false);- if (cfg.IdleBetweenActions) await HumanMouse.HumanIdleAsync(cursor.RawMouse,- HumanRandom.Rand(cfg.IdleBetweenDuration.Min, cfg.IdleBetweenDuration.Max), cursor.X, cursor.Y, cfg).ConfigureAwait(false);- if (!force) await locator.First.ScrollIntoViewIfNeededAsync(new LocatorScrollIntoViewIfNeededOptions { Timeout = (float)RemainingMs(deadline) }).ConfigureAwait(false);- var box = await GetBoxPlaywrightAsync(locator, RemainingMs(deadline)).ConfigureAwait(false);- var input = await IsInputPlaywrightAsync(locator).ConfigureAwait(false);- var target = HumanMouse.ClickTarget(box ?? new BoundingBox(cursor.X, cursor.Y, 1, 1), input, cfg);- await HumanMouse.HumanMoveAsync(cursor.RawMouse, cursor.X, cursor.Y, target.X, target.Y, cfg).ConfigureAwait(false);- cursor.Set(target.X, target.Y);- return (target.X, target.Y, input);- }-- private static async Task<(double X, double Y, bool IsInput)> MoveDirectAsync(ILocator locator,- HumanCursor cursor, HumanConfig cfg, double deadline, bool force, string selector, IReadOnlySet<string> checks, bool skipChecks)- {- await cursor.EnsureInitializedAsync(cfg).ConfigureAwait(false);- var world = await WorldAsync(cursor).ConfigureAwait(false);- if (!force && !skipChecks)- await Actionability.EnsureActionableAsync(cursor.Page, selector, checks, RemainingMs(deadline), false, world).ConfigureAwait(false);- if (cfg.IdleBetweenActions) await HumanMouse.HumanIdleAsync(cursor.RawMouse,- HumanRandom.Rand(cfg.IdleBetweenDuration.Min, cfg.IdleBetweenDuration.Max), cursor.X, cursor.Y, cfg).ConfigureAwait(false);- var snapshot = await EnsureInViewAsync(- cursor, world, selector, cfg, deadline, force).ConfigureAwait(false);- var box = snapshot.Box ?? throw new ElementNotVisibleError(selector);- var target = HumanMouse.ClickTarget(box, snapshot.IsInput, cfg);- await HumanMouse.HumanMoveAsync(cursor.RawMouse, cursor.X, cursor.Y, target.X, target.Y, cfg).ConfigureAwait(false);- cursor.Set(target.X, target.Y);- // Validate the click point after motion, immediately before the caller's mouse-down.- // force bypasses it entirely, matching Playwright.- if (!force)- await Actionability.CheckPointerEventsAsync(cursor.Page, selector, snapshot.TargetId, snapshot.Gen,- target.X, target.Y, RemainingMs(deadline), world).ConfigureAwait(false);- return (target.X, target.Y, snapshot.IsInput);- }-- private static Task<(double X, double Y, bool IsInput)> MoveAsync(ILocator locator, HumanCursor cursor,- HumanConfig cfg, double deadline, bool force, string? selector, IReadOnlySet<string> checks, bool skipChecks) =>- selector == null ? MoveLegacyAsync(locator, cursor, cfg, deadline, force) :- MoveDirectAsync(locator, cursor, cfg, deadline, force, selector, checks, skipChecks);-- private static async Task ClickInternalAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg,- double timeout, bool force, string? selector, IReadOnlySet<string> checks, bool skipChecks)- {- var deadline = System.Environment.TickCount64 + timeout;- var target = await MoveAsync(locator, cursor, cfg, deadline, force, selector, checks, skipChecks).ConfigureAwait(false);- await HumanMouse.HumanClickAsync(cursor.RawMouse, target.IsInput, cfg).ConfigureAwait(false);- }-- public static Task ClickAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null) =>- ClickInternalAsync(locator, cursor, cfg, timeout, force, selector, Actionability.ChecksClick, false);-- // Used by state-changing wrappers after their ChecksCheck preflight.- internal static Task ClickAfterPrecheckAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg,- double timeout, bool force, string? selector) =>- ClickInternalAsync(locator, cursor, cfg, timeout, force, selector, Actionability.ChecksCheck, selector != null);-- public static async Task DblClickAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null)- {- var deadline = System.Environment.TickCount64 + timeout;- await MoveAsync(locator, cursor, cfg, deadline, force, selector, Actionability.ChecksClick, false).ConfigureAwait(false);- await cursor.RawMouseDownAsync(2).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(30, 60)).ConfigureAwait(false);- await cursor.RawMouseUpAsync(2).ConfigureAwait(false);- }-- public static async Task HoverAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null)- {- var deadline = System.Environment.TickCount64 + timeout;- await MoveAsync(locator, cursor, cfg, deadline, force, selector, Actionability.ChecksHover, false).ConfigureAwait(false);- }-- public static Task TapAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null) =>- ClickAsync(locator, cursor, cfg, timeout, force, selector);-- public static async Task FillAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string value, string? selector = null)- {- var deadline = System.Environment.TickCount64 + timeout;- if (selector != null) await EnsureActionableAsync(cursor, selector, Actionability.ChecksInput, RemainingMs(deadline), force).ConfigureAwait(false);- await ClickInternalAsync(locator, cursor, cfg, RemainingMs(deadline), force, selector, Actionability.ChecksInput, selector != null).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(100, 250)).ConfigureAwait(false);- await cursor.SelectAllAsync().ConfigureAwait(false); await HumanRandom.SleepMsAsync(HumanRandom.Rand(30, 80)).ConfigureAwait(false);- await cursor.PressAsync("Backspace").ConfigureAwait(false); await HumanRandom.SleepMsAsync(HumanRandom.Rand(50, 150)).ConfigureAwait(false);- await cursor.HumanTypeAsync(value, cfg).ConfigureAwait(false);- }-- public static async Task TypeAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string text, string? selector = null)- {- var deadline = System.Environment.TickCount64 + timeout;- if (selector != null) await EnsureActionableAsync(cursor, selector, Actionability.ChecksInput, RemainingMs(deadline), force).ConfigureAwait(false);- var focused = selector != null- ? (await SnapshotAsync(cursor, selector).ConfigureAwait(false)).Focused- : await IsFocusedLegacyAsync(locator).ConfigureAwait(false);- if (!focused)- await ClickInternalAsync(locator, cursor, cfg, RemainingMs(deadline), force, selector, Actionability.ChecksInput, selector != null).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(100, 250)).ConfigureAwait(false); await cursor.HumanTypeAsync(text, cfg).ConfigureAwait(false);- }-- public static Task PressSequentiallyAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string text, string? selector = null) =>- TypeAsync(locator, cursor, cfg, timeout, force, text, selector);-- public static async Task PressAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string key, float? delay = null, string? selector = null)- {- var deadline = System.Environment.TickCount64 + timeout;- if (selector != null) await EnsureActionableAsync(cursor, selector, Actionability.ChecksFocus, RemainingMs(deadline), force).ConfigureAwait(false);- var focused = selector != null ? (await SnapshotAsync(cursor, selector).ConfigureAwait(false)).Focused : await IsFocusedLegacyAsync(locator).ConfigureAwait(false);- if (!focused) await ClickInternalAsync(locator, cursor, cfg, RemainingMs(deadline), force, selector, Actionability.ChecksFocus, selector != null).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(50, 150)).ConfigureAwait(false); await cursor.PressAsync(key, delay).ConfigureAwait(false);- }-- public static async Task SelectOptionPrologueAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null)- {- var deadline = System.Environment.TickCount64 + timeout;- if (selector != null) await EnsureActionableAsync(cursor, selector, Actionability.ChecksFocus, RemainingMs(deadline), force).ConfigureAwait(false);- await MoveAsync(locator, cursor, cfg, deadline, force, selector, Actionability.ChecksHover, selector != null).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(100, 300)).ConfigureAwait(false);- }-- public static async Task ClearAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null)- {- var deadline = System.Environment.TickCount64 + timeout;- if (selector != null) await EnsureActionableAsync(cursor, selector, Actionability.ChecksInput, RemainingMs(deadline), force).ConfigureAwait(false);- var focused = selector != null ? (await SnapshotAsync(cursor, selector).ConfigureAwait(false)).Focused : await IsFocusedLegacyAsync(locator).ConfigureAwait(false);- if (!focused) await ClickInternalAsync(locator, cursor, cfg, RemainingMs(deadline), force, selector, Actionability.ChecksInput, selector != null).ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(50, 100)).ConfigureAwait(false); await cursor.SelectAllAsync().ConfigureAwait(false);- await HumanRandom.SleepMsAsync(HumanRandom.Rand(30, 80)).ConfigureAwait(false); await cursor.PressAsync("Backspace").ConfigureAwait(false);- }-}diff --git a/dotnet/tests/CloakBrowser.Tests/BrowserFactAttribute.cs b/dotnet/tests/CloakBrowser.Tests/BrowserFactAttribute.csnew file mode 100644index 0000000..5c341cf--- /dev/null+++ b/dotnet/tests/CloakBrowser.Tests/BrowserFactAttribute.cs@@ -0,0 +1,25 @@+using Xunit;++namespace CloakBrowser.Tests;++/// <summary>A <see cref="FactAttribute"/> for tests that drive a real CloakBrowser binary:+/// reported as skipped (not silently passed) when <c>CLOAKBROWSER_BINARY_PATH</c> is not set.</summary>+public sealed class BrowserFactAttribute : FactAttribute+{+ public static bool Available =>+ !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("CLOAKBROWSER_BINARY_PATH"));++ public BrowserFactAttribute()+ {+ if (!Available) Skip = "set CLOAKBROWSER_BINARY_PATH to run real-browser tests";+ }+}++/// <summary><see cref="TheoryAttribute"/> counterpart of <see cref="BrowserFactAttribute"/>.</summary>+public sealed class BrowserTheoryAttribute : TheoryAttribute+{+ public BrowserTheoryAttribute()+ {+ if (!BrowserFactAttribute.Available) Skip = "set CLOAKBROWSER_BINARY_PATH to run real-browser tests";+ }+}diff --git a/dotnet/tests/CloakBrowser.Tests/Human/PointerEventsFailOpenTests.cs b/dotnet/tests/CloakBrowser.Tests/Human/PointerEventsFailOpenTests.csdeleted file mode 100644index 95be65f..0000000--- a/dotnet/tests/CloakBrowser.Tests/Human/PointerEventsFailOpenTests.cs+++ /dev/null@@ -1,88 +0,0 @@-using System.Diagnostics;-using CloakBrowser.Human;-using CloakBrowser.Tests.Wrappers; // Fake / FakeProxy test infrastructure-using Microsoft.Playwright;-using Xunit;--namespace CloakBrowser.Tests.Human;--/// <summary>-/// Exact ElementHandle probes retain their legacy fail-open behavior. Selector probes-/// require the isolated world and never fall back to Playwright DOM reads.-/// </summary>-public class PointerEventsFailOpenTests-{- // Build a Task<PointerResult?> handler value for the FakeProxy. PointerResult is- // internal (visible to tests via InternalsVisibleTo), so we can construct one.- private static Task<Actionability.PointerResult?> CoveredResult(string covering) =>- Task.FromResult<Actionability.PointerResult?>(- new Actionability.PointerResult { Hit = false, Covering = covering });-- // --- Selector variant ----------------------------------------------------- [Fact]- public async Task Selector_requires_isolated_world_without_locator_fallback()- {- var (page, pageRec) = Fake.Of<IPage>();-- await Assert.ThrowsAsync<StealthWorldUnavailableError>(- () => Actionability.CheckPointerEventsAsync(- page, "#x", targetId: 1, gen: 1, x: 100, y: 100, timeoutMs: 0));-- Assert.False(pageRec.WasCalled("Locator"));- }-- [Fact]- public async Task Legacy_selector_overload_remains_source_compatible()- {- var (page, pageRec) = Fake.Of<IPage>();-- await Assert.ThrowsAsync<StealthWorldUnavailableError>(- () => Actionability.CheckPointerEventsAsync(- page, "#x", x: 100, y: 100, timeoutMs: 0));-- Assert.False(pageRec.WasCalled("Locator"));- }-- [Fact]- public async Task Selector_actionability_requires_isolated_world_without_predicate_fallback()- {- var (page, pageRec) = Fake.Of<IPage>();-- await Assert.ThrowsAsync<StealthWorldUnavailableError>(- () => Actionability.EnsureActionableAsync(- page, "internal:role=button", Actionability.ChecksClick, timeoutMs: 100));-- Assert.False(pageRec.WasCalled("Locator"));- }-- // --- ElementHandle variant ------------------------------------------------ [Fact]- public async Task Handle_fails_open_when_evaluate_throws()- {- var (el, elRec) = Fake.Of<IElementHandle>();- elRec.On("BoundingBoxAsync", _ => throw new PlaywrightException("stale handle"));- elRec.On("EvaluateAsync", _ => throw new PlaywrightException("execution context destroyed"));-- var sw = Stopwatch.StartNew();- await Actionability.CheckPointerEventsHandleAsync(el, 100, 100, timeoutMs: 2000);- sw.Stop();-- Assert.True(sw.ElapsedMilliseconds < 500,- $"fail-open should return promptly, took {sw.ElapsedMilliseconds}ms");- }-- [Fact]- public async Task Handle_raises_when_covered()- {- var (el, elRec) = Fake.Of<IElementHandle>();- elRec.On("BoundingBoxAsync", Task.FromResult<ElementHandleBoundingBoxResult?>(- new ElementHandleBoundingBoxResult { X = 0, Y = 0, Width = 10, Height = 10 }));- elRec.On("EvaluateAsync", _ => CoveredResult("SPAN"));-- var ex = await Assert.ThrowsAsync<ElementNotReceivingEventsError>(- () => Actionability.CheckPointerEventsHandleAsync(el, 5, 5, timeoutMs: 200));- Assert.Contains("SPAN", ex.Message);- }-}diff --git a/dotnet/tests/CloakBrowser.Tests/Human/StealthDomBrowserTests.cs b/dotnet/tests/CloakBrowser.Tests/Human/SelectorParityBrowserTests.cssimilarity index 87%rename from dotnet/tests/CloakBrowser.Tests/Human/StealthDomBrowserTests.csrename to dotnet/tests/CloakBrowser.Tests/Human/SelectorParityBrowserTests.csindex c2e69c2..ba13484 100644--- a/dotnet/tests/CloakBrowser.Tests/Human/StealthDomBrowserTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/Human/SelectorParityBrowserTests.cs@@ -7,11 +7,8 @@ using Xunit;namespace CloakBrowser.Tests.Human;[Collection("env-serial")]-public class StealthDomBrowserTests+public class SelectorParityBrowserTests{- private static bool BrowserAvailable =>- !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("CLOAKBROWSER_BINARY_PATH"));-private static LaunchOptions FastLaunchOptions() => new(){Headless = true,@@ -28,10 +25,9 @@ public class StealthDomBrowserTests},};- [Fact]+ [BrowserFact]public async Task Hidden_script_text_and_shadow_order_match_direct_locators(){- if (!BrowserAvailable) return;await using var browser = await CloakLauncher.LaunchAsync(FastLaunchOptions());var page = await browser.NewPageAsync();@@ -77,10 +73,9 @@ public class StealthDomBrowserTestsAssert.Equal(expected, await page.EvaluateAsync<string[]>("() => window.__order"));}- [Fact]+ [BrowserFact]public async Task Display_contents_text_and_nested_geometry_are_clickable(){- if (!BrowserAvailable) return;await using var browser = await CloakLauncher.LaunchAsync(FastLaunchOptions());var page = await browser.NewPageAsync();@@ -106,10 +101,9 @@ public class StealthDomBrowserTestsAssert.Equal(1, await page.EvaluateAsync<int>("() => window.__nestedClicks"));}- [Fact]+ [BrowserFact]public async Task Text_css_and_actionability_state_match_direct_selector_behavior(){- if (!BrowserAvailable) return;await using var browser = await CloakLauncher.LaunchAsync(FastLaunchOptions());var page = await browser.NewPageAsync();@@ -136,22 +130,6 @@ public class StealthDomBrowserTests}}");- // Exercise the source-compatible pointer overload against a real isolated- // world; it must snapshot a target ID and delegate to exact validation.- object unguardedPage = page is IGuardedProxy guarded ? guarded.GuardTarget : page;- var humanizedPage = Assert.IsType<HumanizedPage>(unguardedPage);- var cursor = Assert.IsType<HumanCursor>(typeof(HumanizedPage)- .GetField("_cursor", BindingFlags.NonPublic | BindingFlags.Instance)!- .GetValue(humanizedPage));- var world = await cursor.GetStealthAsync();- Assert.NotNull(world);- var boxRead = await StealthDom.BoxAsync(world!, "#regex-target");- Assert.Equal(StealthStatus.Ok, boxRead.Status);- var probeBox = boxRead.Target!.Value.Box;- await Actionability.CheckPointerEventsAsync(- page, "#regex-target", probeBox.X + probeBox.Width / 2,- probeBox.Y + probeBox.Height / 2, 3000, world);-string[] selectors ={"text=/^Alpha\\d+$/",@@ -170,14 +148,21 @@ public class StealthDomBrowserTests"structural-target", "adjacent-target",}, await page.EvaluateAsync<string[]>("() => window.__clickedIds"));- await Assert.ThrowsAsync<ElementNotEnabledError>(() =>- page.ClickAsync("#disabled-target", new PageClickOptions { Timeout = 300 }));- await Assert.ThrowsAsync<ElementNotEnabledError>(() =>- page.ClickAsync("#aria-disabled", new PageClickOptions { Timeout = 300 }));- await Assert.ThrowsAsync<ElementNotEditableError>(() =>- page.FillAsync("#readonly-target", "x", new PageFillOptions { Timeout = 300 }));- await Assert.ThrowsAsync<UnsupportedHumanizeSelectorError>(() =>- page.ClickAsync("internal:role=button", new PageClickOptions { Timeout = 300 }));+ // Playwright semantics and messages: a disabled / readonly target waits and times+ // out with the reason; standard selectors (internal:role) are supported.+ var disabled = await Assert.ThrowsAsync<TimeoutException>(() =>+ page.ClickAsync("#disabled-target", new PageClickOptions { Timeout = 500 }));+ Assert.Contains("not enabled", disabled.Message);+ Assert.Contains("not enabled", (await Assert.ThrowsAsync<TimeoutException>(() =>+ page.ClickAsync("#aria-disabled", new PageClickOptions { Timeout = 500 }))).Message);+ // aria-readonly is version-dependent in Playwright's own InjectedScript (ignored by+ // Microsoft.Playwright 1.49, honoured by newer drivers); match the stock answer.+ bool stockEditable = await page.Locator("#readonly-target").IsEditableAsync();+ var readonlyErr = await Record.ExceptionAsync(() =>+ page.FillAsync("#readonly-target", "x", new PageFillOptions { Timeout = 500 }));+ if (stockEditable) Assert.Null(readonlyErr);+ else Assert.Contains("not editable", Assert.IsType<TimeoutException>(readonlyErr).Message);+ await page.ClickAsync("internal:role=button[name=\"adjacent\"i]", new PageClickOptions { Timeout = 3000 });await page.CheckAsync("#check-target", new PageCheckOptions { Timeout = 3000 });Assert.True(await page.Locator("#check-target").IsCheckedAsync());@@ -185,7 +170,7 @@ public class StealthDomBrowserTestsAssert.False(await page.Locator("#check-target").IsCheckedAsync());}- [Theory]+ [BrowserTheory][InlineData(false, "remove")][InlineData(true, "remove")][InlineData(false, "replace")]@@ -193,7 +178,6 @@ public class StealthDomBrowserTestspublic async Task Target_mutation_after_movement_never_clicks_underneath_or_replacement(bool force, string mutation){- if (!BrowserAvailable) return;await using var browser = await CloakLauncher.LaunchAsync(FastLaunchOptions());var page = await browser.NewPageAsync();@@ -220,27 +204,27 @@ public class StealthDomBrowserTests}, {once: true});}", mutation);+ // A removed target times out (never presses on what is under the cursor now);+ // a replaced target is re-resolved and reached with a fresh move, like Playwright.var error = await Record.ExceptionAsync(() => page.ClickAsync("#target", new PageClickOptions{Force = force,- Timeout = 3000,+ Timeout = mutation == "remove" ? 1500 : 15000,}));- Assert.NotNull(error);- if (mutation == "remove") Assert.IsType<ElementNotAttachedError>(error);- else Assert.IsType<ElementTargetChangedError>(error);+ if (mutation == "remove") Assert.IsType<TimeoutException>(error);+ else Assert.Null(error);var counts = await page.EvaluateAsync<ClickCounts>(@"() => ({underlying: window.__underlyingClicks,replacement: window.__replacementClicks,})");Assert.Equal(0, counts.Underlying);- Assert.Equal(0, counts.Replacement);+ Assert.Equal(mutation == "replace" ? 1 : 0, counts.Replacement);}- [Fact]+ [BrowserFact]public async Task Frame_options_and_repeated_position_locators_stay_legacy_compatible(){- if (!BrowserAvailable) return;await using var browser = await CloakLauncher.LaunchAsync(FastLaunchOptions());var page = await browser.NewPageAsync();@@ -285,10 +269,9 @@ public class StealthDomBrowserTestsAssert.Equal(new[] { "first" }, await page.EvaluateAsync<string[]>("() => window.__nestedClicks"));}- [Fact]+ [BrowserFact]public async Task Direct_locator_uses_canonical_scroll_and_rescroll_after_reflow(){- if (!BrowserAvailable) return;await using var browser = await CloakLauncher.LaunchAsync(FastLaunchOptions());var page = await browser.NewPageAsync();@@ -315,10 +298,9 @@ public class StealthDomBrowserTestsAssert.Equal(1, await page.EvaluateAsync<int>("() => window.__belowClicks"));}- [Fact]+ [BrowserFact]public async Task Force_skips_coverage_rejection_but_preserves_target_identity(){- if (!BrowserAvailable) return;await using var browser = await CloakLauncher.LaunchAsync(FastLaunchOptions());var page = await browser.NewPageAsync();diff --git a/dotnet/tests/CloakBrowser.Tests/Human/StealthDomTests.cs b/dotnet/tests/CloakBrowser.Tests/Human/StealthDomTests.csdeleted file mode 100644index 7d2feb5..0000000--- a/dotnet/tests/CloakBrowser.Tests/Human/StealthDomTests.cs+++ /dev/null@@ -1,208 +0,0 @@-using System;-using System.Diagnostics;-using System.IO;-using System.Text.Json;-using CloakBrowser.Human;-using Xunit;--namespace CloakBrowser.Tests.Human;--public class StealthDomTests-{- [Fact]- public void BuildBoxJs_EscapesSelector_AndReadsGeometry()- {- var js = StealthDom.BuildBoxJs("a\"b");- // IsolatedWorld.JsonEncode uses System.Text.Json, which escapes '"' as ".- Assert.Contains("a\\u0022b", js);- Assert.Contains("getBoundingClientRect", js);- }-- [Fact]- public void BuildPointerJs_InlinesCoordinates()- {- Assert.Contains("__deepElementFromPoint(1.5, 2.5)", StealthDom.BuildPointerJs("#x", 1.5, 2.5));- }-- [Fact]- public void ParseResult_strictly_validates_protocol_and_target_identity()- {- Assert.Equal(StealthStatus.Ok, StealthDom.ParseResult(- JsonSerializer.SerializeToElement(new { v = 2, r = "ok", targetId = 7, gen = 3 })).Status);- Assert.Equal(StealthStatus.Stale, StealthDom.ParseResult(- JsonSerializer.SerializeToElement(new { v = 2, r = "stale", targetId = 8, gen = 3 })).Status);- Assert.Equal(StealthStatus.NotFound, StealthDom.ParseResult(- JsonSerializer.SerializeToElement(new { v = 2, r = "not_found" })).Status);- Assert.Equal(StealthStatus.Unsupported, StealthDom.ParseResult(- JsonSerializer.SerializeToElement(new { v = 2, r = "unsupported" })).Status);-- JsonElement?[] malformed =- {- null,- JsonSerializer.SerializeToElement(new { }),- JsonSerializer.SerializeToElement(new { v = 1, r = "ok", targetId = 1, gen = 3 }),- JsonSerializer.SerializeToElement(new { v = 2, r = "ok" }),- JsonSerializer.SerializeToElement(new { v = 2, r = "ok", targetId = 1.5, gen = 3 }),- JsonSerializer.SerializeToElement(new { v = 2, r = "stale", gen = 3 }),- JsonSerializer.SerializeToElement(new { v = 2, r = "unknown", targetId = 1, gen = 3 }),- // identity without the world generation is not trustworthy- JsonSerializer.SerializeToElement(new { v = 2, r = "ok", targetId = 1 }),- JsonSerializer.SerializeToElement(new { v = 2, r = "stale", targetId = 1 }),- };- foreach (var value in malformed)- Assert.Equal(StealthStatus.EvaluationFailed, StealthDom.ParseResult(value).Status);- }-- // Runs the SHIPPED resolver JS (as produced by the C# builders) under Node against- // DOM stubs. Validates the verbatim-string transcription is byte-correct and the- // selector semantics (:has-text / unsupported / not-found) match the other wrappers.- // Skipped when node is not on PATH.- [Fact]- public void ResolverSemantics_RunUnderNode()- {- var node = FindNode();- if (node == null) return; // skip: node unavailable-- string boxHasText = StealthDom.BuildBoxJs("button:has-text('Submit') >> nth=0");- string boxUnsupported = StealthDom.BuildBoxJs("internal:role=button");- string boxNotFound = StealthDom.BuildBoxJs("button");- string ptrHit = StealthDom.BuildPointerJs("button", 5, 5);-- string script = @"-function el(tag, text){- const e = { tagName: tag, textContent: text || '', children: [] };- e.contains = o => o === e;- e.getBoundingClientRect = () => ({ x: 5, y: 6, width: 20, height: 10 });- e.getAttribute = () => null; e.hasAttribute = () => false; e.closest = () => null;- e.disabled = false; e.readOnly = false; e.isContentEditable = false; e.isConnected = true;- return e;-}-function run(js, matches, point){- const document = {- querySelectorAll: () => matches.slice(),- evaluate: () => ({ snapshotLength: matches.length, snapshotItem: i => matches[i] }),- elementFromPoint: () => point || null,- };- return new Function('document','XPathResult','getComputedStyle','return ' + js)(- document, { ORDERED_NODE_SNAPSHOT_TYPE: 7 }, () => ({ visibility: 'visible', display: 'block' }));-}-const b = " + JsStr(boxHasText) + @";-const u = " + JsStr(boxUnsupported) + @";-const nf = " + JsStr(boxNotFound) + @";-const p = " + JsStr(ptrHit) + @";-const btn = el('BUTTON','Submit');-console.log('HASTEXT', run(b, [btn, el('BUTTON','x')]).r);-console.log('UNSUPPORTED', run(u, []).r);-console.log('NOTFOUND', run(nf, []).r);-const t = el('BUTTON','x');-console.log('POINTER', JSON.stringify(run(p, [t], t)));-";-- string outp = RunNode(node, script);- Assert.Contains("HASTEXT ok", outp);- Assert.Contains("UNSUPPORTED unsupported", outp);- Assert.Contains("NOTFOUND not_found", outp);- Assert.Contains("POINTER", outp);- Assert.Contains("\"r\":\"ok\"", outp);- Assert.Contains("\"hit\":true", outp);- }-- [Fact]- public void DisplayContentsGeometry_RunUnderNode()- {- var node = FindNode();- if (node == null) return;-- string targetJs = StealthDom.BuildSnapshotJs(".target");- string unionJs = StealthDom.BuildSnapshotJs(".union");- string hiddenJs = StealthDom.BuildSnapshotJs(".hidden-text");- string script = @"-function rect(x,y,width,height){ return {x,y,width,height}; }-function el(tag,text,box,display,visibility){- const e={tagName:tag,nodeType:1,textContent:text||'',childNodes:[],children:[],firstChild:null,- parentElement:null,previousElementSibling:null,nextSibling:null,isConnected:true,disabled:false,- readOnly:false,isContentEditable:false,type:'text',value:'',checked:false,attrs:{},- style:{display:display||'block',visibility:visibility||'visible'},box:box};- if(text){const t={nodeType:3,nodeValue:text,textContent:text,nextSibling:null,box:box};e.childNodes.push(t);e.firstChild=t;}- e.getBoundingClientRect=()=>e.box;e.getAttribute=n=>e.attrs[n]||null;e.hasAttribute=n=>n in e.attrs;- e.closest=()=>null;e.contains=o=>o===e||e.children.some(c=>c.contains(o));e.getRootNode=()=>document;- return e;-}-function append(parent,child){const prev=parent.childNodes[parent.childNodes.length-1];if(prev)prev.nextSibling=child;- child.parentElement=parent;child.previousElementSibling=parent.children[parent.children.length-1]||null;- parent.children.push(child);parent.childNodes.push(child);parent.firstChild=parent.childNodes[0];}-function run(js,target){let selected=null;const document={children:[target],head:{contains:()=>false},activeElement:null,- querySelectorAll:()=>[target],evaluate:()=>({snapshotLength:0,snapshotItem:()=>null}),elementFromPoint:()=>null,- createRange:()=>({selectNode:n=>{selected=n;},getBoundingClientRect:()=>selected.box})};- function wire(n){n.ownerDocument=document;for(const child of n.childNodes||[])wire(child);}wire(target);- return new Function('document','XPathResult','getComputedStyle','globalThis','return '+js)(- document,{ORDERED_NODE_SNAPSHOT_TYPE:7},n=>n.style,{});-}-const target=el('LI','Hoy',rect(0,0,0,0),'contents');target.childNodes[0].box=rect(5,6,25,10);-const union=el('DIV','',rect(0,0,0,0),'contents');-const left=el('SPAN','left',rect(10,20,20,10));const right=el('SPAN','right',rect(40,20,30,10));-const nested=el('SPAN','',rect(0,0,0,0),'contents');append(nested,el('SPAN','nested',rect(75,20,25,10)));-const hidden=el('SPAN','hidden',rect(1000,1000,100,100),'block','hidden');-append(union,left);append(union,right);append(union,nested);append(union,hidden);-const hiddenText=el('DIV','hidden text',rect(0,0,0,0),'contents','hidden');hiddenText.childNodes[0].box=rect(5,6,50,10);-const t=run(" + JsStr(targetJs) + @",target);const u=run(" + JsStr(unionJs) + @",union);const h=run(" + JsStr(hiddenJs) + @",hiddenText);-console.log('TARGET',JSON.stringify({visible:t.visible,box:t.box}));-console.log('UNION',JSON.stringify({visible:u.visible,box:u.box}));-console.log('HIDDEN',JSON.stringify({visible:h.visible,box:h.box}));-";-- string outp = RunNode(node, script);- Assert.Contains("TARGET {\"visible\":true,\"box\":{\"x\":5,\"y\":6,\"width\":25,\"height\":10}}", outp);- Assert.Contains("UNION {\"visible\":true,\"box\":{\"x\":10,\"y\":20,\"width\":90,\"height\":10}}", outp);- Assert.Contains("HIDDEN {\"visible\":false,\"box\":null}", outp);- }-- private static string JsStr(string s) => JsonSerializer.Serialize(s);-- private static string? FindNode()- {- foreach (var p in new[] { "node", "/usr/local/bin/node", "/opt/homebrew/bin/node", "/usr/bin/node" })- {- try- {- var psi = new ProcessStartInfo(p, "--version") { RedirectStandardOutput = true, UseShellExecute = false };- using var proc = Process.Start(psi);- if (proc == null) continue;- proc.WaitForExit(5000);- if (proc.ExitCode == 0) return p;- }- catch { /* try next */ }- }- return null;- }-- private static string RunNode(string node, string script)- {- // The script inlines the resolver once per builder call, so it is well over- // 100 KB. Linux caps a single argv entry at MAX_ARG_STRLEN (128 KB) and- // "node -e <script>" hits E2BIG there, so hand node a file instead.- string scriptPath = Path.Combine(Path.GetTempPath(),- "cloakbrowser-resolver-" + Guid.NewGuid().ToString("N") + ".js");- File.WriteAllText(scriptPath, script);- try- {- var psi = new ProcessStartInfo(node)- {- RedirectStandardOutput = true,- RedirectStandardError = true,- UseShellExecute = false,- };- psi.ArgumentList.Add(scriptPath);- using var proc = Process.Start(psi)!;- string outp = proc.StandardOutput.ReadToEnd();- string err = proc.StandardError.ReadToEnd();- proc.WaitForExit(30000);- Assert.True(proc.ExitCode == 0, $"node failed:\n{outp}\n{err}");- return outp;- }- finally- {- try { File.Delete(scriptPath); } catch (IOException) { }- }- }-}diff --git a/dotnet/tests/CloakBrowser.Tests/Human/TimeoutBudgetTests.cs b/dotnet/tests/CloakBrowser.Tests/Human/TimeoutBudgetTests.csindex 483f3e1..4038baa 100644--- a/dotnet/tests/CloakBrowser.Tests/Human/TimeoutBudgetTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/Human/TimeoutBudgetTests.cs@@ -4,77 +4,47 @@ using Xunit;namespace CloakBrowser.Tests.Human;/// <summary>-/// Ports the spirit of Python <c>TestTimeoutBudget307</c> (issue #307): sequential-/// operations share one deadline so the overall timeout budget is never multiplied.-///-/// The full end-to-end timing test needs a real browser to drive the retry loops, so it-/// is marked <c>Skip</c>. What we CAN unit-test without a browser is the shared remaining-/// time helper every step uses (<see cref="Actionability.RemainingMs(double)"/>): given a-/// single deadline, it must never go negative and must monotonically shrink as time passes.+/// Issue #307: every step of one action (wait, scroll, move, hit-test, retry) carves out+/// of a single <see cref="Deadline"/>, so the timeout budget is never multiplied. The+/// end-to-end timing is checked against a real browser in HumanEngineBrowserTests; here+/// the deadline arithmetic itself./// </summary>public class TimeoutBudgetTests{[Fact]- public void RemainingMs_never_negative_past_deadline()+ public void Remaining_never_negative_after_expiry(){- double pastDeadline = System.Environment.TickCount64 - 1000; // already expired- Assert.Equal(0, Actionability.RemainingMs(pastDeadline));+ var d = new Deadline(1);+ Thread.Sleep(20);+ Assert.True(d.Expired);+ Assert.Equal(0, d.Remaining);}[Fact]- public void RemainingMs_at_deadline_is_zero()+ public async Task Remaining_shrinks_and_never_exceeds_the_budget(){- double now = System.Environment.TickCount64;- Assert.True(Actionability.RemainingMs(now) <= 0.0 + 1.0); // ~0 (clamped, never < 0)- Assert.True(Actionability.RemainingMs(now) >= 0.0);+ var d = new Deadline(1000);+ var first = d.Remaining;+ await Task.Delay(30);+ var second = d.Remaining;+ Assert.True(first <= 1000);+ Assert.True(second < first);+ Assert.False(d.Expired);}[Fact]- public void RemainingMs_positive_before_deadline()+ public void Zero_timeout_means_no_limit(){- double deadline = System.Environment.TickCount64 + 5000;- double remaining = Actionability.RemainingMs(deadline);- Assert.InRange(remaining, 1, 5000);+ var d = new Deadline(0);+ Assert.False(d.Expired);+ Assert.True(double.IsPositiveInfinity(d.Remaining));}[Fact]- public async Task RemainingMs_shrinks_as_time_passes()+ public void Nested_steps_share_the_parent_deadline(){- double deadline = System.Environment.TickCount64 + 5000;- double first = Actionability.RemainingMs(deadline);- await Task.Delay(60);- double second = Actionability.RemainingMs(deadline);-- Assert.True(second < first, $"remaining should shrink: {first} -> {second}");- Assert.True(second >= 0, "remaining must never go negative");- }-- [Fact]- public void RemainingMs_budget_is_shared_not_multiplied()- {- // Three sequential "steps" computed from a SINGLE deadline must sum to <= the- // original budget - they carve out of one budget rather than each getting the full- // timeout (the bug behind issue #307).- const double budget = 1000;- double deadline = System.Environment.TickCount64 + budget;-- double step1 = Actionability.RemainingMs(deadline);- double step2 = Actionability.RemainingMs(deadline);- double step3 = Actionability.RemainingMs(deadline);-- // Each subsequent read is <= the previous (time only moves forward) and never- // exceeds the single budget.- Assert.True(step1 <= budget + 1);- Assert.True(step2 <= step1 + 1);- Assert.True(step3 <= step2 + 1);- }-- [Fact(Skip = "requires browser: drives the full page.click retry loop to measure end-to-end timing")]- public void Page_click_total_time_within_budget()- {- // Python TestTimeoutBudget307.test_page_click_total_time_within_budget patches a- // live page and asserts the wall-clock click time stays < 1.8x the timeout. That- // exercises real Playwright locator waits and cannot be faithfully reproduced with- // DispatchProxy fakes, so it is covered by the browser-backed integration suite.+ var d = new Deadline(500);+ var nested = new ActOpts { Deadline = d }.With(o => o.Nested = true);+ Assert.Same(d, nested.Deadline);}}diff --git a/dotnet/tests/CloakBrowser.Tests/HumanEngine/ActionabilityApiTests.cs b/dotnet/tests/CloakBrowser.Tests/HumanEngine/ActionabilityApiTests.csnew file mode 100644index 0000000..47c1076--- /dev/null+++ b/dotnet/tests/CloakBrowser.Tests/HumanEngine/ActionabilityApiTests.cs@@ -0,0 +1,103 @@+using CloakBrowser.Human;+using Microsoft.Playwright;+using Xunit;++namespace CloakBrowser.Tests.HumanEngine;++/// <summary>The public <see cref="Actionability"/> API, kept for callers that use it+/// directly, now runs on the engine: typed errors, every Playwright selector.</summary>+[Collection("RealBrowser")]+public class ActionabilityApiTests : IClassFixture<EngineFixture>, IAsyncLifetime+{+ private readonly EngineFixture _f;+ private readonly List<IPage> _pages = new();+ public ActionabilityApiTests(EngineFixture f) => _f = f;++ public Task InitializeAsync() => Task.CompletedTask;+ public async Task DisposeAsync()+ {+ foreach (var p in _pages) { try { await p.CloseAsync(); } catch { } }+ }++ private async Task<IPage> Open(bool humanized)+ {+ var p = humanized ? await _f.Handle!.Browser.NewPageAsync() : await _f.Handle!.RawBrowser.NewPageAsync();+ _pages.Add(p);+ await p.GotoAsync(_f.Url + "index.html");+ return p;+ }++ private static async Task<(double X, double Y)> Center(IPage p, string sel)+ {+ var b = (await p.Locator(sel).BoundingBoxAsync())!;+ return (b.X + b.Width / 2, b.Y + b.Height / 2);+ }++ [BrowserTheory]+ [InlineData(true)]+ [InlineData(false)]+ public async Task Passes_and_accepts_engine_selectors(bool humanized)+ {+ var p = await Open(humanized);+ await Actionability.EnsureActionableAsync(p, "#btn", Actionability.ChecksClick, 2000);+ await Actionability.EnsureActionableAsync(p, "internal:role=button[name=\"Press me\"i]", Actionability.ChecksClick, 2000);+ await Actionability.EnsureActionableAsync(p, "#name", Actionability.ChecksInput, 2000);+ await Actionability.EnsureStableAsync(p, "#btn", 2000);+ var (x, y) = await Center(p, "#btn");+ await Actionability.CheckPointerEventsAsync(p, "#btn", x, y, 2000);+ }++ [BrowserFact]+ public async Task Typed_errors_for_missing_hidden_disabled_readonly()+ {+ var p = await Open(true);+ await p.Locator("#btn").EvaluateAsync("b => { b.insertAdjacentHTML('afterend', " ++ "'<button id=\"hid\" style=\"display:none\">h</button><button id=\"dis\" disabled>d</button><input id=\"ro\" readonly>'); }");+ await Assert.ThrowsAsync<ElementNotAttachedError>(() =>+ Actionability.EnsureActionableAsync(p, "#nope", Actionability.ChecksClick, 300));+ await Assert.ThrowsAsync<ElementNotVisibleError>(() =>+ Actionability.EnsureActionableAsync(p, "#hid", Actionability.ChecksClick, 300));+ await Assert.ThrowsAsync<ElementNotEnabledError>(() =>+ Actionability.EnsureActionableAsync(p, "#dis", Actionability.ChecksClick, 300));+ await Assert.ThrowsAsync<ElementNotEditableError>(() =>+ Actionability.EnsureActionableAsync(p, "#ro", Actionability.ChecksInput, 300));+ await Actionability.EnsureActionableAsync(p, "#dis", Actionability.ChecksClick, 300, force: true);+ }++ [BrowserFact]+ public async Task Covered_point_names_the_covering_element()+ {+ var p = await Open(true);+ await p.Locator("#covered").ScrollIntoViewIfNeededAsync();+ var (x, y) = await Center(p, "#covered");+ var e = await Assert.ThrowsAsync<ElementNotReceivingEventsError>(() =>+ Actionability.CheckPointerEventsAsync(p, "#covered", x, y, 300));+ Assert.Contains("over", e.Message);+ Assert.Equal("pointer_events", e.Check);+ }++ [BrowserFact]+ public async Task Element_handle_variants()+ {+ var p = await Open(true);+ var h = (await p.QuerySelectorAsync("#btn"))!;+ await Actionability.EnsureActionableHandleAsync(h, Actionability.ChecksClick, 2000);+ var (x, y) = await Center(p, "#btn");+ await Actionability.CheckPointerEventsHandleAsync(h, x, y, 2000);+ var c = (await p.QuerySelectorAsync("#covered"))!;+ await c.ScrollIntoViewIfNeededAsync();+ var (cx, cy) = await Center(p, "#covered");+ await Assert.ThrowsAsync<ElementNotReceivingEventsError>(() =>+ Actionability.CheckPointerEventsHandleAsync(c, cx, cy, 300));+ }++ [BrowserFact]+ public async Task Isolated_world_is_still_usable_directly()+ {+ var p = await Open(false);+ var w = new IsolatedWorld(p);+ Assert.True(await w.EvaluateBoolAsync("document.querySelector('#btn') !== null"));+ var v = await w.EvaluateAsync("document.title.length >= 0");+ Assert.True(v!.Value.GetBoolean());+ }+}diff --git a/dotnet/tests/CloakBrowser.Tests/HumanEngine/HumanEngineBrowserTests.cs b/dotnet/tests/CloakBrowser.Tests/HumanEngine/HumanEngineBrowserTests.csnew file mode 100644index 0000000..46cbd84--- /dev/null+++ b/dotnet/tests/CloakBrowser.Tests/HumanEngine/HumanEngineBrowserTests.cs@@ -0,0 +1,424 @@+using System.Diagnostics;+using System.Text.Json;+using CloakBrowser.Human;+using Microsoft.Playwright;+using Xunit;++namespace CloakBrowser.Tests.HumanEngine;++/// <summary>Real-browser launch + fixture site for the engine tests (runs whenever a+/// CloakBrowser binary is configured).</summary>+public sealed class EngineFixture : IAsyncLifetime+{+ public static bool Enabled => BrowserFactAttribute.Available;+ private readonly SiteServer _site = new();+ public string Url => _site.Url;+ public CloakBrowserHandle? Handle { get; private set; }++ public async Task InitializeAsync()+ {+ if (!Enabled) return;+ _site.Start();+ Handle = await CloakLauncher.LaunchAsync(new LaunchOptions { Headless = true, Humanize = true, HumanConfig = SiteServer.Fast });+ }++ public async Task DisposeAsync()+ {+ if (Handle != null) await Handle.DisposeAsync();+ _site.Stop();+ }+}++/// <summary>Port of <c>js/tests/humanizeEngine.test.ts</c> / <c>tests/test_humanize_engine.py</c>.</summary>+[Collection("RealBrowser")]+public class HumanEngineBrowserTests : IClassFixture<EngineFixture>, IAsyncLifetime+{+ private readonly EngineFixture _f;+ private readonly List<IPage> _pages = new();+ public HumanEngineBrowserTests(EngineFixture f) => _f = f;++ public Task InitializeAsync() => Task.CompletedTask;+ public async Task DisposeAsync()+ {+ foreach (var p in _pages) { try { await p.CloseAsync(); } catch { } }+ }++ private async Task<IPage> Open(string path = "index.html")+ {+ var p = await _f.Handle!.Browser.NewPageAsync();+ _pages.Add(p);+ await p.GotoAsync(_f.Url + path);+ return p;+ }++ private async Task<IPage> OpenWith(Dictionary<string, object> overrides)+ {+ var merged = new Dictionary<string, object>(SiteServer.Fast);+ foreach (var (k, v) in overrides) merged[k] = v;+ var ctx = CloakBrowser.Wrappers.Humanize.Context(await _f.Handle!.RawBrowser.NewContextAsync(),+ HumanConfigFactory.Resolve(HumanPreset.Default, merged));+ var p = await ctx.NewPageAsync();+ _pages.Add(p);+ await p.GotoAsync(_f.Url + "index.html");+ return p;+ }++ private static async Task<IFrame> FrameOf(IPage p)+ {+ var f = p.Frame("f")!;+ await f.WaitForLoadStateAsync();+ return f;+ }++ private static async Task<List<JsonElement>> Events(IFrame f, params string[] types)+ {+ var all = JsonSerializer.Deserialize<List<JsonElement>>(await f.EvaluateAsync<string>("JSON.stringify(window.__log)"))!;+ return types.Length == 0 ? all : all.Where(e => types.Contains(e.GetProperty("t").GetString())).ToList();+ }+ private static Task<List<JsonElement>> Events(IPage p, params string[] types) => Events(p.MainFrame, types);+ private static Task Reset(IFrame f) => f.EvaluateAsync("window.__reset(); window.__mainWorldHits.length = 0");+ private static Task Reset(IPage p) => Reset(p.MainFrame);+ private static Task<string> Value(IFrame f, string sel) => f.EvaluateAsync<string>("s => document.querySelector(s).value", sel);+ private static Task<string> Value(IPage p, string sel) => Value(p.MainFrame, sel);+ private static string Targets(IEnumerable<JsonElement> evs) => string.Join(",", evs.Select(e => e.GetProperty("target").GetString()));++ // --- wiring ------------------------------------------------------------++ [BrowserFact]+ public async Task Raw_page_in_the_same_process_is_untouched()+ {+ var p = await _f.Handle!.RawBrowser.NewPageAsync();+ _pages.Add(p);+ await p.GotoAsync(_f.Url + "index.html");+ await Reset(p);+ await p.ClickAsync("#btn");+ await p.FillAsync("#name", "plain");+ Assert.Equal("plain", await Value(p, "#name"));+ Assert.True((await Events(p, "mousemove")).Count < 3, "stock Playwright teleports the mouse");+ }++ [BrowserFact]+ public async Task Humanized_actions_leave_no_side_effects_in_the_page()+ {+ var p = await _f.Handle!.Browser.NewPageAsync();+ _pages.Add(p);+ await p.AddInitScriptAsync(@"(() => {+ const add = EventTarget.prototype.addEventListener;+ const d = window.__engine = { listeners: 0, mutations: 0 };+ EventTarget.prototype.addEventListener = function (t, f, o) {+ if (this === window || this === document) d.listeners++;+ return add.call(this, t, f, o);+ };+ new MutationObserver((m) => { d.mutations += m.length; })+ .observe(document, { subtree: true, childList: true, attributes: true });+ })()");+ await p.GotoAsync(_f.Url + "index.html?nolog");+ var handle = (await p.QuerySelectorAsync("#btn"))!;+ await p.EvaluateAsync("() => { const d = window.__engine; d.listeners = 0; d.mutations = 0; }");+ await p.GetByRole(AriaRole.Button, new() { Name = "Press me" }).ClickAsync();+ await p.Locator("#buttons >> #btn").HoverAsync();+ await handle.ClickAsync();+ await p.FrameLocator("#frame").Locator("#finput").ClickAsync();+ var strict = await Assert.ThrowsAnyAsync<Exception>(() => p.Locator(".dup").ClickAsync(new() { Timeout = 500 }));+ Assert.Contains("strict mode", strict.Message);+ var seen = await p.EvaluateAsync<string>("JSON.stringify(window.__engine)");+ Assert.Equal("{\"listeners\":0,\"mutations\":0}", seen);+ }++ // --- pointer -----------------------------------------------------------++ [BrowserFact]+ public async Task Click_moves_along_a_curve_then_presses()+ {+ var p = await Open();+ await Reset(p);+ await p.ClickAsync("#btn");+ Assert.True((await Events(p, "mousemove")).Count >= 3);+ Assert.Equal("btn", Targets(await Events(p, "click")));+ }++ [BrowserFact]+ public async Task Click_options_are_honoured()+ {+ var p = await Open();+ await Reset(p);+ await p.ClickAsync("#btn", new() { Button = MouseButton.Right, Modifiers = new[] { KeyboardModifier.Shift } });+ var down = (await Events(p, "mousedown")).Last();+ Assert.Equal(2, down.GetProperty("button").GetInt32());+ Assert.True(down.GetProperty("shift").GetBoolean());+ await Reset(p);+ await p.ClickAsync("#btn", new() { ClickCount = 2 });+ Assert.Single(await Events(p, "dblclick"));+ await Reset(p);+ await p.ClickAsync("#btn", new() { Trial = true });+ Assert.Empty(await Events(p, "click"));+ }++ [BrowserFact]+ public async Task Hover_does_not_press_and_dblclick_is_a_real_double_click()+ {+ var p = await Open();+ await Reset(p);+ await p.HoverAsync("#btn");+ Assert.Empty(await Events(p, "mousedown"));+ await Reset(p);+ await p.DblClickAsync("#btn");+ var seq = string.Join(" ", (await Events(p, "mousedown", "click", "dblclick"))+ .Select(e => $"{e.GetProperty("t").GetString()}:{e.GetProperty("detail").GetInt32()}"));+ Assert.Equal("mousedown:1 click:1 mousedown:2 click:2 dblclick:2", seq);+ }++ [BrowserFact]+ public async Task Hover_holds_modifiers_while_the_mouse_moves()+ {+ var p = await Open();+ await p.HoverAsync("#chk");+ await Reset(p);+ await p.HoverAsync("#btn", new() { Modifiers = new[] { KeyboardModifier.Shift } });+ var seq = await Events(p, "mousemove", "keydown", "keyup");+ var moves = seq.Where(e => e.GetProperty("t").GetString() == "mousemove").ToList();+ Assert.NotEmpty(moves);+ Assert.All(moves, e => Assert.True(e.GetProperty("shift").GetBoolean()));+ Assert.Equal("keydown", seq[0].GetProperty("t").GetString());+ Assert.Equal("keyup", seq[^1].GetProperty("t").GetString());+ Assert.Empty(await Events(p, "mousedown"));+ }++ [BrowserFact]+ public async Task Covered_element_times_out_with_the_reason()+ {+ var p = await Open();+ var err = await Assert.ThrowsAsync<TimeoutException>(() => p.ClickAsync("#covered", new() { Timeout = 1000 }));+ Assert.Contains("intercepts pointer events", err.Message);+ }++ [BrowserFact]+ public async Task Strict_mode_violation_and_first()+ {+ var p = await Open();+ var err = await Assert.ThrowsAnyAsync<PlaywrightException>(() => p.Locator(".dup").ClickAsync(new() { Timeout = 1000 }));+ Assert.Contains("strict mode violation", err.Message);+ await p.Locator(".dup").First.ClickAsync();+ }++ [BrowserFact]+ public async Task Page_default_timeout_and_timeout_zero()+ {+ var p = await Open();+ p.SetDefaultTimeout(500);+ var sw = Stopwatch.StartNew();+ await Assert.ThrowsAsync<TimeoutException>(() => p.ClickAsync("#missing"));+ Assert.True(sw.ElapsedMilliseconds < 1500, $"took {sw.ElapsedMilliseconds} ms");+ await p.ClickAsync("#btn", new() { Timeout = 0 });+ }++ [BrowserFact]+ public async Task Standard_locators()+ {+ var p = await Open();+ await p.GetByRole(AriaRole.Button, new() { Name = "Press me" }).ClickAsync();+ await p.Locator("#buttons").Locator("#btn").ClickAsync();+ await p.Locator("button").Filter(new() { HasText = "Press me" }).ClickAsync();+ await p.ClickAsync("#btn:visible");+ }++ // --- keyboard ----------------------------------------------------------++ [BrowserFact]+ public async Task Fill_replaces_press_sequentially_appends_clear_empties()+ {+ var p = await Open();+ await p.FillAsync("#name", "Shaho");+ Assert.Equal("Shaho", await Value(p, "#name"));+ await p.Locator("#name").PressSequentiallyAsync("!");+ Assert.Equal("Shaho!", await Value(p, "#name"));+ await p.Locator("#name").ClearAsync();+ Assert.Equal("", await Value(p, "#name"));+ }++ [BrowserFact]+ public async Task Value_inputs_are_operated_like_a_person()+ {+ var p = await Open();+ await p.EvaluateAsync(@"() => { window.__untrusted = 0;+ for (const t of ['input', 'change'])+ document.addEventListener(t, (e) => { if (!e.isTrusted) window.__untrusted++; }, true); }");+ await p.FillAsync("#date", "2024-01-31");+ await p.FillAsync("#date", "1999-12-05");+ await p.FillAsync("#range", "80");+ Assert.Equal(new[] { "b" }, await p.SelectOptionAsync("#sel", "b"));+ Assert.Equal("1999-12-05", await Value(p, "#date"));+ Assert.Equal("80", await Value(p, "#range"));+ Assert.Equal("b", await Value(p, "#sel"));+ Assert.Equal(0, await p.EvaluateAsync<int>("window.__untrusted"));+ Assert.Contains("native colour picker", (await Assert.ThrowsAnyAsync<PlaywrightException>(() => p.FillAsync("#color", "#ff0000"))).Message);+ Assert.Contains("cannot be filled", (await Assert.ThrowsAnyAsync<PlaywrightException>(() => p.FillAsync("#chk", "x"))).Message);+ }++ [BrowserFact]+ public async Task Unreachable_element_is_not_focused_programmatically()+ {+ var p = await Open();+ var err = await Assert.ThrowsAsync<TimeoutException>(() => p.FillAsync("#neg", "x", new() { Timeout = 1500 }));+ Assert.Contains("outside of the viewport", err.Message);+ Assert.Equal("", await Value(p, "#neg"));+ }++ [BrowserFact]+ public async Task Press_focuses_its_target_first_and_forwards_delay()+ {+ var p = await Open();+ await p.FocusAsync("#fa");+ await (await p.QuerySelectorAsync("#fb"))!.PressAsync("x");+ Assert.Equal("", await Value(p, "#fa"));+ Assert.Equal("x", await Value(p, "#fb"));+ await Reset(p);+ await p.PressAsync("#name", "a", new() { Delay = 150 });+ var ev = await Events(p, "keydown", "keyup");+ Assert.True(ev[^1].GetProperty("ts").GetDouble() - ev[^2].GetProperty("ts").GetDouble() >= 120);+ }++ [BrowserFact]+ public async Task Press_and_type_reach_non_focusable_targets()+ {+ var p = await Open();+ await p.EvaluateAsync("() => { window.__keys = []; document.addEventListener('keydown', e => window.__keys.push(e.key)); }");+ await p.PressAsync("#cv", "ArrowUp");+ await p.Locator("#cv").PressSequentiallyAsync("ab");+ Assert.Equal("[\"ArrowUp\",\"a\",\"b\"]", await p.EvaluateAsync<string>("JSON.stringify(window.__keys)"));+ }++ [BrowserFact]+ public async Task Mistypes_are_corrected_skip_masked_fields_and_use_shift()+ {+ var p = await OpenWith(new() { ["mistype_chance"] = 1.0 });+ await p.FillAsync("#name", "Hello");+ Assert.Equal("Hello", await Value(p, "#name"));+ await p.FillAsync("#hex", "ab");+ Assert.Equal("ab", await Value(p, "#hex"));+ await Reset(p);+ await p.Locator("#name").PressSequentiallyAsync("AB");+ var bad = (await Events(p, "keydown")).Where(e => e.GetProperty("key").GetString() is { Length: 1 } k+ && k[0] is >= 'A' and <= 'Z' && !e.GetProperty("shift").GetBoolean());+ Assert.Empty(bad);+ }++ [BrowserFact]+ public async Task Scroll_overshoot_wheels_past_the_target_and_back()+ {+ var p = await OpenWith(new() { ["scroll_overshoot_chance"] = 1.0, ["scroll_overshoot_px"] = new[] { 120.0, 120.0 } });+ await p.SetViewportSizeAsync(800, 300);+ await Reset(p);+ await p.ClickAsync("#chk");+ var dys = (await Events(p, "wheel")).Select(e => e.GetProperty("dy").GetDouble()).ToList();+ Assert.True(dys.Any(d => d > 0) && dys.Any(d => d < 0), string.Join(",", dys));+ Assert.Equal(new[] { "chk" }, (await Events(p, "click")).Select(e => e.GetProperty("target").GetString()));+ }++ [BrowserFact]+ public async Task Per_call_human_config_through_HumanPage()+ {+ var raw = await _f.Handle!.RawBrowser.NewPageAsync();+ _pages.Add(raw);+ await raw.GotoAsync(_f.Url + "index.html");+ var hp = await HumanPage.CreateAsync(raw, HumanConfigFactory.Resolve(HumanPreset.Default, SiteServer.Fast));+ await Reset(raw);+ await hp.ClickAsync("#btn", new() { HumanConfig = new Dictionary<string, object> { ["click_hold_button"] = new[] { 300.0, 300.0 } } });+ var up = (await Events(raw, "mouseup")).Last().GetProperty("ts").GetDouble();+ var down = (await Events(raw, "mousedown")).Last().GetProperty("ts").GetDouble();+ Assert.True(up - down >= 250, $"held {up - down} ms");+ await hp.FillAsync("#name", "explicit");+ Assert.Equal("explicit", await Value(raw, "#name"));+ Assert.True(raw is not CloakBrowser.Wrappers.HumanizedPage);+ }++ // --- checkable / select ------------------------------------------------++ [BrowserFact]+ public async Task Check_uncheck_set_checked_select_by_index()+ {+ var p = await Open();+ await p.CheckAsync("#chk");+ Assert.True(await p.IsCheckedAsync("#chk"));+ await p.Locator("#chk").UncheckAsync();+ Assert.False(await p.IsCheckedAsync("#chk"));+ await (await p.QuerySelectorAsync("#chk"))!.SetCheckedAsync(true);+ Assert.True(await p.IsCheckedAsync("#chk"));+ Assert.Equal(new[] { "b" }, await p.SelectOptionAsync("#sel", new SelectOptionValue { Index = 1 }));+ }++ // --- frames / handles --------------------------------------------------++ [BrowserFact]+ public async Task Frame_actions()+ {+ var p = await Open();+ var f = await FrameOf(p);+ await f.FillAsync("#finput", "in frame");+ Assert.Equal("in frame", await Value(f, "#finput"));+ await p.FrameLocator("#frame").Locator("#finput").PressSequentiallyAsync("!");+ Assert.Equal("in frame!", await Value(f, "#finput"));+ await Reset(f);+ await f.ClickAsync("#fbottom", new() { Timeout = 5000 });+ Assert.Equal("fbottom", Targets(await Events(f, "click")));+ var err = await Assert.ThrowsAsync<TimeoutException>(() => f.ClickAsync("#fcovered", new() { Timeout = 4000 }));+ Assert.Contains("intercepts pointer events", err.Message);+ }++ [BrowserFact]+ public async Task Element_handle_actions()+ {+ var p = await Open();+ await (await p.QuerySelectorAsync("#name"))!.FillAsync("handle");+ Assert.Equal("handle", await Value(p, "#name"));+ await Reset(p);+ await (await p.QuerySelectorAsync("#btn"))!.ClickAsync();+ Assert.Equal("btn", Targets(await Events(p, "click")));+ }++ [BrowserFact]+ public async Task Stale_handle_after_navigation_throws_instead_of_clicking_the_new_page()+ {+ var p = await Open();+ var h = (await p.QuerySelectorAsync("#btn"))!;+ await h.ClickAsync(); // caches the handle's element id (the first id of this world)+ await p.GotoAsync(_f.Url + "index.html?second");+ // Fill the new document's world so an element there gets the same id again.+ await p.ClickAsync("#chk");+ await Reset(p);+ var sw = System.Diagnostics.Stopwatch.StartNew();+ var e = await Assert.ThrowsAnyAsync<Exception>(() => h.ClickAsync(new() { Timeout = 10000 }));+ Assert.Contains("not attached", e.Message);+ Assert.True(sw.ElapsedMilliseconds < 5000, $"took {sw.ElapsedMilliseconds} ms: should fail fast, not wait for the timeout");+ Assert.Equal("", Targets(await Events(p, "click")));+ }++ [BrowserFact]+ public async Task Mouse_api()+ {+ var p = await Open();+ await Reset(p);+ await p.Mouse.MoveAsync(50, 50, new() { Steps = 1 });+ Assert.Single(await Events(p, "mousemove"));+ var box = (await p.Locator("#btn").BoundingBoxAsync())!;+ await Reset(p);+ await p.Mouse.ClickAsync(box.X + 5, box.Y + 5, new() { Button = MouseButton.Right });+ Assert.Equal(new[] { 2 }, (await Events(p, "mousedown")).Select(e => e.GetProperty("button").GetInt32()));+ }++ [BrowserFact]+ public async Task Select_all_follows_the_persona()+ {+ await using var mac = await CloakLauncher.LaunchAsync(new LaunchOptions+ {+ Headless = true, Humanize = true, HumanConfig = SiteServer.Fast,+ Args = new List<string> { "--fingerprint-platform=macos" },+ });+ var p = await mac.Browser.NewPageAsync();+ await p.GotoAsync(_f.Url + "index.html");+ Assert.Equal("MacIntel", await p.EvaluateAsync<string>("navigator.platform"));+ await p.FillAsync("#name", "old");+ await p.FillAsync("#name", "Mac");+ Assert.Equal("Mac", await Value(p, "#name"));+ }+}diff --git a/dotnet/tests/CloakBrowser.Tests/HumanEngine/SiteServer.cs b/dotnet/tests/CloakBrowser.Tests/HumanEngine/SiteServer.csnew file mode 100644index 0000000..28ff252--- /dev/null+++ b/dotnet/tests/CloakBrowser.Tests/HumanEngine/SiteServer.cs@@ -0,0 +1,304 @@+using System.Net;++namespace CloakBrowser.Tests.HumanEngine;++/// <summary>Serves the humanize test page (input-event recorder, main-world probes,+/// a same-origin iframe) on a random localhost port. Same page as the Python and JS tests.</summary>+public sealed class SiteServer+{+ /// <summary>Fast, deterministic humanize settings: same code paths, no long sleeps, no typos.</summary>+ public static readonly Dictionary<string, object> Fast = new()+ {+ ["mistype_chance"] = 0.0,+ ["field_switch_delay"] = new[] { 0.0, 0.0 },+ ["typing_delay"] = 5.0,+ ["typing_delay_spread"] = 0.0,+ ["typing_pause_chance"] = 0.0,+ ["key_hold"] = new[] { 5.0, 5.0 },+ ["shift_down_delay"] = new[] { 5.0, 5.0 },+ ["shift_up_delay"] = new[] { 5.0, 5.0 },+ ["mouse_min_steps"] = 4,+ ["mouse_max_steps"] = 4,+ ["mouse_burst_pause"] = new[] { 0.0, 0.0 },+ ["mouse_overshoot_chance"] = 0.0,+ ["click_aim_delay_input"] = new[] { 5.0, 5.0 },+ ["click_aim_delay_button"] = new[] { 5.0, 5.0 },+ ["click_hold_input"] = new[] { 20.0, 20.0 },+ ["click_hold_button"] = new[] { 20.0, 20.0 },+ ["idle_between_actions"] = false,+ ["scroll_pause_fast"] = new[] { 5.0, 5.0 },+ ["scroll_pause_slow"] = new[] { 5.0, 5.0 },+ ["scroll_settle_delay"] = new[] { 50.0, 50.0 },+ ["scroll_pre_move_delay"] = new[] { 5.0, 5.0 },+ ["scroll_overshoot_chance"] = 0.0,+ };++ private HttpListener? _listener;+ public string Url { get; private set; } = "";++ private const string IndexHtml = """+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<title>humanize fixture</title>+<script>+// Records DOM reads that only a main-world evaluate makes into window.__mainWorldHits.+(function () {+ const hits = [];+ window.__mainWorldHits = hits;+ const note = (probe, detail) => hits.push({ probe, detail: String(detail ?? '') });++ const origGetAttribute = Element.prototype.getAttribute;+ Element.prototype.getAttribute = function (name) {+ if (name === 'contenteditable') note('getAttribute(contenteditable)', this.id || this.tagName);+ return origGetAttribute.call(this, name);+ };++ const activeDesc = Object.getOwnPropertyDescriptor(Document.prototype, 'activeElement');+ Object.defineProperty(Document.prototype, 'activeElement', {+ configurable: true,+ get() {+ note('document.activeElement', '');+ return activeDesc.get.call(this);+ },+ });++ const origFromPoint = Document.prototype.elementFromPoint;+ Document.prototype.elementFromPoint = function (x, y) {+ note('elementFromPoint', x + ',' + y);+ return origFromPoint.call(this, x, y);+ };++ const origQS = Document.prototype.querySelector;+ Document.prototype.querySelector = function (sel) {+ note('document.querySelector', sel);+ return origQS.call(this, sel);+ };+})();+</script>+<script>+// Records every input event (capture phase) into window.__log.+(function () {+ const log = [];+ window.__log = log;+ window.__reset = () => { log.length = 0; };++ const TYPES = [+ 'pointerdown', 'pointerup', 'mousedown', 'mouseup', 'click', 'dblclick',+ 'contextmenu', 'auxclick', 'mousemove', 'keydown', 'keyup', 'beforeinput',+ 'input', 'wheel', 'focus',+ ];+ const idOf = (el) => {+ if (el === window) return 'window';+ if (!el || el === document) return 'document';+ return el.id || (el.tagName ? el.tagName.toLowerCase() : '?');+ };+ for (const type of TYPES) {+ document.addEventListener(type, (e) => {+ const rec = { t: type, ts: e.timeStamp, trusted: e.isTrusted, target: idOf(e.target) };+ if ('clientX' in e) { rec.x = e.clientX; rec.y = e.clientY; }+ if ('button' in e) rec.button = e.button;+ if ('detail' in e && type !== 'focus') rec.detail = e.detail;+ if ('key' in e) { rec.key = e.key; rec.code = e.code; }+ if ('shiftKey' in e) {+ rec.shift = e.shiftKey; rec.ctrl = e.ctrlKey; rec.meta = e.metaKey; rec.alt = e.altKey;+ }+ if ('inputType' in e) { rec.inputType = e.inputType; rec.data = e.data; }+ if (type === 'wheel') { rec.dx = e.deltaX; rec.dy = e.deltaY; }+ log.push(rec);+ }, true);+ }+ window.addEventListener('scroll', () => {+ log.push({ t: 'scroll', ts: performance.now(), sx: scrollX, sy: scrollY });+ }, true);++})();+</script>+<style>+ body { margin: 0; font: 14px sans-serif; }+ section { padding: 8px 12px; border-bottom: 1px solid #ddd; }+ input, select, button, textarea { font: inherit; margin: 2px 6px 2px 0; }+ button { min-width: 140px; min-height: 36px; }+ #neg { position: absolute; top: -600px; left: -600px; }+ .wrap { position: relative; display: inline-block; }+ .over { position: absolute; inset: 0; background: rgba(255,0,0,.3); }+</style>+</head>+<body>+<section id="text">+ <h4>Text inputs</h4>+ <input id="name" value="firstname">+ <input id="long" value="hello world">+ <!-- Masked field: the page strips anything that is not hex (card/IBAN/serial-style mask). -->+ <input id="hex" oninput="this.value=this.value.replace(/[^0-9a-f]/gi,'')">+ <textarea id="ta">old text</textarea>+</section>+<section id="special">+ <h4>Non-text inputs</h4>+ <input id="date" type="date">+ <input id="range" type="range" min="0" max="100" value="10">+ <input id="color" type="color" value="#000000">+</section>+<section id="focus">+ <h4>Focus targets</h4>+ <input id="fa" placeholder="A (focused first)">+ <input id="fb" placeholder="B (handle target)">+</section>+<section id="buttons">+ <h4>Buttons</h4>+ <button id="btn">Press me</button>+ <button class="dup" id="dup1">Duplicate</button>+ <button class="dup" id="dup2">Duplicate</button>+ <input id="chk" type="checkbox">+ <select id="sel"><option value="a">a</option><option value="b">b</option></select>+</section>+<section id="covered-sec">+ <h4>Covered button (transparent overlay on top)</h4>+ <span class="wrap"><button id="covered">covered</button><div class="over" id="over"></div></span>+</section>+<input id="neg" name="neg">+<canvas id="cv" width="200" height="40" style="border:1px solid #999"></canvas>+<section id="frames">+ <h4>Frame</h4>+ <iframe id="frame" name="f" src="frame.html" style="width:420px;height:200px"></iframe>+</section>+<div style="height:200px"></div>+</body>+</html>+""";++ private const string FrameHtml = """+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<script>+// Records DOM reads that only a main-world evaluate makes into window.__mainWorldHits.+(function () {+ const hits = [];+ window.__mainWorldHits = hits;+ const note = (probe, detail) => hits.push({ probe, detail: String(detail ?? '') });++ const origGetAttribute = Element.prototype.getAttribute;+ Element.prototype.getAttribute = function (name) {+ if (name === 'contenteditable') note('getAttribute(contenteditable)', this.id || this.tagName);+ return origGetAttribute.call(this, name);+ };++ const activeDesc = Object.getOwnPropertyDescriptor(Document.prototype, 'activeElement');+ Object.defineProperty(Document.prototype, 'activeElement', {+ configurable: true,+ get() {+ note('document.activeElement', '');+ return activeDesc.get.call(this);+ },+ });++ const origFromPoint = Document.prototype.elementFromPoint;+ Document.prototype.elementFromPoint = function (x, y) {+ note('elementFromPoint', x + ',' + y);+ return origFromPoint.call(this, x, y);+ };++ const origQS = Document.prototype.querySelector;+ Document.prototype.querySelector = function (sel) {+ note('document.querySelector', sel);+ return origQS.call(this, sel);+ };+})();+</script>+<script>+// Records every input event (capture phase) into window.__log.+(function () {+ const log = [];+ window.__log = log;+ window.__reset = () => { log.length = 0; };++ const TYPES = [+ 'pointerdown', 'pointerup', 'mousedown', 'mouseup', 'click', 'dblclick',+ 'contextmenu', 'auxclick', 'mousemove', 'keydown', 'keyup', 'beforeinput',+ 'input', 'wheel', 'focus',+ ];+ const idOf = (el) => {+ if (el === window) return 'window';+ if (!el || el === document) return 'document';+ return el.id || (el.tagName ? el.tagName.toLowerCase() : '?');+ };+ for (const type of TYPES) {+ document.addEventListener(type, (e) => {+ const rec = { t: type, ts: e.timeStamp, trusted: e.isTrusted, target: idOf(e.target) };+ if ('clientX' in e) { rec.x = e.clientX; rec.y = e.clientY; }+ if ('button' in e) rec.button = e.button;+ if ('detail' in e && type !== 'focus') rec.detail = e.detail;+ if ('key' in e) { rec.key = e.key; rec.code = e.code; }+ if ('shiftKey' in e) {+ rec.shift = e.shiftKey; rec.ctrl = e.ctrlKey; rec.meta = e.metaKey; rec.alt = e.altKey;+ }+ if ('inputType' in e) { rec.inputType = e.inputType; rec.data = e.data; }+ if (type === 'wheel') { rec.dx = e.deltaX; rec.dy = e.deltaY; }+ log.push(rec);+ }, true);+ }+ window.addEventListener('scroll', () => {+ log.push({ t: 'scroll', ts: performance.now(), sx: scrollX, sy: scrollY });+ }, true);++})();+</script>+<style>+ body { margin: 0; font: 14px sans-serif; }+ .wrap { position: relative; display: inline-block; }+ .over { position: absolute; inset: 0; background: rgba(255,0,0,.3); }+</style>+</head>+<body>+<input id="finput" value="old">+<span class="wrap"><button id="fcovered">covered</button><div class="over" id="fover"></div></span>+<div style="height:1200px"></div>+<button id="fbottom">bottom</button>+</body>+</html>+""";++ public void Start()+ {+ for (var attempt = 0; ; attempt++)+ {+ var port = Random.Shared.Next(20000, 60000);+ _listener = new HttpListener();+ _listener.Prefixes.Add($"http://127.0.0.1:{port}/");+ try { _listener.Start(); Url = $"http://127.0.0.1:{port}/"; break; }+ catch (HttpListenerException) when (attempt < 5) { }+ }+ var listener = _listener;+ _ = Task.Run(async () =>+ {+ while (listener.IsListening)+ {+ HttpListenerContext ctx;+ try { ctx = await listener.GetContextAsync(); } catch { return; }+ var html = ctx.Request.Url!.AbsolutePath switch+ {+ "/" or "/index.html" => IndexHtml,+ "/frame.html" => FrameHtml,+ _ => null,+ };+ if (html == null) { ctx.Response.StatusCode = 404; ctx.Response.Close(); continue; }+ ctx.Response.ContentType = "text/html; charset=utf-8";+ var bytes = System.Text.Encoding.UTF8.GetBytes(html);+ await ctx.Response.OutputStream.WriteAsync(bytes);+ ctx.Response.Close();+ }+ });+ }++ public void Stop() => _listener?.Stop();+}++/// <summary>Real-browser tests share one xunit collection, so they never drive two+/// browsers at once (that starves small CI machines and turns+/// timeouts into flakes). Combined with <c>DisableParallelization</c> it also never+/// overlaps other collections.</summary>+[Xunit.CollectionDefinition("RealBrowser", DisableParallelization = true)]+public sealed class RealBrowserCollection { }diff --git a/dotnet/tests/CloakBrowser.Tests/HumanEngine/WorldSmokeTests.cs b/dotnet/tests/CloakBrowser.Tests/HumanEngine/WorldSmokeTests.csnew file mode 100644index 0000000..e695dcc--- /dev/null+++ b/dotnet/tests/CloakBrowser.Tests/HumanEngine/WorldSmokeTests.cs@@ -0,0 +1,39 @@+using CloakBrowser.Human;+using Microsoft.Playwright;+using Xunit;++namespace CloakBrowser.Tests.HumanEngine;++/// <summary>The isolated world installs Playwright's InjectedScript and resolves+/// standard selectors with strict mode, without touching the page.</summary>+[Collection("RealBrowser")]+public class WorldSmokeTests+{+ [Fact]+ public void Injected_source_is_found_in_the_driver_package()+ {+ var lit = InjectedSource.FindLiteral();+ Assert.True(lit.Length > 10_000);+ Assert.Contains("InjectedScript", lit);+ }++ [BrowserFact]+ public async Task World_resolves_selectors_and_reports_strict_mode()+ {+ await using var handle = await CloakLauncher.LaunchAsync(new LaunchOptions { Headless = true });+ var page = await handle.RawBrowser.NewPageAsync();+ await page.EvaluateAsync(@"() => { document.body.innerHTML =+ '<div id=wrap><button id=b>Press me</button></div><i class=d>1</i><i class=d>2</i>';+ window.__calls = 0; const q = Document.prototype.querySelectorAll;+ Document.prototype.querySelectorAll = function (...a) { window.__calls++; return q.apply(this, a); }; }");+ var world = new HumanWorld(page);+ var r = (await world.CallAsync(page.MainFrame, "resolve", "internal:role=button[name=\"Press me\"i]", true, 0))!.Value;+ Assert.Equal("ok", r.GetProperty("status").GetString());+ var chain = (await world.CallAsync(page.MainFrame, "resolve", "#wrap >> #b", true, 0))!.Value;+ Assert.Equal("ok", chain.GetProperty("status").GetString());+ var strict = (await world.CallAsync(page.MainFrame, "resolve", ".d", true, 0))!.Value;+ Assert.Equal("strict", strict.GetProperty("status").GetString());+ Assert.StartsWith("strict mode violation", strict.GetProperty("message").GetString());+ Assert.Equal(0, await page.EvaluateAsync<int>("window.__calls"));+ }+}diff --git a/dotnet/tests/CloakBrowser.Tests/MiscTests.cs b/dotnet/tests/CloakBrowser.Tests/MiscTests.csindex fc55a06..fc30af2 100644--- a/dotnet/tests/CloakBrowser.Tests/MiscTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/MiscTests.cs@@ -177,19 +177,6 @@ public class KeyboardTestspublic class ActionabilityTests{- [Fact]- public void CheckSets_Match_Python()- {- Assert.Equal(new HashSet<string> { "attached", "visible", "enabled", "pointer_events" },- new HashSet<string>(Actionability.ChecksClick));- Assert.Equal(new HashSet<string> { "attached", "visible", "pointer_events" },- new HashSet<string>(Actionability.ChecksHover));- Assert.Equal(new HashSet<string> { "attached", "visible", "enabled", "editable", "pointer_events" },- new HashSet<string>(Actionability.ChecksInput));- Assert.Equal(new HashSet<string> { "attached", "visible", "enabled" },- new HashSet<string>(Actionability.ChecksFocus));- }-[Fact]public void ErrorHierarchy_AllSubclassActionabilityError(){diff --git a/dotnet/tests/CloakBrowser.Tests/ScrollFallbackTests.cs b/dotnet/tests/CloakBrowser.Tests/ScrollFallbackTests.csindex 5a64241..98393ca 100644--- a/dotnet/tests/CloakBrowser.Tests/ScrollFallbackTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/ScrollFallbackTests.cs@@ -191,6 +191,26 @@ public class ScrollFallbackTests});}+ [Fact]+ public async Task Smooth_wheel_never_sends_a_zero_step()+ {+ // A smooth wheel is split into 20-40px chunks and the last one is the+ // remainder. A remainder under 0.5px used to round to a (0, 0) wheel event,+ // which made Box_past_right_edge_scrolls_x_axis_only flaky (~1 run in 60).+ // A 21-40px delta is one or two chunks and leaves such a remainder a few+ // percent of the time, so 300 calls hit it with near certainty.+ var mouse = new CountingMouse();+ double total = 0;+ for (int i = 0; i < 300; i++)+ {+ int delta = 21 + i % 20;+ total += delta;+ await HumanScroll.SmoothWheelAsync(mouse, 0, delta, FastConfig());+ }+ Assert.DoesNotContain(mouse.Wheels, w => w.Dx == 0 && w.Dy == 0);+ Assert.Equal(total, mouse.Wheels.Sum(w => w.Dy));+ }+[Fact]public async Task Box_past_right_edge_with_page_pinned_right_bails_without_scrolling(){@@ -207,10 +227,10 @@ public class ScrollFallbackTests[Fact]public async Task Rtl_page_at_start_scrolls_x_axis_left(){- // RTL page at its start: scrollX 0 with a range of -600..0. The element- // sits in the left overflow, so the page is not pinned in that direction.- var scroll = PlaywrightScrollPage.ParseScrollState(System.Text.Json.JsonDocument.Parse(- """{"y":0,"maxY":0,"x":0,"minX":-600,"maxX":0}""").RootElement);+ // RTL page at its start: scrollX 0 with a range of -600..0, which an+ // IRawScrollPage reports measured from the leftmost position (X = 600 of 0..600).+ // The element sits in the left overflow, so the page is not pinned that way.+ (double, double, double, double) scroll = (0, 0, 600, 600);var page = new ViewportPage((1000, 700), scroll);var mouse = new CountingMouse();var boxes = new Queue<BoundingBox?>(new BoundingBox?[]diff --git a/dotnet/tests/CloakBrowser.Tests/Wrappers/FocusCheckTests.cs b/dotnet/tests/CloakBrowser.Tests/Wrappers/FocusCheckTests.csdeleted file mode 100644index 9503ef4..0000000--- a/dotnet/tests/CloakBrowser.Tests/Wrappers/FocusCheckTests.cs+++ /dev/null@@ -1,117 +0,0 @@-using CloakBrowser.Human;-using CloakBrowser.Wrappers;-using Microsoft.Playwright;-using Xunit;--namespace CloakBrowser.Tests.Wrappers;--/// <summary>-/// Ports Python <c>TestFocusCheck</c>: <see cref="HumanizedLocator.PressAsync"/> and-/// <see cref="HumanizedLocator.ClearAsync"/> only perform the humanized focus-click when-/// the element is not already focused. The focus state is probed via-/// <c>EvaluateAsync<bool>("el => el === document.activeElement")</c>; we mock that-/// to return true/false and assert whether the cursor moved (i.e. whether a click ran).-/// </summary>-public class FocusCheckTests-{- private static HumanConfig FastConfig() => new()- {- IdleBetweenActions = false,- MouseMinSteps = 2,- MouseMaxSteps = 3,- MouseBurstPause = (0, 0),- MouseOvershootChance = 0,- ClickAimDelayButton = (0, 0),- ClickHoldButton = (0, 0),- ClickAimDelayInput = (0, 0),- ClickHoldInput = (0, 0),- TypingDelay = 0,- TypingDelaySpread = 0,- TypingPauseChance = 0,- MistypeChance = 0,- ShiftDownDelay = (0, 0),- ShiftUpDelay = (0, 0),- KeyHold = (0, 0),- InitialCursorX = (100, 100),- InitialCursorY = (100, 100),- };-- private static (IPage page, FakeProxy mouseRec, FakeProxy kbRec) BuildPage()- {- var (mouse, mouseRec) = Fake.Of<IMouse>();- var (keyboard, kbRec) = Fake.Of<IKeyboard>();- var (page, pageRec) = Fake.Of<IPage>();- pageRec.On("Mouse", mouse);- pageRec.On("Keyboard", keyboard);- pageRec.On("ViewportSize", new PageViewportSizeResult { Width = 1280, Height = 720 });- return (page, mouseRec, kbRec);- }-- private static ILocator BuildLocator(bool focused)- {- var (locator, locRec) = Fake.Of<ILocator>();- locRec.On("First", locator);- locRec.On("BoundingBoxAsync", Task.FromResult<LocatorBoundingBoxResult?>(- new LocatorBoundingBoxResult { X = 100, Y = 200, Width = 80, Height = 30 }));- locRec.On("ScrollIntoViewIfNeededAsync", Task.CompletedTask);- // IsFocusedAsync / IsInputAsync both go through EvaluateAsync<bool>.- locRec.On("EvaluateAsync", Task.FromResult(focused));- return locator;- }-- // --- PressAsync ----------------------------------------------------------- [Fact]- public async Task PressAsync_skips_click_when_focused()- {- var (page, mouseRec, kbRec) = BuildPage();- var human = new HumanizedLocator(BuildLocator(focused: true), new HumanCursor(page), FastConfig());-- await human.PressAsync("Control+V", new LocatorPressOptions { Delay = 300 });-- Assert.Equal(0, mouseRec.CountOf("MoveAsync")); // cursor did not move- Assert.Equal(0, mouseRec.CountOf("DownAsync")); // no click- var press = Assert.IsType<KeyboardPressOptions>(kbRec.Last("PressAsync")!.Args[1]);- Assert.Equal(300, press.Delay);- }-- [Fact]- public async Task PressAsync_clicks_when_not_focused()- {- var (page, mouseRec, _) = BuildPage();- var human = new HumanizedLocator(BuildLocator(focused: false), new HumanCursor(page), FastConfig());-- await human.PressAsync("Enter");-- Assert.True(mouseRec.CountOf("MoveAsync") >= 1, "cursor moved to focus the element");- Assert.Equal(1, mouseRec.CountOf("DownAsync")); // humanized click happened- }-- // --- ClearAsync ----------------------------------------------------------- [Fact]- public async Task ClearAsync_skips_click_when_focused()- {- var (page, mouseRec, kbRec) = BuildPage();- var human = new HumanizedLocator(BuildLocator(focused: true), new HumanCursor(page), FastConfig());-- await human.ClearAsync();-- Assert.Equal(0, mouseRec.CountOf("MoveAsync")); // no focus click- Assert.Equal(0, mouseRec.CountOf("DownAsync"));- // Still selects-all + Backspace through the keyboard.- Assert.True(kbRec.CountOf("PressAsync") >= 2, "select-all + Backspace");- }-- [Fact]- public async Task ClearAsync_clicks_when_not_focused()- {- var (page, mouseRec, _) = BuildPage();- var human = new HumanizedLocator(BuildLocator(focused: false), new HumanCursor(page), FastConfig());-- await human.ClearAsync();-- Assert.True(mouseRec.CountOf("MoveAsync") >= 1, "cursor moved to focus the element");- Assert.Equal(1, mouseRec.CountOf("DownAsync"));- }-}diff --git a/dotnet/tests/CloakBrowser.Tests/Wrappers/FrameNavigatedInvalidationTests.cs b/dotnet/tests/CloakBrowser.Tests/Wrappers/FrameNavigatedInvalidationTests.csdeleted file mode 100644index c07c549..0000000--- a/dotnet/tests/CloakBrowser.Tests/Wrappers/FrameNavigatedInvalidationTests.cs+++ /dev/null@@ -1,101 +0,0 @@-using System.Reflection;-using CloakBrowser.Human;-using CloakBrowser.Wrappers;-using Microsoft.Playwright;-using Xunit;--namespace CloakBrowser.Tests.Wrappers;--/// <summary>-/// Regression #507: a click/form/history navigation (not just page.goto) must-/// invalidate the isolated world. bfcache keeps the previous document's context-/// alive, so a stale eval keeps succeeding against the old document and-/// fill()/click() actionability reads fail. Both page wrappers must subscribe to-/// <see cref="IPage.FrameNavigated"/> and invalidate on MAIN-frame navigations only.-/// </summary>-public class FrameNavigatedInvalidationTests-{- private static HumanConfig FastConfig() => new()- {- IdleBetweenActions = false,- InitialCursorX = (100, 100),- InitialCursorY = (100, 100),- };-- /// <summary>Give the world a non-null cached context id so Invalidate() is observable.</summary>- private static void PrimeContextId(IsolatedWorld world, int id) =>- typeof(IsolatedWorld).GetField("_contextId", BindingFlags.NonPublic | BindingFlags.Instance)!- .SetValue(world, id);-- private static int? ReadContextId(IsolatedWorld world) =>- (int?)typeof(IsolatedWorld).GetField("_contextId", BindingFlags.NonPublic | BindingFlags.Instance)!- .GetValue(world);-- [Fact]- public void HumanizedPage_invalidates_world_on_main_frame_nav_only()- {- var (mouse, _) = Fake.Of<IMouse>();- var (keyboard, _) = Fake.Of<IKeyboard>();- var (page, pageRec) = Fake.Of<IPage>();- var (mainFrame, _) = Fake.Of<IFrame>();- var (otherFrame, _) = Fake.Of<IFrame>();-- pageRec.On("Mouse", mouse);- pageRec.On("Keyboard", keyboard);- pageRec.On("MainFrame", mainFrame);-- EventHandler<IFrame>? handler = null;- pageRec.On("add_FrameNavigated", args => { handler = (EventHandler<IFrame>)args[0]!; return null; });-- var cursor = new HumanCursor(page);- // Inject a real isolated world with a primed context id so invalidation is visible.- var world = new IsolatedWorld(page);- PrimeContextId(world, 999);- typeof(HumanCursor).GetField("_stealth", BindingFlags.NonPublic | BindingFlags.Instance)!- .SetValue(cursor, world);-- _ = new HumanizedPage(page, cursor, FastConfig());-- Assert.NotNull(handler); // construction subscribed to FrameNavigated-- // subframe navigation -> world stays bound- handler!(page, otherFrame);- Assert.Equal(999, ReadContextId(world));-- // main-frame navigation -> world invalidated- handler!(page, mainFrame);- Assert.Null(ReadContextId(world));- }-- [Fact]- public void HumanPage_invalidates_world_on_main_frame_nav_only()- {- var (mouse, _) = Fake.Of<IMouse>();- var (keyboard, _) = Fake.Of<IKeyboard>();- var (page, pageRec) = Fake.Of<IPage>();- var (mainFrame, _) = Fake.Of<IFrame>();- var (otherFrame, _) = Fake.Of<IFrame>();-- pageRec.On("Mouse", mouse);- pageRec.On("Keyboard", keyboard);- pageRec.On("MainFrame", mainFrame);-- EventHandler<IFrame>? handler = null;- pageRec.On("add_FrameNavigated", args => { handler = (EventHandler<IFrame>)args[0]!; return null; });-- var human = new HumanPage(page, FastConfig());-- Assert.NotNull(handler);-- var world = new IsolatedWorld(page);- PrimeContextId(world, 777);- typeof(HumanPage).GetField("_stealth", BindingFlags.NonPublic | BindingFlags.Instance)!- .SetValue(human, world);-- handler!(page, otherFrame);- Assert.Equal(777, ReadContextId(world));-- handler!(page, mainFrame);- Assert.Null(ReadContextId(world));- }-}diff --git a/dotnet/tests/CloakBrowser.Tests/Wrappers/GeneratorDelegationTests.cs b/dotnet/tests/CloakBrowser.Tests/Wrappers/GeneratorDelegationTests.csindex e3decc6..16b70c9 100644--- a/dotnet/tests/CloakBrowser.Tests/Wrappers/GeneratorDelegationTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/Wrappers/GeneratorDelegationTests.cs@@ -200,15 +200,63 @@ public class GeneratorDelegationTestsnew object[] { typeof(HumanizedMouse), "MoveAsync" },new object[] { typeof(HumanizedMouse), "ClickAsync" },new object[] { typeof(HumanizedMouse), "DblClickAsync" },- new object[] { typeof(HumanizedMouse), "DownAsync" },- new object[] { typeof(HumanizedMouse), "UpAsync" },- new object[] { typeof(HumanizedMouse), "WheelAsync" },// HumanizedKeyboardnew object[] { typeof(HumanizedKeyboard), "TypeAsync" },- new object[] { typeof(HumanizedKeyboard), "PressAsync" },- new object[] { typeof(HumanizedKeyboard), "InsertTextAsync" },};+ /// <summary>Every member that hands out an element handle, frame or frame locator+ /// re-wraps it; otherwise actions on the result would run stock Playwright (visible to+ /// the page through its InjectedScript events).</summary>+ [Theory]+ [InlineData(typeof(HumanizedPage), "QuerySelectorAsync")]+ [InlineData(typeof(HumanizedPage), "QuerySelectorAllAsync")]+ [InlineData(typeof(HumanizedPage), "WaitForSelectorAsync")]+ [InlineData(typeof(HumanizedPage), "FrameLocator")]+ [InlineData(typeof(HumanizedFrame), "QuerySelectorAsync")]+ [InlineData(typeof(HumanizedFrame), "QuerySelectorAllAsync")]+ [InlineData(typeof(HumanizedFrame), "WaitForSelectorAsync")]+ [InlineData(typeof(HumanizedFrame), "FrameElementAsync")]+ [InlineData(typeof(HumanizedFrame), "FrameLocator")]+ [InlineData(typeof(HumanizedLocator), "ElementHandleAsync")]+ [InlineData(typeof(HumanizedLocator), "ElementHandlesAsync")]+ [InlineData(typeof(HumanizedLocator), "FrameLocator")]+ [InlineData(typeof(HumanizedElementHandle), "QuerySelectorAsync")]+ [InlineData(typeof(HumanizedElementHandle), "ContentFrameAsync")]+ [InlineData(typeof(HumanizedElementHandle), "OwnerFrameAsync")]+ public void Handle_and_frame_returning_member_rewraps(System.Type wrapper, string methodName)+ {+ var methods = wrapper.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)+ .Where(m => m.Name == methodName).ToList();+ Assert.NotEmpty(methods);+ Assert.All(methods, m => Assert.False(IsGenerated(m), $"{wrapper.Name}.{methodName} must re-wrap its result"));+ }++ [Theory]+ [InlineData(typeof(HumanizedLocator), "ContentFrame")]+ public void Frame_locator_property_rewraps(System.Type wrapper, string propertyName)+ {+ var getter = wrapper.GetProperty(propertyName)!.GetGetMethod()!;+ Assert.False(IsGenerated(getter), $"{wrapper.Name}.{propertyName} must re-wrap its result");+ }++ /// <summary>Raw primitives stay raw, like the Python / JS wrappers: a person's+ /// mouse down / up / wheel and key down / up / press / insertText map 1:1 to input.</summary>+ [Theory]+ [InlineData(typeof(HumanizedMouse), "DownAsync")]+ [InlineData(typeof(HumanizedMouse), "UpAsync")]+ [InlineData(typeof(HumanizedMouse), "WheelAsync")]+ [InlineData(typeof(HumanizedKeyboard), "DownAsync")]+ [InlineData(typeof(HumanizedKeyboard), "UpAsync")]+ [InlineData(typeof(HumanizedKeyboard), "PressAsync")]+ [InlineData(typeof(HumanizedKeyboard), "InsertTextAsync")]+ public void Raw_input_primitive_is_delegated(System.Type wrapper, string methodName)+ {+ var methods = wrapper.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)+ .Where(m => m.Name == methodName).ToList();+ Assert.NotEmpty(methods);+ Assert.All(methods, m => Assert.True(IsGenerated(m), $"{wrapper.Name}.{methodName} should be delegated"));+ }+[Theory][MemberData(nameof(InteractionMethodsByWrapper))]public void Interaction_method_is_humanized_not_generator_delegated(System.Type wrapper, string methodName)diff --git a/dotnet/tests/CloakBrowser.Tests/Wrappers/LocatorWrapperTests.cs b/dotnet/tests/CloakBrowser.Tests/Wrappers/LocatorWrapperTests.csindex d504dd6..87b47aa 100644--- a/dotnet/tests/CloakBrowser.Tests/Wrappers/LocatorWrapperTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/Wrappers/LocatorWrapperTests.cs@@ -64,178 +64,6 @@ public class LocatorWrapperTests// Interception// ------------------------------------------------------------------------ [Fact]- public async Task ClickAsync_runs_humanized_motion_and_press()- {- var (page, mouseRec, _) = BuildPage();- var (locator, _) = BuildLocator();- var cursor = new HumanCursor(page);- var human = new HumanizedLocator(locator, cursor, FastConfig());-- await human.ClickAsync();-- Assert.True(mouseRec.CountOf("MoveAsync") >= 1, "should move along a curve");- Assert.Equal(1, mouseRec.CountOf("DownAsync"));- Assert.Equal(1, mouseRec.CountOf("UpAsync"));- }-- [Fact]- public async Task FillAsync_clears_then_types_via_keyboard()- {- var (page, _, kbRec) = BuildPage();- var (locator, _) = BuildLocator();- var human = new HumanizedLocator(locator, new HumanCursor(page), FastConfig());-- await human.FillAsync("hi");-- // Select-all + Backspace + per-char typing all go through the page keyboard.- Assert.True(kbRec.CountOf("PressAsync") >= 2, "select-all + backspace");- Assert.True(kbRec.CountOf("DownAsync") >= 2, "typed characters");- }-- [Fact]- public void Frame_Locator_remains_on_legacy_path()- {- var (page, _, _) = BuildPage();- var (locator, _) = BuildLocator();- var (frame, frameRec) = Fake.Of<IFrame>();- frameRec.On("Locator", locator);- var human = new HumanizedFrame(frame, new HumanCursor(page), FastConfig());-- var wrapped = Assert.IsType<HumanizedLocator>(human.Locator("#inside-frame"));- Assert.Null(wrapped.Selector);- }-- [Fact]- public async Task Frame_PressAsync_forwards_delay()- {- var (page, _, kbRec) = BuildPage();- var (locator, _) = BuildLocator(evaluateResult: true);- var (frame, frameRec) = Fake.Of<IFrame>();- frameRec.On("Locator", locator);- var human = new HumanizedFrame(frame, new HumanCursor(page), FastConfig());-- await human.PressAsync("#field", "Control+V", new FramePressOptions { Delay = 300 });-- var options = Assert.IsType<KeyboardPressOptions>(kbRec.Last("PressAsync")!.Args[1]);- Assert.Equal(300, options.Delay);- }-- [Fact]- public async Task ElementHandle_PressAsync_forwards_delay()- {- var (page, _, kbRec) = BuildPage();- var (element, _) = Fake.Of<IElementHandle>();- var human = new HumanizedElementHandle(element, new HumanCursor(page), FastConfig());-- await human.PressAsync("Control+V", new ElementHandlePressOptions { Delay = 300 });-- var options = Assert.IsType<KeyboardPressOptions>(kbRec.Last("PressAsync")!.Args[1]);- Assert.Equal(300, options.Delay);- }-- [Fact]- public async Task SelectOptionAsync_runs_humanized_hover_then_delegates()- {- var (page, mouseRec, _) = BuildPage();- var (locator, locRec) = BuildLocator();- IReadOnlyList<string> selected = new[] { "opt1" };- locRec.On("SelectOptionAsync", Task.FromResult(selected));- var human = new HumanizedLocator(locator, new HumanCursor(page), FastConfig());-- var result = await human.SelectOptionAsync("opt1");-- // The cursor must travel to the <select> along a curve before the native select.- Assert.True(mouseRec.CountOf("MoveAsync") >= 1, "should move the cursor to the element");- // The real Playwright select is still performed (and its result flows back).- Assert.True(locRec.WasCalled("SelectOptionAsync"));- Assert.Equal(new[] { "opt1" }, result);- }-- [Fact]- public async Task SelectOptionAsync_overloads_all_humanize_and_delegate()- {- IReadOnlyList<string> selected = new[] { "v" };-- // Every ILocator SelectOptionAsync overload should hover (move) then delegate.- async Task AssertOverload(System.Func<HumanizedLocator, Task> call)- {- var (page, mouseRec, _) = BuildPage();- var (locator, locRec) = BuildLocator();- locRec.On("SelectOptionAsync", Task.FromResult(selected));- var human = new HumanizedLocator(locator, new HumanCursor(page), FastConfig());-- await call(human);-- Assert.True(mouseRec.CountOf("MoveAsync") >= 1, "should move the cursor");- Assert.True(locRec.WasCalled("SelectOptionAsync"), "should delegate to inner");- }-- var (handle, _) = Fake.Of<IElementHandle>();- await AssertOverload(h => h.SelectOptionAsync("v"));- await AssertOverload(h => h.SelectOptionAsync(new[] { "v" }));- await AssertOverload(h => h.SelectOptionAsync(new SelectOptionValue { Value = "v" }));- await AssertOverload(h => h.SelectOptionAsync(new[] { new SelectOptionValue { Value = "v" } }));- await AssertOverload(h => h.SelectOptionAsync(handle));- await AssertOverload(h => h.SelectOptionAsync(new[] { handle }));- }-- [Fact]- public async Task ClearAsync_focuses_selects_all_and_backspaces()- {- var (page, mouseRec, kbRec) = BuildPage();- var (locator, _) = BuildLocator(); // EvaluateAsync(IsFocused) -> false- var human = new HumanizedLocator(locator, new HumanCursor(page), FastConfig());-- await human.ClearAsync();-- // Not focused -> humanized click to focus the field (curve + press).- Assert.True(mouseRec.CountOf("MoveAsync") >= 1, "should move the cursor to focus");- Assert.Equal(1, mouseRec.CountOf("DownAsync"));- // Then select-all + Backspace via the keyboard (NOT an instant value reset).- Assert.True(kbRec.CountOf("PressAsync") >= 2, "select-all + backspace");- }-- [Fact]- public async Task ClearAsync_when_focused_skips_click_but_still_selects_and_deletes()- {- var (page, mouseRec, kbRec) = BuildPage();- // Field is already focused -> no humanized click, just select-all + backspace.- var (locator, _) = BuildLocator(evaluateResult: true);- var human = new HumanizedLocator(locator, new HumanCursor(page), FastConfig());-- await human.ClearAsync();-- Assert.Equal(0, mouseRec.CountOf("DownAsync")); // no focus click needed- Assert.True(kbRec.CountOf("PressAsync") >= 2, "select-all + backspace");- }-- [Fact]- public async Task CheckAsync_clicks_only_when_not_already_checked()- {- var (page, mouseRec, _) = BuildPage();- var (locator, locRec) = BuildLocator();- locRec.On("IsCheckedAsync", Task.FromResult(true)); // already checked- var human = new HumanizedLocator(locator, new HumanCursor(page), FastConfig());-- await human.CheckAsync();-- Assert.Equal(0, mouseRec.CountOf("DownAsync")); // no click performed- }-- [Fact]- public async Task CheckAsync_clicks_when_unchecked()- {- var (page, mouseRec, _) = BuildPage();- var (locator, locRec) = BuildLocator();- locRec.On("IsCheckedAsync", Task.FromResult(false));- var human = new HumanizedLocator(locator, new HumanCursor(page), FastConfig());-- await human.CheckAsync();-- Assert.Equal(1, mouseRec.CountOf("DownAsync")); // click performed- }-// -----------------------------------------------------------------------// Nested re-wrapping: locator-returning members return humanized locators.// -----------------------------------------------------------------------@@ -382,18 +210,6 @@ public class LocatorWrapperTestsawait Assert.ThrowsAsync<PlaywrightException>(() => human.ClickAsync());}- [Fact]- public async Task Cancellation_propagates_as_OperationCanceled()- {- var (page, _, _) = BuildPage();- var (locator, locRec) = BuildLocator();- locRec.On("ScrollIntoViewIfNeededAsync", _ => throw new OperationCanceledException());- var human = new HumanizedLocator(locator, new HumanCursor(page), FastConfig());-- await Assert.ThrowsAsync<OperationCanceledException>(() => human.ClickAsync());- }-- // #549: Filter's Has/HasNot must reach Playwright unwrapped.[Fact]public void Filter_unwraps_Has_and_HasNot_and_rewraps_result(){diff --git a/dotnet/tests/CloakBrowser.Tests/Wrappers/MouseKeyboardWrapperTests.cs b/dotnet/tests/CloakBrowser.Tests/Wrappers/MouseKeyboardWrapperTests.csindex 7c38ef0..8213d68 100644--- a/dotnet/tests/CloakBrowser.Tests/Wrappers/MouseKeyboardWrapperTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/Wrappers/MouseKeyboardWrapperTests.cs@@ -90,18 +90,6 @@ public class MouseKeyboardWrapperTestsAssert.True(down < up);}- [Fact]- public async Task Mouse_WheelAsync_is_chunked_into_multiple_inner_wheels()- {- var (page, _, mouseRec, _) = BuildPage();- var mouse = new HumanizedMouse(page.Mouse, MakeCursor(page), FastConfig());-- await mouse.WheelAsync(0, 300);-- Assert.True(mouseRec.CountOf("WheelAsync") > 1,- "wheel should be broken into small inertia bursts");- }-[Fact]public Task Mouse_Original_and_Inner_expose_the_unwrapped_object(){@@ -131,20 +119,6 @@ public class MouseKeyboardWrapperTestsAssert.Equal("Shift", kbRec.Last("DownAsync")!.Args[0]);}- [Fact]- public async Task Keyboard_TypeAsync_produces_per_character_inner_key_events()- {- var (page, _, _, kbRec) = BuildPage();- var kb = new HumanizedKeyboard(page.Keyboard, MakeCursor(page), FastConfig());-- await kb.TypeAsync("abc");-- // Human typing presses each key down+up individually (not one inner TypeAsync).- Assert.Equal(0, kbRec.CountOf("TypeAsync"));- Assert.True(kbRec.CountOf("DownAsync") >= 3, "expected per-char key downs");- Assert.True(kbRec.CountOf("UpAsync") >= 3, "expected per-char key ups");- }-[Fact]public async Task Keyboard_PressAsync_forwards_delay(){@@ -183,13 +157,4 @@ public class MouseKeyboardWrapperTestsAssert.Equal("boom", ex.Message);}- [Fact]- public async Task Keyboard_inner_exception_propagates()- {- var (page, _, _, kbRec) = BuildPage();- kbRec.On("DownAsync", _ => throw new PlaywrightException("kb fail"));- var kb = new HumanizedKeyboard(page.Keyboard, MakeCursor(page), FastConfig());-- await Assert.ThrowsAsync<PlaywrightException>(() => kb.TypeAsync("a"));- }}diff --git a/dotnet/tests/CloakBrowser.Tests/Wrappers/PageWrapperTests.cs b/dotnet/tests/CloakBrowser.Tests/Wrappers/PageWrapperTests.csindex 3d1c66b..db3c164 100644--- a/dotnet/tests/CloakBrowser.Tests/Wrappers/PageWrapperTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/Wrappers/PageWrapperTests.cs@@ -36,57 +36,7 @@ public class PageWrapperTestsInitialCursorY = (100, 100),};- private static IsolatedWorld BuildFakeWorld(IPage page)- {- var (cdp, cdpRec) = Fake.Of<ICDPSession>();- cdpRec.On("SendAsync", args =>- {- string method = (string)args[0]!;- if (method != "Runtime.evaluate")- return Task.FromResult<JsonElement?>(null);-- var parameters = (IDictionary<string, object>)args[1]!;- string expression = (string)parameters["expression"];- object value = expression == StealthDom.ViewportJs- ? new { width = 1280, height = 720 }- : new- {- v = 2, r = "ok", targetId = 1, gen = 3, attached = true,- visible = true, enabled = true, editable = true,- isInput = false, focused = false, @checked = false, hit = true,- box = new { x = 100, y = 200, width = 80, height = 30 },- };- return Task.FromResult<JsonElement?>(JsonSerializer.SerializeToElement(new- {- result = new { value },- }));- });-- var world = new IsolatedWorld(page);- typeof(IsolatedWorld).GetField("_cdp", BindingFlags.NonPublic | BindingFlags.Instance)!- .SetValue(world, cdp);- typeof(IsolatedWorld).GetField("_contextId", BindingFlags.NonPublic | BindingFlags.Instance)!- .SetValue(world, 42);- return world;- }-- private static void InjectWorld(HumanizedPage human, HumanCursor cursor, IsolatedWorld world)- {- typeof(HumanCursor).GetField("_stealth", BindingFlags.NonPublic | BindingFlags.Instance)!- .SetValue(cursor, world);- typeof(HumanCursor).GetField("_stealthInitialized", BindingFlags.NonPublic | BindingFlags.Instance)!- .SetValue(cursor, true);-- var humanPage = (HumanPage)typeof(HumanizedPage)- .GetField("_human", BindingFlags.NonPublic | BindingFlags.Instance)!- .GetValue(human)!;- typeof(HumanPage).GetField("_stealth", BindingFlags.NonPublic | BindingFlags.Instance)!- .SetValue(humanPage, world);- typeof(HumanPage).GetField("_stealthInitialized", BindingFlags.NonPublic | BindingFlags.Instance)!- .SetValue(humanPage, true);- }-- /// <summary>Build a fake page whose isolated world returns an actionable target.</summary>+ /// <summary>Build a fake page (wrapping / delegation only; actions are browser-tested).</summary>private static (HumanizedPage human, FakeProxy pageRec, FakeProxy mouseRec) BuildHumanizedPage(){var (mouse, mouseRec) = Fake.Of<IMouse>();@@ -115,7 +65,6 @@ public class PageWrapperTestsvar cursor = new HumanCursor(page);var human = new HumanizedPage(page, cursor, FastConfig());- InjectWorld(human, cursor, BuildFakeWorld(page));return (human, pageRec, mouseRec);}@@ -141,29 +90,6 @@ public class PageWrapperTestsAssert.IsType<HumanizedLocator>(human.GetByRole(AriaRole.Button));}- [Fact]- public void Locator_threads_selector_for_isolated_world_reads()- {- // Regression guard: page.Locator(sel) must carry the selector into the- // HumanizedLocator so its pre-click reads can resolve in the isolated world.- // GetBy*/chained locators have no CSS selector -> null -> Playwright fallback.- var (human, _, _) = BuildHumanizedPage();- var loc = Assert.IsType<HumanizedLocator>(human.Locator("button:has-text('X')"));- Assert.Equal("button:has-text('X')", loc.Selector);- Assert.Equal("button:has-text('X') >> nth=0", Assert.IsType<HumanizedLocator>(loc.First).Selector);- Assert.Equal("button:has-text('X') >> nth=-1", Assert.IsType<HumanizedLocator>(loc.Last).Selector);- Assert.Equal("button:has-text('X') >> nth=3", Assert.IsType<HumanizedLocator>(loc.Nth(3)).Selector);- Assert.Null(Assert.IsType<HumanizedLocator>(loc.First.First).Selector);- Assert.Null(Assert.IsType<HumanizedLocator>(loc.Nth(1).Nth(0)).Selector);-- var withOptions = Assert.IsType<HumanizedLocator>(human.Locator(- "button", new PageLocatorOptions { HasTextString = "X" }));- Assert.Null(withOptions.Selector);-- var byRole = Assert.IsType<HumanizedLocator>(human.GetByRole(AriaRole.Button));- Assert.Null(byRole.Selector);- }-[Fact]public void MainFrame_and_Frames_return_humanized_frames(){@@ -234,34 +160,6 @@ public class PageWrapperTests// Selector action interception drives the humanize engine.// ------------------------------------------------------------------------ [Fact]- public async Task ClickAsync_selector_runs_humanized_motion()- {- var (human, _, mouseRec) = BuildHumanizedPage();-- await human.ClickAsync("#submit");-- Assert.True(mouseRec.CountOf("MoveAsync") >= 1);- Assert.Equal(1, mouseRec.CountOf("DownAsync"));- Assert.Equal(1, mouseRec.CountOf("UpAsync"));- }-- [Fact]- public async Task PressAsync_selector_forwards_delay()- {- var (human, _, _) = BuildHumanizedPage();- var keyboard = (FakeProxy)(object)human.Original.Keyboard;-- await human.PressAsync("#field", "Control+V", new PagePressOptions { Delay = 300 });-- var options = Assert.IsType<KeyboardPressOptions>(keyboard.Last("PressAsync")!.Args[1]);- Assert.Equal(300, options.Delay);- }-- // ------------------------------------------------------------------------ // Delegation: non-interaction members forward to the inner page.- // ------------------------------------------------------------------------[Fact]public async Task TitleAsync_and_Url_delegate_to_inner(){diff --git a/js/src/human-puppeteer/index.ts b/js/src/human-puppeteer/index.tsindex 6fe9831..916dbeb 100644--- a/js/src/human-puppeteer/index.ts+++ b/js/src/human-puppeteer/index.ts@@ -254,6 +254,22 @@ async function isInputElementHandle(// Page-level patching// ============================================================================+type PressOptions = { button?: 'left' | 'right' | 'middle' | 'back' | 'forward'; clickCount?: number; count?: number; delay?: number };++/** Press like a person with Puppeteer's click options: the chosen button, a real+ * click-count sequence (detail 1, 2, ...) and `delay` as the hold time. */+async function humanPress(raw: RawMouse, isInput: boolean, cfg: HumanConfig, options?: PressOptions): Promise<void> {+ const button = options?.button ?? 'left';+ const count = Math.max(1, options?.count ?? options?.clickCount ?? 1);+ await sleep(randRange(isInput ? cfg.click_aim_delay_input : cfg.click_aim_delay_button));+ for (let n = 1; n <= count; n++) {+ await raw.down({ button, clickCount: n });+ await sleep(options?.delay ?? randRange(isInput ? cfg.click_hold_input : cfg.click_hold_button));+ await raw.up({ button, clickCount: n });+ if (n < count) await sleep(rand(60, 140));+ }+}+function patchPage(page: Page, cfg: HumanConfig, cursor: CursorState): void {const originals = {click: page.click.bind(page),@@ -356,16 +372,7 @@ function patchPage(page: Page, cfg: HumanConfig, cursor: CursorState): void {cursor.x = target.x;cursor.y = target.y;- const clickCount = options?.clickCount ?? options?.count ?? 1;- if (clickCount >= 2) {- await humanClick(raw, isInput, callCfg);- await sleep(rand(40, 90));- await raw.down({ clickCount: 2 });- await sleep(rand(30, 60));- await raw.up({ clickCount: 2 });- } else {- await humanClick(raw, isInput, callCfg);- }+ await humanPress(raw, isInput, callCfg, options);};// ==== hover ====@@ -447,16 +454,7 @@ function patchPage(page: Page, cfg: HumanConfig, cursor: CursorState): void {cursor.x = x;cursor.y = y;- const clickCount = options?.clickCount ?? options?.count ?? 1;- if (clickCount >= 2) {- await humanClick(raw, false, cfg);- await sleep(rand(40, 90));- await raw.down({ clickCount: 2 });- await sleep(rand(30, 60));- await raw.up({ clickCount: 2 });- } else {- await humanClick(raw, false, cfg);- }+ await humanPress(raw, false, cfg, options);};if (originals.mouseWheel) {@@ -680,16 +678,7 @@ function patchSingleElementHandle(const info = await moveToElement(callCfg);if (!info) return origElClick(options);- const clickCount = options?.clickCount ?? options?.count ?? 1;- if (clickCount >= 2) {- await humanClick(raw, info.isInp, callCfg);- await sleep(rand(40, 90));- await raw.down({ clickCount: 2 });- await sleep(rand(30, 60));- await raw.up({ clickCount: 2 });- } else {- await humanClick(raw, info.isInp, callCfg);- }+ await humanPress(raw, info.isInp, callCfg, options);};// --- el.hover() ---@@ -886,38 +875,67 @@ function patchSingleFrame(): void {const origFrameSelect = frame.select.bind(frame);- (frame as any).click = async (selector: string, options?: HumanActionOptions & {- button?: 'left' | 'right' | 'middle' | 'back' | 'forward';- clickCount?: number;- count?: number;- delay?: number;- }) => {- await (page as any).click(selector, options);+ // Frame actions resolve the selector inside *this* frame (stock Puppeteer+ // semantics, #184), then run the humanized ElementHandle action; the handle's+ // boundingBox() is in page coordinates, so the cursor travels correctly into+ // the iframe. Waiting honours `timeout` like Puppeteer's own frame.click.+ if (frame === page.mainFrame()) {+ // The main frame is the page: use the page-level humanized actions.+ (frame as any).click = (selector: string, options?: any) => (page as any).click(selector, options);+ (frame as any).hover = (selector: string, options?: any) => (page as any).hover(selector, options);+ (frame as any).type = (selector: string, text: string, options?: any) => (page as any).type(selector, text, options);+ (frame as any).select = (selector: string, ...values: string[]) => (page as any).select(selector, ...values);+ (frame as any).focus = (selector: string) => (page as any).focus(selector);+ (frame as any).tap = (selector: string, options?: any) => (page as any).tap(selector, options);+ } else {+ patchChildFrameActions();+ }++ function patchChildFrameActions(): void {+ const inFrame = async (selector: string, timeout?: number): Promise<ElementHandle> => {+ const el = await origFrameWaitForSelectorRaw(selector, { timeout });+ if (!el) throw new Error(`No element found for selector: ${selector}`);+ patchSingleElementHandle(el, page, cfg, cursor, raw, rawKb, originals, stealth);+ return el;+ };+ const origFrameWaitForSelectorRaw = frame.waitForSelector.bind(frame);++ (frame as any).click = async (selector: string, options?: HumanActionOptions & PressOptions) => {+ const el = await inFrame(selector, options?.timeout);+ try { await (el as any).click(options); } finally { await el.dispose().catch(() => {}); }};(frame as any).hover = async (selector: string, options?: HumanActionOptions) => {- await (page as any).hover(selector, options);+ const el = await inFrame(selector, options?.timeout);+ try { await (el as any).hover(); } finally { await el.dispose().catch(() => {}); }};(frame as any).type = async (selector: string, text: string, options?: HumanActionOptions & {delay?: number;}) => {- await (page as any).type(selector, text, options);+ const el = await inFrame(selector, options?.timeout);+ try { await (el as any).type(text, options); } finally { await el.dispose().catch(() => {}); }};(frame as any).select = async (selector: string, ...values: string[]) => {- await (page as any).hover(selector);- await sleep(rand(100, 300));- return origFrameSelect(selector, ...values);+ const el = await inFrame(selector);+ try {+ await (el as any).hover();+ await sleep(rand(100, 300));+ return await origFrameSelect(selector, ...values);+ } finally { await el.dispose().catch(() => {}); }};(frame as any).focus = async (selector: string) => {- await (page as any).focus(selector);+ const el = await inFrame(selector);+ try { await (el as any).focus(); } finally { await el.dispose().catch(() => {}); }};(frame as any).tap = async (selector: string, options?: HumanActionOptions) => {- await (page as any).click(selector, options);+ const el = await inFrame(selector, options?.timeout);+ try { await (el as any).click(options); } finally { await el.dispose().catch(() => {}); }};+ }// Patch frame.$() to return patched ElementHandlesconst origFrame$ = frame.$.bind(frame);diff --git a/js/src/human-puppeteer/keyboard.ts b/js/src/human-puppeteer/keyboard.tsindex e74ce8a..6722eee 100644--- a/js/src/human-puppeteer/keyboard.ts+++ b/js/src/human-puppeteer/keyboard.ts@@ -92,7 +92,10 @@ export async function humanType(// Mistypeif (Math.random() < cfg.mistype_chance && /^[a-zA-Z0-9]$/.test(ch)) {const wrong = getNearbyKey(ch);- await typeNormalChar(raw, wrong, cfg);+ // A typo next to an uppercase letter is typed with Shift held, like the+ // letter itself (a bare keydown of "A" reports shiftKey=false).+ if (isUpperCase(wrong)) await typeShiftedChar(raw, wrong, cfg);+ else await typeNormalChar(raw, wrong, cfg);await sleep(randRange(cfg.mistype_delay_notice));await raw.down('Backspace');await sleep(randRange(cfg.key_hold));diff --git a/js/src/human-puppeteer/scroll.ts b/js/src/human-puppeteer/scroll.tsindex 6fedc62..ac3ad71 100644--- a/js/src/human-puppeteer/scroll.ts+++ b/js/src/human-puppeteer/scroll.ts@@ -47,7 +47,10 @@ export async function smoothWheel(let sent = 0;while (sent < absD) {const stepSize = rand(20, 40);- const chunk = Math.min(stepSize, absD - sent);+ let chunk = Math.min(stepSize, absD - sent);+ // Fold a sub-pixel tail into this step: on its own it would round to a+ // (0, 0) wheel event, which no real wheel sends.+ if (absD - sent - chunk < 0.5) chunk = absD - sent;const d = Math.round(chunk) * sign;if (axis === 'x') {await raw.wheel(d, 0);diff --git a/js/src/human/actionability.ts b/js/src/human/actionability.tsdeleted file mode 100644index b66e873..0000000--- a/js/src/human/actionability.ts+++ /dev/null@@ -1,369 +0,0 @@-/**- * Playwright-style actionability checks for the humanize layer.- *- * Selector-based reads stay inside the CDP isolated world. ElementHandle paths- * remain separate because they already identify an exact Playwright handle.- */--import type { Page, Frame, ElementHandle } from 'playwright-core';-import {- buildActionableJs, buildBoxJs, buildValidateJs, evalParsed, getWorld,- OK, NOT_FOUND, UNSUPPORTED, STALE, EVALUATION_FAILED,- StealthEvaluationError, StealthWorldUnavailableError,- UnsupportedHumanizeSelectorError, type StealthWorld,-} from './stealthDom.js';--// ----------------------------------------------------------------------------// Error hierarchy-// -----------------------------------------------------------------------------export class ActionabilityError extends Error {- selector: string;- check: string;-- constructor(selector: string, check: string, message: string) {- super(`Element ${JSON.stringify(selector)} failed ${check} check: ${message}`);- this.name = 'ActionabilityError';- this.selector = selector;- this.check = check;- }-}--export class ElementNotAttachedError extends ActionabilityError {- constructor(selector: string) {- super(selector, 'attached', 'element not found in DOM');- this.name = 'ElementNotAttachedError';- }-}--export class ElementNotVisibleError extends ActionabilityError {- constructor(selector: string) {- super(selector, 'visible', 'element is not visible');- this.name = 'ElementNotVisibleError';- }-}--export class ElementNotStableError extends ActionabilityError {- constructor(selector: string) {- super(selector, 'stable', 'element position is still changing');- this.name = 'ElementNotStableError';- }-}--export class ElementNotEnabledError extends ActionabilityError {- constructor(selector: string) {- super(selector, 'enabled', 'element is disabled');- this.name = 'ElementNotEnabledError';- }-}--export class ElementNotEditableError extends ActionabilityError {- constructor(selector: string) {- super(selector, 'editable', 'element is not editable');- this.name = 'ElementNotEditableError';- }-}--export class ElementNotReceivingEventsError extends ActionabilityError {- coveringTag: string;- constructor(selector: string, coveringTag: string = 'unknown') {- super(selector, 'pointer_events', `element is covered by <${coveringTag}>`);- this.name = 'ElementNotReceivingEventsError';- this.coveringTag = coveringTag;- }-}--export class ElementTargetChangedError extends ActionabilityError {- constructor(selector: string) {- super(selector, 'target_identity', 'selector resolved to a different element before input dispatch');- this.name = 'ElementTargetChangedError';- }-}--// ----------------------------------------------------------------------------// Check-set constants-// -----------------------------------------------------------------------------export type CheckName = 'attached' | 'visible' | 'enabled' | 'editable' | 'pointer_events';--export const CHECKS_CLICK: ReadonlySet<CheckName> = new Set(['attached', 'visible', 'enabled', 'pointer_events']);-export const CHECKS_HOVER: ReadonlySet<CheckName> = new Set(['attached', 'visible', 'pointer_events']);-export const CHECKS_INPUT: ReadonlySet<CheckName> = new Set(['attached', 'visible', 'enabled', 'editable', 'pointer_events']);-export const CHECKS_FOCUS: ReadonlySet<CheckName> = new Set(['attached', 'visible', 'enabled']);-export const CHECKS_CHECK: ReadonlySet<CheckName> = new Set(['attached', 'visible', 'enabled', 'pointer_events']);--const BACKOFF_MS = [100, 250, 500, 1000];--function backoffSleep(attempt: number): Promise<void> {- const idx = Math.min(attempt, BACKOFF_MS.length - 1);- return new Promise(resolve => setTimeout(resolve, BACKOFF_MS[idx]));-}--// ----------------------------------------------------------------------------// Pre-scroll actionability-// -----------------------------------------------------------------------------async function stealthActionable(- pageOrFrame: Page | Frame,- selector: string,- checks: ReadonlySet<CheckName>,-): Promise<void> {- const world = getWorld(pageOrFrame);- if (!world) throw new StealthWorldUnavailableError();-- const { status, data } = await evalParsed(world, buildActionableJs(selector));- if (status === UNSUPPORTED) throw new UnsupportedHumanizeSelectorError(selector);- if (status === EVALUATION_FAILED) throw new StealthEvaluationError(selector);- if (status === NOT_FOUND) throw new ElementNotAttachedError(selector);- if (status !== OK || !data) throw new StealthEvaluationError(selector);- if (checks.has('visible') && !data.visible) throw new ElementNotVisibleError(selector);- if (checks.has('enabled') && !data.enabled) throw new ElementNotEnabledError(selector);- if (checks.has('editable') && !data.editable) throw new ElementNotEditableError(selector);-}--async function readBox(- pageOrFrame: Page | Frame,- selector: string,-): Promise<{ x: number; y: number; width: number; height: number } | null> {- const world = getWorld(pageOrFrame);- if (!world) throw new StealthWorldUnavailableError();-- const { status, data } = await evalParsed(world, buildBoxJs(selector));- if (status === OK && data?.box) return data.box;- if (status === NOT_FOUND) return null;- if (status === UNSUPPORTED) throw new UnsupportedHumanizeSelectorError(selector);- throw new StealthEvaluationError(selector);-}--export async function ensureActionable(- pageOrFrame: Page | Frame,- selector: string,- checks: ReadonlySet<CheckName>,- timeout: number = 30000,- force: boolean = false,-): Promise<void> {- if (force) return;-- const deadline = Date.now() + timeout;- let attempt = 0;- let lastError: Error | null = null;-- while (true) {- const remainingMs = Math.max(0, deadline - Date.now());- if (remainingMs <= 0) {- if (lastError) throw lastError;- throw new ActionabilityError(selector, 'timeout', 'timeout expired before first check');- }-- try {- await stealthActionable(pageOrFrame, selector, checks);- return;- } catch (error) {- if (error instanceof ActionabilityError || error instanceof StealthEvaluationError) {- lastError = error;- if (Date.now() >= deadline) throw lastError;- await backoffSleep(attempt++);- } else {- throw error;- }- }- }-}--// ----------------------------------------------------------------------------// Post-scroll stability check-// -----------------------------------------------------------------------------function boxesDiffer(- a: { x: number; y: number; width: number; height: number },- b: { x: number; y: number; width: number; height: number },-): boolean {- return (- Math.abs(a.x - b.x) > 1 ||- Math.abs(a.y - b.y) > 1 ||- Math.abs(a.width - b.width) > 1 ||- Math.abs(a.height - b.height) > 1- );-}--export async function ensureStable(- pageOrFrame: Page | Frame,- selector: string,- timeout: number = 5000,-): Promise<void> {- const deadline = Date.now() + timeout;- let attempt = 0;-- while (true) {- const remainingMs = Math.max(0, deadline - Date.now());- if (remainingMs <= 0) throw new ElementNotStableError(selector);-- try {- const box1 = await readBox(pageOrFrame, selector);- if (!box1) throw new ElementNotAttachedError(selector);-- await new Promise(resolve => setTimeout(resolve, 100));-- const box2 = await readBox(pageOrFrame, selector);- if (!box2) throw new ElementNotAttachedError(selector);- if (!boxesDiffer(box1, box2)) return;- } catch (error) {- if (error instanceof StealthEvaluationError) {- if (Date.now() >= deadline) throw error;- await backoffSleep(attempt++);- continue;- }- throw error;- }-- if (Date.now() >= deadline) throw new ElementNotStableError(selector);- await backoffSleep(attempt++);- }-}--// ----------------------------------------------------------------------------// Pointer-events and exact-target check-// -----------------------------------------------------------------------------const POINTER_EVENTS_HANDLE_JS = `(expected, data) => {- const rect = expected.getBoundingClientRect();- const frameOffsetX = data.box ? data.box.x - rect.x : 0;- const frameOffsetY = data.box ? data.box.y - rect.y : 0;- const target = document.elementFromPoint(data.x - frameOffsetX, data.y - frameOffsetY);- if (!target) return { hit: false, reason: 'no_element_at_point', covering: 'none' };- let node = target;- while (node) { if (node === expected) return { hit: true }; node = node.parentNode; }- if (expected.contains(target)) return { hit: true };- return { hit: false, reason: 'covered', covering: target.tagName || 'unknown' };-}`;--export async function checkPointerEvents(- pageOrFrame: Page | Frame,- selector: string,- targetId: number,- gen: number,- x: number,- y: number,- stealth?: StealthWorld | null,- timeout: number = 5000,-): Promise<void> {- const deadline = Date.now() + timeout;- let attempt = 0;- let lastMiss: string | null = null;- const world = stealth ?? getWorld(pageOrFrame);-- if (!world) throw new StealthWorldUnavailableError();- if (!Number.isInteger(targetId) || !Number.isInteger(gen)) throw new StealthEvaluationError(selector);-- while (true) {- const { status, data } = await evalParsed(- world,- buildValidateJs(selector, targetId, gen, x, y),- );-- if (status === UNSUPPORTED) throw new UnsupportedHumanizeSelectorError(selector);- if (status === STALE) throw new ElementTargetChangedError(selector);- if (status === NOT_FOUND) throw new ElementNotAttachedError(selector);- if (status === EVALUATION_FAILED) {- if (Date.now() >= deadline) throw new StealthEvaluationError(selector);- } else if (status === OK && data && data.hit) {- return;- } else if (status === OK && data) {- lastMiss = data.covering ?? 'unknown';- if (Date.now() >= deadline) {- throw new ElementNotReceivingEventsError(selector, lastMiss ?? 'unknown');- }- } else {- throw new StealthEvaluationError(selector);- }-- await backoffSleep(attempt++);- }-}--// ----------------------------------------------------------------------------// ElementHandle variant (legacy handle-scoped path)-// -----------------------------------------------------------------------------export async function ensureActionableHandle(- el: ElementHandle,- checks: ReadonlySet<CheckName>,- timeout: number = 30000,- force: boolean = false,-): Promise<void> {- if (force) return;-- const deadline = Date.now() + timeout;- let attempt = 0;- let lastError: ActionabilityError | null = null;- const label = '<ElementHandle>';-- while (true) {- const remainingMs = Math.max(0, deadline - Date.now());- if (remainingMs <= 0) {- if (lastError) throw lastError;- throw new ActionabilityError(label, 'timeout', 'timeout expired before first check');- }-- try {- if (checks.has('visible')) {- try {- await el.waitForElementState('visible', { timeout: Math.max(1, Math.min(remainingMs, 2000)) });- } catch {- throw new ElementNotVisibleError(label);- }- }- if (checks.has('enabled')) {- try {- await el.waitForElementState('enabled', { timeout: Math.max(1, Math.min(remainingMs, 2000)) });- } catch {- throw new ElementNotEnabledError(label);- }- }- if (checks.has('editable')) {- try {- await el.waitForElementState('editable', { timeout: Math.max(1, Math.min(remainingMs, 2000)) });- } catch {- throw new ElementNotEditableError(label);- }- }- return;- } catch (error) {- if (error instanceof ActionabilityError) {- lastError = error;- if (Date.now() >= deadline) throw lastError;- await backoffSleep(attempt++);- } else {- throw error;- }- }- }-}--export async function checkPointerEventsHandle(- el: ElementHandle,- x: number,- y: number,- timeout: number = 5000,-): Promise<void> {- const deadline = Date.now() + timeout;- let attempt = 0;-- while (true) {- let result: any;- try {- const box = await el.boundingBox();- result = await el.evaluate(POINTER_EVENTS_HANDLE_JS, { x, y, box });- } catch {- result = null;- }-- if (!result || result.hit) return;-- const covering = result?.covering ?? 'unknown';- if (Date.now() >= deadline) {- throw new ElementNotReceivingEventsError('<ElementHandle>', covering);- }- await backoffSleep(attempt++);- }-}diff --git a/js/src/human/elementhandle.ts b/js/src/human/elementhandle.tsdeleted file mode 100644index 2694a5b..0000000--- a/js/src/human/elementhandle.ts+++ /dev/null@@ -1,551 +0,0 @@-/**- * ElementHandle humanization for Playwright.- *- * Mirrors Puppeteer's ElementHandle patching architecture.- * Patches page.$(), page.$$(), page.waitForSelector() to return humanized handles,- * and patches all interaction methods on each ElementHandle instance.- *- * Playwright ElementHandle methods patched:- * click, dblclick, hover, type, fill, press, selectOption,- * check, uncheck, setChecked, tap, focus- * + $, $$, waitForSelector (nested elements are also patched)- *- * Stealth-aware:- * - Uses CDP DOM.describeNode when available to check element type- * (no main-world JS execution)- * - Falls back to el.evaluate() only when CDP is unavailable- */--import type { Page, Frame, ElementHandle, CDPSession } from 'playwright-core';-import type { HumanConfig, HumanActionOptions } from './config.js';-import { rand, randRange, sleep, mergeConfig } from './config.js';-import { type RawMouse, type RawKeyboard, humanMove, humanClick, clickTarget, humanIdle } from './mouse.js';-import { humanType, pressWithDelay } from './keyboard.js';-import { humanScrollIntoView } from './scroll.js';-import {- ensureActionableHandle, checkPointerEventsHandle,- CHECKS_CLICK, CHECKS_HOVER, CHECKS_INPUT, CHECKS_FOCUS, CHECKS_CHECK,-} from './actionability.js';--// --- Platform-aware select-all shortcut ----const SELECT_ALL = process.platform === 'darwin' ? 'Meta+a' : 'Control+a';--function reportHumanizeError(action: string, error: unknown): void {- console.error(`[cloakbrowser] ElementHandle ${action} failed:`, error);-}---// ============================================================================-// Stealth ElementHandle input check — uses CDP DOM.describeNode-// ============================================================================--async function isInputElementHandle(- stealth: any, // StealthEval from index.ts- el: ElementHandle,-): Promise<boolean> {- // Try CDP DOM.describeNode first (no main-world JS execution)- if (stealth) {- try {- await stealth.getCdpSession();- // Playwright doesn't expose remoteObject directly like Puppeteer,- // so use el.evaluate as the fallback within the stealth context.- } catch { /* fallthrough */ }- }-- // Fallback: el.evaluate (works reliably in Playwright)- try {- return await el.evaluate((node: any) => {- const tag = node.tagName?.toLowerCase();- return tag === 'input' || tag === 'textarea'- || node.getAttribute?.('contenteditable') === 'true';- });- } catch {- return false;- }-}---// ============================================================================-// CursorState type (matches index.ts)-// ============================================================================--interface CursorState {- x: number;- y: number;- initialized: boolean;-}---// ============================================================================-// Patch a single Playwright ElementHandle-// ============================================================================--export function patchSingleElementHandle(- el: ElementHandle,- page: Page,- cfg: HumanConfig,- cursor: CursorState,- raw: RawMouse,- rawKb: RawKeyboard,- originals: any,- stealth: any,-): void {- if ((el as any)._humanPatched) return;- (el as any)._humanPatched = true;-- // Save originals- const origElClick = el.click.bind(el);- const origElDblclick = el.dblclick.bind(el);- const origElHover = el.hover.bind(el);- const origElType = el.type.bind(el);- const origElFill = el.fill.bind(el);- const origElSelectOption = el.selectOption.bind(el);- const origElCheck = el.check.bind(el);- const origElUncheck = el.uncheck.bind(el);- const origElSetChecked = (el as any).setChecked?.bind(el);- const origElTap = el.tap.bind(el);- const origElFocus = el.focus.bind(el);- const origElScrollIntoViewIfNeeded = (el as any).scrollIntoViewIfNeeded?.bind(el);-- // Nested selectors- const origEl$ = el.$.bind(el);- const origEl$$ = el.$$.bind(el);- const origElWaitForSelector = el.waitForSelector.bind(el);-- // --- Nested elements are also patched ---- (el as any).$ = async (selector: string) => {- const child = await origEl$(selector);- if (child) patchSingleElementHandle(child, page, cfg, cursor, raw, rawKb, originals, stealth);- return child;- };-- (el as any).$$ = async (selector: string) => {- const children = await origEl$$(selector);- for (const child of children) {- patchSingleElementHandle(child, page, cfg, cursor, raw, rawKb, originals, stealth);- }- return children;- };-- (el as any).waitForSelector = async (selector: string, options?: {- state?: 'attached' | 'detached' | 'visible' | 'hidden';- strict?: boolean;- timeout?: number;- }) => {- const child = await origElWaitForSelector(selector, options ?? {});- if (child) patchSingleElementHandle(child, page, cfg, cursor, raw, rawKb, originals, stealth);- return child;- };-- // --- Helper: get bounding box and move cursor to element ---- // Accepts a per-call ``callCfg`` so type/fill overrides like- // ``el.type(text, { human_config: { typing_delay: 30 } })`` or- // ``el.type(text, { typing_delay: 30 })`` carry through to mouse movement- // & idle timing for that single call.- // Also scrolls the element into view first so off-screen elements work- // (#129, #172 follow-up): otherwise boundingBox() returns null and we'd- // silently fall back to the unpatched native method.- const moveToElement = async (callCfg: HumanConfig = cfg) => {- // Ensure cursor is initialized- const ensureCursorInit = (page as any)._ensureCursorInit;- if (ensureCursorInit) await ensureCursorInit();-- // Scroll into view first so boundingBox() returns coordinates even when- // the element starts below the fold. Best-effort — if humanScrollIntoView- // throws (e.g. detached element), we let boundingBox() decide whether to- // proceed or fall back to the original method.- try {- const { cursorX, cursorY } = await humanScrollIntoView(- page, raw,- () => el.boundingBox(),- cursor.x, cursor.y, callCfg,- );- cursor.x = cursorX;- cursor.y = cursorY;- } catch { /* let boundingBox() decide */ }-- const box = await el.boundingBox();- if (!box) return null;-- const isInp = await isInputElementHandle(stealth, el);- const target = clickTarget(box, isInp, callCfg);-- if (callCfg.idle_between_actions) {- await humanIdle(raw, cursor.x, cursor.y, callCfg);- }-- await humanMove(raw, cursor.x, cursor.y, target.x, target.y, callCfg);- cursor.x = target.x;- cursor.y = target.y;- return { box, isInp };- };-- // --- el.click() ---- (el as any).click = async (options?: HumanActionOptions & {- button?: 'left' | 'right' | 'middle';- clickCount?: number;- delay?: number;- force?: boolean;- modifiers?: Array<'Alt' | 'Control' | 'ControlOrMeta' | 'Meta' | 'Shift'>;- noWaitAfter?: boolean;- position?: { x: number; y: number };- trial?: boolean;- }) => {- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- const force = options?.force ?? false;- const timeout = options?.timeout ?? 30000;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());- if (!force) await ensureActionableHandle(el, CHECKS_CLICK, remainingMs(), force);- const info = await moveToElement(callCfg);- if (!info) return origElClick(options);- if (!force) await checkPointerEventsHandle(el, cursor.x, cursor.y, Math.min(remainingMs(), 5000));- await humanClick(raw, info.isInp, callCfg);- };-- // --- el.dblclick() ---- (el as any).dblclick = async (options?: HumanActionOptions & {- button?: 'left' | 'right' | 'middle';- delay?: number;- force?: boolean;- modifiers?: Array<'Alt' | 'Control' | 'ControlOrMeta' | 'Meta' | 'Shift'>;- noWaitAfter?: boolean;- position?: { x: number; y: number };- trial?: boolean;- }) => {- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- const force = options?.force ?? false;- const timeout = options?.timeout ?? 30000;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());- if (!force) await ensureActionableHandle(el, CHECKS_CLICK, remainingMs(), force);- const info = await moveToElement(callCfg);- if (!info) return origElDblclick(options);- if (!force) await checkPointerEventsHandle(el, cursor.x, cursor.y, Math.min(remainingMs(), 5000));- await raw.down({ clickCount: 2 });- await sleep(rand(30, 60));- await raw.up({ clickCount: 2 });- };-- // --- el.hover() ---- (el as any).hover = async (options?: HumanActionOptions & {- force?: boolean;- modifiers?: Array<'Alt' | 'Control' | 'ControlOrMeta' | 'Meta' | 'Shift'>;- position?: { x: number; y: number };- trial?: boolean;- }) => {- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- const force = options?.force ?? false;- const timeout = options?.timeout ?? 30000;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());- if (!force) await ensureActionableHandle(el, CHECKS_HOVER, remainingMs(), force);- const info = await moveToElement(callCfg);- if (!info) return origElHover(options);- };-- // --- el.type() ---- (el as any).type = async (text: string, options?: HumanActionOptions & {- delay?: number;- noWaitAfter?: boolean;- }) => {- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- const force = (options as any)?.force ?? false;- const timeout = options?.timeout ?? 30000;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());- if (!force) await ensureActionableHandle(el, CHECKS_INPUT, remainingMs(), force);- const info = await moveToElement(callCfg);- if (!info) return origElType(text, options);- if (!force) await checkPointerEventsHandle(el, cursor.x, cursor.y, Math.min(remainingMs(), 5000));- await humanClick(raw, info.isInp, callCfg);- await sleep(rand(100, 250));- let cdpSession: CDPSession | null = null;- try {- cdpSession = await stealth?.getCdpSession();- } catch (error) {- reportHumanizeError('typing CDP setup', error);- }- await humanType(page, rawKb, text, callCfg, cdpSession);- };-- // --- el.fill() ---- (el as any).fill = async (value: string, options?: HumanActionOptions & {- force?: boolean;- noWaitAfter?: boolean;- }) => {- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- const force = options?.force ?? false;- const timeout = options?.timeout ?? 30000;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());- if (!force) await ensureActionableHandle(el, CHECKS_INPUT, remainingMs(), force);- const info = await moveToElement(callCfg);- if (!info) return origElFill(value, options);- if (!force) await checkPointerEventsHandle(el, cursor.x, cursor.y, Math.min(remainingMs(), 5000));- await humanClick(raw, info.isInp, callCfg);- await sleep(rand(100, 250));- await originals.keyboardPress(SELECT_ALL);- await sleep(rand(30, 80));- await originals.keyboardPress('Backspace');- await sleep(rand(50, 150));- let cdpSession: CDPSession | null = null;- try {- cdpSession = await stealth?.getCdpSession();- } catch (error) {- reportHumanizeError('fill CDP setup', error);- }- await humanType(page, rawKb, value, callCfg, cdpSession);- };-- // --- el.press() ---- (el as any).press = async (key: string, options?: { delay?: number; noWaitAfter?: boolean; timeout?: number }) => {- await sleep(rand(20, 60));- await pressWithDelay(originals.keyboardPress, key, options, randRange(cfg.key_hold));- };-- // --- el.selectOption() ---- (el as any).selectOption = async (values: any, options?: {- force?: boolean;- noWaitAfter?: boolean;- timeout?: number;- }) => {- const force = options?.force ?? false;- const timeout = options?.timeout ?? 30000;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());- if (!force) await ensureActionableHandle(el, CHECKS_FOCUS, remainingMs(), force);- const info = await moveToElement();- if (!info) return origElSelectOption(values, options);- await humanClick(raw, false, cfg);- await sleep(rand(100, 300));- return origElSelectOption(values, options);- };-- // --- el.check() ---- (el as any).check = async (options?: {- force?: boolean;- noWaitAfter?: boolean;- position?: { x: number; y: number };- timeout?: number;- trial?: boolean;- }) => {- const force = options?.force ?? false;- const timeout = options?.timeout ?? 30000;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());- if (!force) await ensureActionableHandle(el, CHECKS_CHECK, remainingMs(), force);- try {- const checked = await el.isChecked();- if (checked) return;- } catch (error) {- reportHumanizeError('checked-state read', error);- }- const info = await moveToElement();- if (!info) return origElCheck(options);- if (!force) await checkPointerEventsHandle(el, cursor.x, cursor.y, Math.min(remainingMs(), 5000));- await humanClick(raw, info.isInp, cfg);- };-- // --- el.uncheck() ---- (el as any).uncheck = async (options?: {- force?: boolean;- noWaitAfter?: boolean;- position?: { x: number; y: number };- timeout?: number;- trial?: boolean;- }) => {- const force = options?.force ?? false;- const timeout = options?.timeout ?? 30000;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());- if (!force) await ensureActionableHandle(el, CHECKS_CHECK, remainingMs(), force);- try {- const checked = await el.isChecked();- if (!checked) return;- } catch (error) {- reportHumanizeError('unchecked-state read', error);- }- const info = await moveToElement();- if (!info) return origElUncheck(options);- if (!force) await checkPointerEventsHandle(el, cursor.x, cursor.y, Math.min(remainingMs(), 5000));- await humanClick(raw, info.isInp, cfg);- };-- // --- el.setChecked() ---- if (origElSetChecked) {- (el as any).setChecked = async (checked: boolean, options?: {- force?: boolean;- noWaitAfter?: boolean;- position?: { x: number; y: number };- timeout?: number;- trial?: boolean;- }) => {- const force = options?.force ?? false;- const timeout = options?.timeout ?? 30000;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());- if (!force) await ensureActionableHandle(el, CHECKS_CHECK, remainingMs(), force);- try {- const current = await el.isChecked();- if (current === checked) return;- } catch (error) {- reportHumanizeError('checked-state read', error);- }- const info = await moveToElement();- if (!info) return origElSetChecked(checked, options);- if (!force) await checkPointerEventsHandle(el, cursor.x, cursor.y, Math.min(remainingMs(), 5000));- await humanClick(raw, info.isInp, cfg);- };- }-- // --- el.tap() ---- (el as any).tap = async (options?: {- force?: boolean;- modifiers?: Array<'Alt' | 'Control' | 'ControlOrMeta' | 'Meta' | 'Shift'>;- noWaitAfter?: boolean;- position?: { x: number; y: number };- timeout?: number;- trial?: boolean;- }) => {- const info = await moveToElement();- if (!info) return origElTap(options);- await humanClick(raw, info.isInp, cfg);- };-- // --- el.focus() ---- // Move cursor humanly but use programmatic focus (no click side-effects).- // Stock Playwright el.focus() never clicks — clicking would trigger onclick,- // submit forms, navigate links, etc.- (el as any).focus = async () => {- await moveToElement(); // human-like Bézier cursor movement- await origElFocus(); // programmatic focus, no click- };-- // --- el.scrollIntoViewIfNeeded() ---- // Playwright's native version snaps the page — a strong bot signal.- // Replace with the same accelerate → cruise → decelerate → overshoot- // wheel sequence used by page.click() etc. Falls back to the native- // method if the element is detached or scrolling fails.- if (origElScrollIntoViewIfNeeded) {- (el as any).scrollIntoViewIfNeeded = async (options?: HumanActionOptions) => {- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- const ensureCursorInit = (page as any)._ensureCursorInit;- if (ensureCursorInit) await ensureCursorInit();- try {- const { cursorX, cursorY } = await humanScrollIntoView(- page, raw,- () => el.boundingBox(),- cursor.x, cursor.y, callCfg,- );- cursor.x = cursorX;- cursor.y = cursorY;- } catch {- return origElScrollIntoViewIfNeeded(options);- }- };- }-}---// ============================================================================-// Page-level ElementHandle patching-// ============================================================================--export function patchPageElementHandles(- page: Page,- cfg: HumanConfig,- cursor: CursorState,- raw: RawMouse,- rawKb: RawKeyboard,- originals: any,- stealth: any,-): void {- // Patch page.$() — only if the method exists- if (typeof page.$ === 'function') {- const orig$ = page.$.bind(page);- (page as any).$ = async (selector: string) => {- const el = await orig$(selector);- if (el) patchSingleElementHandle(el, page, cfg, cursor, raw, rawKb, originals, stealth);- return el;- };- }-- // Patch page.$$()- if (typeof page.$$ === 'function') {- const orig$$ = page.$$.bind(page);- (page as any).$$ = async (selector: string) => {- const els = await orig$$(selector);- for (const el of els) {- patchSingleElementHandle(el, page, cfg, cursor, raw, rawKb, originals, stealth);- }- return els;- };- }-- // Patch page.waitForSelector()- if (typeof page.waitForSelector === 'function') {- const origWaitForSelector = page.waitForSelector.bind(page);- (page as any).waitForSelector = async (selector: string, options?: {- state?: 'attached' | 'detached' | 'visible' | 'hidden';- strict?: boolean;- timeout?: number;- }) => {- const el = await origWaitForSelector(selector, options ?? {});- if (el) patchSingleElementHandle(el, page, cfg, cursor, raw, rawKb, originals, stealth);- return el;- };- }-}---// ============================================================================-// Frame-level ElementHandle patching-// ============================================================================--export function patchFrameElementHandles(- frame: Frame,- page: Page,- cfg: HumanConfig,- cursor: CursorState,- raw: RawMouse,- rawKb: RawKeyboard,- originals: any,- stealth: any,-): void {- // Patch frame.$() — only if the method exists- if (typeof frame.$ === 'function') {- const origFrame$ = frame.$.bind(frame);- (frame as any).$ = async (selector: string) => {- const el = await origFrame$(selector);- if (el) patchSingleElementHandle(el, page, cfg, cursor, raw, rawKb, originals, stealth);- return el;- };- }-- // Patch frame.$$()- if (typeof frame.$$ === 'function') {- const origFrame$$ = frame.$$.bind(frame);- (frame as any).$$ = async (selector: string) => {- const els = await origFrame$$(selector);- for (const el of els) {- patchSingleElementHandle(el, page, cfg, cursor, raw, rawKb, originals, stealth);- }- return els;- };- }-- // Patch frame.waitForSelector()- if (typeof frame.waitForSelector === 'function') {- const origFrameWaitForSelector = frame.waitForSelector.bind(frame);- (frame as any).waitForSelector = async (selector: string, options?: {- state?: 'attached' | 'detached' | 'visible' | 'hidden';- strict?: boolean;- timeout?: number;- }) => {- const el = await origFrameWaitForSelector(selector, options ?? {});- if (el) patchSingleElementHandle(el, page, cfg, cursor, raw, rawKb, originals, stealth);- return el;- };- }-}diff --git a/js/src/human/engine.ts b/js/src/human/engine.tsnew file mode 100644index 0000000..0bee2fa--- /dev/null+++ b/js/src/human/engine.ts@@ -0,0 +1,1055 @@+/**+ * Unified humanized action pipeline. Port of cloakbrowser/human/engine.py.+ *+ * One implementation drives page / frame / locator / element-handle actions:+ *+ * resolve (isolated world, Playwright selector engine, strict mode)+ * -> wait for element states (visible / enabled / editable / stable)+ * -> scroll into view with mouse-wheel bursts (page, iframes, containers)+ * -> Bezier move to a point inside the visible part of the element+ * -> hit-target check (element itself, and every ancestor <iframe>)+ * -> press / type+ *+ * Nothing falls back to Playwright's stock actions, and failures raise+ * Playwright `Error` / `TimeoutError`.+ */++import type { Frame, Page, ElementHandle, CDPSession } from 'playwright-core';+import { errors } from 'playwright-core';+import { type HumanConfig, mergeConfig, rand, randRange, randIntRange, sleep } from './config.js';+import { NEARBY_KEYS, SHIFT_SYMBOLS, SHIFT_SYMBOL_CODES, SHIFT_SYMBOL_KEYCODES } from './keyboard.js';+import { bezier, easeInOut, randomControlPoints, clickTarget } from './mouse.js';+import * as fields from './fields.js';+import { HELPERS, StaleElement, Worlds, intersect, type Rect } from './world.js';++export const ENTER_FRAME = ' >> internal:control=enter-frame >> ';+const ENTER_FRAME_SPLIT = /\s*>>\s*internal:control=enter-frame\s*>>\s*/;++const CLICK_STATES = ['visible', 'enabled', 'stable'];+const HOVER_STATES = ['visible', 'stable'];+const INPUT_STATES = ['visible', 'enabled', 'editable'];+const FOCUS_STATES = ['visible', 'enabled'];+const RETRY_MS = [0, 20, 100, 100, 500];++const sleepMs = (ms: number) => (ms > 0 ? sleep(ms) : Promise.resolve());++export class CursorState {+ x = 0;+ y = 0;+ initialized = false;+}++/** Original (un-humanized) input primitives of one page. */+export interface RawInput {+ move(x: number, y: number, options?: { steps?: number }): Promise<void>;+ down(options?: { button?: string; clickCount?: number }): Promise<void>;+ up(options?: { button?: string; clickCount?: number }): Promise<void>;+ wheel(dx: number, dy: number): Promise<void>;+ keyDown(key: string): Promise<void>;+ keyUp(key: string): Promise<void>;+ keyPress(key: string, options?: { delay?: number }): Promise<void>;+ insertText(text: string): Promise<void>;+}++// ---------------------------------------------------------------------------+// Targets+// ---------------------------------------------------------------------------++export class Target {+ description: string;+ constructor(public frame: Frame, public selector: string | null = null, public strict = false,+ public handle: ElementHandle | null = null) {+ this.description = selector !== null ? `locator(${JSON.stringify(selector)})` : 'element handle';+ }+}++export class Resolved {+ constructor(public frame: Frame, public id: number) {}+}++export class Deadline {+ private end: number | null;+ constructor(public timeout: number) {+ this.end = timeout ? Date.now() + timeout : null;+ }+ remaining(): number { return this.end === null ? Infinity : Math.max(0, this.end - Date.now()); }+ /** Remaining budget as a Playwright timeout value (0 = no limit). */+ left(): number { return this.end === null ? 0 : Math.max(1, this.remaining()); }+ expired(): boolean { return this.end !== null && Date.now() >= this.end; }+}++/** Internal: the current attempt failed for `reason`; retry until timeout. */+class Retry extends Error {+ constructor(public reason: string) { super(reason); }+}++/** Options every humanized action understands (Playwright names + ours). */+export interface Opts {+ timeout?: number;+ force?: boolean;+ trial?: boolean;+ position?: { x: number; y: number } | null;+ button?: 'left' | 'right' | 'middle';+ clickCount?: number;+ delay?: number;+ modifiers?: string[];+ steps?: number;+ sourcePosition?: { x: number; y: number };+ targetPosition?: { x: number; y: number };+ human_config?: Partial<HumanConfig> | null;+ [k: string]: any;+ /** internal */+ _deadline?: Deadline;+ _nested?: boolean;+ _aim?: any[];+ scroll?: string;+}++const err = (msg: string) => new Error(msg);++type Action = (r: Resolved, x: number, y: number, cfg: HumanConfig) => Promise<void>;+type Box = Rect & { bl: number; bt: number; clip: Rect; visible: Rect; scroller?: Rect };++const isAsciiAlnum = (ch: string) => /^[a-zA-Z0-9]$/.test(ch);+const isAscii = (ch: string) => (ch.codePointAt(0) ?? 128) < 128;+const isUpper = (ch: string) => /^[A-Z]$/.test(ch);++// ---------------------------------------------------------------------------+// Human+// ---------------------------------------------------------------------------++export class Human {+ readonly worlds: Worlds;+ private _platform: string | null = null;+ private handleIds = new Map<string, [Frame, number, number]>();++ constructor(readonly page: Page, public cfg: HumanConfig, public cursor: CursorState, readonly raw: RawInput) {+ this.worlds = new Worlds(page);+ }++ // -- configuration ------------------------------------------------------++ callCfg(overrides?: Partial<HumanConfig> | null): HumanConfig {+ return mergeConfig(this.cfg, overrides ?? undefined);+ }++ timeout(frame: Frame, timeout?: number): number {+ const t = (frame as any)._timeout({ timeout });+ return typeof t === 'number' ? t : t.timeout;+ }++ /** Deadline for an action; nested sub-actions share their caller's. */+ deadline(target: Target, opts: Opts): Deadline {+ return opts._deadline ?? new Deadline(this.timeout(target.frame, opts.timeout));+ }++ /** Persona platform (`navigator.platform` read in the isolated world). */+ async platform(): Promise<string> {+ if (this._platform === null) {+ try { this._platform = String(await this.worlds.call(this.page.mainFrame(), 'platform')); }+ catch { this._platform = ''; }+ }+ return this._platform;+ }++ async isMac(): Promise<boolean> { return (await this.platform()).toLowerCase().startsWith('mac'); }+ async selectAllKey(): Promise<string> { return (await this.isMac()) ? 'Meta+a' : 'Control+a'; }++ private async modifier(key: string): Promise<string> {+ if (key === 'ControlOrMeta') return (await this.isMac()) ? 'Meta' : 'Control';+ return key;+ }++ // -- cursor -------------------------------------------------------------++ async ensureCursor(cfg?: HumanConfig): Promise<void> {+ if (!this.cursor.initialized) {+ const c = cfg ?? this.cfg;+ this.cursor.x = rand(c.initial_cursor_x[0], c.initial_cursor_x[1]);+ this.cursor.y = rand(c.initial_cursor_y[0], c.initial_cursor_y[1]);+ await this.raw.move(this.cursor.x, this.cursor.y);+ this.cursor.initialized = true;+ }+ }++ /** Bezier move from the current cursor position to (x, y). */+ async moveTo(x: number, y: number, cfg: HumanConfig): Promise<void> {+ await this.ensureCursor(cfg);+ const sx = this.cursor.x, sy = this.cursor.y;+ const dist = Math.hypot(x - sx, y - sy);+ if (dist >= 1) {+ const steps = Math.max(cfg.mouse_min_steps, Math.min(cfg.mouse_max_steps, Math.round(dist / cfg.mouse_steps_divisor)));+ const start = { x: sx, y: sy }, end = { x, y };+ const [cp1, cp2] = randomControlPoints(start, end);+ let burst = 0;+ const burstSize = randIntRange(cfg.mouse_burst_size);+ for (let i = 1; i <= steps; i++) {+ const progress = i / steps;+ if (i === steps) { await this.raw.move(x, y); continue; } // exact end point+ const pt = bezier(start, cp1, cp2, end, easeInOut(progress));+ const wobble = Math.sin(Math.PI * progress) * cfg.mouse_wobble_max;+ await this.raw.move(Math.round(pt.x + (Math.random() - 0.5) * 2 * wobble),+ Math.round(pt.y + (Math.random() - 0.5) * 2 * wobble));+ burst++;+ if (burst >= burstSize) { await sleepMs(randRange(cfg.mouse_burst_pause)); burst = 0; }+ }+ if (Math.random() < cfg.mouse_overshoot_chance) {+ const angle = Math.atan2(y - sy, x - sx);+ const over = randRange(cfg.mouse_overshoot_px);+ await this.raw.move(Math.round(x + Math.cos(angle) * over), Math.round(y + Math.sin(angle) * over));+ await sleepMs(rand(30, 70));+ await this.raw.move(x, y);+ }+ }+ this.cursor.x = x; this.cursor.y = y;+ }++ async idle(cfg: HumanConfig): Promise<void> {+ if (!cfg.idle_between_actions) return;+ await this.ensureCursor(cfg);+ const end = Date.now() + rand(cfg.idle_between_duration[0], cfg.idle_between_duration[1]) * 1000;+ let x = this.cursor.x, y = this.cursor.y;+ while (Date.now() < end) {+ x += (Math.random() - 0.5) * 2 * cfg.idle_drift_px;+ y += (Math.random() - 0.5) * 2 * cfg.idle_drift_px;+ await this.raw.move(Math.round(x), Math.round(y));+ await sleepMs(Math.min(randRange(cfg.idle_pause_range), Math.max(0, end - Date.now())));+ }+ // Drift is noise around the resting point, not a new position.+ await this.raw.move(this.cursor.x, this.cursor.y);+ }++ // -- resolution ---------------------------------------------------------++ /** Resolve once. Throws `Retry` (not yet there) or `Error` (final). */+ async resolve(target: Target, deadline: Deadline): Promise<Resolved> {+ if (target.handle) return this.resolveHandle(target.handle, deadline);+ let frame = target.frame;+ const parts = target.selector!.split(ENTER_FRAME_SPLIT);+ for (let i = 0; i < parts.length; i++) {+ const res = await this.worlds.call(frame, 'resolve', parts[i], !!target.strict, 0);+ if (res.status === 'none') throw new Retry(`waiting for ${target.description}`);+ if (res.status === 'strict' || res.status === 'error') throw err(res.message);+ if (i === parts.length - 1) return new Resolved(frame, res.id);+ const child = await this.worlds.contentFrame(frame, res.id);+ if (!child) throw new Retry(`waiting for the frame of ${target.description}`);+ frame = child;+ }+ throw err('unreachable');+ }++ async resolveHandle(handle: ElementHandle, _deadline?: Deadline): Promise<Resolved> {+ const frame: Frame = (handle as any)._frame;+ const rec = await this.worlds.ready(frame);+ const guid: string = (handle as any)._guid;+ const cached = this.handleIds.get(guid);+ if (cached && cached[0] === frame && cached[1] === rec.ctx) return new Resolved(frame, cached[2]);+ // An ElementHandle carries no identity our context can read, so find+ // the element with exactly its border box.+ const box = await handle.boundingBox();+ if (!box) {+ // Resolved in an earlier document of this frame and gone now+ // (a same-document navigation keeps the element, and its box).+ if (cached && cached[0] === frame) throw err('Element is not attached to the DOM');+ throw new Retry('element is not visible');+ }+ const [ox, oy] = await this.worlds.frameGeometry(frame);+ const res = await this.worlds.call(frame, 'matchRect', box.x - ox, box.y - oy, box.width, box.height);+ if (res.count !== 1) {+ throw err('cloakbrowser humanize: cannot identify the element behind this ElementHandle inside the ' ++ 'isolated world (it shares its box with another element); use a Locator instead');+ }+ this.handleIds.set(guid, [frame, rec.ctx!, res.id]);+ return new Resolved(frame, res.id);+ }++ /** Resolve and wait for `states`; Playwright-style retry + timeout. */+ waitFor(target: Target, states: string[], deadline: Deadline, api: string, force = false): Promise<Resolved> {+ return this.retry(api, target, deadline, () => this.attemptStates(target, states, deadline, force));+ }++ async attemptStates(target: Target, states: string[], deadline: Deadline, force: boolean): Promise<Resolved> {+ const r = await this.resolve(target, deadline);+ if (force) return r;+ const res = await this.worlds.call(r.frame, 'states', r.id, states);+ if (res === null || res === undefined) return r;+ if (res.error) throw err(res.error);+ if (res.missing === 'attached') {+ if (target.handle) throw err('Element is not attached to the DOM');+ throw new Retry('element was detached from the DOM, retrying');+ }+ throw new Retry(`element is not ${res.missing}`);+ }++ async retry<T>(api: string, target: Target, deadline: Deadline, attempt: () => Promise<T>): Promise<T> {+ const reasons: string[] = [];+ const note = (r: string) => { if (reasons[reasons.length - 1] !== r) reasons.push(r); };+ for (let n = 0; ; n++) {+ try {+ return await attempt();+ } catch (e: any) {+ if (e instanceof StaleElement) {+ if (target.handle) throw err(`${api}: Element is not attached to the DOM`);+ note('element was detached from the DOM, retrying');+ } else if (e instanceof Retry) {+ note(e.reason);+ } else {+ const msg = String(e?.message ?? e);+ if (msg.startsWith(api)) throw e;+ const out = e instanceof errors.TimeoutError ? new errors.TimeoutError(`${api}: ${msg}`) : err(`${api}: ${msg}`);+ throw out;+ }+ }+ if (deadline.expired()) {+ const log = [`waiting for ${target.description}`, ...reasons.slice(-5)].map((r) => ` - ${r}`).join('\n');+ throw new errors.TimeoutError(`${api}: Timeout ${Math.round(deadline.timeout)}ms exceeded.\nCall log:\n${log}`);+ }+ await sleepMs(Math.min(RETRY_MS[Math.min(n, RETRY_MS.length - 1)], deadline.remaining()));+ }+ }++ // -- geometry -----------------------------------------------------------++ /** Element border box in viewport coordinates plus its visible clip. */+ async elementBox(r: Resolved): Promise<Box> {+ const g = await this.worlds.call(r.frame, 'geometry', r.id);+ if (!g) throw new StaleElement();+ const [ox, oy, frameClip] = await this.worlds.frameGeometry(r.frame);+ let clip = frameClip;+ const box: any = { x: g.x + ox, y: g.y + oy, width: g.width, height: g.height, bl: g.bl, bt: g.bt };+ const scroller = await this.worlds.call(r.frame, 'scroller', r.id);+ if (scroller) {+ const sc = { x: scroller.x + ox, y: scroller.y + oy, width: scroller.width, height: scroller.height };+ clip = intersect(clip, sc);+ box.scroller = sc;+ }+ box.clip = clip;+ box.visible = intersect(clip, box);+ return box;+ }++ // -- scrolling ----------------------------------------------------------++ /** Wheel-scroll until the element sits inside its visible clip (and, for+ * the main document, inside `scroll_target_zone` when the page can still+ * scroll that way). Returns the final box. */+ async scrollIntoView(r: Resolved, cfg: HumanConfig, deadline: Deadline): Promise<Box> {+ let box = await this.elementBox(r);+ const vp = await this.worlds.viewport();+ let stalled = 0, rounds = 0, overshot = false;+ while (stalled < 2 && rounds < 40 && !deadline.expired()) {+ const [dx, dy] = await this.neededScroll(r, box, vp, cfg);+ if (Math.abs(dx) < 1 && Math.abs(dy) < 1) break;+ rounds++;+ const area = box.clip.width > 4 && box.clip.height > 4 ? box.clip : { x: 0, y: 0, width: vp.width, height: vp.height };+ if (!this.inside(area)) {+ await this.moveTo(area.x + area.width * rand(0.3, 0.7), area.y + area.height * rand(0.3, 0.7), cfg);+ await sleepMs(randRange(cfg.scroll_pre_move_delay));+ }+ const before = [box.x, box.y];+ if (Math.abs(dy) >= 1) {+ await this.wheelBurst(0, dy, cfg, deadline);+ if (!overshot) {+ overshot = true;+ await this.overshoot(dy, cfg, deadline);+ }+ }+ if (Math.abs(dx) >= 1) await this.wheelBurst(dx, 0, cfg, deadline);+ await sleepMs(Math.min(randRange(cfg.scroll_settle_delay), deadline.remaining()));+ box = await this.elementBox(r);+ const moved = Math.abs(box.x - before[0]) + Math.abs(box.y - before[1]);+ stalled = moved < 1 ? stalled + 1 : 0;+ }+ return box;+ }++ private inside(a: Rect): boolean {+ const c = this.cursor;+ return a.x <= c.x && c.x <= a.x + a.width && a.y <= c.y && c.y <= a.y + a.height;+ }++ private async neededScroll(r: Resolved, box: Box, vp: { width: number; height: number }, cfg: HumanConfig): Promise<[number, number]> {+ const clip = box.clip;+ if (clip.width <= 0 || clip.height <= 0) {+ // The frame (or container) itself is out of view: bring it in first.+ return [0, (box.y + box.height / 2) - vp.height / 2];+ }+ let dy = 0, dx = 0;+ const top = box.y, bottom = box.y + box.height;+ const zone = cfg.scroll_target_zone;+ const mainDoc = !r.frame.parentFrame() && !box.scroller;+ if (mainDoc && box.height <= vp.height * (zone[1] - zone[0])) {+ const zt = vp.height * zone[0], zb = vp.height * zone[1];+ if (top < zt || bottom > zb) {+ dy = (top + box.height / 2) - vp.height * rand(zone[0], zone[1]);+ if (top >= clip.y - 1 && bottom <= clip.y + clip.height + 1) {+ // Fully visible but off-centre: only if the page can scroll that way.+ const doc = await this.worlds.call(this.page.mainFrame(), 'doc');+ if ((dy < 0 && doc.y <= 0) || (dy > 0 && doc.y >= doc.maxY)) dy = 0;+ }+ }+ } else if (box.height <= clip.height) {+ if (top < clip.y - 1 || bottom > clip.y + clip.height + 1) dy = (top + box.height / 2) - (clip.y + clip.height / 2);+ } else if (box.visible.height < clip.height * 0.5) {+ dy = top - clip.y - clip.height * 0.1;+ }+ // Horizontal (#521): containment only.+ const left = box.x, right = box.x + box.width;+ if (box.width <= clip.width) {+ if (left < clip.x - 1 || right > clip.x + clip.width + 1) dx = (left + box.width / 2) - (clip.x + clip.width / 2);+ } else if (box.visible.width <= 0) {+ dx = left - clip.x;+ }+ return [dx, dy];+ }++ /** Sometimes scroll a little past the target, pause, and wheel back+ * (`scroll_overshoot_chance` / `scroll_overshoot_px`). The next round of+ * `scrollIntoView` fixes whatever is left. */+ private async overshoot(dy: number, cfg: HumanConfig, deadline: Deadline): Promise<void> {+ if (Math.random() >= cfg.scroll_overshoot_chance || deadline.expired()) return;+ const sign = dy > 0 ? 1 : -1;+ await this.wheelBurst(0, Math.round(randRange(cfg.scroll_overshoot_px)) * sign, cfg, deadline);+ await sleepMs(Math.min(randRange(cfg.scroll_settle_delay), deadline.remaining()));+ const corrections = randIntRange([1, 2]);+ for (let i = 0; i < corrections && !deadline.expired(); i++) {+ await this.wheelBurst(0, Math.round(rand(40, 80)) * -sign, cfg, deadline);+ await sleepMs(Math.min(rand(100, 250), deadline.remaining()));+ }+ }++ /** One logical scroll: accelerate -> cruise -> decelerate in wheel ticks. */+ async wheelBurst(dx: number, dy: number, cfg: HumanConfig, deadline?: Deadline): Promise<void> {+ const total = dy ? Math.abs(dy) : Math.abs(dx);+ const sign = (dy || dx) > 0 ? 1 : -1;+ const accel = randIntRange(cfg.scroll_accel_steps), decel = randIntRange(cfg.scroll_decel_steps);+ const avg = (cfg.scroll_delta_base[0] + cfg.scroll_delta_base[1]) / 2;+ const ticks = Math.max(1, Math.ceil(total / avg));+ let sent = 0;+ for (let i = 0; i < ticks; i++) {+ if (sent >= total || deadline?.expired()) break;+ const pause = (i < accel || i >= ticks - decel) ? randRange(cfg.scroll_pause_slow) : randRange(cfg.scroll_pause_fast);+ const tick = Math.min(total - sent, randRange(cfg.scroll_delta_base) * (1 + (Math.random() - 0.5) * 2 * cfg.scroll_delta_variance));+ // Split each tick into small wheel events like real inertia.+ let left = tick;+ while (left > 0.5) {+ const chunk = Math.min(left, rand(20, 40));+ const step = Math.round(chunk) * sign;+ if (step) await this.raw.wheel(dx ? step : 0, dy ? step : 0);+ left -= chunk;+ await sleepMs(rand(8, 20));+ }+ sent += tick;+ await sleepMs(pause);+ }+ }++ // -- pointer ------------------------------------------------------------++ private point(box: Box, position: { x: number; y: number } | null | undefined, isInput: boolean, cfg: HumanConfig): [number, number] {+ if (position) return [box.x + box.bl + position.x, box.y + box.bt + position.y];+ const vis = box.visible;+ if (vis.width <= 0 || vis.height <= 0) throw new Retry('element is outside of the viewport');+ // Aim inside the visible part, keep the input bias for text fields.+ const full = clickTarget(box, isInput, cfg);+ return [Math.min(Math.max(full.x, vis.x + 1), vis.x + vis.width - 1),+ Math.min(Math.max(full.y, vis.y + 1), vis.y + vis.height - 1)];+ }++ /** Exact aim points: a date-editor segment, or a fraction along a slider. */+ private aimPoint(box: Box, aim: any[]): [number, number] {+ let x: number, y: number;+ if (aim[0] === 'segment') {+ const seg = aim[1];+ x = box.x + seg.dx + rand(-2, 2); y = box.y + seg.dy + rand(-2, 2);+ } else {+ const frac = aim[1] as number, vertical = aim[2] as boolean;+ // Native thumbs are inset by about half their width (~8px) at both ends.+ if (vertical) {+ const inset = Math.min(8, box.height / 4);+ y = box.y + box.height - inset - frac * (box.height - 2 * inset);+ x = box.x + box.width / 2;+ } else {+ const inset = Math.min(8, box.width / 4);+ x = box.x + inset + frac * (box.width - 2 * inset);+ y = box.y + box.height / 2 + rand(-1.5, 1.5);+ }+ }+ const v = box.visible;+ if (!(v.x <= x && x <= v.x + v.width && v.y <= y && y <= v.y + v.height)) throw new Retry('element is outside of the viewport');+ return [x, y];+ }++ private async hit(r: Resolved, x: number, y: number): Promise<void> {+ const [ox, oy, clip] = await this.worlds.frameGeometry(r.frame);+ if (!(clip.x <= x && x <= clip.x + clip.width && clip.y <= y && y <= clip.y + clip.height)) {+ throw new Retry('element is outside of the viewport');+ }+ let desc = await this.worlds.call(r.frame, 'hit', r.id, x - ox, y - oy);+ if (!desc && r.frame.parentFrame()) desc = await this.worlds.ownersHit(r.frame, x, y);+ if (desc) throw new Retry(`${desc} intercepts pointer events`);+ }++ /**+ * Shared scroll -> move -> hit-check -> `action` sequence.+ * `hold`: modifier names held down while the cursor travels to the target+ * (Playwright's hover modifiers).+ */+ async pointerAction(api: string, target: Target, opts: Opts, states: string[], isInputHint: boolean | null = null,+ action: Action | null = null, hold?: string[]): Promise<Resolved> {+ let cfg = this.callCfg(opts.human_config);+ if (opts.steps) {+ cfg = mergeConfig(cfg, { mouse_min_steps: Math.trunc(opts.steps), mouse_max_steps: Math.trunc(opts.steps), mouse_overshoot_chance: 0 });+ }+ const deadline = this.deadline(target, opts);+ const force = !!opts.force, trial = !!opts.trial, position = opts.position;+ const noScroll = opts.scroll === 'none';+ await this.ensureCursor(cfg);+ if (!(opts._nested || opts._deadline)) await this.idle(cfg);++ const attempt = async (): Promise<Resolved> => {+ const r = await this.attemptStates(target, states, deadline, force);+ const box = noScroll ? await this.elementBox(r) : await this.scrollIntoView(r, cfg, deadline);+ let isInput: boolean;+ if (isInputHint === null) {+ const info = await this.worlds.call(r.frame, 'info', r.id);+ isInput = info.tag === 'input' || info.tag === 'textarea' || info.editable;+ } else {+ isInput = isInputHint;+ }+ const [x, y] = opts._aim ? this.aimPoint(box, opts._aim) : this.point(box, position, isInput, cfg);+ if (!force) await this.hit(r, x, y);+ if (trial) return r;+ const keys: string[] = [];+ for (const m of hold ?? []) keys.push(await this.modifier(m));+ for (const k of keys) await this.raw.keyDown(k);+ try {+ await this.moveTo(x, y, cfg);+ } finally {+ for (const k of [...keys].reverse()) await this.raw.keyUp(k);+ }+ // The page may replace or remove the target while the cursor travels;+ // never press on whatever is under it now (even with force). Locators+ // re-resolve and run the whole move again.+ if (!(await this.worlds.call(r.frame, 'connected', r.id))) throw new StaleElement();+ if (!force) await this.hit(r, this.cursor.x, this.cursor.y);+ if (action) await action(r, this.cursor.x, this.cursor.y, cfg);+ return r;+ };+ return this.retry(api, target, deadline, attempt);+ }++ async pressMouse(cfg: HumanConfig, isInput: boolean, button = 'left', clickCount = 1, delay?: number,+ modifiers?: string[]): Promise<void> {+ const mods: string[] = [];+ for (const m of modifiers ?? []) mods.push(await this.modifier(m));+ await sleepMs(randRange(isInput ? cfg.click_aim_delay_input : cfg.click_aim_delay_button));+ for (const m of mods) await this.raw.keyDown(m);+ try {+ const count = Math.max(1, Math.trunc(clickCount));+ for (let n = 1; n <= count; n++) {+ const hold = delay ?? randRange(isInput ? cfg.click_hold_input : cfg.click_hold_button);+ await this.raw.down({ button, clickCount: n });+ await sleepMs(hold);+ await this.raw.up({ button, clickCount: n });+ if (n < count) await sleepMs(delay ?? rand(60, 140));+ }+ } finally {+ for (const m of [...mods].reverse()) await this.raw.keyUp(m);+ }+ }++ // -- public actions -----------------------------------------------------++ async click(target: Target, opts: Opts, api = 'click', clickCount?: number): Promise<void> {+ const count = clickCount ?? Math.trunc(opts.clickCount || 1);+ await this.pointerAction(api, target, opts, CLICK_STATES, null, async (r, _x, _y, cfg) => {+ const info = await this.worlds.call(r.frame, 'info', r.id);+ const isInput = info.tag === 'input' || info.tag === 'textarea' || info.editable;+ await this.pressMouse(cfg, isInput, opts.button || 'left', count, opts.delay, opts.modifiers);+ });+ }++ async hover(target: Target, opts: Opts, api = 'hover'): Promise<void> {+ const mods = opts.modifiers;+ // Playwright holds the modifiers while the mouse moves onto the target.+ await this.pointerAction(api, target, opts, HOVER_STATES, false, undefined, mods);+ }++ async tap(target: Target, opts: Opts, api = 'tap'): Promise<void> {+ await this.click(target, { ...opts, clickCount: 1 }, api);+ }++ /**+ * Focus by a human click unless already focused. Returns [r, clickedIn]:+ * clickedIn is true when this call clicked and focus landed in the target.+ * With requireFocus=false (press / type) a click that does not move focus is+ * fine, as in Playwright: the keys go to whatever handles them (a <canvas>,+ * document-level key handlers).+ */+ async focusElement(target: Target, opts: Opts, api: string, _cfg: HumanConfig, deadline: Deadline,+ requireFocus = true): Promise<[Resolved, boolean]> {+ const r = await this.waitFor(target, FOCUS_STATES, deadline, api, !!opts.force);+ let info = await this.worlds.call(r.frame, 'info', r.id);+ if (info.focused) return [r, false];+ // A person focuses a field by clicking it: scroll it into view with the+ // wheel and click. When it cannot be brought on screen at all the click+ // times out with "element is outside of the viewport" -- no silent+ // programmatic focus.+ await this.click(target, { _deadline: deadline, force: opts.force, human_config: opts.human_config }, api);+ info = await this.worlds.call(r.frame, 'info', r.id);+ if (info.focused || (await this.focusMovedInto(r))) return [r, true];+ if (requireFocus) {+ throw err(`${api}: Error: element did not receive focus when clicked (it may not be focusable): ${info.preview}`);+ }+ return [r, false];+ }++ /** The click landed but focus went to a focusable child: accept it. */+ private async focusMovedInto(r: Resolved): Promise<boolean> {+ const act = await this.worlds.call(r.frame, 'activeValue');+ if (!act?.tag) return false;+ return !!(await this.worlds.evaluate(r.frame,+ `(() => { const e = ${HELPERS}.el(${r.id}); const a = document.activeElement; return !!a && (e === a || e.contains(a)); })()`));+ }++ async caretToEnd(r: Resolved): Promise<void> {+ const info = await this.worlds.call(r.frame, 'info', r.id);+ if (info.tag === 'input') {+ if (!(await this.worlds.call(r.frame, 'caretAtEnd', r.id))) await this.raw.keyPress('End');+ } else {+ await this.raw.keyPress('Control+End');+ }+ await sleepMs(rand(20, 60));+ }++ private async keys(key: string): Promise<string> {+ return key.includes('ControlOrMeta') ? key.split('ControlOrMeta').join(await this.modifier('ControlOrMeta')) : key;+ }++ async press(target: Target, key: string, opts: Opts, api = 'press'): Promise<void> {+ const cfg = this.callCfg(opts.human_config);+ const deadline = this.deadline(target, opts);+ await this.focusElement(target, opts, api, cfg, deadline, false);+ await sleepMs(rand(50, 150));+ const k = await this.keys(key);+ await this.raw.keyPress(k, opts.delay !== undefined ? { delay: opts.delay } : undefined);+ }++ async type(target: Target, text: string, opts: Opts, api = 'type'): Promise<void> {+ const cfg = this.callCfg(opts.human_config);+ const deadline = this.deadline(target, opts);+ await sleepMs(randRange(cfg.field_switch_delay));+ const [r, clickedIn] = await this.focusElement(target, opts, api, cfg, deadline, false);+ if (clickedIn) await this.caretToEnd(r);+ await sleepMs(rand(100, 250));+ const info = await this.worlds.call(r.frame, 'info', r.id);+ await this.typeText(text, cfg, r.frame, info, opts.delay);+ }++ async fill(target: Target, value: string, opts: Opts, api = 'fill'): Promise<void> {+ const cfg = this.callCfg(opts.human_config);+ const deadline = this.deadline(target, opts);+ const force = !!opts.force;+ let r = await this.waitFor(target, INPUT_STATES, deadline, api, force);+ let info = await this.worlds.call(r.frame, 'info', r.id);+ const kind = fields.classify(info.tag, info.type, info.editable);+ if (kind === fields.NOT_FILLABLE) throw err(`${api}: Error: ${fields.notFillableMessage(info.tag, info.type)}`);+ if (info.type === 'number') {+ const v = fields.validateNumber(value);+ if (v === null) throw err(`${api}: Error: Cannot type text into input[type=number]`);+ value = v;+ }+ if (kind === fields.SET) {+ value = fields.normalizeSetValue(info.type, value);+ await sleepMs(randRange(cfg.field_switch_delay));+ if (info.type === 'range') await this.setRange(target, r, value, opts, api, cfg, deadline);+ else if (info.type === 'color') this.setColor(api);+ else await this.setDatetime(target, r, info.type, value, opts, api, cfg, deadline);+ return;+ }+ await sleepMs(randRange(cfg.field_switch_delay));+ [r] = await this.focusElement(target, opts, api, cfg, deadline);+ await sleepMs(rand(100, 250));+ info = await this.worlds.call(r.frame, 'info', r.id);+ if (info.value) {+ await this.raw.keyPress(await this.selectAllKey());+ await sleepMs(rand(30, 80));+ await this.raw.keyPress('Backspace');+ await sleepMs(rand(50, 150));+ info = await this.worlds.call(r.frame, 'info', r.id);+ if (info.value) {+ // Some widgets ignore select-all; clear what is left by keys.+ await this.caretToEnd(r);+ for (let i = 0; i < info.value.length; i++) {+ await this.raw.keyPress('Backspace');+ await sleepMs(rand(15, 40));+ }+ }+ }+ if (value) await this.typeText(value, cfg, r.frame, info, undefined);+ }++ async clear(target: Target, opts: Opts, api = 'clear'): Promise<void> {+ await this.fill(target, '', opts, api);+ }++ async setChecked(target: Target, checked: boolean, opts: Opts, api: string): Promise<void> {+ const deadline = this.deadline(target, opts);+ const r = await this.waitFor(target, CLICK_STATES, deadline, api, !!opts.force);+ let state = await this.worlds.call(r.frame, 'checked', r.id);+ if (state.error) throw err(`${api}: Error: ${state.error}`);+ if (state.checked === checked) return;+ if (state.radio && !checked) {+ throw err(`${api}: Error: Cannot uncheck radio button. Radio buttons can only be unchecked by selecting another radio button in the same group.`);+ }+ await this.click(target, {+ force: opts.force, position: opts.position, trial: opts.trial, human_config: opts.human_config, _deadline: deadline,+ }, api);+ if (opts.trial) return;+ state = await this.worlds.call(r.frame, 'checked', r.id);+ if (state.checked !== checked) throw err(`${api}: Error: Clicking the checkbox did not change its state`);+ }++ // -- value inputs: what a person does --------------------------------++ /** date / time / datetime-local / month / week: click the first segment+ * of the native editor and type each part with the keyboard. Segment order+ * comes from the editor itself, so any locale works. */+ async setDatetime(target: Target, r: Resolved, inputType: string, value: string, opts: Opts, api: string,+ cfg: HumanConfig, deadline: Deadline): Promise<void> {+ let parts = fields.datetimeParts(inputType, value);+ if (!parts) throw err(`${api}: Error: Malformed value`);+ const segs = await this.worlds.editorFields(r.frame, r.id);+ const kinds = segs.map((s) => s.kind);+ parts = fields.use24h(parts, kinds.includes('ampm'));+ if (!segs.length || kinds.some((k) => !(k in parts!) && k !== 'ampm')) {+ throw err(`${api}: Error: unsupported date/time editor layout ${JSON.stringify(kinds)}`);+ }+ await this.pointerAction(api, target, { ...opts, _deadline: deadline, position: null, _aim: ['segment', segs[0]] },+ INPUT_STATES, true, (_rr, _x, _y, c) => this.pressMouse(c, true));+ await sleepMs(rand(80, 200));+ const current = fields.datetimeParts(inputType, (await this.worlds.call(r.frame, 'value', r.id)) || '');+ for (let i = 0; i < segs.length; i++) {+ const kind = segs[i].kind;+ if (inputType === 'month' && kind === 'month' && current) {+ // Shown as a month name; over an existing month Chromium's digit+ // matching is unreliable, so step with the arrow keys.+ const diff = parseInt(parts.month, 10) - parseInt(current.month, 10);+ for (let k = 0; k < Math.abs(diff); k++) {+ await this.raw.keyPress(diff > 0 ? 'ArrowUp' : 'ArrowDown');+ await sleepMs(rand(60, 140));+ }+ } else if (kind === 'ampm') {+ await this.typeChar((parts.hour24 ?? 0) >= 12 ? 'P' : 'A', cfg);+ } else {+ const digits: string = parts[kind];+ for (let j = 0; j < digits.length; j++) {+ await this.typeChar(digits[j], cfg);+ if (j < digits.length - 1) {+ // The editor forgets a partial entry after ~1 s without a key;+ // keep the gap inside a segment short.+ await sleepMs(Math.min(450, Math.max(40, cfg.typing_delay + (Math.random() - 0.5) * 2 * cfg.typing_delay_spread)));+ }+ }+ }+ if (i < segs.length - 1 && !fields.segmentAutoAdvances(kind, parts, inputType)) await this.raw.keyPress('ArrowRight');+ await sleepMs(rand(60, 160));+ }+ const got = await this.worlds.call(r.frame, 'value', r.id);+ if (got !== value) throw err(`${api}: Error: the date/time editor produced ${JSON.stringify(got)} instead of ${JSON.stringify(value)}`);+ }++ /** Slider: click on the track near the wanted value, then nudge with arrow+ * keys until it is exact. */+ async setRange(target: Target, r: Resolved, value: string, opts: Opts, api: string, _cfg: HumanConfig,+ deadline: Deadline): Promise<void> {+ const info = await this.worlds.call(r.frame, 'rangeInfo', r.id);+ const want = Number(value);+ if (value === '' || Number.isNaN(want)) throw err(`${api}: Error: Malformed value`);+ const span = info.max - info.min;+ let frac = span <= 0 ? 0.5 : Math.min(1, Math.max(0, (want - info.min) / span));+ if (info.rtl && !info.vertical) frac = 1 - frac;+ await this.pointerAction(api, target, { ...opts, _deadline: deadline, position: null, _aim: ['fraction', frac, info.vertical] },+ INPUT_STATES, false, (_rr, _x, _y, c) => this.pressMouse(c, false));+ const read = async () => Number(await this.worlds.call(r.frame, 'value', r.id));+ for (let k = 0; k < 400; k++) {+ const cur = await read();+ if (Math.abs(cur - want) < 1e-9 || (info.step && Math.abs(cur - want) < info.step / 2)) break;+ const up = cur < want;+ const key = !info.rtl ? (up ? 'ArrowRight' : 'ArrowLeft') : (up ? 'ArrowLeft' : 'ArrowRight');+ await this.raw.keyPress(key);+ await sleepMs(rand(40, 110));+ if ((await read()) === cur) break; // cannot move further (min/max reached)+ }+ const got = await this.worlds.call(r.frame, 'value', r.id);+ if (Number(got) !== this.rangeSnap(info, want)) throw err(`${api}: Error: slider stopped at ${got} instead of ${value}`);+ }++ private rangeSnap(info: any, want: number): number {+ let v = Math.min(info.max, Math.max(info.min, want));+ if (info.step) v = Math.min(info.max, info.min + Math.round((v - info.min) / info.step) * info.step);+ return v;+ }++ /** <input type=color> opens an OS colour dialog that page input cannot+ * drive. Setting the value silently would hide a robot-only path. */+ private setColor(api: string): never {+ throw err(`${api}: Error: <input type=color> opens a native colour picker that cannot be operated with ` ++ 'human input; set it with page._original.fill(...) if a programmatic value is acceptable');+ }++ /** Pick options like a person: a dropdown is opened with a click and moved+ * with arrow keys + Enter; a list box gets clicks on the options+ * (Ctrl/Cmd-click to add more in a multi-select). */+ async selectOption(target: Target, options: any[], handles: ElementHandle[], opts: Opts, api = 'selectOption'): Promise<string[]> {+ const cfg = this.callCfg(opts.human_config);+ const deadline = this.deadline(target, opts);+ const force = !!opts.force;+ const [r, p] = await this.retry(api, target, deadline, async (): Promise<[Resolved, any]> => {+ const rr = await this.attemptStates(target, ['visible', 'enabled'], deadline, force);+ const ids: number[] = [];+ for (const h of handles) ids.push((await this.resolveHandle(h, deadline)).id);+ const res = await this.worlds.call(rr.frame, 'selectPlan', rr.id, options, ids);+ if (res.error) throw err(res.error);+ if (res.retry) throw new Retry(res.retry);+ return [rr, res];+ });+ if (!p.listbox) await this.selectDropdown(target, r, p.targets.length ? p.targets[0] : null, p, opts, api, deadline);+ else await this.selectListbox(target, r, p, opts, api, cfg, deadline);+ const state = await this.worlds.call(r.frame, 'selectState', r.id);+ const sorted = (a: number[]) => JSON.stringify([...a].sort((x, y) => x - y));+ if (sorted(state.selected) !== sorted(p.targets)) {+ throw err(`${api}: Error: selection ended as ${JSON.stringify(state.values)} instead of ${JSON.stringify(p.values)}`);+ }+ return state.values;+ }++ private async selectDropdown(target: Target, r: Resolved, index: number | null, p: any, opts: Opts, api: string,+ deadline: Deadline): Promise<void> {+ if (index === null) throw err(`${api}: Error: a dropdown always keeps one option selected`);+ const state = await this.worlds.call(r.frame, 'selectState', r.id);+ if (state.current === index) {+ await this.hover(target, { _deadline: deadline, human_config: opts.human_config }, api);+ return;+ }+ await this.click(target, { _deadline: deadline, force: opts.force, human_config: opts.human_config }, api);+ await sleepMs(rand(200, 450)); // popup opens; eyes find the option+ if (process.platform === 'darwin') {+ // macOS shows a native popup that ignores arrow keys sent as page+ // input; type-ahead on the option's label still selects it.+ const cfg = this.callCfg(opts.human_config);+ for (const ch of p.labels[0] as string) {+ if (ch.charCodeAt(0) < 128) {+ await this.typeChar(ch, cfg);+ } else { // no US-layout key: send the character itself, like a native layout does+ const session: CDPSession = await this.worlds.session();+ await session.send('Input.dispatchKeyEvent', { type: 'keyDown', key: ch, text: ch, unmodifiedText: ch });+ await sleepMs(randRange(cfg.key_hold));+ await session.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });+ }+ await sleepMs(rand(60, 140)); // type-ahead resets after ~1s of silence+ }+ await this.raw.keyPress('Enter');+ await sleepMs(rand(80, 160));+ return;+ }+ const nav: boolean[] = p.navigable;+ let cur: number = state.current;+ for (let k = 0; k <= nav.length; k++) {+ if (cur === index) break;+ const step = index > cur ? 1 : -1;+ let nxt = cur + step;+ while (nxt >= 0 && nxt < nav.length && !nav[nxt]) nxt += step;+ if (!(nxt >= 0 && nxt < nav.length)) break;+ await this.raw.keyPress(step > 0 ? 'ArrowDown' : 'ArrowUp');+ await sleepMs(rand(70, 180));+ cur = nxt;+ }+ await sleepMs(rand(100, 250));+ await this.raw.keyPress('Enter');+ await sleepMs(rand(80, 160));+ }++ private async selectListbox(target: Target, r: Resolved, p: any, opts: Opts, api: string, cfg: HumanConfig,+ deadline: Deadline): Promise<void> {+ const state = await this.worlds.call(r.frame, 'selectState', r.id);+ const want: number[] = [...p.targets];+ const sorted = (a: number[]) => JSON.stringify([...a].sort((x, y) => x - y));+ if (sorted(state.selected) === sorted(want)) {+ await this.hover(target, { _deadline: deadline, human_config: opts.human_config }, api);+ return;+ }+ if (!want.length) throw err(`${api}: Error: deselecting every option is not something a click can do`);+ const addKey = (await this.isMac()) ? 'Meta' : 'Control';+ let first = true;+ for (const idx of want) {+ const oid = await this.worlds.call(r.frame, 'optionId', r.id, idx);+ const label = new Target(r.frame, null);+ label.description = `option #${idx}`;+ // A plain click on the first option replaces the selection; further+ // options are added with Ctrl/Cmd held, as a person does.+ await this.clickResolved(new Resolved(r.frame, oid), label, cfg, deadline, api, first ? [] : [addKey]);+ first = false;+ await sleepMs(rand(120, 300));+ }+ }++ /** Scroll / move / hit-check / click an already resolved element. */+ private async clickResolved(r: Resolved, label: Target, cfg: HumanConfig, deadline: Deadline, api: string,+ modifiers: string[]): Promise<void> {+ await this.retry(api, label, deadline, async () => {+ const box = await this.scrollIntoView(r, cfg, deadline);+ const [x, y] = this.point(box, null, false, cfg);+ await this.hit(r, x, y);+ await this.moveTo(x, y, cfg);+ await this.hit(r, this.cursor.x, this.cursor.y);+ await this.pressMouse(cfg, false, 'left', 1, undefined, modifiers);+ });+ }++ async drag(source: Target, dest: Target, opts: Opts, api = 'dragAndDrop'): Promise<void> {+ const sub: Opts = {+ _deadline: this.deadline(source, opts), force: opts.force, human_config: opts.human_config,+ position: opts.sourcePosition, trial: opts.trial,+ };+ await this.idle(this.callCfg(opts.human_config));+ await this.hover(source, sub, api);+ if (opts.trial) {+ await this.hover(dest, { ...sub, position: opts.targetPosition, _nested: true }, api);+ return;+ }+ await sleepMs(rand(100, 200));+ await this.raw.down();+ try {+ await sleepMs(rand(80, 150));+ await this.hover(dest, { ...sub, position: opts.targetPosition, force: true, _nested: true }, api);+ await sleepMs(rand(80, 150));+ } finally {+ await this.raw.up();+ }+ }++ async focus(target: Target, opts: Opts, api = 'focus', move = false): Promise<void> {+ const deadline = this.deadline(target, opts);+ if (move) await this.hover(target, { timeout: opts.timeout, human_config: opts.human_config }, api);+ const r = await this.retry(api, target, deadline, () => this.resolve(target, deadline));+ await this.worlds.call(r.frame, 'focus', r.id);+ }++ async scrollIntoViewIfNeeded(target: Target, opts: Opts, api = 'scrollIntoViewIfNeeded'): Promise<void> {+ const cfg = this.callCfg(opts.human_config);+ const deadline = this.deadline(target, opts);+ await this.ensureCursor(cfg);+ await this.retry(api, target, deadline, async () => {+ const r = await this.attemptStates(target, ['visible', 'stable'], deadline, false);+ await this.scrollIntoView(r, cfg, deadline);+ });+ }++ // -- keyboard -----------------------------------------------------------++ /** Type `text` key by key into the focused element of `frame`. */+ async typeText(text: string, cfg: HumanConfig, frame: Frame, info: any, delay: number | undefined): Promise<void> {+ const tag = info?.tag ?? null;+ const mistypes = cfg.mistype_chance > 0 && tag !== null && fields.allowsMistype(tag, info?.type ?? null);+ const chars = [...text];+ for (let i = 0; i < chars.length; i++) {+ const ch = chars[i];+ if (!isAscii(ch)) {+ await sleepMs(randRange(cfg.key_hold));+ await this.raw.insertText(ch);+ } else {+ if (mistypes && isAsciiAlnum(ch) && Math.random() < cfg.mistype_chance) await this.typo(ch, cfg, frame);+ await this.typeChar(ch, cfg);+ }+ if (i < chars.length - 1) await this.betweenKeys(cfg, delay);+ }+ }++ private async typo(ch: string, cfg: HumanConfig, frame: Frame): Promise<void> {+ const lower = ch.toLowerCase();+ const near = NEARBY_KEYS[lower];+ if (!near) return;+ let wrong = near[Math.floor(Math.random() * near.length)];+ if (isUpper(ch)) wrong = wrong.toUpperCase();+ const before = await this.activeValue(frame);+ await this.typeChar(wrong, cfg);+ await sleepMs(randRange(cfg.mistype_delay_notice));+ const after = await this.activeValue(frame);+ if (before !== null && after === before) {+ // The page rejected the wrong key (mask / filter): nothing to undo.+ await sleepMs(randRange(cfg.mistype_delay_correct));+ return;+ }+ await this.raw.keyDown('Backspace');+ await sleepMs(randRange(cfg.key_hold));+ await this.raw.keyUp('Backspace');+ await sleepMs(randRange(cfg.mistype_delay_correct));+ }++ private async activeValue(frame: Frame): Promise<string | null> {+ try { return (await this.worlds.call(frame, 'activeValue'))?.value ?? null; } catch { return null; }+ }++ async typeChar(ch: string, cfg: HumanConfig): Promise<void> {+ if (isUpper(ch)) {+ await this.raw.keyDown('Shift');+ await sleepMs(randRange(cfg.shift_down_delay));+ await this.raw.keyDown(ch);+ await sleepMs(randRange(cfg.key_hold));+ await this.raw.keyUp(ch);+ await sleepMs(randRange(cfg.shift_up_delay));+ await this.raw.keyUp('Shift');+ } else if (SHIFT_SYMBOLS.has(ch)) {+ const session: CDPSession = await this.worlds.session();+ const code = SHIFT_SYMBOL_CODES[ch] || '';+ const vk = SHIFT_SYMBOL_KEYCODES[ch] || 0;+ await this.raw.keyDown('Shift');+ await sleepMs(randRange(cfg.shift_down_delay));+ await session.send('Input.dispatchKeyEvent', {+ type: 'keyDown', modifiers: 8, key: ch, code, windowsVirtualKeyCode: vk, text: ch, unmodifiedText: ch,+ });+ await sleepMs(randRange(cfg.key_hold));+ await session.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: 8, key: ch, code, windowsVirtualKeyCode: vk });+ await sleepMs(randRange(cfg.shift_up_delay));+ await this.raw.keyUp('Shift');+ } else {+ await this.raw.keyDown(ch);+ await sleepMs(randRange(cfg.key_hold));+ await this.raw.keyUp(ch);+ }+ }++ private async betweenKeys(cfg: HumanConfig, delay: number | undefined): Promise<void> {+ if (delay !== undefined && delay !== null) await sleepMs(delay);+ else if (Math.random() < cfg.typing_pause_chance) await sleepMs(randRange(cfg.typing_pause_range));+ else await sleepMs(Math.max(10, cfg.typing_delay + (Math.random() - 0.5) * 2 * cfg.typing_delay_spread));+ }++ /** `page.keyboard.type`: no target; mistypes only where safe. */+ async keyboardType(text: string, delay?: number): Promise<void> {+ const frame = this.page.mainFrame();+ let info: any = null;+ try { info = await this.worlds.call(frame, 'activeValue'); } catch { info = null; }+ if (info?.tag === 'iframe') info = null; // focus inside a child frame: value checks impossible+ await this.typeText(text, this.cfg, frame, info?.tag ? info : null, delay);+ }++ // -- raw mouse API ------------------------------------------------------++ async mouseMove(x: number, y: number, steps?: number): Promise<void> {+ if (steps !== undefined && steps !== null) {+ await this.ensureCursor();+ await this.raw.move(x, y, { steps });+ } else {+ await this.moveTo(x, y, this.cfg);+ }+ this.cursor.x = x; this.cursor.y = y;+ }++ async mouseClick(x: number, y: number, delay?: number, button?: string, clickCount?: number): Promise<void> {+ await this.moveTo(x, y, this.cfg);+ await this.pressMouse(this.cfg, false, button || 'left', clickCount || 1, delay);+ }+}diff --git a/js/src/human/errors.ts b/js/src/human/errors.tsnew file mode 100644index 0000000..784b630--- /dev/null+++ b/js/src/human/errors.ts@@ -0,0 +1,95 @@+/**+ * Error classes kept for API compatibility. The unified engine throws+ * Playwright-style `Error` / `TimeoutError` (with a call log) instead; these+ * classes remain exported so existing `instanceof` imports keep compiling.+ */++export class ActionabilityError extends Error {+ selector: string;+ check: string;++ constructor(selector: string, check: string, message: string) {+ super(`Element ${JSON.stringify(selector)} failed ${check} check: ${message}`);+ this.name = 'ActionabilityError';+ this.selector = selector;+ this.check = check;+ }+}++export class ElementNotAttachedError extends ActionabilityError {+ constructor(selector: string) {+ super(selector, 'attached', 'element not found in DOM');+ this.name = 'ElementNotAttachedError';+ }+}++export class ElementNotVisibleError extends ActionabilityError {+ constructor(selector: string) {+ super(selector, 'visible', 'element is not visible');+ this.name = 'ElementNotVisibleError';+ }+}++export class ElementNotStableError extends ActionabilityError {+ constructor(selector: string) {+ super(selector, 'stable', 'element position is still changing');+ this.name = 'ElementNotStableError';+ }+}++export class ElementNotEnabledError extends ActionabilityError {+ constructor(selector: string) {+ super(selector, 'enabled', 'element is disabled');+ this.name = 'ElementNotEnabledError';+ }+}++export class ElementNotEditableError extends ActionabilityError {+ constructor(selector: string) {+ super(selector, 'editable', 'element is not editable');+ this.name = 'ElementNotEditableError';+ }+}++export class ElementNotReceivingEventsError extends ActionabilityError {+ coveringTag: string;+ constructor(selector: string, coveringTag: string = 'unknown') {+ super(selector, 'pointer_events', `element is covered by <${coveringTag}>`);+ this.name = 'ElementNotReceivingEventsError';+ this.coveringTag = coveringTag;+ }+}++export class ElementTargetChangedError extends ActionabilityError {+ constructor(selector: string) {+ super(selector, 'target_identity', 'selector resolved to a different element before input dispatch');+ this.name = 'ElementTargetChangedError';+ }+}++// Raised by the previous humanize layer; the engine no longer throws them.++export class StealthDomError extends Error {+ constructor(message: string) {+ super(message);+ this.name = new.target.name;+ }+}++export class UnsupportedHumanizeSelectorError extends StealthDomError {+ constructor(selector: string) {+ super(`Humanized selector ${JSON.stringify(selector)} is not supported`);+ }+}++export class StealthWorldUnavailableError extends StealthDomError {+ constructor() {+ super('Humanized DOM read requires an active isolated world');+ }+}++export class StealthEvaluationError extends StealthDomError {+ constructor(selector: string) {+ super(`Isolated-world DOM evaluation failed for ${JSON.stringify(selector)}`);+ }+}diff --git a/js/src/human/fields.ts b/js/src/human/fields.tsnew file mode 100644index 0000000..33abeff--- /dev/null+++ b/js/src/human/fields.ts@@ -0,0 +1,106 @@+/**+ * Field classification for humanized text input. Port of+ * cloakbrowser/human/fields.py; mirrors Playwright's `InjectedScript.fill`+ * rules (playwright-core 1.63):+ *+ * - text-like inputs are typed into key by key;+ * - value inputs (date, range, ...) are operated through their native widget+ * the way a person does it (segments + keyboard, slider click + arrows);+ * - everything else (checkbox, file, hidden, radio, ...) cannot be filled.+ *+ * Mistypes are only simulated where a human plausibly makes and corrects them+ * and where the correction is safe: never in number/email/password/tel/url.+ */++export const TYPE_INTO = new Set(['', 'email', 'number', 'password', 'search', 'tel', 'text', 'url']);+export const SET_VALUE = new Set(['color', 'date', 'time', 'datetime-local', 'month', 'range', 'week']);+export const NO_MISTYPE = new Set(['number', 'email', 'password', 'tel', 'url']);++export const TYPE = 'type';+export const SET = 'set';+export const NOT_FILLABLE = 'reject';+export type FieldKind = typeof TYPE | typeof SET | typeof NOT_FILLABLE;++export function classify(tag: string | null, inputType: string | null, editable: boolean): FieldKind {+ const t = (tag ?? '').toLowerCase();+ if (t === 'input') {+ const it = (inputType ?? '').toLowerCase();+ if (TYPE_INTO.has(it)) return TYPE;+ if (SET_VALUE.has(it)) return SET;+ return NOT_FILLABLE;+ }+ if (t === 'textarea' || editable) return TYPE;+ return NOT_FILLABLE;+}++export function allowsMistype(tag: string | null, inputType: string | null): boolean {+ if ((tag ?? '').toLowerCase() !== 'input') return true;+ return !NO_MISTYPE.has((inputType ?? '').toLowerCase());+}++export function normalizeSetValue(inputType: string | null, value: string): string {+ let v = value.trim();+ if ((inputType ?? '').toLowerCase() === 'color') v = v.toLowerCase();+ return v;+}++/** Playwright rejects non-numeric text for input[type=number]; null = invalid. */+export function validateNumber(value: string): string | null {+ const v = value.trim();+ return Number.isNaN(Number(v)) ? null : v; // Playwright's own check+}++export function notFillableMessage(tag: string | null, inputType: string | null): string {+ if ((tag ?? '').toLowerCase() === 'input') return `Input of type "${(inputType ?? '').toLowerCase()}" cannot be filled`;+ return 'Element is not an <input>, <textarea> or [contenteditable] element';+}++// ---------------------------------------------------------------------------+// Native date/time editors+// ---------------------------------------------------------------------------++const DATE = '(?<year>\\d{4,6})-(?<month>\\d{2})-(?<day>\\d{2})';+const TIME = '(?<hour>\\d{2}):(?<minute>\\d{2})(?::(?<second>\\d{2})(?:\\.(?<millisecond>\\d{1,3}))?)?';+const DT_PATTERNS: Record<string, RegExp> = {+ date: new RegExp(`^${DATE}$`),+ month: /^(?<year>\d{4,6})-(?<month>\d{2})$/,+ week: /^(?<year>\d{4,6})-W(?<week>\d{2})$/,+ time: new RegExp(`^${TIME}$`),+ 'datetime-local': new RegExp(`^${DATE}T${TIME}$`),+};++const FULL_WIDTH: Record<string, number> = { month: 2, day: 2, week: 2, hour: 2, minute: 2, second: 2, millisecond: 3 };++export interface DateTimeParts { [k: string]: any; hour24?: number; }++/** Split an HTML date/time value into the keystrokes per editor segment+ * (null for a malformed value). `hour` is the 12-hour form shown next to an+ * AM/PM segment; `hour24` keeps the original hour. */+export function datetimeParts(inputType: string, value: string): DateTimeParts | null {+ const re = DT_PATTERNS[inputType];+ const m = re ? re.exec(value) : null;+ if (!m || !m.groups) return null;+ const parts: DateTimeParts = {};+ for (const [k, v] of Object.entries(m.groups)) if (v !== undefined) parts[k] = v;+ if (parts.hour !== undefined) {+ const h = parseInt(parts.hour, 10);+ parts.hour24 = h;+ parts.hour12 = String((h % 12) || 12).padStart(2, '0');+ parts.hour = parts.hour12;+ }+ if (parts.millisecond !== undefined) parts.millisecond = String(parts.millisecond).padEnd(3, '0');+ return parts;+}++/** Pick the hour digits matching the editor (with or without AM/PM). */+export function use24h(parts: DateTimeParts, hasAmpm: boolean): DateTimeParts {+ if (parts.hour24 !== undefined && !hasAmpm) return { ...parts, hour: String(parts.hour24).padStart(2, '0') };+ return parts;+}++/** Whether typing this segment's digits moves focus to the next segment. */+export function segmentAutoAdvances(kind: string, parts: DateTimeParts, inputType = ''): boolean {+ if (inputType === 'month' && kind === 'month') return false; // shown as a month name+ const width = FULL_WIDTH[kind];+ return width !== undefined && String(parts[kind] ?? '').length >= width;+}diff --git a/js/src/human/index.ts b/js/src/human/index.tsindex d00b348..c1c3301 100644--- a/js/src/human/index.ts+++ b/js/src/human/index.ts@@ -1,966 +1,32 @@/**- * Human-like behavioral layer for cloakbrowser (JS/TS).+ * Human-like behavioral layer for cloakbrowser (JS/TS, Playwright).*- * Activated via humanize: true in launch() / launchContext().- * Patches page methods to use Bezier mouse curves, realistic typing, and smooth scrolling.+ * Activated via `humanize: true` in launch() / launchContext().*- * Stealth-aware (fixes #110, #512):- * - Selector resolution, state, geometry, and revalidation use the CDP isolated world- * - Shift symbol typing uses CDP Input.dispatchKeyEvent for isTrusted=true events- * - Unsupported selectors and isolated-world failures raise typed errors+ * Every humanized action (page, frame, frameLocator, locator, element handle,+ * mouse, keyboard) runs through one engine (engine.ts):*- * Patches all interaction methods:- * click, dblclick, hover, type, fill, check, uncheck, selectOption,- * press, pressSequentially, tap, dragTo, clear + Frame-level equivalents.- *- * ELEMENTHANDLE-LEVEL:- * click, dblclick, hover, type, fill, press, selectOption,- * check, uncheck, setChecked, tap, focus- * + $, $$, waitForSelector (nested elements are also patched)- *- * page.$(), page.$$(), page.waitForSelector() and Frame equivalents- * return patched ElementHandles automatically.+ * - elements are resolved by Playwright's own selector engine running in a+ * CDP isolated world per frame (world.ts / injected.ts) -- full selector+ * syntax (role, label, text, `>>` chains, filters, frame locators) and+ * strict mode;+ * - scrolling uses mouse-wheel bursts, pointer movement uses Bezier curves,+ * every press is preceded by a hit-target check (also through iframes);+ * - Playwright's options and timeouts are honoured; failures throw+ * Playwright `Error` / `TimeoutError` instead of falling back to+ * Playwright's stock actions.*/-import type { Browser, BrowserContext, Page, Frame, CDPSession } from 'playwright-core';-import { type HumanConfig, type HumanActionOptions, mergeConfig, rand, randRange, sleep } from './config.js';-import { type RawMouse, type RawKeyboard, humanMove, humanClick, clickTarget, humanIdle } from './mouse.js';-import { humanType, pressWithDelay } from './keyboard.js';-import { scrollToElement } from './scroll.js';-import { patchPageElementHandles, patchFrameElementHandles } from './elementhandle.js';-import {- ensureActionable, ensureStable, checkPointerEvents, ElementNotAttachedError,- CHECKS_CLICK, CHECKS_HOVER, CHECKS_INPUT, CHECKS_FOCUS, CHECKS_CHECK,-} from './actionability.js';-import {- buildSnapshotJs, evalParsed, OK, NOT_FOUND, UNSUPPORTED,- StealthEvaluationError, StealthWorldUnavailableError,- UnsupportedHumanizeSelectorError, type SnapshotPayload,-} from './stealthDom.js';-export { HumanConfig, resolveConfig, mergeConfig } from './config.js';export { humanMove, humanClick, clickTarget, humanIdle } from './mouse.js';export { humanType } from './keyboard.js';-export { scrollToElement, humanScrollIntoView } from './scroll.js';-export { patchSingleElementHandle } from './elementhandle.js';+export { CursorState, Human } from './engine.js';+export { patchPage, patchContext, patchBrowser } from './patch.js';+export { StealthWorldError } from './world.js';export {ActionabilityError, ElementNotAttachedError, ElementNotVisibleError,ElementNotStableError, ElementNotEnabledError, ElementNotEditableError,ElementNotReceivingEventsError, ElementTargetChangedError,-} from './actionability.js';-export {StealthDomError, UnsupportedHumanizeSelectorError,StealthWorldUnavailableError, StealthEvaluationError,-} from './stealthDom.js';--// --- Platform-aware select-all shortcut (macOS uses Meta, others use Control) ----const SELECT_ALL = process.platform === 'darwin' ? 'Meta+a' : 'Control+a';---// ============================================================================-// CDP Isolated World — stealth DOM evaluation-// ============================================================================--/**- * Manages a CDP isolated execution context for DOM reads.- * Produces clean Error.stack traces (no 'eval at evaluate :302:')- * and is invisible to querySelector monkey-patches in the main world.- *- * Context ID is invalidated on navigation and auto-recreated on next call.- */-class StealthEval {- private cdp: CDPSession | null = null;- private contextId: number | null = null;- private page: Page;-- constructor(page: Page) {- this.page = page;- }-- private async ensureCdp(): Promise<CDPSession> {- if (!this.cdp) {- this.cdp = await this.page.context().newCDPSession(this.page);- }- return this.cdp;- }-- private async createWorld(): Promise<number> {- const cdp = await this.ensureCdp();- const tree = await cdp.send('Page.getFrameTree');- const frameId = tree.frameTree.frame.id;- const result = await cdp.send('Page.createIsolatedWorld', {- frameId,- worldName: '',- grantUniveralAccess: true,- });- const ctxId = result.executionContextId;- this.contextId = ctxId;- return ctxId;- }-- /**- * Evaluate a JS expression in the isolated world.- * Auto-recreates the world if the context was invalidated (navigation).- * Returns the result value, or undefined on failure.- */- async evaluate(expression: string): Promise<any> {- if (this.contextId === null) {- await this.createWorld();- }-- for (let attempt = 0; attempt < 2; attempt++) {- try {- const cdp = await this.ensureCdp();- const result = await cdp.send('Runtime.evaluate', {- expression,- contextId: this.contextId!,- returnByValue: true,- });-- if (result.exceptionDetails) {- // Context was likely invalidated by navigation- if (attempt === 0) {- await this.createWorld();- continue;- }- return undefined;- }-- return result.result?.value;- } catch {- if (attempt === 0) {- this.contextId = null;- try {- await this.createWorld();- } catch {- return undefined;- }- continue;- }- return undefined;- }- }- return undefined;- }-- /** Mark context as stale — call after navigation. */- invalidate(): void {- this.contextId = null;- }-- /** Get the underlying CDP session (reused for Input.dispatchKeyEvent etc.). */- async getCdpSession(): Promise<CDPSession> {- return this.ensureCdp();- }-}---// ============================================================================-// Cursor state-// ============================================================================--class CursorState {- x = 0;- y = 0;- initialized = false;-}---// ============================================================================-// Canonical selector snapshot — isolated world only-// ============================================================================--async function selectorSnapshot(- stealth: StealthEval | null,- selector: string,-): Promise<SnapshotPayload> {- if (!stealth) throw new StealthWorldUnavailableError();- const { status, data } = await evalParsed(stealth, buildSnapshotJs(selector));- if (status === OK && data) return data as SnapshotPayload;- if (status === NOT_FOUND) throw new ElementNotAttachedError(selector);- if (status === UNSUPPORTED) throw new UnsupportedHumanizeSelectorError(selector);- throw new StealthEvaluationError(selector);-}---// ============================================================================-// Page-level patching-// ============================================================================--/**- * Replace page methods with human-like implementations.- */-function patchPage(page: Page, cfg: HumanConfig, cursor: CursorState): void {- const originals = {- click: page.click.bind(page),- dblclick: page.dblclick.bind(page),- hover: page.hover.bind(page),- type: page.type.bind(page),- fill: page.fill.bind(page),- check: page.check.bind(page),- uncheck: page.uncheck.bind(page),- // Bind to the main frame, not the page: page.selectOption re-dispatches to the- // patched main-frame method, so binding to the page would loop forever.- selectOption: page.mainFrame().selectOption.bind(page.mainFrame()),- press: page.press.bind(page),- goto: page.goto.bind(page),- isChecked: page.isChecked.bind(page),- mouseMove: page.mouse.move.bind(page.mouse),- mouseClick: page.mouse.click.bind(page.mouse),- mouseDblclick: page.mouse.dblclick.bind(page.mouse),- mouseWheel: page.mouse.wheel.bind(page.mouse),- mouseDown: page.mouse.down.bind(page.mouse),- mouseUp: page.mouse.up.bind(page.mouse),- keyboardType: page.keyboard.type.bind(page.keyboard),- keyboardDown: page.keyboard.down.bind(page.keyboard),- keyboardUp: page.keyboard.up.bind(page.keyboard),- keyboardPress: page.keyboard.press.bind(page.keyboard),- keyboardInsertText: page.keyboard.insertText.bind(page.keyboard),- };-- (page as any)._original = originals;- (page as any)._humanCfg = cfg;-- // --- Stealth infrastructure ---- const stealth = new StealthEval(page);- (page as any)._stealth = stealth;-- // CDP session for shift symbol typing (lazy-initialized, reuses stealth's session)- let cdpSession: CDPSession | null = null;- const ensureCdp = async (): Promise<CDPSession | null> => {- if (!cdpSession) {- try {- cdpSession = await stealth.getCdpSession();- } catch (error) {- console.error('[cloakbrowser] Failed to create humanize CDP session:', error);- }- }- return cdpSession;- };-- const raw: RawMouse = {- move: originals.mouseMove,- down: originals.mouseDown,- up: originals.mouseUp,- wheel: originals.mouseWheel,- };-- const rawKb: RawKeyboard = {- down: originals.keyboardDown,- up: originals.keyboardUp,- type: originals.keyboardType,- insertText: originals.keyboardInsertText,- };-- async function ensureCursorInit(): Promise<void> {- if (!cursor.initialized) {- cursor.x = rand(cfg.initial_cursor_x[0], cfg.initial_cursor_x[1]);- cursor.y = rand(cfg.initial_cursor_y[0], cfg.initial_cursor_y[1]);- await originals.mouseMove(cursor.x, cursor.y);- cursor.initialized = true;- }- }-- // --- goto (invalidate isolated world on navigation) ---- const humanGoto = async (url: string, options?: {- referer?: string;- timeout?: number;- waitUntil?: 'load' | 'domcontentloaded' | 'networkidle' | 'commit';- }) => {- const response = await originals.goto(url, options);- stealth.invalidate();- patchFrames(page, cfg, cursor, raw, rawKb, originals, stealth);- return response;- };-- // --- click ---- const humanClickFn = async (selector: string, options?: HumanActionOptions & { _skipChecks?: boolean }) => {- await ensureCursorInit();- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- const timeout = options?.timeout ?? 30000;- const force = options?.force ?? false;- const skipChecks = (options as any)?._skipChecks ?? false;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());-- if (!force && !skipChecks) {- await ensureActionable(page, selector, CHECKS_CLICK, remainingMs(), force);- }- if (callCfg.idle_between_actions) {- await humanIdle(raw, cursor.x, cursor.y, callCfg);- }- const { box, cursorX, cursorY, didScroll } = await scrollToElement(page, raw, selector, cursor.x, cursor.y, callCfg, remainingMs());- cursor.x = cursorX;- cursor.y = cursorY;- const isInput = (await selectorSnapshot(stealth, selector)).isInput;- let finalBox = box;- if (!force && didScroll) {- await ensureStable(page, selector, remainingMs());- // Waiting for the reflow to settle can push the element back out of view,- // and scrolling once before the wait is not enough: the click coords would- // land outside the viewport and hit nothing (#329).- const rescrolled = await scrollToElement(page, raw, selector, cursor.x, cursor.y, callCfg, remainingMs());- finalBox = rescrolled.box;- cursor.x = rescrolled.cursorX;- cursor.y = rescrolled.cursorY;- }- const target = clickTarget(finalBox, isInput, callCfg);- await humanMove(raw, cursor.x, cursor.y, target.x, target.y, callCfg);- cursor.x = target.x;- cursor.y = target.y;- if (!force) {- await checkPointerEvents(- page, selector, finalBox.targetId, finalBox.gen, target.x, target.y,- stealth, remainingMs(),- );- }- await humanClick(raw, isInput, callCfg);- };-- // --- dblclick ---- const humanDblclickFn = async (selector: string, options?: HumanActionOptions) => {- await ensureCursorInit();- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- const timeout = options?.timeout ?? 30000;- const force = options?.force ?? false;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());-- if (!force) await ensureActionable(page, selector, CHECKS_CLICK, remainingMs(), force);- if (callCfg.idle_between_actions) {- await humanIdle(raw, cursor.x, cursor.y, callCfg);- }- const { box, cursorX, cursorY, didScroll } = await scrollToElement(page, raw, selector, cursor.x, cursor.y, callCfg, remainingMs());- cursor.x = cursorX;- cursor.y = cursorY;- const isInput = (await selectorSnapshot(stealth, selector)).isInput;- let finalBox = box;- if (!force && didScroll) {- await ensureStable(page, selector, remainingMs());- // Waiting for the reflow to settle can push the element back out of view,- // and scrolling once before the wait is not enough: the click coords would- // land outside the viewport and hit nothing (#329).- const rescrolled = await scrollToElement(page, raw, selector, cursor.x, cursor.y, callCfg, remainingMs());- finalBox = rescrolled.box;- cursor.x = rescrolled.cursorX;- cursor.y = rescrolled.cursorY;- }- const target = clickTarget(finalBox, isInput, callCfg);- await humanMove(raw, cursor.x, cursor.y, target.x, target.y, callCfg);- cursor.x = target.x;- cursor.y = target.y;- if (!force) {- await checkPointerEvents(- page, selector, finalBox.targetId, finalBox.gen, target.x, target.y,- stealth, remainingMs(),- );- }- await raw.down({ clickCount: 2 });- await sleep(rand(30, 60));- await raw.up({ clickCount: 2 });- };-- // --- hover ---- const humanHoverFn = async (selector: string, options?: HumanActionOptions & { _skipChecks?: boolean }) => {- await ensureCursorInit();- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- const timeout = options?.timeout ?? 30000;- const force = options?.force ?? false;- const skipChecks = (options as any)?._skipChecks ?? false;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());-- if (!force && !skipChecks) await ensureActionable(page, selector, CHECKS_HOVER, remainingMs(), force);- if (callCfg.idle_between_actions) {- await humanIdle(raw, cursor.x, cursor.y, callCfg);- }- const { box, cursorX, cursorY, didScroll } = await scrollToElement(page, raw, selector, cursor.x, cursor.y, callCfg, remainingMs());- cursor.x = cursorX;- cursor.y = cursorY;- let finalBox = box;- if (!force && didScroll) {- await ensureStable(page, selector, remainingMs());- // Waiting for the reflow to settle can push the element back out of view,- // and scrolling once before the wait is not enough: the click coords would- // land outside the viewport and hit nothing (#329).- const rescrolled = await scrollToElement(page, raw, selector, cursor.x, cursor.y, callCfg, remainingMs());- finalBox = rescrolled.box;- cursor.x = rescrolled.cursorX;- cursor.y = rescrolled.cursorY;- }- const target = clickTarget(finalBox, false, callCfg);- await humanMove(raw, cursor.x, cursor.y, target.x, target.y, callCfg);- cursor.x = target.x;- cursor.y = target.y;- if (!force) {- await checkPointerEvents(- page, selector, finalBox.targetId, finalBox.gen, target.x, target.y,- stealth, remainingMs(),- );- }- };-- // --- type ---- const humanTypeFn = async (selector: string, text: string, options?: HumanActionOptions) => {- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- const timeout = options?.timeout ?? 30000;- const force = options?.force ?? false;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());-- if (!force) await ensureActionable(page, selector, CHECKS_INPUT, remainingMs(), force);- await sleep(randRange(callCfg.field_switch_delay));- await humanClickFn(selector, { _skipChecks: true, timeout: remainingMs(), force, human_config: options?.human_config } as any);- await sleep(rand(100, 250));- const cdp = await ensureCdp();- await humanType(page, rawKb, text, callCfg, cdp);- };-- // --- fill (clears existing content first) ---- const humanFillFn = async (selector: string, value: string, options?: HumanActionOptions) => {- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- const timeout = options?.timeout ?? 30000;- const force = options?.force ?? false;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());-- if (!force) await ensureActionable(page, selector, CHECKS_INPUT, remainingMs(), force);- await sleep(randRange(callCfg.field_switch_delay));- await humanClickFn(selector, { _skipChecks: true, timeout: remainingMs(), force, human_config: options?.human_config } as any);- await sleep(rand(100, 250));- await originals.keyboardPress(SELECT_ALL);- await sleep(rand(30, 80));- await originals.keyboardPress('Backspace');- await sleep(rand(50, 150));- const cdp = await ensureCdp();- await humanType(page, rawKb, value, callCfg, cdp);- };-- // --- clear ---- const humanClearFn = async (selector: string, options?: HumanActionOptions) => {- const timeout = options?.timeout ?? 30000;- const force = options?.force ?? false;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());-- if (!force) await ensureActionable(page, selector, CHECKS_FOCUS, remainingMs(), force);- if (!(await selectorSnapshot(stealth, selector)).focused) {- await humanClickFn(selector, { _skipChecks: true, timeout: remainingMs(), force, human_config: options?.human_config } as any);- }- await sleep(rand(50, 150));- await originals.keyboardPress(SELECT_ALL);- await sleep(rand(30, 80));- await originals.keyboardPress('Backspace');- };-- // --- check ---- const humanCheckFn = async (selector: string, options?: HumanActionOptions) => {- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- const timeout = options?.timeout ?? 30000;- const force = options?.force ?? false;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());-- if (!force) await ensureActionable(page, selector, CHECKS_CHECK, remainingMs(), force);- if (callCfg.idle_between_actions) {- await humanIdle(raw, cursor.x, cursor.y, callCfg);- }- const checked = (await selectorSnapshot(stealth, selector)).checked === true;- if (!checked) {- await humanClickFn(selector, { _skipChecks: true, timeout: remainingMs(), force, human_config: options?.human_config } as any);- }- };-- // --- uncheck ---- const humanUncheckFn = async (selector: string, options?: HumanActionOptions) => {- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- const timeout = options?.timeout ?? 30000;- const force = options?.force ?? false;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());-- if (!force) await ensureActionable(page, selector, CHECKS_CHECK, remainingMs(), force);- if (callCfg.idle_between_actions) {- await humanIdle(raw, cursor.x, cursor.y, callCfg);- }- const checked = (await selectorSnapshot(stealth, selector)).checked === true;- if (checked) {- await humanClickFn(selector, { _skipChecks: true, timeout: remainingMs(), force, human_config: options?.human_config } as any);- }- };-- // --- selectOption ---- const humanSelectOptionFn = async (selector: string, values: any, options?: HumanActionOptions) => {- const timeout = options?.timeout ?? 30000;- const force = options?.force ?? false;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());-- if (!force) await ensureActionable(page, selector, CHECKS_FOCUS, remainingMs(), force);- await humanHoverFn(selector, { _skipChecks: true, timeout: remainingMs(), force, human_config: options?.human_config } as any);- await sleep(rand(100, 300));- return originals.selectOption(selector, values, options);- };-- // --- press (checks focus first — avoids redundant mouse moves) ---- const humanPressFn = async (selector: string, key: string, options?: HumanActionOptions) => {- const timeout = options?.timeout ?? 30000;- const force = options?.force ?? false;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());-- if (!force) await ensureActionable(page, selector, CHECKS_FOCUS, remainingMs(), force);- if (!(await selectorSnapshot(stealth, selector)).focused) {- await humanClickFn(selector, { _skipChecks: true, timeout: remainingMs(), force, human_config: options?.human_config } as any);- }- await sleep(rand(50, 150));- await pressWithDelay(originals.keyboardPress, key, options);- };-- // --- pressSequentially ---- const humanPressSequentiallyFn = async (selector: string, text: string, options?: HumanActionOptions) => {- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- const timeout = options?.timeout ?? 30000;- const force = options?.force ?? false;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());-- if (!force) await ensureActionable(page, selector, CHECKS_FOCUS, remainingMs(), force);- if (!(await selectorSnapshot(stealth, selector)).focused) {- await humanClickFn(selector, { _skipChecks: true, timeout: remainingMs(), force, human_config: options?.human_config } as any);- }- await sleep(rand(100, 250));- const cdp = await ensureCdp();- await humanType(page, rawKb, text, callCfg, cdp);- };-- // --- tap ---- const humanTapFn = async (selector: string, options?: HumanActionOptions) => {- await humanClickFn(selector, options);- };-- // Assign page-level patches- (page as any).goto = humanGoto;- (page as any).click = humanClickFn;- (page as any).dblclick = humanDblclickFn;- (page as any).hover = humanHoverFn;- (page as any).type = humanTypeFn;- (page as any).fill = humanFillFn;- (page as any).check = humanCheckFn;- (page as any).uncheck = humanUncheckFn;- (page as any).selectOption = humanSelectOptionFn;- (page as any).press = humanPressFn;- (page as any).pressSequentially = humanPressSequentiallyFn;- (page as any).tap = humanTapFn;- (page as any).clear = humanClearFn;-- // --- mouse patches ---- page.mouse.move = async (x: number, y: number, _options?: {- steps?: number;- }) => {- await ensureCursorInit();- await humanMove(raw, cursor.x, cursor.y, x, y, cfg);- cursor.x = x;- cursor.y = y;- };-- page.mouse.click = async (x: number, y: number, _options?: {- button?: 'left' | 'right' | 'middle';- clickCount?: number;- delay?: number;- }) => {- await ensureCursorInit();- await humanMove(raw, cursor.x, cursor.y, x, y, cfg);- cursor.x = x;- cursor.y = y;- await humanClick(raw, false, cfg);- };-- // --- keyboard patches ---- page.keyboard.type = async (text: string, _options?: { delay?: number }) => {- const cdp = await ensureCdp();- await humanType(page, rawKb, text, cfg, cdp);- };-- // Store helpers for frame patching- (page as any)._humanCursor = cursor;- (page as any)._humanRaw = raw;- (page as any)._humanRawKb = rawKb;- (page as any)._humanOriginals = originals;- (page as any)._humanClickFn = humanClickFn;- (page as any)._humanHoverFn = humanHoverFn;- (page as any)._humanClearFn = humanClearFn;- (page as any)._humanPressFn = humanPressFn;- (page as any)._humanPressSequentiallyFn = humanPressSequentiallyFn;- (page as any)._humanTapFn = humanTapFn;- (page as any)._ensureCursorInit = ensureCursorInit;-- // Initialize cursor immediately so it doesn't visibly jump from (0,0)- cursor.x = rand(cfg.initial_cursor_x[0], cfg.initial_cursor_x[1]);- cursor.y = rand(cfg.initial_cursor_y[0], cfg.initial_cursor_y[1]);- originals.mouseMove(cursor.x, cursor.y).then(() => {- cursor.initialized = true;- }).catch(() => {});-- // --- Patch Frame-level methods (for sub-frames) ---- patchFrames(page, cfg, cursor, raw, rawKb, originals, stealth);-- // --- Patch ElementHandle selectors (page.$, page.$$, page.waitForSelector) ---- patchPageElementHandles(page, cfg, cursor, raw, rawKb, originals, stealth);-}---// ============================================================================-// Frame-level patching-// ============================================================================--/**- * Patch Frame methods so Locator-based calls go through humanization.- * All 13 methods patched: click, dblclick, hover, type, fill, check, uncheck,- * selectOption, press, pressSequentially, tap, clear, dragAndDrop.- */-function patchFrames(- page: Page,- cfg: HumanConfig,- cursor: CursorState,- raw: RawMouse,- rawKb: RawKeyboard,- originals: any,- stealth: StealthEval,-): void {- const patchFrame = (frame: Frame): void => {- if ((frame as any)._humanPatched) return;- patchSingleFrame(frame, page, cfg, cursor, raw, rawKb, originals, stealth);- patchFrameElementHandles(frame, page, cfg, cursor, raw, rawKb, originals, stealth);- (frame as any)._humanPatched = true;- };-- if (!(page as any)._humanFrameListenerAttached) {- page.on('frameattached', (frame: Frame) => {- try {- patchFrame(frame);- } catch (error) {- console.error('[cloakbrowser] Failed to humanize dynamically attached frame:', error);- throw error;- }- });- // Invalidate the isolated world on any main-frame nav, not just goto, so- // click/form navigations don't leave it bound to a stale doc (#507).- page.on('framenavigated', (frame: Frame) => {- if (frame === page.mainFrame()) stealth.invalidate();- });- (page as any)._humanFrameListenerAttached = true;- }-- for (const frame of iterFrames(page)) {- patchFrame(frame);- }-}--function firstFrameLocator(frame: Frame, selector: string): any {- const locator = frame.locator(selector) as any;- return typeof locator.first === 'function' ? locator.first() : locator;-}--async function isFrameInputElement(frame: Frame, selector: string): Promise<boolean> {- return firstFrameLocator(frame, selector).evaluate((el: Element) => {- const tag = el.tagName.toLowerCase();- return tag === 'input' || tag === 'textarea'- || el.getAttribute('contenteditable') === 'true';- }).catch(() => false);-}--async function isFrameSelectorFocused(frame: Frame, selector: string): Promise<boolean> {- return firstFrameLocator(frame, selector).evaluate((el: Element) => el === document.activeElement)- .catch(() => false);-}--function patchSingleFrame(- frame: Frame,- page: Page,- cfg: HumanConfig,- cursor: CursorState,- raw: RawMouse,- rawKb: RawKeyboard,- originals: any,- stealth: StealthEval,-): void {- // The main frame's Locator actions (page.locator(sel).click() etc.) delegate,- // in Playwright, to the main frame's own method. Route those to the already-- // patched page-level methods so they use the full humanized path with the- // isolated-world pre-click reads. Only true sub-frames use the frame-scoped- // path below (iterFrames() includes the main frame). Mirrors the Python- // wrapper, which intercepts at Locator.click and routes to page.click.- if (frame === page.mainFrame()) {- const p = page as any;- (frame as any).click = (selector: string, options?: HumanActionOptions) => p.click(selector, options);- (frame as any).dblclick = (selector: string, options?: HumanActionOptions) => p.dblclick(selector, options);- (frame as any).hover = (selector: string, options?: HumanActionOptions) => p.hover(selector, options);- (frame as any).type = (selector: string, text: string, options?: HumanActionOptions) => p.type(selector, text, options);- (frame as any).fill = (selector: string, value: string, options?: HumanActionOptions) => p.fill(selector, value, options);- (frame as any).check = (selector: string, options?: HumanActionOptions) => p.check(selector, options);- (frame as any).uncheck = (selector: string, options?: HumanActionOptions) => p.uncheck(selector, options);- (frame as any).selectOption = (selector: string, values: any, options?: HumanActionOptions) => p.selectOption(selector, values, options);- (frame as any).press = (selector: string, key: string, options?: HumanActionOptions) => p.press(selector, key, options);- (frame as any).pressSequentially = (selector: string, text: string, options?: HumanActionOptions) => p.pressSequentially(selector, text, options);- (frame as any).tap = (selector: string, options?: HumanActionOptions) => p.tap(selector, options);- (frame as any).clear = (selector: string, options?: HumanActionOptions) => p.clear(selector, options);- // dragAndDrop has no humanized page equivalent; left on the native path (still detectable, out of scope).- return;- }-- // Save originals for methods that need fallback- const origFrameClick = frame.click.bind(frame);- const origFrameDblclick = frame.dblclick.bind(frame);- const origFrameHover = frame.hover.bind(frame);- const origFrameType = frame.type.bind(frame);- const origFrameFill = frame.fill.bind(frame);- const origFrameCheck = frame.check.bind(frame);- const origFrameUncheck = frame.uncheck.bind(frame);- const origFrameSelectOption = frame.selectOption.bind(frame);- const origFramePressSequentially = (frame as any).pressSequentially?.bind(frame);- const origFrameTap = (frame as any).tap?.bind(frame);- const origFrameDragAndDrop = frame.dragAndDrop.bind(frame);-- const moveToFrameSelector = async (- selector: string,- options: HumanActionOptions | undefined,- inputBias: boolean,- remainingMs: () => number,- ) => {- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- if (callCfg.idle_between_actions) {- await humanIdle(raw, cursor.x, cursor.y, callCfg);- }-- const locator = firstFrameLocator(frame, selector);- if (typeof locator.scrollIntoViewIfNeeded === 'function') {- await locator.scrollIntoViewIfNeeded({ timeout: Math.max(1, remainingMs()) }).catch(() => undefined);- }- const box = await locator.boundingBox({ timeout: Math.max(1, remainingMs()) }).catch(() => null);- if (!box) return null;-- const isInput = inputBias || await isFrameInputElement(frame, selector);- const target = clickTarget(box, isInput, callCfg);- await humanMove(raw, cursor.x, cursor.y, target.x, target.y, callCfg);- cursor.x = target.x;- cursor.y = target.y;- return { callCfg, isInput };- };-- const frameClick = async (selector: string, options?: HumanActionOptions) => {- const timeout = options?.timeout ?? 30000;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());- const moved = await moveToFrameSelector(selector, options, false, remainingMs);- if (!moved) return origFrameClick(selector, { ...options, timeout: Math.max(1, remainingMs()) });- await humanClick(raw, moved.isInput, moved.callCfg);- };-- const getFrameCdp = async () => stealth.getCdpSession().catch(() => null);-- const frameHover = async (selector: string, options?: HumanActionOptions) => {- const timeout = options?.timeout ?? 30000;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());- const moved = await moveToFrameSelector(selector, options, false, remainingMs);- if (!moved) return origFrameHover(selector, { ...options, timeout: Math.max(1, remainingMs()) });- };-- (frame as any).click = frameClick;-- (frame as any).dblclick = async (selector: string, options?: HumanActionOptions) => {- const timeout = options?.timeout ?? 30000;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(0, deadline - Date.now());- const moved = await moveToFrameSelector(selector, options, false, remainingMs);- if (!moved) return origFrameDblclick(selector, { ...options, timeout: Math.max(1, remainingMs()) });- await raw.down({ clickCount: 2 });- await sleep(rand(30, 60));- await raw.up({ clickCount: 2 });- };-- (frame as any).hover = frameHover;-- (frame as any).type = async (selector: string, text: string, options?: HumanActionOptions) => {- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- await sleep(randRange(callCfg.field_switch_delay));- await frameClick(selector, options);- await sleep(rand(100, 250));- const cdp = await getFrameCdp();- await humanType(page, rawKb, text, callCfg, cdp).catch(() => origFrameType(selector, text, options));- };-- (frame as any).fill = async (selector: string, value: string, options?: HumanActionOptions) => {- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- await sleep(randRange(callCfg.field_switch_delay));- await frameClick(selector, options);- await sleep(rand(100, 250));- await originals.keyboardPress(SELECT_ALL);- await sleep(rand(30, 80));- await originals.keyboardPress('Backspace');- await sleep(rand(50, 150));- const cdp = await getFrameCdp();- await humanType(page, rawKb, value, callCfg, cdp).catch(() => origFrameFill(selector, value, options));- };-- (frame as any).check = async (selector: string, options?: HumanActionOptions) => {- const locator = firstFrameLocator(frame, selector);- if (typeof locator.isChecked !== 'function') return origFrameCheck(selector, options);- const checked = await locator.isChecked();- if (!checked) await frameClick(selector, options).catch(() => origFrameCheck(selector, options));- };-- (frame as any).uncheck = async (selector: string, options?: HumanActionOptions) => {- const locator = firstFrameLocator(frame, selector);- if (typeof locator.isChecked !== 'function') return origFrameUncheck(selector, options);- const checked = await locator.isChecked();- if (checked) await frameClick(selector, options).catch(() => origFrameUncheck(selector, options));- };-- (frame as any).selectOption = async (selector: string, values: any, options?: HumanActionOptions) => {- await frameHover(selector, options);- await sleep(rand(100, 300));- return origFrameSelectOption(selector, values, options);- };-- (frame as any).press = async (selector: string, key: string, options?: HumanActionOptions) => {- if (!await isFrameSelectorFocused(frame, selector)) {- await frameClick(selector, options);- }- await sleep(rand(50, 150));- await pressWithDelay(originals.keyboardPress, key, options);- };-- (frame as any).pressSequentially = async (selector: string, text: string, options?: HumanActionOptions) => {- const callCfg = mergeConfig(cfg, options?.human_config ?? options);- if (!await isFrameSelectorFocused(frame, selector)) {- await frameClick(selector, options);- }- await sleep(rand(100, 250));- const cdp = await getFrameCdp();- await humanType(page, rawKb, text, callCfg, cdp).catch(() => origFramePressSequentially?.(selector, text, options));- };-- (frame as any).tap = async (selector: string, options?: HumanActionOptions) => {- await frameClick(selector, options).catch(() => origFrameTap?.(selector, options));- };-- (frame as any).clear = async (selector: string, options?: HumanActionOptions) => {- if (!await isFrameSelectorFocused(frame, selector)) {- await frameClick(selector, options);- }- await sleep(rand(50, 150));- await originals.keyboardPress(SELECT_ALL);- await sleep(rand(30, 80));- await originals.keyboardPress('Backspace');- };-- (frame as any).dragAndDrop = async (source: string, target: string, options?: {- force?: boolean;- noWaitAfter?: boolean;- sourcePosition?: { x: number; y: number };- strict?: boolean;- targetPosition?: { x: number; y: number };- timeout?: number;- trial?: boolean;- }) => {- const timeout = options?.timeout ?? 30000;- const deadline = Date.now() + timeout;- const remainingMs = () => Math.max(1, deadline - Date.now());- const srcBox = await firstFrameLocator(frame, source).boundingBox({ timeout: remainingMs() }).catch(() => null);- const tgtBox = await firstFrameLocator(frame, target).boundingBox({ timeout: remainingMs() }).catch(() => null);-- if (srcBox && tgtBox) {- const sx = srcBox.x + srcBox.width / 2;- const sy = srcBox.y + srcBox.height / 2;- const tx = tgtBox.x + tgtBox.width / 2;- const ty = tgtBox.y + tgtBox.height / 2;-- await page.mouse.move(sx, sy);- await sleep(rand(100, 200));- await originals.mouseDown();- await sleep(rand(80, 150));- await page.mouse.move(tx, ty);- await sleep(rand(80, 150));- await originals.mouseUp();- } else {- return origFrameDragAndDrop(source, target, { ...options, timeout: Math.max(1, remainingMs()) });- }- };-}---function* iterFrames(page: Page): Generator<Frame> {- function* walk(frame: Frame): Generator<Frame> {- yield frame;- for (const child of frame.childFrames()) {- yield* walk(child);- }- }- try {- yield* walk(page.mainFrame());- } catch (error) {- console.error('[cloakbrowser] Failed to enumerate page frames:', error);- }-}---// ============================================================================-// Context-level patching-// ============================================================================--function patchContext(context: BrowserContext, cfg: HumanConfig): void {- const cursor = new CursorState();- for (const page of context.pages()) {- patchPage(page, cfg, cursor);- }- context.on('page', (page: Page) => {- if (!(page as any)._original) {- patchPage(page, cfg, new CursorState());- }- });-- const origNewPage = context.newPage.bind(context);- (context as any).newPage = async () => {- const page = await origNewPage();- if (!(page as any)._original) {- patchPage(page, cfg, new CursorState());- }- return page;- };-}---// ============================================================================-// Browser-level patching-// ============================================================================--export function patchBrowser(browser: Browser, cfg: HumanConfig): void {- for (const context of browser.contexts()) {- patchContext(context, cfg);- }-- const origNewContext = browser.newContext.bind(browser);- (browser as any).newContext = async (options?: Parameters<typeof origNewContext>[0]) => {- const context = await origNewContext(options);- patchContext(context, cfg);- return context;- };-- const origNewPage = browser.newPage.bind(browser);- (browser as any).newPage = async (options?: Parameters<typeof origNewPage>[0]) => {- const page = await origNewPage(options);- if (!(page as any)._original) {- const ctx = page.context();- if (!(ctx as any)._humanPatched) {- patchContext(ctx, cfg);- (ctx as any)._humanPatched = true;- }- patchPage(page, cfg, new CursorState());- }- return page;- };-}--export { patchContext, patchPage };+} from './errors.js';diff --git a/js/src/human/injected.ts b/js/src/human/injected.tsnew file mode 100644index 0000000..b555f4e--- /dev/null+++ b/js/src/human/injected.ts@@ -0,0 +1,119 @@+/**+ * Loads Playwright's selector / actionability engine for the humanize layer.+ *+ * Playwright ships its InjectedScript (selector engines for role, label, text,+ * test-id, `>>` chains, `has` / `has-text` filters, `nth`, `visible`, plus+ * `checkElementStates` / `expectHitTarget` / `fill` rules) as a string literal+ * inside playwright-core. The humanize layer evaluates that same source in its+ * own execution context, so it gets exact Playwright selector semantics and+ * strict mode instead of re-implementing accessible-name computation.+ *+ * The literal is extracted from the installed playwright-core, so selector+ * syntax always matches the client that produced the selector string.+ * Mirrors cloakbrowser/human/injected.py.+ */++import fs from 'node:fs';+import path from 'node:path';+import { createRequire } from 'node:module';++/** Global name inside the isolated world (invisible to page scripts). */+export const GLOBAL = '__cloakInjected';++const LITERAL_START = /\bsource\d*\s*[=:]\s*(['"`])/g;+const cache = new Map<string, string>();++function libDirs(): string[] {+ const require = createRequire(import.meta.url);+ try {+ const pkg = require.resolve('playwright-core/package.json');+ const lib = path.join(path.dirname(pkg), 'lib');+ return fs.existsSync(lib) ? [lib] : [];+ } catch {+ return [];+ }+}++/** The JS string literal starting at `text[start]` (quotes included). */+export function readLiteral(text: string, start: number): string {+ const quote = text[start];+ let i = start + 1;+ while (text[i] !== quote) i += text[i] === '\\' ? 2 : 1;+ return text.slice(start, i + 1);+}++function literalAfter(text: string, from: number): string | null {+ LITERAL_START.lastIndex = from;+ const m = LITERAL_START.exec(text);+ if (!m) return null;+ return readLiteral(text, m.index + m[0].length - 1);+}++function* walk(dir: string): Generator<string> {+ for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {+ const p = path.join(dir, ent.name);+ if (ent.isDirectory()) yield* walk(p);+ else if (ent.name === 'injectedScriptSource.js') yield p;+ }+}++/**+ * Locate the InjectedScript source literal in playwright-core. Supports the+ * bundled layout (`coreBundle.js`, >= 1.55) and the older per-file layout+ * (`generated/injectedScriptSource.js`).+ */+export function findInjectedLiteral(dirs: string[] = libDirs()): string {+ const key = dirs.join('|');+ const hit = cache.get(key);+ if (hit) return hit;+ for (const d of dirs) {+ const bundle = path.join(d, 'coreBundle.js');+ if (fs.existsSync(bundle)) {+ const text = fs.readFileSync(bundle, 'utf-8');+ const pos = text.indexOf('generated/injectedScriptSource.ts');+ if (pos >= 0) {+ const lit = literalAfter(text, pos);+ if (lit) { cache.set(key, lit); return lit; }+ }+ }+ for (const f of [...walk(d)].sort()) {+ const lit = literalAfter(fs.readFileSync(f, 'utf-8'), 0);+ if (lit) { cache.set(key, lit); return lit; }+ }+ }+ throw new Error(+ `cloakbrowser humanize: Playwright's InjectedScript source was not found in ${JSON.stringify(dirs)}; ` ++ 'the installed playwright-core layout is not supported',+ );+}++/**+ * Expression that installs the engine in the current (isolated) world.+ * `source` is the *decoded* InjectedScript module text. Idempotent.+ */+export function buildInstallJs(source: string, sdkLanguage = 'javascript', testIdAttribute = 'data-testid'): string {+ const opts = JSON.stringify({+ isUnderTest: false,+ sdkLanguage,+ testIdAttributeName: testIdAttribute,+ stableRafCount: 1,+ browserName: 'chromium',+ isUtilityWorld: true,+ customEngines: [],+ });+ return '(() => {\n' ++ `if (globalThis.${GLOBAL}) return true;\n` ++ 'const module = { exports: {} }; const exports = module.exports;\n' ++ `${source}\n` ++ ';const exp = module.exports.InjectedScript;\n' ++ 'const C = (exp && exp.prototype && exp.prototype.querySelectorAll) ? exp : exp();\n' ++ // Both hooks register listeners / dispatch events on the shared window.+ 'C.prototype._setupGlobalListenersRemovalDetection = function () {};\n' ++ 'C.prototype._setupHitTargetInterceptors = function () {};\n' ++ `const o = ${opts};\n` ++ 'const inj = C.length > 2\n' ++ ' ? new C(globalThis, o.isUnderTest, o.sdkLanguage, o.testIdAttributeName, o.stableRafCount, o.browserName, o.customEngines)\n' ++ ' : new C(globalThis, o);\n' ++ `Object.defineProperty(globalThis, ${JSON.stringify(GLOBAL)}, { value: inj });\n` ++ 'return true; })()';+}diff --git a/js/src/human/keyboard.ts b/js/src/human/keyboard.tsindex 5773486..d5818ee 100644--- a/js/src/human/keyboard.ts+++ b/js/src/human/keyboard.ts@@ -24,12 +24,12 @@ export async function pressWithDelay<Key>(await press(key, { delay });}-const SHIFT_SYMBOLS = new Set([+export const SHIFT_SYMBOLS = new Set(['@', '#', '!', '$', '%', '^', '&', '*', '(', ')','_', '+', '{', '}', '|', ':', '"', '<', '>', '?', '~',]);-const NEARBY_KEYS: Record<string, string> = {+export const NEARBY_KEYS: Record<string, string> = {a: 'sqwz', b: 'vghn', c: 'xdfv', d: 'sfecx', e: 'wrsdf',f: 'dgrtcv', g: 'fhtyb', h: 'gjybn', i: 'ujko', j: 'hkunm',k: 'jloi', l: 'kop', m: 'njk', n: 'bhjm', o: 'iklp',@@ -46,7 +46,7 @@ const NEARBY_KEYS: Record<string, string> = {* CDP key code for each shift symbol's physical key.* Used by Input.dispatchKeyEvent to produce isTrusted=true events.*/-const SHIFT_SYMBOL_CODES: Record<string, string> = {+export const SHIFT_SYMBOL_CODES: Record<string, string> = {'!': 'Digit1', '@': 'Digit2', '#': 'Digit3', '$': 'Digit4','%': 'Digit5', '^': 'Digit6', '&': 'Digit7', '*': 'Digit8','(': 'Digit9', ')': 'Digit0', '_': 'Minus', '+': 'Equal',@@ -59,7 +59,7 @@ const SHIFT_SYMBOL_CODES: Record<string, string> = {* Windows virtual key codes for shift symbols.* Input.dispatchKeyEvent uses these to match real keyboard behavior.*/-const SHIFT_SYMBOL_KEYCODES: Record<string, number> = {+export const SHIFT_SYMBOL_KEYCODES: Record<string, number> = {'!': 49, '@': 50, '#': 51, '$': 52, '%': 53,'^': 54, '&': 55, '*': 56, '(': 57, ')': 48,'_': 189, '+': 187, '{': 219, '}': 221, '|': 220,diff --git a/js/src/human/mouse.ts b/js/src/human/mouse.tsindex 277f0ac..67f3a2f 100644--- a/js/src/human/mouse.ts+++ b/js/src/human/mouse.ts@@ -26,7 +26,7 @@ export interface RawKeyboard {// Easing// ----------------------------------------------------------------------------function easeInOut(t: number): number {+export function easeInOut(t: number): number {return t < 0.5? 4 * t * t * t: 1 - Math.pow(-2 * t + 2, 3) / 2;@@ -36,12 +36,12 @@ function easeInOut(t: number): number {// Bezier// ----------------------------------------------------------------------------interface Point {+export interface Point {x: number;y: number;}-function bezier(p0: Point, p1: Point, p2: Point, p3: Point, t: number): Point {+export function bezier(p0: Point, p1: Point, p2: Point, p3: Point, t: number): Point {const u = 1 - t;const uu = u * u;const uuu = uu * u;@@ -53,7 +53,7 @@ function bezier(p0: Point, p1: Point, p2: Point, p3: Point, t: number): Point {};}-function randomControlPoints(start: Point, end: Point): [Point, Point] {+export function randomControlPoints(start: Point, end: Point): [Point, Point] {const dx = end.x - start.x;const dy = end.y - start.y;const dist = Math.hypot(dx, dy);diff --git a/js/src/human/patch.ts b/js/src/human/patch.tsnew file mode 100644index 0000000..e59aad9--- /dev/null+++ b/js/src/human/patch.ts@@ -0,0 +1,370 @@+/**+ * Wire the humanize engine into playwright-core's client classes.+ * Port of cloakbrowser/human/patch.py.+ *+ * Patching is prototype-level and idempotent: Page, Frame, Locator,+ * ElementHandle, Mouse and Keyboard methods check whether their page was+ * humanized (`patchPage`) and otherwise call the original Playwright method.+ * Every humanized method:+ *+ * - accepts the options the original accepts plus `human_config` (and, for+ * backwards compatibility, HumanConfig keys directly in the options);+ * - honours Playwright's semantics for those options (`button`, `clickCount`,+ * `modifiers`, `position`, `trial`, `force`, `timeout` including page+ * defaults and `0` = no limit, `strict`);+ * - throws Playwright `Error` / `TimeoutError` instead of silently falling+ * back to Playwright's stock implementation.+ *+ * playwright-core does not export its client classes, so prototypes are+ * reached through live instances: the page itself, `page.mainFrame()`,+ * `page.locator()` (no protocol call), `page.mouse` / `page.keyboard`, and+ * the connection's object-creation hook (first ElementHandle created).+ */++import { createRequire } from 'node:module';+import type { Browser, BrowserContext, ElementHandle, Frame, Page } from 'playwright-core';+import { type HumanConfig, rand } from './config.js';+import { CursorState, Human, Target, type Opts, type RawInput } from './engine.js';++type Kind = 'Page' | 'Frame' | 'Locator' | 'ElementHandle' | 'Mouse' | 'Keyboard';+type Handler = (h: Human, self: any, args: any[]) => Promise<any>;++const PATCHED = new WeakSet<object>();+const ORIG = new WeakMap<object, Map<string, (...a: any[]) => any>>();+const MARK = Symbol.for('cloakbrowser.humanized');++const API_NAME: Record<Kind, string> = {+ Page: 'page', Frame: 'frame', Locator: 'locator', ElementHandle: 'elementHandle', Mouse: 'mouse', Keyboard: 'keyboard',+};++// ---------------------------------------------------------------------------+// helpers+// ---------------------------------------------------------------------------++function pageOf(kind: Kind, self: any): any {+ switch (kind) {+ case 'Page': return self;+ case 'Frame': return self._page;+ case 'Locator':+ case 'ElementHandle': return self._frame?._page;+ default: return self._page;+ }+}++function humanFor(kind: Kind, self: any): Human | null {+ // No try/catch: swallowing an error here would run Playwright's stock+ // action on a humanized page.+ return pageOf(kind, self)?._cloakHuman ?? null;+}++/** Per-call options: Playwright options + `human_config` + legacy direct+ * HumanConfig keys (`{ typing_delay: 30 }`). */+function opts(h: Human, o: any): Opts {+ const out: Opts = { ...(o ?? {}) };+ const direct: Record<string, unknown> = {};+ for (const k of Object.keys(out)) if (k in h.cfg) { direct[k] = out[k]; delete out[k]; }+ if (Object.keys(direct).length || out.human_config) out.human_config = { ...direct, ...(out.human_config ?? {}) };+ return out;+}++const isHandle = (v: any) => !!v && typeof v === 'object' && typeof v.boundingBox === 'function' && '_elementChannel' in v;++function selectValues(values: any): [any[], ElementHandle[]] {+ if (values === null || values === undefined) return [[], []];+ const list = Array.isArray(values) ? values : [values];+ const options: any[] = [], handles: ElementHandle[] = [];+ list.forEach((v, i) => {+ if (v === null || v === undefined) throw new Error(`options[${i}]: expected object, got null`);+ if (isHandle(v)) handles.push(v);+ else if (typeof v === 'string') options.push({ valueOrLabel: v });+ else {+ const o: any = {};+ for (const k of ['value', 'label', 'index']) if (v[k] !== undefined) o[k] = v[k];+ options.push(o);+ }+ });+ return [options, handles];+}++// ---------------------------------------------------------------------------+// targets+// ---------------------------------------------------------------------------++function frameOf(kind: Kind, self: any): Frame {+ return kind === 'Page' ? self.mainFrame() : self;+}++function target(kind: Kind, self: any, args: any[], o: Opts): { t: Target; rest: any[] } {+ if (kind === 'Page' || kind === 'Frame') return { t: new Target(frameOf(kind, self), args[0], !!o.strict), rest: args.slice(1) };+ if (kind === 'Locator') return { t: new Target(self._frame, self._selector, true), rest: args };+ return { t: new Target(self._frame, null, false, self), rest: args };+}++/** Index of the options argument for each method (after the selector for+ * Page / Frame). */+const OPT_INDEX: Record<string, number> = {+ click: 0, dblclick: 0, hover: 0, tap: 0, check: 0, uncheck: 0, focus: 0, clear: 0, scrollIntoViewIfNeeded: 0,+ fill: 1, type: 1, pressSequentially: 1, press: 1, setChecked: 1, selectOption: 1, dragTo: 1,+};++function handlers(kind: Kind): Record<string, Handler> {+ const api = API_NAME[kind];+ const sel = kind === 'Page' || kind === 'Frame' ? 1 : 0;+ const optArg = (name: string, args: any[]) => args[sel + OPT_INDEX[name]];+ const prep = (name: string, h: Human, self: any, args: any[]) => {+ const o = opts(h, optArg(name, args));+ return { o, ...target(kind, self, args, o) };+ };++ const table: Record<string, Handler> = {+ click: async (h, self, args) => { const { o, t } = prep('click', h, self, args); await h.click(t, o, `${api}.click`); },+ dblclick: async (h, self, args) => { const { o, t } = prep('dblclick', h, self, args); await h.click(t, o, `${api}.dblclick`, 2); },+ hover: async (h, self, args) => { const { o, t } = prep('hover', h, self, args); await h.hover(t, o, `${api}.hover`); },+ tap: async (h, self, args) => { const { o, t } = prep('tap', h, self, args); await h.tap(t, o, `${api}.tap`); },+ fill: async (h, self, args) => { const { o, t, rest } = prep('fill', h, self, args); await h.fill(t, String(rest[0]), o, `${api}.fill`); },+ type: async (h, self, args) => { const { o, t, rest } = prep('type', h, self, args); await h.type(t, String(rest[0]), o, `${api}.type`); },+ press: async (h, self, args) => { const { o, t, rest } = prep('press', h, self, args); await h.press(t, String(rest[0]), o, `${api}.press`); },+ check: async (h, self, args) => { const { o, t } = prep('check', h, self, args); await h.setChecked(t, true, o, `${api}.check`); },+ uncheck: async (h, self, args) => { const { o, t } = prep('uncheck', h, self, args); await h.setChecked(t, false, o, `${api}.uncheck`); },+ setChecked: async (h, self, args) => {+ const { o, t, rest } = prep('setChecked', h, self, args);+ await h.setChecked(t, !!rest[0], o, `${api}.setChecked`);+ },+ selectOption: async (h, self, args) => {+ const { o, t, rest } = prep('selectOption', h, self, args);+ const [options, handles] = selectValues(rest[0]);+ return h.selectOption(t, options, handles, o, `${api}.selectOption`);+ },+ focus: async (h, self, args) => {+ const { o, t } = prep('focus', h, self, args);+ await h.focus(t, o, `${api}.focus`, kind === 'ElementHandle');+ },+ };+ if (kind === 'Page' || kind === 'Frame') {+ table.dragAndDrop = async (h, self, args) => {+ const o = opts(h, args[2]);+ const frame = frameOf(kind, self);+ await h.drag(new Target(frame, args[0], !!o.strict), new Target(frame, args[1], !!o.strict), o, `${api}.dragAndDrop`);+ };+ }+ if (kind === 'Locator') {+ table.clear = async (h, self, args) => { const { o, t } = prep('clear', h, self, args); await h.fill(t, '', o, `${api}.clear`); };+ table.pressSequentially = async (h, self, args) => {+ const { o, t, rest } = prep('pressSequentially', h, self, args);+ await h.type(t, String(rest[0]), o, `${api}.pressSequentially`);+ };+ table.dragTo = async (h, self, args) => {+ const o = opts(h, args[1]);+ const other = args[0];+ await h.drag(new Target(self._frame, self._selector, true), new Target(other._frame, other._selector, true), o, `${api}.dragTo`);+ };+ }+ if (kind === 'Locator' || kind === 'ElementHandle') {+ table.scrollIntoViewIfNeeded = async (h, self, args) => {+ const { o, t } = prep('scrollIntoViewIfNeeded', h, self, args);+ await h.scrollIntoViewIfNeeded(t, o, `${api}.scrollIntoViewIfNeeded`);+ };+ }+ return table;+}++const INPUT_HANDLERS: Record<'Mouse' | 'Keyboard', Record<string, Handler>> = {+ Mouse: {+ move: (h, _s, [x, y, o]) => h.mouseMove(x, y, o?.steps),+ click: (h, _s, [x, y, o]) => h.mouseClick(x, y, o?.delay, o?.button, o?.clickCount),+ dblclick: (h, _s, [x, y, o]) => h.mouseClick(x, y, o?.delay, o?.button, 2),+ },+ Keyboard: {+ type: (h, _s, [text, o]) => h.keyboardType(String(text), o?.delay),+ },+};++// ---------------------------------------------------------------------------+// prototype patching+// ---------------------------------------------------------------------------++function wrap(kind: Kind, proto: any, name: string, handler: Handler): void {+ const orig = Object.prototype.hasOwnProperty.call(proto, name) ? proto[name] : undefined;+ if (typeof orig !== 'function' || orig[MARK]) return;+ if (!ORIG.has(proto)) ORIG.set(proto, new Map());+ ORIG.get(proto)!.set(name, orig);+ const wrapper = async function (this: any, ...args: any[]) {+ const h = humanFor(kind, this);+ if (!h) return orig.apply(this, args);+ return handler(h, this, args);+ };+ Object.defineProperty(wrapper, 'name', { value: name });+ (wrapper as any)[MARK] = true;+ proto[name] = wrapper;+}++function patchProto(kind: Kind, proto: any): void {+ if (!proto || proto === Object.prototype || PATCHED.has(proto)) return;+ PATCHED.add(proto);+ const table = kind === 'Mouse' || kind === 'Keyboard' ? INPUT_HANDLERS[kind] : handlers(kind);+ for (const [name, handler] of Object.entries(table)) wrap(kind, proto, name, handler);+}++/** The unpatched Playwright method `name` of `obj`'s class. */+export function original(obj: any, name: string): (...a: any[]) => any {+ for (let p = Object.getPrototypeOf(obj); p; p = Object.getPrototypeOf(p)) {+ const f = ORIG.get(p)?.get(name);+ if (f) return f;+ if (Object.prototype.hasOwnProperty.call(p, name)) return p[name];+ }+ return obj[name];+}++/** Oldest playwright-core whose client internals the engine relies on. */+export const MIN_PLAYWRIGHT = '1.53.0';++function playwrightVersion(): string {+ try {+ return createRequire(import.meta.url)('playwright-core/package.json').version ?? 'unknown';+ } catch { return 'unknown'; }+}++function versionAtLeast(v: string, min: string): boolean {+ const a = v.split('.').map((x) => parseInt(x, 10)), b = min.split('.').map((x) => parseInt(x, 10));+ for (let i = 0; i < b.length; i++) {+ if ((a[i] ?? 0) !== b[i]) return (a[i] ?? 0) > b[i];+ }+ return true;+}++function unsupported(reason: string): Error {+ return new Error(+ `cloakbrowser humanize requires playwright-core >= ${MIN_PLAYWRIGHT} ` ++ `(installed: ${playwrightVersion()}; ${reason}). Upgrade with: npm install playwright-core@latest`);+}++function install(page: Page): void {+ const p: any = page;+ const version = playwrightVersion();+ if (version !== 'unknown' && !versionAtLeast(version, MIN_PLAYWRIGHT)) throw unsupported('version too old');+ // Internals the engine uses on a real client object (Frame._timeout,+ // Connection._createRemoteObject). Fail loudly when one is missing instead of+ // letting actions fall back to Playwright's own.+ const conn = p._connection;+ if (conn) {+ if (typeof (page.mainFrame() as any)._timeout !== 'function') throw unsupported('missing Frame._timeout');+ if (typeof conn._createRemoteObject !== 'function') throw unsupported('missing Connection._createRemoteObject');+ }+ patchProto('Page', Object.getPrototypeOf(page));+ patchProto('Frame', Object.getPrototypeOf(page.mainFrame()));+ patchProto('Locator', Object.getPrototypeOf(page.locator('html')));+ patchProto('Mouse', Object.getPrototypeOf(page.mouse));+ patchProto('Keyboard', Object.getPrototypeOf(page.keyboard));+ // ElementHandle: the class is only reachable from an instance. Every protocol+ // object is created by Connection._createRemoteObject (all supported+ // playwright-core versions), so wrap it and patch the first handle's prototype.+ // Without this hook handle.click() would silently run Playwright's stock+ // action, so a missing hook is an error, not a skipped patch.+ if (conn && !conn.__cloakEH) {+ conn.__cloakEH = true;+ const create = conn._createRemoteObject;+ conn._createRemoteObject = function (this: any, parentGuid: string, type: string, ...rest: any[]) {+ const obj = create.call(this, parentGuid, type, ...rest);+ if (type === 'ElementHandle' && obj) patchProto('ElementHandle', Object.getPrototypeOf(obj));+ return obj;+ };+ }+}++// ---------------------------------------------------------------------------+// page attachment+// ---------------------------------------------------------------------------++function rawInput(page: Page): RawInput {+ const m: any = page.mouse, k: any = page.keyboard;+ const om = (n: string) => original(m, n).bind(m);+ const ok = (n: string) => original(k, n).bind(k);+ const move = om('move'), down = om('down'), up = om('up'), wheel = om('wheel');+ const kd = ok('down'), ku = ok('up'), kp = ok('press'), it = ok('insertText');+ return {+ move: (x, y, o) => move(x, y, o), down: (o) => down(o), up: (o) => up(o), wheel: (dx, dy) => wheel(dx, dy),+ keyDown: (key) => kd(key), keyUp: (key) => ku(key), keyPress: (key, o) => kp(key, o), insertText: (t) => it(t),+ };+}++const PAGE_ORIGINALS = ['click', 'dblclick', 'hover', 'type', 'fill', 'check', 'uncheck', 'selectOption', 'press', 'tap',+ 'focus', 'setChecked', 'dragAndDrop'];++/** `page._original`: raw, un-humanized Playwright calls for this page. */+function originals(page: Page): Record<string, (...a: any[]) => any> {+ const out: Record<string, (...a: any[]) => any> = {};+ // Page methods only delegate to the main frame; call the original Frame+ // method directly so the humanized Frame wrapper is never re-entered.+ for (const name of PAGE_ORIGINALS) {+ out[name] = (...a: any[]) => { const f = page.mainFrame(); return original(f, name).apply(f, a); };+ }+ out.goto = (...a: any[]) => (page.goto as any)(...a);+ out.isChecked = (...a: any[]) => (page.isChecked as any)(...a);+ const m: any = page.mouse, k: any = page.keyboard;+ for (const n of ['move', 'click', 'dblclick', 'wheel', 'down', 'up']) {+ out[`mouse${n[0].toUpperCase()}${n.slice(1)}`] = original(m, n).bind(m);+ }+ for (const n of ['type', 'down', 'up', 'press', 'insertText']) {+ out[`keyboard${n[0].toUpperCase()}${n.slice(1)}`] = original(k, n).bind(k);+ }+ return out;+}++/** Humanize one page. */+export function patchPage(page: Page, cfg: HumanConfig, cursor: CursorState = new CursorState()): Human {+ install(page);+ const p: any = page;+ let human: Human = p._cloakHuman;+ if (!human) {+ human = new Human(page, cfg, cursor, rawInput(page));+ Object.defineProperty(p, '_cloakHuman', { value: human, configurable: true, writable: true });+ }+ p._original = originals(page);+ p._humanCfg = cfg;+ p._humanCursor = cursor;+ p._stealth = {+ evaluate: (expression: string) => human.worlds.evaluate(page.mainFrame(), expression),+ invalidate: () => human.worlds.invalidate(),+ getCdpSession: () => human.worlds.session(),+ };+ if (!cursor.initialized) {+ // Start near the address bar instead of (0, 0).+ cursor.x = rand(cfg.initial_cursor_x[0], cfg.initial_cursor_x[1]);+ cursor.y = rand(cfg.initial_cursor_y[0], cfg.initial_cursor_y[1]);+ cursor.initialized = true;+ human.raw.move(cursor.x, cursor.y).catch(() => { cursor.initialized = false; });+ }+ return human;+}++export function patchContext(context: BrowserContext, cfg: HumanConfig): void {+ const ctx: any = context;+ if (ctx._humanPatched) return;+ ctx._humanPatched = true;+ const cursor = new CursorState();+ for (const page of context.pages()) patchPage(page, cfg, cursor);+ context.on('page', (page: Page) => { if (!(page as any)._original) patchPage(page, cfg, new CursorState()); });+ const origNewPage = context.newPage.bind(context);+ ctx.newPage = async (...a: any[]) => {+ const page = await (origNewPage as any)(...a);+ if (!page._original) patchPage(page, cfg, new CursorState());+ return page;+ };+}++export function patchBrowser(browser: Browser, cfg: HumanConfig): void {+ for (const context of browser.contexts()) patchContext(context, cfg);+ const origNewContext = browser.newContext.bind(browser);+ (browser as any).newContext = async (...a: any[]) => {+ const context = await (origNewContext as any)(...a);+ patchContext(context, cfg);+ return context;+ };+ const origNewPage = browser.newPage.bind(browser);+ (browser as any).newPage = async (...a: any[]) => {+ const page = await (origNewPage as any)(...a);+ patchContext(page.context(), cfg);+ if (!page._original) patchPage(page, cfg, new CursorState());+ return page;+ };+}diff --git a/js/src/human/scroll.ts b/js/src/human/scroll.tsdeleted file mode 100644index 05a3a87..0000000--- a/js/src/human/scroll.ts+++ /dev/null@@ -1,315 +0,0 @@-/**- * cloakbrowser-human — Human-like scrolling via mouse wheel events.- *- * Selector geometry and live DOM scroll state are read only through the CDP- * isolated world. ElementHandle callers may still supply their own exact box.- */--import type { Page } from 'playwright-core';-import { type HumanConfig, rand, randRange, randIntRange, sleep } from './config.js';-import { type RawMouse, humanMove } from './mouse.js';-import {- buildBoxJs, evalParsed, getWorld, OK, NOT_FOUND, UNSUPPORTED,- EVALUATION_FAILED, VIEWPORT_JS, StealthEvaluationError,- StealthWorldUnavailableError, UnsupportedHumanizeSelectorError,-} from './stealthDom.js';--export interface ElementBounds {- x: number;- y: number;- width: number;- height: number;- targetId?: number;-}--export interface SelectorBounds extends ElementBounds {- targetId: number;- gen: number;-}--function isInViewport(- bounds: ElementBounds,- viewportHeight: number,- cfg: HumanConfig,-): boolean {- const topEdge = bounds.y;- const bottomEdge = bounds.y + bounds.height;- const zoneTop = viewportHeight * cfg.scroll_target_zone[0];- const zoneBottom = viewportHeight * cfg.scroll_target_zone[1];- return topEdge >= zoneTop && bottomEdge <= zoneBottom;-}--function isInViewportX(bounds: ElementBounds, viewportWidth: number): boolean {- return bounds.x >= 0 && bounds.x + bounds.width <= viewportWidth;-}--// In RTL documents Chrome's scrollX runs from 0 down to -range, and the-// viewport takes its direction from <body> when there is one.-const SCROLL_JS =- '(() => { const e = document.scrollingElement || document.documentElement;' +- ' const rangeX = Math.max(0, e.scrollWidth - e.clientWidth);' +- " const rtl = getComputedStyle(document.body || e).direction === 'rtl';" +- ' return { y: window.scrollY, maxY: Math.max(0, e.scrollHeight - e.clientHeight),' +- ' x: window.scrollX, minX: rtl ? -rangeX : 0, maxX: rtl ? 0 : rangeX }; })()';--async function readScrollState(- page: Page,-): Promise<{ y: number; maxY: number; x: number; minX: number; maxX: number }> {- const world = getWorld(page);- if (!world) throw new StealthWorldUnavailableError();- try {- const state = await world.evaluate(SCROLL_JS);- if (- !state || typeof state !== 'object' ||- typeof state.y !== 'number' || typeof state.maxY !== 'number' ||- typeof state.x !== 'number' || typeof state.minX !== 'number' ||- typeof state.maxX !== 'number'- ) {- throw new StealthEvaluationError('<scroll-state>');- }- return state;- } catch (error) {- if (error instanceof StealthEvaluationError) throw error;- throw new StealthEvaluationError('<scroll-state>');- }-}--async function smoothWheel(- raw: RawMouse,- delta: number,- cfg: HumanConfig,- axis: 'x' | 'y' = 'y',-): Promise<void> {- const absD = Math.abs(delta);- const sign = delta > 0 ? 1 : -1;- let sent = 0;- while (sent < absD) {- const stepSize = rand(20, 40);- const chunk = Math.min(stepSize, absD - sent);- const d = Math.round(chunk) * sign;- if (axis === 'x') {- await raw.wheel(d, 0);- } else {- await raw.wheel(0, d);- }- sent += chunk;- await sleep(rand(8, 20));- }-}--export async function humanScrollIntoView<T extends ElementBounds>(- page: Page,- raw: RawMouse,- getBox: () => Promise<T | null>,- cursorX: number,- cursorY: number,- cfg: HumanConfig,-): Promise<{ box: T; cursorX: number; cursorY: number; didScroll: boolean }> {- let viewport = page.viewportSize();- if (!viewport) {- const world = getWorld(page);- if (!world) throw new StealthWorldUnavailableError();- try {- viewport = await world.evaluate(VIEWPORT_JS);- } catch {- throw new StealthEvaluationError('<viewport>');- }- }- if (!viewport || !viewport.height) throw new Error('Viewport size not available');-- const yPass = await scrollYIntoView(page, raw, getBox, viewport, cursorX, cursorY, cfg);- const xPass = await scrollXIntoView(- page, raw, getBox, yPass.box, viewport, yPass.cursorX, yPass.cursorY, cfg,- );- return { ...xPass, didScroll: yPass.didScroll || xPass.didScroll };-}--/** Vertical pass: bring the box into ``scroll_target_zone``. */-async function scrollYIntoView<T extends ElementBounds>(- page: Page,- raw: RawMouse,- getBox: () => Promise<T | null>,- viewport: { width: number; height: number },- cursorX: number,- cursorY: number,- cfg: HumanConfig,-): Promise<{ box: T; cursorX: number; cursorY: number; didScroll: boolean }> {- let box = await getBox();- if (!box) throw new Error('Element not found while scrolling into view');-- if (isInViewport(box, viewport.height, cfg)) {- return { box, cursorX, cursorY, didScroll: false };- }-- // 1px slack: layout can report a top edge of -1/64 px on an unscrolled page.- const fullyVisible = box.y >= -1 && box.y + box.height <= viewport.height + 1;- if (fullyVisible) {- const zoneMid = viewport.height * (cfg.scroll_target_zone[0] + cfg.scroll_target_zone[1]) / 2;- const needUp = box.y + box.height / 2 < zoneMid;- const { y, maxY } = await readScrollState(page);- if (needUp ? y <= 0 : y >= maxY) {- return { box, cursorX, cursorY, didScroll: false };- }- }-- const scrollAreaX = Math.round(viewport.width * rand(0.3, 0.7));- const scrollAreaY = Math.round(viewport.height * rand(0.3, 0.7));- await humanMove(raw, cursorX, cursorY, scrollAreaX, scrollAreaY, cfg);- cursorX = scrollAreaX;- cursorY = scrollAreaY;- await sleep(randRange(cfg.scroll_pre_move_delay));-- const targetY = viewport.height * rand(cfg.scroll_target_zone[0], cfg.scroll_target_zone[1]);- const elementCenter = box.y + box.height / 2;- const distanceToScroll = elementCenter - targetY;-- const direction = distanceToScroll > 0 ? 1 : -1;- const absDistance = Math.abs(distanceToScroll);- const avgDelta = (cfg.scroll_delta_base[0] + cfg.scroll_delta_base[1]) / 2;- const totalClicks = Math.max(3, Math.ceil(absDistance / avgDelta));- const accelSteps = randIntRange(cfg.scroll_accel_steps);- const decelSteps = randIntRange(cfg.scroll_decel_steps);- let scrolled = 0;-- for (let i = 0; i < totalClicks; i++) {- let delta: number;- let pause: number;-- if (i < accelSteps) {- delta = rand(80, 100);- pause = randRange(cfg.scroll_pause_slow);- } else if (i >= totalClicks - decelSteps) {- delta = rand(60, 90);- pause = randRange(cfg.scroll_pause_slow);- } else {- delta = randRange(cfg.scroll_delta_base);- pause = randRange(cfg.scroll_pause_fast);- }-- delta *= 1 + (Math.random() - 0.5) * 2 * cfg.scroll_delta_variance;- delta = Math.round(delta) * direction;-- await smoothWheel(raw, delta, cfg);- scrolled += Math.abs(delta);- await sleep(pause);-- if (i % 3 === 2 || i === totalClicks - 1) {- const nextBox = await getBox();- if (nextBox) box = nextBox;- if (nextBox && isInViewport(nextBox, viewport.height, cfg)) break;- }- if (scrolled >= absDistance * 1.1) break;- }-- if (Math.random() < cfg.scroll_overshoot_chance) {- const overshootPx = Math.round(randRange(cfg.scroll_overshoot_px)) * direction;- await smoothWheel(raw, overshootPx, cfg);- await sleep(randRange(cfg.scroll_settle_delay));-- const corrections = randIntRange([1, 2]);- for (let c = 0; c < corrections; c++) {- const corrDelta = Math.round(rand(40, 80)) * -direction;- await smoothWheel(raw, corrDelta, cfg);- await sleep(rand(100, 250));- }- }-- await sleep(randRange(cfg.scroll_settle_delay));-- const finalBox = await getBox();- if (!finalBox) throw new Error('Element lost after scrolling into view');- return { box: finalBox, cursorX, cursorY, didScroll: true };-}--/**- * Horizontal pass: bring the box inside the viewport width (#521).- *- * Only containment is checked here, not ``scroll_target_zone``: the zone is a- * vertical reading position, and horizontal overflow is the exception.- */-async function scrollXIntoView<T extends ElementBounds>(- page: Page,- raw: RawMouse,- getBox: () => Promise<T | null>,- box: T,- viewport: { width: number; height: number },- cursorX: number,- cursorY: number,- cfg: HumanConfig,-): Promise<{ box: T; cursorX: number; cursorY: number; didScroll: boolean }> {- if (isInViewportX(box, viewport.width)) {- return { box, cursorX, cursorY, didScroll: false };- }-- const distanceToScroll = box.x + box.width / 2 - viewport.width / 2;- // A box wider than the viewport is never contained; once centred, skip the near-zero wheel.- if (Math.abs(distanceToScroll) < 1) {- return { box, cursorX, cursorY, didScroll: false };- }-- // Page pinned at the boundary in the needed direction: scrolling can't help.- const { x, minX, maxX } = await readScrollState(page);- if (distanceToScroll < 0 ? x <= minX : x >= maxX) {- return { box, cursorX, cursorY, didScroll: false };- }-- const scrollAreaX = Math.round(viewport.width * rand(0.3, 0.7));- const scrollAreaY = Math.round(viewport.height * rand(0.3, 0.7));- await humanMove(raw, cursorX, cursorY, scrollAreaX, scrollAreaY, cfg);- cursorX = scrollAreaX;- cursorY = scrollAreaY;- await sleep(randRange(cfg.scroll_pre_move_delay));-- await smoothWheel(raw, Math.round(distanceToScroll), cfg, 'x');- await sleep(randRange(cfg.scroll_settle_delay));-- const finalBox = await getBox();- if (!finalBox) throw new Error('Element lost after scrolling into view');- return { box: finalBox, cursorX, cursorY, didScroll: true };-}--export async function scrollToElement(- page: Page,- raw: RawMouse,- selector: string,- cursorX: number,- cursorY: number,- cfg: HumanConfig,- timeout: number = 30000,-): Promise<{ box: SelectorBounds; cursorX: number; cursorY: number; didScroll: boolean }> {- return humanScrollIntoView(- page,- raw,- () => getElementBox(page, selector, timeout),- cursorX,- cursorY,- cfg,- );-}--export async function getElementBox(- page: Page,- selector: string,- timeout: number = 30000,-): Promise<SelectorBounds | null> {- const world = getWorld(page);- if (!world) throw new StealthWorldUnavailableError();-- const deadline = Date.now() + Math.max(0, timeout);- let result = await evalParsed(world, buildBoxJs(selector));- while (- (result.status === NOT_FOUND || result.status === EVALUATION_FAILED) &&- Date.now() < deadline- ) {- await sleep(50);- result = await evalParsed(world, buildBoxJs(selector));- }-- const { status, data } = result;- if (status === OK && data?.box && Number.isInteger(data.targetId) && Number.isInteger(data.gen)) {- return { ...data.box, targetId: data.targetId, gen: data.gen };- }- if (status === NOT_FOUND) return null;- if (status === UNSUPPORTED) throw new UnsupportedHumanizeSelectorError(selector);- throw new StealthEvaluationError(selector);-}diff --git a/js/src/human/stealthDom.ts b/js/src/human/stealthDom.tsdeleted file mode 100644index 232aedc..0000000--- a/js/src/human/stealthDom.ts+++ /dev/null@@ -1,718 +0,0 @@-/** Versioned isolated-world DOM selector protocol; mirrors stealth_dom.py. */-export const PROTOCOL_VERSION = 2;-export const OK = 'ok';-export const NOT_FOUND = 'not_found';-export const UNSUPPORTED = 'unsupported';-export const STALE = 'stale';-export const EVALUATION_FAILED = 'evaluation_failed';-export type StealthStatus = typeof OK | typeof NOT_FOUND | typeof UNSUPPORTED | typeof STALE | typeof EVALUATION_FAILED;--export class StealthDomError extends Error { constructor(message: string) { super(message); this.name = new.target.name; } }-export class UnsupportedHumanizeSelectorError extends StealthDomError { constructor(selector: string) { super(`Humanized selector ${JSON.stringify(selector)} is not supported by the isolated-world resolver. Supported: CSS, text=, xpath=, getByTestId, getByPlaceholder, getByAltText, getByTitle, getByText, getByLabel, and a trailing .first()/.nth()/.last(). Not supported: getByRole, chained locators (a >> b, .filter(), .and(), .or()), frameLocator, :visible and :nth-match. Use a CSS or text= selector for this action, or humanize:false to fall back to Playwright.`); } }-export class StealthWorldUnavailableError extends StealthDomError { constructor() { super('Humanized DOM read requires an active isolated world'); } }-export class StealthEvaluationError extends StealthDomError { constructor(selector: string) { super(`Isolated-world DOM evaluation failed for ${JSON.stringify(selector)}`); } }--export interface StealthWorld { evaluate(expression: string): Promise<any>; }-export function getWorld(pageOrFrame: unknown): StealthWorld | null { return (pageOrFrame as any)?._stealth ?? null; }-export interface StealthBox { x: number; y: number; width: number; height: number; }-export interface StealthSnapshot { v: typeof PROTOCOL_VERSION; r: typeof OK; targetId: number; gen: number; attached: boolean; visible: boolean; enabled: boolean; editable: boolean; isInput: boolean; focused: boolean; checked: boolean | null; box: StealthBox | null; }-/** Compatibility name used by the humanized action layer. */-export type SnapshotPayload = StealthSnapshot;-export interface StealthPointerPayload { v: typeof PROTOCOL_VERSION; r: typeof OK; targetId: number; gen: number; hit: boolean; covering?: string; }-export interface ParsedResult { status: StealthStatus; data?: any; }--const RESOLVER_BODY = String.raw`-const __UNS = 'UNSUPPORTED';-const __V = 2;-const __STATE_KEY = '__cloakHumanDomV1';-function __state(){- let s = globalThis[__STATE_KEY];- if (!s) {- // Element ids restart at 1 in every new world, and the world is recreated on- // navigation (#507), so an id alone can name a different element after a nav.- // The generation makes that cross-world reuse detectable as 'stale'.- // 11 bits of wall clock + 20 bits of randomness. The maximum is exactly- // Int32.MaxValue, because the .NET wrapper carries the value as an Int32.- s = { ids: new WeakMap(), nextId: 1,- gen: (Date.now() & 2047) * 1048576 + Math.floor(Math.random() * 1048576) };- Object.defineProperty(globalThis, __STATE_KEY, { value: s, configurable: false, enumerable: false });- }- return s;-}-function __gen(){ return __state().gen; }-function __targetId(el){- const s = __state();- let id = s.ids.get(el);- if (!id) { id = s.nextId++; s.ids.set(el, id); }- return id;-}-function __visibleTextNode(node){- const range = node.ownerDocument.createRange();- range.selectNode(node);- const rect = range.getBoundingClientRect();- return rect.width > 0 && rect.height > 0;-}-function __isVisible(el){- const style = getComputedStyle(el);- if (!style) return true;- if (style.display === 'contents') {- for (let child = el.firstChild; child; child = child.nextSibling) {- if (child.nodeType === 1 && __isVisible(child)) return true;- if (child.nodeType === 3 && style.visibility === 'visible' && __visibleTextNode(child)) return true;- }- return false;- }- try {- if (typeof el.checkVisibility === 'function' && !el.checkVisibility()) return false;- } catch (e) {- // Older engines fall through to computed style + geometry.- }- if (style.visibility !== 'visible') return false;- const rect = el.getBoundingClientRect();- return rect.width > 0 && rect.height > 0;-}-function __visBox(el){- const style = getComputedStyle(el);- if (style && style.display === 'contents') {- let x1 = Infinity, y1 = Infinity, x2 = -Infinity, y2 = -Infinity;- let found = false;- for (let child = el.firstChild; child; child = child.nextSibling) {- let box = null;- if (child.nodeType === 1 && __isVisible(child)) {- box = __visBox(child);- } else if (child.nodeType === 3 && style.visibility === 'visible' &&- __normWS(child.nodeValue)) {- const range = child.ownerDocument.createRange();- range.selectNode(child);- const rect = range.getBoundingClientRect();- if (rect.width > 0 && rect.height > 0) {- box = { x: rect.x, y: rect.y, width: rect.width, height: rect.height };- }- }- if (!box) continue;- found = true;- x1 = Math.min(x1, box.x);- y1 = Math.min(y1, box.y);- x2 = Math.max(x2, box.x + box.width);- y2 = Math.max(y2, box.y + box.height);- }- return found ? { x: x1, y: y1, width: x2 - x1, height: y2 - y1 } : null;- }- const rect = el.getBoundingClientRect();- return rect.width > 0 && rect.height > 0- ? { x: rect.x, y: rect.y, width: rect.width, height: rect.height }- : null;-}-const __ARIA_DISABLED_ROLES = new Set([- 'application','button','composite','gridcell','group','input','link','menuitem',- 'scrollbar','separator','tab','checkbox','columnheader','combobox','grid','listbox',- 'menu','menubar','menuitemcheckbox','menuitemradio','option','radio','radiogroup',- 'row','rowheader','searchbox','select','slider','spinbutton','switch','tablist',- 'textbox','toolbar','tree','treegrid','treeitem'-]);-const __ARIA_READONLY_ROLES = new Set([- 'checkbox','combobox','grid','gridcell','listbox','radiogroup','slider','spinbutton',- 'textbox','columnheader','rowheader','searchbox','switch','treegrid'-]);-function __role(el){- const explicit = (el.getAttribute('role') || '').trim().split(/\s+/)[0];- if (explicit) return explicit;- const tag = el.tagName.toLowerCase();- if (tag === 'button') return 'button';- if (tag === 'textarea') return 'textbox';- if (tag === 'select') return el.multiple ? 'listbox' : 'combobox';- if (tag === 'option') return 'option';- if ((tag === 'a' || tag === 'area') && el.hasAttribute('href')) return 'link';- if (tag === 'input') {- const type = (el.type || 'text').toLowerCase();- if (['button','submit','reset','image'].includes(type)) return 'button';- if (type === 'checkbox') return 'checkbox';- if (type === 'radio') return 'radio';- if (type === 'range') return 'slider';- if (type === 'number') return 'spinbutton';- if (type === 'search') return 'searchbox';- if (!['hidden','file','color'].includes(type)) return 'textbox';- }- return '';-}-function __nativeDisabled(el){- const tag = el.tagName.toLowerCase();- if (!['button','input','select','textarea','option','optgroup'].includes(tag)) return false;- if (el.hasAttribute('disabled')) return true;- if (tag === 'option' && el.closest('optgroup[disabled]')) return true;- const fieldset = el.closest('fieldset[disabled]');- if (!fieldset) return false;- const legend = fieldset.querySelector(':scope > legend');- return !legend || !legend.contains(el);-}-function __ariaDisabled(el){- if (!__ARIA_DISABLED_ROLES.has(__role(el))) return false;- let current = el;- while (current) {- const value = (current.getAttribute('aria-disabled') || '').toLowerCase();- if (value === 'true') return true;- if (value === 'false') return false;- current = __composedParent(current);- }- return false;-}-function __isEnabled(el){ return !(__nativeDisabled(el) || __ariaDisabled(el)); }-function __readonly(el){- const tag = el.tagName.toLowerCase();- if (tag === 'input' || tag === 'textarea' || tag === 'select') return el.hasAttribute('readonly');- if (__ARIA_READONLY_ROLES.has(__role(el))) return el.getAttribute('aria-readonly') === 'true';- if (el.isContentEditable) return false;- return null;-}-function __isEditable(el, enabled){- const readonly = __readonly(el);- return readonly === null ? false : enabled && !readonly;-}-function __normWS(s){- return (s || '').replace(/[\u200b\u00ad]/g, '').replace(/\s+/g, ' ').trim();-}-function __skipText(el){- const tag = el && el.tagName ? el.tagName.toLowerCase() : '';- return tag === 'script' || tag === 'style' || tag === 'noscript' ||- (document.head && document.head.contains(el));-}-function __elementText(el, cache){- if (cache.has(el)) return cache.get(el);- let out = { full: '', normalized: '', immediate: [] };- cache.set(el, out);- if (__skipText(el)) return out;- const tag = el.tagName ? el.tagName.toLowerCase() : '';- if (tag === 'input' && ['button', 'submit', 'reset'].includes((el.type || '').toLowerCase())) {- const value = el.value || '';- out = { full: value, normalized: __normWS(value), immediate: [value] };- cache.set(el, out);- return out;- }- if (!el.childNodes) {- const value = el.textContent || '';- out = { full: value, normalized: __normWS(value), immediate: value ? [value] : [] };- cache.set(el, out);- return out;- }- let full = '', immediate = '';- const fragments = [];- for (const child of el.childNodes) {- if (child.nodeType === 3) {- const value = child.nodeValue || '';- full += value;- immediate += value;- } else if (child.nodeType === 8) {- continue;- } else {- if (immediate) { fragments.push(immediate); immediate = ''; }- if (child.nodeType === 1) full += __elementText(child, cache).full;- }- }- if (immediate) fragments.push(immediate);- if (el.shadowRoot) full += __elementText(el.shadowRoot, cache).full;- out = { full: full, normalized: __normWS(full), immediate: fragments };- cache.set(el, out);- return out;-}-function __byXPath(xp){- try {- const r = document.evaluate(xp, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);- const out = [];- for (let i = 0; i < r.snapshotLength; i++) { out.push(r.snapshotItem(i)); }- return out;- } catch (e) { return __UNS; }-}-function __parseTextMatcher(arg){- arg = arg.trim();- if (arg.charAt(0) === '/') {- let end = -1, escaped = false;- for (let i = 1; i < arg.length; i++) {- const ch = arg.charAt(i);- if (!escaped && ch === '/') end = i;- escaped = !escaped && ch === '\\';- if (ch !== '\\') escaped = false;- }- if (end > 0) {- try { return { kind: 'regex', regex: new RegExp(arg.slice(1, end), arg.slice(end + 1)) }; }- catch (e) { return __UNS; }- }- }- const q = arg.charAt(0);- if ((q === '"' || q === "'") && arg.charAt(arg.length - 1) === q) {- let value;- try {- value = q === '"' ? JSON.parse(arg) : arg.slice(1, -1).replace(/\\(['"\\])/g, '$1');- } catch (e) { return __UNS; }- return { kind: 'exact', value: __normWS(value) };- }- return { kind: 'lax', value: __normWS(arg).toLowerCase() };-}-function __matchTextValue(text, matcher){- if (matcher.kind === 'regex') { matcher.regex.lastIndex = 0; return matcher.regex.test(text.full); }- // The public engine's exact rule compares immediate text-node runs, unlike- // internal:text which compares the full normalized subtree text.- if (matcher.kind === 'exact') return text.immediate.some(x => __normWS(x) === matcher.value);- return text.normalized.toLowerCase().includes(matcher.value);-}-function __matchText(el, matcher, cache){- return __matchTextValue(__elementText(el, cache), matcher);-}-function __publicTextMatches(el, matcher, cache){- // Playwright's elementMatchesText for the public text= engine.- if (__skipText(el)) return 'none';- if (!__matchText(el, matcher, cache)) return 'none';- for (const child of el.children || []) {- if (__matchText(child, matcher, cache)) return 'selfAndChildren';- }- // A host whose shadow content also matches is not the smallest match. This- // cannot be expressed with contains(), which does not pierce shadow roots.- if (el.shadowRoot && __matchTextValue(__elementText(el.shadowRoot, cache), matcher))- return 'selfAndChildren';- return 'self';-}-function __byText(arg){- const matcher = __parseTextMatcher(arg);- if (matcher === __UNS) return __UNS;- const out = [], cache = new Map();- let lastMiss = null;- for (const el of __allElements()) {- // Nothing under a non-matching ancestor can match in lax mode.- if (matcher.kind === 'lax' && lastMiss && lastMiss.contains(el)) continue;- const m = __publicTextMatches(el, matcher, cache);- if (m === 'none') lastMiss = el;- // The public engine also keeps an ancestor when the match is exact.- if (m === 'self' || (m === 'selfAndChildren' && matcher.kind === 'exact')) out.push(el);- }- return out;-}-function __attrUnquote(s, i){- // parseAttributeSelector.readQuotedString: a backslash is dropped and the next- // character taken verbatim -- NOT JSON escapes, so "a\\nb" decodes to 'anb'.- const quote = s.charAt(i);- if (quote !== '"' && quote !== "'") return __UNS;- let out = '';- i++;- while (i < s.length && s.charAt(i) !== quote) {- if (s.charAt(i) === '\\') {- i++;- if (i >= s.length) return __UNS;- }- out += s.charAt(i++);- }- if (s.charAt(i) !== quote) return __UNS;- return { value: out, end: i + 1 };-}-function __parseAttrBody(body){- // [name="value"i] | [name="value"s] | [name=/re/flags]- body = body.trim();- if (body.charAt(0) !== '[' || body.charAt(body.length - 1) !== ']') return __UNS;- const inner = body.slice(1, -1);- const eq = inner.indexOf('=');- if (eq <= 0) return __UNS;- let name = inner.slice(0, eq).trim();- if (name.charAt(0) === '"' || name.charAt(0) === "'") {- const un = __attrUnquote(name, 0);- if (un === __UNS || un.end !== name.length) return __UNS;- name = un.value;- }- // isCSSNameChar, plus ',' for the comma-joined test-id name list. Also rejects- // the *= ^= $= |= ~= operators, whose extra character lands in the name.- if (!/^[\w\u0080-\uFFFF,-]+$/.test(name)) return __UNS;- const rest = inner.slice(eq + 1);- let j = 0;- while (j < rest.length && /\s/.test(rest.charAt(j))) j++;- if (rest.charAt(j) === '/') {- const end = rest.lastIndexOf('/');- if (end <= j) return __UNS;- const flags = rest.slice(end + 1).trim();- if (!/^[dgimsuvy]*$/.test(flags)) return __UNS;- try { return { name: name, regex: new RegExp(rest.slice(j + 1, end), flags), value: null, caseSensitive: true }; }- catch (e) { return __UNS; }- }- const un = __attrUnquote(rest, j);- if (un === __UNS) return __UNS;- let k = un.end, caseSensitive = true;- const flag = rest.charAt(k);- if (flag === 'i' || flag === 'I') { caseSensitive = false; k++; }- else if (flag === 's' || flag === 'S') { caseSensitive = true; k++; }- while (k < rest.length && /\s/.test(rest.charAt(k))) k++;- if (k !== rest.length) return __UNS;- return { name: name, regex: null, value: un.value, caseSensitive: caseSensitive };-}-function __byAttr(body){- // Serves internal:attr (placeholder/alt/title) AND internal:testid -- the- // attribute name comes from the selector. The 'i' flag means case-insensitive- // SUBSTRING, and the RAW attribute value is compared: no trim, no whitespace- // normalization. get_by_test_id always emits 's', so it is strict equality.- const parsed = __parseAttrBody(body);- if (parsed === __UNS) return __UNS;- const names = parsed.name.split(',');- const lower = (parsed.regex || parsed.caseSensitive) ? null : parsed.value.toLowerCase();- const out = [];- try {- for (const el of __allElements()) {- if (!el.getAttribute) continue;- for (const name of names) {- const actual = el.getAttribute(name);- if (actual === null || actual === undefined) continue;- let hit;- if (parsed.regex) { parsed.regex.lastIndex = 0; hit = !!String(actual).match(parsed.regex); }- else if (parsed.caseSensitive) hit = actual === parsed.value;- else hit = String(actual).toLowerCase().indexOf(lower) !== -1;- if (hit) { out.push(el); break; }- }- }- } catch (e) { return __UNS; }- return out;-}-function __parseInternalTextMatcher(arg){- // createTextMatcher(selector, internal=true). Playwright does not trim here.- if (arg.charAt(0) === '/' && arg.lastIndexOf('/') > 0) {- const end = arg.lastIndexOf('/');- try { return { kind: 'regex', regex: new RegExp(arg.slice(1, end), arg.slice(end + 1)) }; }- catch (e) { return __UNS; }- }- if (arg.length > 1 && arg.charAt(0) === '"') {- let body = null, strict = false;- const last = arg.charAt(arg.length - 1);- if (last === '"') { body = arg; strict = true; }- else if (arg.charAt(arg.length - 2) === '"' && (last === 's' || last === 'i')) {- body = arg.slice(0, -1); strict = last === 's';- } else return __UNS;- let value;- try { value = JSON.parse(body); } catch (e) { return __UNS; }- if (typeof value !== 'string') return __UNS;- const norm = __normWS(value);- return strict ? { kind: 'strict', value: norm } : { kind: 'lax', value: norm.toLowerCase() };- }- // A single-quoted body reaches unquote=JSON.parse in Playwright and throws.- if (arg.length > 1 && arg.charAt(0) === "'" && arg.charAt(arg.length - 1) === "'") return __UNS;- return { kind: 'lax', value: __normWS(arg).toLowerCase() };-}-function __matchInternalText(text, matcher){- if (matcher.kind === 'regex') { matcher.regex.lastIndex = 0; return matcher.regex.test(text.full); }- // strict compares the FULL normalized subtree text. The public text= engine- // compares immediate fragments instead (__matchText) -- genuinely different.- if (matcher.kind === 'strict') return text.normalized === matcher.value;- return text.normalized.toLowerCase().indexOf(matcher.value) !== -1;-}-function __internalTextMatches(el, matcher, cache){- if (__skipText(el)) return 'none';- if (!__matchInternalText(__elementText(el, cache), matcher)) return 'none';- // Direct children only, plus the shadow-root probe -- NOT contains() over the- // match set, which would drop an outer element matched only via a grandchild.- for (const child of el.children || []) {- if (__matchInternalText(__elementText(child, cache), matcher)) return 'selfAndChildren';- }- if (el.shadowRoot && __matchInternalText(__elementText(el.shadowRoot, cache), matcher)) return 'selfAndChildren';- return 'self';-}-function __byInternalText(arg){- const matcher = __parseInternalTextMatcher(arg);- if (matcher === __UNS) return __UNS;- const cache = new Map(), out = [];- let lastMiss = null;- for (const el of __allElements()) {- // lastDidNotMatchSelf: in lax mode nothing under a non-matching ancestor matches.- if (matcher.kind === 'lax' && lastMiss && lastMiss.contains(el)) continue;- const m = __internalTextMatches(el, matcher, cache);- if (m === 'none') lastMiss = el;- if (m === 'self') out.push(el);- }- return out;-}-function __idRefRoot(el){- const root = el.getRootNode ? el.getRootNode() : null;- return (root && typeof root.getElementById === 'function') ? root : document;-}-function __labelledByElements(el){- const ref = el.getAttribute ? el.getAttribute('aria-labelledby') : null;- if (ref === null || ref === undefined) return null;- const root = __idRefRoot(el), out = [];- for (const id of ref.split(/\s+/)) {- if (!id) continue;- const target = root.getElementById(id);- if (target && out.indexOf(target) === -1) out.push(target);- }- return out.length ? out : null;-}-function __elementLabels(el, cache){- // First non-empty source wins: aria-labelledby, then aria-label, then .labels.- const refs = __labelledByElements(el);- if (refs) return refs.map(function(x){ return __elementText(x, cache); });- const aria = el.getAttribute ? el.getAttribute('aria-label') : null;- if (aria !== null && aria !== undefined && aria.trim())- return [{ full: aria, normalized: __normWS(aria), immediate: [aria] }];- const tag = el.tagName ? el.tagName.toUpperCase() : '';- const nonHiddenInput = tag === 'INPUT' && String(el.type || '').toLowerCase() !== 'hidden';- if (nonHiddenInput || ['BUTTON','METER','OUTPUT','PROGRESS','SELECT','TEXTAREA'].indexOf(tag) !== -1) {- // Native .labels already resolves both for/id and a wrapping <label>.- const labels = el.labels;- if (labels) return Array.prototype.slice.call(labels).map(function(x){ return __elementText(x, cache); });- }- return [];-}-function __byLabel(arg){- const matcher = __parseInternalTextMatcher(arg);- if (matcher === __UNS) return __UNS;- const cache = new Map(), out = [];- try {- for (const el of __allElements()) {- const labels = __elementLabels(el, cache);- for (const label of labels) {- if (__matchInternalText(label, matcher)) { out.push(el); break; }- }- }- } catch (e) { return __UNS; }- return out;-}-function __allElements(){- if (!document.children && document.querySelectorAll)- return Array.prototype.slice.call(document.querySelectorAll('*'));- const out = [];- function visitRoot(root){- const light = [];- function collectLight(parent){- for (const el of parent.children || []) {- out.push(el);- light.push(el);- collectLight(el);- }- }- collectLight(root);- for (const host of light) {- if (host.shadowRoot) visitRoot(host.shadowRoot);- }- }- visitRoot(document);- return out;-}-function __readQuoted(value){- value = value.trim();- const q = value.charAt(0);- if ((q !== '"' && q !== "'") || value.charAt(value.length - 1) !== q) return __UNS;- try {- return q === '"' ? JSON.parse(value) : value.slice(1, -1).replace(/\\(['"\\])/g, '$1');- } catch (e) { return __UNS; }-}-function __parseCompound(compound){- let css = '', i = 0;- const texts = [];- while (i < compound.length) {- if (compound.slice(i, i + 10) !== ':has-text(') { css += compound.charAt(i++); continue; }- let j = i + 10, quote = '', escaped = false, depth = 1;- for (; j < compound.length; j++) {- const ch = compound.charAt(j);- if (quote) {- if (!escaped && ch === quote) quote = '';- escaped = !escaped && ch === '\\';- if (ch !== '\\') escaped = false;- continue;- }- if (ch === '"' || ch === "'") { quote = ch; continue; }- if (ch === '(') depth++;- else if (ch === ')' && --depth === 0) break;- }- if (depth !== 0) return __UNS;- const text = __readQuoted(compound.slice(i + 10, j));- if (text === __UNS) return __UNS;- texts.push(__normWS(text).toLowerCase());- i = j + 1;- }- css = css.trim() || '*';- if (css.includes(':has-text') || /:(?:text|text-is|text-matches|visible|nth-match)\b/.test(css)) return __UNS;- return { css: css, texts: texts };-}-function __splitSelectorList(css){- const parts = [];- let buf = '', quote = '', escaped = false, brackets = 0, parens = 0;- for (let i = 0; i < css.length; i++) {- const ch = css.charAt(i);- if (escaped) { buf += ch; escaped = false; continue; }- if (ch === '\\') { buf += ch; escaped = true; continue; }- if (quote) {- buf += ch;- if (ch === quote) quote = '';- continue;- }- if (ch === '"' || ch === "'") { quote = ch; buf += ch; continue; }- if (ch === '[') brackets++;- else if (ch === ']') brackets--;- else if (ch === '(') parens++;- else if (ch === ')') parens--;- if (ch === ',' && brackets === 0 && parens === 0) {- if (!buf.trim()) return __UNS;- parts.push(buf.trim()); buf = ''; continue;- }- buf += ch;- }- if (quote || brackets !== 0 || parens !== 0 || !buf.trim()) return __UNS;- parts.push(buf.trim());- return parts;-}-function __parseCss(css){- const compounds = [], combinators = [];- let buf = '', quote = '', escaped = false, brackets = 0, parens = 0;- function pushCompound(){- const value = buf.trim();- if (!value) return false;- const parsed = __parseCompound(value);- if (parsed === __UNS) return __UNS;- compounds.push(parsed); buf = ''; return true;- }- for (let i = 0; i < css.length; i++) {- const ch = css.charAt(i);- if (quote) {- buf += ch;- if (!escaped && ch === quote) quote = '';- escaped = !escaped && ch === '\\';- if (ch !== '\\') escaped = false;- continue;- }- if (ch === '"' || ch === "'") { quote = ch; buf += ch; continue; }- if (ch === '[') { brackets++; buf += ch; continue; }- if (ch === ']') { brackets--; buf += ch; continue; }- if (ch === '(') { parens++; buf += ch; continue; }- if (ch === ')') { parens--; buf += ch; continue; }- if (brackets === 0 && parens === 0 && (ch === '>' || ch === '+' || ch === '~')) {- const pushed = pushCompound();- if (pushed === __UNS || !pushed) return __UNS;- combinators.push(ch);- while (i + 1 < css.length && /\s/.test(css.charAt(i + 1))) i++;- continue;- }- if (brackets === 0 && parens === 0 && /\s/.test(ch)) {- let j = i;- while (j + 1 < css.length && /\s/.test(css.charAt(j + 1))) j++;- const next = css.charAt(j + 1);- if (buf.trim() && next !== '>' && next !== '+' && next !== '~') {- const pushed = pushCompound();- if (pushed === __UNS) return __UNS;- combinators.push(' ');- }- i = j;- continue;- }- buf += ch;- }- const pushed = pushCompound();- if (pushed === __UNS) return __UNS;- if (!compounds.length || combinators.length !== compounds.length - 1) return __UNS;- return { compounds: compounds, combinators: combinators };-}-function __composedParent(el){- if (el.parentElement) return el.parentElement;- const root = el.getRootNode ? el.getRootNode() : null;- return root && root.host ? root.host : null;-}-function __matchesCompound(el, compound, cache){- try { if (typeof el.matches === 'function' && !el.matches(compound.css)) return false; }- catch (e) { return false; }- if (!compound.texts.length) return true;- const text = __elementText(el, cache).normalized.toLowerCase();- return compound.texts.every(x => text.includes(x));-}-function __matchesCss(el, parsed, cache){- let idx = parsed.compounds.length - 1, current = el;- if (!__matchesCompound(current, parsed.compounds[idx], cache)) return false;- while (idx > 0) {- const comb = parsed.combinators[idx - 1];- idx--;- if (comb === '>') {- current = __composedParent(current);- if (!current || !__matchesCompound(current, parsed.compounds[idx], cache)) return false;- } else if (comb === ' ') {- let parent = __composedParent(current), found = null;- while (parent) {- if (__matchesCompound(parent, parsed.compounds[idx], cache)) { found = parent; break; }- parent = __composedParent(parent);- }- if (!found) return false;- current = found;- } else {- let sibling = current.previousElementSibling;- if (comb === '+') {- if (!sibling || !__matchesCompound(sibling, parsed.compounds[idx], cache)) return false;- current = sibling;- } else {- let found = null;- while (sibling) {- if (__matchesCompound(sibling, parsed.compounds[idx], cache)) { found = sibling; break; }- sibling = sibling.previousElementSibling;- }- if (!found) return false;- current = found;- }- }- }- return true;-}-function __byCss(css){- if (css.includes(':scope')) return __UNS;- const branches = __splitSelectorList(css);- if (branches === __UNS) return __UNS;- const parsed = branches.map(__parseCss);- if (parsed.some(x => x === __UNS)) return __UNS;- const cache = new Map();- return __allElements().filter(- el => parsed.some(branch => __matchesCss(el, branch, cache))- );-}-function __deepElementFromPoint(x, y){- let target = document.elementFromPoint(x, y);- while (target && target.shadowRoot &&- typeof target.shadowRoot.elementFromPoint === 'function') {- const inner = target.shadowRoot.elementFromPoint(x, y);- if (!inner || inner === target) break;- target = inner;- }- return target;-}-function __deepActiveElement(){- let active = document.activeElement;- while (active && active.shadowRoot && active.shadowRoot.activeElement) {- active = active.shadowRoot.activeElement;- }- return active;-}-function __resolve(sel){- sel = sel.trim();- // Trailing ">> nth=N" (.first => nth=0, .last => nth=-1, .nth(k) => nth=k).- let nth = 0, hasNth = false;- const m = sel.match(/^([\s\S]*?)\s*>>\s*nth=(-?\d+)\s*$/);- if (m) { sel = m[1].trim(); nth = parseInt(m[2], 10); hasNth = true; }- if (sel.indexOf('>>') !== -1) return __UNS; // chaining we don't reimplement- let list;- // get_by_* engines we reimplement. Anything else under internal: (role, has,- // has-text, and, or, chain, control, describe) stays unsupported.- if (sel.indexOf('internal:testid=') === 0) { list = __byAttr(sel.slice(16)); }- else if (sel.indexOf('internal:attr=') === 0) { list = __byAttr(sel.slice(14)); }- else if (sel.indexOf('internal:text=') === 0) { list = __byInternalText(sel.slice(14)); }- else if (sel.indexOf('internal:label=') === 0) { list = __byLabel(sel.slice(15)); }- else if (sel.indexOf('internal:') !== -1) return __UNS;- else if (sel.indexOf('xpath=') === 0) { list = __byXPath(sel.slice(6)); }- else if (sel.indexOf('//') === 0 || sel.indexOf('(//') === 0 || sel.indexOf('..') === 0) { list = __byXPath(sel); }- else if (sel.indexOf('text=') === 0) { list = __byText(sel.slice(5)); }- else {- const css = (sel.indexOf('css=') === 0) ? sel.slice(4) : sel;- list = __byCss(css);- }- if (list === __UNS) return __UNS;- if (!list || !list.length) return null;- let idx = hasNth ? (nth < 0 ? list.length + nth : nth) : 0;- if (idx < 0 || idx >= list.length) return null;- return list[idx];-}-`;-const SNAPSHOT_OP=String.raw`-const __el=__resolve(__SEL);if(__el==='UNSUPPORTED')return {v:__V,r:'unsupported'};if(!__el)return {v:__V,r:'not_found'};const __box=__visBox(__el),__hasBox=__box!==null,__tag=__el.tagName.toLowerCase(),__enabled=__isEnabled(__el),__editable=__isEditable(__el,__enabled);return {v:__V,r:'ok',targetId:__targetId(__el),gen:__gen(),attached:__el.isConnected===true,visible:__isVisible(__el),enabled:__enabled,editable:__editable,isInput:__tag==='input'||__tag==='textarea'||__el.isContentEditable===true,focused:__deepActiveElement()===__el,checked:typeof __el.checked==='boolean'?__el.checked:null,box:__box};`;-export const VIEWPORT_JS='(() => ({ width: window.innerWidth, height: window.innerHeight }))()';-function wrap(selector:string,op:string){return `(() => {\nconst __SEL = ${JSON.stringify(selector)};\n${RESOLVER_BODY}\n${op}\n})()`;}-export function buildSnapshotJs(selector:string){return wrap(selector,SNAPSHOT_OP);}-export function buildBoxJs(selector:string){return wrap(selector,SNAPSHOT_OP.replace("r:'ok'","r:__hasBox?'ok':'not_found'"));}-export function buildActionableJs(selector:string){return buildSnapshotJs(selector);}-function pointer(selector:string,targetId:number|undefined,gen:number|undefined,x:number,y:number,validate:boolean){const check=validate?`if(__g!==${Math.trunc(gen!)})return {v:__V,r:'stale',targetId:__id,gen:__g};if(__id!==${Math.trunc(targetId!)})return {v:__V,r:'stale',targetId:__id,gen:__g};if(__el.isConnected!==true)return {v:__V,r:'stale',targetId:__id,gen:__g};`:'';return wrap(selector,`const __el=__resolve(__SEL);if(__el==='UNSUPPORTED')return {v:__V,r:'unsupported'};if(!__el)return {v:__V,r:'not_found'};const __g=__gen();const __id=__targetId(__el);${check}const __t=__deepElementFromPoint(${Number(x)},${Number(y)});let __n=__t;while(__n){if(__n===__el)return {v:__V,r:'ok',targetId:__id,gen:__g,hit:true};__n=__composedParent(__n);}if(__t&&__el.contains(__t))return {v:__V,r:'ok',targetId:__id,gen:__g,hit:true};return {v:__V,r:'ok',targetId:__id,gen:__g,hit:false,covering:__t?(__t.tagName||'unknown'):'none'};`);}-export function buildValidateJs(selector:string,targetId:number,gen:number,x:number,y:number){return pointer(selector,targetId,gen,x,y,true);}-export function buildPointerJs(selector:string,x:number,y:number){return pointer(selector,undefined,undefined,x,y,false);}-export function parseResult(raw:any):ParsedResult{if(!raw||typeof raw!=='object'||Array.isArray(raw)||raw.v!==PROTOCOL_VERSION)return{status:EVALUATION_FAILED};if(raw.r===OK)return Number.isInteger(raw.targetId)&&Number.isInteger(raw.gen)?{status:OK,data:raw}:{status:EVALUATION_FAILED};if(raw.r===NOT_FOUND)return{status:NOT_FOUND};if(raw.r===STALE)return Number.isInteger(raw.targetId)&&Number.isInteger(raw.gen)?{status:STALE,data:raw}:{status:EVALUATION_FAILED};if(raw.r===UNSUPPORTED)return{status:UNSUPPORTED};return{status:EVALUATION_FAILED};}-export async function evalParsed(world:StealthWorld,expression:string):Promise<ParsedResult>{try{return parseResult(await world.evaluate(expression));}catch{return{status:EVALUATION_FAILED};}}diff --git a/js/src/human/world.ts b/js/src/human/world.tsnew file mode 100644index 0000000..4bb5104--- /dev/null+++ b/js/src/human/world.ts@@ -0,0 +1,376 @@+/**+ * CDP isolated worlds for every frame of a page (main, same-process, OOPIF).+ *+ * Each frame gets one isolated world per document, created through+ * `Page.createIsolatedWorld` on the CDP session that owns the frame. Into that+ * world we install Playwright's InjectedScript (see injected.ts) and a small+ * helper object:+ *+ * - frame <-> CDP frame id mapping uses `Page.getFrameTree` only;+ * - iframe owner elements are reached via `DOM.getFrameOwner` ++ * `DOM.resolveNode` straight into the parent frame's isolated world;+ * - elements are kept in a world-local registry and addressed by integer ids.+ *+ * Port of cloakbrowser/human/world.py.+ */++import type { CDPSession, Frame, Page } from 'playwright-core';+import { GLOBAL, buildInstallJs, findInjectedLiteral } from './injected.js';+import { HELPERS, HELPERS_JS } from './worldHelpers.js';++export { HELPERS };++let decodedSource: string | null = null;++export class StealthWorldError extends Error {+ constructor(message: string) { super(message); this.name = 'StealthWorldError'; }+}++export class StaleElement extends Error {+ constructor() { super('element is not attached to the DOM'); this.name = 'StaleElement'; }+}++export interface Rect { x: number; y: number; width: number; height: number; }++const STALE_MARKERS = [+ 'Cannot find context', 'Execution context was destroyed', 'Inspected target navigated',+ 'cloak:stale-world', 'Cannot find default execution context',+];+const isStale = (e: unknown) => STALE_MARKERS.some((s) => String((e as any)?.message ?? e).includes(s));++interface FrameRec { session: CDPSession; cdpId: string; ctx: number | null; }++export function intersect(a: Rect, b: Rect): Rect {+ const x0 = Math.max(a.x, b.x), y0 = Math.max(a.y, b.y);+ const x1 = Math.min(a.x + a.width, b.x + b.width);+ const y1 = Math.min(a.y + a.height, b.y + b.height);+ return { x: x0, y: y0, width: Math.max(0, x1 - x0), height: Math.max(0, y1 - y0) };+}++function isDescendant(frame: Frame, ancestor: Frame): boolean {+ for (let p = frame.parentFrame(); p; p = p.parentFrame()) if (p === ancestor) return true;+ return false;+}++function findNode(tree: any, cdpId: string): any {+ if (tree.frame.id === cdpId) return tree;+ for (const c of tree.childFrames ?? []) {+ const f = findNode(c, cdpId);+ if (f) return f;+ }+ return null;+}++/**+ * Pick the CDP child frame for a Playwright frame. Playwright and CDP list+ * child frames in attach order; frames sharing the same (name, url) are+ * matched by their position within that group.+ */+export function matchChild(frame: Frame, parent: Frame, kids: any[]): string | null {+ const keyPw = (f: Frame) => `${f.name()}\u0000${f.url()}`;+ const keyCdp = (k: any) => `${k.name ?? ''}\u0000${(k.url ?? '') + (k.urlFragment ?? '')}`;+ const want = keyPw(frame);+ const cands = kids.filter((k) => keyCdp(k) === want);+ const siblings = parent.childFrames();+ const peers = siblings.filter((f) => keyPw(f) === want);+ if (cands.length && peers.includes(frame) && cands.length === peers.length) return cands[peers.indexOf(frame)].id;+ if (cands.length === 1) return cands[0].id;+ if (kids.length === siblings.length && siblings.includes(frame)) return kids[siblings.indexOf(frame)].id;+ return null;+}++async function release(session: CDPSession, objectId: string): Promise<void> {+ try { await session.send('Runtime.releaseObject', { objectId }); } catch { /* gone */ }+}++/** Isolated worlds for all frames of one Playwright page. */+export class Worlds {+ readonly page: Page;+ private _session: CDPSession | null = null;+ private _sessionP: Promise<CDPSession> | null = null;+ private frames = new Map<Frame, FrameRec>();+ private locating = new Map<Frame, Promise<FrameRec>>();+ private lock: Promise<unknown> = Promise.resolve();++ constructor(page: Page) {+ this.page = page;+ try {+ page.on('framenavigated', (f) => this.invalidate(f));+ page.on('framedetached', (f) => this.invalidate(f));+ } catch { /* emitter missing in mocks */ }+ }++ // -- sessions / frame mapping -------------------------------------------++ async session(): Promise<CDPSession> {+ if (this._session) return this._session;+ if (!this._sessionP) this._sessionP = this.page.context().newCDPSession(this.page);+ try {+ this._session = await this._sessionP;+ } finally {+ this._sessionP = null;+ }+ return this._session;+ }++ /** Forget worlds of `frame` and its descendants (all when undefined). */+ invalidate(frame?: Frame): void {+ if (!frame) { this.frames.clear(); return; }+ for (const f of [...this.frames.keys()]) if (f === frame || isDescendant(f, frame)) this.frames.delete(f);+ }++ private async locate(frame: Frame): Promise<FrameRec> {+ const rec = this.frames.get(frame);+ if (rec) return rec;+ const pending = this.locating.get(frame);+ if (pending) return pending;+ const p = (async () => {+ if (frame.isDetached()) throw new Error('Frame was detached');+ const parent = frame.parentFrame();+ let r: FrameRec;+ if (!parent) {+ const session = await this.session();+ const tree: any = await session.send('Page.getFrameTree');+ r = { session, cdpId: tree.frameTree.frame.id, ctx: null };+ } else {+ r = await this.locateChild(frame, parent);+ }+ this.frames.set(frame, r);+ return r;+ })();+ this.locating.set(frame, p);+ try { return await p; } finally { this.locating.delete(frame); }+ }++ private async locateChild(frame: Frame, parent: Frame): Promise<FrameRec> {+ let own: CDPSession | null = null;+ try { // out-of-process iframe: it has its own target/session+ own = await this.page.context().newCDPSession(frame);+ } catch { own = null; }+ if (own) {+ const tree: any = await own.send('Page.getFrameTree');+ return { session: own, cdpId: tree.frameTree.frame.id, ctx: null };+ }+ const prec = await this.locate(parent);+ const tree: any = await prec.session.send('Page.getFrameTree');+ const node = findNode(tree.frameTree, prec.cdpId);+ const kids = (node?.childFrames ?? []).map((k: any) => k.frame);+ const cdpId = matchChild(frame, parent, kids);+ if (!cdpId) throw new Error('cloakbrowser humanize: could not map the frame to a CDP frame');+ return { session: prec.session, cdpId, ctx: null };+ }++ async cdpFrameId(frame: Frame): Promise<string> { return (await this.locate(frame)).cdpId; }++ async frameForCdpId(parent: Frame, cdpId: string): Promise<Frame | null> {+ for (const child of parent.childFrames()) {+ try { if ((await this.locate(child)).cdpId === cdpId) return child; } catch { /* skip */ }+ }+ return null;+ }++ // -- world lifecycle ----------------------------------------------------++ async ready(frame: Frame): Promise<FrameRec> {+ const rec = await this.locate(frame);+ if (rec.ctx !== null) return rec;+ const run = this.lock.then(async () => {+ if (rec.ctx !== null) return;+ const res: any = await rec.session.send('Page.createIsolatedWorld', {+ frameId: rec.cdpId, worldName: '', grantUniveralAccess: true,+ });+ const ctx = res.executionContextId as number;+ await this.install(rec.session, ctx);+ rec.ctx = ctx;+ });+ this.lock = run.catch(() => undefined);+ await run;+ return rec;+ }++ private async install(session: CDPSession, ctx: number): Promise<void> {+ if (decodedSource === null) decodedSource = await Worlds.rawEval(session, ctx, findInjectedLiteral());+ await Worlds.rawEval(session, ctx, buildInstallJs(decodedSource!));+ await Worlds.rawEval(session, ctx, HELPERS_JS);+ }++ static async rawEval(session: CDPSession, ctx: number, expression: string, byValue = true): Promise<any> {+ const res: any = await session.send('Runtime.evaluate', {+ expression, contextId: ctx, returnByValue: byValue, awaitPromise: true,+ });+ if (res.exceptionDetails) {+ const det = res.exceptionDetails;+ const desc: string = det.exception?.description || det.text || '';+ if (desc.includes('cloak:stale-element')) throw new StaleElement();+ throw new StealthWorldError(`cloakbrowser humanize: isolated-world script failed: ${desc.split('\n')[0]}`);+ }+ return byValue ? res.result?.value : res.result;+ }++ // -- evaluation ---------------------------------------------------------++ /** Evaluate in `frame`'s isolated world; recreate the world once if stale. */+ async evaluate(frame: Frame, expression: string, byValue = true): Promise<any> {+ for (let attempt = 0; attempt < 2; attempt++) {+ const rec = await this.ready(frame);+ try {+ return await Worlds.rawEval(rec.session, rec.ctx!, expression, byValue);+ } catch (e) {+ if (e instanceof StaleElement) throw e;+ if (attempt === 0 && isStale(e)) { rec.ctx = null; continue; }+ throw e;+ }+ }+ throw new StealthWorldError('cloakbrowser humanize: isolated world unavailable');+ }++ call(frame: Frame, method: string, ...args: unknown[]): Promise<any> {+ return this.evaluate(frame, `${HELPERS}.${method}(${args.map((a) => JSON.stringify(a)).join(', ')})`);+ }++ async elementObjectId(frame: Frame, id: number): Promise<[CDPSession, string]> {+ const rec = await this.ready(frame);+ const obj = await Worlds.rawEval(rec.session, rec.ctx!, `${HELPERS}.el(${Math.trunc(id)})`, false);+ return [rec.session, obj.objectId];+ }++ /** Register the DOM node `backendNodeId` in `frame`'s world. */+ async adopt(frame: Frame, backendNodeId: number): Promise<number> {+ const rec = await this.ready(frame);+ let obj: any;+ try {+ obj = (await rec.session.send('DOM.resolveNode', { backendNodeId, executionContextId: rec.ctx! } as any) as any).object;+ } catch { throw new StaleElement(); }+ let res: any;+ try {+ res = await rec.session.send('Runtime.callFunctionOn', {+ objectId: obj.objectId, returnByValue: true,+ functionDeclaration: `function () { return globalThis.${HELPERS}.adopt.call(this); }`,+ });+ } finally {+ await release(rec.session, obj.objectId);+ }+ if (res.exceptionDetails) throw new StaleElement();+ return res.result.value;+ }++ /**+ * Segments of a native date/time editor in visual order, with centres+ * relative to the input's border box. They live in the input's closed+ * user-agent shadow root; CDP's DOM domain (`pierce`) sees them without+ * running any script in the page.+ */+ async editorFields(frame: Frame, id: number): Promise<{ kind: string; dx: number; dy: number }[]> {+ const [session, objectId] = await this.elementObjectId(frame, id);+ let node: any, own: number[];+ try {+ node = (await session.send('DOM.describeNode', { objectId, depth: -1, pierce: true }) as any).node;+ own = (await session.send('DOM.getBoxModel', { objectId }) as any).model.border;+ } finally {+ await release(session, objectId);+ }+ const out: { kind: string; dx: number; dy: number }[] = [];+ const walk = async (n: any): Promise<void> => {+ const attrs: string[] = n.attributes ?? [];+ let pseudo = '';+ for (let i = 0; i + 1 < attrs.length; i += 2) if (attrs[i] === 'pseudo') pseudo = attrs[i + 1];+ if (pseudo.startsWith('-webkit-datetime-edit-') && pseudo.endsWith('-field') && !pseudo.includes('wrapper')) {+ const q = (await session.send('DOM.getBoxModel', { backendNodeId: n.backendNodeId }) as any).model.border;+ out.push({+ kind: pseudo.slice('-webkit-datetime-edit-'.length, -'-field'.length),+ dx: (q[0] + q[2]) / 2 - own[0], dy: (q[1] + q[5]) / 2 - own[1],+ });+ }+ for (const c of [...(n.children ?? []), ...(n.shadowRoots ?? [])]) await walk(c);+ };+ await walk(node);+ out.sort((a, b) => (Math.round(a.dy / 4) - Math.round(b.dy / 4)) || (a.dx - b.dx));+ return out;+ }++ /** Register `frame`'s <iframe> element in the parent frame's world. */+ async ownerElement(frame: Frame): Promise<number> {+ const rec = await this.locate(frame);+ const parent = frame.parentFrame()!;+ const prec = await this.ready(parent);+ const owner: any = await prec.session.send('DOM.getFrameOwner', { frameId: rec.cdpId });+ return this.adopt(parent, owner.backendNodeId);+ }++ /** Child frame owned by the <iframe> element `id` in `frame`. */+ async contentFrame(frame: Frame, id: number): Promise<Frame | null> {+ const [session, objectId] = await this.elementObjectId(frame, id);+ let node: any;+ try {+ node = (await session.send('DOM.describeNode', { objectId }) as any).node;+ } finally {+ await release(session, objectId);+ }+ if (!node.frameId) return null;+ return this.frameForCdpId(frame, node.frameId);+ }++ // -- geometry across frames ---------------------------------------------++ /** Call `declaration` with `this` = the frame's <iframe> element, inside+ * the parent frame's isolated world. */+ private async ownerCall(frame: Frame, declaration: string, ...args: unknown[]): Promise<any> {+ const parent = frame.parentFrame()!;+ const rec = await this.locate(frame);+ const prec = await this.ready(parent);+ const owner: any = await prec.session.send('DOM.getFrameOwner', { frameId: rec.cdpId });+ const obj: any = (await prec.session.send('DOM.resolveNode', {+ backendNodeId: owner.backendNodeId, executionContextId: prec.ctx!,+ } as any) as any).object;+ let res: any;+ try {+ res = await prec.session.send('Runtime.callFunctionOn', {+ objectId: obj.objectId, functionDeclaration: declaration,+ arguments: args.map((value) => ({ value })), returnByValue: true,+ });+ } finally {+ await release(prec.session, obj.objectId);+ }+ if (res.exceptionDetails) throw new StealthWorldError('cloakbrowser humanize: frame owner evaluation failed');+ return res.result?.value;+ }++ async viewport(): Promise<{ width: number; height: number }> {+ const size = this.page.viewportSize();+ if (size && size.width) return { width: size.width, height: size.height };+ const doc = await this.call(this.page.mainFrame(), 'doc');+ return { width: doc.width, height: doc.height };+ }++ /** `[offsetX, offsetY, clip]`: the frame's origin in viewport coordinates+ * and the visible part of it (intersection of all ancestor iframe content+ * boxes and the viewport). */+ async frameGeometry(frame: Frame): Promise<[number, number, Rect]> {+ const parent = frame.parentFrame();+ if (!parent) {+ const vp = await this.viewport();+ return [0, 0, { x: 0, y: 0, width: vp.width, height: vp.height }];+ }+ const [px, py, pclip] = await this.frameGeometry(parent);+ const box = await this.ownerCall(frame, `function () { return ${HELPERS}.ownerContent.call(this); }`);+ const ox = px + box.x, oy = py + box.y;+ return [ox, oy, intersect(pclip, { x: ox, y: oy, width: box.width, height: box.height })];+ }++ /** Check that the viewport point hits each ancestor <iframe> owner. */+ async ownersHit(frame: Frame, vx: number, vy: number): Promise<string | null> {+ let child = frame;+ while (child.parentFrame()) {+ const [px, py] = await this.frameGeometry(child.parentFrame()!);+ const desc = await this.ownerCall(+ child,+ `function (x, y) { const r = globalThis.${GLOBAL}.expectHitTarget({ x, y }, this);` ++ ` return r === 'done' ? null : r.hitTargetDescription; }`,+ vx - px, vy - py,+ );+ if (desc) return desc;+ child = child.parentFrame()!;+ }+ return null;+ }+}diff --git a/js/src/human/worldHelpers.ts b/js/src/human/worldHelpers.tsnew file mode 100644index 0000000..1a64694--- /dev/null+++ b/js/src/human/worldHelpers.ts@@ -0,0 +1,253 @@+/**+ * Helper library evaluated after the InjectedScript in every isolated world.+ *+ * Byte-identical copy of cloakbrowser/human/world.py (_HELPERS_JS); checked by+ * tests/test_resolver_sources_match.py. Edit both together.+ */++export const HELPERS = '__cloakH';++export const HELPERS_JS = String.raw`(() => {+if (globalThis.__cloakH) return true;+const I = globalThis.__cloakInjected;+const els = new Map(); let seq = 0;+const put = (e) => { const id = ++seq; els.set(id, e); return id; };+const get = (id) => { const e = els.get(id); if (!e) throw new Error('cloak:stale-element'); return e; };+const textValue = (t) => t.isContentEditable ? t.textContent : ('value' in t ? String(t.value) : null);+// display:contents elements have no box: use the union of what they render.+const contentsBox = (root) => {+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;+ const add = (r) => { if (!r.width && !r.height) return;+ x0 = Math.min(x0, r.left); y0 = Math.min(y0, r.top); x1 = Math.max(x1, r.right); y1 = Math.max(y1, r.bottom); };+ const walk = (n) => {+ for (const c of n.childNodes) {+ if (c.nodeType === 3) {+ if (!c.textContent.trim()) continue;+ const p = c.parentElement;+ if (p && getComputedStyle(p).visibility !== 'visible') continue;+ const rg = document.createRange(); rg.selectNodeContents(c);+ for (const r of rg.getClientRects()) add(r);+ } else if (c.nodeType === 1) {+ const s = getComputedStyle(c);+ if (s.display === 'contents') { walk(c); continue; }+ if (s.visibility !== 'visible' || s.display === 'none') continue;+ add(c.getBoundingClientRect());+ }+ }+ };+ walk(root);+ return x0 === Infinity ? null : { left: x0, top: y0, width: x1 - x0, height: y1 - y0 };+};+const parentOrHost = (n) => n.parentElement || (n.parentNode && n.parentNode.host) || null;+const H = {+ el: (id) => get(id),+ adopt() { return put(this); },+ matchRect(x, y, w, h) {+ // An ElementHandle carries no identity this context can read, but+ // Playwright reports its border box. Find the element with exactly that box.+ const out = [];+ const visit = (root) => {+ for (const e of root.querySelectorAll('*')) {+ if (e.shadowRoot) visit(e.shadowRoot);+ const b = e.getBoundingClientRect();+ if (Math.abs(b.left - x) < 0.6 && Math.abs(b.top - y) < 0.6 &&+ Math.abs(b.width - w) < 0.6 && Math.abs(b.height - h) < 0.6) out.push(e);+ }+ };+ visit(document);+ if (out.length < 2) return out.length ? { count: 1, id: put(out[0]) } : { count: 0 };+ // A wrapper and its same-size descendants form one nested chain: a click+ // lands the same on any of them. Take the element a real click would focus+ // (the deepest focusable one), else the outermost. Unrelated elements that+ // share the box stay ambiguous and the caller raises.+ const depth = (e) => { let d = 0; for (let n = e; n; n = parentOrHost(n)) d++; return d; };+ const within = (a, e) => { for (let n = e; n; n = parentOrHost(n)) if (n === a) return true; return false; };+ const chain = out.map((e) => [depth(e), e]).sort((a, b) => a[0] - b[0]).map((p) => p[1]);+ for (let i = 1; i < chain.length; i++) if (!within(chain[i - 1], chain[i])) return { count: out.length };+ const focusable = chain.filter((e) => !e.disabled && e.matches('a[href], area[href], button, input:not([type="hidden"]), '+ + 'select, textarea, iframe, summary, [tabindex], [contenteditable]:not([contenteditable="false"])'));+ return { count: 1, id: put(focusable.length ? focusable[focusable.length - 1] : chain[0]) };+ },+ release(ids) { for (const id of ids) els.delete(id); },+ resolve(selector, strict, rootId) {+ const root = rootId ? get(rootId) : document;+ let parsed, all;+ try { parsed = I.parseSelector(selector); all = I.querySelectorAll(parsed, root); }+ catch (e) { return { status: 'error', message: e.message }; }+ if (!all.length) return { status: 'none' };+ if (strict && all.length > 1)+ return { status: 'strict', message: I.strictModeViolationError(parsed, all).message };+ return { status: 'ok', id: put(all[0]), count: all.length };+ },+ fromPath(path) {+ let cur = document;+ for (const step of path) {+ if (step === 'S') { cur = cur.shadowRoot; if (!cur) return { status: 'closed-shadow' }; continue; }+ cur = cur.childNodes[step];+ if (!cur) return { status: 'none' };+ }+ if (cur.nodeType !== 1) return { status: 'none' };+ return { status: 'ok', id: put(cur) };+ },+ retarget(id, behavior) { const t = I.retarget(get(id), behavior); return t ? put(t) : 0; },+ info(id) {+ const e = get(id);+ const t = I.retarget(e, 'follow-label') || e;+ const root = t.getRootNode();+ return {+ connected: e.isConnected,+ tag: t.nodeName.toLowerCase(),+ type: t.nodeName === 'INPUT' ? String(t.type).toLowerCase() : null,+ editable: !!t.isContentEditable,+ focused: !!root && root.activeElement === t,+ value: textValue(t),+ preview: I.previewNode(e),+ };+ },+ connected(id) { return get(id).isConnected; },+ value(id) { const e = get(id); return textValue(I.retarget(e, 'follow-label') || e); },+ activeValue() {+ const a = document.activeElement;+ if (!a || a === document.body) return { tag: null };+ return { tag: a.nodeName.toLowerCase(), type: a.nodeName === 'INPUT' ? String(a.type).toLowerCase() : null,+ editable: !!a.isContentEditable, value: textValue(a) };+ },+ async states(id, states) {+ const e = get(id);+ try {+ if (I.checkElementStates) {+ const r = await I.checkElementStates(e, states);+ if (r === undefined) return null;+ if (r === 'error:notconnected') return { missing: 'attached' };+ return { missing: r.missingState };+ }+ for (const s of states) {+ if (s === 'stable') continue;+ const r = I.elementState(e, s);+ if (r === 'error:notconnected' || r.received === 'error:notconnected') return { missing: 'attached' };+ if (!(r.matches !== undefined ? r.matches : r)) return { missing: s };+ }+ return null;+ } catch (err) { return { error: err.message }; }+ },+ checked(id) {+ try {+ const e = get(id), r = I.elementState(e, 'checked');+ if (typeof r === 'object') return { checked: r.received === 'checked', radio: !!r.isRadio };+ // Playwright < 1.50 returns a boolean here.+ const t = I.retarget(e, 'follow-label');+ return { checked: r === true, radio: !!t && t.nodeName === 'INPUT' && t.type === 'radio' };+ }+ catch (err) { return { error: err.message }; }+ },+ geometry(id) {+ const e = get(id);+ if (!e.isConnected) return null;+ let b = e.getBoundingClientRect();+ const st = getComputedStyle(e);+ if (st.display === 'contents') b = contentsBox(e) || b;+ return { x: b.left, y: b.top, width: b.width, height: b.height,+ bl: parseFloat(st.borderLeftWidth) || 0, bt: parseFloat(st.borderTopWidth) || 0 };+ },+ scroller(id) {+ const e = get(id);+ const b = e.getBoundingClientRect();+ const top = document.scrollingElement || document.documentElement;+ for (let p = parentOrHost(e); p && p !== top && p !== document.body; p = parentOrHost(p)) {+ const s = getComputedStyle(p);+ const sy = /(auto|scroll|overlay)/.test(s.overflowY) && p.scrollHeight > p.clientHeight;+ const sx = /(auto|scroll|overlay)/.test(s.overflowX) && p.scrollWidth > p.clientWidth;+ if (!sy && !sx) continue;+ const r = p.getBoundingClientRect();+ const x = r.left + p.clientLeft, y = r.top + p.clientTop, w = p.clientWidth, h = p.clientHeight;+ if ((sy && (b.top < y || b.bottom > y + h)) || (sx && (b.left < x || b.right > x + w)))+ return { x, y, width: w, height: h };+ }+ return null;+ },+ doc() {+ const e = document.scrollingElement || document.documentElement;+ const rangeX = Math.max(0, e.scrollWidth - e.clientWidth);+ const rtl = getComputedStyle(document.body || e).direction === 'rtl';+ return { y: scrollY, maxY: Math.max(0, e.scrollHeight - e.clientHeight), x: scrollX,+ minX: rtl ? -rangeX : 0, maxX: rtl ? 0 : rangeX, width: innerWidth, height: innerHeight };+ },+ hit(id, x, y) {+ const r = I.expectHitTarget({ x, y }, get(id));+ return r === 'done' ? null : r.hitTargetDescription;+ },+ fill(id, value) {+ try { return { result: I.fill(get(id), value) }; } catch (err) { return { error: err.message }; }+ },+ select(id, options, elementIds) {+ const opts = options.concat(elementIds.map(get));+ try {+ const r = I.selectOptions(get(id), opts);+ return Array.isArray(r) ? { values: r } : { error: String(r) };+ } catch (err) { return { error: err.message }; }+ },+ focus(id) { const e = I.retarget(get(id), 'follow-label') || get(id); I.focusNode(e, false); return true; },+ caretAtEnd(id) {+ const t = I.retarget(get(id), 'follow-label') || get(id);+ if ('selectionStart' in t && t.selectionStart !== null) return t.selectionStart === String(t.value).length;+ return false;+ },+ platform() { return navigator.platform || ''; },+ rangeInfo(id) {+ const e = I.retarget(get(id), 'follow-label') || get(id);+ const n = (v, d) => { const x = parseFloat(v); return Number.isFinite(x) ? x : d; };+ const min = n(e.min, 0), max = Math.max(n(e.max, 100), n(e.min, 0));+ const step = e.step === 'any' ? 0 : n(e.step, 1);+ const st = getComputedStyle(e);+ const vertical = st.writingMode.startsWith('vertical') || st.appearance === 'slider-vertical';+ return { min, max, step, value: n(e.value, min), vertical, rtl: st.direction === 'rtl' };+ },+ // The options a select_option() call targets, without changing anything.+ selectPlan(id, options, elementIds) {+ const sel = I.retarget(get(id), 'follow-label') || get(id);+ if (sel.nodeName !== 'SELECT') return { error: 'Element is not a <select> element' };+ const opts = [...sel.options];+ const wanted = options.concat(elementIds.map(get));+ const norm = (s) => s.replace(/\s+/g, ' ').trim();+ const match = (o, i, w) => {+ if (w instanceof Node) return o === w;+ const lbl = (l) => l === o.label || norm(l) === norm(o.label);+ let ok = true;+ if (w.valueOrLabel !== undefined) ok = ok && (w.valueOrLabel === o.value || lbl(w.valueOrLabel));+ if (w.value !== undefined) ok = ok && w.value === o.value;+ if (w.label !== undefined) ok = ok && lbl(w.label);+ if (w.index !== undefined) ok = ok && w.index === i;+ return ok;+ };+ const enabled = (o) => !o.disabled && !(o.parentElement && o.parentElement.nodeName === 'OPTGROUP' && o.parentElement.disabled);+ let remaining = wanted.slice(); const targets = [];+ for (let i = 0; i < opts.length && remaining.length; i++) {+ if (!remaining.some(w => match(opts[i], i, w))) continue;+ if (!enabled(opts[i])) return { retry: 'option being selected is not enabled' };+ targets.push(i);+ remaining = sel.multiple ? remaining.filter(w => !match(opts[i], i, w)) : [];+ }+ if (remaining.length) return { retry: 'did not find some options' };+ return { targets, multiple: sel.multiple, listbox: sel.multiple || sel.size > 1,+ navigable: opts.map(o => enabled(o) && !o.hidden && getComputedStyle(o).display !== 'none'),+ values: targets.map(i => opts[i].value), labels: targets.map(i => norm(opts[i].label)) };+ },+ optionId(id, index) { const sel = I.retarget(get(id), 'follow-label') || get(id); return put(sel.options[index]); },+ selectState(id) {+ const sel = I.retarget(get(id), 'follow-label') || get(id);+ return { current: sel.selectedIndex, selected: [...sel.options].map((o, i) => o.selected ? i : -1).filter(i => i >= 0),+ values: [...sel.selectedOptions].map(o => o.value) };+ },+ ownerContent() {+ // Runs with this = the <iframe> owner element: viewport-relative content box.+ const r = this.getBoundingClientRect(); const s = getComputedStyle(this);+ const bl = parseFloat(s.borderLeftWidth) || 0, bt = parseFloat(s.borderTopWidth) || 0;+ const pl = parseFloat(s.paddingLeft) || 0, pt = parseFloat(s.paddingTop) || 0;+ const pr = parseFloat(s.paddingRight) || 0, pb = parseFloat(s.paddingBottom) || 0;+ return { x: r.left + bl + pl, y: r.top + bt + pt,+ width: Math.max(0, this.clientWidth - pl - pr), height: Math.max(0, this.clientHeight - pt - pb) };+ },+};+Object.defineProperty(globalThis, '__cloakH', { value: H });+return true;+})()`;diff --git a/js/tests/humanize.test.ts b/js/tests/humanize.test.tsindex 69dc7d5..23aa07f 100644--- a/js/tests/humanize.test.ts+++ b/js/tests/humanize.test.ts@@ -247,85 +247,11 @@ describe("clickTarget", () => {});});-// =========================================================================-// patchPage behavioral: fill uses platform SELECT_ALL-// =========================================================================-describe("patchPage fill", () => {- it("fill calls keyboard.press with platform-correct select-all", async () => {- const { patchPage } = await import("../src/human/index.js");-- const pressedKeys: string[] = [];- const page = buildMockPage({- keyboardPress: async (key: string) => { pressedKeys.push(key); },- });-- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- patchPage(page as any, cfg, cursor as any);-- try { await (page as any).fill("input#name", "hello", { timeout: 2000 }); } catch (error) { expect(error).toBeDefined(); }-- const expected = process.platform === "darwin" ? "Meta+a" : "Control+a";- const wrong = process.platform === "darwin" ? "Control+a" : "Meta+a";- if (pressedKeys.length > 0) {- expect(pressedKeys).toContain(expected);- expect(pressedKeys).not.toContain(wrong);- }- }, 5000);-});-// =========================================================================// patchPage behavioral: check/uncheck with idle_between_actions// =========================================================================-describe("patchPage check/uncheck idle", () => {- it("check with idle=true calls humanClickFn and does not crash on idle", async () => {- const { patchPage } = await import("../src/human/index.js");-- let downCalled = false;- const page = buildMockPage({- isChecked: async () => false,- evaluate: async () => ({ hit: true }),- });- page.mouse.down = vi.fn(async () => { downCalled = true; });-- const cfg = resolveConfig("default", {- idle_between_actions: true,- idle_between_duration: [0.01, 0.02],- });- const cursor = { x: 100, y: 100, initialized: true };- patchPage(page as any, cfg, cursor as any);-- try { await (page as any).check("input#cb", { timeout: 2000 }); } catch (error) { expect(error).toBeDefined(); }-- // humanCheckFn → humanIdle → humanClickFn → humanClick → raw.down- expect(downCalled).toBe(true);- }, 30000);-- it("uncheck with idle=true calls humanClickFn and does not crash on idle", async () => {- const { patchPage } = await import("../src/human/index.js");-- let downCalled = false;- const page = buildMockPage({- isChecked: async () => true,- evaluate: async () => ({ hit: true }),- });- page.mouse.down = vi.fn(async () => { downCalled = true; });-- const cfg = resolveConfig("default", {- idle_between_actions: true,- idle_between_duration: [0.01, 0.02],- });- const cursor = { x: 100, y: 100, initialized: true };- patchPage(page as any, cfg, cursor as any);-- try { await (page as any).uncheck("input#cb", { timeout: 2000 }); } catch (e: any) {- console.error("UNCHECK ERROR:", e?.message?.slice(0, 200));- }-- expect(downCalled).toBe(true);- }, 30000);-+describe("idle config", () => {it("config with idle=true is accepted by resolveConfig", () => {const cfg = resolveConfig("default", {idle_between_actions: true,@@ -336,308 +262,6 @@ describe("patchPage check/uncheck idle", () => {});});-// =========================================================================-// patchPage behavioral: press focus check-// =========================================================================-describe("patchPage press focus", () => {- it("press clicks element when NOT focused (mouse.down called)", async () => {- const { patchPage } = await import("../src/human/index.js");-- let downCount = 0;- const page = buildMockPage({- evaluate: async (expr: string) => {- if (typeof expr === 'string' && expr.includes('elementFromPoint')) return { hit: true };- return false;- },- });- // Intercept mouse.down before patching so raw captures it- page.mouse.down = vi.fn(async () => { downCount++; });-- const cfg = resolveConfig("default");- const cursor = { x: 50, y: 50, initialized: true };- patchPage(page as any, cfg, cursor as any);-- try { await (page as any).press("input#field", "Enter", { timeout: 2000 }); } catch (error) { expect(error).toBeDefined(); }-- expect(downCount).toBeGreaterThan(0);- });-- it("press skips click when element IS focused (no mouse.down)", async () => {- const { patchPage } = await import("../src/human/index.js");-- let downCount = 0;- const page = buildMockPage({- evaluate: vi.fn(async () => true),- snapshotFocused: true,- });- page.mouse.down = vi.fn(async () => { downCount++; });-- const cfg = resolveConfig("default");- const cursor = { x: 50, y: 50, initialized: true };- patchPage(page as any, cfg, cursor as any);-- try { await (page as any).press("input#field", "Enter", { timeout: 2000 }); } catch (error) { expect(error).toBeDefined(); }-- expect(downCount).toBe(0);- expect(page.evaluate).not.toHaveBeenCalled();- });-});--describe("patchPage checked snapshot", () => {- it("does not call Playwright isChecked when isolated snapshot is already checked", async () => {- const { patchPage } = await import("../src/human/index.js");- const originalIsChecked = vi.fn(async () => { throw new Error("must not run"); });- const page = buildMockPage({ isChecked: originalIsChecked, snapshotChecked: true });- const down = page.mouse.down;-- patchPage(- page,- resolveConfig("default", { idle_between_actions: false }),- { x: 50, y: 50, initialized: true } as any,- );- await page.check("input#cb", { timeout: 2000 });-- expect(originalIsChecked).not.toHaveBeenCalled();- expect(down).not.toHaveBeenCalled();- expect(page.evaluate).not.toHaveBeenCalled();- });-});--describe("press delay forwarding", () => {- it("page.press forwards delay to keyboard.press", async () => {- const { patchPage } = await import("../src/human/index.js");- const page = buildMockPage({ evaluate: async () => true });- const originalKeyboardPress = page.keyboard.press;-- patchPage(- page,- resolveConfig("default", { idle_between_actions: false }),- { x: 50, y: 50, initialized: true },- );- await page.press("#field", "Control+V", { delay: 300 });-- expect(originalKeyboardPress).toHaveBeenCalledWith("Control+V", { delay: 300 });- });-- it("frame.press forwards delay to keyboard.press", async () => {- const { patchPage } = await import("../src/human/index.js");- const childFrame = buildMockFrame();- const mainFrame = { ...buildMockFrame(), childFrames: vi.fn(() => [childFrame]) };- const page = buildMockPage({ mainFrameReturn: mainFrame });- const originalKeyboardPress = page.keyboard.press;-- patchPage(- page,- resolveConfig("default", { idle_between_actions: false }),- { x: 50, y: 50, initialized: true },- );- await childFrame.press("#field", "Control+V", { delay: 300 });-- expect(originalKeyboardPress).toHaveBeenCalledWith("Control+V", { delay: 300 });- });-- it("ElementHandle.press forwards delay to keyboard.press", async () => {- const { patchSingleElementHandle } = await import("../src/human/elementhandle.js");- const keyboardPress = vi.fn(async () => {});- const element = buildMockElementHandle();-- patchSingleElementHandle(- element,- buildMockPage(),- resolveConfig("default", { idle_between_actions: false }),- { x: 50, y: 50, initialized: true },- { move: vi.fn(), down: vi.fn(), up: vi.fn(), wheel: vi.fn() },- { down: vi.fn(), up: vi.fn(), type: vi.fn(), insertText: vi.fn() },- { keyboardPress, keyboardDown: vi.fn(), keyboardUp: vi.fn() },- null,- );- await element.press("Control+V", { delay: 300 });-- expect(keyboardPress).toHaveBeenCalledWith("Control+V", { delay: 300 });- });-});--// =========================================================================-// patchPage behavioral: frame patching-// =========================================================================-describe("patchPage frame patching", () => {- it("patches child frames with _humanPatched flag", async () => {- const { patchPage } = await import("../src/human/index.js");-- const childFrame = buildMockFrame();- const mainFrame = {- ...buildMockFrame(),- childFrames: vi.fn(() => [childFrame]),- };-- const page = buildMockPage({ mainFrameReturn: mainFrame });- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- patchPage(page as any, cfg, cursor as any);-- expect((childFrame as any)._humanPatched).toBe(true);- });-- it("patches dynamically attached frames once", async () => {- const { patchPage } = await import("../src/human/index.js");-- const page = buildMockPage();- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- patchPage(page as any, cfg, cursor as any);- await page.goto("https://example.com");-- // Two listeners are wired once: frameattached (patch dynamic frames) and- // framenavigated (invalidate the isolated world — #507).- expect(page.on).toHaveBeenCalledTimes(2);- const attachedCall = page.on.mock.calls.find((c: any[]) => c[0] === "frameattached");- expect(attachedCall).toBeDefined();- const handler = attachedCall[1];-- const attachedFrame = buildMockFrame();- const originalClick = attachedFrame.click;- handler(attachedFrame);- const patchedClick = attachedFrame.click;- handler(attachedFrame);-- expect((attachedFrame as any)._humanPatched).toBe(true);- expect(patchedClick).not.toBe(originalClick);- expect(attachedFrame.click).toBe(patchedClick);- });-- it("invalidates the isolated world on main-frame navigation, not subframes (#507)", async () => {- const { patchPage } = await import("../src/human/index.js");-- const mainFrame = { ...buildMockFrame(), childFrames: vi.fn(() => []) };- const page = buildMockPage({ mainFrameReturn: mainFrame });- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- patchPage(page as any, cfg, cursor as any);-- const invalidateSpy = vi.spyOn((page as any)._stealth, "invalidate");- const navCall = page.on.mock.calls.find((c: any[]) => c[0] === "framenavigated");- expect(navCall).toBeDefined();- const handler = navCall[1];-- // subframe navigation -> no invalidation- handler(buildMockFrame());- expect(invalidateSpy).not.toHaveBeenCalled();-- // main-frame navigation -> invalidate- handler(page.mainFrame());- expect(invalidateSpy).toHaveBeenCalledTimes(1);- });-- it("uses frame.locator for frame.click instead of page.click", async () => {- const { patchPage } = await import("../src/human/index.js");-- const childFrame = buildMockFrame();- const mainFrame = {- ...buildMockFrame(),- childFrames: vi.fn(() => [childFrame]),- };- const page = buildMockPage({ mainFrameReturn: mainFrame });- const originalPageClick = page.click;- const cfg = resolveConfig("default", { mouse_min_steps: 1, mouse_max_steps: 1 });- const cursor = { x: 0, y: 0, initialized: true };- patchPage(page as any, cfg, cursor as any);-- await (childFrame as any).click("button.submit", { timeout: 1234 });-- expect(childFrame.locator).toHaveBeenCalledWith("button.submit");- expect(originalPageClick).not.toHaveBeenCalled();- });-- it("main-frame click delegates to the humanized page.click (not the frame path)", async () => {- // Regression guard: page.locator(sel).click() reaches the MAIN frame's click,- // which must route to the humanized page.click (isolated-world pre-click reads),- // NOT the frame-scoped locator path that reads via Playwright and is detectable.- const { patchPage } = await import("../src/human/index.js");-- const mainFrame = { ...buildMockFrame(), childFrames: vi.fn(() => []) };- const page = buildMockPage({ mainFrameReturn: mainFrame });- const cfg = resolveConfig("default", { mouse_min_steps: 1, mouse_max_steps: 1 });- const cursor = { x: 0, y: 0, initialized: true };- patchPage(page as any, cfg, cursor as any);-- // Swap the humanized page.click for a spy, then drive the main frame's click.- const clickSpy = vi.fn(async () => {});- (page as any).click = clickSpy;- await (mainFrame as any).click("button.submit", { timeout: 1234 });-- expect(clickSpy).toHaveBeenCalledWith("button.submit", { timeout: 1234 });- // must NOT fall through to the frame-scoped locator (the pre-fix leak path)- expect(mainFrame.locator).not.toHaveBeenCalled();- });-- it("selectOption does not infinitely recurse through the patched main frame (regression)", async () => {- // page.selectOption re-dispatches to the patched main frame; originals must- // bind to the frame's native method or humanSelectOptionFn loops forever.- const { patchPage } = await import("../src/human/index.js");-- const nativeSelect = vi.fn(async () => ["b"]);- const mainFrame = { ...buildMockFrame(), childFrames: vi.fn(() => []), selectOption: nativeSelect };- const page = buildMockPage({ mainFrameReturn: mainFrame });-- // Mimic Playwright: the page's own selectOption delegates to the main frame's,- // with a depth guard so a regression throws instead of hanging the test.- let depth = 0;- page.selectOption = (sel: string, val: any, opts: any) => {- if (++depth > 5) throw new Error("RECURSION: selectOption re-dispatched to itself");- return page.mainFrame().selectOption(sel, val, opts);- };-- const cfg = resolveConfig("default", { mouse_min_steps: 1, mouse_max_steps: 1 });- patchPage(page as any, cfg, { x: 0, y: 0, initialized: true } as any);-- await expect((page as any).selectOption("#s", "b", { timeout: 2000 })).resolves.toBeDefined();- expect(nativeSelect).toHaveBeenCalledTimes(1);- expect(depth).toBe(0); // the delegating page.selectOption was never re-entered- }, 30000);-- it.each([- ["type", async (frame: any) => frame.type("input.email", "@")],- ["fill", async (frame: any) => frame.fill("input.email", "@")],- ["pressSequentially", async (frame: any) => frame.pressSequentially("input.email", "@")],- ])("passes the page CDP session to frame.%s", async (_name, runFrameAction) => {- const { patchPage } = await import("../src/human/index.js");-- const cdpSend = vi.fn(async (_method: string, _params?: unknown) => ({}));- const childFrame = buildMockFrame();- const mainFrame = {- ...buildMockFrame(),- childFrames: vi.fn(() => [childFrame]),- };- const page = buildMockPage({ mainFrameReturn: mainFrame });- page.context = vi.fn(() => ({- pages: vi.fn(() => []),- addInitScript: vi.fn(async () => {}),- newCDPSession: vi.fn(async () => ({ send: cdpSend })),- }));-- const cfg = resolveConfig("default", {- field_switch_delay: [0, 0],- key_hold: [0, 0],- shift_down_delay: [0, 0],- shift_up_delay: [0, 0],- typing_delay: 0,- typing_delay_spread: 0,- typing_pause_chance: 0,- mistype_chance: 0,- mouse_min_steps: 1,- mouse_max_steps: 1,- idle_between_actions: false,- });- const cursor = { x: 0, y: 0, initialized: true };- patchPage(page as any, cfg, cursor as any);-- await runFrameAction(childFrame);-- const dispatches = cdpSend.mock.calls.filter(([method]) => method === "Input.dispatchKeyEvent");- expect(dispatches).toHaveLength(2);- expect(page.evaluate).not.toHaveBeenCalled();- });-});// =========================================================================// Mistype config@@ -722,33 +346,6 @@ describe("patchBrowser CDP-connected workflow", () => {expect((page as any)._humanCfg).toBe(cfg);});- it("patched click calls mouse.down (humanized path, not original)", async () => {- const { patchBrowser, resolveConfig } = await import("../src/human/index.js");-- let downCalled = false;- const page = buildMockPage();- page.mouse.down = vi.fn(async () => { downCalled = true; });-- const context: any = {- pages: vi.fn(() => [page]),- on: vi.fn(),- newPage: vi.fn(async () => buildMockPage()),- addInitScript: vi.fn(async () => { }),- };- const browser: any = {- contexts: vi.fn(() => [context]),- newContext: vi.fn(async () => context),- newPage: vi.fn(async () => page),- };-- patchBrowser(browser, resolveConfig("default"));-- // Click through the patched method — should go through humanize path- try { await (page as any).click("button", { timeout: 2000 }); } catch (error) { expect(error).toBeDefined(); }-- expect(downCalled).toBe(true);- }, 30000);-it("new contexts created after patchBrowser are also patched", async () => {const { patchBrowser, resolveConfig } = await import("../src/human/index.js");@@ -961,379 +558,6 @@ describe("humanType non-ASCII", () => {});--// =========================================================================-// ElementHandle patching (Playwright)-// =========================================================================--function buildMockElementHandle(overrides: Record<string, any> = {}): any {- const el: any = {- click: vi.fn(async () => { }),- dblclick: vi.fn(async () => { }),- hover: vi.fn(async () => { }),- type: vi.fn(async () => { }),- fill: vi.fn(async () => { }),- press: vi.fn(async () => { }),- selectOption: vi.fn(async () => { }),- check: vi.fn(async () => { }),- uncheck: vi.fn(async () => { }),- setChecked: vi.fn(async () => { }),- tap: vi.fn(async () => { }),- focus: vi.fn(async () => { }),- boundingBox: overrides.boundingBox ?? vi.fn(async () => ({ x: 100, y: 100, width: 200, height: 30 })),- evaluate: overrides.evaluate ?? vi.fn(async () => ({ hit: true })),- isChecked: overrides.isChecked ?? vi.fn(async () => false),- waitForElementState: vi.fn(async () => {}),- $: vi.fn(async () => null),- $$: vi.fn(async () => []),- waitForSelector: vi.fn(async () => null),- _humanPatched: false,- };- return el;-}--describe("patchSingleElementHandle", () => {- it("marks element as patched", async () => {- const { patchSingleElementHandle } = await import("../src/human/elementhandle.js");- const cfg = resolveConfig("default");- const cursor = { x: 100, y: 100, initialized: true };- const raw = {- move: vi.fn(async () => { }),- down: vi.fn(async () => { }),- up: vi.fn(async () => { }),- wheel: vi.fn(async () => { }),- };- const rawKb = {- down: vi.fn(async () => { }),- up: vi.fn(async () => { }),- type: vi.fn(async () => { }),- insertText: vi.fn(async () => { }),- };- const originals = {- keyboardPress: vi.fn(async () => { }),- keyboardDown: vi.fn(async () => { }),- keyboardUp: vi.fn(async () => { }),- };-- const el = buildMockElementHandle();- const page = buildMockPage();-- patchSingleElementHandle(el, page as any, cfg, cursor as any, raw, rawKb, originals, null);-- expect(el._humanPatched).toBe(true);- });-- it("el.click calls mouse.move and mouse.down/up (humanized path)", async () => {- const { patchSingleElementHandle } = await import("../src/human/elementhandle.js");- const cfg = resolveConfig("default", { idle_between_actions: false });- const cursor = { x: 50, y: 50, initialized: true };-- let moveCount = 0;- let downCalled = false;- let upCalled = false;- const raw = {- move: vi.fn(async () => { moveCount++; }),- down: vi.fn(async () => { downCalled = true; }),- up: vi.fn(async () => { upCalled = true; }),- wheel: vi.fn(async () => { }),- };- const rawKb = {- down: vi.fn(async () => { }),- up: vi.fn(async () => { }),- type: vi.fn(async () => { }),- insertText: vi.fn(async () => { }),- };- const originals = {- keyboardPress: vi.fn(async () => { }),- keyboardDown: vi.fn(async () => { }),- keyboardUp: vi.fn(async () => { }),- };-- const el = buildMockElementHandle();- const page = buildMockPage();- (page as any)._ensureCursorInit = vi.fn(async () => { });-- patchSingleElementHandle(el, page as any, cfg, cursor as any, raw, rawKb, originals, null);-- await el.click();-- expect(moveCount).toBeGreaterThan(0);- expect(downCalled).toBe(true);- expect(upCalled).toBe(true);- }, 30000);-- it("el.hover calls mouse.move but NOT down/up", async () => {- const { patchSingleElementHandle } = await import("../src/human/elementhandle.js");- const cfg = resolveConfig("default", { idle_between_actions: false });- const cursor = { x: 50, y: 50, initialized: true };-- let downCalled = false;- const raw = {- move: vi.fn(async () => { }),- down: vi.fn(async () => { downCalled = true; }),- up: vi.fn(async () => { }),- wheel: vi.fn(async () => { }),- };- const rawKb = {- down: vi.fn(async () => { }),- up: vi.fn(async () => { }),- type: vi.fn(async () => { }),- insertText: vi.fn(async () => { }),- };- const originals = { keyboardPress: vi.fn(async () => { }), keyboardDown: vi.fn(async () => { }), keyboardUp: vi.fn(async () => { }) };-- const el = buildMockElementHandle();- const page = buildMockPage();- (page as any)._ensureCursorInit = vi.fn(async () => { });-- patchSingleElementHandle(el, page as any, cfg, cursor as any, raw, rawKb, originals, null);-- await el.hover();-- expect(raw.move).toHaveBeenCalled();- expect(downCalled).toBe(false);- }, 30000);-- it("el.type triggers mouse move + click + keyboard events", async () => {- const { patchSingleElementHandle } = await import("../src/human/elementhandle.js");- const cfg = resolveConfig("default", { idle_between_actions: false, mistype_chance: 0 });- const cursor = { x: 50, y: 50, initialized: true };-- const raw = {- move: vi.fn(async () => { }),- down: vi.fn(async () => { }),- up: vi.fn(async () => { }),- wheel: vi.fn(async () => { }),- };- const rawKb = {- down: vi.fn(async () => { }),- up: vi.fn(async () => { }),- type: vi.fn(async () => { }),- insertText: vi.fn(async () => { }),- };- const originals = { keyboardPress: vi.fn(async () => { }), keyboardDown: vi.fn(async () => { }), keyboardUp: vi.fn(async () => { }) };-- const el = buildMockElementHandle({ evaluate: vi.fn(async (js: string) => js.includes('elementFromPoint') ? { hit: true } : true) });- const page = buildMockPage();- (page as any)._ensureCursorInit = vi.fn(async () => { });-- patchSingleElementHandle(el, page as any, cfg, cursor as any, raw, rawKb, originals, null);-- await el.type("abc");-- expect(raw.move).toHaveBeenCalled();- expect(raw.down).toHaveBeenCalled(); // click to focus- expect(rawKb.down).toHaveBeenCalled(); // keyboard typing- }, 30000);-- it("el.fill calls selectAll + backspace + type", async () => {- const { patchSingleElementHandle } = await import("../src/human/elementhandle.js");- const cfg = resolveConfig("default", { idle_between_actions: false, mistype_chance: 0 });- const cursor = { x: 50, y: 50, initialized: true };-- const pressedKeys: string[] = [];- const raw = {- move: vi.fn(async () => { }),- down: vi.fn(async () => { }),- up: vi.fn(async () => { }),- wheel: vi.fn(async () => { }),- };- const rawKb = {- down: vi.fn(async () => { }),- up: vi.fn(async () => { }),- type: vi.fn(async () => { }),- insertText: vi.fn(async () => { }),- };- const originals = {- keyboardPress: vi.fn(async (key: string) => { pressedKeys.push(key); }),- keyboardDown: vi.fn(async () => { }),- keyboardUp: vi.fn(async () => { }),- };-- const el = buildMockElementHandle({ evaluate: vi.fn(async (js: string) => js.includes('elementFromPoint') ? { hit: true } : true) });- const page = buildMockPage();- (page as any)._ensureCursorInit = vi.fn(async () => { });-- patchSingleElementHandle(el, page as any, cfg, cursor as any, raw, rawKb, originals, null);-- await el.fill("newtext");-- const expected = process.platform === "darwin" ? "Meta+a" : "Control+a";- expect(pressedKeys).toContain(expected);- expect(pressedKeys).toContain("Backspace");- }, 30000);-- it("no double patching", async () => {- const { patchSingleElementHandle } = await import("../src/human/elementhandle.js");- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- const raw = { move: vi.fn(async () => { }), down: vi.fn(async () => { }), up: vi.fn(async () => { }), wheel: vi.fn(async () => { }) };- const rawKb = { down: vi.fn(async () => { }), up: vi.fn(async () => { }), type: vi.fn(async () => { }), insertText: vi.fn(async () => { }) };- const originals = { keyboardPress: vi.fn(async () => { }), keyboardDown: vi.fn(async () => { }), keyboardUp: vi.fn(async () => { }) };-- const el = buildMockElementHandle();- const page = buildMockPage();-- patchSingleElementHandle(el, page as any, cfg, cursor as any, raw, rawKb, originals, null);- const firstClick = el.click;-- patchSingleElementHandle(el, page as any, cfg, cursor as any, raw, rawKb, originals, null);-- expect(el.click).toBe(firstClick);- });-- it("nested $() returns patched child handle", async () => {- const { patchSingleElementHandle } = await import("../src/human/elementhandle.js");- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- const raw = { move: vi.fn(async () => { }), down: vi.fn(async () => { }), up: vi.fn(async () => { }), wheel: vi.fn(async () => { }) };- const rawKb = { down: vi.fn(async () => { }), up: vi.fn(async () => { }), type: vi.fn(async () => { }), insertText: vi.fn(async () => { }) };- const originals = { keyboardPress: vi.fn(async () => { }), keyboardDown: vi.fn(async () => { }), keyboardUp: vi.fn(async () => { }) };-- const child = buildMockElementHandle();- const el = buildMockElementHandle();- el.$ = vi.fn(async () => child);-- const page = buildMockPage();-- patchSingleElementHandle(el, page as any, cfg, cursor as any, raw, rawKb, originals, null);-- const result = await el.$("span");- expect(result._humanPatched).toBe(true);- });-});--describe("patchPageElementHandles", () => {- it("page.$() returns patched ElementHandle", async () => {- const { patchPageElementHandles } = await import("../src/human/elementhandle.js");- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- const raw = { move: vi.fn(async () => { }), down: vi.fn(async () => { }), up: vi.fn(async () => { }), wheel: vi.fn(async () => { }) };- const rawKb = { down: vi.fn(async () => { }), up: vi.fn(async () => { }), type: vi.fn(async () => { }), insertText: vi.fn(async () => { }) };- const originals = { keyboardPress: vi.fn(async () => { }), keyboardDown: vi.fn(async () => { }), keyboardUp: vi.fn(async () => { }) };-- const el = buildMockElementHandle();- const page = buildMockPage();- (page as any).$ = vi.fn(async () => el);- (page as any).$$ = vi.fn(async () => [el]);- (page as any).waitForSelector = vi.fn(async () => el);-- patchPageElementHandles(page as any, cfg, cursor as any, raw, rawKb, originals, null);-- const result = await (page as any).$("#test");- expect(result._humanPatched).toBe(true);- });-- it("page.$$() returns all patched handles", async () => {- const { patchPageElementHandles } = await import("../src/human/elementhandle.js");- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- const raw = { move: vi.fn(async () => { }), down: vi.fn(async () => { }), up: vi.fn(async () => { }), wheel: vi.fn(async () => { }) };- const rawKb = { down: vi.fn(async () => { }), up: vi.fn(async () => { }), type: vi.fn(async () => { }), insertText: vi.fn(async () => { }) };- const originals = { keyboardPress: vi.fn(async () => { }), keyboardDown: vi.fn(async () => { }), keyboardUp: vi.fn(async () => { }) };-- const el1 = buildMockElementHandle();- const el2 = buildMockElementHandle();- const page = buildMockPage();- (page as any).$ = vi.fn(async () => null);- (page as any).$$ = vi.fn(async () => [el1, el2]);- (page as any).waitForSelector = vi.fn(async () => null);-- patchPageElementHandles(page as any, cfg, cursor as any, raw, rawKb, originals, null);-- const results = await (page as any).$$("div");- expect(results[0]._humanPatched).toBe(true);- expect(results[1]._humanPatched).toBe(true);- });-- it("page.waitForSelector() returns patched handle", async () => {- const { patchPageElementHandles } = await import("../src/human/elementhandle.js");- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- const raw = { move: vi.fn(async () => { }), down: vi.fn(async () => { }), up: vi.fn(async () => { }), wheel: vi.fn(async () => { }) };- const rawKb = { down: vi.fn(async () => { }), up: vi.fn(async () => { }), type: vi.fn(async () => { }), insertText: vi.fn(async () => { }) };- const originals = { keyboardPress: vi.fn(async () => { }), keyboardDown: vi.fn(async () => { }), keyboardUp: vi.fn(async () => { }) };-- const el = buildMockElementHandle();- const page = buildMockPage();- (page as any).$ = vi.fn(async () => null);- (page as any).$$ = vi.fn(async () => []);- (page as any).waitForSelector = vi.fn(async () => el);-- patchPageElementHandles(page as any, cfg, cursor as any, raw, rawKb, originals, null);-- const result = await (page as any).waitForSelector("#test");- expect(result._humanPatched).toBe(true);- });-- it("page.$() returns null when no element found (no crash)", async () => {- const { patchPageElementHandles } = await import("../src/human/elementhandle.js");- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- const raw = { move: vi.fn(async () => { }), down: vi.fn(async () => { }), up: vi.fn(async () => { }), wheel: vi.fn(async () => { }) };- const rawKb = { down: vi.fn(async () => { }), up: vi.fn(async () => { }), type: vi.fn(async () => { }), insertText: vi.fn(async () => { }) };- const originals = { keyboardPress: vi.fn(async () => { }), keyboardDown: vi.fn(async () => { }), keyboardUp: vi.fn(async () => { }) };-- const page = buildMockPage();- (page as any).$ = vi.fn(async () => null);- (page as any).$$ = vi.fn(async () => []);- (page as any).waitForSelector = vi.fn(async () => null);-- patchPageElementHandles(page as any, cfg, cursor as any, raw, rawKb, originals, null);-- const result = await (page as any).$("#nonexistent");- expect(result).toBeNull();- });-});--describe("patchPage integrates ElementHandle patching", () => {- it("patchPage patches page.$ automatically", async () => {- const { patchPage } = await import("../src/human/index.js");-- const el = buildMockElementHandle();- const page = buildMockPage();- (page as any).$ = vi.fn(async () => el);- (page as any).$$ = vi.fn(async () => []);- (page as any).waitForSelector = vi.fn(async () => null);-- const cfg = resolveConfig("default");- const cursor = { x: 100, y: 100, initialized: true };- patchPage(page as any, cfg, cursor as any);-- const result = await (page as any).$("#test");- expect(result._humanPatched).toBe(true);- });-});---function buildMockFrame(): any {- const locator: any = {- boundingBox: vi.fn(async () => ({ x: 0, y: 0, width: 100, height: 30 })),- scrollIntoViewIfNeeded: vi.fn(async () => {}),- evaluate: vi.fn(async () => ({ hit: true })),- isChecked: vi.fn(async () => false),- };- locator.first = vi.fn(() => locator);-- return {- click: vi.fn(async () => { }),- dblclick: vi.fn(async () => { }),- hover: vi.fn(async () => { }),- type: vi.fn(async () => { }),- fill: vi.fn(async () => { }),- check: vi.fn(async () => { }),- uncheck: vi.fn(async () => { }),- selectOption: vi.fn(async () => { }),- press: vi.fn(async () => { }),- pressSequentially: vi.fn(async () => { }),- tap: vi.fn(async () => { }),- clear: vi.fn(async () => { }),- dragAndDrop: vi.fn(async () => { }),- locator: vi.fn(() => locator),- childFrames: vi.fn(() => []),- };-}-// =========================================================================// mergeConfig// =========================================================================@@ -1364,616 +588,3 @@ describe("mergeConfig", () => {});});--// =========================================================================-// Per-call timeout forwarding (issue #137)-// =========================================================================-describe("page.click(selector, { timeout }) forwards timeout to scroll", () => {- it("polls isolated-world geometry until the selector appears", async () => {- const { scrollToElement } = await import("../src/human/scroll.js");- const cfg = resolveConfig("default");- let evaluations = 0;- const page: any = {- viewportSize: () => ({ width: 1280, height: 720 }),- locator: vi.fn(),- _stealth: { evaluate: vi.fn(async () => {- evaluations++;- if (evaluations < 3) return { v: 2, r: "not_found" };- return {- v: 2, r: "ok", targetId: 7, gen: 1,- box: { x: 100, y: 200, width: 50, height: 30 },- };- }) },- };- const raw = {- move: vi.fn(async () => { }), down: vi.fn(async () => { }),- up: vi.fn(async () => { }), wheel: vi.fn(async () => { }),- };-- const result = await scrollToElement(page, raw, "#x", 0, 0, cfg, 5000);- expect(result.box.targetId).toBe(7);- expect(evaluations).toBe(3);- expect(page.locator).not.toHaveBeenCalled();- });-- it("honors a short isolated-world geometry timeout", async () => {- const { getElementBox } = await import("../src/human/scroll.js");- const page: any = {- locator: vi.fn(),- _stealth: { evaluate: vi.fn(async () => ({ v: 2, r: "not_found" })) },- };-- const started = Date.now();- await expect(getElementBox(page, "#missing", 20)).resolves.toBeNull();- expect(Date.now() - started).toBeLessThan(250);- expect(page.locator).not.toHaveBeenCalled();- });-- it("page.click({ timeout }) reaches scrollToElement", async () => {- const scrollMod = await import("../src/human/scroll.js");- const { patchPage } = await import("../src/human/index.js");- const cfg = resolveConfig("default", { idle_between_actions: false });-- let captured = -1;- const spy = vi.spyOn(scrollMod, "scrollToElement").mockImplementation(- async (_page, _raw, _sel, cx, cy, _cfg, timeout?: number) => {- captured = timeout ?? -1;- return { box: { x: 100, y: 100, width: 50, height: 30, targetId: 1 }, cursorX: cx, cursorY: cy, didScroll: false };- },- );-- const page = buildMockPage();- const cursor = { x: 100, y: 100, initialized: true };- patchPage(page as any, cfg, cursor as any);- try {- await (page as any).click("#slow", { timeout: 2000 });- } catch (error) { expect(error).toBeDefined(); }-- if (captured > 0) {- expect(captured).toBeGreaterThan(1500);- expect(captured).toBeLessThanOrEqual(2000);- }- spy.mockRestore();- });-});---// =========================================================================-// Per-call human config override-// =========================================================================-describe("page.type / page.fill accept per-call human config override", () => {- it("page.type forwards nested human_config to humanType", async () => {- const keyboardMod = await import("../src/human/keyboard.js");- const scrollMod = await import("../src/human/scroll.js");- const { patchPage } = await import("../src/human/index.js");-- // Make field_switch_delay tiny so the test runs fast- const cfg = resolveConfig("default", {- idle_between_actions: false,- field_switch_delay: [0, 1],- });- expect(cfg.typing_delay).toBe(70); // baseline-- let captured: any = null;- const typeSpy = vi.spyOn(keyboardMod, "humanType").mockImplementation(- async (_page, _raw, _text, callCfg) => { captured = callCfg; },- );- const scrollSpy = vi.spyOn(scrollMod, "scrollToElement").mockImplementation(- async (_page, _raw, _sel, cx, cy) => ({- box: { x: 100, y: 100, width: 50, height: 30 },- cursorX: cx, cursorY: cy, didScroll: false,- }),- );-- const page = buildMockPage();- const cursor = { x: 100, y: 100, initialized: true };- patchPage(page as any, cfg, cursor as any);-- try {- await (page as any).type("#email", "hi", {- timeout: 2000,- human_config: { typing_delay: 30, mistype_chance: 0 },- });- } catch (error) { expect(error).toBeDefined(); }-- if (captured) {- expect(captured.typing_delay).toBe(30);- expect(captured.mistype_chance).toBe(0);- }- expect(cfg.typing_delay).toBe(70);-- typeSpy.mockRestore();- scrollSpy.mockRestore();- }, 5000);-- it("page.fill forwards flat config to humanType", async () => {- const keyboardMod = await import("../src/human/keyboard.js");- const scrollMod = await import("../src/human/scroll.js");- const { patchPage } = await import("../src/human/index.js");-- const cfg = resolveConfig("default", {- idle_between_actions: false,- field_switch_delay: [0, 1],- });-- let captured: any = null;- const typeSpy = vi.spyOn(keyboardMod, "humanType").mockImplementation(- async (_page, _raw, _text, callCfg) => { captured = callCfg; },- );- const scrollSpy = vi.spyOn(scrollMod, "scrollToElement").mockImplementation(- async (_page, _raw, _sel, cx, cy) => ({- box: { x: 100, y: 100, width: 50, height: 30 },- cursorX: cx, cursorY: cy, didScroll: false,- }),- );-- const page = buildMockPage();- const cursor = { x: 100, y: 100, initialized: true };- patchPage(page as any, cfg, cursor as any);-- try {- await (page as any).fill("#password", "secret", {- timeout: 2000,- typing_delay: 150,- });- } catch (error) { expect(error).toBeDefined(); }-- if (captured) {- expect(captured.typing_delay).toBe(150);- }-- typeSpy.mockRestore();- scrollSpy.mockRestore();- }, 30000);-- it("el.type forwards human_config to humanType", async () => {- const keyboardMod = await import("../src/human/keyboard.js");- const { patchSingleElementHandle } = await import("../src/human/elementhandle.js");- const cfg = resolveConfig("default", { idle_between_actions: false, mistype_chance: 0 });- const cursor = { x: 50, y: 50, initialized: true };-- let captured: any = null;- const typeSpy = vi.spyOn(keyboardMod, "humanType").mockImplementation(- async (_page, _raw, _text, callCfg) => { captured = callCfg; },- );-- const raw = { move: vi.fn(async () => { }), down: vi.fn(async () => { }), up: vi.fn(async () => { }), wheel: vi.fn(async () => { }) };- const rawKb = { down: vi.fn(async () => { }), up: vi.fn(async () => { }), type: vi.fn(async () => { }), insertText: vi.fn(async () => { }) };- const originals = { keyboardPress: vi.fn(async () => { }), keyboardDown: vi.fn(async () => { }), keyboardUp: vi.fn(async () => { }) };-- const el = buildMockElementHandle({ evaluate: vi.fn(async (js: string) => js.includes('elementFromPoint') ? { hit: true } : true) });- const page = buildMockPage();- (page as any)._ensureCursorInit = vi.fn(async () => { });-- patchSingleElementHandle(el, page as any, cfg, cursor as any, raw, rawKb, originals, null);-- await el.type("abc", { human_config: { typing_delay: 25 } });- expect(captured.typing_delay).toBe(25);-- typeSpy.mockRestore();- }, 30000);-});---// =========================================================================-// scrollIntoViewIfNeeded humanization-// =========================================================================-describe("humanScrollIntoView", () => {- it("skips wheel events when element is already in viewport", async () => {- const { humanScrollIntoView } = await import("../src/human/scroll.js");- const cfg = resolveConfig("default");-- const page: any = { viewportSize: () => ({ width: 1280, height: 720 }) };- const raw = {- move: vi.fn(async () => { }),- down: vi.fn(async () => { }),- up: vi.fn(async () => { }),- wheel: vi.fn(async () => { }),- };- // Box centered in viewport — squarely in scroll_target_zone- const inViewBox = { x: 200, y: 300, width: 50, height: 30 };- const result = await humanScrollIntoView(page, raw, async () => inViewBox, 0, 0, cfg);-- expect(result.box).toEqual(inViewBox);- expect(raw.wheel).not.toHaveBeenCalled();- });-- it("fires wheel events when element is below the fold", async () => {- const { humanScrollIntoView } = await import("../src/human/scroll.js");- const cfg = resolveConfig("default", {- scroll_overshoot_chance: 0,- scroll_pre_move_delay: [0, 1],- scroll_pause_fast: [0, 1],- scroll_pause_slow: [0, 1],- scroll_settle_delay: [0, 1],- });-- const page: any = { viewportSize: () => ({ width: 1280, height: 720 }) };- const raw = {- move: vi.fn(async () => { }),- down: vi.fn(async () => { }),- up: vi.fn(async () => { }),- wheel: vi.fn(async () => { }),- };-- const boxes = [- { x: 200, y: 2000, width: 50, height: 30 }, // far below- { x: 200, y: 1500, width: 50, height: 30 },- { x: 200, y: 1000, width: 50, height: 30 },- { x: 200, y: 400, width: 50, height: 30 }, // in view- { x: 200, y: 400, width: 50, height: 30 },- { x: 200, y: 400, width: 50, height: 30 },- ];- let i = 0;- const getBox = async () => boxes[Math.min(i++, boxes.length - 1)];-- await humanScrollIntoView(page, raw, getBox, 0, 0, cfg);- expect(raw.wheel).toHaveBeenCalled();- }, 15000);-- it("bails without scrolling when a fully-visible element is above the zone and the page is at the top (regression)", async () => {- const { humanScrollIntoView } = await import("../src/human/scroll.js");- const cfg = resolveConfig("default");-- // viewport 720 -> zone [144, 576]; element top=50 is above the zone but fully visible.- const page: any = {- viewportSize: () => ({ width: 1280, height: 720 }),- evaluate: vi.fn(),- _stealth: { evaluate: vi.fn(async () => ({ y: 0, maxY: 2000, x: 0, minX: 0, maxX: 0 })) },- };- const raw = {- move: vi.fn(async () => { }), down: vi.fn(async () => { }),- up: vi.fn(async () => { }), wheel: vi.fn(async () => { }),- };- const topBox = { x: 200, y: 50, width: 50, height: 30 };-- const result = await humanScrollIntoView(page, raw, async () => topBox, 0, 0, cfg);-- expect(result.didScroll).toBe(false);- expect(raw.wheel).not.toHaveBeenCalled();- expect(page.evaluate).not.toHaveBeenCalled();- });-- it("bails when layout reports a sub-pixel negative top on an unscrolled page", async () => {- const { humanScrollIntoView } = await import("../src/human/scroll.js");- const cfg = resolveConfig("default");-- const page: any = {- viewportSize: () => ({ width: 1000, height: 700 }),- evaluate: vi.fn(),- _stealth: { evaluate: vi.fn(async () => ({ y: 0, maxY: 0, x: 0, minX: 0, maxX: 0 })) },- };- const raw = {- move: vi.fn(async () => { }), down: vi.fn(async () => { }),- up: vi.fn(async () => { }), wheel: vi.fn(async () => { }),- };- const topBox = { x: 200, y: -0.015625, width: 200, height: 21.5 };-- const result = await humanScrollIntoView(page, raw, async () => topBox, 0, 0, cfg);-- expect(result.didScroll).toBe(false);- expect(raw.wheel).not.toHaveBeenCalled();- });-- it("still scrolls a fully-visible above-zone element when the page CAN scroll up (no over-bail)", async () => {- const { humanScrollIntoView } = await import("../src/human/scroll.js");- const cfg = resolveConfig("default", {- scroll_overshoot_chance: 0,- scroll_pre_move_delay: [0, 1], scroll_pause_fast: [0, 1],- scroll_pause_slow: [0, 1], scroll_settle_delay: [0, 1],- });-- const page: any = {- viewportSize: () => ({ width: 1280, height: 720 }),- evaluate: vi.fn(),- _stealth: { evaluate: vi.fn(async () => ({ y: 500, maxY: 2000, x: 0, minX: 0, maxX: 0 })) },- };- const raw = {- move: vi.fn(async () => { }), down: vi.fn(async () => { }),- up: vi.fn(async () => { }), wheel: vi.fn(async () => { }),- };- const topBox = { x: 200, y: 50, width: 50, height: 30 };-- await humanScrollIntoView(page, raw, async () => topBox, 0, 0, cfg);-- expect(raw.wheel).toHaveBeenCalled();- expect(page.evaluate).not.toHaveBeenCalled();- }, 15000);-- it("scrolls the x axis for an element past the right edge (#521)", async () => {- const { humanScrollIntoView } = await import("../src/human/scroll.js");- const cfg = resolveConfig("default", {- scroll_pre_move_delay: [0, 1], scroll_settle_delay: [0, 1],- });-- const page: any = {- viewportSize: () => ({ width: 1000, height: 700 }),- evaluate: vi.fn(),- _stealth: { evaluate: vi.fn(async () => ({ y: 0, maxY: 0, x: 0, minX: 0, maxX: 600 })) },- };- const raw = {- move: vi.fn(async () => { }), down: vi.fn(async () => { }),- up: vi.fn(async () => { }), wheel: vi.fn(async (_dx: number, _dy: number) => { }),- };- const boxes = [- { x: 800, y: 300, width: 800, height: 30 },- { x: 200, y: 300, width: 800, height: 30 },- ];- let i = 0;- const getBox = async () => boxes[i++];-- const result = await humanScrollIntoView(page, raw, getBox, 0, 0, cfg);-- expect(result.didScroll).toBe(true);- expect(result.box.x).toBe(200);- expect(raw.wheel).toHaveBeenCalled();- for (const [dx, dy] of raw.wheel.mock.calls) {- expect(dx).toBeGreaterThan(0);- expect(dy).toBe(0);- }- expect(page.evaluate).not.toHaveBeenCalled();- }, 15000);-- it("skips the x axis when the page is already scrolled fully right", async () => {- const { humanScrollIntoView } = await import("../src/human/scroll.js");- const cfg = resolveConfig("default");-- const page: any = {- viewportSize: () => ({ width: 1000, height: 700 }),- evaluate: vi.fn(),- _stealth: { evaluate: vi.fn(async () => ({ y: 0, maxY: 0, x: 600, minX: 0, maxX: 600 })) },- };- const raw = {- move: vi.fn(async () => { }), down: vi.fn(async () => { }),- up: vi.fn(async () => { }), wheel: vi.fn(async () => { }),- };- const clippedBox = { x: 900, y: 300, width: 200, height: 30 };-- const result = await humanScrollIntoView(page, raw, async () => clippedBox, 0, 0, cfg);-- expect(result.didScroll).toBe(false);- expect(raw.wheel).not.toHaveBeenCalled();- });-- it("scrolls the x axis left on an RTL page at its start", async () => {- const { humanScrollIntoView } = await import("../src/human/scroll.js");- const cfg = resolveConfig("default", {- scroll_pre_move_delay: [0, 1], scroll_settle_delay: [0, 1],- });-- const page: any = {- viewportSize: () => ({ width: 1000, height: 700 }),- evaluate: vi.fn(),- _stealth: {- evaluate: vi.fn(async () => ({ y: 0, maxY: 0, x: 0, minX: -600, maxX: 0 })),- },- };- const raw = {- move: vi.fn(async () => { }), down: vi.fn(async () => { }),- up: vi.fn(async () => { }), wheel: vi.fn(async (_dx: number, _dy: number) => { }),- };- const boxes = [- { x: -600, y: 300, width: 200, height: 30 },- { x: 400, y: 300, width: 200, height: 30 },- ];- let i = 0;- const getBox = async () => boxes[i++];-- const result = await humanScrollIntoView(page, raw, getBox, 0, 0, cfg);-- expect(result.didScroll).toBe(true);- expect(result.box.x).toBe(400);- expect(raw.wheel).toHaveBeenCalled();- for (const [dx, dy] of raw.wheel.mock.calls) {- expect(dx).toBeLessThan(0);- expect(dy).toBe(0);- }- }, 15000);-});--describe("el.scrollIntoViewIfNeeded humanization", () => {- it("calls humanScrollIntoView instead of native snap-scroll", async () => {- const scrollMod = await import("../src/human/scroll.js");- const { patchSingleElementHandle } = await import("../src/human/elementhandle.js");-- let called = 0;- const spy = vi.spyOn(scrollMod, "humanScrollIntoView").mockImplementation(- async (_p, _raw, _gb, cx, cy) => {- called++;- return { box: { x: 200, y: 200, width: 50, height: 30 }, cursorX: cx, cursorY: cy, didScroll: false };- },- );-- const cfg = resolveConfig("default", { idle_between_actions: false });- const cursor = { x: 50, y: 50, initialized: true };- const raw = { move: vi.fn(async () => { }), down: vi.fn(async () => { }), up: vi.fn(async () => { }), wheel: vi.fn(async () => { }) };- const rawKb = { down: vi.fn(async () => { }), up: vi.fn(async () => { }), type: vi.fn(async () => { }), insertText: vi.fn(async () => { }) };- const originals = { keyboardPress: vi.fn(async () => { }), keyboardDown: vi.fn(async () => { }), keyboardUp: vi.fn(async () => { }) };-- const el = buildMockElementHandle();- el.scrollIntoViewIfNeeded = vi.fn(async () => { });- const page = buildMockPage();- (page as any)._ensureCursorInit = vi.fn(async () => { });-- patchSingleElementHandle(el, page as any, cfg, cursor as any, raw, rawKb, originals, null);- await el.scrollIntoViewIfNeeded();-- expect(called).toBeGreaterThan(0);- spy.mockRestore();- });-- it("falls back to native scrollIntoViewIfNeeded if humanized helper throws", async () => {- const scrollMod = await import("../src/human/scroll.js");- const { patchSingleElementHandle } = await import("../src/human/elementhandle.js");-- const spy = vi.spyOn(scrollMod, "humanScrollIntoView").mockImplementation(- async () => { throw new Error("detached"); },- );-- const cfg = resolveConfig("default", { idle_between_actions: false });- const cursor = { x: 50, y: 50, initialized: true };- const raw = { move: vi.fn(async () => { }), down: vi.fn(async () => { }), up: vi.fn(async () => { }), wheel: vi.fn(async () => { }) };- const rawKb = { down: vi.fn(async () => { }), up: vi.fn(async () => { }), type: vi.fn(async () => { }), insertText: vi.fn(async () => { }) };- const originals = { keyboardPress: vi.fn(async () => { }), keyboardDown: vi.fn(async () => { }), keyboardUp: vi.fn(async () => { }) };-- const nativeFallback = vi.fn(async () => { });- const el = buildMockElementHandle();- el.scrollIntoViewIfNeeded = nativeFallback;- const page = buildMockPage();- (page as any)._ensureCursorInit = vi.fn(async () => { });-- patchSingleElementHandle(el, page as any, cfg, cursor as any, raw, rawKb, originals, null);- await el.scrollIntoViewIfNeeded();-- expect(nativeFallback).toHaveBeenCalled();- spy.mockRestore();- });-});---// =========================================================================-// Issue #307: frame.click timeout should not multiply-// =========================================================================-describe("frame.click timeout budget (#307)", () => {- it("total wait time should not exceed the specified timeout", async () => {- const { patchPage } = await import("../src/human/index.js");-- const TIMEOUT_MS = 500;- const delay = (ms: number) => new Promise(r => setTimeout(r, ms));-- // Build a frame where the element does NOT exist:- // scrollIntoViewIfNeeded and boundingBox each wait until their- // individual timeout before failing, and origFrameClick does the same.- const frameLoc: any = {- boundingBox: vi.fn(async (opts?: { timeout?: number }) => {- await delay(opts?.timeout ?? 30000);- return null;- }),- scrollIntoViewIfNeeded: vi.fn(async (opts?: { timeout?: number }) => {- await delay(opts?.timeout ?? 30000);- throw new Error("timeout");- }),- evaluate: vi.fn(async () => ({ hit: true })),- isChecked: vi.fn(async () => false),- };- frameLoc.first = vi.fn(() => frameLoc);-- const origClickFn = vi.fn(async (_sel: string, opts?: any) => {- await delay(opts?.timeout ?? 30000);- throw new Error("timeout");- });-- const childFrame: any = {- click: origClickFn,- dblclick: vi.fn(async () => {}),- hover: vi.fn(async () => {}),- type: vi.fn(async () => {}),- fill: vi.fn(async () => {}),- check: vi.fn(async () => {}),- uncheck: vi.fn(async () => {}),- selectOption: vi.fn(async () => {}),- press: vi.fn(async () => {}),- pressSequentially: vi.fn(async () => {}),- tap: vi.fn(async () => {}),- clear: vi.fn(async () => {}),- dragAndDrop: vi.fn(async () => {}),- locator: vi.fn(() => frameLoc),- childFrames: vi.fn(() => []),- };-- const mainFrame = {- ...buildMockFrame(),- childFrames: vi.fn(() => [childFrame]),- };-- const page = buildMockPage({ mainFrameReturn: mainFrame });- const cfg = resolveConfig("default", {- mouse_min_steps: 1,- mouse_max_steps: 1,- idle_between_actions: false,- });- const cursor = { x: 0, y: 0, initialized: true };- patchPage(page as any, cfg, cursor as any);-- const start = Date.now();- try {- await (childFrame as any).click("#does-not-exist", { timeout: TIMEOUT_MS });- } catch {- // expected — element doesn't exist- }- const elapsed = Date.now() - start;-- // With the bug, elapsed ≈ 3 * TIMEOUT_MS (scrollIntoView + boundingBox + origClick).- // Fixed: elapsed should be ≈ 1 * TIMEOUT_MS (shared deadline).- // Allow 1.8x as upper bound to account for test overhead but catch the 3x bug.- expect(elapsed).toBeLessThan(TIMEOUT_MS * 1.8);- });-});--describe("selector reads stay isolated", () => {- it("ensureActionable rejects unsupported selectors without locator predicates", async () => {- const { ensureActionable, CHECKS_CLICK } = await import("../src/human/actionability.js");- const { UnsupportedHumanizeSelectorError } = await import("../src/human/stealthDom.js");- const page = {- _stealth: { evaluate: vi.fn().mockResolvedValue({ v: 2, r: "unsupported" }) },- locator: vi.fn(),- };-- await expect(- ensureActionable(page as any, "internal:role=button", CHECKS_CLICK, 100),- ).rejects.toBeInstanceOf(UnsupportedHumanizeSelectorError);- expect(page.locator).not.toHaveBeenCalled();- });-- it("getElementBox rejects unsupported selectors without boundingBox", async () => {- const { getElementBox } = await import("../src/human/scroll.js");- const { UnsupportedHumanizeSelectorError } = await import("../src/human/stealthDom.js");- const page = {- _stealth: { evaluate: vi.fn().mockResolvedValue({ v: 2, r: "unsupported" }) },- locator: vi.fn(),- };-- await expect(getElementBox(page as any, "internal:role=button", 100))- .rejects.toBeInstanceOf(UnsupportedHumanizeSelectorError);- expect(page.locator).not.toHaveBeenCalled();- });-});--describe("pointer-events failure semantics", () => {- // Exact ElementHandle checks retain their legacy fail-open behavior. Selector- // checks fail explicitly and never fall back to Playwright DOM reads.- it("checkPointerEventsHandle returns promptly when evaluate throws", async () => {- const { checkPointerEventsHandle } = await import("../src/human/actionability.js");- const el = {- boundingBox: vi.fn().mockRejectedValue(new Error("stale handle")),- evaluate: vi.fn().mockRejectedValue(new Error("execution context destroyed")),- };- const start = Date.now();- await checkPointerEventsHandle(el as any, 100, 100, 2000); // must not throw- expect(Date.now() - start).toBeLessThan(500);- });-- it("checkPointerEvents fails explicitly without a Playwright fallback", async () => {- const { checkPointerEvents } = await import("../src/human/actionability.js");- const { StealthEvaluationError } = await import("../src/human/stealthDom.js");- const page = { locator: vi.fn() };- const world = { evaluate: vi.fn().mockRejectedValue(new Error("execution context destroyed")) };-- await expect(- checkPointerEvents(page as any, "#x", 1, 1, 100, 100, world, 0),- ).rejects.toBeInstanceOf(StealthEvaluationError);- expect(page.locator).not.toHaveBeenCalled();- });-- it("checkPointerEventsHandle still throws when genuinely covered", async () => {- const { checkPointerEventsHandle, ElementNotReceivingEventsError } =- await import("../src/human/actionability.js");- const el = {- boundingBox: vi.fn().mockResolvedValue({ x: 0, y: 0, width: 10, height: 10 }),- evaluate: vi.fn().mockResolvedValue({ hit: false, covering: "DIV" }),- };- await expect(checkPointerEventsHandle(el as any, 5, 5, 200)).rejects.toBeInstanceOf(- ElementNotReceivingEventsError,- );- });-});diff --git a/js/tests/humanizeEngine.test.ts b/js/tests/humanizeEngine.test.tsnew file mode 100644index 0000000..5dfeb06--- /dev/null+++ b/js/tests/humanizeEngine.test.ts@@ -0,0 +1,388 @@+/**+ * Behaviour tests for the unified humanize engine (real browser, fast config).+ *+ * These replace the old mock-based tests that asserted on internals of the+ * previous implementation. Every test drives the real CloakBrowser binary+ * headless against a small local test page (js/tests/humanizeHarness.ts) with+ * near-zero delays. Mirrors tests/test_humanize_engine.py.+ *+ * Run with: CLOAKBROWSER_BINARY_PATH=/path/to/chrome npx vitest run tests/humanizeEngine.test.ts+ */++import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest';+import type { Browser, Page, Frame } from 'playwright-core';+import { errors } from 'playwright-core';+import { FAST, startServer, events, reset, value } from './humanizeHarness.js';++const HERE = path.dirname(fileURLToPath(import.meta.url));++describe('worldHelpers stays identical to the Python copy', () => {+ it('HELPERS_JS matches cloakbrowser/human/world.py', async () => {+ const { HELPERS_JS } = await import('../src/human/worldHelpers.js');+ const py = fs.readFileSync(path.resolve(HERE, '../../cloakbrowser/human/world.py'), 'utf-8');+ const m = /_HELPERS_JS = r"""([\s\S]*?)"""/.exec(py);+ expect(m).not.toBeNull();+ expect(HELPERS_JS).toBe(m![1]);+ });+});++describe('fields', () => {+ it('classifies like Playwright fill', async () => {+ const f = await import('../src/human/fields.js');+ expect(f.classify('input', 'text', false)).toBe(f.TYPE);+ expect(f.classify('input', 'date', false)).toBe(f.SET);+ expect(f.classify('input', 'checkbox', false)).toBe(f.NOT_FILLABLE);+ expect(f.classify('div', null, true)).toBe(f.TYPE);+ expect(f.allowsMistype('input', 'password')).toBe(false);+ expect(f.validateNumber('12.5')).toBe('12.5');+ expect(f.validateNumber('abc')).toBeNull();+ });++ it('splits date/time values into editor segments', async () => {+ const f = await import('../src/human/fields.js');+ expect(f.datetimeParts('date', '2024-01-31')).toMatchObject({ year: '2024', month: '01', day: '31' });+ const t = f.datetimeParts('time', '13:05')!;+ expect(t).toMatchObject({ hour: '01', hour24: 13, minute: '05' });+ expect(f.use24h(t, false).hour).toBe('13');+ expect(f.datetimeParts('date', '2024-1-31')).toBeNull();+ expect(f.segmentAutoAdvances('year', { year: '2024' })).toBe(false);+ expect(f.segmentAutoAdvances('month', { month: '01' }, 'month')).toBe(false);+ expect(f.segmentAutoAdvances('day', { day: '31' })).toBe(true);+ });+});++describe('InjectedScript source', () => {+ it('is found in the installed playwright-core', async () => {+ const { findInjectedLiteral } = await import('../src/human/injected.js');+ const lit = findInjectedLiteral();+ expect(lit.length).toBeGreaterThan(10_000);+ expect(lit.includes('InjectedScript')).toBe(true);+ });+});++describe.skipIf(!process.env.CLOAKBROWSER_BINARY_PATH)('humanize engine (real browser)', { timeout: 30_000 }, () => {+ let srv: { url: string; close: () => Promise<void> };+ let browser: Browser;+ let page: Page;++ const frame = async (p: Page): Promise<Frame> => {+ const f = p.frame({ name: 'f' })!;+ await f.waitForLoadState();+ return f;+ };++ beforeAll(async () => {+ const { launch } = await import('../src/playwright.js');+ srv = await startServer();+ browser = await launch({ headless: true, humanize: true, humanConfig: FAST as any });+ }, 120_000);++ afterAll(async () => {+ await browser?.close();+ await srv?.close();+ });++ const open = async () => {+ page = await browser.newPage();+ await page.goto(srv.url + 'index.html');+ return page;+ };+ afterEach(async () => { await page?.close().catch(() => {}); });++ // --- wiring -------------------------------------------------------------++ it('page is humanized and keeps the compat attributes', async () => {+ const p: any = await open();+ expect(p._humanCfg.mistype_chance).toBe(0);+ expect(await p._stealth.evaluate('1 + 1')).toBe(2);+ await p._original.click('#btn'); // raw Playwright still reachable+ });++ it('a non-humanized page in the same process is untouched', async () => {+ const { launch } = await import('../src/playwright.js');+ const plain = await launch({ headless: true });+ try {+ const p = await plain.newPage();+ await p.goto(srv.url + 'index.html');+ expect((p as any)._original).toBeUndefined();+ await reset(p);+ await p.click('#btn');+ await p.fill('#name', 'plain');+ expect(await value(p, '#name')).toBe('plain');+ // Playwright's own click teleports: no curve of mouse moves.+ expect((await events(p, 'mousemove')).length).toBeLessThan(3);+ } finally {+ await plain.close();+ }+ }, 60_000);++ it('humanized actions leave no side effects in the page (listeners, mutations)', async () => {+ page = await browser.newPage();+ await page.addInitScript(() => {+ const add = EventTarget.prototype.addEventListener;+ const d: any = (window as any).__engine = { listeners: 0, mutations: 0 };+ EventTarget.prototype.addEventListener = function (this: any, t: any, f: any, o: any) {+ if (this === window || this === document) d.listeners++;+ return add.call(this, t, f, o);+ };+ new MutationObserver((m) => { d.mutations += m.length; })+ .observe(document, { subtree: true, childList: true, attributes: true });+ });+ await page.goto(srv.url + 'index.html?nolog');+ // page.$() is Playwright's own query; take the handle first, then measure our actions.+ const handle = (await page.$('#btn'))!;+ await page.evaluate(() => { const d = (window as any).__engine; d.listeners = 0; d.mutations = 0; });+ await page.getByRole('button', { name: 'Press me' }).click();+ await page.locator('#buttons >> #btn').hover();+ await handle.click();+ await page.frameLocator('#frame').locator('#finput').click();+ await expect(page.locator('.dup').click({ timeout: 500 })).rejects.toThrow(/strict mode/);+ const seen = await page.evaluate(() => {+ const d = (window as any).__engine;+ return { listeners: d.listeners, mutations: d.mutations };+ });+ expect(seen).toEqual({ listeners: 0, mutations: 0 });+ });++ // --- pointer actions ------------------------------------------------------++ it('click moves along a curve, then presses', async () => {+ const p = await open();+ await reset(p);+ await p.click('#btn');+ expect((await events(p, 'mousemove')).length).toBeGreaterThanOrEqual(3);+ expect((await events(p, 'click')).map((e) => e.target)).toEqual(['btn']);+ });++ it('click options are honoured', async () => {+ const p = await open();+ await reset(p);+ await p.click('#btn', { button: 'right', modifiers: ['Shift'] });+ const down = (await events(p, 'mousedown')).pop();+ expect([down.button, down.shift]).toEqual([2, true]);+ await reset(p);+ await p.click('#btn', { clickCount: 2 });+ expect((await events(p, 'dblclick')).length).toBe(1);+ await reset(p);+ await p.click('#btn', { trial: true });+ expect(await events(p, 'click')).toEqual([]);+ });++ it('hover does not press; dblclick matches a real double click', async () => {+ const p = await open();+ await reset(p);+ await p.hover('#btn');+ expect(await events(p, 'mousedown')).toEqual([]);+ await reset(p);+ await p.dblclick('#btn');+ const seq = (await events(p, 'mousedown', 'click', 'dblclick')).map((e) => `${e.t}:${e.detail}`).join(' ');+ expect(seq).toBe('mousedown:1 click:1 mousedown:2 click:2 dblclick:2');+ });++ it('hover holds the modifiers while the mouse moves', async () => {+ const p = await open();+ await p.hover('#chk');+ await reset(p);+ await p.hover('#btn', { modifiers: ['Shift'] });+ const seq = await events(p, 'mousemove', 'keydown', 'keyup');+ const moves = seq.filter((e) => e.t === 'mousemove');+ expect(moves.length).toBeGreaterThan(0);+ expect(moves.every((e) => e.shift)).toBe(true);+ expect(seq[0].t).toBe('keydown');+ expect(seq[seq.length - 1].t).toBe('keyup');+ expect(await events(p, 'mousedown')).toEqual([]);+ });++ it('covered element times out with the reason', async () => {+ const p = await open();+ const err = await p.click('#covered', { timeout: 1000 }).catch((e) => e);+ expect(err).toBeInstanceOf(errors.TimeoutError);+ expect(err.message).toMatch(/intercepts pointer events/);+ });++ it('strict mode violation', async () => {+ const p = await open();+ await expect(p.locator('.dup').click({ timeout: 1000 })).rejects.toThrow(/strict mode violation/);+ await p.locator('.dup').first().click();+ });++ it('page default timeout and timeout: 0', async () => {+ const p = await open();+ p.setDefaultTimeout(500);+ const t0 = Date.now();+ await expect(p.click('#missing')).rejects.toBeInstanceOf(errors.TimeoutError);+ expect(Date.now() - t0).toBeLessThan(1500);+ await p.click('#btn', { timeout: 0 });+ });++ it('standard locators', async () => {+ const p = await open();+ await p.getByRole('button', { name: 'Press me' }).click();+ await p.locator('#buttons').locator('#btn').click();+ await p.locator('button').filter({ hasText: 'Press me' }).click();+ await p.click('#btn:visible');+ });++ // --- keyboard -------------------------------------------------------------++ it('fill replaces, pressSequentially appends, clear empties', async () => {+ const p = await open();+ await p.fill('#name', 'Shaho');+ expect(await value(p, '#name')).toBe('Shaho');+ await p.locator('#name').pressSequentially('!');+ expect(await value(p, '#name')).toBe('Shaho!');+ await p.locator('#name').clear();+ expect(await value(p, '#name')).toBe('');+ });++ it('value inputs are operated like a person (trusted events only)', async () => {+ const p = await open();+ await p.evaluate(() => {+ (window as any).__untrusted = 0;+ for (const t of ['input', 'change']) {+ document.addEventListener(t, (e) => { if (!e.isTrusted) (window as any).__untrusted++; }, true);+ }+ });+ await p.fill('#date', '2024-01-31');+ await p.fill('#date', '1999-12-05');+ await p.fill('#range', '80');+ expect(await p.selectOption('#sel', 'b')).toEqual(['b']);+ expect([await value(p, '#date'), await value(p, '#range'), await value(p, '#sel')]).toEqual(['1999-12-05', '80', 'b']);+ expect(await p.evaluate(() => (window as any).__untrusted)).toBe(0);+ await expect(p.fill('#color', '#ff0000')).rejects.toThrow(/native colour picker/);+ await expect(p.fill('#chk', 'x')).rejects.toThrow(/cannot be filled/);+ }, 60_000);++ it('unreachable element is not focused programmatically', async () => {+ const p = await open();+ const err = await p.fill('#neg', 'x', { timeout: 1500 }).catch((e) => e);+ expect(err).toBeInstanceOf(errors.TimeoutError);+ expect(err.message).toMatch(/outside of the viewport/);+ expect(await value(p, '#neg')).toBe('');+ });++ it('press focuses its target first and forwards delay', async () => {+ const p = await open();+ await p.focus('#fa');+ await (await p.$('#fb'))!.press('x');+ expect([await value(p, '#fa'), await value(p, '#fb')]).toEqual(['', 'x']);+ await reset(p);+ await p.press('#name', 'a', { delay: 150 });+ const ev = await events(p, 'keydown', 'keyup');+ expect(ev[ev.length - 1].ts - ev[ev.length - 2].ts).toBeGreaterThanOrEqual(120);+ });++ it('press / type reach non-focusable targets (canvas, document key handlers)', async () => {+ const p = await open();+ await p.evaluate(() => { (window as any).__keys = []; document.addEventListener('keydown', (e) => (window as any).__keys.push(e.key)); });+ await p.press('#cv', 'ArrowUp');+ await p.locator('#cv').pressSequentially('ab');+ expect(await p.evaluate(() => (window as any).__keys)).toEqual(['ArrowUp', 'a', 'b']);+ });++ it('mistypes are corrected, skip masked fields, uppercase uses Shift', async () => {+ const p = await open();+ const typo = { human_config: { mistype_chance: 1 } } as any;+ await p.fill('#name', 'Hello', typo);+ expect(await value(p, '#name')).toBe('Hello');+ await p.fill('#hex', 'ab', typo);+ expect(await value(p, '#hex')).toBe('ab');+ await reset(p);+ await p.locator('#name').pressSequentially('AB', typo);+ const bad = (await events(p, 'keydown')).filter((e) => /^[A-Z]$/.test(e.key) && !e.shift);+ expect(bad).toEqual([]);+ });++ it('scroll overshoot wheels past the target and back', async () => {+ const p = await open();+ await p.setViewportSize({ width: 800, height: 300 });+ await reset(p);+ await p.click('#chk', { human_config: { scroll_overshoot_chance: 1, scroll_overshoot_px: [120, 120] } });+ const dys = (await events(p, 'wheel')).map((e) => e.dy);+ expect(dys.some((d) => d > 0) && dys.some((d) => d < 0)).toBe(true);+ expect((await events(p, 'click')).map((e) => e.target)).toEqual(['chk']);+ await reset(p);+ await p.evaluate(() => scrollTo(0, 0));+ await p.click('#chk', { human_config: { scroll_overshoot_chance: 0 } });+ expect((await events(p, 'wheel')).every((e) => e.dy > 0)).toBe(true);+ });++ it('per-call human_config and flat config keys', async () => {+ const p = await open();+ const hold = async (o: any) => {+ await reset(p);+ await p.click('#btn', o);+ const up = (await events(p, 'mouseup')).pop(), down = (await events(p, 'mousedown')).pop();+ return up.ts - down.ts;+ };+ expect(await hold({ human_config: { click_hold_button: [300, 300] } })).toBeGreaterThanOrEqual(250);+ expect(await hold({ click_hold_button: [300, 300] })).toBeGreaterThanOrEqual(250);+ });++ // --- checkable / select ---------------------------------------------------++ it('check, uncheck, setChecked, selectOption by index', async () => {+ const p = await open();+ await p.check('#chk');+ expect(await p.isChecked('#chk')).toBe(true);+ await p.locator('#chk').uncheck();+ expect(await p.isChecked('#chk')).toBe(false);+ await (await p.$('#chk'))!.setChecked(true);+ expect(await p.isChecked('#chk')).toBe(true);+ expect(await p.selectOption('#sel', { index: 1 })).toEqual(['b']);+ });++ // --- frames and handles ---------------------------------------------------++ it('frame actions', async () => {+ const p = await open();+ const f = await frame(p);+ await f.fill('#finput', 'in frame');+ expect(await value(f, '#finput')).toBe('in frame');+ await p.frameLocator('#frame').locator('#finput').pressSequentially('!');+ expect(await value(f, '#finput')).toBe('in frame!');+ await reset(f);+ await f.click('#fbottom', { timeout: 5000 });+ expect((await events(f, 'click')).map((e) => e.target)).toEqual(['fbottom']);+ // The frame was scrolled to its bottom above; wheeling back up takes time.+ await expect(f.click('#fcovered', { timeout: 4000 })).rejects.toThrow(/intercepts pointer events/);+ }, 60_000);++ it('element handle actions', async () => {+ const p = await open();+ await (await p.$('#name'))!.fill('handle');+ expect(await value(p, '#name')).toBe('handle');+ await reset(p);+ await (await p.$('#btn'))!.click();+ expect((await events(p, 'click')).map((e) => e.target)).toEqual(['btn']);+ });++ it('mouse API', async () => {+ const p = await open();+ await reset(p);+ await p.mouse.move(50, 50, { steps: 1 });+ expect((await events(p, 'mousemove')).length).toBe(1);+ const box = (await p.locator('#btn').boundingBox())!;+ await reset(p);+ await p.mouse.click(box.x + 5, box.y + 5, { button: 'right' });+ expect((await events(p, 'mousedown')).map((e) => e.button)).toEqual([2]);+ });++ it('select-all follows the persona, not the host OS', async () => {+ const { launch } = await import('../src/playwright.js');+ const mac = await launch({ headless: true, humanize: true, humanConfig: FAST as any, args: ['--fingerprint-platform=macos'] });+ try {+ const p = await mac.newPage();+ await p.goto(srv.url + 'index.html');+ expect(await p.evaluate(() => navigator.platform)).toBe('MacIntel');+ await p.fill('#name', 'old');+ await p.fill('#name', 'Mac');+ expect(await value(p, '#name')).toBe('Mac');+ } finally {+ await mac.close();+ }+ }, 60_000);+});diff --git a/js/tests/humanizeHarness.ts b/js/tests/humanizeHarness.tsnew file mode 100644index 0000000..23ade3e--- /dev/null+++ b/js/tests/humanizeHarness.ts@@ -0,0 +1,289 @@+/**+ * Test page and helpers for the real-browser humanize tests (JS).+ *+ * The page logs every input event into window.__log and main-world DOM reads+ * into window.__mainWorldHits. It is served from 127.0.0.1 so its iframe is+ * same-origin. Same page as tests/test_humanize_engine.py and the .NET tests.+ */++import http from 'node:http';+import type { AddressInfo } from 'node:net';++/** Fast, deterministic humanize settings (same code paths, no long sleeps). */+export const FAST = {+ mistype_chance: 0,+ field_switch_delay: [0, 0] as [number, number],+ typing_delay: 5,+ typing_delay_spread: 0,+ typing_pause_chance: 0,+ key_hold: [5, 5] as [number, number],+ shift_down_delay: [5, 5] as [number, number],+ shift_up_delay: [5, 5] as [number, number],+ mouse_min_steps: 4,+ mouse_max_steps: 4,+ mouse_burst_pause: [0, 0] as [number, number],+ mouse_overshoot_chance: 0,+ click_aim_delay_input: [5, 5] as [number, number],+ click_aim_delay_button: [5, 5] as [number, number],+ click_hold_input: [20, 20] as [number, number],+ click_hold_button: [20, 20] as [number, number],+ idle_between_actions: false,+ scroll_pause_fast: [5, 5] as [number, number],+ scroll_pause_slow: [5, 5] as [number, number],+ scroll_settle_delay: [50, 50] as [number, number],+ scroll_pre_move_delay: [5, 5] as [number, number],+ scroll_overshoot_chance: 0,+};++const INDEX_HTML = `<!doctype html>+<html>+<head>+<meta charset="utf-8">+<title>humanize fixture</title>+<script>+// Records DOM reads that only a main-world evaluate makes into window.__mainWorldHits.+(function () {+ const hits = [];+ window.__mainWorldHits = hits;+ const note = (probe, detail) => hits.push({ probe, detail: String(detail ?? '') });++ const origGetAttribute = Element.prototype.getAttribute;+ Element.prototype.getAttribute = function (name) {+ if (name === 'contenteditable') note('getAttribute(contenteditable)', this.id || this.tagName);+ return origGetAttribute.call(this, name);+ };++ const activeDesc = Object.getOwnPropertyDescriptor(Document.prototype, 'activeElement');+ Object.defineProperty(Document.prototype, 'activeElement', {+ configurable: true,+ get() {+ note('document.activeElement', '');+ return activeDesc.get.call(this);+ },+ });++ const origFromPoint = Document.prototype.elementFromPoint;+ Document.prototype.elementFromPoint = function (x, y) {+ note('elementFromPoint', x + ',' + y);+ return origFromPoint.call(this, x, y);+ };++ const origQS = Document.prototype.querySelector;+ Document.prototype.querySelector = function (sel) {+ note('document.querySelector', sel);+ return origQS.call(this, sel);+ };+})();+</script>+<script>+// Records every input event (capture phase) into window.__log.+(function () {+ const log = [];+ window.__log = log;+ window.__reset = () => { log.length = 0; };++ const TYPES = [+ 'pointerdown', 'pointerup', 'mousedown', 'mouseup', 'click', 'dblclick',+ 'contextmenu', 'auxclick', 'mousemove', 'keydown', 'keyup', 'beforeinput',+ 'input', 'wheel', 'focus',+ ];+ const idOf = (el) => {+ if (el === window) return 'window';+ if (!el || el === document) return 'document';+ return el.id || (el.tagName ? el.tagName.toLowerCase() : '?');+ };+ for (const type of TYPES) {+ document.addEventListener(type, (e) => {+ const rec = { t: type, ts: e.timeStamp, trusted: e.isTrusted, target: idOf(e.target) };+ if ('clientX' in e) { rec.x = e.clientX; rec.y = e.clientY; }+ if ('button' in e) rec.button = e.button;+ if ('detail' in e && type !== 'focus') rec.detail = e.detail;+ if ('key' in e) { rec.key = e.key; rec.code = e.code; }+ if ('shiftKey' in e) {+ rec.shift = e.shiftKey; rec.ctrl = e.ctrlKey; rec.meta = e.metaKey; rec.alt = e.altKey;+ }+ if ('inputType' in e) { rec.inputType = e.inputType; rec.data = e.data; }+ if (type === 'wheel') { rec.dx = e.deltaX; rec.dy = e.deltaY; }+ log.push(rec);+ }, true);+ }+ window.addEventListener('scroll', () => {+ log.push({ t: 'scroll', ts: performance.now(), sx: scrollX, sy: scrollY });+ }, true);++})();+</script>+<style>+ body { margin: 0; font: 14px sans-serif; }+ section { padding: 8px 12px; border-bottom: 1px solid #ddd; }+ input, select, button, textarea { font: inherit; margin: 2px 6px 2px 0; }+ button { min-width: 140px; min-height: 36px; }+ #neg { position: absolute; top: -600px; left: -600px; }+ .wrap { position: relative; display: inline-block; }+ .over { position: absolute; inset: 0; background: rgba(255,0,0,.3); }+</style>+</head>+<body>+<section id="text">+ <h4>Text inputs</h4>+ <input id="name" value="firstname">+ <input id="long" value="hello world">+ <!-- Masked field: the page strips anything that is not hex (card/IBAN/serial-style mask). -->+ <input id="hex" oninput="this.value=this.value.replace(/[^0-9a-f]/gi,'')">+ <textarea id="ta">old text</textarea>+</section>+<section id="special">+ <h4>Non-text inputs</h4>+ <input id="date" type="date">+ <input id="range" type="range" min="0" max="100" value="10">+ <input id="color" type="color" value="#000000">+</section>+<section id="focus">+ <h4>Focus targets</h4>+ <input id="fa" placeholder="A (focused first)">+ <input id="fb" placeholder="B (handle target)">+</section>+<section id="buttons">+ <h4>Buttons</h4>+ <button id="btn">Press me</button>+ <button class="dup" id="dup1">Duplicate</button>+ <button class="dup" id="dup2">Duplicate</button>+ <input id="chk" type="checkbox">+ <select id="sel"><option value="a">a</option><option value="b">b</option></select>+</section>+<section id="covered-sec">+ <h4>Covered button (transparent overlay on top)</h4>+ <span class="wrap"><button id="covered">covered</button><div class="over" id="over"></div></span>+</section>+<input id="neg" name="neg">+<canvas id="cv" width="200" height="40" style="border:1px solid #999"></canvas>+<section id="frames">+ <h4>Frame</h4>+ <iframe id="frame" name="f" src="frame.html" style="width:420px;height:200px"></iframe>+</section>+<div style="height:200px"></div>+</body>+</html>+`;++const FRAME_HTML = `<!doctype html>+<html>+<head>+<meta charset="utf-8">+<script>+// Records DOM reads that only a main-world evaluate makes into window.__mainWorldHits.+(function () {+ const hits = [];+ window.__mainWorldHits = hits;+ const note = (probe, detail) => hits.push({ probe, detail: String(detail ?? '') });++ const origGetAttribute = Element.prototype.getAttribute;+ Element.prototype.getAttribute = function (name) {+ if (name === 'contenteditable') note('getAttribute(contenteditable)', this.id || this.tagName);+ return origGetAttribute.call(this, name);+ };++ const activeDesc = Object.getOwnPropertyDescriptor(Document.prototype, 'activeElement');+ Object.defineProperty(Document.prototype, 'activeElement', {+ configurable: true,+ get() {+ note('document.activeElement', '');+ return activeDesc.get.call(this);+ },+ });++ const origFromPoint = Document.prototype.elementFromPoint;+ Document.prototype.elementFromPoint = function (x, y) {+ note('elementFromPoint', x + ',' + y);+ return origFromPoint.call(this, x, y);+ };++ const origQS = Document.prototype.querySelector;+ Document.prototype.querySelector = function (sel) {+ note('document.querySelector', sel);+ return origQS.call(this, sel);+ };+})();+</script>+<script>+// Records every input event (capture phase) into window.__log.+(function () {+ const log = [];+ window.__log = log;+ window.__reset = () => { log.length = 0; };++ const TYPES = [+ 'pointerdown', 'pointerup', 'mousedown', 'mouseup', 'click', 'dblclick',+ 'contextmenu', 'auxclick', 'mousemove', 'keydown', 'keyup', 'beforeinput',+ 'input', 'wheel', 'focus',+ ];+ const idOf = (el) => {+ if (el === window) return 'window';+ if (!el || el === document) return 'document';+ return el.id || (el.tagName ? el.tagName.toLowerCase() : '?');+ };+ for (const type of TYPES) {+ document.addEventListener(type, (e) => {+ const rec = { t: type, ts: e.timeStamp, trusted: e.isTrusted, target: idOf(e.target) };+ if ('clientX' in e) { rec.x = e.clientX; rec.y = e.clientY; }+ if ('button' in e) rec.button = e.button;+ if ('detail' in e && type !== 'focus') rec.detail = e.detail;+ if ('key' in e) { rec.key = e.key; rec.code = e.code; }+ if ('shiftKey' in e) {+ rec.shift = e.shiftKey; rec.ctrl = e.ctrlKey; rec.meta = e.metaKey; rec.alt = e.altKey;+ }+ if ('inputType' in e) { rec.inputType = e.inputType; rec.data = e.data; }+ if (type === 'wheel') { rec.dx = e.deltaX; rec.dy = e.deltaY; }+ log.push(rec);+ }, true);+ }+ window.addEventListener('scroll', () => {+ log.push({ t: 'scroll', ts: performance.now(), sx: scrollX, sy: scrollY });+ }, true);++})();+</script>+<style>+ body { margin: 0; font: 14px sans-serif; }+ .wrap { position: relative; display: inline-block; }+ .over { position: absolute; inset: 0; background: rgba(255,0,0,.3); }+</style>+</head>+<body>+<input id="finput" value="old">+<span class="wrap"><button id="fcovered">covered</button><div class="over" id="fover"></div></span>+<div style="height:1200px"></div>+<button id="fbottom">bottom</button>+</body>+</html>+`;++const PAGES: Record<string, string> = { '/index.html': INDEX_HTML, '/frame.html': FRAME_HTML };++export async function startServer(): Promise<{ url: string; close: () => Promise<void> }> {+ const srv = http.createServer((req, res) => {+ const body = PAGES[(req.url ?? '/').split('?')[0]];+ res.writeHead(body ? 200 : 404, { 'content-type': 'text/html; charset=utf-8' });+ res.end(body ?? '');+ });+ await new Promise<void>((r) => srv.listen(0, '127.0.0.1', r));+ const { port } = srv.address() as AddressInfo;+ return { url: `http://127.0.0.1:${port}/`, close: () => new Promise((r) => srv.close(() => r())) };+}++/** Recorded input events, optionally filtered by type. */+export async function events(target: any, ...types: string[]): Promise<any[]> {+ const log: any[] = await target.evaluate('window.__log.slice()');+ return types.length ? log.filter((e) => types.includes(e.t)) : log;+}++export async function reset(target: any): Promise<void> {+ await target.evaluate('window.__reset(); window.__mainWorldHits.length = 0');+}++export async function value(target: any, selector: string): Promise<string> {+ return target.evaluate(+ (s: string) => { const e: any = document.querySelector(s); return e.isContentEditable ? e.textContent : e.value; },+ selector,+ );+}diff --git a/js/tests/humanizePuppeteer.test.ts b/js/tests/humanizePuppeteer.test.tsnew file mode 100644index 0000000..b0ca93f--- /dev/null+++ b/js/tests/humanizePuppeteer.test.ts@@ -0,0 +1,96 @@+/**+ * Real-browser behaviour tests for the Puppeteer humanize wrapper.+ *+ * Drives the CloakBrowser binary headless against the test page in humanizeHarness.ts with+ * near-zero delays. Skipped unless CLOAKBROWSER_BINARY_PATH is set.+ */++import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest';+import type { Browser, Page } from 'puppeteer-core';+import { launch } from '../src/puppeteer.js';+import { FAST, startServer, events, reset, value } from './humanizeHarness.js';++describe.skipIf(!process.env.CLOAKBROWSER_BINARY_PATH)('humanize: Puppeteer (real browser)', { timeout: 30_000 }, () => {+ let srv: { url: string; close: () => Promise<void> };+ let browser: Browser;+ const pages: Page[] = [];++ const open = async (b: Browser = browser): Promise<Page> => {+ const page = await b.newPage();+ pages.push(page);+ await page.setViewport({ width: 1280, height: 720 });+ await page.goto(srv.url + 'index.html');+ return page;+ };+ const frameOf = async (page: Page) => {+ const f = page.frames().find((x) => x.name() === 'f')!;+ await f.waitForSelector('#finput');+ return f;+ };++ beforeAll(async () => {+ srv = await startServer();+ browser = await launch({ headless: true, humanize: true, humanConfig: FAST as any });+ }, 120_000);++ afterEach(async () => {+ for (const p of pages.splice(0)) await p.close().catch(() => {});+ });++ afterAll(async () => {+ await browser?.close();+ await srv?.close();+ });++ it("click({ button: 'right' }) and mouse.click({ button: 'right' })", async () => {+ const page = await open();+ await reset(page);+ await page.click('#btn', { button: 'right' });+ const b = (await (await page.$('#btn'))!.boundingBox())!;+ await page.mouse.click(b.x + 5, b.y + 5, { button: 'right' });+ expect((await events(page, 'mousedown')).map((e) => e.button)).toEqual([2, 2]);+ expect((await events(page, 'contextmenu')).length).toBe(2);+ });++ it('click({ count: 2 }) is a real double click (detail 1, 2)', async () => {+ const page = await open();+ await reset(page);+ await page.click('#btn', { count: 2 } as any);+ const seq = (await events(page, 'mousedown', 'click', 'dblclick')).map((e) => `${e.t}:${e.detail}`).join(' ');+ expect(seq).toBe('mousedown:1 click:1 mousedown:2 click:2 dblclick:2');+ });++ it('frame.click / type / hover resolve inside the frame (#184)', async () => {+ // Tall viewport: the frame input is already in view, so no wheel scroll can+ // land over the iframe (known gap: Puppeteer's scroll may wheel the iframe).+ const page = await open();+ await page.setViewport({ width: 1280, height: 1400 });+ const f = await frameOf(page);+ await reset(f);+ await f.click('#finput');+ expect((await events(f, 'click')).map((e) => e.target)).toEqual(['finput']);+ // Puppeteer's type() leaves the caret where the click landed, so start empty.+ await f.evaluate(() => { (document.querySelector('#finput') as HTMLInputElement).value = ''; });+ await f.type('#finput', 'abc');+ expect(await value(f, '#finput')).toBe('abc');+ await reset(f);+ await f.hover('#finput');+ expect((await events(f, 'mousemove')).length).toBeGreaterThan(0);+ });++ it('uppercase typos are typed with Shift', async () => {+ const b = await launch({ headless: true, humanize: true, humanConfig: { ...FAST, mistype_chance: 1 } as any });+ try {+ const page = await open(b);+ await page.evaluate(() => { (document.querySelector('#name') as HTMLInputElement).value = ''; });+ await reset(page);+ await page.type('#name', 'AB');+ const unshifted = (await events(page, 'keydown'))+ .filter((e) => e.key.length === 1 && /[A-Z]/.test(e.key) && !e.shift).map((e) => e.key);+ expect(unshifted).toEqual([]);+ expect(await value(page, '#name')).toBe('AB');+ } finally {+ await b.close();+ }+ }, 60_000);+});diff --git a/js/tests/stealth.puppeteer.test.ts b/js/tests/stealth.puppeteer.test.tsindex ae805db..9852da2 100644--- a/js/tests/stealth.puppeteer.test.ts+++ b/js/tests/stealth.puppeteer.test.ts@@ -915,6 +915,23 @@ describe("Puppeteer: mouse.wheel() smooth scroll", () => {expect(wheelCalls.length).toBeGreaterThan(1);});+ it("smoothWheel never sends a zero step (sub-pixel tail folded in)", async () => {+ const { smoothWheel } = await import("../src/human-puppeteer/scroll.js");+ const calls: [number, number][] = [];+ const raw: any = { wheel: async (dx: number, dy: number) => { calls.push([dx, dy]); } };+ const cfg = resolveConfig("default");+ let total = 0;+ // A 21-40px delta is one or two chunks; a remainder under 0.5px used to+ // round to a (0, 0) wheel event a few percent of the time.+ for (let i = 0; i < 300; i++) {+ const delta = 21 + (i % 20);+ total += delta;+ await smoothWheel(raw, delta, cfg);+ }+ expect(calls.some(([dx, dy]) => dx === 0 && dy === 0)).toBe(false);+ expect(calls.reduce((a, [, dy]) => a + dy, 0)).toBe(total);+ }, 30_000);+it("mouse.wheel({deltaX: 200}) smooths horizontal scroll too", async () => {const { patchPage } = await import("../src/human-puppeteer/index.js");diff --git a/js/tests/stealth.test.ts b/js/tests/stealth.test.tsindex 05ddc1b..db690b7 100644--- a/js/tests/stealth.test.ts+++ b/js/tests/stealth.test.ts@@ -2,11 +2,9 @@* Unit tests for stealth / anti-detection fixes (issue #110).** Covers:- * - StealthEval — CDP isolated-world lifecycle (evaluate, invalidate, retry)- * - isInputElement / isSelectorFocused — stealth DOM queries with fallback+ * - page._stealth wiring (isolated-world evaluate / invalidate / CDP session)* - typeShiftSymbol — CDP Input.dispatchKeyEvent path vs evaluate fallback* - humanType integration — shift symbols routed via CDP- * - Navigation invalidation (goto → stealth.invalidate)* - patchPage stealth infrastructure wiring* - SHIFT_SYMBOL_CODES / SHIFT_SYMBOL_KEYCODES completeness*@@ -537,443 +535,6 @@ describe("patchPage stealth infrastructure", () => {expect((page as any)._original).toBeDefined();expect((page as any)._humanCfg).toBe(cfg);});-- it("goto invalidates stealth context", async () => {- const { patchPage } = await import("../src/human/index.js");-- const page = buildMockPage();- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- patchPage(page as any, cfg, cursor as any);-- const stealth = (page as any)._stealth;- const invalidateSpy = vi.spyOn(stealth, "invalidate");-- await page.goto("https://example.com");-- expect(invalidateSpy).toHaveBeenCalled();- });-- it("humanClickFn is stored for frame patching", async () => {- const { patchPage } = await import("../src/human/index.js");-- const page = buildMockPage();- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- patchPage(page as any, cfg, cursor as any);-- expect(typeof (page as any)._humanClickFn).toBe("function");- expect(typeof (page as any)._humanHoverFn).toBe("function");- expect(typeof (page as any)._humanClearFn).toBe("function");- expect(typeof (page as any)._humanPressFn).toBe("function");- });-});---// =========================================================================-// StealthEval lifecycle (via patchPage)-// =========================================================================-describe("StealthEval lifecycle", () => {- it("stealth.invalidate() is callable without error", async () => {- const { patchPage } = await import("../src/human/index.js");-- const page = buildMockPage();- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- patchPage(page as any, cfg, cursor as any);-- const stealth = (page as any)._stealth;- expect(() => stealth.invalidate()).not.toThrow();- });-- it("stealth.getCdpSession() returns a CDP session", async () => {- const { patchPage } = await import("../src/human/index.js");-- const page = buildMockPage();- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- patchPage(page as any, cfg, cursor as any);-- const stealth = (page as any)._stealth;- const session = await stealth.getCdpSession();- expect(session).toBeDefined();- expect(typeof session.send).toBe("function");- });-- it("stealth.evaluate() creates world and returns value", async () => {- const { patchPage } = await import("../src/human/index.js");-- const mockCdp = buildMockCDP({- send: vi.fn(async (method: string, params?: any) => {- if (method === "Page.getFrameTree") {- return { frameTree: { frame: { id: "F1" } } };- }- if (method === "Page.createIsolatedWorld") {- return { executionContextId: 42 };- }- if (method === "Runtime.evaluate") {- return { result: { value: true } };- }- return {};- }),- });-- const page = buildMockPage();- page.context = vi.fn(() => ({- pages: vi.fn(() => []),- addInitScript: vi.fn(async () => {}),- newCDPSession: vi.fn(async () => mockCdp),- }));-- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- patchPage(page as any, cfg, cursor as any);-- const stealth = (page as any)._stealth;- const result = await stealth.evaluate("1 + 1");- expect(result).toBe(true);- });-- it("stealth.evaluate() retries on exceptionDetails", async () => {- const { patchPage } = await import("../src/human/index.js");- let attempt = 0;-- const mockCdp = buildMockCDP({- send: vi.fn(async (method: string, params?: any) => {- if (method === "Page.getFrameTree") {- return { frameTree: { frame: { id: "F1" } } };- }- if (method === "Page.createIsolatedWorld") {- return { executionContextId: 50 + attempt };- }- if (method === "Runtime.evaluate") {- attempt++;- if (attempt === 1) {- return { exceptionDetails: { text: "stale" } };- }- return { result: { value: "recovered" } };- }- return {};- }),- });-- const page = buildMockPage();- page.context = vi.fn(() => ({- pages: vi.fn(() => []),- addInitScript: vi.fn(async () => {}),- newCDPSession: vi.fn(async () => mockCdp),- }));-- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- patchPage(page as any, cfg, cursor as any);-- const stealth = (page as any)._stealth;- const result = await stealth.evaluate("test");- expect(result).toBe("recovered");- });-- it("stealth.evaluate() returns undefined after double failure", async () => {- const { patchPage } = await import("../src/human/index.js");-- const mockCdp = buildMockCDP({- send: vi.fn(async (method: string) => {- if (method === "Page.getFrameTree") {- return { frameTree: { frame: { id: "F1" } } };- }- if (method === "Page.createIsolatedWorld") {- return { executionContextId: 70 };- }- if (method === "Runtime.evaluate") {- return { exceptionDetails: { text: "always broken" } };- }- return {};- }),- });-- const page = buildMockPage();- page.context = vi.fn(() => ({- pages: vi.fn(() => []),- addInitScript: vi.fn(async () => {}),- newCDPSession: vi.fn(async () => mockCdp),- }));-- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- patchPage(page as any, cfg, cursor as any);-- const stealth = (page as any)._stealth;- const result = await stealth.evaluate("broken");- expect(result).toBeUndefined();- });-});---// =========================================================================-// isInputElement / isSelectorFocused — through patchPage click flow-// =========================================================================-describe("isInputElement stealth integration via patchPage", () => {- it("click() uses stealth.evaluate for isInputElement (no page.evaluate)", async () => {- const { patchPage } = await import("../src/human/index.js");-- const evaluateCalls: any[] = [];- const stealthEvaluateCalls: string[] = [];-- const mockCdp = buildMockCDP({- send: vi.fn(async (method: string, params?: any) => {- if (method === "Page.getFrameTree") {- return { frameTree: { frame: { id: "F1" } } };- }- if (method === "Page.createIsolatedWorld") {- return { executionContextId: 100 };- }- if (method === "Runtime.evaluate") {- stealthEvaluateCalls.push(params.expression);- return { result: { value: {- v: 2, r: "ok", targetId: 1, gen: 1, attached: true, visible: true,- enabled: true, editable: true, isInput: false, focused: false,- checked: false, hit: true,- box: { x: 100, y: 300, width: 200, height: 30 },- } } };- }- return {};- }),- });-- const page = buildMockPage({- evaluate: vi.fn(async (...args: any[]) => {- evaluateCalls.push(args);- return { hit: true };- }),- });- page.context = vi.fn(() => ({- pages: vi.fn(() => []),- addInitScript: vi.fn(async () => {}),- newCDPSession: vi.fn(async () => mockCdp),- }));-- const cfg = resolveConfig("default", { idle_between_actions: false });- const cursor = { x: 100, y: 100, initialized: true };- patchPage(page as any, cfg, cursor as any);-- try {- await page.click("#btn");- } catch (e) {- // scrollToElement might throw with mocks; that's fine- }-- // The stealth path should have been used for isInputElement- // (Runtime.evaluate in isolated world, NOT page.evaluate)- const isInputCalls = stealthEvaluateCalls.filter(- expr => expr.includes("tagName") || expr.includes("querySelector")- );-- // We expect at least one stealth evaluate for the isInputElement check- // OR page.evaluate was NOT called for this purpose- // The key assertion: page.evaluate is NOT used for querySelector-based DOM checks- const qsCalls = evaluateCalls.filter(- args => typeof args[0] === "string" && args[0].includes("querySelector")- );- // If stealth worked, no querySelector calls should go through page.evaluate- if (isInputCalls.length > 0) {- expect(qsCalls.length).toBe(0);- }- });-});---// =========================================================================-// isSelectorFocused stealth integration via patchPage press flow-// =========================================================================-describe("isSelectorFocused stealth integration via patchPage", () => {- it("press() uses stealth.evaluate for focus check", async () => {- const { patchPage } = await import("../src/human/index.js");-- const stealthEvaluateCalls: string[] = [];-- const mockCdp = buildMockCDP({- send: vi.fn(async (method: string, params?: any) => {- if (method === "Page.getFrameTree") {- return { frameTree: { frame: { id: "F1" } } };- }- if (method === "Page.createIsolatedWorld") {- return { executionContextId: 200 };- }- if (method === "Runtime.evaluate") {- stealthEvaluateCalls.push(params.expression);- return { result: { value: {- v: 2, r: "ok", targetId: 1, gen: 1, attached: true, visible: true,- enabled: true, editable: true, isInput: true, focused: true,- checked: false, hit: true,- box: { x: 100, y: 300, width: 200, height: 30 },- } } };- }- return {};- }),- });-- const pressedKeys: string[] = [];- const page = buildMockPage({- evaluate: vi.fn(async () => true),- keyboardPress: async (key: string) => { pressedKeys.push(key); },- });- page.context = vi.fn(() => ({- pages: vi.fn(() => []),- addInitScript: vi.fn(async () => {}),- newCDPSession: vi.fn(async () => mockCdp),- }));-- const cfg = resolveConfig("default");- const cursor = { x: 50, y: 50, initialized: true };- patchPage(page as any, cfg, cursor as any);-- try {- await page.press("input#field", "Enter");- } catch (e) {- // May throw with mocks- }-- // Focus check should use isolated world (Runtime.evaluate with activeElement)- const focusCalls = stealthEvaluateCalls.filter(- expr => expr.includes("activeElement")- );- expect(focusCalls.length).toBeGreaterThan(0);- });-});---// =========================================================================-// Frame patching with stealth-// =========================================================================-describe("frame patching with stealth", () => {- it("child frames use stealth for clear() focus check", async () => {- const { patchPage } = await import("../src/human/index.js");-- const childFrame: any = {- click: vi.fn(async () => {}),- dblclick: vi.fn(async () => {}),- hover: vi.fn(async () => {}),- type: vi.fn(async () => {}),- fill: vi.fn(async () => {}),- check: vi.fn(async () => {}),- uncheck: vi.fn(async () => {}),- selectOption: vi.fn(async () => {}),- press: vi.fn(async () => {}),- clear: vi.fn(async () => {}),- dragAndDrop: vi.fn(async () => {}),- locator: vi.fn(() => ({- boundingBox: vi.fn(async () => ({ x: 0, y: 0, width: 100, height: 30 })),- })),- childFrames: vi.fn(() => []),- };-- const mainFrame = {- ...childFrame,- childFrames: vi.fn(() => [childFrame]),- };-- const page = buildMockPage({ mainFrameReturn: mainFrame });- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- patchPage(page as any, cfg, cursor as any);-- expect((childFrame as any)._humanPatched).toBe(true);- });-});---// =========================================================================-// Page-level: pressSequentially, tap, clear are patched-// =========================================================================-describe("page-level pressSequentially, tap, clear patches", () => {- it("page.pressSequentially is replaced after patchPage", async () => {- const { patchPage } = await import("../src/human/index.js");-- const page = buildMockPage();- const originalPressSeq = page.pressSequentially ?? (() => {});- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- patchPage(page as any, cfg, cursor as any);-- expect(typeof (page as any).pressSequentially).toBe("function");- expect((page as any).pressSequentially).not.toBe(originalPressSeq);- });-- it("page.tap is replaced after patchPage", async () => {- const { patchPage } = await import("../src/human/index.js");-- const page = buildMockPage();- const originalTap = page.tap ?? (() => {});- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- patchPage(page as any, cfg, cursor as any);-- expect(typeof (page as any).tap).toBe("function");- expect((page as any).tap).not.toBe(originalTap);- });-- it("page.clear is replaced after patchPage", async () => {- const { patchPage } = await import("../src/human/index.js");-- const page = buildMockPage();- const originalClear = page.clear ?? (() => {});- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- patchPage(page as any, cfg, cursor as any);-- expect(typeof (page as any).clear).toBe("function");- expect((page as any).clear).not.toBe(originalClear);- });-});---// =========================================================================-// Frame-level: pressSequentially, tap are patched-// =========================================================================-describe("frame-level pressSequentially, tap patches", () => {- it("child frame has pressSequentially patched", async () => {- const { patchPage } = await import("../src/human/index.js");-- const childFrame: any = {- click: vi.fn(async () => {}),- dblclick: vi.fn(async () => {}),- hover: vi.fn(async () => {}),- type: vi.fn(async () => {}),- fill: vi.fn(async () => {}),- check: vi.fn(async () => {}),- uncheck: vi.fn(async () => {}),- selectOption: vi.fn(async () => {}),- press: vi.fn(async () => {}),- pressSequentially: vi.fn(async () => {}),- tap: vi.fn(async () => {}),- clear: vi.fn(async () => {}),- dragAndDrop: vi.fn(async () => {}),- locator: vi.fn(() => ({- boundingBox: vi.fn(async () => ({ x: 0, y: 0, width: 100, height: 30 })),- })),- childFrames: vi.fn(() => []),- };-- const origPressSeq = childFrame.pressSequentially;- const origTap = childFrame.tap;-- const mainFrame = {- ...childFrame,- childFrames: vi.fn(() => [childFrame]),- };-- const page = buildMockPage({ mainFrameReturn: mainFrame });- const cfg = resolveConfig("default");- const cursor = { x: 0, y: 0, initialized: false };- patchPage(page as any, cfg, cursor as any);-- expect((childFrame as any)._humanPatched).toBe(true);- // pressSequentially and tap should be replaced with humanized versions- expect(childFrame.pressSequentially).not.toBe(origPressSeq);- expect(childFrame.tap).not.toBe(origTap);- expect(typeof childFrame.pressSequentially).toBe("function");- expect(typeof childFrame.tap).toBe("function");- });});@@ -1247,27 +808,28 @@ describeIfSlow("stealth browser: selector parity and target identity", () => {}, 60000);it.each([false, true])(- "rejects selector replacement after movement (force=%s)",+ "replacement during movement is re-resolved and reached with a fresh move (force=%s)",async (force) => {+ // A locator re-resolves like Playwright does; the press never lands on+ // the stale element or on whatever happens to be under the cursor.const { launch } = await import("../src/index.js");- const { ElementTargetChangedError } = await import("../src/human/actionability.js");const browser = await launch({ headless: true, humanize: true, humanConfig: fastHumanConfig });try {const page = await browser.newPage();await page.goto("https://example.com", { waitUntil: "domcontentloaded" });await page.evaluate(() => {document.body.innerHTML = `<button id="race" style="margin:180px;width:180px;height:60px">race</button>`;- (window as any).__replacementClicked = false;+ (window as any).__clicks = { original: 0, replacement: 0 };const original = document.querySelector("#race")!;+ original.addEventListener("click", () => (window as any).__clicks.original++);original.addEventListener("mousemove", () => {const replacement = original.cloneNode(true) as HTMLElement;- replacement.addEventListener("click", () => { (window as any).__replacementClicked = true; });+ replacement.addEventListener("click", () => (window as any).__clicks.replacement++);original.replaceWith(replacement);}, { once: true });});-- await expect(page.click("#race", { force })).rejects.toBeInstanceOf(ElementTargetChangedError);- expect(await page.evaluate(() => (window as any).__replacementClicked)).toBe(false);+ await page.click("#race", { force, timeout: 5000 });+ expect(await page.evaluate(() => (window as any).__clicks)).toEqual({ original: 0, replacement: 1 });} finally {await browser.close();}@@ -1276,10 +838,10 @@ describeIfSlow("stealth browser: selector parity and target identity", () => {);it.each([false, true])(- "rejects target removal after movement without clicking underneath (force=%s)",+ "target removed during movement times out without clicking underneath (force=%s)",async (force) => {const { launch } = await import("../src/index.js");- const { ElementNotAttachedError } = await import("../src/human/actionability.js");+ const { errors } = await import("playwright-core");const browser = await launch({ headless: true, humanize: true, humanConfig: fastHumanConfig });try {const page = await browser.newPage();@@ -1296,7 +858,7 @@ describeIfSlow("stealth browser: selector parity and target identity", () => {original.addEventListener("mousemove", () => original.remove(), { once: true });});- await expect(page.click("#race", { force })).rejects.toBeInstanceOf(ElementNotAttachedError);+ await expect(page.click("#race", { force, timeout: 1500 })).rejects.toBeInstanceOf(errors.TimeoutError);expect(await page.evaluate(() => (window as any).__underlyingClicks)).toBe(0);} finally {await browser.close();@@ -1411,7 +973,7 @@ describeIfSlow("stealth browser: full form no evaluate leak", () => {expect(evalLeaks.length).toBe(0);expect(untrusted.length).toBe(0);- await page.click('button[type="submit"]');+ await page.getByRole('button', { name: 'Login' }).click();await sleep(5000);const body = await page.locator('body').textContent();diff --git a/js/tests/stealthDom.test.ts b/js/tests/stealthDom.test.tsdeleted file mode 100644index 4dfa218..0000000--- a/js/tests/stealthDom.test.ts+++ /dev/null@@ -1,116 +0,0 @@-import { describe, it, expect } from 'vitest';-import { OK, NOT_FOUND, UNSUPPORTED, STALE, EVALUATION_FAILED, buildSnapshotJs, buildValidateJs, buildPointerJs, parseResult, evalParsed } from '../src/human/stealthDom.js';--type E = any;-const defaultRect = () => ({ x: 1, y: 2, width: 10, height: 10 });-function node(tag:string, text='', cls=''):E {- const e:any={tagName:tag.toUpperCase(),nodeType:1,childNodes:[],children:[],firstChild:null,parentElement:null,previousElementSibling:null,nextSibling:null,textContent:text,isConnected:true,disabled:false,readOnly:false,isContentEditable:false,type:'text',value:'',attrs:{},checked:false,style:{display:'block',visibility:'visible'},rect:defaultRect()};- if(text){const t:any={nodeType:3,nodeValue:text,textContent:text,nextSibling:null,rect:defaultRect()};e.childNodes.push(t);e.firstChild=t;}- e.getAttribute=(n:string)=>e.attrs[n]??null;e.hasAttribute=(n:string)=>n in e.attrs;e.contains=(x:E)=>x===e||e.children.some((c:E)=>c.contains(x));e.closest=()=>null;e.getRootNode=()=>e.parentElement?e.parentElement.getRootNode():doc;e.getBoundingClientRect=()=>e.rect;e.matches=(s:string)=>s==='*'||s.split('.').every((x,i)=>i?cls.split(' ').includes(x):!x||x===tag);return e;-}-let doc:any;-function append(p:E,c:E){const prev=p.childNodes.at(-1);if(prev)prev.nextSibling=c;c.nextSibling=null;c.parentElement=p;c.previousElementSibling=p.children.at(-1)??null;p.children.push(c);p.childNodes.push(c);p.firstChild=p.childNodes[0]??null;}-function wireOwner(n:E){n.ownerDocument=doc;for(const child of n.childNodes??[])wireOwner(child);}-function run(js:string, roots:E[], point?:E, active?:E, store:any={}){let selected:any=null;doc={children:roots,head:{contains:()=>false},getElementById:(id:string)=>{let hit:any=null;const walk=(n:any)=>{if(n.attrs&&n.attrs.id===id)hit=n;for(const c of n.children??[])walk(c);};for(const r of roots)walk(r);return hit;},activeElement:active??null,querySelectorAll:()=>[],elementFromPoint:()=>point??null,evaluate:()=>({snapshotLength:0,snapshotItem:()=>null}),createRange:()=>({selectNode:(n:any)=>{selected=n;},getBoundingClientRect:()=>selected?.rect??{x:0,y:0,width:0,height:0}})};for(const r of roots){r.getRootNode=()=>doc;wireOwner(r);}const f=new Function('document','XPathResult','getComputedStyle','globalThis','return '+js);return f(doc,{ORDERED_NODE_SNAPSHOT_TYPE:7},(e:E)=>e.style??{display:'block',visibility:'visible'},store);}--describe('protocol',()=>{it('strictly rejects malformed payloads and evaluator failures',async()=>{expect(parseResult({v:2,r:OK,targetId:1,gen:5})).toMatchObject({status:OK});for(const x of [null,{}, {v:1,r:OK,targetId:1,gen:5},{v:2,r:OK},{v:2,r:OK,targetId:1},{v:2,r:STALE,targetId:1.5,gen:5},{v:2,r:STALE,targetId:1,gen:1.5}])expect(parseResult(x)).toEqual({status:EVALUATION_FAILED});expect(parseResult({v:2,r:NOT_FOUND})).toEqual({status:NOT_FOUND});expect(parseResult({v:2,r:UNSUPPORTED})).toEqual({status:UNSUPPORTED});expect(await evalParsed({evaluate:async()=>{throw Error()}},'x')).toEqual({status:EVALUATION_FAILED});});});--describe('shipped resolver',()=>{it('unions only visible display:contents geometry, including nested content',()=>{const target=node('li','Hoy','target');target.style.display='contents';target.rect={x:0,y:0,width:0,height:0};target.childNodes[0].rect={x:5,y:6,width:25,height:10};const targetResult=run(buildSnapshotJs('.target'),[target]);expect(targetResult).toMatchObject({r:OK,visible:true,box:{x:5,y:6,width:25,height:10}});const union=node('div','','union');union.style.display='contents';union.rect={x:0,y:0,width:0,height:0};const left=node('span','left');left.rect={x:10,y:20,width:20,height:10};const right=node('span','right');right.rect={x:40,y:20,width:30,height:10};const nested=node('span','','nested');nested.style.display='contents';nested.rect={x:0,y:0,width:0,height:0};const nestedChild=node('span','nested');nestedChild.rect={x:75,y:20,width:25,height:10};append(nested,nestedChild);const hidden=node('span','hidden');hidden.style.visibility='hidden';hidden.rect={x:1000,y:1000,width:100,height:100};append(union,left);append(union,right);append(union,nested);append(union,hidden);expect(run(buildSnapshotJs('.union'),[union])).toMatchObject({r:OK,visible:true,box:{x:10,y:20,width:90,height:10}});const hiddenText=node('div','hidden text','hidden-text');hiddenText.style={display:'contents',visibility:'hidden'};hiddenText.rect={x:0,y:0,width:0,height:0};hiddenText.childNodes[0].rect={x:5,y:6,width:50,height:10};expect(run(buildSnapshotJs('.hidden-text'),[hiddenText])).toMatchObject({r:OK,visible:false,box:null});});it('executes descendant, child, adjacent, sibling, lists and structural has-text',()=>{const root=node('div');const a=node('span','one','a'), b=node('button','Save','b'), c=node('button','Other','c');append(root,a);append(root,b);append(root,c);for(const s of ['div button','div > button','.a + button','.a ~ button','.no, button:has-text("Save")'])expect(run(buildSnapshotJs(s),[root]).r).toBe(OK);});it('executes exact/lax/regex text and excludes script text (#512)',()=>{const r=node('div'), s=node('span',' Hello World '), script=node('script','secret');append(r,s);append(r,script);expect(run(buildSnapshotJs('text="Hello World"'),[r]).r).toBe(OK);expect(run(buildSnapshotJs('text=hello world'),[r]).r).toBe(OK);expect(run(buildSnapshotJs('text=/world/i'),[r]).r).toBe(OK);expect(run(buildSnapshotJs('text=secret'),[r]).r).toBe(NOT_FOUND);});it('executes native and ARIA state',()=>{const root=node('div'),disabled=node('button','','disabled'),ariaDisabled=node('button','','aria-disabled'),readonly=node('div','','readonly');disabled.attrs.disabled='';ariaDisabled.attrs.role='button';ariaDisabled.attrs['aria-disabled']='true';readonly.attrs.role='textbox';readonly.attrs['aria-readonly']='true';append(root,disabled);append(root,ariaDisabled);append(root,readonly);expect(run(buildSnapshotJs('.disabled'),[root]).enabled).toBe(false);expect(run(buildSnapshotJs('.aria-disabled'),[root]).enabled).toBe(false);expect(run(buildSnapshotJs('.readonly'),[root]).editable).toBe(false);});it('executes deep shadow ordering, focus, hit testing and stale validation',()=>{const host=node('div'), light=node('button','light'), shadow=node('button','shadow');append(host,light);const disabled=node('button');disabled.attrs.disabled='';append(host,disabled);host.shadowRoot={children:[shadow],elementFromPoint:()=>shadow,activeElement:shadow};shadow.getRootNode=()=>host.shadowRoot;shadow.parentElement=null;expect(run(buildSnapshotJs('button >> nth=2'),[host],host,host).focused).toBe(true);expect(run(buildSnapshotJs('button >> nth=1'),[host]).enabled).toBe(false);expect(run(buildSnapshotJs('button'),[host],host,host).focused).toBe(false);expect(run(buildPointerJs('button >> nth=2',1,2),[host],host).hit).toBe(true);const world:any={};const snap=run(buildSnapshotJs('button'),[host],host,host,world);expect(run(buildValidateJs('button',snap.targetId,snap.gen,1,2),[host],host,host,world).r).toBe(OK);expect(run(buildValidateJs('button',999,snap.gen,1,2),[host],host,host,world).r).toBe(STALE);expect(run(buildValidateJs('button',snap.targetId,snap.gen+1,1,2),[host],host,host,world).r).toBe(STALE);expect(run(buildValidateJs('button',snap.targetId,snap.gen,1,2),[host],host,host,{}).r).toBe(STALE);});});--describe('internal engines',()=>{- const id=(r:any)=>r.box?.x; // distinct rects identify WHICH element matched-- it('internal:attr i-flag is case-insensitive SUBSTRING on the raw value',()=>{- const root=node('div');- const p1=node('input');p1.attrs.placeholder='Your Email';p1.rect={x:11,y:0,width:5,height:5};- const t1=node('span');t1.attrs.title=' Go ';t1.rect={x:22,y:0,width:5,height:5};- append(root,p1);append(root,t1);- // 'mail' matches 'Your Email' -- substring, not equality- expect(id(run(buildSnapshotJs('internal:attr=[placeholder="mail"i]'),[root]))).toBe(11);- // raw value: no trim, no whitespace normalization- expect(run(buildSnapshotJs('internal:attr=[title="Go"s]'),[root]).r).toBe(NOT_FOUND);- expect(id(run(buildSnapshotJs('internal:attr=[title=" Go "s]'),[root]))).toBe(22);- expect(id(run(buildSnapshotJs('internal:attr=[title="go"i]'),[root]))).toBe(22);- });-- it('internal:testid is strict equality, never a prefix match',()=>{- const root=node('div');- const a=node('button');a.attrs['data-testid']='submit-button';a.rect={x:31,y:0,width:5,height:5};- const b=node('button');b.attrs['data-testid']='submit';b.rect={x:32,y:0,width:5,height:5};- append(root,a);append(root,b);- expect(id(run(buildSnapshotJs('internal:testid=[data-testid="submit"s]'),[root]))).toBe(32);- expect(run(buildSnapshotJs('internal:testid=[data-testid="sub"s]'),[root]).r).toBe(NOT_FOUND);- });-- it('internal:attr supports a regex value and rejects unsupported grammar',()=>{- const root=node('div');- const el=node('span');el.attrs.title='Go42';el.rect={x:41,y:0,width:5,height:5};- append(root,el);- expect(id(run(buildSnapshotJs('internal:attr=[title=/^Go\\d+$/]'),[root]))).toBe(41);- for(const bad of ['internal:attr=[title]','internal:attr=[title*="Go"]',- 'internal:attr=[title=Go]','internal:attr=title="Go"'])- expect(run(buildSnapshotJs(bad),[root]).r).toBe(UNSUPPORTED);- });-- it('internal:text exact is the full subtree, unlike the public text= engine',()=>{- const root=node('div');- const btn=node('button','Hello');btn.rect={x:51,y:0,width:5,height:5};- const span=node('span','World');span.rect={x:52,y:0,width:5,height:5};- append(btn,span);append(root,btn);- expect(id(run(buildSnapshotJs('internal:text="HelloWorld"s'),[root]))).toBe(51);- // the public engine compares immediate fragments, so it does NOT match- expect(run(buildSnapshotJs('text="HelloWorld"'),[root]).r).toBe(NOT_FOUND);- });-- it('internal:text keeps the smallest match via direct children only',()=>{- const root=node('div');- const gp=node('div','X');gp.rect={x:61,y:0,width:5,height:5};- const sect=node('section');sect.rect={x:62,y:0,width:5,height:5};- const deep=node('span','X');deep.rect={x:63,y:0,width:5,height:5};- append(sect,deep);append(gp,sect);append(root,gp);- // section's own text matches too, so the innermost element wins- expect(id(run(buildSnapshotJs('internal:text="X"s'),[root]))).toBe(63);- });-- it('internal:label resolves labelledby, then aria-label, then native labels',()=>{- const root=node('div');- const ref=node('span','Referenced');ref.attrs.id='lbref';ref.rect={x:71,y:0,width:5,height:5};- const byRef=node('input');byRef.attrs['aria-labelledby']='lbref';byRef.rect={x:72,y:0,width:5,height:5};- const fallback=node('input');fallback.attrs['aria-labelledby']='missing';- fallback.attrs['aria-label']='Fallback';fallback.rect={x:73,y:0,width:5,height:5};- const native=node('input');native.rect={x:74,y:0,width:5,height:5};- const lbl=node('label','Password');native.labels=[lbl];- const divLabel=node('div','x');divLabel.attrs['aria-label']='Div Label';divLabel.rect={x:75,y:0,width:5,height:5};- const hidden=node('input');hidden.type='hidden';hidden.rect={x:76,y:0,width:5,height:5};- hidden.labels=[node('label','HiddenLabel')];- for(const e of [ref,byRef,fallback,native,divLabel,hidden])append(root,e);- expect(id(run(buildSnapshotJs('internal:label="Referenced"i'),[root]))).toBe(72);- expect(id(run(buildSnapshotJs('internal:label="Fallback"i'),[root]))).toBe(73);- expect(id(run(buildSnapshotJs('internal:label="Password"i'),[root]))).toBe(74);- expect(id(run(buildSnapshotJs('internal:label="Div Label"i'),[root]))).toBe(75);- // a hidden input contributes no native label- expect(run(buildSnapshotJs('internal:label="HiddenLabel"i'),[root]).r).toBe(NOT_FOUND);- });-- it('public text= excludes a shadow host whose shadow content also matches',()=>{- // Regression: __elementText concatenates shadow text into the host, so the- // host matches too. contains() cannot see into a shadow root, so the old- // smallest-element filter kept the host and (being light DOM) returned it- // first. Playwright returns the shadow child.- const host=node('div','','host');host.rect={x:81,y:0,width:5,height:5};- const shadowChild=node('button','ShadowText');shadowChild.rect={x:82,y:0,width:5,height:5};- host.shadowRoot={children:[shadowChild],childNodes:[shadowChild],- elementFromPoint:()=>shadowChild,activeElement:null};- shadowChild.getRootNode=()=>host.shadowRoot;shadowChild.parentElement=null;- expect(id(run(buildSnapshotJs('text=ShadowText'),[host]))).toBe(82);- expect(id(run(buildSnapshotJs('internal:text="ShadowText"i'),[host]))).toBe(82);- });-- it('leaves role, chaining and single-quoted bodies unsupported',()=>{- const root=node('div','x');- for(const sel of ['internal:role=button[name="Go"i]','internal:has-text="Go"i',- 'internal:control=enter-frame','#a >> #b',- "internal:text='Go'"])- expect(run(buildSnapshotJs(sel),[root]).r).toBe(UNSUPPORTED);- });-});diff --git a/pyproject.toml b/pyproject.tomlindex 6f20b42..8c05183 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -49,7 +49,7 @@ classifiers = ["Topic :: Software Development :: Testing",]dependencies = [- "playwright>=1.40",+ "playwright>=1.53","httpx>=0.24","cryptography>=41.0", # verify Ed25519 signature on SHA256SUMS before trusting it]@@ -57,7 +57,7 @@ dependencies = [[project.optional-dependencies]geoip = ["geoip2>=4.0", "socksio>=1.0"] # socksio: SOCKS5 transport for httpxserve = ["aiohttp>=3.9", "websockets>=12.0"]-dev = ["pytest>=7.0", "pytest-asyncio>=0.23"]+dev = ["pytest>=7.0", "pytest-asyncio>=0.23", "pytest-timeout>=2.1"][project.scripts]cloakbrowser = "cloakbrowser.__main__:main"diff --git a/tests/test_humanize_engine.py b/tests/test_humanize_engine.pynew file mode 100644index 0000000..4cc22f8--- /dev/null+++ b/tests/test_humanize_engine.py@@ -0,0 +1,703 @@+"""Behaviour tests for the unified humanize engine (real browser, fast config).++These replace the old mock-based tests that asserted on internals of the+previous implementation (private helpers, call forwarding into Playwright).+Every test here drives the real CloakBrowser binary headless against a small+local page (served below; it records every input event the page observes)+with near-zero delays, so the whole file runs in well under a minute.+"""++from __future__ import annotations++import asyncio+import http.server+import socketserver+import threading+import time+from typing import Any++import pytest+from playwright.sync_api import Error, TimeoutError++# Fast, deterministic humanize settings: same code paths, no long sleeps, no+# random typos. Tests that need specific behaviour override per context/call.+FAST: dict[str, Any] = {+ "mistype_chance": 0.0,+ "field_switch_delay": (0, 0),+ "typing_delay": 5,+ "typing_delay_spread": 0,+ "typing_pause_chance": 0.0,+ "key_hold": (5, 5),+ "shift_down_delay": (5, 5),+ "shift_up_delay": (5, 5),+ "mouse_min_steps": 4,+ "mouse_max_steps": 4,+ "mouse_burst_pause": (0, 0),+ "mouse_overshoot_chance": 0.0,+ "click_aim_delay_input": (5, 5),+ "click_aim_delay_button": (5, 5),+ "click_hold_input": (20, 20),+ "click_hold_button": (20, 20),+ "idle_between_actions": False,+ "scroll_pause_fast": (5, 5),+ "scroll_pause_slow": (5, 5),+ "scroll_settle_delay": (50, 50),+ "scroll_pre_move_delay": (5, 5),+ "scroll_overshoot_chance": 0.0,+}++# Test page: recorder (window.__log), main-world probes (window.__mainWorldHits),+# inputs of every kind, a covered button, an off-screen input and an iframe.+INDEX_HTML = """<!doctype html>+<html>+<head>+<meta charset="utf-8">+<title>humanize fixture</title>+<script>+// Records DOM reads that only a main-world evaluate makes into window.__mainWorldHits.+(function () {+ const hits = [];+ window.__mainWorldHits = hits;+ const note = (probe, detail) => hits.push({ probe, detail: String(detail ?? '') });++ const origGetAttribute = Element.prototype.getAttribute;+ Element.prototype.getAttribute = function (name) {+ if (name === 'contenteditable') note('getAttribute(contenteditable)', this.id || this.tagName);+ return origGetAttribute.call(this, name);+ };++ const activeDesc = Object.getOwnPropertyDescriptor(Document.prototype, 'activeElement');+ Object.defineProperty(Document.prototype, 'activeElement', {+ configurable: true,+ get() {+ note('document.activeElement', '');+ return activeDesc.get.call(this);+ },+ });++ const origFromPoint = Document.prototype.elementFromPoint;+ Document.prototype.elementFromPoint = function (x, y) {+ note('elementFromPoint', x + ',' + y);+ return origFromPoint.call(this, x, y);+ };++ const origQS = Document.prototype.querySelector;+ Document.prototype.querySelector = function (sel) {+ note('document.querySelector', sel);+ return origQS.call(this, sel);+ };+})();+</script>+<script>+// Records every input event (capture phase) into window.__log.+(function () {+ const log = [];+ window.__log = log;+ window.__reset = () => { log.length = 0; };++ const TYPES = [+ 'pointerdown', 'pointerup', 'mousedown', 'mouseup', 'click', 'dblclick',+ 'contextmenu', 'auxclick', 'mousemove', 'keydown', 'keyup', 'beforeinput',+ 'input', 'wheel', 'focus',+ ];+ const idOf = (el) => {+ if (el === window) return 'window';+ if (!el || el === document) return 'document';+ return el.id || (el.tagName ? el.tagName.toLowerCase() : '?');+ };+ for (const type of TYPES) {+ document.addEventListener(type, (e) => {+ const rec = { t: type, ts: e.timeStamp, trusted: e.isTrusted, target: idOf(e.target) };+ if ('clientX' in e) { rec.x = e.clientX; rec.y = e.clientY; }+ if ('button' in e) rec.button = e.button;+ if ('detail' in e && type !== 'focus') rec.detail = e.detail;+ if ('key' in e) { rec.key = e.key; rec.code = e.code; }+ if ('shiftKey' in e) {+ rec.shift = e.shiftKey; rec.ctrl = e.ctrlKey; rec.meta = e.metaKey; rec.alt = e.altKey;+ }+ if ('inputType' in e) { rec.inputType = e.inputType; rec.data = e.data; }+ if (type === 'wheel') { rec.dx = e.deltaX; rec.dy = e.deltaY; }+ log.push(rec);+ }, true);+ }+ window.addEventListener('scroll', () => {+ log.push({ t: 'scroll', ts: performance.now(), sx: scrollX, sy: scrollY });+ }, true);++})();+</script>+<style>+ body { margin: 0; font: 14px sans-serif; }+ section { padding: 8px 12px; border-bottom: 1px solid #ddd; }+ input, select, button, textarea { font: inherit; margin: 2px 6px 2px 0; }+ button { min-width: 140px; min-height: 36px; }+ #neg { position: absolute; top: -600px; left: -600px; }+ .wrap { position: relative; display: inline-block; }+ .over { position: absolute; inset: 0; background: rgba(255,0,0,.3); }+</style>+</head>+<body>+<section id="text">+ <h4>Text inputs</h4>+ <input id="name" value="firstname">+ <input id="long" value="hello world">+ <!-- Masked field: the page strips anything that is not hex (card/IBAN/serial-style mask). -->+ <input id="hex" oninput="this.value=this.value.replace(/[^0-9a-f]/gi,'')">+ <textarea id="ta">old text</textarea>+</section>+<section id="special">+ <h4>Non-text inputs</h4>+ <input id="date" type="date">+ <input id="range" type="range" min="0" max="100" value="10">+ <input id="color" type="color" value="#000000">+</section>+<section id="focus">+ <h4>Focus targets</h4>+ <input id="fa" placeholder="A (focused first)">+ <input id="fb" placeholder="B (handle target)">+</section>+<section id="buttons">+ <h4>Buttons</h4>+ <button id="btn">Press me</button>+ <button class="dup" id="dup1">Duplicate</button>+ <button class="dup" id="dup2">Duplicate</button>+ <input id="chk" type="checkbox">+ <select id="sel"><option value="a">a</option><option value="b">b</option></select>+</section>+<section id="covered-sec">+ <h4>Covered button (transparent overlay on top)</h4>+ <span class="wrap"><button id="covered">covered</button><div class="over" id="over"></div></span>+</section>+<input id="neg" name="neg">+<canvas id="cv" width="200" height="40" style="border:1px solid #999"></canvas>+<section id="frames">+ <h4>Frame</h4>+ <iframe id="frame" name="f" src="frame.html" style="width:420px;height:200px"></iframe>+</section>+<div style="height:200px"></div>+</body>+</html>+"""++FRAME_HTML = """<!doctype html>+<html>+<head>+<meta charset="utf-8">+<script>+// Records DOM reads that only a main-world evaluate makes into window.__mainWorldHits.+(function () {+ const hits = [];+ window.__mainWorldHits = hits;+ const note = (probe, detail) => hits.push({ probe, detail: String(detail ?? '') });++ const origGetAttribute = Element.prototype.getAttribute;+ Element.prototype.getAttribute = function (name) {+ if (name === 'contenteditable') note('getAttribute(contenteditable)', this.id || this.tagName);+ return origGetAttribute.call(this, name);+ };++ const activeDesc = Object.getOwnPropertyDescriptor(Document.prototype, 'activeElement');+ Object.defineProperty(Document.prototype, 'activeElement', {+ configurable: true,+ get() {+ note('document.activeElement', '');+ return activeDesc.get.call(this);+ },+ });++ const origFromPoint = Document.prototype.elementFromPoint;+ Document.prototype.elementFromPoint = function (x, y) {+ note('elementFromPoint', x + ',' + y);+ return origFromPoint.call(this, x, y);+ };++ const origQS = Document.prototype.querySelector;+ Document.prototype.querySelector = function (sel) {+ note('document.querySelector', sel);+ return origQS.call(this, sel);+ };+})();+</script>+<script>+// Records every input event (capture phase) into window.__log.+(function () {+ const log = [];+ window.__log = log;+ window.__reset = () => { log.length = 0; };++ const TYPES = [+ 'pointerdown', 'pointerup', 'mousedown', 'mouseup', 'click', 'dblclick',+ 'contextmenu', 'auxclick', 'mousemove', 'keydown', 'keyup', 'beforeinput',+ 'input', 'wheel', 'focus',+ ];+ const idOf = (el) => {+ if (el === window) return 'window';+ if (!el || el === document) return 'document';+ return el.id || (el.tagName ? el.tagName.toLowerCase() : '?');+ };+ for (const type of TYPES) {+ document.addEventListener(type, (e) => {+ const rec = { t: type, ts: e.timeStamp, trusted: e.isTrusted, target: idOf(e.target) };+ if ('clientX' in e) { rec.x = e.clientX; rec.y = e.clientY; }+ if ('button' in e) rec.button = e.button;+ if ('detail' in e && type !== 'focus') rec.detail = e.detail;+ if ('key' in e) { rec.key = e.key; rec.code = e.code; }+ if ('shiftKey' in e) {+ rec.shift = e.shiftKey; rec.ctrl = e.ctrlKey; rec.meta = e.metaKey; rec.alt = e.altKey;+ }+ if ('inputType' in e) { rec.inputType = e.inputType; rec.data = e.data; }+ if (type === 'wheel') { rec.dx = e.deltaX; rec.dy = e.deltaY; }+ log.push(rec);+ }, true);+ }+ window.addEventListener('scroll', () => {+ log.push({ t: 'scroll', ts: performance.now(), sx: scrollX, sy: scrollY });+ }, true);++})();+</script>+<style>+ body { margin: 0; font: 14px sans-serif; }+ .wrap { position: relative; display: inline-block; }+ .over { position: absolute; inset: 0; background: rgba(255,0,0,.3); }+</style>+</head>+<body>+<input id="finput" value="old">+<span class="wrap"><button id="fcovered">covered</button><div class="over" id="fover"></div></span>+<div style="height:1200px"></div>+<button id="fbottom">bottom</button>+</body>+</html>+"""++_PAGES = {"/index.html": INDEX_HTML, "/frame.html": FRAME_HTML}+++class _Handler(http.server.BaseHTTPRequestHandler):+ def do_GET(self) -> None: # noqa: N802+ body = _PAGES.get(self.path.split("?")[0])+ self.send_response(200 if body else 404)+ self.send_header("content-type", "text/html; charset=utf-8")+ self.end_headers()+ if body:+ self.wfile.write(body.encode())++ def log_message(self, *args: Any) -> None: # pragma: no cover+ pass+++class SiteServer:+ """Serve the test pages on 127.0.0.1 with a random port (the iframe must be same-origin)."""++ def __init__(self) -> None:+ self._srv = socketserver.ThreadingTCPServer(("127.0.0.1", 0), _Handler)+ self._srv.daemon_threads = True+ self.url = f"http://127.0.0.1:{self._srv.server_address[1]}/"+ threading.Thread(target=self._srv.serve_forever, daemon=True).start()++ def close(self) -> None:+ self._srv.shutdown()+ self._srv.server_close()+++def events(target: Any, *types: str) -> list[dict]:+ """Recorded input events, optionally filtered by type."""+ log = target.evaluate("window.__log.slice()")+ return [e for e in log if not types or e["t"] in types]+++def reset(target: Any) -> None:+ target.evaluate("window.__reset(); window.__mainWorldHits.length = 0")+++def value(target: Any, selector: str) -> str:+ return target.evaluate(+ "s => { const e = document.querySelector(s);"+ " return e.isContentEditable ? e.textContent : e.value; }",+ selector,+ )++pytestmark = [pytest.mark.timeout(120), pytest.mark.real_browser]++[email protected](scope="module")+def site():+ srv = SiteServer()+ yield srv+ srv.close()++[email protected](scope="module")+def browser(site):+ from cloakbrowser import launch++ b = launch(headless=True, humanize=True, human_config=FAST)+ yield b+ b.close()+++def page(browser, site):+ p = browser.new_page()+ p.goto(site.url + "index.html")+ yield p+ p.close()+++def frame(p):+ f = p.frame(name="f")+ f.wait_for_load_state()+ return f+++# --- wiring ---------------------------------------------------------------++def test_page_is_humanized_and_keeps_compat_attributes(page):+ assert page._human_cfg.mistype_chance == 0.0+ assert page._human_cursor.initialized+ assert page._stealth_world.evaluate("1 + 1") == 2+ page._original.click("#btn") # raw Playwright still reachable+++def test_unknown_keyword_still_raises_type_error(page):+ with pytest.raises(TypeError):+ page.click("#btn", no_such_option=True)+++# --- pointer actions --------------------------------------------------------++def test_click_moves_along_a_curve_then_presses(page):+ reset(page)+ page.click("#btn")+ moves = events(page, "mousemove")+ clicks = [e["target"] for e in events(page, "click")]+ assert len(moves) >= 3 and clicks == ["btn"]+++def test_click_options(page):+ reset(page)+ page.click("#btn", button="right", modifiers=["Shift"])+ down = events(page, "mousedown")[-1]+ assert down["button"] == 2 and down["shift"] is True+ reset(page)+ page.click("#btn", click_count=2)+ assert len(events(page, "dblclick")) == 1+ reset(page)+ page.click("#btn", trial=True)+ assert events(page, "click") == []+++def test_hover_does_not_press(page):+ reset(page)+ page.hover("#btn")+ assert events(page, "mousedown") == [] and events(page, "mousemove")+++def test_hover_holds_modifiers_during_the_move(page):+ page.hover("#chk")+ reset(page)+ page.hover("#btn", modifiers=["Shift"])+ seq = events(page, "mousemove", "keydown", "keyup")+ moves = [i for i, e in enumerate(seq) if e["t"] == "mousemove"]+ assert moves and all(seq[i]["shift"] for i in moves)+ assert seq[0]["t"] == "keydown" and seq[-1]["t"] == "keyup"+ assert events(page, "mousedown") == []+++def test_dblclick_matches_a_real_double_click(page):+ reset(page)+ page.dblclick("#btn")+ seq = [(e["t"], e["detail"]) for e in events(page, "mousedown", "click", "dblclick")]+ assert seq == [("mousedown", 1), ("click", 1), ("mousedown", 2), ("click", 2), ("dblclick", 2)]+++def test_covered_element_times_out_with_reason(page):+ with pytest.raises(TimeoutError, match="intercepts pointer events"):+ page.click("#covered", timeout=1000)+++def test_strict_mode_violation(page):+ with pytest.raises(Error, match="strict mode violation"):+ page.locator(".dup").click(timeout=1000)+ page.locator(".dup").first.click() # explicit choice is fine+++def test_page_default_timeout_and_zero(page):+ page.set_default_timeout(500)+ t0 = time.monotonic()+ with pytest.raises(TimeoutError):+ page.click("#missing")+ assert time.monotonic() - t0 < 1.5+ page.click("#btn", timeout=0)+++def test_standard_locators(page):+ page.get_by_role("button", name="Press me").click()+ page.locator("#buttons").locator("#btn").click()+ page.locator("button").filter(has_text="Press me").click()+ page.click("#btn:visible")+++# --- keyboard ---------------------------------------------------------------++def test_fill_replaces_and_type_appends(page):+ page.fill("#name", "Shaho")+ assert value(page, "#name") == "Shaho"+ page.locator("#name").press_sequentially("!")+ assert value(page, "#name") == "Shaho!"+ page.locator("#name").clear()+ assert value(page, "#name") == ""+++def test_value_inputs_are_operated_like_a_person(page):+ """date/time editors are typed segment by segment, sliders clicked and+ nudged with arrows, dropdowns opened and moved with arrow keys. Every+ input/change event the page sees is trusted (no programmatic value)."""+ page.evaluate("""() => { window.__untrusted = 0;+ for (const t of ['input', 'change'])+ document.addEventListener(t, e => { if (!e.isTrusted) __untrusted++; }, true); }""")+ page.fill("#date", "2024-01-31")+ page.fill("#date", "1999-12-05")+ page.fill("#range", "80")+ assert page.select_option("#sel", "b") == ["b"]+ assert (value(page, "#date"), value(page, "#range"), value(page, "#sel")) == ("1999-12-05", "80", "b")+ assert page.evaluate("__untrusted") == 0+ with pytest.raises(Error, match="native colour picker"):+ page.fill("#color", "#ff0000")+ with pytest.raises(Error, match="cannot be filled"):+ page.fill("#chk", "x")+++def test_unreachable_element_is_not_focused_programmatically(page):+ """#neg sits at (-600, -600): no scroll can reach it, so a person could+ not click it. No hidden focus() -- a clear timeout instead."""+ with pytest.raises(TimeoutError, match="outside of the viewport"):+ page.fill("#neg", "x", timeout=1500)+ assert value(page, "#neg") == ""+++def test_press_focuses_target_first(page):+ page.focus("#fa")+ page.query_selector("#fb").press("x")+ assert (value(page, "#fa"), value(page, "#fb")) == ("", "x")+++def test_handle_sharing_its_box_with_a_child_acts_on_the_focusable_one(page):+ """A wrapper and its same-size child form one nested chain. The handle acts on+ the element a real click would focus (the focusable wrapper), not the child."""+ page.evaluate("""() => document.body.insertAdjacentHTML('beforeend',+ '<div id="wrap" tabindex="0" style="display:inline-block"><span id="inner"'+ + ' style="display:block;width:80px;height:20px">x</span></div>')""")+ page.evaluate("() => { window.__kd = []; document.addEventListener('keydown',"+ " e => __kd.push(e.target.id + ':' + e.key)); }")+ page.query_selector("#wrap").press("a")+ assert page.evaluate("() => __kd") == ["wrap:a"]+++def test_stale_handle_after_navigation_fails_fast(page, site):+ """A handle from a previous document raises "not attached" at once, like+ Playwright, instead of waiting out the timeout. A same-document navigation+ keeps the element, so its handle keeps working."""+ h = page.query_selector("#btn")+ h.click()+ page.evaluate("() => history.pushState({}, '', '#spa')")+ h.click()+ page.goto(site.url + "index.html?second")+ page.click("#chk")+ t = time.monotonic()+ with pytest.raises(Error, match="not attached"):+ h.click(timeout=10000)+ assert time.monotonic() - t < 5+++def test_handle_click_on_same_box_nesting(page):+ """Common markup where parent and child share a border box: a block link+ wrapping a same-size image, and a list item filled by its link."""+ page.evaluate("""() => { document.body.insertAdjacentHTML('beforeend',+ '<a id="card" href="#c" style="display:block;width:60px"><img id="thumb" width="60" height="60"'+ + ' style="display:block" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"></a>'+ + '<ul style="width:200px;padding:0;margin:0;list-style:none"><li id="li"><a id="nav" href="#n"'+ + ' style="display:block">nav</a></li></ul>');+ window.__clicks = []; document.addEventListener('click', e => { __clicks.push(e.target.id); e.preventDefault(); }); }""")+ page.query_selector("#card").click()+ page.query_selector("#nav").click()+ page.query_selector("#li").click()+ assert page.evaluate("() => __clicks") == ["thumb", "nav", "nav"]+++def test_handle_sharing_its_box_with_an_unrelated_element_raises(page):+ """Two unrelated elements stacked on the same box cannot be told apart by the+ box alone: the handle action raises instead of guessing."""+ page.evaluate("""() => document.body.insertAdjacentHTML('beforeend',+ '<div style="position:relative;width:80px;height:20px">'+ + '<span id="s1" style="position:absolute;inset:0"></span>'+ + '<span id="s2" style="position:absolute;inset:0"></span></div>')""")+ with pytest.raises(Error, match="shares its box"):+ page.query_selector("#s1").click()+++def test_press_and_type_reach_non_focusable_targets(page):+ """A <canvas> (or a game area with document-level key handlers) does not take+ focus. press()/type() click it and send the keys anyway, like Playwright."""+ page.evaluate("() => { window.__keys = []; document.addEventListener('keydown', e => __keys.push(e.key)); }")+ page.press("#cv", "ArrowUp")+ page.type("#cv", "ab")+ assert page.evaluate("__keys") == ["ArrowUp", "a", "b"]+++def test_press_delay_is_forwarded(page):+ reset(page)+ page.press("#name", "a", delay=150)+ ev = events(page, "keydown", "keyup")+ assert ev[-1]["ts"] - ev[-2]["ts"] >= 120+++def test_mistypes_are_corrected_and_skip_masked_fields(browser, site):+ p = browser.new_page()+ p.goto(site.url + "index.html")+ try:+ p.fill("#name", "Hello", human_config={"mistype_chance": 1.0})+ assert value(p, "#name") == "Hello"+ p.fill("#hex", "ab", human_config={"mistype_chance": 1.0})+ assert value(p, "#hex") == "ab"+ reset(p)+ p.locator("#name").press_sequentially("AB", human_config={"mistype_chance": 1.0})+ assert all(e["shift"] for e in events(p, "keydown")+ if len(e["key"]) == 1 and e["key"].isupper())+ finally:+ p.close()+++def test_scroll_overshoot_wheels_back(page):+ page.set_viewport_size({"width": 800, "height": 300})+ reset(page)+ page.click("#chk", human_config={"scroll_overshoot_chance": 1.0, "scroll_overshoot_px": (120, 120)})+ dys = [e["dy"] for e in events(page, "wheel")]+ assert any(d > 0 for d in dys) and any(d < 0 for d in dys), dys+ assert [e["target"] for e in events(page, "click")] == ["chk"]+ reset(page)+ page.evaluate("scrollTo(0, 0)")+ page.click("#chk", human_config={"scroll_overshoot_chance": 0.0})+ assert all(e["dy"] > 0 for e in events(page, "wheel"))+++def test_per_call_human_config(page):+ reset(page)+ page.click("#btn", human_config={"click_hold_button": (300, 300)})+ assert events(page, "mouseup")[-1]["ts"] - events(page, "mousedown")[-1]["ts"] >= 250+++# --- checkable / select -----------------------------------------------------++def test_check_uncheck_and_select(page):+ page.check("#chk")+ assert page.is_checked("#chk")+ page.locator("#chk").uncheck()+ assert not page.is_checked("#chk")+ page.query_selector("#chk").set_checked(True)+ assert page.is_checked("#chk")+ assert page.select_option("#sel", index=1) == ["b"]+++# --- frames and handles ------------------------------------------------------++def test_frame_actions(page):+ f = frame(page)+ f.fill("#finput", "in frame")+ assert value(f, "#finput") == "in frame"+ page.frame_locator("#frame").locator("#finput").press_sequentially("!")+ assert value(f, "#finput") == "in frame!"+ reset(f)+ f.click("#fbottom", timeout=5000)+ assert [e["target"] for e in events(f, "click")] == ["fbottom"]+ # The frame was scrolled to its bottom above; wheeling back up takes time.+ with pytest.raises(TimeoutError, match="intercepts pointer events"):+ f.click("#fcovered", timeout=4000)+++def test_element_handle_actions(page):+ h = page.query_selector("#name")+ h.fill("handle")+ assert value(page, "#name") == "handle"+ reset(page)+ page.query_selector("#btn").click()+ assert [e["target"] for e in events(page, "click")] == ["btn"]+++def test_mouse_api(page):+ reset(page)+ page.mouse.move(50, 50, steps=1)+ assert len(events(page, "mousemove")) == 1+ box = page.locator("#btn").bounding_box()+ reset(page)+ page.mouse.click(box["x"] + 5, box["y"] + 5, button="right")+ assert [e["button"] for e in events(page, "mousedown")] == [2]+++# --- separate browser processes -----------------------------------------------+# Sync Playwright allows one driver per thread, and the module browser above+# owns this one; these scenarios each run in a fresh interpreter.++_PRELUDE = """+import asyncio, sys+sys.path.insert(0, {root!r})+from tests.test_humanize_engine import FAST+URL = {url!r}+"""++_SCENARIOS = {+ "non_humanized_untouched": """+from cloakbrowser import launch+b = launch(headless=True)+p = b.new_page(); p.goto(URL + "index.html")+assert not hasattr(p, "_original")+p.click("#btn"); p.fill("#name", "plain")+assert p.evaluate("document.querySelector('#name').value") == "plain"+b.close()+""",+ "select_all_follows_persona": """+from cloakbrowser import launch+b = launch(headless=True, humanize=True, human_config=FAST, args=["--fingerprint-platform=macos"])+p = b.new_page(); p.goto(URL + "index.html")+assert p.evaluate("navigator.platform") == "MacIntel"+p.fill("#name", "Mac")+assert p.evaluate("document.querySelector('#name').value") == "Mac"+b.close()+""",+ "async_api": """+from cloakbrowser import launch_async+from playwright.async_api import Error+async def main():+ b = await launch_async(headless=True, humanize=True, human_config=FAST)+ try:+ p = await b.new_page(); await p.goto(URL + "index.html")+ await p.get_by_role("button", name="Press me").click()+ await p.fill("#name", "async")+ await p.frame_locator("#frame").locator("#finput").fill("af")+ await (await p.query_selector("#chk")).check()+ try:+ await p.locator(".dup").click(timeout=1000)+ raise AssertionError("strict mode not enforced")+ except Error as e:+ assert "strict mode violation" in str(e)+ assert await p.evaluate("document.querySelector('#name').value") == "async"+ assert await p.frame(name="f").evaluate("document.querySelector('#finput').value") == "af"+ assert await p.is_checked("#chk")+ finally:+ await b.close()+asyncio.run(main())+""",+}++[email protected]("name", list(_SCENARIOS))+def test_in_fresh_process(site, name):+ import os+ import subprocess+ import sys++ root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+ code = _PRELUDE.format(root=root, url=site.url) + _SCENARIOS[name]+ res = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=100)+ assert res.returncode == 0, res.stderr[-2000:]diff --git a/tests/test_humanize_unit.mjs b/tests/test_humanize_unit.mjsindex fa67dd6..e7f86f0 100644--- a/tests/test_humanize_unit.mjs+++ b/tests/test_humanize_unit.mjs@@ -290,10 +290,13 @@ await test('page has _original after launch', async () => {await test('page.click is humanized', async () => {const browser = await launch({ headless: true, humanize: true });const page = await browser.newPage();- const clickStr = page.click.toString();- if (!clickStr.includes('ensureCursorInit') && !clickStr.includes('humanClickFn') && !clickStr.includes('scrollToElement')) {- throw new Error('page.click does not appear humanized');- }+ await page.evaluate(() => {+ document.body.innerHTML = '<button id="b" style="margin:200px">b</button>';+ window.__moves = 0; document.addEventListener('mousemove', () => window.__moves++, true);+ });+ await page.click('#b');+ const moves = await page.evaluate(() => window.__moves);+ if (moves < 3) throw new Error(`page.click does not appear humanized (${moves} mousemove events)`);await browser.close();});@@ -331,21 +334,11 @@ await test('press skips click when element already focused', async () => {await delay(300);// Record mouse moves before pressing Enter- const movesBefore = [];- const origMove = page._humanOriginals.mouseMove;- let moveCount = 0;- page._humanOriginals.mouseMove = async (x, y, opts) => {- moveCount++;- return origMove(x, y, opts);- };+ await page.evaluate(() => { window.__moves = 0; document.addEventListener('mousemove', () => window.__moves++, true); });- // Press Enter — element is already focused, should NOT trigger mouse move- const movesAtStart = moveCount;+ // Press — element is already focused, should NOT trigger a mouse pathawait page.locator('#searchInput').press('a');- const movesUsed = moveCount - movesAtStart;-- // Restore- page._humanOriginals.mouseMove = origMove;+ const movesUsed = await page.evaluate(() => window.__moves);// If focus check works, should be 0 moves (just keyboard press)if (movesUsed > 0) {@@ -394,8 +387,7 @@ await test('frame has all methods patched', async () => {const mainFrame = page.mainFrame();const expected = ['click', 'dblclick', 'hover', 'type', 'fill',- 'check', 'uncheck', 'selectOption', 'press',- 'clear', 'dragAndDrop'];+ 'check', 'uncheck', 'selectOption', 'press', 'dragAndDrop'];const missing = [];for (const method of expected) {if (typeof mainFrame[method] !== 'function') {@@ -407,9 +399,9 @@ await test('frame has all methods patched', async () => {}// Verify they are patched (not original Playwright bindings)- if (!mainFrame._humanPatched) {- throw new Error('mainFrame._humanPatched flag not set');- }+ const marker = Symbol.for('cloakbrowser.humanized');+ const unpatched = expected.filter((m) => !mainFrame[m][marker]);+ if (unpatched.length) throw new Error(`Frame methods not humanized: ${unpatched.join(', ')}`);await browser.close();});diff --git a/tests/test_humanize_unit.py b/tests/test_humanize_unit.pyindex 55e0b28..7e9cd7d 100644--- a/tests/test_humanize_unit.py+++ b/tests/test_humanize_unit.py@@ -16,8 +16,6 @@ import asyncioimport pytestfrom unittest.mock import MagicMock-from cloakbrowser.human.stealth_dom import PROTOCOL_VERSION-def _mock_el_evaluate(is_input=False):"""Mock evaluate that returns is_input for tagName checks and {hit: True} for pointer events."""@@ -42,11 +40,6 @@ def _async_mock_el_evaluate(is_input=False):# Helper: ensure Locator class is patched before mock tests# =========================================================================-def _ensure_locator_patched():- import cloakbrowser.human as h- h._locator_sync_patched = False- h._patch_locator_class_sync()-# =========================================================================# Helper: fake RawMouse for Bézier tests@@ -191,667 +184,31 @@ class TestBezierMath:# 3. Async compatibility# =========================================================================-class TestAsyncCompat:- def test_async_modules_import(self):- from cloakbrowser.human.mouse_async import async_human_move- from cloakbrowser.human.keyboard_async import async_human_type- from cloakbrowser.human.scroll_async import async_scroll_to_element- assert callable(async_human_move)- assert callable(async_human_type)- assert callable(async_scroll_to_element)-- def test_async_locator_patch(self):- import cloakbrowser.human as h- h._locator_async_patched = False- h._patch_locator_class_async()- assert h._locator_async_patched- from playwright.async_api._generated import Locator as AsyncLocator- assert 'humanized' in AsyncLocator.fill.__name__-- def test_async_sleep_is_coroutine(self):- from cloakbrowser.human.config import async_sleep_ms- import asyncio- assert asyncio.iscoroutinefunction(async_sleep_ms)-- def test_patch_page_async_does_not_crash(self):- """patch_page_async must not raise NameError for missing definitions."""- import cloakbrowser.human as h- from cloakbrowser.human import _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock, AsyncMock-- cfg = resolve_config("default", {"idle_between_actions": False})- cursor = _CursorState()- cursor.initialized = True- cursor.x = 100- cursor.y = 100-- page = MagicMock()- page.click = AsyncMock()- page.dblclick = AsyncMock()- page.hover = AsyncMock()- page.type = AsyncMock()- page.fill = AsyncMock()- page.goto = AsyncMock()- page.check = AsyncMock()- page.uncheck = AsyncMock()- page.select_option = AsyncMock()- page.press = AsyncMock()- page.is_checked = AsyncMock(return_value=False)- page.viewport_size = {"width": 1280, "height": 720}- page.evaluate = AsyncMock(return_value={"hit": True})- page.context.new_cdp_session = AsyncMock(side_effect=Exception("no cdp"))- page.mouse = MagicMock()- page.mouse.move = AsyncMock()- page.mouse.click = AsyncMock()- page.mouse.wheel = AsyncMock()- page.mouse.down = AsyncMock()- page.mouse.up = AsyncMock()- page.keyboard = MagicMock()- page.keyboard.type = AsyncMock()- page.keyboard.down = AsyncMock()- page.keyboard.up = AsyncMock()- page.keyboard.press = AsyncMock()- page.keyboard.insert_text = AsyncMock()- page.query_selector = AsyncMock(return_value=None)- page.query_selector_all = AsyncMock(return_value=[])- page.wait_for_selector = AsyncMock(return_value=None)- page.main_frame = MagicMock()- page.main_frame.return_value = MagicMock()- page.main_frame.return_value.child_frames = MagicMock(return_value=[])- page.main_frame.child_frames = MagicMock(return_value=[])-- h.patch_page_async(page, cfg, cursor)-- assert hasattr(page, '_original')- assert page.select_option != AsyncMock-# =========================================================================# 4. Focus check — press / clear / pressSequentially# =========================================================================-class TestFocusCheck:- def test_press_skips_click_when_focused(self):- _ensure_locator_patched()- from unittest.mock import MagicMock, patch as mock_patch- page = MagicMock()- page._original = MagicMock()- page._human_cfg = MagicMock()- page._human_cfg.idle_between_actions = False-- with mock_patch("cloakbrowser.human._is_selector_focused", return_value=True):- from playwright.sync_api._generated import Locator- loc = MagicMock()- loc.page = page- loc._impl_obj = MagicMock()- loc._impl_obj._selector = "#test"- loc._impl_obj._frame = None- Locator.press(loc, "Enter", delay=300)-- page.click.assert_not_called()- page.keyboard.press.assert_called_once_with("Enter", delay=300)-- def test_press_clicks_when_not_focused(self):- _ensure_locator_patched()- from unittest.mock import MagicMock, patch as mock_patch- page = MagicMock()- page._original = MagicMock()- page._human_cfg = MagicMock()- page._human_cfg.idle_between_actions = False-- with mock_patch("cloakbrowser.human._is_selector_focused", return_value=False):- from playwright.sync_api._generated import Locator- loc = MagicMock()- loc.page = page- loc._impl_obj = MagicMock()- loc._impl_obj._selector = "#test"- Locator.press(loc, "Enter")-- page.click.assert_called_with("#test")---class TestPressDelayForwarding:- @pytest.mark.asyncio- async def test_async_locator_press_forwards_delay(self):- import cloakbrowser.human as h- from playwright.async_api._generated import Locator as AsyncLocator- from unittest.mock import AsyncMock, patch-- h._locator_async_patched = False- h._patch_locator_class_async()-- page = MagicMock()- page._original = MagicMock()- page._human_cfg = MagicMock()- page._human_cfg.idle_between_actions = False- page.keyboard.press = AsyncMock()- locator = MagicMock()- locator.page = page- locator._impl_obj = MagicMock()- locator._impl_obj._selector = "#field"- locator._impl_obj._frame = None-- with patch.object(h, "_async_is_selector_focused", new=AsyncMock(return_value=True)), \- patch.object(h, "async_sleep_ms", new=AsyncMock()):- await AsyncLocator.press(locator, "Control+V", delay=300)-- page.keyboard.press.assert_awaited_once_with("Control+V", delay=300)-- @staticmethod- def _config_and_cursor():- from cloakbrowser.human import _CursorState- from cloakbrowser.human.config import resolve_config-- cfg = resolve_config("default", {"idle_between_actions": False})- cursor = _CursorState()- cursor.initialized = True- return cfg, cursor-- @staticmethod- def _sync_originals():- originals = MagicMock()- originals.keyboard_press = MagicMock()- return originals-- @staticmethod- def _sync_frame(focused=True):- frame = MagicMock()- frame._human_patched = False- locator = MagicMock()- locator.first.evaluate = MagicMock(return_value=focused)- frame.locator.return_value = locator- return frame-- def test_page_press_forwards_delay(self):- import cloakbrowser.human as h- from unittest.mock import patch-- cfg, cursor = self._config_and_cursor()- page = MagicMock()- page.mouse = MagicMock()- page.keyboard = MagicMock()- original_press = page.keyboard.press- page.context.new_cdp_session.side_effect = RuntimeError("no cdp")- page.main_frame = self._sync_frame()- page.main_frame.child_frames = []-- with patch.object(h, "ensure_actionable"), \- patch.object(h, "_is_selector_focused", return_value=True), \- patch.object(h, "sleep_ms"):- h.patch_page(page, cfg, cursor)- page.press("#field", "Control+V", delay=300)-- original_press.assert_called_once_with("Control+V", delay=300)-- def test_frame_press_forwards_delay(self):- import cloakbrowser.human as h- from unittest.mock import patch-- cfg, cursor = self._config_and_cursor()- originals = self._sync_originals()- frame = self._sync_frame()- page = MagicMock()- page._stealth_world = None-- with patch.object(h, "sleep_ms"):- h._patch_single_frame_sync(- frame, page, cfg, cursor, MagicMock(), MagicMock(), originals- )- frame.press("#field", "Control+V", delay=300)-- originals.keyboard_press.assert_called_once_with("Control+V", delay=300)-- def test_element_handle_press_forwards_delay(self):- import cloakbrowser.human as h- from unittest.mock import patch-- cfg, cursor = self._config_and_cursor()- originals = self._sync_originals()- element = MagicMock()- element._human_patched = False-- with patch.object(h, "sleep_ms"):- h._patch_single_element_handle_sync(- element, MagicMock(), cfg, cursor, MagicMock(), MagicMock(),- originals, None, None,- )- element.press("Control+V", delay=300)-- originals.keyboard_press.assert_called_once_with("Control+V", delay=300)-- @pytest.mark.asyncio- async def test_async_page_press_forwards_delay(self):- import cloakbrowser.human as h- from unittest.mock import AsyncMock, patch-- cfg, cursor = self._config_and_cursor()- page = MagicMock()- page.mouse = MagicMock()- page.keyboard = MagicMock()- page.keyboard.press = AsyncMock()- original_press = page.keyboard.press- page.context.new_cdp_session = AsyncMock(side_effect=RuntimeError("no cdp"))- page.main_frame = MagicMock()- page.main_frame._human_patched = True- page.main_frame.child_frames = []-- with patch.object(h, "async_ensure_actionable", new=AsyncMock()), \- patch.object(h, "_async_is_selector_focused", new=AsyncMock(return_value=True)), \- patch.object(h, "async_sleep_ms", new=AsyncMock()):- h.patch_page_async(page, cfg, cursor)- await page.press("#field", "Control+V", delay=300)-- original_press.assert_awaited_once_with("Control+V", delay=300)-- @pytest.mark.asyncio- async def test_async_frame_press_forwards_delay(self):- import cloakbrowser.human as h- from unittest.mock import AsyncMock, patch-- cfg, cursor = self._config_and_cursor()- originals = MagicMock()- originals.keyboard_press = AsyncMock()- frame = MagicMock()- frame._human_patched = False- locator = MagicMock()- locator.first.evaluate = AsyncMock(return_value=True)- frame.locator.return_value = locator- page = MagicMock()- page._stealth_world = None-- with patch.object(h, "async_sleep_ms", new=AsyncMock()):- h._patch_single_frame_async(- frame, page, cfg, cursor, MagicMock(), MagicMock(), originals- )- await frame.press("#field", "Control+V", delay=300)-- originals.keyboard_press.assert_awaited_once_with("Control+V", delay=300)-- @pytest.mark.asyncio- async def test_async_element_handle_press_forwards_delay(self):- import cloakbrowser.human as h- from unittest.mock import AsyncMock, patch-- cfg, cursor = self._config_and_cursor()- originals = MagicMock()- originals.keyboard_press = AsyncMock()- element = MagicMock()- element._human_patched = False-- with patch.object(h, "async_sleep_ms", new=AsyncMock()):- h._patch_single_element_handle_async(- element, MagicMock(), cfg, cursor, MagicMock(), MagicMock(),- originals, None, [None],- )- await element.press("Control+V", delay=300)-- originals.keyboard_press.assert_awaited_once_with("Control+V", delay=300)-# =========================================================================# 5. check/uncheck idle# =========================================================================-class TestCheckUncheckIdle:- def test_check_calls_idle_when_enabled(self):- _ensure_locator_patched()- from unittest.mock import MagicMock, patch as mock_patch- from cloakbrowser.human.config import resolve_config- cfg = resolve_config("default", {"idle_between_actions": True, "idle_between_duration": (50, 100)})-- page = MagicMock()- page._original = MagicMock()- page._original.mouse_move = MagicMock()- page._human_cfg = cfg- page._stealth_world = _FakeWorld({"r": "ok", "checked": False})-- idle_called = {"n": 0}- def fake_idle(*a, **kw):- idle_called["n"] += 1-- from playwright.sync_api._generated import Locator- loc = MagicMock()- loc.page = page- loc._impl_obj = MagicMock()- loc._impl_obj._selector = "#checkbox"- loc.is_checked = MagicMock(return_value=False)-- with mock_patch("cloakbrowser.human.human_idle", fake_idle):- Locator.check(loc)-- assert idle_called["n"] >= 1-- def test_uncheck_calls_idle_when_enabled(self):- _ensure_locator_patched()- from unittest.mock import MagicMock, patch as mock_patch- from cloakbrowser.human.config import resolve_config- cfg = resolve_config("default", {"idle_between_actions": True, "idle_between_duration": (50, 100)})-- page = MagicMock()- page._original = MagicMock()- page._original.mouse_move = MagicMock()- page._human_cfg = cfg- page._stealth_world = _FakeWorld({"r": "ok", "checked": True})-- idle_called = {"n": 0}- def fake_idle(*a, **kw):- idle_called["n"] += 1-- from playwright.sync_api._generated import Locator- loc = MagicMock()- loc.page = page- loc._impl_obj = MagicMock()- loc._impl_obj._selector = "#checkbox"- loc.is_checked = MagicMock(return_value=True)-- with mock_patch("cloakbrowser.human.human_idle", fake_idle):- Locator.uncheck(loc)-- assert idle_called["n"] >= 1-# =========================================================================# 6. Frame patching completeness# =========================================================================-class TestFramePatching:- def test_all_11_methods_patched(self):- from cloakbrowser.human import _patch_single_frame_sync, _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", None)- cursor = _CursorState()- page = MagicMock()- page._original = MagicMock()- frame = MagicMock()- frame._human_patched = False-- _patch_single_frame_sync(frame, page, cfg, cursor, MagicMock(), MagicMock(), page._original)-- expected = ['click', 'dblclick', 'hover', 'type', 'fill',- 'check', 'uncheck', 'select_option', 'press',- 'clear', 'drag_and_drop']- for method in expected:- fn = getattr(frame, method)- assert not isinstance(fn, MagicMock), f"frame.{method} was not patched"-- def test_sync_dynamically_attached_frame_patched_once(self):- from cloakbrowser.human import _patch_frames_sync, _CursorState- from cloakbrowser.human.config import resolve_config-- page = MagicMock()- page._human_frame_listener_attached = False- page._original_main_frame = True- page._stealth_world = None- main_frame = MagicMock()- main_frame._human_patched = True- main_frame.child_frames = []- page.main_frame = main_frame-- cfg = resolve_config("default", None)- raw_mouse = MagicMock()- raw_keyboard = MagicMock()- originals = MagicMock()- _patch_frames_sync(- page, cfg, _CursorState(), raw_mouse, raw_keyboard, originals,- )- _patch_frames_sync(- page, cfg, _CursorState(), raw_mouse, raw_keyboard, originals,- )-- page.on.assert_called_once()- event_name, handler = page.on.call_args.args- assert event_name == "frameattached"-- attached_frame = MagicMock()- attached_frame._human_patched = False- handler(attached_frame)- patched_click = attached_frame.click- handler(attached_frame)-- assert attached_frame._human_patched is True- assert attached_frame.click is patched_click-- def test_async_dynamically_attached_frame_patched_once(self):- from cloakbrowser.human import _patch_frames_async, _CursorState- from cloakbrowser.human.config import resolve_config-- page = MagicMock()- page._human_frame_listener_attached = False- page._original_main_frame = True- page._stealth_world = None- page._cdp_session_holder = [None]- main_frame = MagicMock()- main_frame._human_patched = True- main_frame.child_frames = []- page.main_frame = main_frame-- cfg = resolve_config("default", None)- raw_mouse = MagicMock()- raw_keyboard = MagicMock()- originals = MagicMock()- _patch_frames_async(- page, cfg, _CursorState(), raw_mouse, raw_keyboard, originals,- )- _patch_frames_async(- page, cfg, _CursorState(), raw_mouse, raw_keyboard, originals,- )-- page.on.assert_called_once()- event_name, handler = page.on.call_args.args- assert event_name == "frameattached"-- attached_frame = MagicMock()- attached_frame._human_patched = False- handler(attached_frame)- patched_click = attached_frame.click- handler(attached_frame)-- assert attached_frame._human_patched is True- assert attached_frame.click is patched_click-# =========================================================================# 6b. iframe humanize routing (#428)# =========================================================================-def _make_frame_for_routing(is_input=False, box=None):- """A MagicMock frame whose locator resolves to a real bounding box."""- from cloakbrowser.human import _patch_single_frame_sync, _CursorState- from cloakbrowser.human.config import resolve_config- cfg = resolve_config("default", None)- cursor = _CursorState()- page = MagicMock()- page._original = MagicMock()- page._stealth_world = None # skip CDP path- frame = MagicMock()- frame._human_patched = False- loc_first = frame.locator.return_value.first- loc_first.bounding_box.return_value = box if box is not None else {- "x": 10.0, "y": 10.0, "width": 40.0, "height": 20.0}- loc_first.evaluate.return_value = is_input- loc_first.is_checked.return_value = False- orig_click = frame.click # capture pre-patch- _patch_single_frame_sync(frame, page, cfg, cursor, MagicMock(), MagicMock(), MagicMock())- return frame, page, orig_click---class TestFrameHumanizedRouting:- def test_frame_click_resolves_in_frame_not_page(self):- from unittest.mock import patch as mock_patch- frame, page, _ = _make_frame_for_routing()- with mock_patch("cloakbrowser.human.human_move") as mv, \- mock_patch("cloakbrowser.human.human_click") as clk:- frame.click("#btn")- # resolved through the frame's own locator, moved + clicked the real mouse,- # and NEVER re-dispatched to page.click (the #428 bug)- frame.locator.assert_any_call("#btn")- assert mv.called and clk.called- page.click.assert_not_called()-- def test_frame_click_falls_back_to_native_when_no_box(self):- from unittest.mock import patch as mock_patch- frame, page, orig_click = _make_frame_for_routing(box=False) # bounding_box -> falsy- with mock_patch("cloakbrowser.human.human_move") as mv, \- mock_patch("cloakbrowser.human.human_click") as clk:- frame.click("#btn")- assert not mv.called and not clk.called- orig_click.assert_called_once() # native frame.click used- page.click.assert_not_called()---def _make_locator_for_routing(frame_kind):- """Build a MagicMock locator + page.frames for _route_target testing.-- frame_kind: 'main' | 'patched_sub' | 'unpatched_sub'- Returns (loc, page, child_frame).- """- _ensure_locator_patched()- page = MagicMock()- page._original = MagicMock()- main = MagicMock()- child = MagicMock()- child._human_patched = (frame_kind == "patched_sub")- page.main_frame = main- page.frames = [main, child]- loc = MagicMock()- loc.page = page- loc._impl_obj._selector = "#btn"- if frame_kind == "main":- loc._impl_obj._frame = main._impl_obj- else:- loc._impl_obj._frame = child._impl_obj- return loc, page, child---class TestLocatorSubframeRouting:- def test_subframe_locator_routes_to_owning_frame(self):- from playwright.sync_api._generated import Locator- loc, page, child = _make_locator_for_routing("patched_sub")- Locator.click(loc)- child.click.assert_called_once()- assert child.click.call_args[0][0] == "#btn"- page.click.assert_not_called()-- def test_mainframe_locator_routes_to_page(self):- from playwright.sync_api._generated import Locator- loc, page, child = _make_locator_for_routing("main")- Locator.click(loc)- page.click.assert_called_once()- assert page.click.call_args[0][0] == "#btn"- child.click.assert_not_called()-- def test_unpatched_subframe_falls_back_to_native(self):- from playwright.sync_api._generated import Locator- loc, page, child = _make_locator_for_routing("unpatched_sub")- # native Locator.click is invoked on the mock; neither humanized path runs- Locator.click(loc)- child.click.assert_not_called()- page.click.assert_not_called()---class TestLocatorSubframeRoutingAsync:- @pytest.mark.asyncio- async def test_async_subframe_locator_routes_to_owning_frame(self):- import cloakbrowser.human as h- from unittest.mock import AsyncMock- h._locator_async_patched = False- h._patch_locator_class_async()- from playwright.async_api._generated import Locator as AsyncLocator-- page = MagicMock()- page._original = MagicMock()- main = MagicMock()- child = MagicMock()- child._human_patched = True- child.click = AsyncMock()- page.main_frame = main- page.frames = [main, child]- loc = MagicMock()- loc.page = page- loc._impl_obj._selector = "#btn"- loc._impl_obj._frame = child._impl_obj-- await AsyncLocator.click(loc)- child.click.assert_awaited_once()- assert child.click.call_args[0][0] == "#btn"---class TestFrameClickArgContract:- """#428 guard: _frame_click must call human_click(raw, is_input, cfg) in order.- The routing tests mock human_click, so a swap would slip through."""-- def test_frame_click_passes_is_input_bool_and_cfg(self):- from unittest.mock import patch as mock_patch- from cloakbrowser.human.config import HumanConfig- frame, page, _ = _make_frame_for_routing(is_input=False) # button- with mock_patch("cloakbrowser.human.human_move"), \- mock_patch("cloakbrowser.human.human_click") as clk:- frame.click("#btn")- args = clk.call_args[0]- assert isinstance(args[1], bool) and args[1] is False # is_input- assert isinstance(args[2], HumanConfig) # cfg-- def test_frame_click_marks_is_input_true_for_input(self):- from unittest.mock import patch as mock_patch- frame, page, _ = _make_frame_for_routing(is_input=True)- with mock_patch("cloakbrowser.human.human_move"), \- mock_patch("cloakbrowser.human.human_click") as clk:- frame.click("#inp")- assert clk.call_args[0][1] is True---class TestFrameFillFocus:- def test_frame_fill_clicks_before_typing(self):- from unittest.mock import patch as mock_patch- frame, page, _ = _make_frame_for_routing(is_input=True)- with mock_patch("cloakbrowser.human.human_move"), \- mock_patch("cloakbrowser.human.human_click"), \- mock_patch("cloakbrowser.human.human_type") as htype:- frame.fill("#inp", "hello")- assert htype.called and htype.call_args[0][2] == "hello"-- def test_frame_fill_falls_back_when_type_raises(self):- from unittest.mock import patch as mock_patch- frame, page, _ = _make_frame_for_routing(is_input=True)- with mock_patch("cloakbrowser.human.human_move"), \- mock_patch("cloakbrowser.human.human_click"), \- mock_patch("cloakbrowser.human.human_type", side_effect=RuntimeError("boom")):- frame.fill("#inp", "hello") # must not raise — native fallback-# =========================================================================# 7. drag_to safety# =========================================================================-class TestDragToSafety:- def test_handles_missing_original(self):- _ensure_locator_patched()- from playwright.sync_api._generated import Locator- from unittest.mock import MagicMock-- page = MagicMock()- page._original = None-- source_loc = MagicMock()- source_loc.page = page- source_loc._impl_obj = MagicMock()- source_loc._impl_obj._selector = "#src"- source_loc.bounding_box = MagicMock(return_value={"x": 10, "y": 10, "width": 50, "height": 50})-- target_loc = MagicMock()- target_loc.page = page- target_loc._impl_obj = MagicMock()- target_loc._impl_obj._selector = "#tgt"- target_loc.bounding_box = MagicMock(return_value={"x": 200, "y": 200, "width": 50, "height": 50})-- try:- Locator.drag_to(source_loc, target_loc)- except AttributeError:- pytest.fail("drag_to crashed without page._original")-# =========================================================================# 8. Page config persistence@@ -899,19 +256,6 @@ class TestMistypeConfig:# 10. Select-all platform detection# =========================================================================-class TestSelectAllPlatform:- def test_select_all_constant_exists(self):- from cloakbrowser.human import _SELECT_ALL- assert _SELECT_ALL in ("Meta+a", "Control+a")-- def test_select_all_matches_platform(self):- import sys- from cloakbrowser.human import _SELECT_ALL- if sys.platform == "darwin":- assert _SELECT_ALL == "Meta+a"- else:- assert _SELECT_ALL == "Control+a"-# =========================================================================# 11. Non-ASCII keyboard input@@ -1012,28 +356,6 @@ class TestNonAsciiKeyboard:human_type(page, raw, "Тест кириллицы", cfg)-class TestNonAsciiKeyboardAsync:- @pytest.mark.asyncio- async def test_async_cyrillic_uses_insert_text(self):- from cloakbrowser.human.keyboard_async import async_human_type- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock, AsyncMock-- cfg = resolve_config("default", {"mistype_chance": 0})- page = MagicMock()- raw = MagicMock()-- inserted = []- raw.down = AsyncMock()- raw.up = AsyncMock()- raw.insert_text = AsyncMock(side_effect=lambda t: inserted.append(t))-- await async_human_type(page, raw, "Привет", cfg)-- assert "".join(inserted) == "Привет"---# =========================================================================# SLOW TESTS — require browser (skipped in CI unless pytest -m slow)# =========================================================================@@ -1177,8 +499,9 @@ class TestBrowserIframeHumanize:}""")frame = event.valueframe.wait_for_load_state("domcontentloaded")- assert getattr(frame, "_human_patched", False)+ frame.evaluate("window.__moves = 0; addEventListener('mousemove', () => __moves++)")frame.click("#btn", timeout=5000)+ assert frame.evaluate("__moves") > 0, "frame click was not preceded by mouse movement"assert frame.locator("#btn").text_content() == "CLICKED"finally:browser.close()@@ -1231,8 +554,9 @@ class TestBrowserIframeHumanizeAsync:}""")frame = await event.valueawait frame.wait_for_load_state("domcontentloaded")- assert getattr(frame, "_human_patched", False)+ await frame.evaluate("window.__moves = 0; addEventListener('mousemove', () => __moves++)")await frame.click("#btn", timeout=5000)+ assert await frame.evaluate("__moves") > 0, "frame click was not preceded by mouse movement"assert await frame.locator("#btn").text_content() == "CLICKED"finally:await browser.close()@@ -1280,47 +604,6 @@ class TestBrowserHorizontalScroll:await browser.close()-class TestBrowserPatching:- def test_page_has_original(self):- from cloakbrowser import launch- browser = launch(headless=False, humanize=True)- page = browser.new_page()- assert hasattr(page, '_original')- assert hasattr(page, '_human_cfg')- browser.close()-- def test_locator_methods_patched(self):- from cloakbrowser import launch- browser = launch(headless=False, humanize=True)- page = browser.new_page()- from playwright.sync_api._generated import Locator- methods = ['fill', 'click', 'type', 'dblclick', 'hover', 'check', 'uncheck',- 'set_checked', 'select_option', 'press', 'press_sequentially',- 'tap', 'drag_to', 'clear']- for method in methods:- fn = getattr(Locator, method)- assert 'humanized' in fn.__name__, f"{method} not patched"- browser.close()-- def test_non_humanized_page_normal(self):- from playwright.sync_api import sync_playwright- with sync_playwright() as p:- browser = p.chromium.launch(headless=True)- page = browser.new_page()- assert not hasattr(page, '_original')- browser.close()-- def test_page_human_cfg_persists(self):- from cloakbrowser import launch- browser = launch(headless=False, humanize=True)- page = browser.new_page()- assert page._human_cfg is not None- assert hasattr(page._human_cfg, 'idle_between_actions')- assert hasattr(page._human_cfg, 'mistype_chance')- browser.close()--@pytest.mark.slowclass TestBrowserBotDetection:PROXY = None@@ -1394,496 +677,11 @@ class TestAsyncEndToEnd:# 12. ElementHandle patching — SYNC# =========================================================================-class TestElementHandlePatchingSync:- """Test that ElementHandle objects returned by query_selector etc. are humanized."""-- def test_patch_single_element_handle_marks_patched(self):- from cloakbrowser.human import _patch_single_element_handle_sync, _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", None)- cursor = _CursorState()- cursor.initialized = True- cursor.x = 100- cursor.y = 100- page = MagicMock()- page._original = MagicMock()- el = MagicMock()- el._human_patched = False- el.bounding_box = MagicMock(return_value={"x": 50, "y": 50, "width": 100, "height": 30})- el.evaluate = _mock_el_evaluate(is_input=True)- el.is_checked = MagicMock(return_value=False)- el.query_selector = MagicMock(return_value=None)- el.query_selector_all = MagicMock(return_value=[])- el.wait_for_selector = MagicMock(return_value=None)-- raw_mouse = MagicMock()- raw_keyboard = MagicMock()-- _patch_single_element_handle_sync(- el, page, cfg, cursor, raw_mouse, raw_keyboard, page._original, None, None- )-- assert el._human_patched is True-- def test_element_handle_click_calls_human_move(self):- from cloakbrowser.human import _patch_single_element_handle_sync, _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", {"idle_between_actions": False})- cursor = _CursorState()- cursor.initialized = True- cursor.x = 100- cursor.y = 100- page = MagicMock()- page._original = MagicMock()-- el = MagicMock()- el._human_patched = False- el.bounding_box = MagicMock(return_value={"x": 200, "y": 200, "width": 100, "height": 30})- el.evaluate = _mock_el_evaluate(is_input=False)- el.is_checked = MagicMock(return_value=False)- el.query_selector = MagicMock(return_value=None)- el.query_selector_all = MagicMock(return_value=[])- el.wait_for_selector = MagicMock(return_value=None)-- raw_mouse = MagicMock()- raw_mouse.move = MagicMock()- raw_mouse.down = MagicMock()- raw_mouse.up = MagicMock()- raw_mouse.wheel = MagicMock()- raw_keyboard = MagicMock()-- _patch_single_element_handle_sync(- el, page, cfg, cursor, raw_mouse, raw_keyboard, page._original, None, None- )-- # Call the patched click- el.click()-- # Should call raw_mouse.move (Bezier path) and then down/up- assert raw_mouse.move.called- assert raw_mouse.down.called- assert raw_mouse.up.called-- def test_element_handle_hover_moves_cursor_without_click(self):- from cloakbrowser.human import _patch_single_element_handle_sync, _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", {"idle_between_actions": False})- cursor = _CursorState()- cursor.initialized = True- cursor.x = 50- cursor.y = 50- page = MagicMock()- page._original = MagicMock()-- el = MagicMock()- el._human_patched = False- el.bounding_box = MagicMock(return_value={"x": 200, "y": 200, "width": 100, "height": 30})- el.evaluate = _mock_el_evaluate(is_input=False)- el.is_checked = MagicMock(return_value=False)- el.query_selector = MagicMock(return_value=None)- el.query_selector_all = MagicMock(return_value=[])- el.wait_for_selector = MagicMock(return_value=None)-- raw_mouse = MagicMock()- raw_mouse.move = MagicMock()- raw_mouse.down = MagicMock()- raw_mouse.up = MagicMock()- raw_mouse.wheel = MagicMock()- raw_keyboard = MagicMock()-- _patch_single_element_handle_sync(- el, page, cfg, cursor, raw_mouse, raw_keyboard, page._original, None, None- )-- el.hover()-- # Move should be called, but NOT down/up (hover, not click)- assert raw_mouse.move.called- assert not raw_mouse.down.called-- def test_element_handle_type_calls_human_type(self):- from cloakbrowser.human import _patch_single_element_handle_sync, _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", {"idle_between_actions": False, "mistype_chance": 0})- cursor = _CursorState()- cursor.initialized = True- cursor.x = 50- cursor.y = 50- page = MagicMock()- originals = MagicMock()- page._original = originals-- el = MagicMock()- el._human_patched = False- el.bounding_box = MagicMock(return_value={"x": 200, "y": 200, "width": 100, "height": 30})- el.evaluate = _mock_el_evaluate(is_input=True) # is input- el.is_checked = MagicMock(return_value=False)- el.query_selector = MagicMock(return_value=None)- el.query_selector_all = MagicMock(return_value=[])- el.wait_for_selector = MagicMock(return_value=None)-- raw_mouse = MagicMock()- raw_mouse.move = MagicMock()- raw_mouse.down = MagicMock()- raw_mouse.up = MagicMock()- raw_mouse.wheel = MagicMock()- raw_keyboard = MagicMock()- raw_keyboard.down = MagicMock()- raw_keyboard.up = MagicMock()- raw_keyboard.insert_text = MagicMock()-- _patch_single_element_handle_sync(- el, page, cfg, cursor, raw_mouse, raw_keyboard, originals, None, None- )-- el.type("hello")-- # Mouse moved + clicked (to focus), then keyboard used- assert raw_mouse.move.called- assert raw_mouse.down.called # click to focus the input- # Keyboard events should have fired (down/up for ASCII chars)- assert raw_keyboard.down.called or raw_keyboard.insert_text.called-- def test_element_handle_fill_clears_and_types(self):- from cloakbrowser.human import _patch_single_element_handle_sync, _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", {"idle_between_actions": False, "mistype_chance": 0})- cursor = _CursorState()- cursor.initialized = True- cursor.x = 50- cursor.y = 50- page = MagicMock()- originals = MagicMock()- page._original = originals-- pressed_keys = []- originals.keyboard_press = MagicMock(side_effect=lambda k: pressed_keys.append(k))-- el = MagicMock()- el._human_patched = False- el.bounding_box = MagicMock(return_value={"x": 200, "y": 200, "width": 100, "height": 30})- el.evaluate = _mock_el_evaluate(is_input=True)- el.is_checked = MagicMock(return_value=False)- el.query_selector = MagicMock(return_value=None)- el.query_selector_all = MagicMock(return_value=[])- el.wait_for_selector = MagicMock(return_value=None)-- raw_mouse = MagicMock()- raw_mouse.move = MagicMock()- raw_mouse.down = MagicMock()- raw_mouse.up = MagicMock()- raw_mouse.wheel = MagicMock()- raw_keyboard = MagicMock()- raw_keyboard.down = MagicMock()- raw_keyboard.up = MagicMock()- raw_keyboard.insert_text = MagicMock()-- _patch_single_element_handle_sync(- el, page, cfg, cursor, raw_mouse, raw_keyboard, originals, None, None- )-- el.fill("replaced")-- # Should have pressed Select-All and Backspace to clear- import sys- expected_select = "Meta+a" if sys.platform == "darwin" else "Control+a"- assert expected_select in pressed_keys- assert "Backspace" in pressed_keys-- def test_element_handle_no_double_patching(self):- from cloakbrowser.human import _patch_single_element_handle_sync, _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", None)- cursor = _CursorState()- page = MagicMock()- page._original = MagicMock()- el = MagicMock()- el._human_patched = False- el.query_selector = MagicMock(return_value=None)- el.query_selector_all = MagicMock(return_value=[])- el.wait_for_selector = MagicMock(return_value=None)-- _patch_single_element_handle_sync(- el, page, cfg, cursor, MagicMock(), MagicMock(), page._original, None, None- )-- # Save patched click- first_click = el.click-- # Try to patch again- _patch_single_element_handle_sync(- el, page, cfg, cursor, MagicMock(), MagicMock(), page._original, None, None- )-- # Should be the same — no double wrap- assert el.click is first_click-- def test_nested_query_selector_returns_patched_handle(self):- from cloakbrowser.human import _patch_single_element_handle_sync, _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", None)- cursor = _CursorState()- page = MagicMock()- page._original = MagicMock()-- child = MagicMock()- child._human_patched = False- child.bounding_box = MagicMock(return_value={"x": 10, "y": 10, "width": 50, "height": 30})- child.evaluate = MagicMock(return_value=False)- child.is_checked = MagicMock(return_value=False)- child.query_selector = MagicMock(return_value=None)- child.query_selector_all = MagicMock(return_value=[])- child.wait_for_selector = MagicMock(return_value=None)-- el = MagicMock()- el._human_patched = False- el.bounding_box = MagicMock(return_value={"x": 50, "y": 50, "width": 100, "height": 30})- el.evaluate = _mock_el_evaluate(is_input=False)- el.is_checked = MagicMock(return_value=False)- el.query_selector = MagicMock(return_value=child)- el.query_selector_all = MagicMock(return_value=[])- el.wait_for_selector = MagicMock(return_value=None)-- _patch_single_element_handle_sync(- el, page, cfg, cursor, MagicMock(), MagicMock(), page._original, None, None- )-- result = el.query_selector("span")- assert result._human_patched is True-- def test_page_query_selector_patched(self):- from cloakbrowser.human import _patch_page_element_handles_sync, _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", None)- cursor = _CursorState()-- el = MagicMock()- el._human_patched = False- el.bounding_box = MagicMock(return_value={"x": 50, "y": 50, "width": 100, "height": 30})- el.evaluate = _mock_el_evaluate(is_input=False)- el.is_checked = MagicMock(return_value=False)- el.query_selector = MagicMock(return_value=None)- el.query_selector_all = MagicMock(return_value=[])- el.wait_for_selector = MagicMock(return_value=None)-- page = MagicMock()- page._original = MagicMock()- page.query_selector = MagicMock(return_value=el)- page.query_selector_all = MagicMock(return_value=[el])- page.wait_for_selector = MagicMock(return_value=el)-- _patch_page_element_handles_sync(- page, cfg, cursor, MagicMock(), MagicMock(), page._original, None, None- )-- result = page.query_selector("#test")- assert result._human_patched is True-- def test_page_query_selector_all_patches_all(self):- from cloakbrowser.human import _patch_page_element_handles_sync, _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", None)- cursor = _CursorState()-- def make_el():- e = MagicMock()- e._human_patched = False- e.bounding_box = MagicMock(return_value={"x": 10, "y": 10, "width": 50, "height": 30})- e.evaluate = MagicMock(return_value=False)- e.is_checked = MagicMock(return_value=False)- e.query_selector = MagicMock(return_value=None)- e.query_selector_all = MagicMock(return_value=[])- e.wait_for_selector = MagicMock(return_value=None)- return e-- el1, el2, el3 = make_el(), make_el(), make_el()-- page = MagicMock()- page._original = MagicMock()- page.query_selector = MagicMock(return_value=None)- page.query_selector_all = MagicMock(return_value=[el1, el2, el3])- page.wait_for_selector = MagicMock(return_value=None)-- _patch_page_element_handles_sync(- page, cfg, cursor, MagicMock(), MagicMock(), page._original, None, None- )-- results = page.query_selector_all("div")- for r in results:- assert r._human_patched is True-- def test_wait_for_selector_patched(self):- from cloakbrowser.human import _patch_page_element_handles_sync, _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", None)- cursor = _CursorState()-- el = MagicMock()- el._human_patched = False- el.bounding_box = MagicMock(return_value={"x": 50, "y": 50, "width": 100, "height": 30})- el.evaluate = _mock_el_evaluate(is_input=False)- el.is_checked = MagicMock(return_value=False)- el.query_selector = MagicMock(return_value=None)- el.query_selector_all = MagicMock(return_value=[])- el.wait_for_selector = MagicMock(return_value=None)-- page = MagicMock()- page._original = MagicMock()- page.query_selector = MagicMock(return_value=None)- page.query_selector_all = MagicMock(return_value=[])- page.wait_for_selector = MagicMock(return_value=el)-- _patch_page_element_handles_sync(- page, cfg, cursor, MagicMock(), MagicMock(), page._original, None, None- )-- result = page.wait_for_selector("#test")- assert result._human_patched is True-- def test_element_handle_all_methods_patched(self):- """Verify all expected interaction methods are replaced."""- from cloakbrowser.human import _patch_single_element_handle_sync, _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", None)- cursor = _CursorState()- page = MagicMock()- page._original = MagicMock()-- el = MagicMock()- el._human_patched = False- el.bounding_box = MagicMock(return_value={"x": 50, "y": 50, "width": 100, "height": 30})- el.evaluate = _mock_el_evaluate(is_input=False)- el.is_checked = MagicMock(return_value=False)- el.query_selector = MagicMock(return_value=None)- el.query_selector_all = MagicMock(return_value=[])- el.wait_for_selector = MagicMock(return_value=None)- el.set_checked = MagicMock() # ensure it exists-- _patch_single_element_handle_sync(- el, page, cfg, cursor, MagicMock(), MagicMock(), page._original, None, None- )-- expected_methods = ['click', 'dblclick', 'hover', 'type', 'fill', 'press',- 'select_option', 'check', 'uncheck', 'set_checked',- 'tap', 'focus', 'query_selector', 'query_selector_all',- 'wait_for_selector']- for method in expected_methods:- fn = getattr(el, method)- assert not isinstance(fn, MagicMock), f"el.{method} was not patched"-# =========================================================================# 13. ElementHandle patching — ASYNC# =========================================================================-class TestElementHandlePatchingAsync:- @pytest.mark.asyncio- async def test_async_element_handle_click(self):- from cloakbrowser.human import _patch_single_element_handle_async, _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock, AsyncMock-- cfg = resolve_config("default", {"idle_between_actions": False})- cursor = _CursorState()- cursor.initialized = True- cursor.x = 100- cursor.y = 100-- page = MagicMock()- originals = MagicMock()- originals.mouse_move = AsyncMock()- page._original = originals-- el = MagicMock()- el._human_patched = False- el.bounding_box = AsyncMock(return_value={"x": 200, "y": 200, "width": 100, "height": 30})- el.evaluate = _async_mock_el_evaluate(is_input=False)- el.is_checked = AsyncMock(return_value=False)- el.wait_for_element_state = AsyncMock()- el.query_selector = AsyncMock(return_value=None)- el.query_selector_all = AsyncMock(return_value=[])- el.wait_for_selector = AsyncMock(return_value=None)-- raw_mouse = MagicMock()- raw_mouse.move = AsyncMock()- raw_mouse.down = AsyncMock()- raw_mouse.up = AsyncMock()- raw_mouse.wheel = AsyncMock()- raw_keyboard = MagicMock()- raw_keyboard.down = AsyncMock()- raw_keyboard.up = AsyncMock()- raw_keyboard.insert_text = AsyncMock()-- stealth = MagicMock()- stealth.get_cdp_session = AsyncMock(return_value=None)-- _patch_single_element_handle_async(- el, page, cfg, cursor, raw_mouse, raw_keyboard, originals, stealth, [None]- )-- await el.click()-- assert raw_mouse.move.called- assert raw_mouse.down.called- assert raw_mouse.up.called-- @pytest.mark.asyncio- async def test_async_page_query_selector_patched(self):- from cloakbrowser.human import _patch_page_element_handles_async, _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock, AsyncMock-- cfg = resolve_config("default", None)- cursor = _CursorState()-- el = MagicMock()- el._human_patched = False- el.bounding_box = AsyncMock(return_value={"x": 50, "y": 50, "width": 100, "height": 30})- el.evaluate = _async_mock_el_evaluate(is_input=False)- el.is_checked = AsyncMock(return_value=False)- el.wait_for_element_state = AsyncMock()- el.query_selector = AsyncMock(return_value=None)- el.query_selector_all = AsyncMock(return_value=[])- el.wait_for_selector = AsyncMock(return_value=None)-- page = MagicMock()- page._original = MagicMock()- page.query_selector = AsyncMock(return_value=el)- page.query_selector_all = AsyncMock(return_value=[el])- page.wait_for_selector = AsyncMock(return_value=el)-- stealth = MagicMock()- stealth.get_cdp_session = AsyncMock(return_value=None)-- _patch_page_element_handles_async(- page, cfg, cursor, MagicMock(), MagicMock(), page._original, stealth, [None]- )-- result = await page.query_selector("#test")- assert result._human_patched is True-# =========================================================================# 14. SLOW: Browser ElementHandle end-to-end@@ -1901,7 +699,6 @@ class TestBrowserElementHandle:el = page.query_selector('#searchInput')assert el is not None- assert getattr(el, '_human_patched', False), "ElementHandle not patched"t0 = time.time()el.click()@@ -1951,18 +748,23 @@ class TestBrowserElementHandle:browser.close()def test_query_selector_all_returns_patched(self):- """page.query_selector_all() returns all handles patched."""+ """page.query_selector_all() handles are humanized: clicks move the mouse first."""from cloakbrowser import launchbrowser = launch(headless=False, humanize=True)- page = browser.new_page()- page.goto('https://the-internet.herokuapp.com/checkboxes', wait_until='domcontentloaded')- time.sleep(1)-- els = page.query_selector_all('input[type="checkbox"]')- assert len(els) >= 2- for el in els:- assert getattr(el, '_human_patched', False), "ElementHandle not patched"- browser.close()+ try:+ page = browser.new_page()+ page.evaluate("""() => {+ document.body.innerHTML = '<input type="checkbox" id="a"><input type="checkbox" id="b">';+ window.__moves = 0; addEventListener('mousemove', () => __moves++);+ }""")+ els = page.query_selector_all('input[type="checkbox"]')+ assert len(els) == 2+ for el in els:+ el.click()+ assert page.evaluate("__moves") > 0, "handle clicks were not preceded by mouse movement"+ assert page.evaluate("[a.checked, b.checked]") == [True, True]+ finally:+ browser.close()def test_query_selector_hover_humanized(self):"""el.hover() should move cursor with human Bezier curve."""@@ -1993,7 +795,6 @@ class TestAsyncElementHandle:el = await page.query_selector('#searchInput')assert el is not None- assert getattr(el, '_human_patched', False), "Async ElementHandle not patched"t0 = time.time()await el.click()@@ -2007,1068 +808,26 @@ class TestAsyncElementHandle:# 15. Per-call timeout forwarding (issue #137)# =========================================================================-class TestPerCallTimeoutForwarding:- """Per-call deadlines must reach isolated-world geometry polling."""-- def test_scroll_to_element_forwards_timeout(self):- from cloakbrowser.human import scroll as scroll_module- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock, patch-- cfg = resolve_config("default", None)- page = MagicMock()- page.viewport_size = {"width": 1280, "height": 720}- raw = MagicMock()- box = {"x": 100, "y": 200, "width": 50, "height": 30}-- with patch.object(scroll_module, "_get_element_box", return_value=box) as get_box:- scroll_module.scroll_to_element(page, raw, "#x", 0, 0, cfg, timeout=7500)-- get_box.assert_called_with(page, "#x", 7500)-- def test_page_click_forwards_timeout_kwarg(self):- """page.click(selector, timeout=...) reaches scroll_to_element.-- Patches scroll_to_element module-side via monkey-patching the- cloakbrowser.human module attribute used by patch_page.- """- import cloakbrowser.human as h- from cloakbrowser.human import _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock, patch-- cfg = resolve_config("default", {"idle_between_actions": False})- cursor = _CursorState()- cursor.initialized = True- cursor.x = 100- cursor.y = 100-- # Build a minimal page mock- page = MagicMock()- page.click = MagicMock()- page.dblclick = MagicMock()- page.hover = MagicMock()- page.type = MagicMock()- page.fill = MagicMock()- page.goto = MagicMock()- page.is_checked = MagicMock(return_value=False)- page.viewport_size = {"width": 1280, "height": 720}- page.evaluate = MagicMock(return_value={"hit": True})- page.context.new_cdp_session = MagicMock(side_effect=Exception("no cdp"))- page.mouse = MagicMock()- page.keyboard = MagicMock()- page.query_selector = MagicMock(return_value=None)- page.query_selector_all = MagicMock(return_value=[])- page.wait_for_selector = MagicMock(return_value=None)- page.main_frame = MagicMock()- page.main_frame.child_frames = []-- captured = {}- def fake_scroll(page_arg, raw, selector, cx, cy, cfg_arg, timeout=30000):- captured["timeout"] = timeout- return ({"x": 100, "y": 100, "width": 50, "height": 30}, cx, cy, False)-- with patch.object(h, "scroll_to_element", side_effect=fake_scroll), \- patch.object(h, "ensure_actionable"), \- patch.object(h, "_is_input_element", return_value=False), \- patch.object(h, "check_pointer_events"):- h.patch_page(page, cfg, cursor)- page.click("#slow-button", timeout=5000)-- assert 4900 <= captured.get("timeout", 0) <= 5000, f"expected ~5000, got {captured}"-# =========================================================================# 16. Per-call human_config override (typing speed customization)# =========================================================================-class TestPerCallHumanConfigOverride:- """page.type('#email', text, human_config={'typing_delay': 30}) lets users- override typing speed (and any other HumanConfig field) on a per-call- basis without re-patching the page."""-- def test_merge_config_creates_new_instance(self):- from cloakbrowser.human.config import resolve_config, merge_config-- base = resolve_config("default", None)- merged = merge_config(base, {"typing_delay": 30})-- assert merged.typing_delay == 30- assert base.typing_delay != 30 # not mutated- # Non-overridden fields are preserved- assert merged.mouse_min_steps == base.mouse_min_steps-- def test_merge_config_none_returns_base(self):- from cloakbrowser.human.config import resolve_config, merge_config-- base = resolve_config("default", None)- merged = merge_config(base, None)- assert merged is base-- def test_merge_config_ignores_unknown_keys(self):- from cloakbrowser.human.config import resolve_config, merge_config-- base = resolve_config("default", None)- # ``not_a_real_field`` is silently dropped — callers shouldn't crash- # if they pass typos or future field names.- merged = merge_config(base, {"typing_delay": 30, "not_a_real_field": 99})- assert merged.typing_delay == 30-- def test_page_type_uses_per_call_typing_delay(self):- """page.type(..., human_config={'typing_delay': 30}) reaches human_type- with cfg.typing_delay == 30 even when patch was done with default 70."""- import cloakbrowser.human as h- from cloakbrowser.human import _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock, patch-- cfg = resolve_config("default", {- "idle_between_actions": False,- "field_switch_delay": (0, 1),- })- assert cfg.typing_delay == 70 # baseline-- cursor = _CursorState()- cursor.initialized = True- cursor.x = 100- cursor.y = 100-- page = MagicMock()- page.click = MagicMock()- page.dblclick = MagicMock()- page.hover = MagicMock()- page.type = MagicMock()- page.fill = MagicMock()- page.goto = MagicMock()- page.is_checked = MagicMock(return_value=False)- page.viewport_size = {"width": 1280, "height": 720}- page.evaluate = MagicMock(return_value={"hit": True})- page.context.new_cdp_session = MagicMock(side_effect=Exception("no cdp"))- page.mouse = MagicMock()- page.keyboard = MagicMock()- page.query_selector = MagicMock(return_value=None)- page.query_selector_all = MagicMock(return_value=[])- page.wait_for_selector = MagicMock(return_value=None)- page.main_frame = MagicMock()- page.main_frame.child_frames = []-- captured = {}- def fake_human_type(page_arg, raw, text, cfg_arg, cdp_session=None):- captured["typing_delay"] = cfg_arg.typing_delay- captured["mistype_chance"] = cfg_arg.mistype_chance-- def fake_scroll(*args, **kwargs):- return ({"x": 100, "y": 100, "width": 50, "height": 30}, 100, 100, False)-- with patch.object(h, "human_type", side_effect=fake_human_type), \- patch.object(h, "scroll_to_element", side_effect=fake_scroll), \- patch.object(h, "ensure_actionable"), \- patch.object(h, "_is_input_element", return_value=True), \- patch.object(h, "check_pointer_events"):- h.patch_page(page, cfg, cursor)- page.type(- "#email", "hi",- human_config={"typing_delay": 30, "mistype_chance": 0},- )-- assert captured["typing_delay"] == 30- assert captured["mistype_chance"] == 0- assert cfg.typing_delay == 70-- def test_page_fill_uses_per_call_typing_delay(self):- """Same as type, but for fill (which also clears the field first)."""- import cloakbrowser.human as h- from cloakbrowser.human import _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock, patch-- cfg = resolve_config("default", {- "idle_between_actions": False,- "field_switch_delay": (0, 1),- })- cursor = _CursorState()- cursor.initialized = True- cursor.x = 100- cursor.y = 100-- page = MagicMock()- page.viewport_size = {"width": 1280, "height": 720}- page.is_checked = MagicMock(return_value=False)- page.evaluate = MagicMock(return_value={"hit": True})- page.context.new_cdp_session = MagicMock(side_effect=Exception("no cdp"))- page.mouse = MagicMock()- page.keyboard = MagicMock()- page.query_selector = MagicMock(return_value=None)- page.query_selector_all = MagicMock(return_value=[])- page.wait_for_selector = MagicMock(return_value=None)- page.main_frame = MagicMock()- page.main_frame.child_frames = []-- captured = {}- def fake_human_type(page_arg, raw, text, cfg_arg, cdp_session=None):- captured["typing_delay"] = cfg_arg.typing_delay-- def fake_scroll(*args, **kwargs):- return ({"x": 100, "y": 100, "width": 50, "height": 30}, 100, 100, False)-- with patch.object(h, "human_type", side_effect=fake_human_type), \- patch.object(h, "scroll_to_element", side_effect=fake_scroll), \- patch.object(h, "ensure_actionable"), \- patch.object(h, "_is_input_element", return_value=True), \- patch.object(h, "check_pointer_events"):- h.patch_page(page, cfg, cursor)- page.fill("#password", "secret", human_config={"typing_delay": 150})-- assert captured["typing_delay"] == 150-- def test_element_handle_type_uses_per_call_human_config(self):- """el.type(text, human_config={...}) merges per-call overrides on the- ElementHandle path (which doesn't go through page.type)."""- from cloakbrowser.human import _patch_single_element_handle_sync, _CursorState- from cloakbrowser.human.config import resolve_config- import cloakbrowser.human as h- from unittest.mock import MagicMock, patch-- cfg = resolve_config("default", {- "idle_between_actions": False,- "field_switch_delay": (0, 1),- })- cursor = _CursorState()- cursor.initialized = True- cursor.x = 50- cursor.y = 50-- page = MagicMock()- page.viewport_size = {"width": 1280, "height": 720}- page._original = MagicMock()-- el = MagicMock()- el._human_patched = False- el.bounding_box = MagicMock(- return_value={"x": 200, "y": 200, "width": 100, "height": 30}- )- el.evaluate = _mock_el_evaluate(is_input=True)- el.is_checked = MagicMock(return_value=False)- el.query_selector = MagicMock(return_value=None)- el.query_selector_all = MagicMock(return_value=[])- el.wait_for_selector = MagicMock(return_value=None)- el.scroll_into_view_if_needed = MagicMock()-- raw_mouse = MagicMock()- raw_keyboard = MagicMock()-- captured = {}- def fake_human_type(page_arg, raw, text, cfg_arg, cdp_session=None):- captured["typing_delay"] = cfg_arg.typing_delay-- with patch.object(h, "human_type", side_effect=fake_human_type):- _patch_single_element_handle_sync(- el, page, cfg, cursor, raw_mouse, raw_keyboard,- page._original, None, None,- )- el.type("abc", human_config={"typing_delay": 25})-- assert captured["typing_delay"] == 25-# =========================================================================# 17. scroll_into_view_if_needed humanization# =========================================================================-class TestScrollIntoViewIfNeeded:- """scroll_into_view_if_needed should run through the same- accelerate → cruise → decelerate → overshoot wheel sequence as page.click—- not Playwright's instant-snap default."""-- def test_human_scroll_into_view_skips_when_in_viewport(self):- """Already-visible elements: no wheel events, just return."""- from cloakbrowser.human.scroll import human_scroll_into_view- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", None)- page = MagicMock()- page.viewport_size = {"width": 1280, "height": 720}- raw = MagicMock()- # Box is dead-center of viewport — squarely in scroll_target_zone- in_view_box = {"x": 200, "y": 300, "width": 50, "height": 30}-- box, cx, cy, did_scroll = human_scroll_into_view(- page, raw, lambda: in_view_box, 0, 0, cfg,- )- assert not did_scroll, "In-viewport elements shouldn't report scrolling"- assert box == in_view_box- assert not raw.wheel.called, "In-viewport elements shouldn't trigger wheel events"-- def test_human_scroll_into_view_scrolls_when_below_fold(self):- """Below-fold elements: wheel events fire, eventually box becomes visible."""- from cloakbrowser.human.scroll import human_scroll_into_view- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", {- "scroll_overshoot_chance": 0, # deterministic- "scroll_pre_move_delay": (0, 1),- "scroll_pause_fast": (0, 1),- "scroll_pause_slow": (0, 1),- "scroll_settle_delay": (0, 1),- })- page = MagicMock()- page.viewport_size = {"width": 1280, "height": 720}- raw = MagicMock()-- # First box is far below the fold; subsequent boxes "come into view"- # so the loop terminates after a few wheel bursts.- boxes = [- {"x": 200, "y": 2000, "width": 50, "height": 30},- {"x": 200, "y": 1500, "width": 50, "height": 30},- {"x": 200, "y": 1000, "width": 50, "height": 30},- {"x": 200, "y": 400, "width": 50, "height": 30}, # in viewport- {"x": 200, "y": 400, "width": 50, "height": 30},- {"x": 200, "y": 400, "width": 50, "height": 30},- ]- idx = {"i": 0}- def get_box():- i = min(idx["i"], len(boxes) - 1)- idx["i"] += 1- return boxes[i]-- human_scroll_into_view(page, raw, get_box, 0, 0, cfg)- assert raw.wheel.called, "Below-fold scroll should produce wheel events"-- def test_human_scroll_into_view_scrolls_x_when_off_right_edge(self):- """#521: a box past the right edge gets horizontal wheel events only."""- from cloakbrowser.human.scroll import human_scroll_into_view- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", {- "scroll_pre_move_delay": (0, 1),- "scroll_settle_delay": (0, 1),- })- page = MagicMock()- page.viewport_size = {"width": 1000, "height": 700}- page._stealth_world.evaluate.return_value = {"y": 0, "maxY": 0, "x": 0, "minX": 0, "maxX": 600}- raw = MagicMock()- boxes = iter([- {"x": 800, "y": 300, "width": 800, "height": 30},- {"x": 200, "y": 300, "width": 800, "height": 30},- ])-- box, _, _, did_scroll = human_scroll_into_view(- page, raw, lambda: next(boxes), 0, 0, cfg,- )- assert did_scroll- assert box["x"] == 200- wheel_deltas = [c.args for c in raw.wheel.call_args_list]- assert wheel_deltas, "Off-screen-right element should trigger wheel events"- assert all(dx > 0 and dy == 0 for dx, dy in wheel_deltas)-- def test_human_scroll_into_view_skips_x_when_pinned_right(self):- """Page already scrolled fully right: horizontal scrolling can't help."""- from cloakbrowser.human.scroll import human_scroll_into_view- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", None)- page = MagicMock()- page.viewport_size = {"width": 1000, "height": 700}- page._stealth_world.evaluate.return_value = {"y": 0, "maxY": 0, "x": 600, "minX": 0, "maxX": 600}- raw = MagicMock()- clipped_box = {"x": 900, "y": 300, "width": 200, "height": 30}-- box, _, _, did_scroll = human_scroll_into_view(- page, raw, lambda: clipped_box, 0, 0, cfg,- )- assert not did_scroll- assert box == clipped_box- assert not raw.wheel.called-- def test_human_scroll_into_view_subpixel_negative_top_at_page_top_bails(self):- """Layout reports top=-1/64 px on an unscrolled page. Still fully visible,- so the pinned-at-top check must stop a pointless upward scroll."""- from cloakbrowser.human.scroll import human_scroll_into_view- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", None)- page = MagicMock()- page.viewport_size = {"width": 1000, "height": 700}- page._stealth_world.evaluate.return_value = {"y": 0, "maxY": 0, "x": 0, "minX": 0, "maxX": 0}- raw = MagicMock()- top_box = {"x": 200, "y": -0.015625, "width": 200, "height": 21.5}-- _, _, _, did_scroll = human_scroll_into_view(- page, raw, lambda: top_box, 0, 0, cfg,- )- assert not did_scroll- assert not raw.wheel.called-- def test_human_scroll_into_view_scrolls_x_left_on_rtl_page(self):- """RTL page at its start (scrollX 0, range -600..0): a box in the left- overflow gets negative horizontal wheel events."""- from cloakbrowser.human.scroll import human_scroll_into_view- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- cfg = resolve_config("default", {- "scroll_pre_move_delay": (0, 1),- "scroll_settle_delay": (0, 1),- })- page = MagicMock()- page.viewport_size = {"width": 1000, "height": 700}- page._stealth_world.evaluate.return_value = {- "y": 0, "maxY": 0, "x": 0, "minX": -600, "maxX": 0,- }- raw = MagicMock()- boxes = iter([- {"x": -600, "y": 300, "width": 200, "height": 30},- {"x": 400, "y": 300, "width": 200, "height": 30},- ])-- box, _, _, did_scroll = human_scroll_into_view(- page, raw, lambda: next(boxes), 0, 0, cfg,- )- assert did_scroll- assert box["x"] == 400- wheel_deltas = [c.args for c in raw.wheel.call_args_list]- assert wheel_deltas, "Off-screen-left element on an RTL page should trigger wheel events"- assert all(dx < 0 and dy == 0 for dx, dy in wheel_deltas)-- async def test_async_human_scroll_into_view_scrolls_x_left_on_rtl_page(self):- """Async twin of the RTL case above."""- from cloakbrowser.human.scroll_async import async_human_scroll_into_view- from cloakbrowser.human.config import resolve_config- from unittest.mock import AsyncMock, MagicMock-- cfg = resolve_config("default", {- "scroll_pre_move_delay": (0, 1),- "scroll_settle_delay": (0, 1),- })- page = MagicMock()- page.viewport_size = {"width": 1000, "height": 700}- page._stealth_world.evaluate = AsyncMock(return_value={- "y": 0, "maxY": 0, "x": 0, "minX": -600, "maxX": 0,- })- raw = MagicMock()- raw.move = AsyncMock()- raw.wheel = AsyncMock()- boxes = iter([- {"x": -600, "y": 300, "width": 200, "height": 30},- {"x": 400, "y": 300, "width": 200, "height": 30},- ])-- async def get_box():- return next(boxes)-- box, _, _, did_scroll = await async_human_scroll_into_view(- page, raw, get_box, 0, 0, cfg,- )- assert did_scroll- assert box["x"] == 400- wheel_deltas = [c.args for c in raw.wheel.call_args_list]- assert wheel_deltas, "Off-screen-left element on an RTL page should trigger wheel events"- assert all(dx < 0 and dy == 0 for dx, dy in wheel_deltas)-- def test_element_handle_scroll_into_view_if_needed_humanized(self):- """el.scroll_into_view_if_needed() routes through human_scroll_into_view."""- from cloakbrowser.human import _patch_single_element_handle_sync, _CursorState- from cloakbrowser.human.config import resolve_config- import cloakbrowser.human as h- from unittest.mock import MagicMock, patch-- cfg = resolve_config("default", None)- cursor = _CursorState()- cursor.initialized = True- cursor.x = 50- cursor.y = 50-- page = MagicMock()- page.viewport_size = {"width": 1280, "height": 720}- page._original = MagicMock()-- el = MagicMock()- el._human_patched = False- el.bounding_box = MagicMock(- return_value={"x": 200, "y": 200, "width": 50, "height": 30}- )- el.evaluate = _mock_el_evaluate(is_input=False)- el.is_checked = MagicMock(return_value=False)- el.query_selector = MagicMock(return_value=None)- el.query_selector_all = MagicMock(return_value=[])- el.wait_for_selector = MagicMock(return_value=None)- # Make sure the original method exists so the patch is wired up- el.scroll_into_view_if_needed = MagicMock()-- called = {"count": 0}- def fake(*args, **kwargs):- called["count"] += 1- return ({"x": 200, "y": 200, "width": 50, "height": 30}, 100, 100, False)-- with patch.object(h, "human_scroll_into_view", side_effect=fake):- _patch_single_element_handle_sync(- el, page, cfg, cursor, MagicMock(), MagicMock(),- page._original, None, None,- )- el.scroll_into_view_if_needed()-- assert called["count"] >= 1, "humanized scroll helper was never called"-- def test_locator_scroll_into_view_if_needed_humanized(self):- """Locator.scroll_into_view_if_needed() also goes through humanized scroll."""- import cloakbrowser.human as h- from cloakbrowser.human import _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock, patch-- # Patch Locator class fresh- _ensure_locator_patched()-- from playwright.sync_api._generated import Locator-- cfg = resolve_config("default", None)- cursor = _CursorState()- cursor.x = 50- cursor.y = 50- cursor.initialized = True-- page = MagicMock()- page._original = MagicMock()- page._human_cfg = cfg- page._human_cursor = cursor- page._human_raw_mouse = MagicMock()- page.viewport_size = {"width": 1280, "height": 720}-- # Build a Locator-like object satisfying the patched method- loc = MagicMock(spec=Locator)- loc.page = page- impl_obj = MagicMock()- impl_obj._selector = "#x"- loc._impl_obj = impl_obj- loc.bounding_box = MagicMock(- return_value={"x": 100, "y": 100, "width": 50, "height": 30}- )-- called = {"count": 0, "cfg": None}- def fake(*args, **kwargs):- called["count"] += 1- # cfg is the 6th positional arg (page, raw, get_box, cx, cy, cfg)- called["cfg"] = args[5] if len(args) >= 6 else kwargs.get("cfg")- return ({"x": 100, "y": 100, "width": 50, "height": 30}, 200, 200, False)-- with patch.object(h, "human_scroll_into_view", side_effect=fake):- getattr(Locator, "scroll_into_view_if_needed")(- loc, human_config={"scroll_overshoot_chance": 0.5},- )-- assert called["count"] == 1- # Per-call override merged into the cfg passed downstream- assert called["cfg"].scroll_overshoot_chance == 0.5- # Cursor was updated from the helper's return value- assert cursor.x == 200 and cursor.y == 200-# =========================================================================# Issue #307: frame/page click timeout should not multiply# =========================================================================-class TestTimeoutBudget307:- """Verify timeout budget is shared across sequential operations."""-- def test_page_click_total_time_within_budget(self):- """page.click on a missing element should not exceed ~1x the timeout."""- import cloakbrowser.human as h- from cloakbrowser.human import _CursorState- from cloakbrowser.human.config import resolve_config- from unittest.mock import MagicMock-- TIMEOUT_MS = 500- cfg = resolve_config("default", {"idle_between_actions": False})- cursor = _CursorState()- cursor.initialized = True- cursor.x = 100- cursor.y = 100-- page = MagicMock()- page.click = MagicMock()- page.dblclick = MagicMock()- page.hover = MagicMock()- page.type = MagicMock()- page.fill = MagicMock()- page.goto = MagicMock()- page.is_checked = MagicMock(return_value=False)- page.viewport_size = {"width": 1280, "height": 720}- page.evaluate = MagicMock(return_value={"hit": True})- page.context.new_cdp_session = MagicMock(side_effect=Exception("no cdp"))- page.mouse = MagicMock()- page.keyboard = MagicMock()- page.query_selector = MagicMock(return_value=None)- page.query_selector_all = MagicMock(return_value=[])- page.wait_for_selector = MagicMock(return_value=None)- page.main_frame = MagicMock()- page.main_frame.child_frames = []-- loc = MagicMock()- loc.wait_for = MagicMock(side_effect=lambda **kw: time.sleep(kw.get("timeout", 30000) / 1000.0))- loc.is_visible = MagicMock(return_value=False)- loc.first = loc- page.locator = MagicMock(return_value=loc)-- h.patch_page(page, cfg, cursor)-- start = time.monotonic()- try:- page.click("#does-not-exist", timeout=TIMEOUT_MS)- except Exception:- pass- elapsed_ms = (time.monotonic() - start) * 1000-- assert elapsed_ms < TIMEOUT_MS * 1.8, (- f"expected <{TIMEOUT_MS * 1.8}ms, got {elapsed_ms:.0f}ms"- )---class TestPointerEventsFailurePolicy:- """Legacy handles fail open; selector paths in the stealth world fail closed."""-- def test_handle_failopen_returns_on_evaluate_error(self):- from cloakbrowser.human.actionability import check_pointer_events_handle- el = MagicMock()- el.bounding_box = MagicMock(side_effect=Exception("stale handle"))- el.evaluate = MagicMock(side_effect=Exception("execution context destroyed"))- start = time.monotonic()- check_pointer_events_handle(MagicMock(), el, 100, 100, timeout=2000) # must not raise- elapsed_ms = (time.monotonic() - start) * 1000- assert elapsed_ms < 500, f"fail-open should return promptly, took {elapsed_ms:.0f}ms"-- def test_selector_evaluation_error_fails_closed_without_playwright(self):- from cloakbrowser.human.actionability import check_pointer_events- from cloakbrowser.human.stealth_dom import StealthEvaluationError- page = _no_locator_page(_FakeWorld(None))- start = time.monotonic()- with pytest.raises(StealthEvaluationError):- check_pointer_events(page, "#x", 1, 1, 100, 100, timeout=1)- elapsed_ms = (time.monotonic() - start) * 1000- assert elapsed_ms < 500-- def test_handle_still_raises_when_covered(self):- """A genuine 'covered' result (not None) must still raise — fail-open- only applies when the check could not be determined."""- from cloakbrowser.human.actionability import (- check_pointer_events_handle, ElementNotReceivingEventsError,- )- el = MagicMock()- el.bounding_box = MagicMock(return_value={"x": 0, "y": 0, "width": 10, "height": 10})- el.evaluate = MagicMock(return_value={"hit": False, "covering": "DIV"})- with pytest.raises(ElementNotReceivingEventsError):- check_pointer_events_handle(MagicMock(), el, 5, 5, timeout=200)-- def test_async_handle_failopen_returns_on_evaluate_error(self):- from cloakbrowser.human.actionability_async import async_check_pointer_events_handle- from unittest.mock import AsyncMock- el = MagicMock()- el.bounding_box = AsyncMock(side_effect=Exception("stale handle"))- el.evaluate = AsyncMock(side_effect=Exception("execution context destroyed"))- start = time.monotonic()- asyncio.run(async_check_pointer_events_handle(MagicMock(), el, 100, 100, timeout=2000))- elapsed_ms = (time.monotonic() - start) * 1000- assert elapsed_ms < 500, f"fail-open should return promptly, took {elapsed_ms:.0f}ms"---# =========================================================================-# Isolated-world DOM helper (stealth_dom) + rewired actionability/scroll-# =========================================================================--def _versioned_fake_payload(response):- if not isinstance(response, dict):- return response- payload = dict(response)- payload.setdefault("v", PROTOCOL_VERSION)- if payload.get("r") in ("ok", "stale"):- payload.setdefault("targetId", 1)- payload.setdefault("gen", 1)- return payload---class _FakeWorld:- """Sync stand-in for page._stealth_world with protocol-valid payloads."""- def __init__(self, response):- self.response = response- self.calls = []-- def evaluate(self, expr):- self.calls.append(expr)- response = self.response(expr) if callable(self.response) else self.response- return _versioned_fake_payload(response)---class _AsyncFakeWorld:- def __init__(self, response):- self.response = response- self.calls = []-- async def evaluate(self, expr):- self.calls.append(expr)- response = self.response(expr) if callable(self.response) else self.response- return _versioned_fake_payload(response)---def _no_locator_page(world):- """A page whose .locator explodes — proves the isolated world handled the- read and Playwright was never touched (the whole point of the change)."""- page = MagicMock()- page._stealth_world = world- page.locator = MagicMock(side_effect=AssertionError("Playwright locator must not be used when the isolated world handles the read"))- return page---class TestStealthDomBuilders:- def test_box_js_escapes_selector(self):- from cloakbrowser.human.stealth_dom import build_box_js- js = build_box_js('a"b')- assert '"a\\"b"' in js- assert "getBoundingClientRect" in js-- def test_actionable_js_reads_visibility(self):- from cloakbrowser.human.stealth_dom import build_actionable_js- js = build_actionable_js("#x")- assert '"#x"' in js- assert "visible" in js and "getComputedStyle" in js-- def test_snapshot_js_uses_versioned_identity_protocol(self):- from cloakbrowser.human.stealth_dom import build_snapshot_js- js = build_snapshot_js("#x")- assert "v: __V" in js- assert "targetId: __targetId(__el)" in js- assert "Object.defineProperty(globalThis" in js-- def test_validate_js_requires_same_target_at_point(self):- from cloakbrowser.human.stealth_dom import build_validate_js- js = build_validate_js("#x", 7, 3, 1.5, 2.5)- assert "__id !== 7" in js- assert "r: 'stale'" in js- assert "__deepElementFromPoint(1.5, 2.5)" in js-- def test_pointer_js_inlines_coords(self):- from cloakbrowser.human.stealth_dom import build_pointer_js- js = build_pointer_js("#x", 1.5, 2.5)- assert "__deepElementFromPoint(1.5, 2.5)" in js-- def test_parse_result(self):- from cloakbrowser.human.stealth_dom import (- parse_result, EVALUATION_FAILED, NOT_FOUND, OK, STALE, UNSUPPORTED,- )- ok = {"v": 2, "r": "ok", "targetId": 4, "gen": 3, "box": {"x": 1}}- assert parse_result(ok) == (OK, ok)- assert parse_result({"v": 2, "r": "not_found"}) == (NOT_FOUND, None)- stale = {"v": 2, "r": "stale", "targetId": 9, "gen": 3}- assert parse_result(stale) == (STALE, stale)- assert parse_result({"v": 2, "r": "unsupported"}) == (UNSUPPORTED, None)- # A payload without the world generation cannot be trusted for identity.- assert parse_result({"v": 2, "r": "ok", "targetId": 4}) == (EVALUATION_FAILED, None)- assert parse_result({"v": 2, "r": "stale", "targetId": 4}) == (EVALUATION_FAILED, None)- # Malformed/empty evaluation results are explicit failures, never fallback signals.- assert parse_result(None) == (EVALUATION_FAILED, None)- assert parse_result("UNSUPPORTED") == (EVALUATION_FAILED, None)- assert parse_result([]) == (EVALUATION_FAILED, None)- assert parse_result({"v": 999, "r": "ok", "targetId": 1}) == (- EVALUATION_FAILED, None,- )- assert parse_result({"v": 1, "r": "ok"}) == (EVALUATION_FAILED, None)---class TestEnsureActionableStealth:- def test_ok_returns_without_playwright(self):- from cloakbrowser.human.actionability import ensure_actionable, CHECKS_CLICK- world = _FakeWorld({"r": "ok", "visible": True, "enabled": True, "editable": True})- page = _no_locator_page(world)- ensure_actionable(page, "#x", CHECKS_CLICK, timeout=100)- assert len(world.calls) == 1 # single in-world read, no locator fallback-- def test_not_visible_raises(self):- from cloakbrowser.human.actionability import ensure_actionable, CHECKS_CLICK, ElementNotVisibleError- page = _no_locator_page(_FakeWorld({"r": "ok", "visible": False, "enabled": True, "editable": True}))- with pytest.raises(ElementNotVisibleError):- ensure_actionable(page, "#x", CHECKS_CLICK, timeout=100)-- def test_disabled_raises(self):- from cloakbrowser.human.actionability import ensure_actionable, CHECKS_CLICK, ElementNotEnabledError- page = _no_locator_page(_FakeWorld({"r": "ok", "visible": True, "enabled": False, "editable": True}))- with pytest.raises(ElementNotEnabledError):- ensure_actionable(page, "#x", CHECKS_CLICK, timeout=100)-- def test_not_found_raises_attached(self):- from cloakbrowser.human.actionability import ensure_actionable, CHECKS_CLICK, ElementNotAttachedError- page = _no_locator_page(_FakeWorld({"r": "not_found"}))- with pytest.raises(ElementNotAttachedError):- ensure_actionable(page, "#x", CHECKS_CLICK, timeout=100)-- def test_unsupported_raises_without_playwright(self):- from cloakbrowser.human.actionability import ensure_actionable, CHECKS_CLICK- from cloakbrowser.human.stealth_dom import UnsupportedHumanizeSelectorError- page = _no_locator_page(_FakeWorld({"r": "unsupported"}))- with pytest.raises(UnsupportedHumanizeSelectorError):- ensure_actionable(page, "internal:role=button", CHECKS_CLICK, timeout=100)-- def test_no_world_raises_without_playwright(self):- from cloakbrowser.human.actionability import ensure_actionable, CHECKS_CLICK- from cloakbrowser.human.stealth_dom import StealthWorldUnavailableError- page = MagicMock()- page._stealth_world = None- page.locator = MagicMock(side_effect=AssertionError("must not call Playwright"))- with pytest.raises(StealthWorldUnavailableError):- ensure_actionable(page, "#x", CHECKS_CLICK, timeout=100)- page.locator.assert_not_called()---class TestSelectorSnapshotHelpers:- def test_input_and_focus_use_canonical_snapshot(self):- from cloakbrowser.human import _is_input_element, _is_selector_focused- world = _FakeWorld({- "r": "ok", "isInput": True, "focused": True,- })- page = _no_locator_page(world)- page.evaluate = MagicMock(side_effect=AssertionError("must stay isolated"))- assert _is_input_element(page, "text=Submit") is True- assert _is_selector_focused(page, "text=Submit") is True- page.evaluate.assert_not_called()-- def test_unsupported_input_selector_raises(self):- from cloakbrowser.human import _is_input_element- from cloakbrowser.human.stealth_dom import UnsupportedHumanizeSelectorError- page = _no_locator_page(_FakeWorld({"r": "unsupported"}))- with pytest.raises(UnsupportedHumanizeSelectorError):- _is_input_element(page, "internal:role=button")-- def test_async_input_and_focus_use_canonical_snapshot(self):- from cloakbrowser.human import (- _async_is_input_element, _async_is_selector_focused,- )- world = _AsyncFakeWorld({- "r": "ok", "isInput": True, "focused": False,- })- page = _no_locator_page(world)- assert asyncio.run(_async_is_input_element(page, "text=Submit")) is True- assert asyncio.run(_async_is_selector_focused(page, "text=Submit")) is False---class TestGetElementBoxStealth:- def test_ok_returns_box_without_playwright(self):- from cloakbrowser.human.scroll import _get_element_box- box = {"x": 10.0, "y": 20.0, "width": 30.0, "height": 40.0}- page = _no_locator_page(_FakeWorld({"r": "ok", "targetId": 7, "gen": 3, "box": box}))- assert _get_element_box(page, "#x") == {**box, "targetId": 7, "gen": 3}-- def test_not_found_returns_none_stays_in_world(self):- from cloakbrowser.human.scroll import _get_element_box- page = _no_locator_page(_FakeWorld({"r": "not_found"}))- assert _get_element_box(page, "#x", timeout=100) is None-- def test_unsupported_raises_without_fallback(self):- from cloakbrowser.human.scroll import _get_element_box- from cloakbrowser.human.stealth_dom import UnsupportedHumanizeSelectorError- page = _no_locator_page(_FakeWorld({"r": "unsupported"}))- with pytest.raises(UnsupportedHumanizeSelectorError):- _get_element_box(page, "internal:role=button")-- def test_custom_timeout_is_not_capped_at_two_seconds(self):- from cloakbrowser.human.scroll import _get_element_box- from unittest.mock import patch-- responses = iter([- {"r": "not_found"},- {"r": "ok", "targetId": 3,- "box": {"x": 1, "y": 2, "width": 3, "height": 4}},- ])- page = _no_locator_page(_FakeWorld(lambda expr: next(responses)))- with patch("cloakbrowser.human.scroll.time") as mock_time:- mock_time.monotonic.side_effect = [0, 2.5]- box = _get_element_box(page, "#slow", timeout=5000)- assert box["targetId"] == 3-- def test_async_custom_timeout_is_not_capped_at_two_seconds(self):- from cloakbrowser.human.scroll_async import _get_element_box_async- from unittest.mock import AsyncMock, patch-- responses = iter([- {"r": "not_found"},- {"r": "ok", "targetId": 4,- "box": {"x": 1, "y": 2, "width": 3, "height": 4}},- ])- page = _no_locator_page(_AsyncFakeWorld(lambda expr: next(responses)))- with patch("cloakbrowser.human.scroll_async.time") as mock_time, patch(- "cloakbrowser.human.scroll_async.asyncio.sleep", new=AsyncMock()- ):- mock_time.monotonic.side_effect = [0, 2.5]- box = asyncio.run(_get_element_box_async(page, "#slow", timeout=5000))- assert box["targetId"] == 4---class TestCheckPointerEventsStealth:- def test_hit_returns(self):- from cloakbrowser.human.actionability import check_pointer_events- world = _FakeWorld({"r": "ok", "hit": True})- page = _no_locator_page(world)- check_pointer_events(page, "#x", 1, 1, 5, 5, stealth=world, timeout=200)-- def test_miss_raises(self):- from cloakbrowser.human.actionability import check_pointer_events, ElementNotReceivingEventsError- world = _FakeWorld({"r": "ok", "hit": False, "covering": "DIV"})- page = _no_locator_page(world)- with pytest.raises(ElementNotReceivingEventsError):- check_pointer_events(page, "#x", 1, 1, 5, 5, stealth=world, timeout=200)-- def test_force_skips_the_check_entirely(self):- """force=True bypasses the pointer check, matching Playwright, where- force skips all actionability rather than only coverage rejection."""- from unittest.mock import patch-- import cloakbrowser.human as h- from cloakbrowser.human.config import resolve_config-- cfg = resolve_config("default")- cursor = h._CursorState()- cursor.initialized = True- cursor.x = 100- cursor.y = 100-- page = MagicMock()- page.viewport_size = {"width": 1280, "height": 720}- page.context.new_cdp_session = MagicMock(side_effect=Exception("no cdp"))- page.main_frame = MagicMock()- page.main_frame.child_frames = []-- def fake_scroll(page_arg, raw, selector, cx, cy, cfg_arg, timeout=30000):- return ({"x": 10, "y": 10, "width": 50, "height": 30, "targetId": 1}, cx, cy, False)-- with patch.object(h, "scroll_to_element", side_effect=fake_scroll), \- patch.object(h, "ensure_actionable"), \- patch.object(h, "_is_input_element", return_value=False), \- patch.object(h, "check_pointer_events") as checked:- h.patch_page(page, cfg, cursor)- page.click("#x", force=True)- assert not checked.called, "force=True must not run the pointer check"-- page.click("#x")- assert checked.called, "force=False must still run the pointer check"-- def test_stale_target_raises(self):- from cloakbrowser.human.actionability import (- check_pointer_events, ElementTargetChangedError,- )- world = _FakeWorld({"r": "stale", "targetId": 2})- page = _no_locator_page(world)- with pytest.raises(ElementTargetChangedError):- check_pointer_events(page, "#x", 1, 1, 5, 5, stealth=world, timeout=200)-- def test_unsupported_raises_without_fallback(self):- from cloakbrowser.human.actionability import check_pointer_events- from cloakbrowser.human.stealth_dom import UnsupportedHumanizeSelectorError- world = _FakeWorld({"r": "unsupported"})- page = _no_locator_page(world)- with pytest.raises(UnsupportedHumanizeSelectorError):- check_pointer_events(- page, "internal:role=button", 1, 1, 5, 5,- stealth=world, timeout=200,- )---class TestStealthAsync:- def test_async_ensure_actionable_ok(self):- from cloakbrowser.human.actionability_async import async_ensure_actionable- from cloakbrowser.human.actionability import CHECKS_CLICK- world = _AsyncFakeWorld({"r": "ok", "visible": True, "enabled": True, "editable": True})- page = _no_locator_page(world)- asyncio.run(async_ensure_actionable(page, "#x", CHECKS_CLICK, timeout=100))- assert len(world.calls) == 1-- def test_async_get_element_box_ok(self):- from cloakbrowser.human.scroll_async import _get_element_box_async- box = {"x": 1.0, "y": 2.0, "width": 3.0, "height": 4.0}- page = _no_locator_page(_AsyncFakeWorld({"r": "ok", "targetId": 9, "gen": 3, "box": box}))- assert asyncio.run(_get_element_box_async(page, "#x")) == {**box, "targetId": 9, "gen": 3}-# =========================================================================# framenavigated -> isolated-world invalidation (#507)# =========================================================================-class TestFrameNavigatedInvalidation:- """Regression #507: click/form/history navigation must invalidate the- isolated world, not just page.goto. Without this the world stays bound to- a bfcached old document and fill()/click() actionability reads fail."""-- @staticmethod- def _build_page(is_async):- from unittest.mock import MagicMock, AsyncMock- Mock = AsyncMock if is_async else MagicMock- page = MagicMock()- for name in ("click", "dblclick", "hover", "type", "fill", "goto",- "check", "uncheck", "select_option", "press"):- setattr(page, name, Mock())- page.is_checked = Mock(return_value=False)- page.viewport_size = {"width": 1280, "height": 720}- page.evaluate = Mock(return_value={"hit": True})- # new_cdp_session must SUCCEED so the stealth world is created- page.context.new_cdp_session = Mock(return_value=MagicMock())- for surface in ("mouse", "keyboard"):- setattr(page, surface, MagicMock())- for m in ("move", "click", "wheel", "down", "up"):- setattr(page.mouse, m, Mock())- for m in ("type", "down", "up", "press", "insert_text"):- setattr(page.keyboard, m, Mock())- page.query_selector = Mock(return_value=None)- page.query_selector_all = Mock(return_value=[])- page.wait_for_selector = Mock(return_value=None)- # main_frame is a property in the Playwright API (sync + async)- main_frame = MagicMock()- main_frame.child_frames = []- page.main_frame = main_frame- return page-- @staticmethod- def _framenavigated_handler(page):- # capture the handler registered via page.on("framenavigated", cb)- for call in page.on.call_args_list:- if call.args and call.args[0] == "framenavigated":- return call.args[1]- return None-- def _run(self, is_async):- import cloakbrowser.human as h- from cloakbrowser.human import _CursorState- from cloakbrowser.human.config import resolve_config-- cfg = resolve_config("default", {"idle_between_actions": False})- cursor = _CursorState()- cursor.initialized = True- cursor.x = cursor.y = 100- page = self._build_page(is_async)-- (h.patch_page_async if is_async else h.patch_page)(page, cfg, cursor)-- handler = self._framenavigated_handler(page)- assert handler is not None, "framenavigated listener was not registered"-- world = page._stealth_world- assert world is not None-- # main-frame navigation invalidates the world- world._context_id = 123- handler(page.main_frame)- assert world._context_id is None, "main-frame nav did not invalidate the world"-- # a subframe navigation must NOT invalidate- world._context_id = 456- handler(MagicMock()) # some other frame- assert world._context_id == 456, "subframe nav wrongly invalidated the world"-- def test_sync_invalidates_on_main_frame_nav(self):- self._run(is_async=False)-- def test_async_invalidates_on_main_frame_nav(self):- self._run(is_async=True)-# =========================================================================# Direct runner (backwards compat)@@ -3076,3 +835,20 @@ class TestFrameNavigatedInvalidation:if __name__ == "__main__":sys.exit(pytest.main([__file__, "-v", "--tb=short", "-x"]))+++def test_error_classes_stay_importable():+ """Same compatibility set as JS errors.ts / .NET Actionability.cs."""+ from cloakbrowser import human as h++ for name in ("ElementNotAttachedError", "ElementNotVisibleError", "ElementNotStableError",+ "ElementNotEnabledError", "ElementNotEditableError",+ "ElementNotReceivingEventsError", "ElementTargetChangedError"):+ cls = getattr(h, name)+ assert issubclass(cls, h.ActionabilityError) and issubclass(cls, RuntimeError)+ e = h.ElementNotReceivingEventsError("#b", "div")+ assert (e.selector, e.check, e.covering_tag) == ("#b", "pointer_events", "div")+ assert str(e) == "Element '#b' failed pointer_events check: element is covered by <div>"+ for name in ("UnsupportedHumanizeSelectorError", "StealthWorldUnavailableError",+ "StealthEvaluationError"):+ assert issubclass(getattr(h, name), h.StealthDomError)diff --git a/tests/test_resolver_sources_match.py b/tests/test_resolver_sources_match.pyindex e1591bc..efa1ec7 100644--- a/tests/test_resolver_sources_match.py+++ b/tests/test_resolver_sources_match.py@@ -1,70 +1,39 @@-"""The isolated-world resolver JS is hand-copied into three wrappers.--``cloakbrowser/human/stealth_dom.py``, ``js/src/human/stealthDom.ts`` and-``dotnet/src/CloakBrowser/Human/StealthDom.cs`` each embed the same resolver as a-string literal. Nothing generates them, so they can silently drift: a fix landed in-one wrapper and forgotten in another means that wrapper resolves a *different*-element and clicks the wrong coordinates, with no test failing.--These tests assert the three literals stay byte-identical, and that the shared JS-never grows a character that would terminate or corrupt one of the three host-literals (a backtick or ``${`` breaks the TS ``String.raw``; ``\"\"\"`` breaks the-Python and C# raw strings).+"""The isolated-world helper library (``__cloakH``) is hand-copied into three ports.++``cloakbrowser/human/world.py``, ``js/src/human/worldHelpers.ts`` and+``dotnet/src/CloakBrowser/Human/WorldHelpers.cs`` each embed the same JS as a+string literal. Nothing generates them, so they can silently drift; these tests+assert the copies stay byte-identical and never grow a character that would+terminate one of the host literals (a backtick or ``${`` breaks the TS+``String.raw``; a triple quote breaks the Python and C# raw strings)."""from __future__ import annotationsimport refrom pathlib import Path-import pytest-ROOT = Path(__file__).resolve().parent.parent-PY_SRC = ROOT / "cloakbrowser" / "human" / "stealth_dom.py"-TS_SRC = ROOT / "js" / "src" / "human" / "stealthDom.ts"-CS_SRC = ROOT / "dotnet" / "src" / "CloakBrowser" / "Human" / "StealthDom.cs"-_TRIPLE = '"' * 3def _extract(path: Path, pattern: str) -> str:m = re.search(pattern, path.read_text(encoding="utf-8"), re.S)- assert m, f"could not find the resolver literal in {path}"+ assert m, f"could not find the helper literal in {path}"return m.group(1)-def _resolvers() -> dict[str, str]:- return {- "python": _extract(PY_SRC, r'_RESOLVER_BODY = r"""(.*?)"""'),- "typescript": _extract(TS_SRC, r"RESOLVER_BODY\s*=\s*String\.raw`(.*?)`"),- "dotnet": _extract(CS_SRC, r'ResolverBody = """(.*?)"""'),- }---def test_resolver_bodies_are_byte_identical():- bodies = _resolvers()- py = bodies["python"]- for name, body in bodies.items():- if body != py:- # Surface the first differing line rather than dumping 17k chars.- for i, (a, b) in enumerate(zip(py.splitlines(), body.splitlines()), 1):- if a != b:- pytest.fail(- f"{name} resolver diverges from python at line {i}:\n"- f" python: {a!r}\n {name}: {b!r}"- )- pytest.fail(- f"{name} resolver differs from python in length only "- f"({len(body)} vs {len(py)} chars)"- )--[email protected]("name", ["python", "typescript", "dotnet"])-def test_resolver_has_no_host_literal_hazards(name):- body = _resolvers()[name]- assert "`" not in body, "a backtick terminates the TypeScript String.raw literal"- assert "${" not in body, "'${' interpolates inside the TypeScript String.raw literal"- assert _TRIPLE not in body, "a triple quote terminates the Python and C# raw strings"- assert "\r" not in body, "CR would make the three copies differ by line ending"- for i, line in enumerate(body.splitlines(), 1):+def test_world_helpers_are_byte_identical():+ """The isolated-world helper library (``__cloakH``) is shared by the+ Python and JS humanize engines; the copies must not drift."""+ py = _extract(ROOT / "cloakbrowser" / "human" / "world.py", r'_HELPERS_JS = r"""(.*?)"""')+ ts = _extract(ROOT / "js" / "src" / "human" / "worldHelpers.ts", r"HELPERS_JS = String\.raw`(.*?)`;")+ assert ts == py, "js/src/human/worldHelpers.ts diverges from cloakbrowser/human/world.py"+ cs = _extract(ROOT / "dotnet" / "src" / "CloakBrowser" / "Human" / "WorldHelpers.cs",+ r'public const string Js = """\n(.*?)\n""";')+ assert cs == py, "dotnet/src/CloakBrowser/Human/WorldHelpers.cs diverges from cloakbrowser/human/world.py"+ assert _TRIPLE not in py, "a triple quote terminates the C# raw string"+ assert "`" not in py and "${" not in py, "would break the TypeScript String.raw literal"+ assert "\r" not in py, "CR would make the three copies differ by line ending"+ for i, line in enumerate(py.splitlines(), 1):assert line == line.rstrip(), f"line {i} has trailing whitespace (invisible drift)"diff --git a/tests/test_stealth_dom_browser.py b/tests/test_stealth_dom_browser.pyindex 84726f4..35b22dc 100644--- a/tests/test_stealth_dom_browser.py+++ b/tests/test_stealth_dom_browser.py@@ -1,25 +1,26 @@-"""Real-browser parity tests for isolated-world humanize DOM reads."""--import json+"""Real-browser parity tests: humanized actions land on the element Playwright resolves."""import pytest-from cloakbrowser.human.stealth_dom import _RESOLVER_BODY++_RECORD_CLICKS = """() => {+ window.__clicked = [];+ document.addEventListener('click', (e) => {+ // The innermost element with an id (a click on a button's <span> is the button's).+ const el = e.composedPath().find((n) => n.id);+ window.__clicked.push(el ? el.id : null);+ }, true);+}"""-def _resolve_identity_js(selector: str) -> str:- """Resolve with the shipped isolated-world resolver and return its identity."""- return (- "(() => {\n"- + _RESOLVER_BODY- + "\nconst el = __resolve("- + json.dumps(selector)- + ");\n"- + "if (el === 'UNSUPPORTED') return {status: 'unsupported'};\n"- + "if (!el) return {status: 'not_found'};\n"- + "return {status: 'ok', id: el.id, tag: el.tagName};\n"- + "})()"- )+def _clicked_id(page, selector_or_locator):+ """Click humanized and return the id of the element that received it."""+ page.evaluate("window.__clicked = []")+ if isinstance(selector_or_locator, str):+ page.click(selector_or_locator, timeout=3000)+ else:+ selector_or_locator.click(timeout=3000)+ return page.evaluate("window.__clicked")[-1]@pytest.mark.slow@@ -57,12 +58,7 @@ def test_text_selector_ignores_hidden_head_script_and_clicks_visible_target():playwright_identity = page.locator(selector).first.evaluate("el => ({status: 'ok', id: el.id, tag: el.tagName})")- isolated_identity = page._stealth_world.evaluate(- _resolve_identity_js(selector)- )-assert playwright_identity == expected- assert isolated_identity == expectedpage.click(selector, timeout=3000)assert page.evaluate("window.targetClicks") == 1@@ -74,7 +70,6 @@ def test_text_selector_ignores_hidden_head_script_and_clicks_visible_target():def test_display_contents_uses_rendered_content_geometry():"""A boxless display:contents target uses its rendered text/child union."""from cloakbrowser import launch- from cloakbrowser.human.stealth_dom import build_snapshot_jsbrowser = launch(headless=False, humanize=True, release_channel="preview")try:@@ -114,35 +109,6 @@ def test_display_contents_uses_rendered_content_geometry():)assert own_rect == {"width": 0, "height": 0}- target = page._stealth_world.evaluate(build_snapshot_js("text=Hoy"))- assert target["visible"] is True- assert target["box"]["width"] > 0- assert target["box"]["height"] > 0-- union = page._stealth_world.evaluate(build_snapshot_js("#union"))- assert union["visible"] is True- rects = page.evaluate(- """() => Object.fromEntries(- ['left', 'right', 'nested-child', 'hidden'].map(id => {- const r = document.querySelector('#' + id).getBoundingClientRect();- return [id, {x: r.x, y: r.y, width: r.width, height: r.height}];- })- )"""- )- union_right = union["box"]["x"] + union["box"]["width"]- union_bottom = union["box"]["y"] + union["box"]["height"]- for child_id in ("left", "right", "nested-child"):- child = rects[child_id]- assert union["box"]["x"] <= child["x"]- assert union["box"]["y"] <= child["y"]- assert union_right >= child["x"] + child["width"]- assert union_bottom >= child["y"] + child["height"]- assert union_right < rects["hidden"]["x"]-- hidden_text = page._stealth_world.evaluate(build_snapshot_js("#hidden-text"))- assert hidden_text["visible"] is False- assert hidden_text["box"] is None-page.click("text=Hoy", timeout=3000)page.click("#nested", timeout=3000)assert page.evaluate("window.targetClicks") == 1@@ -177,15 +143,10 @@ def test_text_selector_semantics_match_playwright():("text=Submit Me", "value-target"),("text=foobar", "normalized-target"),]+ page.evaluate(_RECORD_CLICKS)for selector, expected_id in cases:- playwright_identity = page.locator(selector).first.evaluate(- "el => ({status: 'ok', id: el.id, tag: el.tagName})"- )- isolated_identity = page._stealth_world.evaluate(- _resolve_identity_js(selector)- )- assert playwright_identity["id"] == expected_id- assert isolated_identity == playwright_identity+ assert page.locator(selector).first.evaluate("el => el.id") == expected_id+ assert _clicked_id(page, selector) == expected_id, selectorfinally:browser.close()@@ -194,7 +155,6 @@ def test_text_selector_semantics_match_playwright():def test_structural_has_text_and_open_shadow_dom_match_playwright():"""Custom text pseudos keep their compound position and pierce open shadows."""from cloakbrowser import launch- from cloakbrowser.human.stealth_dom import build_snapshot_jsbrowser = launch(headless=False, humanize=True, release_channel="preview")try:@@ -231,17 +191,10 @@ def test_structural_has_text_and_open_shadow_dom_match_playwright():('article:has-text("Wanted") > button', "correct"),("#shadow-target", "shadow-target"),]+ page.evaluate(_RECORD_CLICKS)for selector, expected_id in cases:- playwright_identity = page.locator(selector).first.evaluate(- "el => ({status: 'ok', id: el.id, tag: el.tagName})"- )- isolated_identity = page._stealth_world.evaluate(- _resolve_identity_js(selector)- )- assert playwright_identity["id"] == expected_id- assert isolated_identity == playwright_identity-- page.click("#shadow-target", timeout=3000)+ assert page.locator(selector).first.evaluate("el => el.id") == expected_id+ assert _clicked_id(page, selector) == expected_id, selectorassert page._stealth_world.evaluate("document.body.dataset.shadowClicks") == "1"@@ -253,8 +206,9 @@ def test_structural_has_text_and_open_shadow_dom_match_playwright():) == "2"page.locator("#shadow-input").focus()- focused = page._stealth_world.evaluate(build_snapshot_js("#shadow-input"))- assert focused["focused"] is True+ assert page._stealth_world.evaluate(+ "document.querySelector('#shadow-host').shadowRoot.activeElement.id"+ ) == "shadow-input"finally:browser.close()@@ -292,10 +246,9 @@ def test_mixed_light_and_nested_shadow_order_matches_playwright():playwright_ids = page.locator("button").evaluate_all("elements => elements.map(element => element.id)")+ page.evaluate(_RECORD_CLICKS)isolated_ids = [- page._stealth_world.evaluate(- _resolve_identity_js(f"button >> nth={index}")- )["id"]+ _clicked_id(page, f"button >> nth={index}")for index in range(len(playwright_ids))]@@ -312,7 +265,7 @@ def test_mixed_light_and_nested_shadow_order_matches_playwright():def test_actionability_state_matches_playwright():"""Visibility, native disabled, and ARIA readonly semantics stay in parity."""from cloakbrowser import launch- from cloakbrowser.human.stealth_dom import build_snapshot_js+ from playwright.sync_api import TimeoutError as PwTimeoutbrowser = launch(headless=False, humanize=True, release_channel="preview")try:@@ -342,29 +295,13 @@ def test_actionability_state_matches_playwright():}""")- cases = [- ("#fieldset-input", ("visible", "enabled", "editable")),- ("#aria-button", ("visible", "enabled")),- ("#aria-readonly", ("visible", "enabled", "editable")),- ("#disabled-option", ("visible", "enabled")),- ("#display-contents", ("visible",)),- ("#content-hidden", ("visible",)),- ("#zero-width", ("visible",)),- ]- method_for = {- "visible": "is_visible",- "enabled": "is_enabled",- "editable": "is_editable",- }- for selector, fields in cases:- locator = page.locator(selector).first- isolated = page._stealth_world.evaluate(build_snapshot_js(selector))- assert isolated["r"] == "ok"- for field in fields:- expected = getattr(locator, method_for[field])()- assert isolated[field] is expected, (- selector, field, expected, isolated[field]- )+ # Humanized actions wait for the same states Playwright does.+ for selector in ("#fieldset-input", "#aria-button", "#content-hidden"):+ with pytest.raises(PwTimeout):+ page.click(selector, timeout=500)+ with pytest.raises(PwTimeout):+ page.fill("#aria-readonly", "x", timeout=500)+ page.click("#display-contents", timeout=3000)# Selector check state must come from the same isolated snapshot, not# Playwright's page.is_checked DOM read.@@ -372,8 +309,9 @@ def test_actionability_state_matches_playwright():AssertionError("page.is_checked must not be called"))page.check("#check-target", timeout=3000)- checked = page._stealth_world.evaluate(build_snapshot_js("#check-target"))- assert checked["checked"] is True+ assert page._stealth_world.evaluate(+ "document.querySelector('#check-target').checked"+ ) is Truecheckbox = page.locator("#check-target")checkbox.is_checked = lambda *args, **kwargs: (_ for _ in ()).throw(@@ -381,12 +319,12 @@ def test_actionability_state_matches_playwright():)checkbox.uncheck(timeout=3000)assert page._stealth_world.evaluate(- build_snapshot_js("#check-target")- )["checked"] is False+ "document.querySelector('#check-target').checked"+ ) is Falsecheckbox.set_checked(True, timeout=3000)assert page._stealth_world.evaluate(- build_snapshot_js("#check-target")- )["checked"] is True+ "document.querySelector('#check-target').checked"+ ) is Truefinally:browser.close()@@ -441,68 +379,54 @@ def test_force_click_keeps_identity_but_skips_coverage_rejection():def test_click_rejects_target_mutation_after_mouse_movement(monkeypatch, force, mutation,):- """Never dispatch to an underlying/replacement target after movement."""+ """Never dispatch to an underlying/stale target after movement.++ The page swaps the target while the cursor travels. The press must not+ land on what is under the cursor now: a removed target times out; a+ replaced target is re-resolved and reached with a fresh move, exactly+ like Playwright re-resolves locators.+ """from cloakbrowser import launch- import cloakbrowser.human as human- from cloakbrowser.human.actionability import (- ElementNotAttachedError, ElementTargetChangedError,- )+ from cloakbrowser.human.engine import Human+ from playwright.sync_api import TimeoutError as PwTimeout- browser = launch(headless=False, humanize=True, release_channel="preview")+ browser = launch(headless=True, humanize=True)try:page = browser.new_page()- page.goto("https://example.com", wait_until="domcontentloaded")- page.evaluate(- """() => {- document.body.innerHTML = `- <button id="underlying" style="position:absolute;left:20px;top:20px">- Underlying- </button>- <button id="target" style="position:absolute;left:20px;top:20px">- Original- </button>`;- document.body.dataset.underlyingClicks = '0';- document.body.dataset.replacementClicks = '0';- document.querySelector('#underlying').addEventListener('click', () => {- document.body.dataset.underlyingClicks = String(- Number(document.body.dataset.underlyingClicks) + 1- );- });- }"""- )-- def mutate_during_move(raw, start_x, start_y, end_x, end_y, cfg):- page._stealth_world.evaluate(- """((mutation) => {- const old = document.querySelector('#target');- if (mutation === 'remove') {- old.remove();- return;- }- const replacement = document.createElement('button');- replacement.id = 'target';- replacement.textContent = 'Replacement';- replacement.style.cssText = old.style.cssText;- replacement.addEventListener('click', () => {- document.body.dataset.replacementClicks = String(- Number(document.body.dataset.replacementClicks) + 1- );- });- old.replaceWith(replacement);- })""" + "(" + json.dumps(mutation) + ")"- )-- monkeypatch.setattr(human, "human_move", mutate_during_move)- with pytest.raises((ElementNotAttachedError, ElementTargetChangedError)):- page.click("#target", force=force, timeout=1000)-- click_counts = page._stealth_world.evaluate(- """(() => ({- underlying: document.body.dataset.underlyingClicks,- replacement: document.body.dataset.replacementClicks,- }))()"""- )- assert click_counts == {"underlying": "0", "replacement": "0"}+ page.evaluate("""() => {+ document.body.innerHTML = `+ <button id="underlying" style="position:absolute;left:20px;top:20px">Underlying</button>+ <button id="target" style="position:absolute;left:20px;top:20px">Original</button>`;+ window.counts = {underlying: 0, replacement: 0};+ document.querySelector('#underlying').onclick = () => counts.underlying++;+ }""")+ real_move = Human.move_to+ state = {"mutated": False}++ async def mutate_during_move(self, x, y, cfg):+ await real_move(self, x, y, cfg)+ if state["mutated"]:+ return+ state["mutated"] = True+ # Mutate from the page's own world, like a real page script would.+ await self.page.main_frame.evaluate("""(mutation) => {+ const old = document.querySelector('#target');+ if (mutation === 'remove') { old.remove(); return; }+ const r = document.createElement('button');+ r.id = 'target'; r.textContent = 'Replacement'; r.style.cssText = old.style.cssText;+ r.onclick = () => counts.replacement++;+ old.replaceWith(r);+ }""", mutation)++ monkeypatch.setattr(Human, "move_to", mutate_during_move)+ if mutation == "remove":+ with pytest.raises(PwTimeout):+ page.click("#target", force=force, timeout=1500)+ else:+ page.click("#target", force=force, timeout=3000)+ counts = page.evaluate("counts")+ assert counts["underlying"] == 0+ assert counts["replacement"] == (1 if mutation == "replace" else 0)finally:browser.close()@@ -510,47 +434,34 @@ def test_click_rejects_target_mutation_after_mouse_movement(@pytest.mark.slow@pytest.mark.asyncioasync def test_async_click_rejects_replacement_after_mouse_movement(monkeypatch):- """Async humanized clicks enforce the same exact-target invariant."""+ """Async: an ElementHandle whose element is replaced mid-move must fail+ (handles are not re-resolved), and nothing is clicked."""from cloakbrowser import launch_async- import cloakbrowser.human as human- from cloakbrowser.human.actionability import ElementTargetChangedError+ from cloakbrowser.human.engine import Human+ from playwright.async_api import Error as PwError- browser = await launch_async(- headless=False, humanize=True, release_channel="preview"- )+ browser = await launch_async(headless=True, humanize=True)try:page = await browser.new_page()- await page.goto("https://example.com", wait_until="domcontentloaded")- await page.evaluate(- """() => {- document.body.innerHTML = '<button id="target">Original</button>';- document.body.dataset.replacementClicks = '0';- }"""- )-- async def replace_during_move(raw, start_x, start_y, end_x, end_y, cfg):- await page._stealth_world.evaluate(- """(() => {- const old = document.querySelector('#target');- const replacement = document.createElement('button');- replacement.id = 'target';- replacement.textContent = 'Replacement';- replacement.addEventListener('click', () => {- document.body.dataset.replacementClicks = String(- Number(document.body.dataset.replacementClicks) + 1- );- });- old.replaceWith(replacement);- })()"""- )-- monkeypatch.setattr(human, "async_human_move", replace_during_move)- with pytest.raises(ElementTargetChangedError):- await page.click("#target", force=True, timeout=1000)-- assert await page._stealth_world.evaluate(- "document.body.dataset.replacementClicks"- ) == "0"+ await page.evaluate("""() => {+ document.body.innerHTML = '<button id="target">Original</button>';+ window.clicks = 0; document.addEventListener('click', () => clicks++, true);+ }""")+ handle = await page.query_selector("#target")+ real_move = Human.move_to++ async def replace_during_move(self, x, y, cfg):+ await real_move(self, x, y, cfg)+ await self.worlds.evaluate(self.page.main_frame, """(() => {+ const old = document.querySelector('#target');+ const r = document.createElement('button'); r.id = 'target'; r.textContent = 'Replacement';+ old.replaceWith(r);+ })()""")++ monkeypatch.setattr(Human, "move_to", replace_during_move)+ with pytest.raises(PwError, match="not attached"):+ await handle.click(force=True, timeout=1000)+ assert await page.evaluate("clicks") == 0finally:await browser.close()@@ -628,34 +539,18 @@ def test_get_by_engines_match_playwright():(page.get_by_label("Referenced Label"), "in4"),(page.get_by_label("Fallback Label"), "in5"),]+ page.evaluate(_RECORD_CLICKS)for locator, expected_id in cases:selector = locator._impl_obj._selector- playwright_identity = locator.first.evaluate(- "el => ({status: 'ok', id: el.id, tag: el.tagName})"- )- isolated_identity = page._stealth_world.evaluate(- _resolve_identity_js(selector)- )- assert playwright_identity["id"] == expected_id, selector- assert isolated_identity == playwright_identity, selector+ assert locator.first.evaluate("el => el.id") == expected_id, selector+ assert _clicked_id(page, locator.first) == expected_id, selector# A strict test id must not match by prefix, and a raw attribute value is# never trimmed -- both would be silent over-matches.assert page.get_by_test_id("submit").count() == 1assert page.get_by_title("Go", exact=True).count() == 0- assert page._stealth_world.evaluate(- _resolve_identity_js(- page.get_by_title("Go", exact=True)._impl_obj._selector- )- ) == {"status": "not_found"}- # End-to-end: a humanized click through a reimplemented engine.- page.get_by_test_id("submit").click()-- # get_by_role is deliberately still unsupported.- role_selector = page.get_by_role("button", name="Go Now")._impl_obj._selector- assert page._stealth_world.evaluate(- _resolve_identity_js(role_selector)- ) == {"status": "unsupported"}+ # get_by_role resolves through Playwright's own engine as well.+ assert _clicked_id(page, page.get_by_role("button", name="Go Now")) == "b2"finally:browser.close()diff --git a/tests/test_stealth_resolver_js.py b/tests/test_stealth_resolver_js.pydeleted file mode 100644index bfee2ce..0000000--- a/tests/test_stealth_resolver_js.py+++ /dev/null@@ -1,185 +0,0 @@-"""Resolver-JS selector-semantics tests.--``cloakbrowser/human/stealth_dom.py`` embeds a JavaScript selector resolver that-runs in the browser's isolated world. Its selector *semantics* (``:has-text``,-``text=``, ``xpath=``, trailing ``>> nth=N``, and the unsupported-grammar-fallback) can't be exercised from pure Python — they need a JS engine + DOM.--This test extracts the exact ``_RESOLVER_BODY`` string that ships and runs it-under Node against recording DOM stubs, asserting each selector routes to the-right engine / element (or reports ``unsupported``). Skipped when ``node`` is not-on PATH; CI has Node (the JS wrapper builds there).-"""-import shutil-import subprocess--import pytest--from cloakbrowser.human.stealth_dom import _RESOLVER_BODY--node = shutil.which("node")-pytestmark = pytest.mark.skipif(node is None, reason="node not on PATH")--# Harness: define the shipped resolver body, then drive __resolve() with a-# recording DOM. querySelectorAll/evaluate record their args and return-# caller-supplied matches, so we assert both the classification and the engine.-_HARNESS = r"""-const RESOLVER = %s;--function el(tag, text, kids, attrs){- attrs = attrs || {};- const e = {- tagName: tag, textContent: text || '', children: kids || [],- id: attrs.id || '', className: attrs.className || '', parentElement: null,- };- for (let i = 0; i < e.children.length; i++) {- e.children[i].parentElement = e;- e.children[i].previousElementSibling = i ? e.children[i - 1] : null;- }- e.contains = (o) => (o === e) || e.children.some(c => c.contains && c.contains(o));- e.matches = (s) => {- if (s === '*') return true;- const id = s.match(/#([\w-]+)/); if (id && e.id !== id[1]) return false;- const cls = s.match(/\.([\w-]+)/); if (cls && !e.className.split(/\s+/).includes(cls[1])) return false;- const tagMatch = s.match(/^[a-zA-Z][\w-]*/); if (tagMatch && e.tagName.toLowerCase() !== tagMatch[0].toLowerCase()) return false;- return true;- };- return e;-}--function run(sel, matches, xpathMatches){- const calls = { css: null, xpath: null };- const roots = (matches || []).filter(e => !e.parentElement);- const document = {- children: roots,- head: { contains(){ return false; } },- querySelectorAll(s){ calls.css = s; return (matches || []).slice(); },- evaluate(xp){ calls.xpath = xp; const m = xpathMatches || [];- return { snapshotLength: m.length, snapshotItem: i => m[i] }; },- };- const src = RESOLVER + `- return (function(){- const __SEL = ${JSON.stringify(sel)};- const el = __resolve(__SEL);- const cls = (el === 'UNSUPPORTED') ? 'unsupported' : (el === null ? 'not_found' : 'ok');- return { cls, text: el && el.textContent, tag: el && el.tagName, calls };- })();`;- return new Function('document', 'calls', 'XPathResult', src)(document, calls, { ORDERED_NODE_SNAPSHOT_TYPE: 7 });-}--let fails = 0;-function eq(name, got, want){- if (got !== want){ fails++; console.log('FAIL ' + name + ' | got ' + JSON.stringify(got) + ' want ' + JSON.stringify(want)); }-}--// :has-text on CSS, with trailing nth=0 (.first)-let r = run("button:has-text('Submit') >> nth=0", [ el('BUTTON','Submit'), el('BUTTON','other') ]);-eq('has-text cls', r.cls, 'ok'); eq('has-text picks match', r.text, 'Submit');--// :has-text stays attached to its compound before a combinator.-let correct = el('BUTTON','Go',[],{id:'correct'}); let wrong = el('BUTTON','Wanted',[],{id:'wrong'});-let wantedArticle = el('ARTICLE','Wanted',[correct]); let otherArticle = el('ARTICLE','Other Wanted',[wrong]);-r = run('article:has-text("Wanted") > button', [ wantedArticle, otherArticle ]);-eq('structural has-text target', r.text, 'Go');--// plain CSS + .first-let plainChild = el('SPAN','hi',[],{className:'c'}); let plainParent = el('DIV','hi',[plainChild],{id:'x'});-r = run('#x .c >> nth=0', [ plainParent ]); eq('plain css cls', r.cls, 'ok'); eq('plain css target', r.tag, 'SPAN');--// Playwright orders all light-DOM matches before open-shadow matches.-let shadowButton = el('BUTTON','shadow',[],{id:'shadow'});-let shadowHost = el('DIV','host',[],{id:'host'});-shadowHost.shadowRoot = { children: [shadowButton] };-let normalButton = el('BUTTON','normal',[],{id:'normal'});-r = run('button >> nth=0', [shadowHost, normalButton]);-eq('mixed shadow first', r.text, 'normal');-r = run('button >> nth=1', [shadowHost, normalButton]);-eq('mixed shadow second', r.text, 'shadow');--// chaining and the get_by_* engines we do NOT reimplement stay unsupported-eq('chaining', run('a >> b', [el('A')]).cls, 'unsupported');-eq('internal role', run('internal:role=button', []).cls, 'unsupported');-for (const sel of ['internal:has-text="Go"i', 'internal:has="x"', 'internal:and="x"',- 'internal:or="x"', 'internal:chain="x"', 'internal:control=enter-frame'])- eq('unsupported ' + sel, run(sel, []).cls, 'unsupported');--// Engines we DO reimplement route to their engine rather than bailing out.-// (Semantics live in the browser/stub tiers; el() has no childNodes, so text-// comparisons here cannot distinguish full-subtree from immediate fragments.)-eq('internal text routes', run('internal:text="Submit"s', [el('BUTTON','Submit')]).cls, 'ok');-eq('internal text lax routes', run('internal:text=submit', [el('BUTTON','Submit')]).cls, 'ok');-eq('internal text no match', run('internal:text="Nope"s', [el('BUTTON','Submit')]).cls, 'not_found');-// A single-quoted internal body reaches JSON.parse in Playwright and throws.-eq('internal text single quotes', run("internal:text='Submit'", [el('BUTTON','Submit')]).cls, 'unsupported');-// Malformed attribute bodies and unsupported operators are refused, not guessed.-for (const sel of ['internal:attr=[placeholder]', 'internal:attr=[placeholder*="a"]',- 'internal:attr=[placeholder=a]', 'internal:attr=placeholder="a"'])- eq('bad attr body ' + sel, run(sel, []).cls, 'unsupported');-// The '>>' guard runs first, so a quoted argument containing '>>' is refused-// (a documented, deliberate under-match) while a trailing nth= still works.-eq('internal text with >> in arg', run('internal:text="a >> b"i', []).cls, 'unsupported');-eq('internal chained', run('internal:text="a"i >> internal:text="b"i', []).cls, 'unsupported');-eq('internal text keeps nth', run('internal:text=submit >> nth=1',- [el('BUTTON','Submit'), el('BUTTON','Submit two')]).cls, 'ok');--// xpath (explicit prefix and leading //)-r = run('xpath=//button', [], [ el('BUTTON','x') ]); eq('xpath= cls', r.cls, 'ok'); eq('xpath= arg', r.calls.xpath, '//button');-eq('// route', run('//button', [], [ el('BUTTON','x') ]).cls, 'ok');--// text= engine picks the innermost matching element-let inner = el('SPAN','hi'); let outer = el('DIV','hi',[inner]);-r = run('text=hi', [ outer, inner ]); eq('text= cls', r.cls, 'ok'); eq('text= smallest', r.text, 'hi');-eq('text exact quoted case-sensitive miss', run('text="Hi"', [ el('DIV','hi') ]).cls, 'not_found');--// Playwright text extraction skips non-user-content elements.-r = run('text=Hoy', [ el('SCRIPT','Hoy'), el('LI','Hoy') ]);-eq('text skips script', r.cls, 'ok'); eq('text skips script target', r.tag, 'LI');--// Regex, button-like input values, and zero-width normalization.-eq('text regex', run('text=/^Alpha\\d+$/', [ el('BUTTON','Alpha42') ]).cls, 'ok');-let input = el('INPUT',''); input.type = 'button'; input.value = 'Submit Me';-eq('text input value', run('text=Submit Me', [ input ]).cls, 'ok');-eq('text zero width', run('text=foobar', [ el('BUTTON','foo\u200bbar') ]).cls, 'ok');--// :has-text with a regex arg is not reimplemented-eq('has-text regex', run(':has-text(/re/)', [ el('DIV','x') ]).cls, 'unsupported');--// multiple :has-text clauses AND together-r = run("div:has-text('a'):has-text('b')", [ el('DIV','a and b'), el('DIV','only a') ]);-eq('multi has-text cls', r.cls, 'ok'); eq('multi has-text match', r.text, 'a and b');--// nth variants-eq('.last (nth=-1)', run('button >> nth=-1', [ el('BUTTON','1'), el('BUTTON','2') ]).text, '2');-eq('nth=1', run('button >> nth=1', [ el('BUTTON','1'), el('BUTTON','2') ]).text, '2');--// css= prefix, selector lists, and genuine not-found-eq('css= prefix', run('css=button', [ el('BUTTON','1') ]).cls, 'ok');-r = run('button, a', [ el('A','first'), el('BUTTON','second') ]);-eq('selector list cls', r.cls, 'ok'); eq('selector list DOM order', r.tag, 'A');-eq('not found', run('button', []).cls, 'not_found');--// The world generation must fit an Int32: the .NET wrapper carries it as one,-// and an out-of-range value makes every .NET snapshot fail to parse (Snap()-// uses TryGetInt32, so an overflowing gen breaks every humanized .NET action).-const genOnce = new Function(RESOLVER + '\nreturn __state().gen;');-for (let i = 0; i < 200; i++) {- delete globalThis['__cloakHumanDomV1'];- const g = genOnce();- if (!(Number.isInteger(g) && g >= 0 && g <= 2147483647)) {- fails++; console.log('FAIL gen out of Int32 range | got ' + g);- break;- }-}-delete globalThis['__cloakHumanDomV1'];--if (fails) { console.log(fails + ' FAILED'); process.exit(1); }-console.log('ALL PASS');-"""---def test_resolver_selector_semantics():- import json- script = _HARNESS % json.dumps(_RESOLVER_BODY)- result = subprocess.run([node, "-e", script], capture_output=True, text=True, timeout=30)- assert result.returncode == 0, f"resolver JS failed:\n{result.stdout}\n{result.stderr}"- assert "ALL PASS" in result.stdoutdiff --git a/tests/test_stealth_unit.py b/tests/test_stealth_unit.pyindex 224141c..3d63ffe 100644--- a/tests/test_stealth_unit.py+++ b/tests/test_stealth_unit.py@@ -20,7 +20,6 @@ import timeimport pytestfrom unittest.mock import MagicMock, AsyncMock, patch as mock_patch, call-from cloakbrowser.human.stealth_dom import PROTOCOL_VERSION# =========================================================================@@ -36,423 +35,16 @@ def _cfg(**overrides):# 12. _SyncIsolatedWorld# =========================================================================-class TestSyncIsolatedWorld:- """Tests for the synchronous CDP isolated-world wrapper."""-- def _make_world(self, cdp_send_side_effect=None):- """Return (_SyncIsolatedWorld, mock_page, mock_cdp)."""- from cloakbrowser.human import _SyncIsolatedWorld-- mock_cdp = MagicMock()- mock_cdp.send = MagicMock(side_effect=cdp_send_side_effect)-- mock_context = MagicMock()- mock_context.new_cdp_session = MagicMock(return_value=mock_cdp)-- mock_page = MagicMock()- mock_page.context = mock_context-- world = _SyncIsolatedWorld(mock_page)- return world, mock_page, mock_cdp-- def test_initial_state(self):- from cloakbrowser.human import _SyncIsolatedWorld- page = MagicMock()- w = _SyncIsolatedWorld(page)- assert w._cdp is None- assert w._context_id is None-- def test_evaluate_creates_world_and_returns_value(self):- """First evaluate() should create CDP session → isolated world → Runtime.evaluate."""- call_counter = {"n": 0}-- def cdp_send(method, params=None):- call_counter["n"] += 1- if method == "Page.getFrameTree":- return {"frameTree": {"frame": {"id": "F1"}}}- if method == "Page.createIsolatedWorld":- return {"executionContextId": 42}- if method == "Runtime.evaluate":- return {"result": {"value": True}}- return {}-- world, page, cdp = self._make_world(cdp_send_side_effect=cdp_send)- result = world.evaluate("1 + 1")-- assert result is True- assert world._context_id == 42- assert world._cdp is not None-- def test_evaluate_caches_context_id(self):- """Second evaluate() reuses cached context_id — no second createIsolatedWorld."""- create_calls = {"n": 0}-- def cdp_send(method, params=None):- if method == "Page.getFrameTree":- return {"frameTree": {"frame": {"id": "F1"}}}- if method == "Page.createIsolatedWorld":- create_calls["n"] += 1- return {"executionContextId": 99}- if method == "Runtime.evaluate":- return {"result": {"value": "ok"}}- return {}-- world, _, _ = self._make_world(cdp_send_side_effect=cdp_send)- world.evaluate("a")- world.evaluate("b")-- assert create_calls["n"] == 1 # world created only once-- def test_evaluate_retries_on_exception_details(self):- """If Runtime.evaluate returns exceptionDetails, recreate world and retry."""- attempt = {"n": 0}-- def cdp_send(method, params=None):- if method == "Page.getFrameTree":- return {"frameTree": {"frame": {"id": "F1"}}}- if method == "Page.createIsolatedWorld":- return {"executionContextId": 50 + attempt["n"]}- if method == "Runtime.evaluate":- attempt["n"] += 1- if attempt["n"] == 1:- return {"exceptionDetails": {"text": "stale"}}- return {"result": {"value": "recovered"}}- return {}-- world, _, _ = self._make_world(cdp_send_side_effect=cdp_send)- result = world.evaluate("test")- assert result == "recovered"-- def test_evaluate_retries_on_cdp_exception(self):- """If cdp.send raises, recreate world and retry."""- attempt = {"n": 0}-- def cdp_send(method, params=None):- if method == "Page.getFrameTree":- return {"frameTree": {"frame": {"id": "F1"}}}- if method == "Page.createIsolatedWorld":- return {"executionContextId": 60 + attempt["n"]}- if method == "Runtime.evaluate":- attempt["n"] += 1- if attempt["n"] == 1:- raise Exception("Target closed")- return {"result": {"value": "ok"}}- return {}-- world, _, _ = self._make_world(cdp_send_side_effect=cdp_send)- result = world.evaluate("test")- assert result == "ok"-- def test_evaluate_returns_none_after_double_failure(self):- """If both attempts fail, evaluate returns None."""- def cdp_send(method, params=None):- if method == "Page.getFrameTree":- return {"frameTree": {"frame": {"id": "F1"}}}- if method == "Page.createIsolatedWorld":- return {"executionContextId": 70}- if method == "Runtime.evaluate":- return {"exceptionDetails": {"text": "always broken"}}- return {}-- world, _, _ = self._make_world(cdp_send_side_effect=cdp_send)- result = world.evaluate("broken")- assert result is None-- def test_invalidate_resets_context_id(self):- """invalidate() sets _context_id to None."""- def cdp_send(method, params=None):- if method == "Page.getFrameTree":- return {"frameTree": {"frame": {"id": "F1"}}}- if method == "Page.createIsolatedWorld":- return {"executionContextId": 80}- if method == "Runtime.evaluate":- return {"result": {"value": "val"}}- return {}-- world, _, _ = self._make_world(cdp_send_side_effect=cdp_send)- world.evaluate("x")- assert world._context_id == 80-- world.invalidate()- assert world._context_id is None-- def test_get_cdp_session_creates_and_caches(self):- """get_cdp_session() creates and caches the CDP session."""- world, page, cdp = self._make_world()- session = world.get_cdp_session()- assert session is cdp- # Second call returns same session- session2 = world.get_cdp_session()- assert session2 is session-- def test_evaluate_returns_none_when_create_world_fails_on_retry(self):- """If _create_world fails during retry, return None gracefully."""- attempt = {"n": 0}-- def cdp_send(method, params=None):- if method == "Page.getFrameTree":- if attempt["n"] > 0:- raise Exception("Frame tree gone")- return {"frameTree": {"frame": {"id": "F1"}}}- if method == "Page.createIsolatedWorld":- return {"executionContextId": 90}- if method == "Runtime.evaluate":- attempt["n"] += 1- raise Exception("Fail")- return {}-- world, _, _ = self._make_world(cdp_send_side_effect=cdp_send)- result = world.evaluate("test")- assert result is None-# =========================================================================# 13. _AsyncIsolatedWorld# =========================================================================-class TestAsyncIsolatedWorld:- """Tests for the async CDP isolated-world wrapper."""-- def _make_world(self, cdp_send_side_effect=None):- from cloakbrowser.human import _AsyncIsolatedWorld-- mock_cdp = MagicMock()- if cdp_send_side_effect:- mock_cdp.send = AsyncMock(side_effect=cdp_send_side_effect)- else:- mock_cdp.send = AsyncMock()-- mock_context = MagicMock()- mock_context.new_cdp_session = AsyncMock(return_value=mock_cdp)-- mock_page = MagicMock()- mock_page.context = mock_context-- world = _AsyncIsolatedWorld(mock_page)- return world, mock_page, mock_cdp-- @pytest.mark.asyncio- async def test_initial_state(self):- from cloakbrowser.human import _AsyncIsolatedWorld- page = MagicMock()- w = _AsyncIsolatedWorld(page)- assert w._cdp is None- assert w._context_id is None-- @pytest.mark.asyncio- async def test_evaluate_creates_world_and_returns_value(self):- def cdp_send(method, params=None):- if method == "Page.getFrameTree":- return {"frameTree": {"frame": {"id": "AF1"}}}- if method == "Page.createIsolatedWorld":- return {"executionContextId": 142}- if method == "Runtime.evaluate":- return {"result": {"value": True}}- return {}-- world, _, _ = self._make_world(cdp_send_side_effect=cdp_send)- result = await world.evaluate("async test")- assert result is True- assert world._context_id == 142-- @pytest.mark.asyncio- async def test_evaluate_retries_on_exception_details(self):- attempt = {"n": 0}-- def cdp_send(method, params=None):- if method == "Page.getFrameTree":- return {"frameTree": {"frame": {"id": "AF1"}}}- if method == "Page.createIsolatedWorld":- return {"executionContextId": 150 + attempt["n"]}- if method == "Runtime.evaluate":- attempt["n"] += 1- if attempt["n"] == 1:- return {"exceptionDetails": {"text": "stale"}}- return {"result": {"value": "async_recovered"}}- return {}-- world, _, _ = self._make_world(cdp_send_side_effect=cdp_send)- result = await world.evaluate("test")- assert result == "async_recovered"-- @pytest.mark.asyncio- async def test_invalidate_and_recreate(self):- create_count = {"n": 0}-- def cdp_send(method, params=None):- if method == "Page.getFrameTree":- return {"frameTree": {"frame": {"id": "AF1"}}}- if method == "Page.createIsolatedWorld":- create_count["n"] += 1- return {"executionContextId": 200 + create_count["n"]}- if method == "Runtime.evaluate":- return {"result": {"value": "ok"}}- return {}-- world, _, _ = self._make_world(cdp_send_side_effect=cdp_send)-- await world.evaluate("first")- assert create_count["n"] == 1-- world.invalidate()- assert world._context_id is None-- await world.evaluate("second")- assert create_count["n"] == 2 # recreated-- @pytest.mark.asyncio- async def test_get_cdp_session_async(self):- world, page, cdp = self._make_world()- session = await world.get_cdp_session()- assert session is cdp-# =========================================================================# 14. _is_input_element stealth# =========================================================================-def _snapshot_payload(**overrides):- payload = {- "v": PROTOCOL_VERSION, "r": "ok", "targetId": 1, "gen": 1,- "isInput": False, "focused": False,- }- payload.update(overrides)- return payload---class TestIsInputElementStealth:- def test_uses_canonical_isolated_snapshot(self):- from cloakbrowser.human import _is_input_element-- mock_world = MagicMock()- mock_world.evaluate.return_value = _snapshot_payload(isInput=True)- page = MagicMock(_stealth_world=mock_world)-- assert _is_input_element(page, "text=Submit") is True- mock_world.evaluate.assert_called_once()- page.evaluate.assert_not_called()-- def test_returns_false_for_non_input_and_escapes_selector(self):- from cloakbrowser.human import _is_input_element-- mock_world = MagicMock()- mock_world.evaluate.return_value = _snapshot_payload(isInput=False)- page = MagicMock(_stealth_world=mock_world)- selector = 'input[name="email"]'-- assert _is_input_element(page, selector) is False- assert json.dumps(selector) in mock_world.evaluate.call_args.args[0]-- def test_no_world_raises_without_page_evaluate(self):- from cloakbrowser.human import _is_input_element- from cloakbrowser.human.stealth_dom import StealthWorldUnavailableError-- page = MagicMock(_stealth_world=None)- with pytest.raises(StealthWorldUnavailableError):- _is_input_element(page, "#inp")- page.evaluate.assert_not_called()-- def test_evaluation_failure_raises_without_fallback(self):- from cloakbrowser.human import _is_input_element- from cloakbrowser.human.stealth_dom import StealthEvaluationError-- mock_world = MagicMock()- mock_world.evaluate.side_effect = Exception("CDP gone")- page = MagicMock(_stealth_world=mock_world)- with pytest.raises(StealthEvaluationError):- _is_input_element(page, "#inp")- page.evaluate.assert_not_called()---class TestAsyncIsInputElementStealth:- @pytest.mark.asyncio- async def test_uses_canonical_isolated_snapshot(self):- from cloakbrowser.human import _async_is_input_element-- mock_world = MagicMock()- mock_world.evaluate = AsyncMock(- return_value=_snapshot_payload(isInput=True)- )- page = MagicMock(_stealth_world=mock_world)- page.evaluate = AsyncMock()-- assert await _async_is_input_element(page, "text=Submit") is True- page.evaluate.assert_not_called()-- @pytest.mark.asyncio- async def test_evaluation_failure_raises_without_fallback(self):- from cloakbrowser.human import _async_is_input_element- from cloakbrowser.human.stealth_dom import StealthEvaluationError-- mock_world = MagicMock()- mock_world.evaluate = AsyncMock(side_effect=Exception("dead"))- page = MagicMock(_stealth_world=mock_world)- page.evaluate = AsyncMock()- with pytest.raises(StealthEvaluationError):- await _async_is_input_element(page, "#inp")- page.evaluate.assert_not_called()---class TestIsSelectorFocusedStealth:- def test_uses_canonical_isolated_snapshot(self):- from cloakbrowser.human import _is_selector_focused-- mock_world = MagicMock()- mock_world.evaluate.return_value = _snapshot_payload(focused=True)- page = MagicMock(_stealth_world=mock_world)-- assert _is_selector_focused(page, "text=Field") is True- page.evaluate.assert_not_called()-- def test_returns_false_when_not_focused(self):- from cloakbrowser.human import _is_selector_focused-- mock_world = MagicMock()- mock_world.evaluate.return_value = _snapshot_payload(focused=False)- page = MagicMock(_stealth_world=mock_world)- assert _is_selector_focused(page, "#field") is False-- def test_failure_is_explicit_without_fallback(self):- from cloakbrowser.human import _is_selector_focused- from cloakbrowser.human.stealth_dom import StealthEvaluationError-- mock_world = MagicMock()- mock_world.evaluate.side_effect = Exception("gone")- page = MagicMock(_stealth_world=mock_world)- with pytest.raises(StealthEvaluationError):- _is_selector_focused(page, "#field")- page.evaluate.assert_not_called()---class TestAsyncIsSelectorFocusedStealth:- @pytest.mark.asyncio- async def test_uses_canonical_isolated_snapshot(self):- from cloakbrowser.human import _async_is_selector_focused-- mock_world = MagicMock()- mock_world.evaluate = AsyncMock(- return_value=_snapshot_payload(focused=True)- )- page = MagicMock(_stealth_world=mock_world)- page.evaluate = AsyncMock()-- assert await _async_is_selector_focused(page, "#field") is True- page.evaluate.assert_not_called()-- @pytest.mark.asyncio- async def test_failure_is_explicit_without_fallback(self):- from cloakbrowser.human import _async_is_selector_focused- from cloakbrowser.human.stealth_dom import StealthEvaluationError-- mock_world = MagicMock()- mock_world.evaluate = AsyncMock(side_effect=Exception("dead"))- page = MagicMock(_stealth_world=mock_world)- page.evaluate = AsyncMock()- with pytest.raises(StealthEvaluationError):- await _async_is_selector_focused(page, "#field")- page.evaluate.assert_not_called()--# =========================================================================# 16. Shift symbol CDP stealth path (sync)# =========================================================================@@ -675,261 +267,16 @@ class TestHumanTypeShiftCDP:# 17. Shift symbol CDP stealth path (async)# =========================================================================-class TestShiftSymbolCDPAsync:-- @pytest.mark.asyncio- async def test_cdp_path_sends_events_async(self):- from cloakbrowser.human.keyboard_async import _type_shift_symbol- from cloakbrowser.human.keyboard import _SHIFT_SYMBOL_CODES, _SHIFT_SYMBOL_KEYCODES-- cfg = _cfg()- page = MagicMock()- raw = MagicMock()- raw.down = AsyncMock()- raw.up = AsyncMock()- raw.insert_text = AsyncMock()-- cdp_calls = []- cdp_session = MagicMock()- cdp_session.send = AsyncMock(side_effect=lambda m, p: cdp_calls.append((m, p)))-- await _type_shift_symbol(page, raw, "@", cfg, cdp_session=cdp_session)-- raw.down.assert_any_call("Shift")- raw.up.assert_any_call("Shift")-- assert len(cdp_calls) == 2- assert cdp_calls[0][1]["type"] == "keyDown"- assert cdp_calls[0][1]["key"] == "@"- assert cdp_calls[1][1]["type"] == "keyUp"-- @pytest.mark.asyncio- async def test_cdp_path_no_evaluate_async(self):- from cloakbrowser.human.keyboard_async import _type_shift_symbol-- cfg = _cfg()- page = MagicMock()- page.evaluate = AsyncMock()- raw = MagicMock()- raw.down = AsyncMock()- raw.up = AsyncMock()- cdp_session = MagicMock()- cdp_session.send = AsyncMock()-- await _type_shift_symbol(page, raw, "#", cfg, cdp_session=cdp_session)-- page.evaluate.assert_not_called()-- @pytest.mark.asyncio- async def test_fallback_path_async(self):- from cloakbrowser.human.keyboard_async import _type_shift_symbol-- cfg = _cfg()- page = MagicMock()- page.evaluate = AsyncMock()- raw = MagicMock()- raw.down = AsyncMock()- raw.up = AsyncMock()- raw.insert_text = AsyncMock()-- await _type_shift_symbol(page, raw, "$", cfg, cdp_session=None)-- page.evaluate.assert_called_once()- raw.insert_text.assert_called_once_with("$")-- @pytest.mark.asyncio- async def test_async_human_type_routes_via_cdp(self):- from cloakbrowser.human.keyboard_async import async_human_type-- cfg = _cfg(mistype_chance=0)- page = MagicMock()- page.evaluate = AsyncMock()- raw = MagicMock()- raw.down = AsyncMock()- raw.up = AsyncMock()- raw.insert_text = AsyncMock()-- cdp_calls = []- cdp_session = MagicMock()- cdp_session.send = AsyncMock(side_effect=lambda m, p: cdp_calls.append((m, p)))-- await async_human_type(page, raw, "test!", cfg, cdp_session=cdp_session)-- page.evaluate.assert_not_called()- # Only '!' should trigger CDP calls (2 events)- assert len(cdp_calls) == 2-# =========================================================================# 18. Navigation invalidation# =========================================================================-class TestNavigationInvalidation:- """Tests that goto invalidates the isolated world context."""-- def test_goto_invalidates_stealth_world_sync(self):- from cloakbrowser.human import patch_page, _CursorState- from cloakbrowser.human.config import resolve_config-- cfg = resolve_config("default")- cursor = _CursorState()-- page = MagicMock()- page.mouse = MagicMock()- page.keyboard = MagicMock()- page.context = MagicMock()- page.main_frame = MagicMock(return_value=MagicMock(child_frames=[]))- page.frames = MagicMock(return_value=[])-- # Make CDP session creation succeed- mock_cdp = MagicMock()- mock_cdp.send = MagicMock(side_effect=lambda m, p=None: {- "Page.getFrameTree": {"frameTree": {"frame": {"id": "F1"}}},- "Page.createIsolatedWorld": {"executionContextId": 500},- }.get(m, {}))- page.context.new_cdp_session = MagicMock(return_value=mock_cdp)-- patch_page(page, cfg, cursor)-- # Get reference to stealth world- stealth_world = page._stealth_world- assert stealth_world is not None-- # Warm up the context_id- stealth_world._context_id = 500-- # Call patched goto- orig_goto = page._original.goto- orig_goto.return_value = MagicMock() # response object- page.goto("https://example.com")-- # After goto, context_id should be invalidated- assert stealth_world._context_id is None-# =========================================================================# 19. patch_page stealth infrastructure wiring# =========================================================================-class TestPatchPageStealthWiring:- """Tests that patch_page creates and attaches stealth infrastructure."""-- def _make_mock_page(self):- page = MagicMock()- page.mouse = MagicMock()- page.keyboard = MagicMock()- page.context = MagicMock()- page.main_frame = MagicMock(return_value=MagicMock(child_frames=[]))- page.frames = MagicMock(return_value=[])-- mock_cdp = MagicMock()- mock_cdp.send = MagicMock(return_value={})- page.context.new_cdp_session = MagicMock(return_value=mock_cdp)-- return page, mock_cdp-- def test_patch_page_sets_stealth_world(self):- from cloakbrowser.human import patch_page, _CursorState, _SyncIsolatedWorld-- page, cdp = self._make_mock_page()- cfg = _cfg()- cursor = _CursorState()-- patch_page(page, cfg, cursor)-- assert hasattr(page, '_stealth_world')- assert isinstance(page._stealth_world, _SyncIsolatedWorld)-- def test_patch_page_sets_original(self):- from cloakbrowser.human import patch_page, _CursorState-- page, _ = self._make_mock_page()- cfg = _cfg()- cursor = _CursorState()-- patch_page(page, cfg, cursor)-- assert hasattr(page, '_original')- assert hasattr(page, '_human_cfg')- assert page._human_cfg is cfg-- def test_stealth_world_none_when_cdp_fails(self):- """If CDP session creation fails, stealth_world should be None."""- from cloakbrowser.human import patch_page, _CursorState-- page = MagicMock()- page.mouse = MagicMock()- page.keyboard = MagicMock()- page.context = MagicMock()- page.context.new_cdp_session = MagicMock(side_effect=Exception("no CDP"))- page.main_frame = MagicMock(return_value=MagicMock(child_frames=[]))- page.frames = MagicMock(return_value=[])-- cfg = _cfg()- cursor = _CursorState()-- patch_page(page, cfg, cursor)-- assert page._stealth_world is None-- def test_click_passes_through_stealth_dom_query(self):- """Verify that patched click() calls _is_input_element which uses _stealth_world.-- We mock scroll_to_element to bypass viewport/scrolling complexity,- then intercept CDP send() to verify Runtime.evaluate is called in- the isolated world for the isInputElement DOM query.- """- from cloakbrowser.human import patch_page, _CursorState-- # Track all cdp.send() calls- runtime_eval_expressions: list[str] = []-- def tracking_cdp_send(method, params=None):- if method == "Page.getFrameTree":- return {"frameTree": {"frame": {"id": "F1"}}}- if method == "Page.createIsolatedWorld":- return {"executionContextId": 300}- if method == "Runtime.evaluate":- runtime_eval_expressions.append(params.get("expression", ""))- return {"result": {"value": False}} # not an input element- return {}-- page, _ = self._make_mock_page()- cfg = _cfg(idle_between_actions=False)- cursor = _CursorState()-- # Wire up the tracking CDP mock- mock_cdp = MagicMock()- mock_cdp.send = MagicMock(side_effect=tracking_cdp_send)- page.context.new_cdp_session = MagicMock(return_value=mock_cdp)-- patch_page(page, cfg, cursor)-- stealth_world = page._stealth_world- assert stealth_world is not None-- # Mock scroll_to_element to bypass all scrolling logic and return- # a bounding box immediately — this lets click() proceed to- # _is_input_element without getting stuck in viewport checks.- fake_box = {"x": 100, "y": 200, "width": 200, "height": 30}- with mock_patch(- "cloakbrowser.human.scroll_to_element",- return_value=(fake_box, 200.0, 215.0, False),- ), mock_patch(- "cloakbrowser.human.ensure_actionable",- ), mock_patch(- "cloakbrowser.human.check_pointer_events",- ):- try:- page.click("#btn")- except Exception:- pass-- # The isolated world should have been used for the isInputElement check.- # Runtime.evaluate calls from the isolated world contain querySelector + tagName.- assert len(runtime_eval_expressions) >= 1- assert any("tagName" in expr or "querySelector" in expr for expr in runtime_eval_expressions)-# =========================================================================# 20. SHIFT_SYMBOL_CODES / SHIFT_SYMBOL_KEYCODES correctness@@ -1002,46 +349,6 @@ class TestCDPModifiers:# 22. Isolated world expression injection safety# =========================================================================-class TestIsolatedWorldSafety:- """Ensure selectors are properly escaped in JS expressions."""-- def test_selector_with_quotes_is_escaped(self):- from cloakbrowser.human import _is_input_element-- mock_world = MagicMock()- calls = []- mock_world.evaluate = MagicMock(- side_effect=lambda expr: calls.append(expr) or _snapshot_payload()- )-- page = MagicMock()- page._stealth_world = mock_world-- dangerous_selector = 'input[data-x="\\");alert(1)//"]'- _is_input_element(page, dangerous_selector)-- assert len(calls) == 1- # The expression should contain JSON-escaped selector- escaped = json.dumps(dangerous_selector)- assert escaped in calls[0]-- def test_selector_with_backticks_escaped(self):- from cloakbrowser.human import _is_selector_focused-- mock_world = MagicMock()- calls = []- mock_world.evaluate = MagicMock(- side_effect=lambda expr: calls.append(expr) or _snapshot_payload()- )-- page = MagicMock()- page._stealth_world = mock_world-- _is_selector_focused(page, "div[class=`test`]")-- assert len(calls) == 1- assert json.dumps("div[class=`test`]") in calls[0]-# =========================================================================# SLOW TESTS — require browser (skipped in CI unless pytest -m slow)@@ -1302,7 +609,8 @@ class TestStealthBrowserReal:assert len(eval_leaks) == 0, f"Evaluate leaks: {eval_leaks}"assert len(untrusted) == 0, f"Untrusted key events: {untrusted}"- await page.locator('button[type="submit"]').click()+ # Strict mode (like Playwright): this page has two submit buttons.+ await page.get_by_role('button', name='Login').click()await asyncio.sleep(5)body = await page.locator('body').text_content()