use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, MutexGuard, OnceLock};
use serde_json::{json, Value};
use super::{Action, ActionOptions, ActionReceipt, LocatorQuery, LocatorSpec};
use crate::util::LockExt;
use crate::{cdp::Session, error::classify, Element, Error, ErrorCode, Page, Result};
/// A read-only observation of a resolved control, without its input value.
#[derive(Debug, Clone)]
pub struct ControlState {
/// Whether the node is attached to the document.
pub connected: bool,
/// Whether the node is rendered and visible.
pub visible: bool,
/// Whether the node is not disabled.
pub enabled: bool,
}
/// A lazy query bound to a page; it holds no cached DOM node.
#[derive(Clone)]
pub struct Locator {
pub(crate) page: Page,
pub(crate) spec: LocatorSpec,
}
impl Locator {
/// Inspect the current match without dispatching input or generating a selector.
pub async fn state(&self) -> Result<Option<ControlState>> {
let Some(node) = resolve(&self.page, &self.spec).await? else {
return Ok(None);
};
let properties = node.properties().await?;
Ok(Some(ControlState {
connected: properties["connected"] == true,
visible: properties["visible"] == true,
enabled: properties["disabled"] != true,
}))
}
/// Explicitly select the first matching element.
pub fn first(self) -> Self {
self.nth(0)
}
/// Explicitly select a zero-based match.
pub fn nth(mut self, index: usize) -> Self {
self.spec.index = Some(index);
self
}
/// Restrict resolution to a pinned frame identifier.
pub fn in_frame(mut self, frame_id: impl Into<String>) -> Self {
self.spec.frame_id = Some(frame_id.into());
self
}
/// Return the serializable query.
pub fn specification(&self) -> LocatorSpec {
self.spec.clone()
}
/// Click once and verify the supplied completion condition.
pub async fn click(&self, options: ActionOptions) -> Result<ActionReceipt> {
self.run(Action::click(self.spec.clone(), false), options)
.await
}
/// Replace and verify the target value.
pub async fn fill(&self, value: &str, options: ActionOptions) -> Result<ActionReceipt> {
self.run(Action::fill(self.spec.clone(), value), options)
.await
}
/// Set and verify selected option values.
pub async fn select(
&self,
values: Vec<String>,
options: ActionOptions,
) -> Result<ActionReceipt> {
self.run(
Action::Select {
target: self.spec.clone(),
values,
},
options,
)
.await
}
/// Double-click and verify the supplied completion condition.
pub async fn double_click(&self, options: ActionOptions) -> Result<ActionReceipt> {
self.run(
Action::Click {
target: self.spec.clone(),
human: false,
double: true,
},
options,
)
.await
}
/// Move the pointer over the target and verify hover.
pub async fn hover(&self, options: ActionOptions) -> Result<ActionReceipt> {
self.run(Action::hover(self.spec.clone()), options).await
}
/// Focus the target and type without clearing; verify the supplied condition.
pub async fn type_text(&self, text: &str, options: ActionOptions) -> Result<ActionReceipt> {
self.run(Action::type_text(self.spec.clone(), text), options)
.await
}
/// Focus the target and verify focus.
pub async fn focus(&self, options: ActionOptions) -> Result<ActionReceipt> {
self.run(
Action::Focus {
target: self.spec.clone(),
},
options,
)
.await
}
/// Focus the target, press Enter and verify the supplied condition.
pub async fn submit(&self, options: ActionOptions) -> Result<ActionReceipt> {
self.run(
Action::Submit {
target: self.spec.clone(),
},
options,
)
.await
}
/// Scroll the target into the viewport and verify it is there.
pub async fn scroll_into_view(&self, options: ActionOptions) -> Result<ActionReceipt> {
self.run(
Action::ScrollIntoView {
target: self.spec.clone(),
},
options,
)
.await
}
async fn run(&self, action: Action, options: ActionOptions) -> Result<ActionReceipt> {
self.page.act(action, options).await
}
/// Set and verify the uploaded files.
pub async fn upload(
&self,
files: Vec<String>,
options: ActionOptions,
) -> Result<ActionReceipt> {
self.run(
Action::Upload {
target: self.spec.clone(),
files,
},
options,
)
.await
}
}
impl Page {
/// Create a lazy CSS locator requiring a unique match.
pub fn locator(&self, selector: &str) -> Locator {
self.locator_spec(LocatorSpec::css(selector))
}
/// Create a lazy, case-insensitive text locator.
pub fn locator_text(&self, text: &str) -> Locator {
self.locator_spec(LocatorSpec::text(text))
}
/// Bind a serializable locator to this page.
pub fn locator_spec(&self, spec: LocatorSpec) -> Locator {
Locator {
page: self.clone(),
spec,
}
}
}
pub(super) fn call_value(result: &Value) -> Result<Value> {
if let Some(exception) = result.get("exceptionDetails").filter(|v| !v.is_null()) {
return Err(Error::javascript_exception(exception));
}
Ok(result["result"]["value"].clone())
}
pub(super) struct Node {
pub session: Session,
pub object: String,
pub frame_id: Option<String>,
group: String,
attached: bool,
hover_observer: Option<String>,
}
impl Node {
pub(super) fn call_params(&self, body: &str, args: Vec<Value>) -> Value {
json!({
"objectId":self.object, "functionDeclaration":body,
"arguments":args.into_iter().map(|value| json!({"value":value})).collect::<Vec<_>>(),
"returnByValue":true, "awaitPromise":true,
})
}
pub(super) async fn call(&self, body: &str, args: Vec<Value>) -> Result<Value> {
let result: Value = self
.session
.send("Runtime.callFunctionOn", &self.call_params(body, args))
.await?;
call_value(&result)
}
pub(super) fn property(properties: &Value, field: &str) -> Value {
let mut actual = properties[field].clone();
if field == "selected" {
if let Some(values) = actual.as_array_mut() {
values.sort_by(|a, b| a.as_str().cmp(&b.as_str()));
}
}
actual
}
pub(super) async fn properties(&self) -> Result<Value> {
let mut properties = self.call(include_str!("properties.js"), vec![]).await?;
if let Some(observer) = &self.hover_observer {
let result: Value = self.session.send("Runtime.callFunctionOn", &json!({"objectId":observer,"functionDeclaration":"function(){return this.seen}","returnByValue":true})).await?;
properties["hovered"] = result["result"]["value"].clone();
}
Ok(properties)
}
pub(super) async fn arm_hover(&mut self) -> Result<()> {
let result: Value = self.session.send("Runtime.callFunctionOn", &json!({"objectId":self.object,"objectGroup":self.group,"returnByValue":false,
"functionDeclaration":"function(){const target=this;const state={seen:false};const doc=this.ownerDocument;const handler=e=>{if(e.isTrusted && (e.target===target || target.contains(e.target))){state.seen=true;state.dispose()}};const timer=setTimeout(()=>state.dispose(),30000);state.dispose=()=>{clearTimeout(timer);doc.removeEventListener('mousemove',handler,true);doc.removeEventListener('mouseover',handler,true)};doc.addEventListener('mousemove',handler,true);doc.addEventListener('mouseover',handler,true);return state}"})).await?;
self.hover_observer = Some(
result["result"]["objectId"]
.as_str()
.ok_or_else(|| Error::cdp_msg("Could not arm hover observation"))?
.into(),
);
Ok(())
}
}
impl Drop for Node {
fn drop(&mut self) {
let session = self.session.clone();
let group = std::mem::take(&mut self.group);
let attached = self.attached;
let observer = self.hover_observer.take();
crate::util::spawn_detached(async move {
let _ = tokio::time::timeout(std::time::Duration::from_secs(2), async {
if let Some(observer)=observer {
let _=session.send::<_,Value>("Runtime.callFunctionOn",&json!({"objectId":observer,"functionDeclaration":"function(){this.dispose()}"})).await;
}
let _ = session
.send::<_, Value>(
"Runtime.releaseObjectGroup",
&json!({"objectGroup":group}),
)
.await;
if attached {
let _ = session.detach().await;
}
})
.await;
});
}
}
pub(crate) async fn is_visible(page: &Page, spec: &LocatorSpec) -> Result<bool> {
let Some(node) = resolve(page, spec).await? else {
return Ok(false);
};
Ok(node.properties().await?["visible"] == true)
}
/// Calls `body` on the element `spec` pins, in the isolated world, and
/// returns its result by value. A node removed from the document can still be
/// read. The node's object group is released on drop.
pub(crate) async fn call_on(
page: &Page,
spec: &LocatorSpec,
body: &str,
args: Vec<Value>,
) -> Result<Value> {
let params = pinned(spec).ok_or_else(|| Error::cdp_msg("element reads need a pinned node"))?;
resolve_pinned(page, spec, params, false)
.await?
.call(body, args)
.await
}
/// `spec` with an explicit first index, so several matches are not ambiguous.
fn first(mut spec: LocatorSpec) -> LocatorSpec {
spec.index = Some(0);
spec
}
/// The first element `spec` matches, without the strict-uniqueness check.
pub(crate) async fn first_element(page: &Page, spec: LocatorSpec) -> Result<Option<Element>> {
match resolve(page, &first(spec)).await? {
Some(node) => Ok(Some(node.element(page).await?)),
None => Ok(None),
}
}
/// The first match's visibility, by the rule `properties.js` gives actions.
pub(crate) enum Visibility {
/// Nothing matches.
Missing,
/// The first match is not visible.
Hidden,
/// The first match is visible; a handle to it when one was asked for.
Visible(Option<Element>),
}
/// The visibility of the first element `spec` matches, read from the same
/// resolved node. With `element`, a visible match comes with its handle.
pub(crate) async fn first_visibility(
page: &Page,
spec: LocatorSpec,
element: bool,
) -> Result<Visibility> {
let Some(node) = resolve(page, &first(spec)).await? else {
return Ok(Visibility::Missing);
};
if node.properties().await?["visible"] != true {
return Ok(Visibility::Hidden);
}
Ok(Visibility::Visible(if element {
Some(node.element(page).await?)
} else {
None
}))
}
/// Every element `spec` matches, in document (or text-priority) order.
pub(crate) async fn all_elements(page: &Page, spec: &LocatorSpec) -> Result<Vec<Element>> {
let Some(node) = query(page, spec, Pick::All).await? else {
return Err(Error::cdp_msg("Locator did not return an array"));
};
// Indexed properties of the isolated-world array, in its object group so
// dropping `node` releases them too. An empty array has none.
let properties: Value = node
.session
.send(
"Runtime.getProperties",
&json!({"objectId":node.object,"ownProperties":true}),
)
.await?;
let mut indexed: Vec<(usize, &str)> = properties["result"]
.as_array()
.into_iter()
.flatten()
.filter_map(|property| {
let index = property["name"].as_str()?.parse().ok()?;
Some((index, property["value"]["objectId"].as_str()?))
})
.collect();
indexed.sort_unstable_by_key(|(index, _)| *index);
// `node` stays alive, keeping the objects, until every id is described.
let elements =
futures_util::future::try_join_all(indexed.into_iter().map(|(_, object)| async {
Ok::<_, Error>(Element {
page: page.clone(),
backend_node_id: describe(&node.session, object).await?,
})
}))
.await?;
drop(node);
Ok(elements)
}
/// The backend node id of a remote object.
async fn describe(session: &Session, object: &str) -> Result<i64> {
let described: Value = session
.send("DOM.describeNode", &json!({ "objectId": object }))
.await?;
described["node"]["backendNodeId"]
.as_i64()
.ok_or_else(|| Error::cdp("DOM.describeNode", -1, "No backendNodeId returned"))
}
impl Node {
/// A handle pinned to this node's backend id. Top frame only.
async fn element(&self, page: &Page) -> Result<Element> {
Ok(Element {
page: page.clone(),
backend_node_id: describe(&self.session, &self.object).await?,
})
}
}
/// A fresh node with its own object group, on the session that owns
/// `spec`'s frame, and that frame's id.
async fn start(page: &Page, spec: &LocatorSpec) -> Result<(Node, String)> {
static NEXT: AtomicU64 = AtomicU64::new(1);
let mut node = Node {
session: page.session().clone(),
object: String::new(),
frame_id: spec.frame_id.clone(),
group: format!("eoka-action-{}", NEXT.fetch_add(1, Ordering::Relaxed)),
attached: false,
hover_observer: None,
};
// Locators always run in an isolated world, so page scripts can neither
// observe them nor patch the DOM APIs they use. A page target's main
// frame id is its target id.
let frame_id = match &spec.frame_id {
Some(frame_id) => {
let target = page.frame_target_id(frame_id).await?;
if target != page.target_id() {
node.session = page.session().attach_frame_target(&target).await?;
node.attached = true;
}
frame_id.clone()
}
None => page.target_id().to_owned(),
};
Ok((node, frame_id))
}
/// Whether a CDP reply carries eoka's stale-world exception.
fn world_mismatch(reply: &Value) -> bool {
reply["exceptionDetails"]["exception"]["description"]
.as_str()
.is_some_and(|text| text.contains(WORLD_MISMATCH))
}
/// What an attempt in a stale world returns: Chrome's lost-context error, or
/// a mismatched world token.
enum Attempt<T> {
Done(T),
Stale(Option<Error>),
}
/// Runs `attempt` in the frame's cached isolated world. A cached world that
/// turns out stale is replaced once; a world created for this attempt is
/// never retried, so a failing read creates at most one world. When the
/// world stays stale the last real CDP error is returned, so navigation-race
/// checks still recognise it.
async fn in_world<T, F, Fut>(node: &Node, frame_id: &str, attempt: F) -> Result<T>
where
F: Fn(World) -> Fut,
Fut: std::future::Future<Output = Result<Attempt<T>>>,
{
let mut last = None;
loop {
let world = isolated_world(&node.session, frame_id).await?;
match attempt(world).await? {
Attempt::Done(value) => return Ok(value),
Attempt::Stale(error) => {
forget_isolated_world(&node.session, frame_id);
last = error.or(last);
if world.fresh {
return Err(last.unwrap_or_else(classify::world_replaced));
}
}
}
}
}
/// Whether an error says the world's context itself is gone. Lost objects
/// and nodes from another document are not: the world may be fine.
fn stale_context(error: &Error) -> bool {
classify::is_stale_world(error)
}
/// The `DOM.resolveNode` parameters for a pinned query, or `None`.
fn pinned(spec: &LocatorSpec) -> Option<Value> {
match spec.query {
LocatorQuery::BackendNode { id } => Some(json!({"backendNodeId": id})),
LocatorQuery::Node { id } => Some(json!({"nodeId": id})),
LocatorQuery::Css { .. }
| LocatorQuery::Text { .. }
| LocatorQuery::Placeholder { .. }
| LocatorQuery::Role { .. } => None,
}
}
pub(super) async fn resolve(page: &Page, spec: &LocatorSpec) -> Result<Option<Node>> {
if let Some(params) = pinned(spec) {
return resolve_pinned(page, spec, params, true).await.map(Some);
}
query(page, spec, spec.index.map_or(Pick::Strict, Pick::Index)).await
}
fn stale() -> Error {
Error::coded(
ErrorCode::TargetStale,
"pinned element no longer refers to a live node",
)
}
/// Resolves a pinned node into the isolated world of the frame whose
/// document holds it. With `connected`, a node that is no longer in the
/// document is stale, never retargeted.
///
/// Without a `frame_id` the top frame is tried first. A node of a
/// same-origin child frame resolves there too, but its reads and input
/// coordinates belong to its own frame, so it moves to that frame's world;
/// a cross-origin child frame's node does not resolve in the top world at
/// all, so the page's other frames are searched for it.
async fn resolve_pinned(
page: &Page,
spec: &LocatorSpec,
params: Value,
connected: bool,
) -> Result<Node> {
let (mut node, frame_id) = start(page, spec).await?;
let found = match pinned_object(&node, &frame_id, ¶ms, connected).await? {
Pinned::Here(object) => Some((object, None)),
Pinned::Frame(frame) => match pinned_object(&node, &frame, ¶ms, connected).await? {
Pinned::Here(object) => Some((object, Some(frame))),
Pinned::Frame(_) | Pinned::Elsewhere => None,
},
Pinned::Elsewhere if spec.frame_id.is_none() => {
child_frame_object(&node, ¶ms, connected).await?
}
Pinned::Elsewhere => None,
};
let (object, frame) = found.ok_or_else(stale)?;
node.object = object;
if frame.is_some() {
node.frame_id = frame;
}
Ok(node)
}
/// Where a pinned node resolved from one frame's isolated world.
enum Pinned {
/// In this frame: the node's object.
Here(String),
/// In a child frame's document, reached through this one (same origin).
Frame(String),
/// Not reachable from this frame: another frame's or a replaced document.
Elsewhere,
}
/// Searches the session's child frames, in tree order, for the one whose
/// isolated world resolves the pinned node; returns its object and frame.
async fn child_frame_object(
node: &Node,
params: &Value,
connected: bool,
) -> Result<Option<(String, Option<String>)>> {
fn collect(tree: &crate::cdp::FrameTree, frames: &mut Vec<String>) {
for child in &tree.child_frames {
frames.push(child.frame.id.clone());
collect(child, frames);
}
}
let mut frames = Vec::new();
collect(&node.session.get_frame_tree().await?, &mut frames);
for frame in frames {
match pinned_object(node, &frame, params, connected).await {
Ok(Pinned::Here(object)) => return Ok(Some((object, Some(frame)))),
Ok(Pinned::Frame(_) | Pinned::Elsewhere) => {}
// A frame this session cannot reach, such as one that just went
// away or lives in another process.
Err(error) if error.cdp_context().is_some() => {
tracing::debug!("pinned node search skipped frame {frame}: {error}");
}
Err(error) => return Err(error),
}
}
Ok(None)
}
/// Resolves a pinned node in one frame's isolated world.
async fn pinned_object(
node: &Node,
frame_id: &str,
params: &Value,
connected: bool,
) -> Result<Pinned> {
in_world(node, frame_id, |world| {
let mut params = params.clone();
params["objectGroup"] = json!(node.group);
params["executionContextId"] = json!(world.context);
let session = node.session.clone();
let group = node.group.clone();
async move {
let resolved = match session.send::<_, Value>("DOM.resolveNode", ¶ms).await {
Err(error) if stale_context(&error) => return Ok(Attempt::Stale(Some(error))),
// Chrome gives this both for a node this world cannot reach
// and for a context that no longer exists. A world created
// for this attempt, or one whose token still answers, is
// live: the node is elsewhere.
Err(error) if classify::node_left_document(&error) => {
return if world.fresh || world_answers(&session, world).await {
Ok(Attempt::Done(Pinned::Elsewhere))
} else {
Ok(Attempt::Stale(Some(error)))
};
}
// A pinned node is never retargeted, so one that is gone is
// stale now, not "not yet" for a wait.
Err(error) if classify::is(&error, classify::CdpFailure::NodeGone) => {
return Err(stale());
}
result => result?,
};
// A null object: the node's document is not this world's to
// reach (a cross-origin frame's, or a replaced one).
let Some(object) = resolved["object"]["objectId"].as_str() else {
return Ok(Attempt::Done(Pinned::Elsewhere));
};
let object = object.to_owned();
// The token proves the context is still eoka's world, not a
// reused id that now belongs to the page.
let checked = session
.send::<_, Value>(
"Runtime.callFunctionOn",
&json!({
"objectId":object,"returnByValue":true,
"functionDeclaration":"function(token,stale){if(globalThis.__eoka_world!==token){throw new Error(stale)}const view=this.ownerDocument.defaultView;return {connected:this.isConnected===true,own:this.ownerDocument===document,framed:view!==null&&view!==window}}",
"arguments":[{"value":world.token},{"value":WORLD_MISMATCH}],
}),
)
.await;
let state = match checked {
// The object was just created in this world, so losing it
// means the world went too.
Err(error) if classify::is(&error, classify::CdpFailure::ContextLost) => {
return Ok(Attempt::Stale(Some(error)));
}
Ok(reply) if world_mismatch(&reply) => return Ok(Attempt::Stale(None)),
reply => call_value(&reply?)?,
};
if state["own"] != true {
if let Some(frame) = owner_frame(&session, &object, &group).await? {
return Ok(Attempt::Done(Pinned::Frame(frame)));
}
// Another frame's document whose owner this world cannot
// see (it sits in a cross-origin document): that frame's own
// world has to resolve it. A template's or a detached
// document has no window and stays here.
if state["framed"] == true {
return Ok(Attempt::Done(Pinned::Elsewhere));
}
}
if connected && state["connected"] != true {
return Err(stale());
}
Ok(Attempt::Done(Pinned::Here(object)))
}
})
.await
}
/// The id of the frame whose document holds `object`, when that document
/// belongs to a frame (not a template's or a detached one).
async fn owner_frame(session: &Session, object: &str, group: &str) -> Result<Option<String>> {
let owner: Value = session
.send(
"Runtime.callFunctionOn",
&json!({
"objectId":object,"objectGroup":group,"returnByValue":false,
"functionDeclaration":"function(){return this.ownerDocument.defaultView?.frameElement ?? null}",
}),
)
.await?;
let Some(owner) = owner["result"]["objectId"].as_str() else {
return Ok(None);
};
let described: Value = session
.send("DOM.describeNode", &json!({ "objectId": owner }))
.await?;
Ok(described["node"]["frameId"].as_str().map(str::to_owned))
}
/// What a non-pinned query returns.
#[derive(Clone, Copy)]
pub(super) enum Pick {
/// The array of every match, in order.
All,
/// The only match; several matches are ambiguous.
Strict,
/// The match at a zero-based index.
Index(usize),
}
/// Runs a non-pinned query in the frame's isolated world in one
/// `Runtime.evaluate`. Returns the node holding the picked element, or the
/// array of every match for [`Pick::All`]; `None` when nothing is picked.
pub(super) async fn query(page: &Page, spec: &LocatorSpec, pick: Pick) -> Result<Option<Node>> {
let (mut node, frame_id) = start(page, spec).await?;
let query = serde_json::to_string(&spec.query)?;
let pick = match pick {
Pick::All => Value::Null,
Pick::Strict => json!({ "index": null }),
Pick::Index(index) => json!({ "index": index }),
};
let expression = format!(
"({})({query},{pick})",
include_str!("resolve.js")
.replace(
"TEXT_CANDIDATES",
include_str!("../page/text_candidates.js")
)
.replace("AMBIGUOUS", &format!("'{AMBIGUOUS}'"))
);
let result: Value = in_world(&node, &frame_id, |world| {
let guarded = format!(
"(()=>{{if(globalThis.__eoka_world!=={}){{throw new Error('{WORLD_MISMATCH}')}}return {expression}}})()",
world.token
);
let params = json!({"expression":guarded,"objectGroup":node.group,"returnByValue":false,"contextId":world.context});
let session = node.session.clone();
async move {
match session.send::<_, Value>("Runtime.evaluate", ¶ms).await {
Err(error) if stale_context(&error) => Ok(Attempt::Stale(Some(error))),
Ok(reply) if world_mismatch(&reply) => Ok(Attempt::Stale(None)),
result => result.map(Attempt::Done),
}
}
})
.await?;
if let Some(exception) = result.get("exceptionDetails") {
if exception["exception"]["description"]
.as_str()
.is_some_and(|text| text.contains(AMBIGUOUS))
{
return Err(Error::coded(
ErrorCode::AmbiguousTarget,
"locator matched multiple elements; select first/nth explicitly",
));
}
// Any other exception means the query itself is invalid, such as a
// CSS selector that does not parse.
return Err(Error::invalid_argument("invalid locator query"));
}
// A miss is `null`, which has no object id.
let Some(object) = result["result"]["objectId"].as_str() else {
return Ok(None);
};
node.object = object.into();
Ok(Some(node))
}
const AMBIGUOUS: &str = "eoka: ambiguous locator";
const WORLD_MISMATCH: &str = "eoka: stale isolated world";
#[derive(Clone, Copy)]
struct World {
context: i64,
token: u64,
/// Created by this lookup rather than taken from the cache.
fresh: bool,
}
/// Whether `world` still exists and is eoka's: its token answers.
async fn world_answers(session: &Session, world: World) -> bool {
session
.send::<_, Value>(
"Runtime.evaluate",
&json!({"expression":"globalThis.__eoka_world","contextId":world.context,"returnByValue":true}),
)
.await
.is_ok_and(|reply| reply["result"]["value"].as_u64() == Some(world.token))
}
/// Cached worlds keyed by (session id, frame id).
fn worlds() -> MutexGuard<'static, HashMap<(String, String), World>> {
static WORLDS: OnceLock<Mutex<HashMap<(String, String), World>>> = OnceLock::new();
WORLDS.get_or_init(Default::default).lock_unpoisoned()
}
/// The cached eoka isolated world for a frame, created on first use.
///
/// Creating a world per poll grew Chrome's world list on every 25ms retry.
/// A navigation destroys the world; callers detect that through the token
/// check or a lost-context error and call [`forget_isolated_world`]. The
/// token, set inside the world, also catches a reused context id.
async fn isolated_world(session: &Session, frame_id: &str) -> Result<World> {
let key = (session.session_id().to_owned(), frame_id.to_owned());
if let Some(world) = worlds().get(&key).copied() {
return Ok(world);
}
let context = session.create_isolated_world(frame_id).await?;
let token = fastrand::u64(1..u64::MAX >> 11);
session
.send::<_, Value>(
"Runtime.evaluate",
&json!({"expression":format!("globalThis.__eoka_world={token}"),"contextId":context}),
)
.await?;
let world = World {
context,
token,
fresh: false,
};
let mut cache = worlds();
if cache.len() >= 512 {
cache.clear();
}
cache.insert(key, world);
Ok(World {
fresh: true,
..world
})
}
fn forget_isolated_world(session: &Session, frame_id: &str) {
worlds().remove(&(session.session_id().to_owned(), frame_id.to_owned()));
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
/// A local HTTP server answering every GET with `page(path)` as HTML.
async fn serve(page: fn(&str) -> String) -> String {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
tokio::spawn(async move {
while let Ok((mut stream, _)) = listener.accept().await {
tokio::spawn(async move {
let mut request = vec![0u8; 4096];
let read = stream.read(&mut request).await.unwrap_or(0);
let request = String::from_utf8_lossy(&request[..read]);
let path = request.split_whitespace().nth(1).unwrap_or("/");
let body = page(path);
let _ = stream
.write_all(
format!(
"HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
)
.as_bytes(),
)
.await;
});
}
});
base
}
async fn launch() -> crate::Browser {
crate::Browser::launch_with(|config| {
config.chrome_path = std::env::var("EOKA_TEST_CHROME_PATH").ok();
config.cdp_timeout = Duration::from_secs(5);
})
.await
.unwrap()
}
/// The context id of the page's cached top-frame world, if any.
fn cached_world(page: &Page) -> Option<i64> {
let key = (
page.session().session_id().to_owned(),
page.target_id().to_owned(),
);
worlds().get(&key).map(|world| world.context)
}
#[tokio::test]
#[ignore = "requires Chrome"]
async fn chrome_an_element_from_a_previous_document_is_stale_at_once() {
let base = serve(|path| format!("<p id=p>{}</p>", &path[1..])).await;
let browser = launch().await;
let page = browser.new_page(&format!("{base}/old")).await.unwrap();
let old = page.find("p").await.unwrap();
assert_eq!(old.text().await.unwrap(), "old");
let dead = cached_world(&page).expect("the first find caches a world");
page.goto(&format!("{base}/new")).await.unwrap();
// A live node of the new document, pinned before any locator ran
// there: the cached world died with the old document, so the read
// replaces it once and succeeds.
let new = Element {
page: page.clone(),
backend_node_id: backend_id_in_frames(&page, "p").await,
};
assert_eq!(new.text().await.unwrap(), "new");
let world = cached_world(&page).expect("the replacement world is cached");
assert_ne!(world, dead);
// The old node is stale at once.
let start = std::time::Instant::now();
let error = old.text().await.unwrap_err();
assert_eq!(error.code(), ErrorCode::TargetStale, "{error}");
assert_eq!(cached_world(&page), Some(world));
// Later reads keep that world: no new world per read, no waiting.
for _ in 0..3 {
assert_eq!(old.text().await.unwrap_err().code(), ErrorCode::TargetStale);
assert_eq!(
old.is_visible().await.unwrap_err().code(),
ErrorCode::TargetStale
);
}
assert_eq!(cached_world(&page), Some(world));
assert!(
start.elapsed() < Duration::from_secs(2),
"{:?}",
start.elapsed()
);
// A wait on the pinned node fails at once instead of polling.
let pinned = LocatorSpec {
query: LocatorQuery::BackendNode {
id: old.backend_node_id,
},
frame_id: None,
index: None,
};
let start = std::time::Instant::now();
let error = page
.wait_for_expectation(
&crate::Expectation::Visible { target: pinned },
Duration::from_secs(10),
)
.await
.unwrap_err();
assert_eq!(error.code(), ErrorCode::TargetStale, "{error}");
assert!(
start.elapsed() < Duration::from_secs(1),
"{:?}",
start.elapsed()
);
// The new document resolves in the same world.
assert_eq!(page.find("p").await.unwrap().text().await.unwrap(), "new");
assert_eq!(cached_world(&page), Some(world));
browser.close().await.unwrap();
}
/// The backend node id of the element with `id` anywhere in the page,
/// child frames included, once it exists.
async fn backend_id_in_frames(page: &Page, id: &str) -> i64 {
fn find(node: &Value, id: &str) -> Option<i64> {
let attributes = node["attributes"].as_array();
if attributes.is_some_and(|a| a.chunks(2).any(|pair| pair[0] == "id" && pair[1] == id))
{
return node["backendNodeId"].as_i64();
}
let children = node["children"].as_array().into_iter().flatten();
children
.chain(node.get("contentDocument"))
.find_map(|child| find(child, id))
}
for _ in 0..100 {
let document: Value = page
.session()
.send("DOM.getDocument", &json!({"depth":-1,"pierce":true}))
.await
.unwrap();
if let Some(found) = find(&document["root"], id) {
return found;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
panic!("no element #{id} in any frame");
}
/// An Element pinned by backend id with no frame, as eoka-tools builds
/// from accessibility refs, works inside a child frame: reads run in that
/// frame's isolated world and a click lands on the element, not at its
/// frame-local coordinates.
async fn pinned_frame_element_works(page: &Page) {
let button = Element {
page: page.clone(),
backend_node_id: backend_id_in_frames(page, "go").await,
};
let field = Element {
page: page.clone(),
backend_node_id: backend_id_in_frames(page, "field").await,
};
assert!(button.is_visible().await.unwrap());
assert_eq!(button.text().await.unwrap(), "go");
assert_eq!(
button.get_attribute("id").await.unwrap().as_deref(),
Some("go")
);
assert_eq!(field.value().await.unwrap(), "inner");
let receipt = button
.click()
.expecting(crate::Expectation::Text {
target: LocatorSpec {
query: LocatorQuery::BackendNode {
id: button.backend_node_id,
},
frame_id: None,
index: None,
},
value: "clicked".into(),
contains: false,
})
.timeout(Duration::from_secs(5))
.await
.unwrap();
assert_eq!(receipt.outcome, crate::ActionOutcome::VerifiedComplete);
assert_eq!(button.text().await.unwrap(), "clicked");
// The top frame's own clicks were not hit.
assert_eq!(page.eval::<u32>("window.topClicks").await.unwrap(), 0);
}
fn framed_page(inner: &str) -> String {
format!(
"<body onclick='window.topClicks++'><script>window.topClicks=0</script>\
<div style='margin:200px 0 0 300px'><iframe src='{inner}' style='width:300px;height:150px'></iframe></div></body>"
)
}
/// Pages for nested-frame layouts; the query carries the next URL, so
/// one router serves every origin.
fn frames_router(path: &str) -> String {
if let Some(next) = path.strip_prefix("/top?") {
framed_page(next)
} else if let Some(next) = path.strip_prefix("/mid?") {
format!("<iframe src='{next}' style='margin:10px;width:260px;height:120px'></iframe>")
} else if let Some(other) = path.strip_prefix("/two?") {
format!(
"<body onclick='window.topClicks++'><script>window.topClicks=0</script>\
<iframe src='{other}/blank'></iframe>\
<div style='margin:100px 0 0 300px'><iframe src='{other}/inner' style='width:300px;height:150px'></iframe></div></body>"
)
} else if path == "/blank" {
"<p>blank</p>".into()
} else {
inner_page()
}
}
#[tokio::test]
#[ignore = "requires Chrome"]
async fn chrome_a_pinned_node_resolves_in_its_own_frame_among_nested_and_sibling_frames() {
let a = serve(frames_router).await;
let b = serve(frames_router).await;
let browser = launch().await;
// Top a, child b, grandchild a: the top world can wrap the node but
// cannot see its frame owner, which sits in b's document.
let page = browser
.new_page(&format!("{a}/top?{b}/mid?{a}/inner"))
.await
.unwrap();
pinned_frame_element_works(&page).await;
// Two b siblings under a: the first sibling's world can wrap the
// second's node, but the node belongs to the second.
page.goto(&format!("{a}/two?{b}")).await.unwrap();
pinned_frame_element_works(&page).await;
browser.close().await.unwrap();
}
fn inner_page() -> String {
"<button id=go style='margin:40px' onclick=\"this.textContent='clicked'\">go</button><input id=field value=inner>".into()
}
#[tokio::test]
#[ignore = "requires Chrome"]
async fn chrome_a_pinned_node_in_a_same_origin_frame_resolves_in_its_frame() {
let base = serve(|path| {
if path == "/inner" {
inner_page()
} else {
framed_page("/inner")
}
})
.await;
let browser = launch().await;
let page = browser.new_page(&format!("{base}/")).await.unwrap();
pinned_frame_element_works(&page).await;
browser.close().await.unwrap();
}
#[tokio::test]
#[ignore = "requires Chrome"]
async fn chrome_a_pinned_node_in_a_cross_origin_frame_resolves_in_its_frame() {
// Another port on the same host is cross-origin but same-site, so
// the frame stays in the page's process and session.
let inner = serve(|_| inner_page()).await;
let base = serve(|path| framed_page(path.strip_prefix("/?").unwrap_or_default())).await;
let browser = launch().await;
let page = browser
.new_page(&format!("{base}/?{inner}/"))
.await
.unwrap();
pinned_frame_element_works(&page).await;
browser.close().await.unwrap();
}
#[tokio::test]
#[ignore = "requires Chrome"]
async fn chrome_dropping_a_match_list_releases_it_and_its_elements() {
let browser = crate::Browser::launch_with(|config| {
config.chrome_path = std::env::var("EOKA_TEST_CHROME_PATH").ok();
config.cdp_timeout = Duration::from_secs(5);
})
.await
.unwrap();
let page = browser
.new_page("data:text/html,<p>a</p><p>b</p>")
.await
.unwrap();
let node = query(&page, &LocatorSpec::css("p"), Pick::All)
.await
.unwrap()
.unwrap();
assert_eq!(
all_elements(&page, &LocatorSpec::css("p"))
.await
.unwrap()
.len(),
2
);
let session = node.session.clone();
let array = node.object.clone();
// An element object derived from the array, as all_elements gets them.
let properties: Value = session
.send(
"Runtime.getProperties",
&json!({"objectId":array,"ownProperties":true}),
)
.await
.unwrap();
let element = properties["result"]
.as_array()
.unwrap()
.iter()
.find(|property| property["name"] == "0")
.and_then(|property| property["value"]["objectId"].as_str())
.unwrap()
.to_owned();
let call = |object: String| {
let session = session.clone();
async move {
session
.send::<_, Value>(
"Runtime.callFunctionOn",
&json!({"objectId":object,"functionDeclaration":"function(){return 1}","returnByValue":true}),
)
.await
}
};
call(element.clone()).await.unwrap();
drop(node);
tokio::time::timeout(Duration::from_secs(2), async {
while call(element.clone()).await.is_ok() || call(array.clone()).await.is_ok() {
tokio::time::sleep(Duration::from_millis(20)).await;
}
})
.await
.expect("dropping the node must release the array and its element objects");
browser.close().await.unwrap();
}
}