Class: Capybara::Simulated::Browser
- Inherits:
-
Object
- Object
- Capybara::Simulated::Browser
- Includes:
- RecordedActions
- Defined in:
- lib/capybara/simulated/browser.rb
Defined Under Namespace
Modules: RecordedActions
Constant Summary collapse
- POLLING_GRACE_POLLS =
Sticky window after timers finish: keep polling? true so a setTimeout firing mid-loop doesn’t drop Capybara’s synchronize before its own default_max_wait_time kicks in. Counted in poll calls (not wall time) for determinism under GC/load pressure. 1000 polls × Capybara’s default 0.01 s retry_interval ≈ 10 s.
1000- IDLE_SETTLE_POLLS =
When ‘@timers_active` is true but `@runtime.settle_gen` hasn’t bumped in this many consecutive polls, treat the page as observably idle and let Capybara’s per-find timer give up. See ‘polling?` for the full rationale. 300 polls ≈ 3 s at Capybara’s default 10 ms retry interval — long enough to ride through brief async idle windows during Discourse’s ProseMirror editor boot (which sometimes pauses ~1 s mid-load while a webpack chunk + Glimmer reconcile complete) while still cutting the full 4 s wait on tests destined to fail.
300- POST_NAV_POLL_GRACE_POLLS =
Brief window after a Ruby-side navigate (context rebuild) so Capybara’s outer synchronize gets one retry against the new context.
10- POLL_TICK_STEP_MS =
Deterministic virtual-clock model (replaces the old wall-sync, where each tick advanced by REAL wall-elapsed and so coupled virtual time to JS/Ruby/GC speed — a faster ‘visible_text` shifted WHEN debounces fired, e.g. Avo actions_spec:464). Now each poll advances by a FIXED step; near-future timers on an otherwise-idle page are fast-forwarded to (horizon-gated).
100 ms is empirically the floor that lets a “commit debounce scheduled between two user actions” fire before the next action (Avo actions_spec:464’s ~50-75 ms field-commit flips at step 10/50, fixed at >=75). Group-A transient-catch observability does NOT depend on this step — it comes from the ‘timer_wait_elapsed?` FREQUENCY gate (the first find after an action doesn’t tick, so the pre-debounce state is observed regardless of step size), so a larger step completes Group-B without losing Group-A (verified green at 100 across gem 1579, WPT 660, Forem, Avo, :464 passing). Clamped >=1 so a ‘CSIM_POLL_TICK_STEP_MS=0` misconfig can’t freeze the fixed-step path.
[(ENV['CSIM_POLL_TICK_STEP_MS'] || '100').to_i, 1].max
- FF_HORIZON_MS =
Horizon-gated fast-forward: when the page is observably idle (no timer due now, no background IO) but a timer is parked within this horizon, jump the virtual clock straight to it instead of waiting ~delay/step polls. A timer farther out (ahoy 1000 ms, session-timeout, analytics) is LEFT parked. 600 clears every legit must-fire wait (Backburner/DTextField 500, refetch/chart <=200, image-grid 64) while staying BELOW ahoy’s 1000. ‘=0` disables FF →pure deterministic fixed-step (the fallback model).
(ENV['CSIM_FF_HORIZON_MS'] || '600').to_i
- FF_TRANSIENT_GUARD_POLLS =
Transient guard: hold the page pre-debounce for this many consecutive idle polls before allowing a fast-forward, so “catch the DOM before the 200 ms debounce fires” tests (Discourse refetchForSearch / doubled-filter, Avo filters) still observe the intermediate state across several polls.
(ENV['CSIM_FF_TRANSIENT_GUARD_POLLS'] || '6').to_i
- SETTLE_DRAIN_MS =
32- SETTLE_MAX_ITER =
10- SETTLE_MAX_ITER_TASKS =
Per-‘run_loop_step` task cap (its `maxIter`). Bounds a self-rescheduling timer/microtask storm so one settle iter returns to Ruby; large enough for the heaviest legit chain (Mastodon hydrate, Turbo stream batch).
256- USER_ACTION_DRAIN_MS =
Post-user-action virtual-clock advance. Default 0 — the wall-sync model (each tick_real_time advances by the wall ms elapsed since the last tick) lets Capybara’s outer poll loop drive the clock at the same rate a real browser sees, so debounced chains complete naturally during polling without being pre-emptively flushed past the transient window real-browser tests rely on.
‘CSIM_USER_ACTION_DRAIN_MS=600` restores the pre-wall-sync burst behaviour: post-action, drain everything due in the next 600 ms of virtual time before returning. Costs the transient- state observability the wall-sync model preserves; recovers the ~5-10 % wall on action-heavy suites where Capybara would otherwise poll N times to catch a single debounce.
(ENV['CSIM_USER_ACTION_DRAIN_MS'] || '0').to_i
- USER_AGENT =
Sent on every driver-originated Rack call. ‘HTTP_USER_AGENT` must lead with `Mozilla/5.0` so server-side bot detectors (ahoy_matey’s ‘Browser.new(ua).bot?`) treat us as a real client. `REMOTE_ADDR` has to be a non-empty, parseable IP —Devise’s ‘trackable` mixin runs `IPAddr.new(request.remote_ip)` during `set_user`/sign-in, and an empty string trips `IPAddr::AddressFamilyError`. Keep `USER_AGENT` in sync with `navigator.userAgent` in `lib/capybara/simulated/js/bridge.js` — the JS side ships in the V8 snapshot, so injecting from Ruby at boot would defeat snapshot warmth. Discourse’s ‘non_crawler_user_agents` adds a “Rails Testing” bypass in test mode (see lib/crawler_detection.rb); without one of its bypass tokens here Discourse serves a no-JS crawler-only HTML view. Putting “Rails Testing” in the UA satisfies that without claiming a specific real-browser engine (which would send Turbo / Stimulus down chrome-specific code paths Avo’s tests don’t exercise).
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 capybara-simulated'- REMOTE_ADDR_IPV4 =
Approximate Chrome’s resolution: when connecting to ‘localhost`, Linux glibc returns IPv6 (::1) first and the server sees the client at `::1`; for any literal IP (or a non-localhost name), the server keeps IPv4. Match that so Discourse system specs (`expect(event).to eq(’::1’)‘) line up with what they would see under selenium.
'127.0.0.1'- REMOTE_ADDR_IPV6 =
'::1'- RECENT_URLS_STALE_AGE_MS =
Queued URLs older than this (real wall clock) are treated as stale and dropped on the next ‘current_url` read. Capybara’s default polling interval is 50 ms, so a ‘have_current_path` walk runs through its iterations well under this threshold; a `page.current_url` read between unrelated user actions arrives long after the prior action’s settle pushed intermediates, falls past the cutoff, and surfaces the current URL directly.
250- FIND_PRE_TICK_MIN_S =
Minimum wall-clock gap before find() re-ticks. The smoke contract is “first find returns the current DOM without firing pending timers” — apps assert ‘have_selector` on a `<div>` whose constructor schedules a `setTimeout(0)` to remove it, expecting to catch the div before removal. Keep this above one Ruby boundary so a single visit+find pair doesn’t accidentally tick.
0.05- MODIFIER_KEYS =
{ shift: 'shiftKey', control: 'ctrlKey', ctrl: 'ctrlKey', alt: 'altKey', option: 'altKey', meta: 'metaKey', command: 'metaKey' }.freeze
- MODIFIER_KEY_NAMES =
MODIFIER_KEYS.keys.to_set.freeze
- CONSOLE_STDERR =
Resolved once — log_console fires for every page console.* line (CLAUDE.md rule 3: no per-call ENV reads on hot paths).
ENV['CSIM_CONSOLE_STDERR'] == '1'
- ANNOTATABLE_SEVERITIES =
info/debug/log lines almost never carry stack traces — keep them out of the regex pass so per-call cost stays at the severity gate.
%w[error warning warn].freeze
- ASSET_SRC_MAX =
4096- HIJACK_PIPE_MAX_WAIT_S =
MessageBus’s ‘long_polling_interval` defaults to 25 s — its `cleanup_timer` fires after that interval, closing the hijacked connection with an empty `[]` write. Pick a slightly larger wall cap so the close reaches us before our pipe read gives up. Other hijack-using middleware likely behaves similarly; if any need much longer waits, this becomes a per- request option.
30- MAX_FETCH_REDIRECTS =
20- NETWORK_BODY_CAP =
Cap per-body capture so one big asset/response can’t bloat the trace. Generous (this is a local debugging artifact).
256 * 1024
- TEXT_CONTENT_TYPE_PREFIXES =
Content types whose bytes are already representable in the UTF-8 string that ships back to JS — base64 wouldn’t add anything and ‘Base64.strict_encode64` is ~1 % of suite wall time on Discourse. Binary types (images, octet-stream, gzipped traineddata, etc.) still need `body_b64` because V8 / QuickJS mangle bytes 0x80-0xFF over the UTF-8 string boundary. `fetch.js#_decodeBytes` and `xhr.js` both fall back to the text body when `body_b64` is absent.
%w[text/ application/json application/javascript application/ecmascript application/xml image/svg+xml].freeze
- @@asset_cache =
Process-wide HTTP/1.1 response cache for ‘rack_fetch`. Real browsers (cuprite / selenium) reuse fetched assets across the suite — without this, Simulated re-fetches every <script src> on every visit (Redmine baseline: ~6× more requests than selenium). Honors `Cache-Control` / `Expires` / `ETag` / `Last-Modified` per RFC 9111.
AssetCache.new
- @@asset_src =
Cross-visit cache of external asset bodies (classic ‘<script src>` bundles AND linked `<link rel=stylesheet>` CSS), url → [body, fresh_until]. A fresh VM per visit (`reset_page` → `clear_volatile`) would otherwise re-fetch the same fingerprinted app assets (avo.base.js, avo.base.css, …) on every visit — a real browser HTTP-caches them once. Safety: only responses the server marks durably cacheable (`fresh_until` from max-age) are stored, and these are content-stable assets at content-hashed URLs (a change yields a new URL = cache miss), so a stale body can’t shadow a later test. Survives ‘clear_volatile` (that is the point); size-capped.
{}
- @@asset_src_lock =
Mutex.new
Instance Attribute Summary collapse
-
#context_gen ⇒ Object
readonly
Returns the value of attribute context_gen.
-
#current_realm_id ⇒ Object
readonly
Returns the value of attribute current_realm_id.
-
#default_user_agent ⇒ Object
Capybara’s ‘current_window.resize_to(w, h)` lands here; the ahoy hamburger test (mobile breakpoint at 425×694) and any responsive-utility-aware test (Tailwind `m:` show / hide, bootstrap `.d-md-flex`, …) depends on this surfacing through the JS-side `innerWidth` / `innerHeight` so the cascade’s ‘mediaMatches` and `matchMedia()` evaluate against the test’s chosen viewport instead of the 1024×768 default.
-
#default_viewport ⇒ Object
Capybara’s ‘current_window.resize_to(w, h)` lands here; the ahoy hamburger test (mobile breakpoint at 425×694) and any responsive-utility-aware test (Tailwind `m:` show / hide, bootstrap `.d-md-flex`, …) depends on this surfacing through the JS-side `innerWidth` / `innerHeight` so the cascade’s ‘mediaMatches` and `matchMedia()` evaluate against the test’s chosen viewport instead of the 1024×768 default.
-
#pending_trace ⇒ Object
readonly
Returns the value of attribute pending_trace.
-
#timers_active ⇒ Object
writeonly
Sets the attribute timers_active.
-
#trace ⇒ Object
readonly
Returns the value of attribute trace.
-
#trace_mode ⇒ Object
readonly
Returns the value of attribute trace_mode.
-
#window_handle ⇒ Object
The Driver’s handle for the window this Browser backs (set right after construction).
Class Method Summary collapse
-
.default_host ⇒ Object
Fallback origin for ‘visit(’/foo’)‘ and friends when no current page is loaded yet.
- .remote_addr_for(host) ⇒ Object
Instance Method Summary collapse
- #active_element_handle ⇒ Object
- #advance_virtual_clock_ms(ms) ⇒ Object
-
#all_text(handle) ⇒ Object
Capybara::Driver::Node surface — Node calls ‘check_stale` before each read, and that advances the virtual clock.
- #annotate_console_message(severity, message) ⇒ Object
- #append_multipart_part(body, boundary, name, content, filename: nil, content_type: nil) ⇒ Object
-
#apply_request_headers(env, headers) ⇒ Object
CGI convention: ‘Content-Type` and `Content-Length` land in env without the HTTP_ prefix.
-
#async_io_pending? ⇒ Boolean
Cheap O(1) gate: is there any non-timer async channel with traffic that ‘tick_real_time` would drain? `tick_real_time` itself runs exactly when `worker_pending? || event_source_pending? || hijack_fetch_pending?` (plus `@timers_active`), and each of those predicates is a single `.empty?` / counter check.
- #attr(handle, name) ⇒ Object
- #blob_register(url, body_b64, owner_realm = nil) ⇒ Object
- #blob_resolve(url) ⇒ Object
- #blob_unregister(url) ⇒ Object
-
#boot_blob_document(url, bytes, content_type) ⇒ Object
Load a blob: document (bytes from the opener) as THIS window’s top-level document — for ‘window.open(blobURL)` / a blob: aux-window navigation, where the blob isn’t rack-navigable and lives in the opener’s isolate.
-
#broadcast_to_windows(name, data) ⇒ Object
‘BroadcastChannel.postMessage` in THIS window — fan out to every OTHER window’s matching channels (same-window delivery happens in-VM).
- #build_multipart_body(fields, file_inputs) ⇒ Object
- #build_runtime(engine) ⇒ Object
-
#cached_find(kind, arg, ctx) ⇒ Object
Single-slot cache for the most recent find_xpath / find_css / find_first_css result.
-
#cap_trace_body(body) ⇒ Object
JSON-safe body for the trace: binary (non-UTF-8) bodies become a placeholder rather than mojibake, and long bodies are truncated (scrubbed so a mid-codepoint cut can’t yield invalid UTF-8).
- #check_stale(handle, initial, gen = nil) ⇒ Object
- #clear_trace! ⇒ Object
- #click(handle, keys = [], **opts) ⇒ Object
-
#click_event_init(handle, keys, opts) ⇒ Object
Resolve click offset against the element’s CSS-declared box.
- #close_child_window(handle) ⇒ Object
- #coerce_set_value(v) ⇒ Object
- #computed_style(handle, names) ⇒ Object
-
#consume_pending_aux_window ⇒ Object
A script-driven ‘anchor.click()` / `target=_blank` navigation with no Capybara action behind it (e.g. a WPT test) — open the aux window from the event-loop drain.
-
#consume_pending_download ⇒ Object
‘<a download>` clicked synthetically (file-saver’s saveAs ships a freshly-created anchor through ‘dispatchEvent(MouseEvent ’click’)‘).
-
#consume_pending_form_submit ⇒ Object
Read the form-submit pending intent set by JS-side ‘form.submit()` / `form.requestSubmit()`.
- #consume_pending_frame_nav ⇒ Object
- #consume_pending_frame_reload ⇒ Object
- #consume_pending_frame_submit ⇒ Object
- #consume_pending_history_traverse ⇒ Object
- #consume_pending_location ⇒ Object
-
#consume_pending_navigation ⇒ Object
Read the anchor-navigation pending intent set by JS-side ‘el.click()` (Element.prototype.click) on an `<a href>`.
- #consume_pending_reload ⇒ Object
-
#current_browsing_context_url ⇒ Object
The active browsing context’s own URL: the frame document’s URL inside a ‘within_frame` block, else the main page URL.
-
#current_document_handle ⇒ Object
Root for a context-less find: the active frame’s document (handle 0 ⇒ the realm’s own ‘globalThis.document`) when in a frame, else the main document handle.
- #current_path ⇒ Object
- #current_referer ⇒ Object
- #current_url ⇒ Object
-
#decode_image(b64_bytes, max_w = nil, max_h = nil) ⇒ Object
── Image decode (libvips) ─────────────────────────────────────.
- #decode_response_bom(s) ⇒ Object
-
#decode_video_frame(b64_bytes) ⇒ Object
── Video decode (ffprobe + ffmpeg) ────────────────────────────.
-
#decode_windows1252(s) ⇒ Object
Decode bytes as windows-1252 (the HTML locale-default encoding) to a UTF-8 Ruby string.
-
#deliver_event_source_events ⇒ Object
Drain any queued events into the VM.
- #deliver_hijacked_fetches ⇒ Object
- #deliver_websocket_events ⇒ Object
-
#deliver_window_messages ⇒ Object
Fire queued cross-window messages (postMessage + BroadcastChannel).
- #deliver_worker_messages ⇒ Object
-
#describe_node_handle(handle) ⇒ Object
‘tag#id.class` short description of the handle, for trace `description` fields.
- #disabled?(handle) ⇒ Boolean
- #dispatch_event(handle, type, init = {}) ⇒ Object
-
#dispose ⇒ Object
Tear down an auxiliary window’s Browser when its window closes (the Driver calls this on close_window / reset!).
-
#document_cookie ⇒ Object
‘document.cookie` is TEXT; jar entries parsed out of Rack’s Set-Cookie headers can carry the BINARY tag, which would make the joined string cross into JS as a Uint8Array (‘document.cookie.match is not a function`).
-
#dom_call(name, *args) ⇒ Object
DOM / node / query host-fn dispatch.
-
#domain_to_ascii(domain) ⇒ Object
WHATWG URL “domain to ASCII” — the JS tr46 stub delegates non-ASCII / xn– hosts here (the ASCII fast path stays in-VM).
-
#domain_to_unicode(domain) ⇒ Object
WHATWG URL “domain to Unicode” — best-effort (never fails the parse per spec), so on an IDNA error fall back to the input domain (unlike to_ascii, which signals failure with nil — the asymmetry is intentional).
- #double_click(handle, keys = [], **opts) ⇒ Object
- #download_link(url, filename_hint = '') ⇒ Object
-
#drag_to(source_handle, target_handle, **_opts) ⇒ Object
Element-to-element drag.
-
#drain_after_user_action ⇒ Object
Every user-action entry point (set / send_keys / select / unselect) ends in this trio: drain any pending form submit, drain any pending Element.click anchor activation, then settle the page.
- #drain_pending_navigation ⇒ Object
-
#drop(handle, args) ⇒ Object
HTML5 drag-and-drop simulation.
- #drop_items(arg) ⇒ Object
-
#drop_pending_transfers ⇒ Object
Release every outstanding transfer token’s backing store.
-
#durable_source(url) ⇒ Object
Fetch a source body and report how long it stays safely reusable per its OWN response headers — an absolute freshness deadline (Time), or nil when the response is not durably cacheable (no-store / no-cache / max-age=0 / dynamic with no freshness).
- #empty_find_result?(result) ⇒ Boolean
- #encode_image(pixels_ref, width, height, mime_type = 'image/png', quality = 90) ⇒ Object
-
#enqueue_broadcast(name, data) ⇒ Object
A BroadcastChannel message from another window, queued for delivery to this window’s channels with the same name.
-
#enqueue_window_message(data, origin, source_handle) ⇒ Object
Queue a cross-window message for delivery into THIS window’s VM (called by the Driver on the target Browser).
-
#ensure_alive_after_tick(handle) ⇒ Object
‘tick_real_time` may have rebuilt the DOM (Ember route hydration finishing on its first idle tick replaces server-rendered nodes with fresh ones).
-
#eval_esm_module(url, src = nil) ⇒ Object
Native ESM entry point.
- #evaluate_async_script(code, args = []) ⇒ Object
- #evaluate_script(code, args = []) ⇒ Object
- #event_source_close(id) ⇒ Object
-
#event_source_open(url) ⇒ Object
── EventSource (SSE) ──────────────────────────────────────────.
- #event_source_pending? ⇒ Boolean
- #event_source_poll ⇒ Object
-
#execute_script(code, args = []) ⇒ Object
Fire-and-forget variant: runs the script but never returns its value to Ruby.
-
#external_asset_source(url) ⇒ Object
Body of an external durably-cacheable asset (classic script or stylesheet), served from the cross-visit cache when still fresh, else fetched (which read-throughs the per-visit asset cache) and cached iff durably cacheable.
- #file_input?(handle) ⇒ Boolean
-
#file_pick_paths(fi) ⇒ Object
The on-disk paths backing a file input’s current selection.
- #file_picks_for(handle) ⇒ Object
- #find_css(css, context_handle = nil) ⇒ Object
- #find_first_css(css, context_handle = nil) ⇒ Object
- #find_with_timer_fallback(kind, arg, ctx) ⇒ Object
-
#find_xpath(xpath, context_handle = nil) ⇒ Object
XPath is evaluated inside V8 against the live JS DOM via the xpathway engine (bundled, installed at snapshot build).
-
#finish_trace_to(path, trace = (@trace || @pending_trace)) ⇒ Object
Persist ‘trace` (defaults to live or pending) to `path` and return the path.
-
#form_get_url(action, body) ⇒ Object
HTML form-submission “mutate action URL” for GET: REPLACE the action URL’s query with the serialized entry list (dropping any pre-existing query), preserving a trailing #fragment.
- #format_temporal_value(v, handle) ⇒ Object
-
#frame_nav_target_entry(target) ⇒ Object
Resolve a link/form ‘target` to the frame stack entry its navigation should rebuild, or nil when it targets the top page / a new context (the caller then falls through to a full-page `navigate` or aux window).
-
#frame_navigate_self(url, realm_id) ⇒ Object
A nested browsing context navigating its OWN ‘location` (the frame’s ‘location.href`/assign/replace/`location=`, incl. cross-frame `iframe.contentWindow.location.href = …`).
-
#frame_reload_self(realm_id) ⇒ Object
‘frame.contentWindow.location.reload()` from a nested browsing context.
-
#frame_self_target?(target) ⇒ Boolean
Does a link/form ‘target` load into the CURRENT frame? Empty or `_self` do; `_top` / `_blank` / `_parent` / a named context do not.
-
#frame_submit_self(realm_id) ⇒ Object
A <form> submitted from INSIDE a nested browsing context (a frame realm reached via ‘contentWindow`, not an entered `within_frame` block).
-
#geolocation_state_json ⇒ Object
Backs the ‘__csimGeolocationState` host fn.
-
#go_back ⇒ Object
Capybara-initiated ‘page.go_back` runs from Ruby, not inside a JS call, so it’s safe to rebuild the Context synchronously.
- #go_forward ⇒ Object
-
#handle_modal(type, message, default_value) ⇒ Object
JS-side ‘alert(…)` / `confirm(…)` / `prompt(…)` route here.
- #hijack_fetch_pending? ⇒ Boolean
-
#history_go(delta, force: false) ⇒ Object
Move through the history stack by ‘delta`.
-
#history_length ⇒ Object
Total history entries (after forward-tail truncation), surfaced to JS ‘history.length` via the `__historyLength` host fn.
-
#history_push(url, state = nil) ⇒ Object
‘history.pushState(state, _, url)` from SPA navigation (Turbo Visit, InstantClick, …) appends a new browser-history entry.
-
#history_state(url, state = nil) ⇒ Object
‘history.pushState(state, ”, ’/path’)‘ ships the URL through `__setCurrentUrl` and lands here.
-
#horizon_fast_forward_step ⇒ Object
This tick’s deterministic virtual-clock advance (ms).
- #hover(handle) ⇒ Object
-
#html ⇒ Object
‘page.html` inside a `within_frame` block returns the frame document’s source (Selenium parity), so route through the active realm.
-
#html_charset_signal?(content_type, raw) ⇒ Boolean
Does the response carry an explicit encoding signal (so the default windows-1252 decode must NOT apply)? A ‘charset=` in the Content-Type, or a `<meta charset>` / `<meta http-equiv=content-type … charset=…>` in the HTML prescan window (the first 1024 bytes, per the HTML sniffing algorithm).
-
#initialize(app, driver: nil, js_engine: nil, cookies: nil, local_storage: nil) ⇒ Browser
constructor
A new instance of Browser.
- #inner_html(handle) ⇒ Object
-
#invalidate_find_cache ⇒ Object
Any operation that may have mutated the DOM (click, set, send_keys, navigate, hover, …) must call this so the next find falls through to a fresh V8 query.
-
#location_assign(url) ⇒ Object
Defer the navigation: doing it from inside the running V8 call would dispose the Context mid-call.
-
#location_reload ⇒ Object
Mirror of ‘location_assign`’s deferral for ‘location.reload()`: the JS call lands here from `__locationReload`; running `browser.refresh` directly would `navigate` (rebuilding the Context) while we’re still inside the V8 call, which V8 terminates with a ‘ScriptTerminatedError`.
- #log_console(severity, message) ⇒ Object
- #log_network(method, url, status, **extra) ⇒ Object
- #lookup_node(handle) ⇒ Object
-
#mark_action_baseline ⇒ Object
Pin the URL the page is at as a user action BEGINS — the FIRST line of every action entry (click / double_click / right_click / hover / set / send_keys / select / unselect).
-
#marshal_args(args) ⇒ Object
Capybara passes Node instances directly as script args (‘session.evaluate_script(’arguments.click()‘, some_node)`).
- #mime_type_for_path(path) ⇒ Object
- #modifier_flags(keys) ⇒ Object
- #navigate_post(url, body, content_type, depth: 0, from_history: false) ⇒ Object
-
#navigate_realm_self(realm_id, get_url, action, method, body, enctype) ⇒ Object
Navigate the initiating frame realm itself (a self-targeted form submit).
- #node_path(handle) ⇒ Object
- #normalize_trace_headers(headers) ⇒ Object
-
#open_child_window(url, name) ⇒ Object
‘window.open(url, name)` from JS — returns the new (or reused, by name) window’s handle, or nil.
- #opener_handle ⇒ Object
-
#option_selected?(h) ⇒ Boolean
HTML spec: ‘<option>.selected` IDL is true when the `selected` attribute is set OR when no sibling option has `selected` and this is the first non-disabled option of a single-select `<select>` (implicit default).
- #outer_html(handle) ⇒ Object
- #parse_trace_mode(raw) ⇒ Object
-
#polling? ⇒ Boolean
Capybara polls find / has_? via ‘synchronize` while `Driver#wait?` is true.
-
#post_message_to_window(target_handle, data, origin) ⇒ Object
‘targetWindow.postMessage(data, origin)` — route to the target window’s inbox, tagged with this window as the source.
- #pure_fragment_navigation?(url) ⇒ Boolean
- #push_user_agent_to_js ⇒ Object
-
#rack_fetch(method, url, body, headers, redirect_mode, env_extras: nil) ⇒ Object
URLs we won’t even try to route through Rack: anything that isn’t http(s) (data: / mailto: / about:) plus pseudo-tokens like V8’s ‘<snapshot>` that sourcemap libraries pull out of error stacks and feed straight to `fetch()` / `xhr.open()`.
-
#rack_fetch_async(method, url, body, headers_json) ⇒ Object
── Hijack-aware async XHR ─────────────────────────────────────.
- #rack_fetch_async_abort(id) ⇒ Object
-
#rack_fetch_body(url) ⇒ Object
── Host-fn callbacks invoked by bridge.js ──────────────────.
-
#read_blob_for_window(url) ⇒ Object
Read a blob URL’s bytes + content type from THIS window’s VM (its local blob store) — the Driver uses it to load a blob: document into a fresh aux window opened by this window.
-
#read_file_pick(handle, index, start = nil, finish = nil) ⇒ Object
JS-side ‘__HostBackedFile.text()` / `arrayBuffer()` route through this to read attached file bytes on demand — ActiveStorage’s ‘DirectUpload` MD5-chunks the file via FileReader before POSTing to `/rails/active_storage/direct_uploads`.
-
#read_property(prop, doc: false) ⇒ Object
Read a primitive property off THIS window’s globalThis / document — called by the Driver to serve another window’s cross-window proxy read.
-
#read_rack_body(body) ⇒ Object
Rack response bodies must respond to ‘each` (or be an Array of strings).
-
#record_action(kind, description) ⇒ Object
Wraps a driver action so the trace records description, urls, console / network activity, and (on action error / full mode) a post-action DOM snapshot.
- #record_history(entry) ⇒ Object
- #record_response(status, headers) ⇒ Object
-
#record_url_transition(new_url) ⇒ Object
Called whenever ‘@current_url` is about to be set to a new value during a page-load drain or a settle tick driven by a user action; queues the prior URL for surface-via- `current_url` so a polling matcher walks the intermediate chain.
-
#refresh ⇒ Object
is just a re-GET.
- #replay_history_entry(entry) ⇒ Object
- #reset! ⇒ Object
- #reset_event_sources ⇒ Object
-
#reset_frame_scope ⇒ Object
Return DOM-op routing to the main document and drop any frame stack.
- #reset_hijacked_fetches ⇒ Object
-
#reset_timer_state ⇒ Object
Re-sync the Ruby-side timer mirror with a freshly-rebuilt JS context.
- #reset_websockets ⇒ Object
- #reset_workers ⇒ Object
- #resolve_against(url, base) ⇒ Object
-
#resolve_document_url(url) ⇒ Object
Public entry for the Driver to resolve a ‘window.open` / cross-window `location` URL against THIS window’s document (the internal resolver is private).
- #resolve_module_specifier(specifier, base_url) ⇒ Object
- #resolve_visit_url(url) ⇒ Object
- #response_hash(status, headers, body, url, redirected) ⇒ Object
-
#response_headers ⇒ Object
Rack 3 lowercases header names; Capybara tests do ‘[’Content-Type’]‘.
-
#revoke_owned_blobs(key) ⇒ Object
Revoke every blob URL owned by a context that’s going away (its blob URL store is part of the global being torn down).
- #revoke_realm_blobs(realm_id) ⇒ Object
-
#revoke_worker_blobs(handle) ⇒ Object
Keys are normalized with ‘.to_i` on BOTH sides (register tags “r:#owner_realmowner_realm.to_i”) so a marshalled Float/String id still matches.
- #right_click(handle, keys = [], **opts) ⇒ Object
-
#same_document_traversal?(from, to) ⇒ Boolean
Same-document = every entry between ‘from` and `to` (inclusive) is a `:push_state` entry (or the boundary just changed state on the current URL).
- #select_option(handle) ⇒ Object
-
#send_keys(handle, keys) ⇒ Object
Capybara’s ‘send_keys` accepts Strings and Symbols (special keys: `:enter`, `:tab`, `:backspace`, …) and Array combos (modifier + key).
- #send_session_key(key) ⇒ Object
-
#send_session_keys(keys) ⇒ Object
Session-level keystroke.
-
#set_geolocation(latitude: nil, longitude: nil, accuracy: 10, denied: false, **rest) ⇒ Object
CDP-ish shim: override navigator.geolocation (like CDP’s ‘Emulation.setGeolocationOverride`).
- #set_header(name, value) ⇒ Object
-
#set_importmap(json) ⇒ Object
JS-side ‘ingestImportmaps` calls this through the host fn so Ruby-side `resolve_module_specifier` agrees with the bare- specifier map shipped by `<script type=“importmap”>`.
- #set_value_with_events(handle, value) ⇒ Object
- #set_viewport(w, h) ⇒ Object
- #set_window_location(handle, url) ⇒ Object
-
#settle ⇒ Object
Yield on the first observable change.
- #shadow_root_handle(handle) ⇒ Object
- #stack_resolver ⇒ Object
- #start_trace(metadata = {}) ⇒ Object
- #status_code ⇒ Object
- #storage_clear(kind) ⇒ Object
-
#storage_get(kind, key) ⇒ Object
Web Storage host-fn shims.
- #storage_key(kind, index) ⇒ Object
- #storage_length(kind) ⇒ Object
- #storage_remove(kind, key) ⇒ Object
- #storage_set(kind, key, value) ⇒ Object
-
#submit_form(handle) ⇒ Object
‘Node#submit(*)` (Capybara DSL) hits here.
-
#submit_form_handle(form_handle, submitter_handle) ⇒ Object
Pulls the serialised form-state out of JS, encodes it, and drives the Rack app via ‘navigate` (for GET) or a POST.
-
#submit_form_in_realm(realm_id, form_handle, submitter_handle) ⇒ Object
Serialize + route a form submitted inside frame realm ‘realm_id`.
-
#switch_to_frame(target) ⇒ Object
Capybara ‘switch_to_frame`.
-
#syntax_or_invalid_selector_error?(e) ⇒ Boolean
JS-side selector parser throws a ‘DOMException(’csim: …‘, ’SyntaxError’)‘.
- #tag(handle) ⇒ Object
- #tag_name(handle) ⇒ Object
- #text(handle) ⇒ Object
- #text_response?(headers) ⇒ Boolean
-
#tick_real_time(step_ms: nil) ⇒ Object
Advance the virtual JS clock and fire timers that came due.
- #timer_wait_elapsed? ⇒ Boolean
- #title ⇒ Object
-
#trace_network(method, url, status, req_headers, req_body, resp_headers, resp_body, t0, redirected) ⇒ Object
Enriched network log for the trace: response content-type / byte size / elapsed ms / redirect flag, plus request + response headers and bodies (devtools-style).
- #transfer_buffer_fetch(id) ⇒ Object
-
#transfer_buffer_fetch_for_js(id) ⇒ Object
Wraps the raw bytes in whatever binary shape the ACTIVE runtime can marshal to a JS Uint8Array (V8: the BINARY-tagged string itself — tag-driven marshalling crosses it as a Uint8Array; QuickJS: base64 that the JS shim’s ‘fetchedToBytes` atob’s — it has no binary marshaller).
-
#transfer_buffer_stash(bytes) ⇒ Object
── postMessage transferable-buffer registry ───────────────────.
-
#transfer_token_issued(token) ⇒ Object
JS reports each zero-copy transfer token it mints (‘RustyRacer.transferOut`) so we can release any that go unimported.
- #unselect_option(handle) ⇒ Object
- #update_current_hash(url) ⇒ Object
- #value(handle) ⇒ Object
- #viewport_height ⇒ Object
- #viewport_width ⇒ Object
- #visible?(handle) ⇒ Boolean
- #visible_text(handle) ⇒ Object
-
#visit(url) ⇒ Object
Address-bar navigation: no Referer, and relative paths resolve against the host root (not the current page’s directory).
- #webauthn ⇒ Object
- #websocket_pending? ⇒ Boolean
- #window_closed?(handle) ⇒ Boolean
- #window_doc_get(handle, prop) ⇒ Object
-
#window_get(handle, prop) ⇒ Object
Cross-window property reads (a WindowProxy ‘win.foo` / `win.document.foo`): route to the Driver, which reads a PRIMITIVE off the target window’s VM.
- #window_location_of(handle) ⇒ Object
-
#window_message_pending? ⇒ Boolean
Covers both cross-window postMessage AND BroadcastChannel — the two cross-window event channels share these drain/pending hooks.
-
#with_modal(handler) ⇒ Object
Push a one-shot handler onto the modal-dialog stack — the next modal that fires consumes the topmost handler.
- #worker_pending? ⇒ Boolean
- #worker_post_to_worker(handle, data) ⇒ Object
-
#worker_spawn(url, shared: false) ⇒ Object
── Web Workers ────────────────────────────────────────────────.
- #worker_terminate(handle) ⇒ Object
- #write_document_cookie(s) ⇒ Object
- #ws_close(id, code = 1000, reason = '') ⇒ Object
- #ws_open(url, protocols = nil) ⇒ Object
-
#ws_send(id, data, binary = false, b64 = false) ⇒ Object
‘binary` is set by the JS side (it knows whether `send` was given a string or an ArrayBuffer/view) → opcode 0x2 vs the text 0x1.
-
#xml_content_type?(content_type) ⇒ Boolean
Strip + decode a single leading byte-order mark, returning ‘[utf8_text, charset]` — `charset` is the BOM-selected Encoding-standard name (highest-precedence encoding signal) or nil when there’s no BOM (the hot path: just a 2–3 byte prefix check).
- #xpath_shaped?(s) ⇒ Boolean
Constructor Details
#initialize(app, driver: nil, js_engine: nil, cookies: nil, local_storage: nil) ⇒ Browser
Returns a new instance of Browser.
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 |
# File 'lib/capybara/simulated/browser.rb', line 170 def initialize(app, driver: nil, js_engine: nil, cookies: nil, local_storage: nil) @app = app @driver = driver @runtime = build_runtime(js_engine) # Per-poll clock decisions cached at construction (CLAUDE.md rule 3 — the # runtime type + env are fixed for the session): the wall-sync escape # hatch and whether the runtime exposes the fast-forward timer query. @clock_wall = !ENV['CSIM_CLOCK_WALL'].nil? @runtime_supports_ff = @runtime.respond_to?(:next_timer_delay_ms) @current_url = nil # Real browsers yield control between asynchronous URL # transitions (XHR-driven model loads, then `replaceWith` to a # child route), so Capybara polls catch the intermediate URL — # e.g. Discourse's `/wizard` → `/wizard/steps/setup` flow holds # at `/wizard` while `Wizard.load()` runs. Our env drains # microtasks synchronously and only the final URL is reachable # by the time Ruby regains control. Queue URLs we transitioned # through; `current_url` shifts one out per call so a polling # `assert_current_path` walks the same set the real browser # would have observed. @recent_urls = [] @recent_urls_last_push_at = nil # The URL the page was at when the current user-action drain began. # It's the *starting point* of the action, not an intermediate the # action transitioned through, so a pushState/replaceState back to a # fresh URL during the drain (a Turbo Drive Visit triggered by the # action) must NOT queue it into `@recent_urls` — otherwise a one-shot # `current_url` read after the action returns the pre-action URL # instead of the navigated-to one (Avo filter `encoded_filters`). @action_url_baseline = nil # The URL of the page that navigated to the current document — # HTTP `Referer` header on the response that loaded the page, # exposed to JS as `document.referrer`. Tracked by `navigate` # so post-auth flows (Discourse login: `cookie('destination_url', # referrer)` when navigating from `/t/N` → `/login` via link # click) can reconstruct the origin URL. @current_referer = '' # Cookies + localStorage are origin-shared in real browsers — # the Driver injects the jars so aux windows (per-window VMs) # see the same auth state and storage as the primary. Tests # without a Driver (gem-internal callers) get fresh jars. @cookies = || {} @local_storage = local_storage || {} @session_storage = {} @sticky_headers = {} @timers_active = false # Capybara config is set once per suite; cache the derived # origin so the per-request fallback path doesn't re-dispatch # `Capybara.app_host` / `server_host` / `server_port` on every # rack call (CLAUDE.md: cache env decisions at construction). @default_host = self.class.default_host # Handle IDs are per-Context integer sequences: a handle from # a pre-rebuild context could collide with a fresh node's id # in the new context. Node captures this on construction; # `check_stale` rejects on mismatch. @context_gen = 0 @find_cache_dirty = true @find_cache_kind = nil @find_cache_arg = nil @find_cache_ctx = nil @find_cache_value = nil @document_handle = 0 # `within_frame` state. `@current_realm_id` is the V8 context id of the # active frame realm (nil = the main document); `@frame_stack` records # the enclosing realms so `switch_to_frame(:parent)` can pop one level. # DOM / node / query ops route through `dom_call`, which dispatches to # this realm. nil is the steady state, so the routing is one nil-check. @current_realm_id = nil @frame_stack = [] @last_tick_ts = Process.clock_gettime(Process::CLOCK_MONOTONIC) @polling_grace = nil @last_polled_gen = nil @idle_settle_polls = 0 @ticking = false @history = [] @history_idx = -1 @modal_handlers = [] # Geolocation override (CDP-ish). nil = no override configured → # navigator.geolocation reports POSITION_UNAVAILABLE. Ruby-backed so # it survives the per-call VM rebuilds, like web storage. Read by the # `__csimGeolocationState` host fn. @geolocation = nil # Per-test action trace. `@trace` is the live recorder; `reset!` # moves it to `@pending_trace` so an after-hook running after # session reset still has access. `@trace_mode` is cached at # construction so `record_action`'s hot path doesn't pay an # ENV lookup. # # `CSIM_TRACE=off|on-failure|full` (default `on-failure`): # - `off` — no recording at all; `record_action` early-exits. # - `on-failure` — record kind/url/console/network in-memory; # snapshot `dom_after` only on action error. # - `full` — record + snapshot DOM after every action # (debug-heavy). # File output is orthogonal — `CSIM_TRACE_DIR=path` makes the # test-runner hook persist the trace JSON there; unset means # in-memory only (no files written without explicit opt-in). @trace = nil @pending_trace = nil @recording_action = false @trace_mode = parse_trace_mode(ENV['CSIM_TRACE']) # EventSource (SSE) — per-Browser handle counter, background # reader threads, and a thread-safe Queue of parsed events # awaiting delivery into the VM. Threads do the long-lived # HTTP read; the main thread polls the Queue in `settle` and # dispatches via `__csim_deliverEventSourceEvents`. @event_source_seq = 0 @event_source_threads = {} @event_source_queue = Thread::Queue.new # WebSocket — per-Browser handle counter, background frame-reader # threads, the csim-side socket end of each connection (for writing # client→server frames), and a Queue of lifecycle / message events # awaiting delivery into the VM. Same model as SSE: the reader thread # does the blocking socket read; the main thread drains the Queue in # `settle` and dispatches via `__csim_deliverWebSocketEvents`. The # connection rides the in-process `rack.hijack` socket Action Cable # (and any Rack WebSocket middleware) takes over. @websocket_seq = 0 @websocket_threads = {} @websocket_sockets = {} # id → csim's socket end (main thread owns this hash) @websocket_app_sockets = {} # id → the app's hijack end (closed on teardown) @websocket_queue = Thread::Queue.new # All frame writes (the reader thread's pong replies + the main thread's # send/close) go through one socket; serialise them so two threads can't # interleave bytes into a corrupt frame. @websocket_write_lock = Mutex.new # Hijacked-XHR delivery — per-Browser handle counter, # background threads, and a Queue of completed responses for # Rack calls where the middleware used `rack.hijack` to hold # the connection open (the contract `message_bus`'s long-poll # uses to push publishes immediately rather than waiting for # the next client poll). Same shape as SSE: the thread reads # the hijacked pipe; main settle drains the Queue and # dispatches via `__csim_deliverHijackedFetches`. @hijack_fetch_seq = 0 @hijack_fetch_threads = {} @hijack_fetch_queue = Thread::Queue.new # Web Workers — per-Browser handle counter, per-worker # {thread, inbox} pair, and a shared outbox the main settle # drains via `__csim_deliverWorkerMessages`. Each worker # thread owns its own V8 Context / QuickJS VM (real isolate); # cross-isolate messaging is JSON-marshalled. @worker_seq = 0 @workers = {} @worker_outbox = Thread::Queue.new # Outstanding posts-to-worker; `polling?` stays true while > 0 # so long-running compute (e.g. mozjpeg over an 8900×8900 frame) # isn't starved by the settle_gen idle gate. @worker_in_flight = 0 # Workers whose initial script hasn't finished running yet. A worker that # posts immediately on spawn (no main->worker message first) would leave # `@worker_in_flight` at 0, so `worker_pending?` would be false in the gap # between spawn and that first post — and settle / tick_real_time would # stop waiting before the message lands. Count spawned-but-not-initialised # workers so the async drain holds until the initial script has run. @worker_initializing = 0 @worker_init_lock = Mutex.new # Cross-isolate `blob:` store. Worker isolates can't see the # main scope's `__csimBlobs` Map, so we mirror bytes here and # workers resolve them through a host fn. @blob_registry = {} @blob_registry_lock = Mutex.new # url => owning worker handle, for blob URLs created INSIDE a worker. A # worker's blob URL store dies with it, so terminating the worker revokes # them (url-lifetime "Terminating worker revokes its URLs"). @blob_owners = {} # Postmessage transferable-buffer store. Large Uint8Array / # ArrayBuffer payloads cross isolates as a Ruby-side byte ID # rather than a JSON base64 string, so peak JS heap stays flat. @transfer_buffer_lock = Mutex.new @transfer_buffers = {} @transfer_buffer_seq = 0 # Zero-copy postMessage transfer tokens (rusty_racer >= 0.1.6 # `RustyRacer.transferOut`): a buffer in a `postMessage` transfer list # crosses isolates by token (no byte copy), its source detached. A token # parked but never imported pins its backing store PROCESS-WIDE, so we # record every issued token (reported from JS, possibly on a worker # thread — hence the lock) and `transferDrop` the lot on `reset!` # (idempotent: an already-imported token no-ops). @transfer_tokens = [] @transfer_tokens_lock = Mutex.new # Cross-window `postMessage` inbox. Another window's `target.postMessage` # routes through the Driver and lands here; this window drains it into a # `message` event the next time it's active and settles/ticks. Plain # array (same thread — windows aren't background-threaded like workers). @window_inbox = [] # Cross-window BroadcastChannel messages from OTHER windows, delivered to # this window's matching channels on settle. [{name, data}] (same thread). @broadcast_inbox = [] end |
Instance Attribute Details
#context_gen ⇒ Object (readonly)
Returns the value of attribute context_gen.
2109 2110 2111 |
# File 'lib/capybara/simulated/browser.rb', line 2109 def context_gen @context_gen end |
#current_realm_id ⇒ Object (readonly)
Returns the value of attribute current_realm_id.
513 514 515 |
# File 'lib/capybara/simulated/browser.rb', line 513 def current_realm_id @current_realm_id end |
#default_user_agent ⇒ Object
Capybara’s ‘current_window.resize_to(w, h)` lands here; the ahoy hamburger test (mobile breakpoint at 425×694) and any responsive-utility-aware test (Tailwind `m:` show / hide, bootstrap `.d-md-flex`, …) depends on this surfacing through the JS-side `innerWidth` / `innerHeight` so the cascade’s ‘mediaMatches` and `matchMedia()` evaluate against the test’s chosen viewport instead of the 1024×768 default. Sticky defaults applied at ‘reset!`. Used by the driver to carry mobile viewport / user-agent across per-test resets —without these the second mobile-tagged spec sees the desktop default. The user-agent also flows into `navigator.userAgent` on every VM rebuild so JS-side UA branches (Discourse’s ‘viewport_based_mobile_mode = false` path) resolve correctly.
1559 1560 1561 |
# File 'lib/capybara/simulated/browser.rb', line 1559 def default_user_agent @default_user_agent end |
#default_viewport ⇒ Object
Capybara’s ‘current_window.resize_to(w, h)` lands here; the ahoy hamburger test (mobile breakpoint at 425×694) and any responsive-utility-aware test (Tailwind `m:` show / hide, bootstrap `.d-md-flex`, …) depends on this surfacing through the JS-side `innerWidth` / `innerHeight` so the cascade’s ‘mediaMatches` and `matchMedia()` evaluate against the test’s chosen viewport instead of the 1024×768 default. Sticky defaults applied at ‘reset!`. Used by the driver to carry mobile viewport / user-agent across per-test resets —without these the second mobile-tagged spec sees the desktop default. The user-agent also flows into `navigator.userAgent` on every VM rebuild so JS-side UA branches (Discourse’s ‘viewport_based_mobile_mode = false` path) resolve correctly.
1559 1560 1561 |
# File 'lib/capybara/simulated/browser.rb', line 1559 def @default_viewport end |
#pending_trace ⇒ Object (readonly)
Returns the value of attribute pending_trace.
1713 1714 1715 |
# File 'lib/capybara/simulated/browser.rb', line 1713 def pending_trace @pending_trace end |
#timers_active=(value) ⇒ Object (writeonly)
Sets the attribute timers_active
57 58 59 |
# File 'lib/capybara/simulated/browser.rb', line 57 def timers_active=(value) @timers_active = value end |
#trace ⇒ Object (readonly)
Returns the value of attribute trace.
1713 1714 1715 |
# File 'lib/capybara/simulated/browser.rb', line 1713 def trace @trace end |
#trace_mode ⇒ Object (readonly)
Returns the value of attribute trace_mode.
1713 1714 1715 |
# File 'lib/capybara/simulated/browser.rb', line 1713 def trace_mode @trace_mode end |
#window_handle ⇒ Object
The Driver’s handle for the window this Browser backs (set right after construction). Lets host fns name the source window of a cross-window ‘postMessage` / `window.open` so the Driver can route to the target.
62 63 64 |
# File 'lib/capybara/simulated/browser.rb', line 62 def window_handle @window_handle end |
Class Method Details
.default_host ⇒ Object
Fallback origin for ‘visit(’/foo’)‘ and friends when no current page is loaded yet. Track Capybara’s idea of the test server (‘app_host` if set, else explicitly-configured `server_host` / `server_port`) so the host header reaching the Rack app matches what host-specific helpers expect — Discourse’s ‘setup_system_test` sets `SiteSetting.force_hostname = Capybara.server_host` / `port = Capybara.server_port`, and the request-tracker specs assert `event == Discourse.base_url_no_prefix + path`, which derives from the same SiteSetting pair. We only consult `server_host` when it was explicitly set: Capybara’s getter returns ‘’127.0.0.1’‘ when unset, but Rack::Test’s hardcoded default origin is ‘www.example.com` and capybara’s own shared specs hard-code that literal — fall back to it when no suite-side configuration is in play.
41 42 43 44 45 46 47 |
# File 'lib/capybara/simulated/browser.rb', line 41 def self.default_host return ::Capybara.app_host if ::Capybara.app_host host = ::Capybara.server_host return 'http://www.example.com' if host == '127.0.0.1' port = ::Capybara.server_port.to_i port > 0 ? "http://#{host}:#{port}" : "http://#{host}" end |
.remote_addr_for(host) ⇒ Object
161 162 163 164 |
# File 'lib/capybara/simulated/browser.rb', line 161 def self.remote_addr_for(host) = host.to_s.downcase.sub(/:\d+\z/, '').sub(/\A\[(.+)\]\z/, '\1') == 'localhost' ? REMOTE_ADDR_IPV6 : REMOTE_ADDR_IPV4 end |
Instance Method Details
#active_element_handle ⇒ Object
1680 1681 1682 1683 1684 |
# File 'lib/capybara/simulated/browser.rb', line 1680 def active_element_handle tick_real_time h = dom_call('__csimActiveElement').to_i h.zero? ? nil : h end |
#advance_virtual_clock_ms(ms) ⇒ Object
2087 2088 2089 2090 |
# File 'lib/capybara/simulated/browser.rb', line 2087 def advance_virtual_clock_ms(ms) ms = ms.to_i tick_real_time(step_ms: ms) if ms > 0 end |
#all_text(handle) ⇒ Object
Capybara::Driver::Node surface — Node calls ‘check_stale` before each read, and that advances the virtual clock.
794 |
# File 'lib/capybara/simulated/browser.rb', line 794 def all_text(handle) = text(handle) |
#annotate_console_message(severity, message) ⇒ Object
1797 1798 1799 1800 1801 |
# File 'lib/capybara/simulated/browser.rb', line 1797 def (severity, ) return unless ANNOTATABLE_SEVERITIES.include?(severity.to_s) return unless .is_a?(String) && .include?('://') stack_resolver.annotate() end |
#append_multipart_part(body, boundary, name, content, filename: nil, content_type: nil) ⇒ Object
2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 |
# File 'lib/capybara/simulated/browser.rb', line 2203 def append_multipart_part(body, boundary, name, content, filename: nil, content_type: nil) body << "--#{boundary}\r\n" disposition = %[form-data; name="#{name}"] disposition += %[; filename="#{filename}"] if filename body << "Content-Disposition: #{disposition}\r\n" body << "Content-Type: #{content_type}\r\n" if content_type body << "\r\n" body << content.to_s.b body << "\r\n" end |
#apply_request_headers(env, headers) ⇒ Object
CGI convention: ‘Content-Type` and `Content-Length` land in env without the HTTP_ prefix. Rails / Rack params parsing reads `CONTENT_TYPE` and dispatches JSON / multipart parsers off it; sending it as `HTTP_CONTENT_TYPE` lets the request through but with the default `text/plain`, so JSON bodies from `@rails/request.js` never deserialise and the server reads an empty params hash.
3780 3781 3782 3783 3784 3785 3786 3787 3788 |
# File 'lib/capybara/simulated/browser.rb', line 3780 def apply_request_headers(env, headers) headers.each {|k, v| name = k.to_s.upcase.tr('-', '_') case name when 'CONTENT_TYPE', 'CONTENT_LENGTH' then env[name] = v.to_s else env["HTTP_#{name}"] = v.to_s end } end |
#async_io_pending? ⇒ Boolean
Cheap O(1) gate: is there any non-timer async channel with traffic that ‘tick_real_time` would drain? `tick_real_time` itself runs exactly when `worker_pending? || event_source_pending? || hijack_fetch_pending?` (plus `@timers_active`), and each of those predicates is a single `.empty?` / counter check. Reusing them here lets an attribute poll whose value is delivered only by a Worker / SSE / hijacked-fetch message (with no active timer) still drain that channel, without paying an unconditional drain on timer-driven runloop pages.
747 748 749 |
# File 'lib/capybara/simulated/browser.rb', line 747 def async_io_pending? worker_pending? || event_source_pending? || hijack_fetch_pending? || || websocket_pending? end |
#attr(handle, name) ⇒ Object
784 |
# File 'lib/capybara/simulated/browser.rb', line 784 def attr(handle, name) = dom_call('__csimAttr', handle, name.to_s) |
#blob_register(url, body_b64, owner_realm = nil) ⇒ Object
3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 |
# File 'lib/capybara/simulated/browser.rb', line 3266 def blob_register(url, body_b64, owner_realm = nil) # Tag the creating context so the URL is revoked when that context goes # away: a WORKER (separate thread, tagged via Thread.current) when it # terminates ("Terminating worker"), or a FRAME REALM (owner_realm passed # from JS createObjectURL) when the iframe is removed ("Removing an # iframe"). Namespaced ('w:' / 'r:') so a worker handle and a realm id # never collide. Main-realm blobs (no owner) live until clear_volatile. worker = Thread.current[:csim_worker_handle] key = if worker then "w:#{worker}" elsif owner_realm && owner_realm.to_i != 0 then "r:#{owner_realm.to_i}" end @blob_registry_lock.synchronize do @blob_registry[url.to_s] = body_b64.to_s # Keep ownership in sync both ways: a (re-)registration with no owner # (main thread / main realm) must DROP any prior owner, else revoking # that context would wrongly revoke a now-page-owned URL. if key then @blob_owners[url.to_s] = key else @blob_owners.delete(url.to_s) end end nil end |
#blob_resolve(url) ⇒ Object
3287 3288 3289 |
# File 'lib/capybara/simulated/browser.rb', line 3287 def blob_resolve(url) @blob_registry_lock.synchronize { @blob_registry[url.to_s] } end |
#blob_unregister(url) ⇒ Object
3340 3341 3342 3343 |
# File 'lib/capybara/simulated/browser.rb', line 3340 def blob_unregister(url) @blob_registry_lock.synchronize { @blob_registry.delete(url.to_s); @blob_owners.delete(url.to_s) } nil end |
#boot_blob_document(url, bytes, content_type) ⇒ Object
Load a blob: document (bytes from the opener) as THIS window’s top-level document — for ‘window.open(blobURL)` / a blob: aux-window navigation, where the blob isn’t rack-navigable and lives in the opener’s isolate.
3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 |
# File 'lib/capybara/simulated/browser.rb', line 3327 def boot_blob_document(url, bytes, content_type) @current_url = url.to_s ct = content_type.to_s.empty? ? 'text/html' : content_type.to_s # Blob string parts are UTF-8-encoded; when the Blob type carries no # charset, decode the document as UTF-8 (not the windows-1252 HTML locale # default, which is an HTTP concept that doesn't apply to in-memory blobs — # matches the iframe blob: path's decodeBlobBody). A charset in the Blob # type (url-charset) is preserved so it can override <meta charset>. ct = "#{ct};charset=utf-8" unless ct.downcase.include?('charset') record_response(200, {'content-type' => ct}) boot_response_into_ctx(bytes) end |
#broadcast_to_windows(name, data) ⇒ Object
‘BroadcastChannel.postMessage` in THIS window — fan out to every OTHER window’s matching channels (same-window delivery happens in-VM).
3202 3203 3204 |
# File 'lib/capybara/simulated/browser.rb', line 3202 def broadcast_to_windows(name, data) @driver.broadcast_channel(self, name.to_s, data) if @driver.respond_to?(:broadcast_channel) end |
#build_multipart_body(fields, file_inputs) ⇒ Object
2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 |
# File 'lib/capybara/simulated/browser.rb', line 2153 def build_multipart_body(fields, file_inputs) boundary = "csim-#{SecureRandom.hex(8)}" body = String.new.force_encoding(Encoding::ASCII_8BIT) fields.each do |name, value| append_multipart_part(body, boundary, name, value.to_s) end file_inputs.each do |fi| picks = file_pick_paths(fi) if picks.empty? append_multipart_part(body, boundary, fi['name'].to_s, '', filename: '') else picks.each do |path| append_multipart_part(body, boundary, fi['name'].to_s, File.binread(path), filename: File.basename(path), content_type: Rack::Mime.mime_type(File.extname(path))) end end end body << "--#{boundary}--\r\n" {content_type: "multipart/form-data; boundary=#{boundary}", body: body} end |
#build_runtime(engine) ⇒ Object
374 375 376 377 378 379 380 381 382 383 384 385 386 |
# File 'lib/capybara/simulated/browser.rb', line 374 def build_runtime(engine) engine ||= detect_js_engine case engine when :v8 require_relative 'v8_runtime' V8Runtime.new(self) when :quickjs require_relative 'quickjs_runtime' QuickJSRuntime.new(self) else raise ArgumentError, "unknown CSIM_JS_ENGINE #{engine.inspect}; expected one of #{JS_ENGINES.inspect}" end end |
#cached_find(kind, arg, ctx) ⇒ Object
Single-slot cache for the most recent find_xpath / find_css / find_first_css result. Capybara’s ‘synchronize` retry loop re-issues the same find on every poll while waiting for an element to appear or disappear; if no DOM-mutating event has happened since the last call (no timer fired, no click / set / navigate), the result is guaranteed identical and we can skip the V8 round-trip + xpathway traversal.
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 |
# File 'lib/capybara/simulated/browser.rb', line 758 def cached_find(kind, arg, ctx) if !@find_cache_dirty && @find_cache_kind == kind && @find_cache_ctx == ctx && @find_cache_arg == arg return @find_cache_value end result = yield @find_cache_kind = kind @find_cache_arg = arg @find_cache_ctx = ctx @find_cache_value = result @find_cache_dirty = false result end |
#cap_trace_body(body) ⇒ Object
JSON-safe body for the trace: binary (non-UTF-8) bodies become a placeholder rather than mojibake, and long bodies are truncated (scrubbed so a mid-codepoint cut can’t yield invalid UTF-8).
Rack response bodies are ASCII-8BIT (BINARY); reinterpret the bytes as UTF-8 up front and keep working in UTF-8 throughout. Otherwise a body whose bytes ARE valid UTF-8 but stays BINARY-tagged would flow out of here still BINARY, and the first concat with a UTF-8 string (the truncation marker here, or the trace-buffer / JSON serialization downstream) raises Encoding::CompatibilityError on any byte ≥ 0x80.
3762 3763 3764 3765 3766 |
# File 'lib/capybara/simulated/browser.rb', line 3762 def cap_trace_body(body) s = body.to_s.dup.force_encoding('UTF-8') return "[binary, #{s.bytesize} bytes]" unless s.valid_encoding? s.bytesize > NETWORK_BODY_CAP ? (s.byteslice(0, NETWORK_BODY_CAP).scrub + "\n…[truncated, #{s.bytesize} bytes total]") : s end |
#check_stale(handle, initial, gen = nil) ⇒ Object
825 826 827 828 829 830 831 832 |
# File 'lib/capybara/simulated/browser.rb', line 825 def check_stale(handle, initial, gen = nil) return if initial && (gen.nil? || gen == @context_gen) && dom_call('__csimAlive', handle) tick_real_time return if initial && (gen.nil? || gen == @context_gen) && dom_call('__csimAlive', handle) raise Capybara::Simulated::StaleElement, "Element with handle #{handle} is no longer attached to the document" end |
#clear_trace! ⇒ Object
1736 1737 1738 1739 1740 |
# File 'lib/capybara/simulated/browser.rb', line 1736 def clear_trace! @trace = nil @pending_trace = nil @runtime.call('__csimSetTraceActive', false) end |
#click(handle, keys = [], **opts) ⇒ Object
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 |
# File 'lib/capybara/simulated/browser.rb', line 847 def click(handle, keys = [], **opts) mark_action_baseline tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) init = click_event_init(handle, keys, opts) delay = opts[:delay].to_f action = if delay > 0 # Wall-sleep between mousedown and mouseup so click handlers # reading `Date.now()` see the elapsed gap (selenium parity). init['mouseDownOnly'] = true partial = dom_call('__csimClickResolve', handle, init) sleep delay dom_call('__csimClickFinish', handle, partial.is_a?(Hash) ? partial['base'] : init) else dom_call('__csimClickResolve', handle, init) end unless action.is_a?(Hash) settle # Drain the download intent the click chain may have queued. # Avo's action-download path: form submit → Turbo applies a # turbo-stream → `StreamActions.download` → file-saver's # `saveAs` → `setTimeout(() => click(<a download>), 0)` → # our dispatchEvent default-action sets # `__csimPendingDownload`. Settle bails on the first # observable change (the stream-render mutation), so the # await-chain inside the stream's `connectedCallback` # (`await nextRepaint(); await performAction()` → # `setTimeout(click(a), 0)`) hasn't reached saveAs yet — # nudge it forward with a few alternating microtask / # timer drain rounds, then consume directly. (Can't route # via `tick_real_time`: post-drain `@timers_active` is # false and it bails before its own consume_pending_* # drains.) if @runtime.respond_to?(:drain_microtasks) && @runtime.respond_to?(:drain_timers) # Most clicks don't queue any timers; bail as soon as a # round drains nothing rather than burning the full 8 engine # round-trips. Profile (Avo actions_spec / V8): the # unconditional loop cost ~7.7 % of wall time. 8.times do @runtime.drain_microtasks break if @runtime.drain_timers(50).to_i.zero? end end consume_pending_download # Discourse's `lib/click-track.js` preventDefaults link # clicks and routes navigation through `DiscourseURL # .redirectTo → window.location = href`, which our setter # parks on `@pending_location`. Drain it here so attachment # downloads from `click_link` complete inside the click # action. consume_pending_location consume_pending_frame_nav return end case action['kind'] when 'navigate' url = action['url'].to_s target = action['target'].to_s # Inside a frame, a frame-targeted link (self, or `_parent` of a # ≥2-deep frame) navigates that FRAME, not the top page: fetch + # rebuild its realm. A self-targeted pure-fragment link is already # handled in-realm by the frame's own location JS, so skip it. if (frame_entry = frame_nav_target_entry(target)) unless frame_entry.equal?(@frame_stack.last) && (url) tick_real_time navigate_frame(resolve_against_current(url, use_base: true), entry: frame_entry) end # `target="_blank"` (or any non-_self/_top/_parent name) opens # in a new browsing context (its own Browser/VM); the primary # stays put (per HTML spec — original window is unaffected). No # `opener_handle` is passed: modern browsers default `target=_blank` # to `noopener` (so `window.opener` is null), unlike JS `window.open` # which keeps the opener — see `open_window_from_js`. elsif !target.empty? && !%w[_self _top _parent].include?(target.downcase) && @driver.respond_to?(:open_aux_window) @driver.open_aux_window(resolve_against_current(url, use_base: true), source: self, blob_snapshot: action['blob']) # In-page anchor links (`#frag` / current-page + `#frag`) move # the hash but don't fetch a new document. Pure-fragment also # short-circuits the `<a>`s test fixtures use as click sinks. elsif (url) update_current_hash(url) else # Drain any work the click handler queued before the VM gets # rebuilt — analytics libraries (Ahoy / segment / GA) queue # the event into a setTimeout-driven flush and rely on the # browser firing it before navigation tears their context # down. Without this drain the tracking POST is lost on # every internal link click. tick_real_time # Link clicks honour `<base href>` (HTML spec); `visit` # does not — that's address-bar navigation. navigate(resolve_against_current(url, use_base: true)) end when 'submit' # Drain any work the click handler queued before the form # submission. Mastodon's logout flow: submit-button click # fires the form handler, which kicks off an axios DELETE for # `/auth/sign_out`; the response sets # `window.location.href = '/auth/sign_in'`. Without the # drain, we'd submit the form (no `action` attr → current # URL, e.g. `/start`) before the XHR resolves, landing on # the wrong page. Loop matches the navigate branch — bail # as soon as a drain round fires nothing. submit_baseline_url = @current_url if @runtime.respond_to?(:drain_microtasks) && @runtime.respond_to?(:drain_timers) 8.times do @runtime.drain_microtasks break if @runtime.drain_timers(50).to_i.zero? end end # If the drain queued or consumed a `location.assign`, that # navigation supersedes the form's default submit. Honour # pending; if `@current_url` already changed mid-drain (the # navigate landed during a timer fire), skip the form submit # entirely — its form handle is in a stale VM by now. consume_pending_frame_nav if @pending_location consume_pending_location elsif @current_url != submit_baseline_url # Already navigated; nothing more to do. else submit_form_handle(action['formHandle'], action['submitter']) end when 'download' download_link(resolve_against_current(action['url'].to_s), action['filename'].to_s) end end |
#click_event_init(handle, keys, opts) ⇒ Object
Resolve click offset against the element’s CSS-declared box. ‘opts == :center` means “x/y is relative to the element’s centre” (Capybara’s w3c_click_offset semantics); otherwise the offset is relative to the top-left. We don’t run a real layout engine — ‘__csimElementRect` reads top / left / width / height from the cascade so tests that declare those values via CSS see honest coordinates.
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 |
# File 'lib/capybara/simulated/browser.rb', line 1237 def click_event_init(handle, keys, opts) out = modifier_flags(keys) has_xy = opts[:x] || opts[:y] center = opts[:offset] == :center || !has_xy if has_xy || center rect = dom_call('__csimElementRect', handle) base_x = rect['x'].to_f + (center ? rect['width'].to_f / 2.0 : 0.0) base_y = rect['y'].to_f + (center ? rect['height'].to_f / 2.0 : 0.0) out['clientX'] = base_x + opts[:x].to_f out['clientY'] = base_y + opts[:y].to_f end out end |
#close_child_window(handle) ⇒ Object
3166 |
# File 'lib/capybara/simulated/browser.rb', line 3166 def close_child_window(handle) = (@driver.close_window(handle.to_s) if @driver.respond_to?(:close_window)) |
#coerce_set_value(v) ⇒ Object
1093 1094 1095 1096 1097 1098 1099 |
# File 'lib/capybara/simulated/browser.rb', line 1093 def coerce_set_value(v) case v when Pathname then v.to_s when Array then v.map {|x| x.is_a?(Pathname) ? x.to_s : x.to_s } else v end end |
#computed_style(handle, names) ⇒ Object
813 814 815 816 817 818 |
# File 'lib/capybara/simulated/browser.rb', line 813 def computed_style(handle, names) tick_real_time result = dom_call('__csimComputedStyle', handle, names.map(&:to_s)) return names.to_h {|n| [n, ''] } unless result.is_a?(Hash) result.transform_keys(&:to_s) end |
#consume_pending_aux_window ⇒ Object
A script-driven ‘anchor.click()` / `target=_blank` navigation with no Capybara action behind it (e.g. a WPT test) — open the aux window from the event-loop drain. Safe mid-call (builds a separate Browser). Same-window / frame navs are left untouched (handled by drain_after_user_action).
4121 4122 4123 4124 4125 4126 4127 4128 |
# File 'lib/capybara/simulated/browser.rb', line 4121 def consume_pending_aux_window pending = @runtime.call('__csimTakePendingAuxWindow') return unless pending.is_a?(Hash) && pending['url'] && @driver.respond_to?(:open_aux_window) @driver.open_aux_window(resolve_against_current(pending['url'].to_s, use_base: true), source: self, blob_snapshot: pending['blob']) rescue StandardError => e log_console('warn', "aux-window open failed: #{e.}") end |
#consume_pending_download ⇒ Object
‘<a download>` clicked synthetically (file-saver’s saveAs ships a freshly-created anchor through ‘dispatchEvent(MouseEvent ’click’)‘). The bridge queues `filename` on __csimPendingDownload during the click default-action; we drain here at every tick so the file lands in `downloads_directory` before Capybara’s ‘wait_for_download` polls.
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 |
# File 'lib/capybara/simulated/browser.rb', line 1493 def consume_pending_download pending = @runtime.call('__csimTakePendingDownload') return unless pending.is_a?(Hash) && pending['url'] url = pending['url'].to_s filename = pending['filename'].to_s if url.start_with?('blob:') b64 = @runtime.call('__csimReadBlobBase64', url) return if b64.nil? content = Base64.decode64(b64.to_s) name = filename.empty? ? 'download' : filename dir = downloads_directory FileUtils.mkdir_p(dir) File.binwrite(File.join(dir, name), content) else download_link(resolve_against_current(url, use_base: true), filename) end end |
#consume_pending_form_submit ⇒ Object
Read the form-submit pending intent set by JS-side ‘form.submit()` / `form.requestSubmit()`. Called by user-action entry points (click is the primary, but a `<select onchange=“$ (’#form’).submit()”>‘ pattern reaches here through select_option). Without this hop the intent sits on the slot forever and the form never actually navigates / POSTs.
1375 1376 1377 1378 1379 |
# File 'lib/capybara/simulated/browser.rb', line 1375 def consume_pending_form_submit pending = @runtime.call('__csimTakePendingFormSubmit') return unless pending.is_a?(Hash) && pending['formHandle'] submit_form_handle(pending['formHandle'].to_i, pending['submitterHandle']) end |
#consume_pending_frame_nav ⇒ Object
3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 |
# File 'lib/capybara/simulated/browser.rb', line 3942 def consume_pending_frame_nav return if @pending_frame_nav.nil? || @pending_frame_nav.empty? navs = @pending_frame_nav @pending_frame_nav = nil navs.each do |realm_id, url| invalidate_find_cache # If this frame is on the entered `within_frame` stack, navigate it # through `navigate_frame` — it does the full fetch (redirects / # downloads / cookies) AND updates `@frame_stack` / `@current_realm_id` # so the enclosing `within_frame` block sees the new document. Otherwise # (a parent's `iframe.contentWindow.location.href = …`) re-navigate the # owning iframe by realm id via the src-reassignment path. Top-level # frames live in the main document; a nested non-entered frame's element # is in its parent realm's DOM (not yet routed — documented gap). entry = @frame_stack.find {|e| e[:realm_id] == realm_id } if entry navigate_frame(url, entry: entry) else @runtime.call('__csimNavigateFrameByRealm', realm_id, url) end rescue StandardError => e log_console('warn', "frame self-navigation failed: #{e.}") end end |
#consume_pending_frame_reload ⇒ Object
3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 |
# File 'lib/capybara/simulated/browser.rb', line 3986 def consume_pending_frame_reload return if @pending_frame_reload.nil? || @pending_frame_reload.empty? realm_ids = @pending_frame_reload.uniq @pending_frame_reload = nil realm_ids.each do |realm_id| invalidate_find_cache # An entered `within_frame` frame reloads through `navigate_frame` (keeps # the frame stack in sync) — re-fetching its current document URL, which # we read from the still-alive realm. (A blob: URL entered this way is # re-fetched through Rack and so does NOT reuse retained bytes — reloading # an *entered* revoked-blob frame is an accepted gap; the common parent- # held path below reuses bytes via reloadFrame.) Otherwise (a parent's # `iframe.contentWindow.location.reload()`, empty href, or a realm torn # down between flag and drain) re-navigate the owning iframe by realm id # JS-side, reusing the retained content so blob bytes survive a revoke. entry = @frame_stack.find {|e| e[:realm_id] == realm_id } url = entry && @runtime.frame_realm_alive?(realm_id) ? @runtime.realm_call(realm_id, '__csimLocationHref').to_s : '' if entry && !url.empty? navigate_frame(url, entry: entry) else @runtime.call('__csimReloadFrameByRealm', realm_id) end rescue StandardError => e log_console('warn', "frame self-reload failed: #{e.}") end end |
#consume_pending_frame_submit ⇒ Object
4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 |
# File 'lib/capybara/simulated/browser.rb', line 4023 def consume_pending_frame_submit return if @pending_frame_submit.nil? || @pending_frame_submit.empty? realm_ids = @pending_frame_submit.uniq @pending_frame_submit = nil realm_ids.each do |realm_id| next unless @runtime.frame_realm_alive?(realm_id) sub = @runtime.realm_call(realm_id, '__csimTakePendingFormSubmit') next unless sub.is_a?(Hash) && sub['formHandle'] invalidate_find_cache submit_form_in_realm(realm_id, sub['formHandle'], sub['submitterHandle']) rescue StandardError => e log_console('warn', "nested-context form submission failed: #{e.}") end end |
#consume_pending_history_traverse ⇒ Object
1645 1646 1647 1648 1649 |
# File 'lib/capybara/simulated/browser.rb', line 1645 def consume_pending_history_traverse return unless (target = @pending_history_traverse) @pending_history_traverse = nil perform_history_traverse(target) end |
#consume_pending_location ⇒ Object
3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 |
# File 'lib/capybara/simulated/browser.rb', line 3910 def consume_pending_location return unless (url = @pending_location) @pending_location = nil # A `location.href`/`assign`/`hash` set to a same-document # fragment (e.g. `location.hash = ''`) is NOT a document fetch — # move the hash without rebuilding the VM, matching the anchor- # click navigate branch. Without this a hash assignment reloaded # the page, discarding all JS state. if (url) update_current_hash(url) elsif @current_realm_id # A JS-driven `location.*` from inside a `within_frame` block # navigates the FRAME, not the top page (same as a self-targeted # link/form there). Gated on the realm, so the main-page path is # untouched. navigate_frame(url) else navigate(url) end end |
#consume_pending_navigation ⇒ Object
Read the anchor-navigation pending intent set by JS-side ‘el.click()` (Element.prototype.click) on an `<a href>`. Avo’s boolean-filter / select-filter controllers respond to ‘input` events by building the filtered URL and calling `urlRedirectTarget.click()` on a hidden anchor; the click chain starts from Ruby’s ‘set_value_with_events` rather than `click`, so without a parallel drain here the navigation stays queued and the page never reloads.
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 |
# File 'lib/capybara/simulated/browser.rb', line 1472 def pending = @runtime.call('__csimTakePendingNavigation') return unless pending.is_a?(Hash) && pending['url'] url = pending['url'].to_s target = pending['target'].to_s if !target.empty? && !%w[_self _top _parent].include?(target.downcase) && @driver.respond_to?(:open_aux_window) @driver.open_aux_window(resolve_against_current(url, use_base: true), source: self, blob_snapshot: pending['blob']) elsif (url) update_current_hash(url) else tick_real_time navigate(resolve_against_current(url, use_base: true)) end end |
#consume_pending_reload ⇒ Object
3973 3974 3975 3976 3977 |
# File 'lib/capybara/simulated/browser.rb', line 3973 def consume_pending_reload return unless @pending_reload @pending_reload = false refresh end |
#current_browsing_context_url ⇒ Object
The active browsing context’s own URL: the frame document’s URL inside a ‘within_frame` block, else the main page URL. Used to resolve a frame-relative navigation and to set its request referrer, so `resolve_against_current` / `pure_fragment_navigation?` work the same whether the navigation originates in the main page or a frame.
607 608 609 610 611 |
# File 'lib/capybara/simulated/browser.rb', line 607 def current_browsing_context_url return @current_url unless @current_realm_id href = dom_call('__csimLocationHref').to_s href.empty? ? @current_url : href end |
#current_document_handle ⇒ Object
Root for a context-less find: the active frame’s document (handle 0 ⇒the realm’s own ‘globalThis.document`) when in a frame, else the main document handle.
539 540 541 |
# File 'lib/capybara/simulated/browser.rb', line 539 def current_document_handle @current_realm_id ? 0 : @document_handle end |
#current_path ⇒ Object
1920 1921 1922 1923 1924 1925 1926 |
# File 'lib/capybara/simulated/browser.rb', line 1920 def current_path tick_real_time return '' if @current_url.nil? || @current_url.empty? URI.parse(@current_url).path rescue URI::InvalidURIError '' end |
#current_referer ⇒ Object
4181 |
# File 'lib/capybara/simulated/browser.rb', line 4181 def current_referer ; @current_referer.to_s ; end |
#current_url ⇒ Object
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 |
# File 'lib/capybara/simulated/browser.rb', line 457 def current_url tick_real_time # `tick_real_time` may have queued URL transitions via # `record_url_transition`. A polling matcher # (`have_current_path`) calls here once per ~50 ms iteration # and shifts one entry per call so it walks the same # intermediate-URL chain a real browser would have observed # before microtasks all collapsed onto the final URL — the # finish_installation_spec wizard chain depends on this for # the `/wizard` step before the JS replaceWith to # `/wizard/steps/setup` lands. A non-polling read # (`topic_url = page.current_url` long after the prior # action's settle) just wants the current URL; drop entries # older than the polling-cadence window so they don't leak # into an unrelated call (tags_spec:221's composer-submit # leaves `/new-topic` queued, and the read happens minutes # of test wall-clock later). if @recent_urls_last_push_at && @recent_urls.any? age_ms = Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond) - @recent_urls_last_push_at @recent_urls.clear if age_ms > RECENT_URLS_STALE_AGE_MS end return @recent_urls.shift if @recent_urls.any? @current_url || '' end |
#decode_image(b64_bytes, max_w = nil, max_h = nil) ⇒ Object
── Image decode (libvips) ─────────────────────────────────────
Called by the JS bridge whenever a Canvas / OffscreenCanvas path needs raw RGBA pixels — ‘drawImage(image, …)` whose source is an HTMLImageElement / Blob / ImageBitmap with encoded bytes still on the wire. ruby-vips decodes any format libvips supports (PNG, JPEG, WebP, GIF, …) into a contiguous row-major RGBA buffer. Returns `height, refId` — the raw bytes land in the transfer-buffer registry so the JS side fetches them as a `Uint8Array` (tag-driven binary marshalling) rather than building a 423 MB latin-1 + base64 intermediate for the 8900×8900 frames Discourse uploads exercise. Optional `max_w`/`max_h` lets the caller pre-shrink for cheap OCR-style “downscale before pixel-touch” flows.
3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 |
# File 'lib/capybara/simulated/browser.rb', line 3220 def decode_image(b64_bytes, max_w = nil, max_h = nil) host_image_op('decode_image') { require 'vips' unless defined?(Vips) bytes = Base64.decode64(b64_bytes.to_s) # `access: :sequential` keeps libvips from applying the # source's ICC profile mid-stream (changes RGBA values by ±2 # vs raw decode). `colourspace('srgb')` is the same ICC # transform Chrome's createImageBitmap runs, but rounding # differs by a few ulp; only convert when libvips reports # a non-sRGB interpretation, otherwise trust the bytes. img = Vips::Image.new_from_buffer(bytes, '', access: :sequential) img = img.colourspace('srgb') unless img.interpretation == :srgb || img.interpretation == :rgb img = img.bandjoin(255) if img.bands < 4 if max_w && max_h && max_w.to_i > 0 && max_h.to_i > 0 && (img.width > max_w.to_i || img.height > max_h.to_i) shrink_x = img.width.to_f / max_w.to_i shrink_y = img.height.to_f / max_h.to_i shrink = [shrink_x, shrink_y].max img = img.resize(1.0 / shrink) if shrink > 1 end raw = img.write_to_memory {'width' => img.width, 'height' => img.height, 'refId' => transfer_buffer_stash(raw)} } end |
#decode_response_bom(s) ⇒ Object
3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 |
# File 'lib/capybara/simulated/browser.rb', line 3867 def decode_response_bom(s) b = s.b if b.start_with?("\xEF\xBB\xBF".b) [b.byteslice(3..).force_encoding(Encoding::UTF_8), 'UTF-8'] elsif b.start_with?("\xFF\xFE".b) || b.start_with?("\xFE\xFF".b) # Generic UTF-16: the BOM picks endianness and is dropped by the decoder. # Replace malformed units rather than raising (a truncated/odd-length # body still yields readable UTF-8 instead of falling back to raw bytes). # A UTF-32LE BOM (FF FE 00 00) is matched here as UTF-16LE too — which is # exactly what browsers do (UTF-32 unsupported; the leading FF FE is read # as the UTF-16LE BOM). charset = b.start_with?("\xFF\xFE".b) ? 'UTF-16LE' : 'UTF-16BE' [b.force_encoding(Encoding::UTF_16).encode(Encoding::UTF_8, invalid: :replace, undef: :replace), charset] else [s, nil] end rescue StandardError [s, nil] end |
#decode_video_frame(b64_bytes) ⇒ Object
── Video decode (ffprobe + ffmpeg) ────────────────────────────
Called from the JS bridge when a ‘<video>` element’s ‘src` is assigned a `blob:` URL. ffprobe extracts dimensions + duration, ffmpeg extracts the first frame as raw RGBA. JS caches both so `canvas.drawImage(video, …)` blits like any ImageBitmap.
3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 |
# File 'lib/capybara/simulated/browser.rb', line 3415 def decode_video_frame(b64_bytes) host_image_op('decode_video_frame') { bytes = Base64.decode64(b64_bytes.to_s) next nil if bytes.empty? require 'tempfile' require 'json' Tempfile.create(['csim-video', '.bin'], binmode: true) do |f| f.write(bytes) f.flush info = ffprobe_stream(f.path) or break nil width = info['width'].to_i height = info['height'].to_i break nil if width <= 0 || height <= 0 raw = ffmpeg_first_frame_rgba(f.path) duration = (info['duration'] || info.dig('format_duration')).to_f result = {'width' => width, 'height' => height, 'duration' => duration} result['refId'] = transfer_buffer_stash(raw) if raw && !raw.empty? result end } end |
#decode_windows1252(s) ⇒ Object
Decode bytes as windows-1252 (the HTML locale-default encoding) to a UTF-8 Ruby string. Replaces undefined slots rather than raising.
3860 3861 3862 3863 3864 3865 |
# File 'lib/capybara/simulated/browser.rb', line 3860 def decode_windows1252(s) s.to_s.b.dup.force_encoding(Encoding::WINDOWS_1252) .encode(Encoding::UTF_8, invalid: :replace, undef: :replace) rescue StandardError RuntimeShared.utf8_text(s) end |
#deliver_event_source_events ⇒ Object
Drain any queued events into the VM. Cheap when no SSE connection is active (no threads → no queue items → empty return). Returns the number of events delivered so settle can tell whether progress was made.
2469 2470 2471 2472 2473 2474 2475 |
# File 'lib/capybara/simulated/browser.rb', line 2469 def deliver_event_source_events return 0 if @event_source_threads.empty? && @event_source_queue.empty? events = event_source_poll return 0 if events.empty? @runtime.call('__csim_deliverEventSourceEvents', events) events.size end |
#deliver_hijacked_fetches ⇒ Object
2970 2971 2972 2973 2974 2975 2976 |
# File 'lib/capybara/simulated/browser.rb', line 2970 def deliver_hijacked_fetches return 0 if @hijack_fetch_threads.empty? && @hijack_fetch_queue.empty? responses = drain_queue(@hijack_fetch_queue) return 0 if responses.empty? @runtime.call('__csim_deliverHijackedFetches', responses) responses.size end |
#deliver_websocket_events ⇒ Object
2714 2715 2716 2717 2718 2719 2720 |
# File 'lib/capybara/simulated/browser.rb', line 2714 def deliver_websocket_events return 0 if @websocket_threads.empty? && @websocket_queue.empty? events = drain_queue(@websocket_queue) return 0 if events.empty? @runtime.call('__csim_deliverWebSocketEvents', events) events.size end |
#deliver_window_messages ⇒ Object
Fire queued cross-window messages (postMessage + BroadcastChannel).
3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 |
# File 'lib/capybara/simulated/browser.rb', line 3185 def n = 0 unless @window_inbox.empty? events = @window_inbox.slice!(0, @window_inbox.length) @runtime.call('__csim_deliverWindowMessages', events) n += events.size end unless @broadcast_inbox.empty? events = @broadcast_inbox.slice!(0, @broadcast_inbox.length) @runtime.call('__csim_deliverBroadcasts', events) n += events.size end n end |
#deliver_worker_messages ⇒ Object
3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 |
# File 'lib/capybara/simulated/browser.rb', line 3118 def return 0 if @workers.empty? && @worker_outbox.empty? events = drain_queue(@worker_outbox) return 0 if events.empty? # `__error` postbacks don't correspond to a prior post, so # bottom out at zero. @worker_in_flight = [0, @worker_in_flight - events.size].max @runtime.call('__csim_deliverWorkerMessages', events) events.size end |
#describe_node_handle(handle) ⇒ Object
‘tag#id.class` short description of the handle, for trace `description` fields. One V8 round-trip; only paid when a step is actively being recorded (`record_action` lazy-evaluates the description Proc).
1813 1814 1815 1816 1817 1818 1819 1820 1821 |
# File 'lib/capybara/simulated/browser.rb', line 1813 def describe_node_handle(handle) return "handle=#{handle}" if handle.nil? || handle.zero? info = dom_call('__csimDescribeNode', handle) return "handle=#{handle}" unless info.is_a?(Hash) s = info['tag'].to_s s += "##{info['id']}" unless info['id'].to_s.empty? s += ".#{info['cls']}" unless info['cls'].to_s.empty? s end |
#disabled?(handle) ⇒ Boolean
798 799 800 801 802 803 804 805 806 807 |
# File 'lib/capybara/simulated/browser.rb', line 798 def disabled?(handle) = dom_call('__csimDisabled', handle) # HTML spec: `<option>.selected` IDL is true when the `selected` # *attribute* is set OR when no sibling option has `selected` and # this is the first non-disabled option of a single-select # `<select>` (implicit default). Capybara's `have_select(selected: # "Choose an option")` filter calls `selected?` on each option; # without the implicit-default branch, a select with no explicit # `<option selected>` reports no selected options and the matcher # fails even though the first option *is* the currently chosen # one in real browsers. |
#dispatch_event(handle, type, init = {}) ⇒ Object
1268 1269 1270 1271 1272 1273 |
# File 'lib/capybara/simulated/browser.rb', line 1268 def dispatch_event(handle, type, init = {}) tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) dom_call('__csimDispatchEvent', handle, type.to_s, init) end |
#dispose ⇒ Object
Tear down an auxiliary window’s Browser when its window closes (the Driver calls this on close_window / reset!). Releases what a bare GC of the isolate would NOT: live background threads (worker / SSE / hijacked- fetch / WebSocket readers) and any parked zero-copy transfer backing stores this window issued (the transfer registry is process-wide). Runs while the runtime is still alive so the transferDrop call lands.
2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 |
# File 'lib/capybara/simulated/browser.rb', line 2324 def dispose drop_pending_transfers reset_workers reset_event_sources reset_hijacked_fetches reset_websockets @window_inbox.clear @broadcast_inbox.clear # Dispose the JS runtime/isolate itself — for an auxiliary window this # Browser is the isolate's last owner, but V8Runtime registers every # isolate in a process-wide `@@live` set (for at_exit cleanup), which # pins it past a bare GC. Without this, each closed window leaked a live # V8 isolate (RSS climbed across a long suite). Only reached on teardown, # never on the per-test `reset!` path (which keeps the runtime). @runtime.dispose if @runtime.respond_to?(:dispose) rescue StandardError nil end |
#document_cookie ⇒ Object
‘document.cookie` is TEXT; jar entries parsed out of Rack’s Set-Cookie headers can carry the BINARY tag, which would make the joined string cross into JS as a Uint8Array (‘document.cookie.match is not a function`). Cookies are ASCII per RFC 6265.
4178 4179 4180 |
# File 'lib/capybara/simulated/browser.rb', line 4178 def RuntimeShared.utf8_text(@cookies.map {|k, v| "#{k}=#{v}" }.join('; ')) end |
#dom_call(name, *args) ⇒ Object
DOM / node / query host-fn dispatch. Inside a ‘within_frame` block it routes to the active frame realm’s context; otherwise straight to the main context. Handle integers are per-realm (each realm is a full bridge with its own registry), so an op on a frame node must run in the realm the handle came from — which, per Capybara’s within_frame contract, is the current realm for the block’s duration. Hot path: ‘@current_realm_id` is nil outside frames, so this is one nil-check over a direct `@runtime.call`.
523 524 525 526 527 528 529 530 531 532 533 534 |
# File 'lib/capybara/simulated/browser.rb', line 523 def dom_call(name, *args) return @runtime.call(name, *args) if @current_realm_id.nil? # The active frame's realm was torn down mid-block (the iframe was # removed or re-navigated). Surface a stale element so Capybara # retries / reports, rather than letting realm_call fall back to the # main context where this frame handle would mis-resolve. unless @runtime.frame_realm_alive?(@current_realm_id) raise Capybara::Simulated::StaleElement, "frame browsing context #{@current_realm_id} was torn down (frame removed or re-navigated)" end @runtime.realm_call(@current_realm_id, name, *args) end |
#domain_to_ascii(domain) ⇒ Object
WHATWG URL “domain to ASCII” — the JS tr46 stub delegates non-ASCII / xn– hosts here (the ASCII fast path stays in-VM). Returns the punycode form, or nil on an IDNA failure (so whatwg-url reports “domain to ASCII failed”). ‘be_strict: false` is the URL parser’s mode (UseSTD3ASCIIRules and VerifyDnsLength off) — empty middle labels (‘x..y`) and `_`/etc. are allowed, matching whatwg-url’s ‘domainToASCII(domain, false)`.
3297 3298 3299 3300 3301 3302 |
# File 'lib/capybara/simulated/browser.rb', line 3297 def domain_to_ascii(domain) URI::IDNA.whatwg_to_ascii(domain.to_s, be_strict: false) rescue URI::IDNA::Error nil # a genuine IDNA failure (bad punycode / disallowed codepoint) — let # whatwg-url report "domain to ASCII failed". Non-IDNA errors propagate. end |
#domain_to_unicode(domain) ⇒ Object
WHATWG URL “domain to Unicode” — best-effort (never fails the parse per spec), so on an IDNA error fall back to the input domain (unlike to_ascii, which signals failure with nil — the asymmetry is intentional).
3307 3308 3309 3310 3311 |
# File 'lib/capybara/simulated/browser.rb', line 3307 def domain_to_unicode(domain) URI::IDNA.whatwg_to_unicode(domain.to_s, be_strict: false) rescue URI::IDNA::Error domain.to_s end |
#double_click(handle, keys = [], **opts) ⇒ Object
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 |
# File 'lib/capybara/simulated/browser.rb', line 1194 def double_click(handle, keys = [], **opts) mark_action_baseline tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) # UI Events spec: two full mousedown→mouseup→click chains # before the trailing `dblclick`. Jspreadsheet (table-builder's # `.jss_worksheet`) enters edit mode on the inner mousedown. 2.times { dom_call('__csimClickResolve', handle, opts) } init = {'bubbles' => true, 'cancelable' => true}.merge(click_event_init(handle, keys, opts)) dom_call('__csimDispatchEvent', handle, 'dblclick', init) # Real browsers' default-action on dblclick selects the word # under the cursor — ProseMirror / Tiptap "paste URL over # selection wraps with link" tests rely on the word being # selected before the paste. dom_call('__csimSelectWordAt', handle) settle end |
#download_link(url, filename_hint = '') ⇒ Object
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 |
# File 'lib/capybara/simulated/browser.rb', line 976 def download_link(url, filename_hint = '') env = Rack::MockRequest.env_for(url, method: 'GET') env['HTTP_USER_AGENT'] = @default_user_agent || USER_AGENT env['REMOTE_ADDR'] = self.class.remote_addr_for(env['HTTP_HOST'] || env['SERVER_NAME']) env['HTTP_COOKIE'] = unless @cookies.empty? env['HTTP_REFERER'] = @current_url unless @current_url.nil? || @current_url.empty? status, headers, body = @app.call(env) return unless status.to_i == 200 # Fall back to the link's `download="filename"` value or the # URL path tail when Content-Disposition is absent — `<a download>` # is the spec hook for naming a download independently of the # response headers. forced_headers = headers.dup if content_disposition_header(forced_headers).to_s.empty? name = filename_hint.empty? ? File.basename(URI.parse(url).path.to_s) : filename_hint forced_headers['Content-Disposition'] = %(attachment; filename="#{name}") unless name.empty? end save_downloaded_response(url, forced_headers, body) end |
#drag_to(source_handle, target_handle, **_opts) ⇒ Object
Element-to-element drag. Capybara’s ‘Element#drag_to(target, delay: …)` lands here. Fires the HTML5 drag event sequence on the source / target pair (mousedown → dragstart → dragenter →dragover → drop → dragend) with a shared DataTransfer. Discourse sidebar reorder + Avo Sortable-shaped widgets read the `event.offsetY` to decide “above vs below”; without a layout engine we report 0, which routes drops above the target.
1171 1172 1173 1174 1175 1176 1177 1178 1179 |
# File 'lib/capybara/simulated/browser.rb', line 1171 def drag_to(source_handle, target_handle, **_opts) mark_action_baseline tick_real_time invalidate_find_cache ensure_alive_after_tick(source_handle) ensure_alive_after_tick(target_handle) dom_call('__csimDragOnto', source_handle, target_handle) drain_after_user_action end |
#drain_after_user_action ⇒ Object
Every user-action entry point (set / send_keys / select / unselect) ends in this trio: drain any pending form submit, drain any pending Element.click anchor activation, then settle the page. Missing one site silently breaks the Stimulus filter pattern that wires ‘link.click()` into input/change/keypress listeners.
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 |
# File 'lib/capybara/simulated/browser.rb', line 1403 def drain_after_user_action consume_pending_form_submit settle # Settle bails on first observable change, but Backburner-style # 500 ms debounces park behind a setTimeout that hasn't fired # yet. Drain one 600 ms window so input → debounce → parent # state propagation completes before the next Capybara call. @runtime.drain_timers(USER_ACTION_DRAIN_MS) if @timers_active && @runtime.respond_to?(:drain_timers) end |
#drain_pending_navigation ⇒ Object
4107 4108 4109 4110 4111 4112 4113 4114 4115 |
# File 'lib/capybara/simulated/browser.rb', line 4107 def consume_pending_location consume_pending_frame_nav consume_pending_frame_submit consume_pending_frame_reload consume_pending_reload consume_pending_history_traverse consume_pending_aux_window end |
#drop(handle, args) ⇒ Object
HTML5 drag-and-drop simulation. Capybara routes ‘Element#drop` here with a flat list of paths / Pathnames / Hashes; build a DataTransfer-shaped object and dispatch dragenter / dragover / drop in sequence.
1156 1157 1158 1159 1160 1161 1162 |
# File 'lib/capybara/simulated/browser.rb', line 1156 def drop(handle, args) tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) items = args.flat_map {|arg| drop_items(arg) } dom_call('__csimDropOnto', handle, items) end |
#drop_items(arg) ⇒ Object
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 |
# File 'lib/capybara/simulated/browser.rb', line 1180 def drop_items(arg) case arg when Hash arg.map {|type, value| {'kind' => 'string', 'type' => type.to_s, 'value' => value.to_s} } when ->(x) { x.respond_to?(:to_path) } path = arg.to_path [{'kind' => 'file', 'name' => File.basename(path), 'path' => path}] when String [{'kind' => 'file', 'name' => File.basename(arg), 'path' => arg}] else [] end end |
#drop_pending_transfers ⇒ Object
Release every outstanding transfer token’s backing store. The transfer registry is process-wide (it bridges isolates) and survives isolate teardown, so an unimported token would leak across the whole run; drop them on ‘reset!` via the (still-live) main context — `transferDrop` is idempotent, so dropping already-imported tokens is a harmless no-op.
3392 3393 3394 3395 3396 |
# File 'lib/capybara/simulated/browser.rb', line 3392 def drop_pending_transfers toks = @transfer_tokens_lock.synchronize { ts = @transfer_tokens; @transfer_tokens = []; ts } return if toks.empty? @runtime.call('__csimTransferDropAll', toks) rescue nil end |
#durable_source(url) ⇒ Object
Fetch a source body and report how long it stays safely reusable per its OWN response headers — an absolute freshness deadline (Time), or nil when the response is not durably cacheable (no-store / no-cache / max-age=0 / dynamic with no freshness). This lets a loader persist the body across visits and skip the round-trip next time, driven by the server’s cache directives (RFC 9111 §5.2.2 / §4.2.2 heuristic) — NOT a URL-shape guess. ‘clear_volatile` drops the body from the volatile per-visit asset cache, but a content-hashed asset’s source is content-stable while fresh, so a loader’s own cross-visit cache can hold it for ‘fresh_until`. Used by the external-asset cache (`external_asset_source`, scripts + stylesheets); name is generic.
2362 2363 2364 2365 2366 2367 2368 |
# File 'lib/capybara/simulated/browser.rb', line 2362 def durable_source(url) body = rack_fetch_body(url) return [nil, nil] unless body entry = @@asset_cache.lookup(url) fresh_until = entry && entry.fresh? && entry.max_age ? entry.stored_at + entry.max_age : nil [body, fresh_until] end |
#empty_find_result?(result) ⇒ Boolean
721 722 723 |
# File 'lib/capybara/simulated/browser.rb', line 721 def empty_find_result?(result) result.nil? || (result.respond_to?(:empty?) && result.empty?) end |
#encode_image(pixels_ref, width, height, mime_type = 'image/png', quality = 90) ⇒ Object
3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 |
# File 'lib/capybara/simulated/browser.rb', line 3476 def encode_image(pixels_ref, width, height, mime_type = 'image/png', quality = 90) host_image_op('encode_image') { require 'vips' unless defined?(Vips) raw = transfer_buffer_fetch(pixels_ref).to_s w = width.to_i h = height.to_i next nil if w <= 0 || h <= 0 || raw.bytesize < w * h * 4 img = Vips::Image.new_from_memory_copy(raw, w, h, 4, :uchar) ext = MIME_TO_VIPS_EXT[mime_type.to_s.downcase] || '.png' opts = (ext == '.jpg' || ext == '.webp') ? {Q: quality.to_i} : {} {'refId' => transfer_buffer_stash(img.write_to_buffer(ext, **opts))} } end |
#enqueue_broadcast(name, data) ⇒ Object
A BroadcastChannel message from another window, queued for delivery to this window’s channels with the same name.
3182 |
# File 'lib/capybara/simulated/browser.rb', line 3182 def enqueue_broadcast(name, data) = (@broadcast_inbox << {'name' => name.to_s, 'data' => data}) |
#enqueue_window_message(data, origin, source_handle) ⇒ Object
Queue a cross-window message for delivery into THIS window’s VM (called by the Driver on the target Browser). Delivered as a ‘message` event the next time this window settles / ticks.
3172 3173 3174 |
# File 'lib/capybara/simulated/browser.rb', line 3172 def (data, origin, source_handle) @window_inbox << {'data' => data, 'origin' => origin.to_s, 'sourceHandle' => source_handle.to_s} end |
#ensure_alive_after_tick(handle) ⇒ Object
‘tick_real_time` may have rebuilt the DOM (Ember route hydration finishing on its first idle tick replaces server-rendered nodes with fresh ones). `Node` ran check_stale before calling here, but that was BEFORE the tick — re-verify after so Capybara catches the now-stale handle and retries the find. Otherwise `__csim*` lookups would return null and the operation would silently no-op (or, in the case of `__csimClickResolve`, dispatch on a detached node whose listeners no longer matter).
842 843 844 845 |
# File 'lib/capybara/simulated/browser.rb', line 842 def ensure_alive_after_tick(handle) return if dom_call('__csimAlive', handle) raise Capybara::Simulated::StaleElement, "Element with handle #{handle} is no longer attached to the document" end |
#eval_esm_module(url, src = nil) ⇒ Object
Native ESM entry point. QuickJS uses its ‘vm.module_loader`; V8 uses `Context#compile_module` + `Module#instantiate` / `#evaluate` + `Context#dynamic_import_resolver=`. Both runtimes expose `eval_esm_module`.
2418 2419 2420 |
# File 'lib/capybara/simulated/browser.rb', line 2418 def eval_esm_module(url, src = nil) @runtime.eval_esm_module(url, src) end |
#evaluate_async_script(code, args = []) ⇒ Object
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 |
# File 'lib/capybara/simulated/browser.rb', line 1898 def evaluate_async_script(code, args = []) tick_real_time invalidate_find_cache # Runs in the active frame realm inside `within_frame` (Selenium # parity), same as evaluate_script; the result slot is realm-local so # the poll below must read from the same realm. dom_call('__evalAsyncScript', code.to_s, marshal_args(args || [])) # Pump virtual time so any setTimeout-driven completion lands. # Capybara's polling can't help here — we're inside one session # call, not a retry loop. deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + Capybara.default_max_wait_time.to_f loop do result = dom_call('__pollAsyncResult') return result['value'] if result.is_a?(Hash) && result.key?('value') break if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline sleep 0.01 tick_real_time end nil end |
#evaluate_script(code, args = []) ⇒ Object
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 |
# File 'lib/capybara/simulated/browser.rb', line 1822 def evaluate_script(code, args = []) # Drain timers first so ready handlers (jQuery `$(handler)`, # framework `DOMContentLoaded` listeners) run before the # user's script. Without this, `execute_script` can fire # *before* the page's own setup code that the test expects # to be active. tick_real_time invalidate_find_cache # Routes to the active frame realm inside `within_frame` (Selenium # parity: `evaluate_script` runs in the current browsing context). result = dom_call('__csimEvalScript', code.to_s, marshal_args(args || [])) result end |
#event_source_close(id) ⇒ Object
2453 2454 2455 2456 2457 |
# File 'lib/capybara/simulated/browser.rb', line 2453 def event_source_close(id) thread = @event_source_threads.delete(id.to_i) thread&.kill nil end |
#event_source_open(url) ⇒ Object
── EventSource (SSE) ──────────────────────────────────────────
Mastodon (and any app using Server-Sent Events) opens an ‘EventSource` to a streaming endpoint and expects pushed events to fire `message`/typed listeners on the live instance. Our implementation:
1. JS-side `new EventSource(url)` calls `__csim_eventSourceOpen`
which returns an integer handle and spawns a Ruby thread.
2. The thread holds a chunked-read HTTP connection open and
parses the SSE event-stream wire format, pushing each
`{id:, type:, data:, lastEventId:}` (or `{type: '__open'}`
/ `{type: '__error', message:}` sentinel) onto a
thread-safe queue.
3. Settle's drain loop calls `deliver_event_source_events`
which polls the queue and hands the batch to
`__csim_deliverEventSourceEvents` for dispatch.
rusty_racer / quickjs.rb VMs are single-threaded; only the main thread ever enters the VM. Background threads only touch the Queue. ‘reset!` and per-visit context rebuilds kill all open threads — the new VM gets a fresh handle space.
2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 |
# File 'lib/capybara/simulated/browser.rb', line 2442 def event_source_open(url) id = (@event_source_seq += 1) queue = @event_source_queue thread = Thread.new do Thread.current.report_on_exception = false run_event_source_reader(id, url.to_s, queue) end @event_source_threads[id] = thread id end |
#event_source_pending? ⇒ Boolean
2463 |
# File 'lib/capybara/simulated/browser.rb', line 2463 def event_source_pending? = !@event_source_queue.empty? |
#event_source_poll ⇒ Object
2459 2460 2461 |
# File 'lib/capybara/simulated/browser.rb', line 2459 def event_source_poll drain_queue(@event_source_queue) end |
#execute_script(code, args = []) ⇒ Object
Fire-and-forget variant: runs the script but never returns its value to Ruby. Lets execute_script handle scripts whose return is a complex JS object (jQuery chainable, DOM tree, …) that the marshaller would recurse into.
1841 1842 1843 1844 1845 1846 1847 |
# File 'lib/capybara/simulated/browser.rb', line 1841 def execute_script(code, args = []) tick_real_time invalidate_find_cache dom_call('__csimExecScript', code.to_s, marshal_args(args || [])) nil end |
#external_asset_source(url) ⇒ Object
Body of an external durably-cacheable asset (classic script or stylesheet), served from the cross-visit cache when still fresh, else fetched (which read-throughs the per-visit asset cache) and cached iff durably cacheable. Returns nil on 4xx / fetch failure so the JS caller skips it exactly as the old ‘__rackFetch` branch did.
2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 |
# File 'lib/capybara/simulated/browser.rb', line 2388 def external_asset_source(url) key = resolve_against_current(url.to_s) return nil unless key.is_a?(String) @@asset_src_lock.synchronize do if (e = @@asset_src[key]) return e[0] if e[1].nil? || Time.now < e[1] @@asset_src.delete(key) end end # `durable_source` already does the spec-compliant fetch + header-driven # freshness (RFC 9111 max-age → absolute deadline); reuse it instead of # re-deriving `fresh_until` here. body, fresh_until = durable_source(key) return nil unless body # Script / stylesheet source is TEXT, but the raw Rack / binread body # arrives BINARY-tagged (see `RuntimeShared.utf8_text`). body = RuntimeShared.utf8_text(body) if fresh_until @@asset_src_lock.synchronize do @@asset_src.clear if @@asset_src.size >= ASSET_SRC_MAX @@asset_src[key] = [body, fresh_until] end end body end |
#file_input?(handle) ⇒ Boolean
787 788 789 |
# File 'lib/capybara/simulated/browser.rb', line 787 def file_input?(handle) tag(handle) == 'input' && attr(handle, 'type').to_s.downcase == 'file' end |
#file_pick_paths(fi) ⇒ Object
The on-disk paths backing a file input’s current selection. Each selected File reports its host-backed source (‘handle`/`index` → the `@file_picks` slot recorded at `attach_file` time); this resolves bytes even when JS moved a File onto a different input (`input.files = dataTransfer.files`), whose own handle was never attached to. Falls back to the input’s own handle for older serializer payloads.
Only host-backed Files (from ‘attach_file`) resolve here; a purely in-memory `new File(, …)` assigned via JS has no `@file_picks` slot, so a CLASSIC (non-Turbo) submit drops its bytes — the fetch/XHR path serializes those in JS (`serializeMultipart` → `blobBytes`) and is unaffected. This matches the pre-existing behaviour and covers every realistic upload (host-backed file submitted through Turbo or a plain form).
2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 |
# File 'lib/capybara/simulated/browser.rb', line 2189 def file_pick_paths(fi) refs = fi['files'] if refs.is_a?(Array) && !refs.empty? refs.filter_map {|ref| handle = ref['handle'] next if handle.nil? picks = @file_picks && @file_picks[handle.to_i] picks && picks[ref['index'].to_i] } else (@file_picks && @file_picks[fi['handle'].to_i]) || [] end end |
#file_picks_for(handle) ⇒ Object
1114 1115 1116 |
# File 'lib/capybara/simulated/browser.rb', line 1114 def file_picks_for(handle) (@file_picks && @file_picks[handle]) || [] end |
#find_css(css, context_handle = nil) ⇒ Object
642 643 644 645 646 647 648 649 650 651 652 653 |
# File 'lib/capybara/simulated/browser.rb', line 642 def find_css(css, context_handle = nil) s = css.to_s return find_xpath(s, context_handle) if xpath_shaped?(s) find_with_timer_fallback(:css, s, context_handle) do dom_call('__csimQuery', context_handle || current_document_handle, s).to_a rescue StandardError => e # Invalid selector → empty result. Callers that genuinely # need the throw go through `evaluate_script`. raise unless syntax_or_invalid_selector_error?(e) [] end end |
#find_first_css(css, context_handle = nil) ⇒ Object
655 656 657 658 659 660 661 662 663 664 |
# File 'lib/capybara/simulated/browser.rb', line 655 def find_first_css(css, context_handle = nil) s = css.to_s find_with_timer_fallback(:css_first, s, context_handle) do h = dom_call('__csimQueryOne', context_handle || current_document_handle, s).to_i h.zero? ? nil : h rescue StandardError => e raise unless syntax_or_invalid_selector_error?(e) nil end end |
#find_with_timer_fallback(kind, arg, ctx) ⇒ Object
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 |
# File 'lib/capybara/simulated/browser.rb', line 698 def find_with_timer_fallback(kind, arg, ctx) tick_real_time if timer_wait_elapsed? result = cached_find(kind, arg, ctx) { yield } # An empty result is the wait-for-it case: Capybara is retrying for # an element that hasn't appeared yet. Re-tick so the next poll # observes anything an active timer OR a background-IO channel # (Worker / EventSource / a held long-poll publish) is about to # deliver. Gating on `@timers_active` alone misses the held-poll # case — a MessageBus subscription waiting on a cross-session # publish has NO pending JS timer (the re-poll only schedules after # the current poll returns), so `@timers_active` is false while # `hijack_fetch_pending?` is true. Without `async_io_pending?` here # the delivered message never reaches the DOM during find-polling # (only `evaluate_script`, which ticks unconditionally, would see # it). Non-empty results keep the fast path — no extra tick. return result unless empty_find_result?(result) && (@timers_active || async_io_pending?) tick_real_time return result unless @find_cache_dirty cached_find(kind, arg, ctx) { yield } end |
#find_xpath(xpath, context_handle = nil) ⇒ Object
XPath is evaluated inside V8 against the live JS DOM via the xpathway engine (bundled, installed at snapshot build). One IPC per ‘find_xpath` — no serialise + reparse round-trip.
691 692 693 694 695 696 |
# File 'lib/capybara/simulated/browser.rb', line 691 def find_xpath(xpath, context_handle = nil) xpath_str = xpath.to_s find_with_timer_fallback(:xpath, xpath_str, context_handle) do dom_call('__csimEvaluateXPath', xpath_str, context_handle || 0).to_a end end |
#finish_trace_to(path, trace = (@trace || @pending_trace)) ⇒ Object
Persist ‘trace` (defaults to live or pending) to `path` and return the path. Doesn’t clear — ‘clear_trace!` is the explicit follow-up so a caller can inspect after writing if it wants.
1731 1732 1733 1734 |
# File 'lib/capybara/simulated/browser.rb', line 1731 def finish_trace_to(path, trace = (@trace || @pending_trace)) return nil unless trace trace.write_json(path) end |
#form_get_url(action, body) ⇒ Object
HTML form-submission “mutate action URL” for GET: REPLACE the action URL’s query with the serialized entry list (dropping any pre-existing query), preserving a trailing #fragment. String-based so it works on the raw (possibly relative) action attribute without URI.parse fragility; the absolute equivalent of submit_form_handle’s ‘uri.query = body`.
4082 4083 4084 4085 4086 4087 4088 |
# File 'lib/capybara/simulated/browser.rb', line 4082 def form_get_url(action, body) return action if body.empty? base, _hash, frag = action.partition('#') path = base.split('?', 2).first url = "#{path}?#{body}" frag.empty? ? url : "#{url}##{frag}" end |
#format_temporal_value(v, handle) ⇒ Object
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 |
# File 'lib/capybara/simulated/browser.rb', line 1101 def format_temporal_value(v, handle) type = attr(handle, 'type').to_s.downcase case type when 'date' then v.respond_to?(:strftime) ? v.strftime('%Y-%m-%d') : v.to_s when 'time' then v.respond_to?(:strftime) ? v.strftime('%H:%M') : v.to_s when 'datetime-local' then v.respond_to?(:strftime) ? v.strftime('%Y-%m-%dT%H:%M') : v.to_s when 'month' then v.respond_to?(:strftime) ? v.strftime('%Y-%m') : v.to_s when 'week' then v.respond_to?(:strftime) ? v.strftime('%Y-W%V') : v.to_s else v.is_a?(Date) ? v.strftime('%Y-%m-%d') : v.to_s end end |
#frame_nav_target_entry(target) ⇒ Object
Resolve a link/form ‘target` to the frame stack entry its navigation should rebuild, or nil when it targets the top page / a new context (the caller then falls through to a full-page `navigate` or aux window). Only meaningful inside a frame (`@current_realm_id` set):
- `''` / `_self` → the current frame.
- `_parent` → the intermediate parent frame, but only when nested ≥2
levels deep; at one level the parent IS the top browsing context, so
it returns nil and the full-page path handles it (same as `_top`).
635 636 637 638 639 640 |
# File 'lib/capybara/simulated/browser.rb', line 635 def frame_nav_target_entry(target) return nil unless @current_realm_id return @frame_stack.last if frame_self_target?(target) return @frame_stack[-2] if target.to_s.downcase == '_parent' && @frame_stack.size >= 2 nil end |
#frame_navigate_self(url, realm_id) ⇒ Object
A nested browsing context navigating its OWN ‘location` (the frame’s ‘location.href`/assign/replace/`location=`, incl. cross-frame `iframe.contentWindow.location.href = …`). `realm_id` is the frame’s realm. Deferred like location_assign: applying it re-navigates the owning iframe, which disposes that realm — illegal while the frame’s location setter is still on the V8 stack — so we stash and drain from ‘tick_real_time`.
3936 3937 3938 3939 3940 3941 |
# File 'lib/capybara/simulated/browser.rb', line 3936 def frame_navigate_self(url, realm_id) return if realm_id.nil? || realm_id.zero? # Keyed by realm id (last URL wins per frame) so two different frames each # navigating in one turn both apply — a single slot would drop one. (@pending_frame_nav ||= {})[realm_id] = url.to_s end |
#frame_reload_self(realm_id) ⇒ Object
‘frame.contentWindow.location.reload()` from a nested browsing context. Like `frame_navigate_self`, the JS side flags the initiating realm here and we defer (so the child realm isn’t disposed mid-reload()). Keyed by realm id so two frames reloading in one turn both apply.
3982 3983 3984 3985 |
# File 'lib/capybara/simulated/browser.rb', line 3982 def frame_reload_self(realm_id) return if realm_id.nil? || realm_id.zero? (@pending_frame_reload ||= []) << realm_id end |
#frame_self_target?(target) ⇒ Boolean
Does a link/form ‘target` load into the CURRENT frame? Empty or `_self` do; `_top` / `_blank` / `_parent` / a named context do not.
622 623 624 625 |
# File 'lib/capybara/simulated/browser.rb', line 622 def frame_self_target?(target) t = target.to_s.downcase t.empty? || t == '_self' end |
#frame_submit_self(realm_id) ⇒ Object
A <form> submitted from INSIDE a nested browsing context (a frame realm reached via ‘contentWindow`, not an entered `within_frame` block). The pending-submit slot lives on the initiating realm’s globalThis, which no top-page drain reads, so the JS side flags the realm here (mirrors ‘frame_navigate_self`). Keyed by realm id; deferred + drained from `drain_pending_navigation` so we never serialize/navigate while the form’s ‘submit()` is still on the V8 stack.
4019 4020 4021 4022 |
# File 'lib/capybara/simulated/browser.rb', line 4019 def frame_submit_self(realm_id) return if realm_id.nil? || realm_id.zero? (@pending_frame_submit ||= []) << realm_id end |
#geolocation_state_json ⇒ Object
Backs the ‘__csimGeolocationState` host fn. Returns the configured geolocation override as a JSON string (or ’null’ when none is set), which the JS geolocation object reads on every getCurrentPosition / watchPosition call.
1880 1881 1882 |
# File 'lib/capybara/simulated/browser.rb', line 1880 def geolocation_state_json JSON.generate(@geolocation) end |
#go_back ⇒ Object
Capybara-initiated ‘page.go_back` runs from Ruby, not inside a JS call, so it’s safe to rebuild the Context synchronously. The ‘force:` flag bypasses the deferral that `history_go` uses to avoid terminating the running JS context.
1607 |
# File 'lib/capybara/simulated/browser.rb', line 1607 def go_back ; history_go(-1, force: true) ; end |
#go_forward ⇒ Object
1608 |
# File 'lib/capybara/simulated/browser.rb', line 1608 def go_forward ; history_go(+1, force: true) ; end |
#handle_modal(type, message, default_value) ⇒ Object
JS-side ‘alert(…)` / `confirm(…)` / `prompt(…)` route here. If no handler is pushed (typical of apps under test), accept the dialog (Rails system-test default) so `data-turbo-confirm` / similar progress without an explicit `accept_confirm` in the test.
4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 |
# File 'lib/capybara/simulated/browser.rb', line 4242 def handle_modal(type, , default_value) handler = @modal_handlers.pop if handler handler.call(type, , default_value) else case type.to_s when 'alert' then nil when 'confirm' then true when 'prompt' then default_value.to_s end end end |
#hijack_fetch_pending? ⇒ Boolean
2968 |
# File 'lib/capybara/simulated/browser.rb', line 2968 def hijack_fetch_pending? = !@hijack_fetch_threads.empty? || !@hijack_fetch_queue.empty? |
#history_go(delta, force: false) ⇒ Object
Move through the history stack by ‘delta`. Per HTML spec, a same-document traversal (within a chain of pushState entries rooted at a single navigation) updates `location` and fires `popstate` with the entry’s state — no full reload. A cross- document traversal replays the entry (full navigate / re-POST).
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 |
# File 'lib/capybara/simulated/browser.rb', line 1615 def history_go(delta, force: false) delta = delta.to_i return if delta == 0 target = @history_idx + delta return if target < 0 || target >= @history.size if same_document_traversal?(@history_idx, target) # Pure pushState traversal — no VM rebuild, safe to run # inline; the popstate dispatch happens within the current # call's JS context. @history_idx = target entry = @history[target] @current_url = entry[:url] @runtime.call('__csimUpdateLocation', @current_url) @runtime.call('__csimDispatchPopState', entry[:state]) elsif force # Ruby-driven (`page.go_back`) — no live JS call to interrupt, # safe to rebuild the Context synchronously. perform_history_traverse(target) else # JS-driven (`history.back()` from a page handler): replaying # the history entry synchronously would call `rebuild_ctx` # on the still-executing Context and terminate the current # call with `ScriptTerminatedError` (terminating the # in-flight call on the isolate). Stash the intent # and drain after the call returns — mirrors # `location_assign` / `location_reload`. @pending_history_traverse = target end end |
#history_length ⇒ Object
Total history entries (after forward-tail truncation), surfaced to JS ‘history.length` via the `__historyLength` host fn.
4171 4172 4173 |
# File 'lib/capybara/simulated/browser.rb', line 4171 def history_length [@history.size, 1].max end |
#history_push(url, state = nil) ⇒ Object
‘history.pushState(state, _, url)` from SPA navigation (Turbo Visit, InstantClick, …) appends a new browser-history entry. Mirror that on the Ruby side so `Capybara#go_back` traverses within the pushState chain (fires `popstate`) and only crosses to a real reload when the back hits a `:visit` boundary.
4162 4163 4164 4165 4166 4167 |
# File 'lib/capybara/simulated/browser.rb', line 4162 def history_push(url, state = nil) resolved = resolve_against_current(url.to_s) record_url_transition(resolved) @current_url = resolved record_history({method: :get, url: resolved, state: state, kind: :push_state}) end |
#history_state(url, state = nil) ⇒ Object
‘history.pushState(state, ”, ’/path’)‘ ships the URL through `__setCurrentUrl` and lands here. Tab controllers / SPA frameworks pass a relative path; resolve it against the existing absolute `@current_url` so subsequent `resolve_against_current(href)` calls (e.g. click_link to a relative href) don’t hit ‘URI::BadURIError: both URI are relative`. `history.replaceState(state, _, url)` updates the current entry in place rather than appending. Both the state and (when given) the URL are mirrored on Ruby’s slot so a subsequent back to this entry restores the same state.
4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 |
# File 'lib/capybara/simulated/browser.rb', line 4144 def history_state(url, state = nil) if url resolved = resolve_against_current(url.to_s) record_url_transition(resolved) @current_url = resolved end return if @history_idx < 0 @history[@history_idx] = (@history[@history_idx] || {}).merge( url: @current_url, state: state, kind: @history[@history_idx] ? @history[@history_idx][:kind] : :push_state ) end |
#horizon_fast_forward_step ⇒ Object
This tick’s deterministic virtual-clock advance (ms). Default is the fixed ‘POLL_TICK_STEP_MS` — never wall-derived, so per-poll JS/Ruby/GC cost cannot shift WHEN a timer fires (the wall-sync↔perf coupling this replaces). When the page is observably idle (nothing runnable now, no background IO) but a near-future timer is parked within `FF_HORIZON_MS`, fast-forward straight to it — but only after the transient-guard window so pre-debounce states are still observed across several polls. `FF_HORIZON_MS=0` ⇒ pure fixed-step.
2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 |
# File 'lib/capybara/simulated/browser.rb', line 2042 def horizon_fast_forward_step # Escape hatch to the legacy wall-sync clock (virtual advance = real # wall-elapsed per poll). The deterministic model decouples perf from # timing but can't match a real browser's wall-proportional cadence for # timing-fragile heavy-JS flows; `CSIM_CLOCK_WALL=1` restores wall-sync. if @clock_wall now = Process.clock_gettime(Process::CLOCK_MONOTONIC) step = ((now - (@wall_clock_last || now)) * 1000).to_i.clamp(0, 1000) @wall_clock_last = now return step end # (1) Background async (cheap Ruby-side checks, no V8 crossing) we must let # land before jumping the clock: advance one fixed step, reset the guard. if worker_pending? || event_source_pending? || hijack_fetch_pending? || websocket_pending? @ff_transient_polls = 0 return POLL_TICK_STEP_MS end # No fast-forward support on this runtime (e.g. a worker realm) → fixed step. return POLL_TICK_STEP_MS unless @runtime_supports_ff # ONE V8 crossing: `delay` = ms until the nearest timer; 0 = runnable now # (a rAF or a due-now timer — equivalent to `has_ready_timer?`), -1 = none. delay = @runtime.next_timer_delay_ms # (2) Runnable now → fixed step, reset guard (not a quiet pre-debounce window). if delay.zero? @ff_transient_polls = 0 return POLL_TICK_STEP_MS end # (3) Nothing parked → nothing to fast-forward to. return POLL_TICK_STEP_MS if delay.negative? # (4) Beyond the horizon (ahoy 1000 / session-timeout / analytics): leave # parked, advance only at the fixed rate. Not a transient window. if delay > FF_HORIZON_MS @ff_transient_polls = 0 return POLL_TICK_STEP_MS end # (5) Near-future timer, page idle: hold the pre-debounce window for the # guard so transient-catch tests observe the intermediate state. @ff_transient_polls = (@ff_transient_polls || 0) + 1 return POLL_TICK_STEP_MS if @ff_transient_polls < FF_TRANSIENT_GUARD_POLLS # (6) Fast-forward: jump exactly to the next timer's due. `runLoopStepLocal` # breaks on strict `nextDue > limit`, so `limit = virtualNow + delay` # (== that timer's due) fires it — and ONLY it, not a timer 1 ms later. delay end |
#hover(handle) ⇒ Object
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 |
# File 'lib/capybara/simulated/browser.rb', line 1251 def hover(handle) mark_action_baseline tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) # Set `document._hoverElement` so `:hover` pseudo-class matches # resolve against this element (Redmine's gantt tooltips + # context-menu submenus rely on CSS `:hover`). The host fn # call into `__csimSetHover` does the slot update on the JS # side AND fires `mouseover` / `mouseenter` — keeping the # state-set and dispatch on the same path avoids the # double-eval recursion the inlined `globalThis.document. # _hoverElement = ...` triggered (the eval string ran inside # a fresh microtask that re-entered the hover listeners). dom_call('__csimSetHover', handle) end |
#html ⇒ Object
‘page.html` inside a `within_frame` block returns the frame document’s source (Selenium parity), so route through the active realm.
1528 1529 1530 1531 |
# File 'lib/capybara/simulated/browser.rb', line 1528 def html tick_real_time dom_call('__csimDocumentHtml').to_s end |
#html_charset_signal?(content_type, raw) ⇒ Boolean
Does the response carry an explicit encoding signal (so the default windows-1252 decode must NOT apply)? A ‘charset=` in the Content-Type, or a `<meta charset>` / `<meta http-equiv=content-type … charset=…>` in the HTML prescan window (the first 1024 bytes, per the HTML sniffing algorithm). The `charset` must start a real attribute / content-charset (preceded by whitespace, a quote, or `;`), so hyphenated look-alikes — `data-charset=`, `accept-charset=` — don’t false-trigger the signal.
3852 3853 3854 3855 3856 |
# File 'lib/capybara/simulated/browser.rb', line 3852 def html_charset_signal?(content_type, raw) return true if /;\s*charset\s*=/i.match?(content_type.to_s) head = raw.to_s.b[0, 1024].to_s /<meta\b[^>]*[\s"';]charset\s*=/i.match?(head) end |
#inner_html(handle) ⇒ Object
785 |
# File 'lib/capybara/simulated/browser.rb', line 785 def inner_html(handle) = dom_call('__csimInnerHTML', handle).to_s |
#invalidate_find_cache ⇒ Object
Any operation that may have mutated the DOM (click, set, send_keys, navigate, hover, …) must call this so the next find falls through to a fresh V8 query. Timer drains that fire any callbacks also dirty (see ‘tick_real_time`).
778 779 780 |
# File 'lib/capybara/simulated/browser.rb', line 778 def invalidate_find_cache @find_cache_dirty = true end |
#location_assign(url) ⇒ Object
Defer the navigation: doing it from inside the running V8 call would dispose the Context mid-call. tick_real_time drains after the call returns. Same pattern as ‘__csimPendingFormSubmit`.
3907 3908 3909 |
# File 'lib/capybara/simulated/browser.rb', line 3907 def location_assign(url) @pending_location = resolve_against_current(url.to_s) end |
#location_reload ⇒ Object
Mirror of ‘location_assign`’s deferral for ‘location.reload()`: the JS call lands here from `__locationReload`; running `browser.refresh` directly would `navigate` (rebuilding the Context) while we’re still inside the V8 call, which V8 terminates with a ‘ScriptTerminatedError`. Stash the intent and drain it from `tick_real_time` after the call returns.
3972 |
# File 'lib/capybara/simulated/browser.rb', line 3972 def location_reload ; @pending_reload = true ; end |
#log_console(severity, message) ⇒ Object
1786 1787 1788 1789 1790 1791 1792 |
# File 'lib/capybara/simulated/browser.rb', line 1786 def log_console(severity, ) # Diagnostic mirror: surface page console output on stderr regardless # of trace state (engine bring-up / CI triage). warn "[console:#{severity}] #{.to_s[0, 300]}" if CONSOLE_STDERR return unless @trace @trace.log_console(severity, (severity, )) end |
#log_network(method, url, status, **extra) ⇒ Object
1807 |
# File 'lib/capybara/simulated/browser.rb', line 1807 def log_network(method, url, status, **extra) = @trace&.log_network(method, url, status, **extra) |
#lookup_node(handle) ⇒ Object
821 822 823 |
# File 'lib/capybara/simulated/browser.rb', line 821 def lookup_node(handle) handle if dom_call('__csimAlive', handle) end |
#mark_action_baseline ⇒ Object
Pin the URL the page is at as a user action BEGINS — the FIRST line of every action entry (click / double_click / right_click / hover / set / send_keys / select / unselect). A Turbo Drive Visit the action triggers is async — its pushState may fire synchronously mid-action or in a LATER find-poll tick (the test’s ‘wait_for_loaded`) — so `record_url_transition` uses this baseline to recognise the pre-action URL as the action’s starting point, not a walkable intermediate, and skip queuing it. Set at action entry (NOT the tail drain, which runs after the pushState); must precede the action’s first ‘tick_real_time` so a deferred prior-page timer firing in that tick is still measured against the pre-action URL. Persists until the next action (so the async case is covered) and is reset by `navigate` so a stale baseline can’t leak across a document boundary.
1394 1395 1396 |
# File 'lib/capybara/simulated/browser.rb', line 1394 def mark_action_baseline @action_url_baseline = @current_url end |
#marshal_args(args) ⇒ Object
Capybara passes Node instances directly as script args (‘session.evaluate_script(’arguments.click()‘, some_node)`). the marshaller can’t pass a Ruby Node, so wrap as a sentinel the JS side recognises and rehydrates via the handle registry.
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 |
# File 'lib/capybara/simulated/browser.rb', line 1888 def marshal_args(args) args.map {|a| case a when Capybara::Simulated::Node then {'__elementHandle' => a.handle_id} when Array then marshal_args(a) when Hash then a.transform_values {|v| marshal_args([v]).first } else a end } end |
#mime_type_for_path(path) ⇒ Object
166 167 168 |
# File 'lib/capybara/simulated/browser.rb', line 166 def mime_type_for_path(path) Rack::Mime.mime_type(File.extname(path.to_s), '') end |
#modifier_flags(keys) ⇒ Object
1223 1224 1225 1226 1227 1228 |
# File 'lib/capybara/simulated/browser.rb', line 1223 def modifier_flags(keys) Array(keys).each_with_object({}) {|k, h| field = MODIFIER_KEYS[k.is_a?(Symbol) ? k : k.to_sym] h[field] = true if field } end |
#navigate_post(url, body, content_type, depth: 0, from_history: false) ⇒ Object
2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 |
# File 'lib/capybara/simulated/browser.rb', line 2214 def navigate_post(url, body, content_type, depth: 0, from_history: false) raise 'too many redirects' if depth > 10 invalidate_find_cache record_history({method: :post, url: url, body: body, content_type: content_type}) unless from_history || depth > 0 env = Rack::MockRequest.env_for(url, method: 'POST', input: body) env['CONTENT_TYPE'] = content_type.empty? ? 'application/x-www-form-urlencoded' : content_type env['CONTENT_LENGTH'] = body.bytesize.to_s apply_default_request_env(env, referer: @current_url) status, headers, resp_body = dispatch_rack_or_http(url, env, method: 'POST', body: body) (headers) if (loc = redirect_location(status, headers)) next_url = resolve_against_current(loc) resp_body.close if resp_body.respond_to?(:close) # HTTP semantics: 301/302/303 → method becomes GET; 307/308 # require the method (and body) to be preserved. if [307, 308].include?(status) return navigate_post(next_url, body, content_type, depth: depth + 1) else return navigate(next_url, depth: depth + 1) end end if download_response?(headers) save_downloaded_response(url, headers, resp_body) return end @current_url = url record_response(status, headers) html = read_rack_body(resp_body) # Same rebuild-on-full-load contract as `navigate`. POST # responses (form submissions that don't redirect, AJAX-less # data-remote replies) replace the page; we follow real-browser # semantics and bring up a fresh VM rather than papering over # the previous one's state. boot_response_into_ctx(html) end |
#navigate_realm_self(realm_id, get_url, action, method, body, enctype) ⇒ Object
Navigate the initiating frame realm itself (a self-targeted form submit).
4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 |
# File 'lib/capybara/simulated/browser.rb', line 4090 def navigate_realm_self(realm_id, get_url, action, method, body, enctype) entry = @frame_stack.find {|e| e[:realm_id] == realm_id } if method == 'GET' if entry navigate_frame(resolve_against_current(get_url), entry: entry) else # A frame reached via contentWindow (not on the entered stack): its # owning iframe lives in the parent document — re-navigate by realm id # (relative get_url resolves against the frame's base on rebuild). @runtime.call('__csimNavigateFrameByRealm', realm_id, get_url) end elsif entry navigate_frame_post(resolve_against_current(action), body, enctype, entry: entry) else log_console('warn', "nested-context self-form POST (realm #{realm_id}) is not modeled") end end |
#node_path(handle) ⇒ Object
819 |
# File 'lib/capybara/simulated/browser.rb', line 819 def node_path(handle) = dom_call('__csimNodePath', handle).to_s |
#normalize_trace_headers(headers) ⇒ Object
3768 3769 3770 3771 |
# File 'lib/capybara/simulated/browser.rb', line 3768 def normalize_trace_headers(headers) return nil unless headers headers.each_with_object({}) {|(k, v), out| out[k.to_s] = v.is_a?(Array) ? v.join(', ') : v.to_s } end |
#open_child_window(url, name) ⇒ Object
‘window.open(url, name)` from JS — returns the new (or reused, by name) window’s handle, or nil. The URL is resolved against THIS document so a relative ‘window.open(’/x’)‘ targets the right origin/path.
3140 3141 3142 3143 |
# File 'lib/capybara/simulated/browser.rb', line 3140 def open_child_window(url, name) return nil unless @driver.respond_to?(:open_window_from_js) @driver.open_window_from_js(self, url.to_s, name.to_s) end |
#opener_handle ⇒ Object
3167 |
# File 'lib/capybara/simulated/browser.rb', line 3167 def opener_handle = @driver.respond_to?(:opener_handle_of) ? @driver.opener_handle_of(self) : nil |
#option_selected?(h) ⇒ Boolean
HTML spec: ‘<option>.selected` IDL is true when the `selected` attribute is set OR when no sibling option has `selected` and this is the first non-disabled option of a single-select `<select>` (implicit default). Capybara’s ‘have_select(selected: “Choose an option”)` filter calls `selected?` on each option; without the implicit-default branch, a select with no explicit `<option selected>` reports no selected options and the matcher fails even though the first option is the currently chosen one in real browsers.
808 |
# File 'lib/capybara/simulated/browser.rb', line 808 def option_selected?(h) = !!dom_call('__csimOptionSelected', h) |
#outer_html(handle) ⇒ Object
786 |
# File 'lib/capybara/simulated/browser.rb', line 786 def outer_html(handle) = dom_call('__csimOuterHTML', handle).to_s |
#parse_trace_mode(raw) ⇒ Object
1718 1719 1720 1721 |
# File 'lib/capybara/simulated/browser.rb', line 1718 def parse_trace_mode(raw) return :on_failure if raw.nil? || raw.empty? TRACE_MODES[raw] || raise(ArgumentError, "CSIM_TRACE must be one of #{TRACE_MODES.keys.join(', ')}; got #{raw.inspect}") end |
#polling? ⇒ Boolean
Capybara polls find / has_? via ‘synchronize` while `Driver#wait?` is true. We stay true while there’s any scheduled timer (‘@timers_active` is flipped by the JS bridge’s ‘__setTimersActive` callback), plus a sticky grace window after the last timer fires so a `setTimeout` firing mid-loop doesn’t drop us off polling before Capybara’s own retry deadline.
Settle-gen idle gate: a recurring ‘setInterval` from a framework runloop (Ember / Glimmer) keeps `@timers_active` true forever even when nothing observable is changing. Without a second signal, Capybara waits the full `default_max_wait_time` on every `has_css?` / `has_no_css?` that’s destined to fail — which Discourse’s ‘CapybaraTimeoutExtension` reports as a “slow spec” failure. Track `@runtime.settle_gen` across polls: when it hasn’t bumped for ‘IDLE_SETTLE_POLLS` calls, drop polling even though timers are scheduled. `settle_gen` already bumps on every DOM mutation / URL change (see __settleGen wiring), so this only short-circuits genuinely idle loops.
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 |
# File 'lib/capybara/simulated/browser.rb', line 1946 def polling? # Background-thread work (workers, EventSource, MessageBus # long-poll) keeps the settle loop alive even when settle_gen # is otherwise idle. return true if worker_pending? || event_source_pending? || hijack_fetch_pending? || || websocket_pending? if @timers_active gen = @runtime.settle_gen if @last_polled_gen.nil? || gen != @last_polled_gen @last_polled_gen = gen @idle_settle_polls = 0 @polling_grace = POLLING_GRACE_POLLS return true end @idle_settle_polls += 1 return true if @idle_settle_polls < IDLE_SETTLE_POLLS # Treat as idle for this poll; if a fresh timer fires later # the next poll's settle_gen check will resume polling. false elsif @polling_grace && @polling_grace > 0 @polling_grace -= 1 true else false end end |
#post_message_to_window(target_handle, data, origin) ⇒ Object
‘targetWindow.postMessage(data, origin)` — route to the target window’s inbox, tagged with this window as the source.
3147 3148 3149 3150 |
# File 'lib/capybara/simulated/browser.rb', line 3147 def (target_handle, data, origin) return unless @driver.respond_to?(:window_post_message) @driver.(self, target_handle.to_s, data, origin.to_s) end |
#pure_fragment_navigation?(url) ⇒ Boolean
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 |
# File 'lib/capybara/simulated/browser.rb', line 996 def (url) return true if url.start_with?('#') doc_url = current_browsing_context_url return false if doc_url.nil? target = resolve_against_current(url) a = URI.parse(target) b = URI.parse(doc_url) # Same-document iff everything but the fragment matches AND the # fragment actually changes — `a.fragment != b.fragment` covers # both adding/changing a fragment and *clearing* one (target has # no fragment while the current URL does, e.g. `location.hash = # ''`). The old `!a.fragment.nil?` missed the clearing case, so a # hash-reset turned into a full document reload. a.scheme == b.scheme && a.host == b.host && a.port == b.port && a.path == b.path && a.query == b.query && a.fragment != b.fragment rescue URI::InvalidURIError false end |
#push_user_agent_to_js ⇒ Object
1571 1572 1573 1574 1575 |
# File 'lib/capybara/simulated/browser.rb', line 1571 def push_user_agent_to_js ua = @default_user_agent or return return unless @runtime @runtime.eval("try { Object.defineProperty(navigator, 'userAgent', { value: #{ua.to_json}, configurable: true }); } catch (_) {}") end |
#rack_fetch(method, url, body, headers, redirect_mode, env_extras: nil) ⇒ Object
URLs we won’t even try to route through Rack: anything that isn’t http(s) (data: / mailto: / about:) plus pseudo-tokens like V8’s ‘<snapshot>` that sourcemap libraries pull out of error stacks and feed straight to `fetch()` / `xhr.open()`.
3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 |
# File 'lib/capybara/simulated/browser.rb', line 3655 def rack_fetch(method, url, body, headers, redirect_mode, env_extras: nil) target = resolve_against_current(url.to_s) return nil unless target.is_a?(String) && target.match?(%r{\Ahttps?://}i) method = (method || 'GET').to_s.upcase redirected = false # JS-side base64-encodes Blob/File bodies (raw bytes survive # the engine's UTF-8 string boundary that way); decode before # handing to Rack so the upload PUT lands intact. if headers.is_a?(Hash) && headers['X-Csim-Body-B64'].to_s == '1' body = Base64.decode64(body.to_s) headers = headers.reject {|k, _| k == 'X-Csim-Body-B64' } end MAX_FETCH_REDIRECTS.times do t0 = @trace && Process.clock_gettime(Process::CLOCK_MONOTONIC) # GET-only cache shortcut (RFC 9111). Fresh hit → skip @app.call # entirely; stale-but-revalidatable → fall through with conditional # headers added so the server can return 304. cache_entry = method == 'GET' ? @@asset_cache.lookup(target) : nil if cache_entry&.fresh? # Cached static asset — log headers/type/size but skip the (boring) body. trace_network(method, target, cache_entry.status, headers, body, cache_entry.headers, nil, t0, false) return response_hash(cache_entry.status, cache_entry.headers, cache_entry.body, target, redirected) end env = Rack::MockRequest.env_for(target, method: method, input: body || '') apply_request_headers(env, headers) if headers apply_request_headers(env, @@asset_cache.revalidation_headers(cache_entry)) if cache_entry apply_default_request_env(env, referer: @current_url, force: false) env.merge!(env_extras) if env_extras status, resp_headers, resp_body = dispatch_rack_or_http(target, env, method: method, body: body) (resp_headers) if status == 304 && cache_entry trace_network(method, target, cache_entry.status, headers, body, cache_entry.headers, nil, t0, false) resp_body.close if resp_body.respond_to?(:close) @@asset_cache.refresh(cache_entry, resp_headers) return response_hash(cache_entry.status, cache_entry.headers, cache_entry.body, target, redirected) end if redirect_mode != 'manual' && (loc = redirect_location(status, resp_headers)) raise StandardError, '[capybara-simulated] fetch: redirect blocked by redirect=error mode' if redirect_mode == 'error' # Log this hop (3xx) before method/body are rewritten for the next. trace_network(method, target, status, headers, body, resp_headers, nil, t0, true) redirected = true preserve = [307, 308].include?(status) next_url = resolve_against(loc, target) target = carry_fragment(target, next_url) method = 'GET' unless preserve body = nil unless preserve resp_body.close if resp_body.respond_to?(:close) next end body_str = read_rack_body(resp_body) trace_network(method, target, status, headers, body, resp_headers, body_str, t0, false) @@asset_cache.store(target, status, resp_headers, body_str) if method == 'GET' return response_hash(status, resp_headers, body_str, target, redirected) end raise StandardError, "[capybara-simulated] fetch exceeded #{MAX_FETCH_REDIRECTS} redirects" rescue StandardError => e warn "[capybara-simulated] rack_fetch failed: #{e.class}: #{e.[0, 200]}" nil end |
#rack_fetch_async(method, url, body, headers_json) ⇒ Object
── Hijack-aware async XHR ─────────────────────────────────────
Real browsers’ long-poll keeps the request socket open across the entire user-interactive session, so a server-side ‘MessageBus.publish` (or any other middleware writing through `rack.hijack`) lands on the open connection and the client gets the response when the server is ready. Our default `__rackFetch` is purely sync — the middleware’s hijack path never engaged, so MessageBus’s ‘subscribe(channel, -1)` + `__status` reset chain dropped any publish that landed between two scheduled polls.
‘rack_fetch_async` runs the Rack call with a `rack.hijack` lambda installed. The lambda is invoked iff the middleware actually hijacks; we detect that and spawn a background thread to read from the pipe until the middleware closes its end (a publish landed via `notify_clients`, or `cleanup_timer` fired the empty-`[]` close after `long_polling_interval`). Non-hijacking responses queue immediately on the same thread — no thread spawn, no backpressure beyond the existing sync `__rackFetch` cost.
The contract is generic: any middleware that follows the Rack hijack protocol works, not just ‘message_bus`. JS-side XHR’s async path routes every request here; sync XHRs (‘xhr.open(_, _, false)`, deprecated) stay on `__rackFetch` because the hijack contract can’t satisfy a synchronous XHR response anyway. Returns either a response hash (immediate — middleware didn’t hijack) or a ‘=> N‘ token (deferred — middleware hijacked the connection and a background thread is reading the pipe). The JS-side XHR checks the return shape to pick between inline processing and waiting for `_csim deliverHijackedFetches`.
2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 |
# File 'lib/capybara/simulated/browser.rb', line 2910 def rack_fetch_async(method, url, body, headers_json) headers = begin JSON.parse(headers_json.to_s) rescue JSON::ParserError {} end # `rack_fetch` already handles redirects, cookie merge, the # asset cache shortcut, and download detection — keep async # XHRs on that single source of truth. The new behaviour is # the hijack hook for long-poll-shaped requests: install # `rack.hijack` so the middleware can hold the connection # open until something publishes through it. # # We can't unconditionally install the hijack env keys: some # downstream Discourse middleware paths take a different # streaming branch when `rack.hijack?` is truthy (even # without ever invoking the lambda) and the response then # re-renders the page in a slightly different order, racing # subsequent Capybara `find`s into StaleElement. Restrict # the hook to URLs that look like the long-poll endpoints # we actually need it for (`/message-bus/{id}/poll` today; # extend as new patterns surface). read_io = nil env_extras = if HIJACK_AWARE_URL_PATTERNS.any? {|re| re.match?(url.to_s) } { 'rack.hijack?' => true, 'rack.hijack' => lambda { read_io, write_io = IO.pipe write_io } } end resp = rack_fetch(method, url, body, headers, 'follow', env_extras: env_extras) return resp || {'status' => 0, 'headers' => {}, 'body' => ''} unless read_io id = (@hijack_fetch_seq += 1) @hijack_fetch_threads[id] = Thread.new do Thread.current.report_on_exception = false run_hijacked_pipe_read(id, read_io, @hijack_fetch_queue) end {'handle' => id} end |
#rack_fetch_async_abort(id) ⇒ Object
2962 2963 2964 2965 2966 |
# File 'lib/capybara/simulated/browser.rb', line 2962 def rack_fetch_async_abort(id) thread = @hijack_fetch_threads.delete(id.to_i) thread&.kill nil end |
#rack_fetch_body(url) ⇒ Object
── Host-fn callbacks invoked by bridge.js ──────────────────
2345 2346 2347 2348 2349 |
# File 'lib/capybara/simulated/browser.rb', line 2345 def rack_fetch_body(url) result = rack_fetch('GET', url, '', {}, 'follow') return nil unless result && result['status'].to_i < 400 result['body'].to_s end |
#read_blob_for_window(url) ⇒ Object
Read a blob URL’s bytes + content type from THIS window’s VM (its local blob store) — the Driver uses it to load a blob: document into a fresh aux window opened by this window. Returns type: or nil.
3316 3317 3318 3319 3320 3321 3322 |
# File 'lib/capybara/simulated/browser.rb', line 3316 def read_blob_for_window(url) r = @runtime.call('__csimReadBlobForWindow', url.to_s) return nil unless r.is_a?(Hash) && r['b64'] { bytes: Base64.decode64(r['b64'].to_s), type: r['type'].to_s } rescue StandardError nil end |
#read_file_pick(handle, index, start = nil, finish = nil) ⇒ Object
JS-side ‘__HostBackedFile.text()` / `arrayBuffer()` route through this to read attached file bytes on demand — ActiveStorage’s ‘DirectUpload` MD5-chunks the file via FileReader before POSTing to `/rails/active_storage/direct_uploads`. Returns the requested byte range as base64 so binary content survives the engine string boundary (same approach as `__csimReadBlobBase64`).
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 |
# File 'lib/capybara/simulated/browser.rb', line 1125 def read_file_pick(handle, index, start = nil, finish = nil) paths = file_picks_for(handle.to_i) path = paths && paths[index.to_i] return nil unless path && File.exist?(path) size = File.size(path) s = [start.to_i, 0].max e = finish.nil? ? size : [finish.to_i, size].min return Base64.strict_encode64('') if e <= s bytes = File.open(path, 'rb') do |f| f.seek(s) f.read(e - s) end Base64.strict_encode64(bytes || '') end |
#read_property(prop, doc: false) ⇒ Object
Read a primitive property off THIS window’s globalThis / document — called by the Driver to serve another window’s cross-window proxy read.
3159 3160 3161 3162 3163 |
# File 'lib/capybara/simulated/browser.rb', line 3159 def read_property(prop, doc: false) @runtime.call('__csimReadWindowProp', doc, prop.to_s) rescue StandardError nil end |
#read_rack_body(body) ⇒ Object
Rack response bodies must respond to ‘each` (or be an Array of strings). `to_s` on a streaming body returns the inspect form, not the bytes — which silently shipped 43-byte `#<Rack::Files…>` strings to the JS engine for big assets like jquery.js.
3897 3898 3899 3900 3901 3902 |
# File 'lib/capybara/simulated/browser.rb', line 3897 def read_rack_body(body) buf = +'' body.each {|chunk| buf << chunk.to_s } if body.respond_to?(:each) body.close if body.respond_to?(:close) buf end |
#record_action(kind, description) ⇒ Object
Wraps a driver action so the trace records description, urls, console / network activity, and (on action error / full mode) a post-action DOM snapshot. Re-entrant: nested recorded actions (label-click → click, session send_keys → send_keys) let the outer step own the boundary and the inner just yields.
‘description` is a String or Proc — Procs are lazy-evaluated only when a step is actually being recorded, so the off-path doesn’t pay ‘describe_node_handle`’s V8 round-trip.
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 |
# File 'lib/capybara/simulated/browser.rb', line 1751 def record_action(kind, description) # Off-mode: no autostart, only proceed if a trace was started # explicitly via `driver.start_tracing`. Hot path for users # who set CSIM_TRACE=off. return yield if @trace.nil? && @trace_mode == :off if @trace.nil? @trace = Trace.new(metadata: {auto_started_at: Time.now.utc.iso8601(3)}) @runtime.call('__csimSetTraceActive', true) end return yield if @recording_action @recording_action = true desc = description.is_a?(Proc) ? description.call : description @trace.begin_step(kind, description: desc, url_before: @current_url) error = nil begin yield rescue => e error = {class: e.class.name, message: e.} raise ensure # `full` mode serializes the document after every action; the # default `on_failure` mode only snapshots when an action # errored. The V8 round-trip + DOM serialize is the # expensive part of trace recording, so skipping it on the # happy path is the whole point of the default. dom = (error || @trace_mode == :full) ? html : nil @trace.finish_step(url_after: @current_url, dom_after: dom, error: error) @recording_action = false end end |
#record_history(entry) ⇒ Object
1665 1666 1667 1668 1669 1670 1671 |
# File 'lib/capybara/simulated/browser.rb', line 1665 def record_history(entry) # Discard any forward-history tail (a real browser drops the # redo stack the moment you navigate after a `go_back`). @history = @history[0..@history_idx] if @history_idx + 1 < @history.size @history << entry.merge(kind: entry[:kind] || :visit) @history_idx = @history.size - 1 end |
#record_response(status, headers) ⇒ Object
1540 1541 1542 1543 |
# File 'lib/capybara/simulated/browser.rb', line 1540 def record_response(status, headers) @last_response_status = status @last_response_headers = headers.to_h end |
#record_url_transition(new_url) ⇒ Object
Called whenever ‘@current_url` is about to be set to a new value during a page-load drain or a settle tick driven by a user action; queues the prior URL for surface-via- `current_url` so a polling matcher walks the intermediate chain. Out-of-band JS-driven pushStates (`execute_script(“history.pushState(…)”)`) bypass the queue —they have no chain of microtask-driven transitions to walk, and the caller expects to read the new URL one-shot. Bounded to size 8 to guard against runaway chains; `current_url`’s staleness check drops the rest on any read past the polling- cadence window. Without the queue the finish_installation wizard chain’s intermediate ‘/wizard` would be invisible: the JS-side `replaceWith` to `/wizard/steps/setup` lands during a tick, so by the time Capybara polls `@current_url` is already the final URL.
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 |
# File 'lib/capybara/simulated/browser.rb', line 497 def record_url_transition(new_url) return unless @ticking || @navigating old = @current_url return if old.nil? || old.to_s.empty? return if old.to_s == new_url.to_s # The URL the action started from is the starting point, not an # intermediate it walked through — don't surface it to a polling # (or one-shot) `current_url` as a step. Genuine mid-action # intermediates (a load to /wizard, *then* a replaceState to # /wizard/steps/setup) differ from the baseline and still queue. return if @action_url_baseline && old.to_s == @action_url_baseline.to_s @recent_urls << old.to_s @recent_urls.shift while @recent_urls.size > 8 @recent_urls_last_push_at = Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond) end |
#refresh ⇒ Object
is just a re-GET. Replay the current history entry.
4131 4132 4133 |
# File 'lib/capybara/simulated/browser.rb', line 4131 def refresh replay_history_entry(@history[@history_idx]) end |
#replay_history_entry(entry) ⇒ Object
1672 1673 1674 1675 1676 1677 1678 1679 |
# File 'lib/capybara/simulated/browser.rb', line 1672 def replay_history_entry(entry) return unless entry if entry[:method] == :post navigate_post(entry[:url], entry[:body], entry[:content_type], from_history: true) else navigate(entry[:url], from_history: true) end end |
#reset! ⇒ Object
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 |
# File 'lib/capybara/simulated/browser.rb', line 2250 def reset! @cookies.clear @local_storage.clear @session_storage.clear @sticky_headers.clear # The driver-side resize buffer has to clear too — without # this the previous test's `driver.resize(425, …)` leaks into # the next test's default viewport and any cascade rule that # gates on `(min-width: …)` reports the wrong answer for the # whole new test (Forem's comment-actions dropdown is # mobile-collapsed-by-default). The exception is the # `default_viewport` channel — drivers built for a mobile # session (Discourse's `playwright_mobile_chrome`) need to # stay mobile across resets, not snap back to desktop on the # next mobile-tagged test. if @default_viewport @viewport_width = @default_viewport[0] @viewport_height = @default_viewport[1] else @viewport_width = nil @viewport_height = nil end @current_url = nil @document_handle = 0 # A test may leave a frame switched-to without switching back # (Capybara's reset_session spec covers exactly this); start the # next test back on the main document. reset_frame_scope @history.clear @history_idx = -1 @file_picks = {} if @file_picks # Hand the live trace off to `@pending_trace` so an after-hook # running after `reset_session!` (Capybara's per-test teardown # order) still finds it. Anything stuck in `@pending_trace` # from a prior test is dropped — better than fusing two # tests' actions into one record. @pending_trace = @trace @trace = nil @recording_action = false # Kill any open SSE reader threads — the new VM has no JS-side # EventSource instances to dispatch into, and the old handles # would collide on the fresh handle counter the bridge starts # from after `reset_page`. Same shape for worker threads. reset_event_sources reset_hijacked_fetches reset_workers reset_websockets @window_inbox.clear @broadcast_inbox.clear # Free any zero-copy transfer backing stores that went unimported # (worker killed before draining its inbox, etc.) before the rebuild. drop_pending_transfers @blob_registry_lock.synchronize { @blob_registry.clear; @blob_owners.clear } # Drop volatile entries from the class-level HTTP asset cache # so test-local DB state (TranslationOverride, etc.) reaches # the app on subsequent visits. Fingerprinted assets # (`Cache-Control: immutable`) survive: their URLs are content- # addressable so a stale entry can't shadow a later test. @@asset_cache.clear_volatile if @@asset_cache.respond_to?(:clear_volatile) @runtime.reset_page # Per-visit ctx rebuild drops the JS-side trace-active flag, # so re-flip it if we're carrying a pending trace into the # next visit. @runtime.call('__csimSetTraceActive', false) reset_timer_state invalidate_find_cache end |
#reset_event_sources ⇒ Object
2616 2617 2618 2619 2620 |
# File 'lib/capybara/simulated/browser.rb', line 2616 def reset_event_sources @event_source_threads.each_value(&:kill) @event_source_threads.clear @event_source_queue.clear end |
#reset_frame_scope ⇒ Object
Return DOM-op routing to the main document and drop any frame stack. Called by ‘switch_to_frame(:top)`, per-test `reset!`, and every full page (re)build (which disposes all frame realms) — anything that invalidates the active `within_frame` scope.
597 598 599 600 |
# File 'lib/capybara/simulated/browser.rb', line 597 def reset_frame_scope @current_realm_id = nil @frame_stack.clear end |
#reset_hijacked_fetches ⇒ Object
2978 2979 2980 2981 2982 |
# File 'lib/capybara/simulated/browser.rb', line 2978 def reset_hijacked_fetches @hijack_fetch_threads.each_value(&:kill) @hijack_fetch_threads.clear @hijack_fetch_queue.clear end |
#reset_timer_state ⇒ Object
Re-sync the Ruby-side timer mirror with a freshly-rebuilt JS context. Clear ‘@timers_active` and the `@polling_grace` grace window so the previous page’s pending-timer state doesn’t leak into the next test, leaving ‘Driver#wait?` true and dragging every failing matcher through the full `default_max_wait_time` retry loop.
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 |
# File 'lib/capybara/simulated/browser.rb', line 2098 def reset_timer_state @last_tick_ts = Process.clock_gettime(Process::CLOCK_MONOTONIC) @wall_clock_last = @last_tick_ts # CSIM_CLOCK_WALL escape hatch: don't replay the prev page's gap @timers_active = false @polling_grace = nil @last_polled_gen = nil @idle_settle_polls = 0 @ff_transient_polls = 0 @context_gen += 1 end |
#reset_websockets ⇒ Object
2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 |
# File 'lib/capybara/simulated/browser.rb', line 2722 def reset_websockets @websocket_threads.each_value(&:kill) @websocket_threads.clear # Close BOTH pair ends: csim's read/write end and the app's hijack end # (the app may abandon its end without closing it — e.g. its connection # thread was just killed), so neither leaks across tests. @websocket_sockets.each_value {|s| s.close rescue nil } @websocket_app_sockets.each_value {|s| s.close rescue nil } @websocket_sockets.clear @websocket_app_sockets.clear @websocket_queue.clear end |
#reset_workers ⇒ Object
3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 |
# File 'lib/capybara/simulated/browser.rb', line 3252 def reset_workers @workers.each_value do |w| w[:inbox] << :terminate w[:thread].kill end @workers.clear @worker_outbox.clear @worker_in_flight = 0 @transfer_buffer_lock.synchronize { @transfer_buffers.clear @transfer_buffer_seq = 0 } end |
#resolve_against(url, base) ⇒ Object
3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 |
# File 'lib/capybara/simulated/browser.rb', line 3628 def resolve_against(url, base) return url if url =~ %r{\A[a-z]+://}i # quickjs.rb's module_loader passes the importer for nested # relative imports; if the importer was an inline-script # pseudo-name (no scheme), fall through to the page URL. base = nil unless base.is_a?(String) && base =~ %r{\A[a-z]+://}i eff = base || @current_url || @default_host # Memo of `URI.join(eff, url)` — a pure function of (effective base, url). # A heavy ESM app re-resolves the same ~80 module specifiers against the # same base on every visit (a fresh VM re-instantiates the whole module # graph); Ruby's URI parser was a measured ~11% of per-visit wall. The # Browser persists across a suite's visits, so this instance-level memo # (same scope/threading assumptions as @importmap / @current_url) turns # all but the first visit's resolves into hash hits. cache = (@resolve_against_cache ||= {}) cache[[eff, url]] ||= begin URI.join(eff, url).to_s rescue URI::InvalidURIError, URI::BadURIError url end end |
#resolve_document_url(url) ⇒ Object
Public entry for the Driver to resolve a ‘window.open` / cross-window `location` URL against THIS window’s document (the internal resolver is private). Honours ‘<base href>` like the page’s own links do.
616 617 618 |
# File 'lib/capybara/simulated/browser.rb', line 616 def resolve_document_url(url) resolve_against_current(url, use_base: true) end |
#resolve_module_specifier(specifier, base_url) ⇒ Object
3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 |
# File 'lib/capybara/simulated/browser.rb', line 3617 def resolve_module_specifier(specifier, base_url) @importmap ||= {'imports' => {}, 'scopes' => {}} if (mapped = @importmap['imports'][specifier]) return resolve_against(mapped, base_url) end if specifier.start_with?('/', './', '../') || specifier.match?(%r{\A[a-z]+://}i) return resolve_against(specifier, base_url) end specifier end |
#resolve_visit_url(url) ⇒ Object
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 |
# File 'lib/capybara/simulated/browser.rb', line 413 def resolve_visit_url(url) s = url.to_s # `about:blank` (and other authority-less schemes) have no `//`, so the # `scheme://` test below would treat them as relative paths and prepend # the host root. `navigate` handles `about:blank` specially — pass it # through untouched (open_new_window opens an about:blank tab). return s if s.match?(/\Aabout:/i) unless s =~ %r{\A[a-z]+://}i # Strip path/query/fragment off the current URL to get the origin # root. An opaque or host-less current URL (e.g. `about:blank` in a # freshly-opened window) can't yield an origin — fall back to the # default host so a subsequent relative `visit` still resolves. host_root = begin u = URI.parse(@current_url.to_s) if u.opaque || u.host.nil? @default_host else u.path = ''; u.query = nil; u.fragment = nil u.to_s end rescue URI::InvalidURIError @default_host end host_root = host_root.sub(/\/+$/, '') s = "/#{s}" unless s.start_with?('/') s = "#{host_root}#{s}" end # Real browsers percent-encode characters that aren't legal in their # URL position before issuing the request. Skip the escape pass when # the input is already clean (the common case). s.match?(URL_UNSAFE_CHARS) ? URI::DEFAULT_PARSER.escape(s, URL_UNSAFE_CHARS) : s end |
#response_hash(status, headers, body, url, redirected) ⇒ Object
3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 |
# File 'lib/capybara/simulated/browser.rb', line 3800 def response_hash(status, headers, body, url, redirected) raw = body.to_s hdrs = stringify(headers) is_text = text_response?(hdrs) # `body` crosses as TEXT — `responseText` semantics: the bytes decoded # as UTF-8 with invalid sequences replaced (a leading BOM selects the # encoding per the HTML "decode" algorithm and is removed). The real # bytes for binary consumers ride `body_b64`; the Rack body arrives # BINARY-tagged (see `RuntimeShared.utf8_text`). bom_charset = nil text = if is_text decoded, bom_charset = decode_response_bom(raw) RuntimeShared.utf8_text(decoded) else RuntimeShared.utf8_text(raw) end out = { 'status' => status, 'headers' => hdrs, 'body' => text, 'url' => url, 'redirected' => redirected, 'type' => 'basic' } # The BOM-detected encoding (if any) — a frame load pins its document's # characterSet to it (see __csimFrameWindow); highest-precedence signal. out['charset'] = bom_charset if bom_charset out['body_b64'] = Base64.strict_encode64(raw) unless is_text out end |
#response_headers ⇒ Object
Rack 3 lowercases header names; Capybara tests do ‘[’Content-Type’]‘.
1535 1536 1537 1538 1539 |
# File 'lib/capybara/simulated/browser.rb', line 1535 def response_headers (@last_response_headers || {}).each_with_object({}) {|(k, v), h| h[k.to_s.split('-').map(&:capitalize).join('-')] = v } end |
#revoke_owned_blobs(key) ⇒ Object
Revoke every blob URL owned by a context that’s going away (its blob URL store is part of the global being torn down).
3347 3348 3349 3350 3351 3352 |
# File 'lib/capybara/simulated/browser.rb', line 3347 def revoke_owned_blobs(key) @blob_registry_lock.synchronize do urls = @blob_owners.select {|_url, owner| owner == key }.keys urls.each {|url| @blob_registry.delete(url); @blob_owners.delete(url) } end end |
#revoke_realm_blobs(realm_id) ⇒ Object
3356 |
# File 'lib/capybara/simulated/browser.rb', line 3356 def revoke_realm_blobs(realm_id) = revoke_owned_blobs("r:#{realm_id.to_i}") |
#revoke_worker_blobs(handle) ⇒ Object
Keys are normalized with ‘.to_i` on BOTH sides (register tags “r:#Capybara::Simulated::Browser.owner_realmowner_realm.to_i”) so a marshalled Float/String id still matches.
3355 |
# File 'lib/capybara/simulated/browser.rb', line 3355 def revoke_worker_blobs(handle) = revoke_owned_blobs("w:#{handle.to_i}") |
#right_click(handle, keys = [], **opts) ⇒ Object
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 |
# File 'lib/capybara/simulated/browser.rb', line 1140 def right_click(handle, keys = [], **opts) mark_action_baseline tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) init = {'bubbles' => true, 'cancelable' => true, 'button' => 2, 'which' => 3}.merge(click_event_init(handle, keys, opts)) dom_call('__csimDispatchEvent', handle, 'mousedown', init) sleep opts[:delay].to_f if opts[:delay].to_f > 0 dom_call('__csimDispatchEvent', handle, 'mouseup', init) dom_call('__csimDispatchEvent', handle, 'contextmenu', init) end |
#same_document_traversal?(from, to) ⇒ Boolean
Same-document = every entry between ‘from` and `to` (inclusive) is a `:push_state` entry (or the boundary just changed state on the current URL). A `:visit` entry between them means we’d cross a real navigation, which needs a fresh document.
1660 1661 1662 1663 |
# File 'lib/capybara/simulated/browser.rb', line 1660 def same_document_traversal?(from, to) lo, hi = [from, to].sort ((lo + 1)..hi).all? {|i| @history[i] && @history[i][:kind] == :push_state } end |
#select_option(handle) ⇒ Object
1342 1343 1344 1345 1346 1347 1348 1349 |
# File 'lib/capybara/simulated/browser.rb', line 1342 def select_option(handle) mark_action_baseline tick_real_time invalidate_find_cache dom_call('__csimSelectOption', handle) tick_real_time drain_after_user_action end |
#send_keys(handle, keys) ⇒ Object
Capybara’s ‘send_keys` accepts Strings and Symbols (special keys: `:enter`, `:tab`, `:backspace`, …) and Array combos (modifier + key). We hand each item to JS as a tagged atom so the bridge can fire proper KeyboardEvents with `key` / `code` / `ctrlKey` / `metaKey` / `shiftKey` filled in — required by libraries that gate behaviour on the modifier flags (Redmine’s jstoolbar reads ‘event.ctrlKey || event.metaKey` for Ctrl+B / Cmd+B; quote-reply Stimulus controllers read `event.key`). An Array combo is the canonical “modifier + key” pattern: everything but the last entry is a modifier; the last entry is the key being pressed (String char or Symbol special).
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 |
# File 'lib/capybara/simulated/browser.rb', line 1286 def send_keys(handle, keys) mark_action_baseline tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) # Selenium's contract: a bare modifier symbol (`:shift`) at the # top level "holds" the modifier from that point on. `:null` # releases all modifiers. We rewrite the atom stream so each # following character / key carries the accumulated modifiers. held = [] atoms = keys.flat_map {|k| case k when Symbol if k == :null held = []; nil elsif MODIFIER_KEY_NAMES.include?(k) held = (held + [k.to_s]).uniq; nil else held.empty? ? {'kind' => 'key', 'name' => k.to_s} : {'kind' => 'combo', 'parts' => held + [k.to_s]} end when String held.empty? ? {'kind' => 'text', 'value' => k} : {'kind' => 'combo', 'parts' => held + [k]} when Array parts = k.map {|x| x.is_a?(Symbol) ? x.to_s : x.to_s } {'kind' => 'combo', 'parts' => parts} end }.compact # Contenteditable hosts (ProseMirror, Trix, Tiptap) reconcile # their view between chars; a batched `__csimSendKeys` queues # all `beforeinput` events on the same microtask round and PM # nukes the editor wrapper when its reconciler can't apply # them in order. Split multi-char text atoms into per-char # calls with a `settle` between so PM commits each transaction # before the next char arrives. Plain `<input>` / `<textarea>` # don't need this — keep the single batched call there. has_multichar_text = atoms.any? {|a| a['kind'] == 'text' && a['value'].to_s.length > 1 } if has_multichar_text && dom_call('__csimIsContentEditable', handle) per_char = atoms.flat_map {|a| next a unless a['kind'] == 'text' && a['value'].to_s.length > 1 a['value'].to_s.each_char.map {|c| {'kind' => 'text', 'value' => c} } } head, *tail = per_char dom_call('__csimSendKeys', handle, [head]) tail.each {|atom| tick_real_time dom_call('__csimSendKeys', handle, [atom]) settle } else dom_call('__csimSendKeys', handle, atoms) end drain_after_user_action end |
#send_session_key(key) ⇒ Object
1712 |
# File 'lib/capybara/simulated/browser.rb', line 1712 def send_session_key(key) = send_session_keys([key]) |
#send_session_keys(keys) ⇒ Object
Session-level keystroke. Tab / shift-tab cycle focus; everything else is routed to the currently focused element (if any) as a plain keydown/keyup pair.
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 |
# File 'lib/capybara/simulated/browser.rb', line 1688 def send_session_keys(keys) # Walk the key list with running modifier state so a Selenium- # style `(:shift, :enter)` invocation reaches `Browser#send_keys` # as one combo atom (shift held over enter), while independent # non-modifier keys stay separate calls — each one settles # between dispatches so a dropdown highlight (Avo Tags input's # arrow navigation) commits before the next key fires. Tab / # backtab are focus-advance, dispatched out of band. held = [] Array(keys).each do |k| sym = k.is_a?(Symbol) ? k : (k.respond_to?(:to_sym) ? k.to_sym : nil) if sym == :tab || sym == :backtab dom_call('__csimAdvanceFocus', sym == :backtab) elsif sym && MODIFIER_KEY_NAMES.include?(sym) held << sym else handle = active_element_handle handle = current_document_handle if handle.nil? || handle.zero? atom = held.empty? ? k : (held + [k]) send_keys(handle, [atom]) end end end |
#set_geolocation(latitude: nil, longitude: nil, accuracy: 10, denied: false, **rest) ⇒ Object
CDP-ish shim: override navigator.geolocation (like CDP’s ‘Emulation.setGeolocationOverride`). State is Ruby-backed on `@geolocation`; the JS geolocation object reads it on every call via the `__csimGeolocationState` host fn, so it survives the per-call VM rebuilds (the same model web storage uses).
set_geolocation(latitude: 35.6, longitude: 139.7)
set_geolocation(latitude: 1, longitude: 2, accuracy: 5, altitude: 10)
set_geolocation(denied: true) # report PERMISSION_DENIED
set_geolocation # clear -> report POSITION_UNAVAILABLE
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 |
# File 'lib/capybara/simulated/browser.rb', line 1859 def set_geolocation(latitude: nil, longitude: nil, accuracy: 10, denied: false, **rest) @geolocation = if denied {'denied' => true} elsif latitude.nil? || longitude.nil? nil else {'coords' => {'latitude' => latitude, 'longitude' => longitude, 'accuracy' => accuracy}.merge(rest.transform_keys(&:to_s))} end # Re-deliver to any active watchPosition watchers, mirroring a real # browser firing the watch again when the location updates. The JS # side reads the fresh @geolocation via the host fn. execute_script('if (typeof globalThis.__csimGeoRefireWatches === "function") globalThis.__csimGeoRefireWatches();') nil end |
#set_header(name, value) ⇒ Object
1545 |
# File 'lib/capybara/simulated/browser.rb', line 1545 def set_header(name, value) ; @sticky_headers[name.to_s] = value.to_s ; end |
#set_importmap(json) ⇒ Object
JS-side ‘ingestImportmaps` calls this through the host fn so Ruby-side `resolve_module_specifier` agrees with the bare- specifier map shipped by `<script type=“importmap”>`.
3611 3612 3613 3614 3615 |
# File 'lib/capybara/simulated/browser.rb', line 3611 def set_importmap(json) @importmap = JSON.parse(json.to_s) rescue JSON::ParserError @importmap = {'imports' => {}, 'scopes' => {}} end |
#set_value_with_events(handle, value) ⇒ Object
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 |
# File 'lib/capybara/simulated/browser.rb', line 1030 def set_value_with_events(handle, value) mark_action_baseline tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) # `attach_file` hands us a Pathname (or Array of Pathnames); # the marshaller rejects non-primitive types. Coerce to a path-list # form V8 can hold — the actual multipart upload happens later # in `build_multipart_body` during form submission. coerced = coerce_set_value(value) # For date/time-shaped inputs we need the type-specific # string. Probe the handle's `type` and re-format Date / Time # accordingly — `Date.today` → `2026-05-13` (date input) is # already right via to_s, but `Time` needs the input-type- # specific format. coerced = format_temporal_value(value, handle) if value.is_a?(Date) || value.is_a?(Time) @file_picks ||= {} # Capybara `attach_file` calls `Node#set` with a Pathname; some # callers pass a String path through directly. When the target # IS a file input, promote either form into the file-list path # so `.files` / `@file_picks` reflect the chosen file. coerced = [coerced.to_s] if value.is_a?(Pathname) if !coerced.is_a?(Array) && coerced.is_a?(String) && file_input?(handle) coerced = [coerced] end if coerced.is_a?(Array) paths = coerced.reject(&:empty?) @file_picks[handle] = paths # Expose File-list metadata to the JS side BEFORE setting the # value: __csimSetValue fires input + change synchronously, # and Redmine's onchange="addInputFiles(this)" reads # `inputEl.files` — if we set files after, the handler sees # an empty FileList and tears down the input. file_infos = paths.map {|p| stat = (File.stat(p) rescue nil) { 'name' => File.basename(p), 'size' => stat ? stat.size : 0, # Real browsers tag the File with the MIME type they # sniffed from the path / disk header. Uppy's image-type # filter rejects files whose `type` is empty, so without # this even a `logo.png` `attach_file` finishes uploading # 0 bytes through the validator and the composer's # `#file-uploading` flag stays set forever. Use the OS's # extension-based guess (matches what selenium / Chromium # do on these paths) and fall back to empty when the # extension is unknown. 'type' => mime_type_for_path(p), 'lastModified' => stat ? (stat.mtime.to_f * 1000).to_i : 0 } } dom_call('__csimSetFiles', handle, file_infos) # Mirror real browser: <input type=file>.value reflects only # the filename of the first chosen file (security-faked path). # __csimSetValue dispatches input + change synchronously. js_value = paths.first ? File.basename(paths.first) : '' dom_call('__csimSetValue', handle, js_value) else dom_call('__csimSetValue', handle, coerced) end drain_after_user_action end |
#set_viewport(w, h) ⇒ Object
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 |
# File 'lib/capybara/simulated/browser.rb', line 1577 def (w, h) @viewport_width = w.to_i @viewport_height = h.to_i invalidate_find_cache @runtime.eval("globalThis.innerWidth = #{@viewport_width}; globalThis.innerHeight = #{@viewport_height};") # Recompute the cascade `@media` rules against the new # viewport so visibility checks (Capybara `visible?`, # `getComputedStyle().display`) re-reflect mobile-breakpoint # `display: none` / `display: block` flips. Without this the # cascade keeps the pre-resize hide-rule set. @runtime.call('__csimRebuildCascade') if @document_handle.to_i > 0 # Fire `change` events on every live MediaQueryList whose # match state flipped, so libraries that hold `matchMedia(...)` # listeners (Discourse's `TrackedMediaQuery` powering the # viewport-based mobile/desktop class swap) reactively # re-render. The JS-side function iterates `_activeQueries` # and dispatches only on transitions — cheap no-op when no # query is open. @runtime.call('__csimViewportChanged') if @document_handle.to_i > 0 # Re-fire a `resize` event so libraries that re-layout on # resize (responsive nav, sidebar collapse) see the new size. @runtime.eval("try { (globalThis.dispatchEvent || function(){})(new Event('resize')); } catch (_) {}") nil end |
#set_window_location(handle, url) ⇒ Object
3164 |
# File 'lib/capybara/simulated/browser.rb', line 3164 def set_window_location(handle, url) = (@driver.window_set_location(handle.to_s, url.to_s) if @driver.respond_to?(:window_set_location)) |
#settle ⇒ Object
Yield on the first observable change. Each iter (a) drains the chained-await/‘.then` microtask queue a few rounds, (b) checks the JS-side `__settleGen` counter — bumped on every DOM mutation / URL change — and bails if it ticked, otherwise © advances the virtual clock to fire rAF / setTimeout that the chain is parked on. Capybara’s outer polling loop drives the next iter on the next find / has_? — matching real browsers’ “one paint = one observable moment” semantics.
This makes a user-action settle as cheap as ~4 evals when the click immediately mutates DOM, and lets ‘wait_for_*` helpers catch transient states like “modal removed before the redirect_to Visit’s render rebuilds it” — exactly the window real browsers paint at.
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 |
# File 'lib/capybara/simulated/browser.rb', line 1428 def settle start_gen = @runtime.settle_gen prev_gen = start_gen SETTLE_MAX_ITER.times do deliver_event_source_events deliver_hijacked_fetches deliver_websocket_events break if @runtime.settle_gen > start_gen break unless @timers_active || event_source_pending? || worker_pending? || hijack_fetch_pending? || || websocket_pending? # ONE event-loop step replaces the old drain_microtasks(4)+drain_timers(32) # pair: it fires due timers, runs a per-task microtask checkpoint (so # chained .then / MutationObserver delivery interleave spec-correctly), # and runs the render phase — bailing INTERNALLY on the first settleGen # bump (yield_on_gen), which preserves the one-observable-boundary-per-poll # contract. maxMs 0 when no timer is active just flushes microtasks + # render for the work the deliveries above queued. @runtime.run_loop_step(@timers_active ? SETTLE_DRAIN_MS : 0, SETTLE_MAX_ITER_TASKS, yield_on_gen: true) deliver_event_source_events deliver_hijacked_fetches deliver_websocket_events break if @runtime.settle_gen > start_gen # No progress this iter (no DOM/URL change observed) — the # remaining timers are queued for the future; bail and let # Capybara's wall-clock-driven poll loop drive the next tick # via `tick_real_time`. SSE / Worker channels keep us in # the loop as long as background threads have data queued. break if @runtime.settle_gen == prev_gen && !@runtime.has_ready_timer? && !event_source_pending? && !worker_pending? && !hijack_fetch_pending? && ! && !websocket_pending? prev_gen = @runtime.settle_gen end @find_cache_dirty = true end |
#shadow_root_handle(handle) ⇒ Object
809 810 811 812 |
# File 'lib/capybara/simulated/browser.rb', line 809 def shadow_root_handle(handle) h = dom_call('__csimShadowRoot', handle).to_i h.zero? ? nil : h end |
#stack_resolver ⇒ Object
1803 1804 1805 |
# File 'lib/capybara/simulated/browser.rb', line 1803 def stack_resolver @stack_resolver ||= StackResolver.new(self) end |
#start_trace(metadata = {}) ⇒ Object
1723 1724 1725 1726 |
# File 'lib/capybara/simulated/browser.rb', line 1723 def start_trace( = {}) @trace = Trace.new(metadata: ) @runtime.call('__csimSetTraceActive', true) end |
#status_code ⇒ Object
1533 1534 |
# File 'lib/capybara/simulated/browser.rb', line 1533 def status_code = (@last_response_status || 200) # Rack 3 lowercases header names; Capybara tests do `['Content-Type']`. |
#storage_clear(kind) ⇒ Object
4214 4215 4216 4217 |
# File 'lib/capybara/simulated/browser.rb', line 4214 def storage_clear(kind) store(kind).clear nil end |
#storage_get(kind, key) ⇒ Object
Web Storage host-fn shims. The Ruby-side hashes survive ‘rebuild_ctx` between visits, so apps that cache user data in `localStorage` on page A (Forem’s ‘browserStoreCache(’set’)‘ inside fetchBaseData) see it on page B — without this, every visit boots into a JS-side Map that starts empty and the first-call branches that hinge on cached user data (the onboarding task-card render, `initializeLocalStorageRender`, etc.) silently skip.
4203 4204 4205 |
# File 'lib/capybara/simulated/browser.rb', line 4203 def storage_get(kind, key) store(kind)[key.to_s] end |
#storage_key(kind, index) ⇒ Object
4218 4219 4220 |
# File 'lib/capybara/simulated/browser.rb', line 4218 def storage_key(kind, index) store(kind).keys[index.to_i] end |
#storage_length(kind) ⇒ Object
4221 4222 4223 |
# File 'lib/capybara/simulated/browser.rb', line 4221 def storage_length(kind) store(kind).size end |
#storage_remove(kind, key) ⇒ Object
4210 4211 4212 4213 |
# File 'lib/capybara/simulated/browser.rb', line 4210 def storage_remove(kind, key) store(kind).delete(key.to_s) nil end |
#storage_set(kind, key, value) ⇒ Object
4206 4207 4208 4209 |
# File 'lib/capybara/simulated/browser.rb', line 4206 def storage_set(kind, key, value) store(kind)[key.to_s] = value.to_s nil end |
#submit_form(handle) ⇒ Object
‘Node#submit(*)` (Capybara DSL) hits here. Find the enclosing form, serialise, post.
1513 1514 1515 1516 1517 1518 1519 |
# File 'lib/capybara/simulated/browser.rb', line 1513 def submit_form(handle) tick_real_time invalidate_find_cache form_handle = dom_call('__csimAncestorForm', handle).to_i return if form_handle.zero? submit_form_handle(form_handle, nil) end |
#submit_form_handle(form_handle, submitter_handle) ⇒ Object
Pulls the serialised form-state out of JS, encodes it, and drives the Rack app via ‘navigate` (for GET) or a POST.
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 |
# File 'lib/capybara/simulated/browser.rb', line 2113 def submit_form_handle(form_handle, submitter_handle) invalidate_find_cache spec = dom_call('__csimFormSerialize', form_handle, submitter_handle || 0) return unless spec.is_a?(Hash) action = spec['action'].to_s method = spec['method'].to_s.upcase method = 'GET' if method.empty? fields = (spec['fields'] || []).map {|pair| [pair[0].to_s, pair[1].to_s] } file_inputs = spec['fileInputs'] || [] enctype = spec['enctype'].to_s multipart = enctype.start_with?('multipart/form-data') content_type = nil body = if multipart built = build_multipart_body(fields, file_inputs) content_type = built[:content_type] built[:body] else # Non-multipart: file inputs contribute the filename only. file_inputs.each do |fi| picks = @file_picks && @file_picks[fi['handle'].to_i] || [] fields << [fi['name'].to_s, picks.first ? File.basename(picks.first) : ''] end URI.encode_www_form(fields) end action_url = action.empty? ? (current_browsing_context_url || @default_host) : resolve_against_current(action) # A form submitted inside a frame whose target is that frame (self, or a # `_parent` of a ≥2-deep frame) navigates the FRAME, not the top page. frame_entry = frame_nav_target_entry(spec['target']) if method == 'GET' uri = URI.parse(action_url) uri.query = body unless body.empty? frame_entry ? navigate_frame(uri.to_s, entry: frame_entry) : navigate(uri.to_s) elsif frame_entry navigate_frame_post(action_url, body, content_type || enctype, entry: frame_entry) else navigate_post(action_url, body, content_type || enctype) end end |
#submit_form_in_realm(realm_id, form_handle, submitter_handle) ⇒ Object
Serialize + route a form submitted inside frame realm ‘realm_id`. We serialize in the INITIATING realm (so shadow-tree controls are excluded and relative URLs resolve against that document), then route by target:
- a NAMED frame within that context (a sibling iframe) — reassign its src;
- self / _self / '' — navigate the initiating frame itself, same as a
self-targeted link there (within_frame → navigate_frame; a frame
reached via contentWindow → re-navigate its owning iframe by realm id).
GET fully supported. POST to a self frame needs the entered stack (navigate_frame_post); POST-to-named and other targets from a nested context aren’t modeled (no in-scope need) — logged rather than dropped.
4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 |
# File 'lib/capybara/simulated/browser.rb', line 4047 def submit_form_in_realm(realm_id, form_handle, submitter_handle) spec = @runtime.realm_call(realm_id, '__csimFormSerialize', form_handle, submitter_handle || 0) return unless spec.is_a?(Hash) method = spec['method'].to_s.upcase method = 'GET' if method.empty? target = spec['target'].to_s action = spec['action'].to_s fields = (spec['fields'] || []).map {|pair| [pair[0].to_s, pair[1].to_s] } # Non-multipart file inputs contribute the filename only (mirror submit_form_handle's GET path). (spec['fileInputs'] || []).each do |fi| picks = @file_picks && @file_picks[fi['handle'].to_i] || [] fields << [fi['name'].to_s, picks.first ? File.basename(picks.first) : ''] end body = URI.encode_www_form(fields) get_url = form_get_url(action, body) if frame_self_target?(target) navigate_realm_self(realm_id, get_url, action, method, body, spec['enctype'].to_s) elsif %w[_parent _top _blank].include?(target.downcase) log_console('warn', "nested-context form submit (target=#{target.inspect}) is not modeled") elsif method == 'GET' # Named sibling frame, GET. realm_call returns false when no frame of # that name exists in the initiating document (e.g. it lives in an # ancestor/top context, which HTML target resolution would reach but # we don't); surface it rather than dropping silently. found = @runtime.realm_call(realm_id, '__csimNavigateNamedFrame', target, get_url) log_console('warn', "nested-context form submit: no frame named #{target.inspect} in the submitting document") unless found else log_console('warn', "nested-context form submit (target=#{target.inspect}, method=POST) is not modeled") end end |
#switch_to_frame(target) ⇒ Object
Capybara ‘switch_to_frame`. `target` is an `<iframe>` handle in the CURRENT realm, or `:parent` / `:top`. Entering builds (or reuses) the frame’s V8 realm and routes subsequent DOM ops there; ‘:parent` pops one level, `:top` returns to the main document. Frame switches invalidate the find cache (its keys aren’t realm-qualified, and a switch is rare).
Scope: finds, reads, interactions (click/fill_in/…), evaluate_script, and navigation (a link / form submit whose default action loads a new document) all route into the frame — the target frame’s realm is rebuilt from the fetched document, leaving the top page untouched (see ‘navigate_frame` / `frame_nav_target_entry`). A `_parent`-targeted link or form from a frame nested ≥2 levels rebuilds the intermediate parent frame; `_top` (and a one-level `_parent`, whose parent is the top context) navigate the main page. Cross-origin frame locality is resolved against the main page’s origin.
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 |
# File 'lib/capybara/simulated/browser.rb', line 558 def switch_to_frame(target) invalidate_find_cache case target when :parent @frame_stack.pop @current_realm_id = @frame_stack.last && @frame_stack.last[:realm_id] when :top reset_frame_scope else # Per-frame realms are a V8-engine feature; QuickJS has no nested # browsing context to route into. Distinguish that (unsupported # engine) from a frame that simply failed to build (below), so the # error doesn't misattribute a load failure to the engine. unless @runtime.respond_to?(:realm_call) raise Capybara::Simulated::FrameNotSupported, 'within_frame needs a per-frame browsing context, which only the ' \ 'V8 (rusty_racer) engine provides; QuickJS keeps a same-realm fallback.' end parent_realm = @current_realm_id tick_real_time rid = dom_call('__csimEnsureFrameRealm', target.to_i).to_i if rid.zero? raise Capybara::Simulated::StaleElement, "could not enter frame ##{target} (not a frame element, or its document failed to load)" end # Record the iframe handle + the realm it lives in so a frame-scoped # navigation can rebuild this exact frame (`reload_current_frame_realm`). @frame_stack.push({realm_id: rid, iframe_handle: target.to_i, parent_realm_id: parent_realm}) @current_realm_id = rid # Let the freshly built realm's inline scripts / load handlers settle # so a find immediately inside the block sees the loaded document. settle end end |
#syntax_or_invalid_selector_error?(e) ⇒ Boolean
JS-side selector parser throws a ‘DOMException(’csim: …‘, ’SyntaxError’)‘. The JS engine surfaces it as a `…::SyntaxError` (QuickJS via dynamic-named class) or, under V8, a `RustyRacer::RuntimeError` whose message is `“SyntaxError: csim: …”`. Match the `csim: ` marker anywhere in the message (it’s no longer at the start once the DOMException name is prefixed) or the class suffix, so neither gem becomes a hard dependency.
673 674 675 676 |
# File 'lib/capybara/simulated/browser.rb', line 673 def syntax_or_invalid_selector_error?(e) e.class.name.to_s.end_with?('::SyntaxError') || e..to_s.include?('csim: ') end |
#tag(handle) ⇒ Object
783 |
# File 'lib/capybara/simulated/browser.rb', line 783 def tag(handle) = dom_call('__csimTag', handle).to_s |
#tag_name(handle) ⇒ Object
796 |
# File 'lib/capybara/simulated/browser.rb', line 796 def tag_name(handle) = tag(handle) |
#text(handle) ⇒ Object
782 |
# File 'lib/capybara/simulated/browser.rb', line 782 def text(handle) = dom_call('__csimText', handle).to_s |
#text_response?(headers) ⇒ Boolean
3887 3888 3889 3890 3891 |
# File 'lib/capybara/simulated/browser.rb', line 3887 def text_response?(headers) ct = (headers['content-type'] || headers['Content-Type']).to_s.downcase return false if ct.empty? TEXT_CONTENT_TYPE_PREFIXES.any? {|p| ct.start_with?(p) } end |
#tick_real_time(step_ms: nil) ⇒ Object
Advance the virtual JS clock and fire timers that came due. When ‘step_ms` is omitted, advance by `horizon_fast_forward_step` — a DETERMINISTIC step (never wall-derived, so per-poll JS/Ruby/GC cost can’t shift when a timer fires): a fixed ‘POLL_TICK_STEP_MS` per poll, fast- forwarding straight to a near-future timer when the page is otherwise idle. Explicit `step_ms` is used by `SleepHook#advance_virtual_clock_ms` (from `Kernel#sleep`) and by `Playwright::Page#wait_for_timeout` to step a precise virtual duration.
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 |
# File 'lib/capybara/simulated/browser.rb', line 1980 def tick_real_time(step_ms: nil) return unless @timers_active || worker_pending? || event_source_pending? || hijack_fetch_pending? || || websocket_pending? # Re-entrancy guard. Capybara's `Result#each` triggers nested # finds (visible? per element); the outermost tick has already # advanced the clock, the inner calls would only re-drain # already-fired timers. return if @ticking @ticking = true begin now = Process.clock_gettime(Process::CLOCK_MONOTONIC) # Kept wall-anchored ONLY for `timer_wait_elapsed?` / FIND_PRE_TICK_MIN_S # (gates tick FREQUENCY for the smoke first-find-no-fire contract); the # step SIZE below is deterministic. @last_tick_ts = now effective_step = step_ms || horizon_fast_forward_step if @timers_active && effective_step > 0 r = @runtime.run_loop_step(effective_step) # `dirtied` (settleGen changed) catches a render-phase rAF / microtask- # delivered MutationObserver that mutated the DOM without firing a timer # (fired == 0) — a fired-count-only test would leave a stale find cache. @find_cache_dirty = true if r['dirtied'] || r['fired'].to_i > 0 end # Pull any pending Worker / EventSource messages into JS # state. Without this, `evaluate_script` after kicking off # a worker round-trip would see stale state — the inbox # outbox only drains during `settle`, which doesn't run # for direct `execute_script` / `evaluate_script` calls. @find_cache_dirty = true if > 0 @find_cache_dirty = true if deliver_event_source_events > 0 @find_cache_dirty = true if deliver_hijacked_fetches > 0 @find_cache_dirty = true if > 0 @find_cache_dirty = true if deliver_websocket_events > 0 ensure @ticking = false end # Drain navigation intents queued by JS-side handlers that fired # during the drain (e.g. `setTimeout(() => location.pathname = X)`). # Outside the @ticking guard so the navigate's rebuild_ctx is # well-clear of the V8 call we just made. # Same shape for `form.submit()` queued by a timer callback — # Forem's comment-edit form has an `onsubmit` handler that # `preventDefault`s, polls for the CSRF meta tag inside # `setInterval(…, 1)`, then calls `form.submit()` once the # meta is present. The click that originally fired the submit # event has already returned by the time the interval triggers, # so without this drain the intent sits on the slot forever # and the form never posts. consume_pending_form_submit # And for `<a download>` clicks (Avo's action-download chain # goes via file-saver's `saveAs` → synthetic dispatchEvent # on a freshly-created anchor with `download` + blob URL). consume_pending_download end |
#timer_wait_elapsed? ⇒ Boolean
733 734 735 736 |
# File 'lib/capybara/simulated/browser.rb', line 733 def timer_wait_elapsed? @timers_active && (Process.clock_gettime(Process::CLOCK_MONOTONIC) - @last_tick_ts) >= FIND_PRE_TICK_MIN_S end |
#title ⇒ Object
1521 1522 1523 1524 |
# File 'lib/capybara/simulated/browser.rb', line 1521 def title tick_real_time @runtime.call('__csimDocumentTitle').to_s end |
#trace_network(method, url, status, req_headers, req_body, resp_headers, resp_body, t0, redirected) ⇒ Object
Enriched network log for the trace: response content-type / byte size / elapsed ms / redirect flag, plus request + response headers and bodies (devtools-style). No-ops — and skips all the lookups —unless a trace is recording, so the fetch hot path is unaffected when tracing is off.
3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 |
# File 'lib/capybara/simulated/browser.rb', line 3725 def trace_network(method, url, status, req_headers, req_body, resp_headers, resp_body, t0, redirected) return unless @trace ct = resp_headers && (resp_headers['content-type'] || resp_headers['Content-Type']) ct = ct.first if ct.is_a?(Array) # Rack 3 permits array-valued header fields ct = ct.split(';', 2).first.strip if ct.is_a?(String) size = if resp_body resp_body.bytesize elsif (cl = resp_headers && (resp_headers['content-length'] || resp_headers['Content-Length'])) (cl.is_a?(Array) ? cl.first : cl).to_i end log_network(method, url, status, content_type: (ct if ct.is_a?(String)), size: size, duration_ms: (t0 && ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0) * 1000).round), redirected: (redirected || nil), request_headers: normalize_trace_headers(req_headers), request_body: (req_body && !req_body.to_s.empty? ? cap_trace_body(req_body) : nil), response_headers: normalize_trace_headers(resp_headers), response_body: (resp_body ? cap_trace_body(resp_body) : nil)) rescue StandardError => e # A trace-logging bug must NEVER break the real fetch: rack_fetch's # own `rescue StandardError` would otherwise swallow it and return # nil, so the asset (e.g. jQuery) silently fails to load. Drop the # log entry instead. warn "capybara-simulated: trace network log failed: #{e.class}: #{e.}" end |
#transfer_buffer_fetch(id) ⇒ Object
3375 3376 3377 |
# File 'lib/capybara/simulated/browser.rb', line 3375 def transfer_buffer_fetch(id) @transfer_buffer_lock.synchronize { @transfer_buffers.delete(id.to_i) } end |
#transfer_buffer_fetch_for_js(id) ⇒ Object
Wraps the raw bytes in whatever binary shape the ACTIVE runtime can marshal to a JS Uint8Array (V8: the BINARY-tagged string itself —tag-driven marshalling crosses it as a Uint8Array; QuickJS: base64 that the JS shim’s ‘fetchedToBytes` atob’s — it has no binary marshaller). Asked of the runtime so each engine picks its shape.
3403 3404 3405 3406 3407 |
# File 'lib/capybara/simulated/browser.rb', line 3403 def transfer_buffer_fetch_for_js(id) bytes = transfer_buffer_fetch(id) return nil unless bytes @runtime.wrap_binary(bytes) end |
#transfer_buffer_stash(bytes) ⇒ Object
── postMessage transferable-buffer registry ───────────────────
Large Uint8Array / ArrayBuffer payloads cross isolates by ID; rusty_racer marshals typed arrays as ASCII-8BIT Strings so no JS-side latin-1 / base64 intermediate is built. Without this the 317 MB raw frames in Discourse’s media-optimization-worker peak >4 GB of JS strings before the worker even sees them.
3365 3366 3367 3368 3369 3370 3371 3372 3373 |
# File 'lib/capybara/simulated/browser.rb', line 3365 def transfer_buffer_stash(bytes) s = bytes.to_s s = s.dup.force_encoding(Encoding::ASCII_8BIT) unless s.encoding == Encoding::ASCII_8BIT @transfer_buffer_lock.synchronize { id = (@transfer_buffer_seq += 1) @transfer_buffers[id] = s id } end |
#transfer_token_issued(token) ⇒ Object
JS reports each zero-copy transfer token it mints (‘RustyRacer.transferOut`) so we can release any that go unimported. Callable from a worker thread.
3381 3382 3383 3384 3385 |
# File 'lib/capybara/simulated/browser.rb', line 3381 def transfer_token_issued(token) t = token.to_i @transfer_tokens_lock.synchronize { @transfer_tokens << t } if t > 0 nil end |
#unselect_option(handle) ⇒ Object
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 |
# File 'lib/capybara/simulated/browser.rb', line 1351 def unselect_option(handle) mark_action_baseline tick_real_time invalidate_find_cache # Single-select <select>s can't have a selection cleared per # HTML — Capybara surfaces this as `UnselectNotAllowed`. Ask # the JS side whether the option's parent select is `multiple` # before issuing the unselect; the answer doubles as the # "found the right ancestor" check. info = dom_call('__csimOptionContext', handle) if info.is_a?(Hash) && info['hasSelect'] && !info['multiple'] raise Capybara::UnselectNotAllowed, 'Cannot unselect option from single select box.' end dom_call('__csimUnselectOption', handle) tick_real_time drain_after_user_action end |
#update_current_hash(url) ⇒ Object
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 |
# File 'lib/capybara/simulated/browser.rb', line 1015 def update_current_hash(url) return if @current_url.nil? new_url = resolve_against_current(url) @current_url = new_url # JS-driven same-document fragment navigations (anchor clicks AND # `location.hash`/`href`/`assign` sets) are now handled entirely in # the VM by `tryFragmentNavigate` — they update the JS location and # fire `hashchange` there and never round-trip through here. This # path remains only as a defensive fallback for a fragment URL that # reaches the Ruby navigate/pending drain by some other route; keep # the VM's location object in sync so its `location.href` getter # doesn't read stale. @runtime.call('__csimUpdateLocation', new_url) if @runtime.respond_to?(:call) end |
#value(handle) ⇒ Object
797 |
# File 'lib/capybara/simulated/browser.rb', line 797 def value(handle) = dom_call('__csimValue', handle) |
#viewport_height ⇒ Object
1602 |
# File 'lib/capybara/simulated/browser.rb', line 1602 def ; @viewport_height || 768 ; end |
#viewport_width ⇒ Object
1601 |
# File 'lib/capybara/simulated/browser.rb', line 1601 def ; @viewport_width || 1024 ; end |
#visible?(handle) ⇒ Boolean
790 |
# File 'lib/capybara/simulated/browser.rb', line 790 def visible?(handle) = dom_call('__csimVisible', handle) ? true : false |
#visible_text(handle) ⇒ Object
795 |
# File 'lib/capybara/simulated/browser.rb', line 795 def visible_text(handle) = dom_call('__csimVisibleText', handle).to_s |
#visit(url) ⇒ Object
Address-bar navigation: no Referer, and relative paths resolve against the host root (not the current page’s directory).
406 407 408 |
# File 'lib/capybara/simulated/browser.rb', line 406 def visit(url) navigate(resolve_visit_url(url), referer: nil) end |
#webauthn ⇒ Object
3490 |
# File 'lib/capybara/simulated/browser.rb', line 3490 def webauthn = (@webauthn ||= WebauthnState.new) |
#websocket_pending? ⇒ Boolean
2712 |
# File 'lib/capybara/simulated/browser.rb', line 2712 def websocket_pending? = !@websocket_queue.empty? |
#window_closed?(handle) ⇒ Boolean
3165 |
# File 'lib/capybara/simulated/browser.rb', line 3165 def window_closed?(handle) = @driver.respond_to?(:window_closed?) ? @driver.window_closed?(handle.to_s) : true |
#window_doc_get(handle, prop) ⇒ Object
3156 3157 3158 |
# File 'lib/capybara/simulated/browser.rb', line 3156 def window_doc_get(handle, prop) = (@driver.respond_to?(:window_read) ? @driver.window_read(handle.to_s, prop.to_s, doc: true) : nil) # Read a primitive property off THIS window's globalThis / document — called # by the Driver to serve another window's cross-window proxy read. |
#window_get(handle, prop) ⇒ Object
Cross-window property reads (a WindowProxy ‘win.foo` / `win.document.foo`): route to the Driver, which reads a PRIMITIVE off the target window’s VM.
3155 |
# File 'lib/capybara/simulated/browser.rb', line 3155 def window_get(handle, prop) = (@driver.respond_to?(:window_read) ? @driver.window_read(handle.to_s, prop.to_s, doc: false) : nil) |
#window_location_of(handle) ⇒ Object
3152 3153 3154 |
# File 'lib/capybara/simulated/browser.rb', line 3152 def window_location_of(handle) = @driver.respond_to?(:window_location) ? @driver.window_location(handle.to_s).to_s : '' # Cross-window property reads (a WindowProxy `win.foo` / `win.document.foo`): # route to the Driver, which reads a PRIMITIVE off the target window's VM. |
#window_message_pending? ⇒ Boolean
Covers both cross-window postMessage AND BroadcastChannel — the two cross-window event channels share these drain/pending hooks.
3178 |
# File 'lib/capybara/simulated/browser.rb', line 3178 def = !@window_inbox.empty? || !@broadcast_inbox.empty? |
#with_modal(handler) ⇒ Object
Push a one-shot handler onto the modal-dialog stack — the next modal that fires consumes the topmost handler. Block exit pops in case the dialog never fired.
4230 4231 4232 4233 4234 4235 |
# File 'lib/capybara/simulated/browser.rb', line 4230 def with_modal(handler) @modal_handlers.push(handler) yield if block_given? ensure @modal_handlers.delete(handler) end |
#worker_pending? ⇒ Boolean
3129 |
# File 'lib/capybara/simulated/browser.rb', line 3129 def worker_pending? = !@worker_outbox.empty? || @worker_in_flight > 0 || @worker_init_lock.synchronize { @worker_initializing } > 0 |
#worker_post_to_worker(handle, data) ⇒ Object
3089 3090 3091 3092 3093 3094 |
# File 'lib/capybara/simulated/browser.rb', line 3089 def worker_post_to_worker(handle, data) w = @workers[handle.to_i] return unless w @worker_in_flight += 1 w[:inbox] << data.to_s end |
#worker_spawn(url, shared: false) ⇒ Object
── Web Workers ────────────────────────────────────────────────
‘new Worker(url)` in JS lands in `worker_spawn`. The Ruby thread it spawns owns a fresh V8 Context / QuickJS VM (true isolate, separate microtask queue and timer table), evals the worker script there, and runs an event loop draining timers, microtasks, and the inbox queue from the main thread. Each worker’s ‘__csim_workerPostMessage` host fn closes over its handle and routes outgoing messages onto a shared outbox the main settle drains.
3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 |
# File 'lib/capybara/simulated/browser.rb', line 3067 def worker_spawn(url, shared: false) handle = (@worker_seq += 1) inbox = Thread::Queue.new outbox = @worker_outbox engine_class = @runtime.class target = resolve_against_current(url.to_s) # Resolve the worker script body on the main thread before # handing off to the worker. `blob:` URLs need the main VM's # blob registry; calling into the main runtime from a # non-owning thread SEGVs (V8 isolates are thread- # bound; quickjs.rb's VM is similarly per-thread). body = fetch_worker_script(target) # Pending until the worker's initial script has run (see @worker_initializing). @worker_init_lock.synchronize { @worker_initializing += 1 } thread = Thread.new do Thread.current.report_on_exception = false run_worker(handle, target, body, inbox, outbox, engine_class, shared: shared) end @workers[handle] = {thread: thread, inbox: inbox} handle end |
#worker_terminate(handle) ⇒ Object
3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 |
# File 'lib/capybara/simulated/browser.rb', line 3096 def worker_terminate(handle) w = @workers.delete(handle.to_i) return unless w w[:inbox] << :terminate # Most clean shutdowns are <10 ms; the kill is the fallback # for blocked workers. Join again AFTER the kill so the thread is actually # dead before we revoke its URLs — `Thread#kill` is async, and a worker # still running a `createObjectURL` could otherwise re-register a URL after # the revoke and leak it. w[:thread].join(WORKER_TERMINATE_GRACE) if w[:thread].alive? w[:thread].kill w[:thread].join(WORKER_TERMINATE_GRACE) end # A blocked worker that never returned messages leaves # `@worker_in_flight` permanently > 0; reset when no workers # remain so `polling?` can short-circuit again. @worker_in_flight = 0 if @workers.empty? # The worker is gone — revoke the blob URLs it created. revoke_worker_blobs(handle.to_i) end |
#write_document_cookie(s) ⇒ Object
4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 |
# File 'lib/capybara/simulated/browser.rb', line 4182 def (s) return if s.nil? || s.empty? name, rest = s.split('=', 2) return if name.nil? || name.empty? parts = (rest || '').split(';').map(&:strip) value = parts.shift.to_s if (parts) @cookies.delete(name.strip) else @cookies[name.strip] = value end end |
#ws_close(id, code = 1000, reason = '') ⇒ Object
2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 |
# File 'lib/capybara/simulated/browser.rb', line 2701 def ws_close(id, code = 1000, reason = '') sock = @websocket_sockets[id.to_i] or return # Send the close frame and let the close HANDSHAKE complete: the server # replies with its own close frame, which the reader thread surfaces as # the `__close` event (carrying the agreed code) before tearing the # socket down in its `ensure`. Force teardown is `reset_websockets`'s job. payload = [code.to_i].pack('n') + reason.to_s.b ws_write_frame(sock, 0x8, payload) rescue nil nil end |
#ws_open(url, protocols = nil) ⇒ Object
2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 |
# File 'lib/capybara/simulated/browser.rb', line 2638 def ws_open(url, protocols = nil) id = (@websocket_seq += 1) # ws:// → http://, wss:// → https:// for the Rack env; resolve relative # against the current document (Action Cable's consumer builds an # absolute ws URL, but be tolerant). http_url = url.to_s.sub(/\Awss/i, 'https').sub(/\Aws/i, 'http') target = resolve_against_current(http_url) key = SecureRandom.base64(16) csim_io, app_io = Socket.pair(:UNIX, :STREAM, 0) env = Rack::MockRequest.env_for(target, method: 'GET') apply_default_request_env(env, referer: @current_url) env['HTTP_UPGRADE'] = 'websocket' env['HTTP_CONNECTION'] = 'Upgrade' env['HTTP_SEC_WEBSOCKET_KEY'] = key env['HTTP_SEC_WEBSOCKET_VERSION'] = '13' list = Array(protocols).map(&:to_s).reject(&:empty?) env['HTTP_SEC_WEBSOCKET_PROTOCOL'] = list.join(', ') unless list.empty? env['rack.hijack?'] = true env['rack.hijack'] = -> { app_io } env['rack.hijack_io'] = app_io # The app hijacks + writes the 101 (synchronously, or on its own event # loop thread — Action Cable handles the upgrade on a separate thread, so # `@app.call` may return before the handshake bytes appear; the reader # blocks until they do). Run it on the main thread like the long-poll # hijack so we don't race a second concurrent `@app.call`. (No handshake # timeout: a server that never writes the 101 leaks the reader+socket # until `reset_websockets` — acceptable, real servers always respond.) @app.call(env) @websocket_sockets[id] = csim_io @websocket_app_sockets[id] = app_io accept = Digest::SHA1.base64digest(key + WS_GUID) queue = @websocket_queue @websocket_threads[id] = Thread.new do Thread.current.report_on_exception = false run_websocket_reader(id, csim_io, accept, queue) end id rescue StandardError => e # Nothing was registered for cleanup yet — close both pair ends here so # a failed upgrade (mis-routed URL, app error) doesn't leak fds. csim_io.close rescue nil app_io.close rescue nil @websocket_queue << {id: id, type: '__error', message: "#{e.class}: #{e.}"} id end |
#ws_send(id, data, binary = false, b64 = false) ⇒ Object
‘binary` is set by the JS side (it knows whether `send` was given a string or an ArrayBuffer/view) → opcode 0x2 vs the text 0x1. Action Cable is text-only (JSON). `b64` is set when the bytes arrived base64- encoded (the QuickJS binary path — raw bytes ≥0x80 don’t survive its host boundary); decode before framing.
2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 |
# File 'lib/capybara/simulated/browser.rb', line 2689 def ws_send(id, data, binary = false, b64 = false) sock = @websocket_sockets[id.to_i] or return if binary ws_write_frame(sock, 0x2, b64 ? Base64.decode64(data.to_s) : data.to_s.b) else ws_write_frame(sock, 0x1, data.to_s.b) end nil rescue StandardError nil end |
#xml_content_type?(content_type) ⇒ Boolean
Strip + decode a single leading byte-order mark, returning ‘[utf8_text, charset]` — `charset` is the BOM-selected Encoding-standard name (highest-precedence encoding signal) or nil when there’s no BOM (the hot path: just a 2–3 byte prefix check). One BOM is consumed; any further BOMs are ordinary U+FEFF characters in the decoded text (per spec the parser does not strip them again). An XML-family document (XHTML / SVG / application+text/xml). Its encoding default is UTF-8 — the windows-1252 locale default is HTML-only.
3840 3841 3842 3843 |
# File 'lib/capybara/simulated/browser.rb', line 3840 def xml_content_type?(content_type) mime = content_type.to_s.split(';', 2).first.to_s.strip.downcase mime.end_with?('+xml') || mime == 'application/xml' || mime == 'text/xml' end |
#xpath_shaped?(s) ⇒ Boolean
678 679 680 681 682 683 684 685 686 |
# File 'lib/capybara/simulated/browser.rb', line 678 def xpath_shaped?(s) # Cheap probe: anything starting with `/` (absolute or relative # XPath), `(` (grouped XPath like `(//a)[1]`), or `./` / # `..` (XPath current-node + step) is XPath. We can't treat a # bare leading `.` as XPath because CSS class selectors look # exactly like that (`.contextual`); only the `./` form is # unambiguous. !!(s =~ %r{\A\s*(?:/|\(\s*/|\./|\.\.)}) end |