Repository navigation
API Reference
English · 中文
Everything on this page comes from the Python package in python/ruyijs. Signatures are copied from the source; descriptions follow its docstrings. Methods marked no docstring are public but undocumented in the source, so only their signature is given.
from ruyijs import (Context, JSError, UNDEFINED, ReentrantError,
JSObject, JSFunction, get_runtime_path, __version__)Context(shell=None, timeout=10.0, environment=None, mode="default", proxy=None, tls=None)Starts one SpiderMonkey shell process and connects to it over a local frame transport (a named pipe on Windows, a Unix socket on macOS and Linux).
| Parameter | Default | Description |
|---|---|---|
shell |
None |
Path of the shell executable. Overrides RUYIJS_SHELL; otherwise the source-checkout or bundled runtime is used. A missing file raises FileNotFoundError. |
timeout |
10.0 |
Seconds allowed for startup and for each request after it acquires the context lock. Must be a finite positive number. A timeout or broken protocol closes the context and kills its process. |
environment |
None |
Profile passed to configure_environment() right after startup. |
mode |
"default" |
"default" or "debug". Debug mode feeds the API log (see Console and debug API log). |
proxy |
None |
Explicit HTTP(S) proxy URL for this context's network requests. None or "" connects directly. It does not alter the host environment or other contexts. |
tls |
None |
Firefox release 100–159 whose TLS ClientHello, HTTP/2 settings and HTTP/3 priorities this context's Necko transport sends. Accepts "120", 120, "120.0" or "firefox-120". None keeps Firefox 159 (or NECKO_FIREFOX if set). It changes the network fingerprint only; pair it with a matching configure_fingerprint user agent. |
Errors raised by the constructor: ValueError for a bad timeout, mode or tls value, or a proxy URL containing NUL/CR/LF; TypeError for a non-string proxy or a tls that is neither a string nor an int; BrokenPipeError("ruyijs process exited (code N): …"), including the tail of the shell's stderr, if the process dies during startup.
Attributes
| Name | Description |
|---|---|
closed |
Read-only property, True once the context is closed. |
timeout |
Per-request timeout in seconds. It is read on every request, so it can be changed between calls (the Akamai example does this). |
tls |
The resolved TLS profile version string, e.g. "159". |
mode |
"default" or "debug". |
shell |
pathlib.Path of the shell executable in use. |
locals |
Property: the page's original Window as a live reference, including callable assignment and live members. |
Calls on one Context are serialized by an internal lock.
| Signature | Description |
|---|---|
close() |
Close the shell process; repeated close calls have no effect. |
with Context(...) as context: |
__exit__ calls close(). Entering a closed context raises RuntimeError. |
A Context that is garbage-collected without close() kills its process.
Evaluate code (text or UTF-8 bytes) in the page and return the result. _TYPED is a private "not given" sentinel.
- Without
to_py, the original typed snapshot protocol is used and the result is converted to plain Python values (see Value conversion). -
to_py=Falsekeeps DOM, class and function references asJSObject/JSFunction;to_py=Truelabels top-level references. Ordinary containers become Python values in both modes. -
filename— or its keyword aliasname(use one, not both) — names the source in stack traces;lineandcolset the source position (signed 32-bit integers). The filename must not contain NUL. -
devtoolsis accepted but not forwarded to the runtime by the current binding. - A JavaScript exception raises
JSError; the context stays usable.
Copy a Python value to a property of this context's page global.
Expose a global host function. name defaults to the function's __name__. If function is not callable, the value is copied as data into __ruyijs__.data[name] instead: data needs an explicit name and adds no Window property; the lexical __ruyijs__ namespace remains accessible to scripts that know its name.
Callbacks run on a helper thread while the script waits. Arguments arrive converted like eval's default mode; the return value is converted like set(). A Python exception is reported back to the script as an error carrying its type name, message and traceback. Calling the same Context from inside a callback raises ReentrantError; a callback that does not return before the request deadline raises TimeoutError("ruyijs host callback timed out").
Bind a native host wrapper, optionally callable with new. name and source are strings, constructor is a bool.
Drain pending engine jobs through the shared runtime coordinator.
Run a full engine collection and return the major GC counter.
Navigate the page to url and load html into the main document. Parser-inserted classic scripts run in order with document.currentScript set; src scripts are read through the resource directory or the network. readyState then becomes interactive (DOMContentLoaded) and complete (load). The first uncaught script or listener error is raised after the load finishes. Returns {"url", "scripts"}.
replay_async_scripts optionally lists recorded async classic script URLs to run at the interactive boundary, draining due tasks between entries. This explicit replay phase does not reproduce a complete task schedule.
Start a top-level navigation the browser itself makes (address bar). The request has no Referer, Sec-Fetch-Site: none and Sec-Fetch-User: ?1; a later location.reload() of that document is made the same way. The navigation runs on the event loop: advance() lets it fetch and commit. Returns {"url"}.
| Signature | Description |
|---|---|
configure_fingerprint(fingerprint) |
Apply a partial, validated Firefox fingerprint profile. Same groups and schema as configure_environment(). Fields are merged atomically; values are read from the browser APIs themselves, not injected as page globals. Configure it before loading a page. |
configure_environment(environment) |
Atomically merge configuration before the first page operation. Fields and ranges are validated by the runtime; a rejected configuration preserves existing state and allows retry. Returns the resulting environment snapshot. |
get_defaults() |
Return the fixed Firefox baseline, independent of this context's overrides. |
The argument must be a plain JSON object: a dict with string keys whose values are None, str, bool, int, finite float, list or dict, at most 64 levels deep and 100,000 nodes, without cycles. Details and examples: Fingerprint and Environment.
| Signature | Description |
|---|---|
configure_clock(mode, epoch_ms=None) |
Configure "system" or "logical" time before page work or timer advancement. Logical mode requires an explicit integer epoch in milliseconds. Returns the clock state. |
clock_status() |
Read the current clock and pending timer count without running timers. |
advance(ms, step_ms=16.667, max_tasks=100000) |
Advance the runtime clock, running bounded macro tasks and engine jobs. Logical time advances without wall-clock waiting; system mode waits. An exhausted budget (max_tasks) returns the actual stopping point and retains the remaining work. step_ms is passed to the runtime and not described further in the docstring. |
tick(ms=0) |
Advance with a one-task budget and report the actual stopping time. |
sleep(ms, step_ms=16.667, max_tasks=100000) |
Same as advance(); logical mode does not wait. |
drain_timers(max_tasks=100000) |
Run currently due timers without manually advancing the clock. |
advance() can raise JSError for page script errors; the shipped examples wrap it in try/except JSError to record the error and keep going.
Used to reproduce a recorded run. Configure them before page execution.
| Signature | Description |
|---|---|
configure_random(state0, state1) |
Restore the initial page's Math.random state. Each word is an exact 16-digit hexadecimal string. The state is local to the initial page realm; child realms and later navigate() documents keep independent generators. Use load_page() to replay that page. |
configure_crypto_replay(documents) |
Ordered {url, values: [...]} entries. Each exact document URL consumes one configured occurrence on load. Hex strings describe getRandomValues calls; UUID records are {method: "randomUUID", value: "..."}. The Crypto instance reports method, length and exhaustion mismatches; unplanned documents use OS randomness. |
crypto_replay_status() |
Document binding and call-consumption counts, without input bytes. |
configure_navigation_replay(documents) |
{url, fields} measurements for at most 32 documents. Exact fragment-free URLs bind by occurrence. fields may contain requestStart, responseStart, responseEnd, transferSize, encodedBodySize, decodedBodySize and loadEventEnd; completion values become visible at the original load completion. Task timing is not restored. |
navigation_replay_status() |
Planned URL, field count and binding status, without advancing time. |
configure_timer_replay(enabled=True) |
Enable explicit host timer selection before page execution. |
pending_timers() |
Live public timers with Context-local realm/task IDs and due times. |
timer_realm(target="window") |
Resolve a live installed Window (a JS expression) to its Context-local timer realm ID. Requires timer replay; the expression may execute script and freezes configuration. No timer handle is consumed. |
run_timer(task_id, expected_firings, at_ms) |
In enabled logical mode, select one due timer and run its engine jobs. at_ms is absolute owner elapsed time. Does not select messages, external completions or Worker tasks, and can reorder ready timers. |
configure_message_replay(enabled=True) |
No docstring. |
pending_messages() |
No docstring. |
run_message(task_id, source_realm, target_realm, sequence, kind, at_ms) |
No docstring. |
| Signature | Description |
|---|---|
put_resource(url, body, status=200, headers=None) |
Atomically store a text (str) or bytes response under the explicit resource key url. headers are ordered name/value pairs. No network request is made; the runtime validates status, fields and storage limits. |
get_resource(url) |
An independent snapshot with a str/bytes body, or None. |
resource_status() |
The shared resource count and charged storage bytes. |
clear_resources() |
Clear the runtime resource directory and return its empty status. |
net_log() |
Ordered page requests recorded by the resource owner. Each entry has id, method, url, requestBody, status and matched; a request carrying cookies also has cookieNames (names only, never values). The log is appended by the same call that matches a request, so an unmatched request is listed with matched False and status 0. |
export_cookies() |
Snapshot of all live cookies in this context, including HttpOnly. Records keep domain/path, hostOnly, secure, httpOnly, sameSite, session, expires, created and order. Times are Unix seconds; a session cookie's expiry is None. Installs nothing in the page. |
cookie_header(url, *, source_url=None, navigation=False, method="GET") |
Select the Cookie header for an external HTTP(S) request, including HttpOnly, using the runtime's domain/path/Secure/expiry/SameSite rules and keeping duplicate names. source_url is the initiating site's URL (None or "" means none); navigation marks a top-level navigation. Recompute for each redirect target. |
Cookie strings map jar bytes to Latin-1 without losing bytes. More context: Network and TLS.
| Signature | Description |
|---|---|
console_log(clear=False) |
Records the page wrote, oldest first, as a list of dicts with realm (Window realm id), method, level, text, indent and stack. The ring is bounded, so it holds the newest records only. clear=True reads and drains every realm's records in one command. |
clear_console() |
Drop every recorded console call and return the empty log. |
peek_api_log(filter=None) |
Return recorded API-log entries without draining them. |
get_api_log(filter=None) |
Return recorded API-log entries and drain the log. |
clear_api_log() |
Drop every API-log entry and report the remaining count. |
The API log is empty unless the context was created with mode="debug". It records accesses to members that a production installer registered; a property a script defines later is not wrapped and produces no entry. The format of filter is not documented in the source.
| Signature | Description |
|---|---|
dispatch_input(event_type, *, target="document", **init) |
Dispatch one trusted Mouse/Pointer event; returns True on delivery. target is a JavaScript expression evaluated in this context, and the event is created in that target's realm. **init coordinate/flag fields use the native event dictionary (the Akamai example passes clientX, clientY, screenX, screenY, button, buttons); timeStamp reads the context's clock. No layout, hit testing or automatic compatibility mouse event is generated. |
click(target, *, hold_ms=80) |
Click the element target (a JavaScript expression) as a user does: trusted pointer/mouse events in Firefox's order at the element's center — enter/over, move, down (which moves focus), hold_ms of running event loop, up, then click (a PointerEvent) and its activation: a submit button submits its form, a link navigates. |
type(text, *, target=None, interval_ms=60) |
Type text into the focused element (or focus target first). Each character is keydown, keypress, beforeinput, the insertion, input and keyup, with interval_ms of running event loop between characters. |
press(key, *, target=None) |
Press one named key: Enter, Backspace, Tab, Escape or an arrow key. Enter inserts a line break in a textarea and submits from an input. |
| Exception | When |
|---|---|
JSError(name, message, stack="") |
JavaScript threw, or the runtime rejected a request. Subclass of RuntimeError with attributes name, message and stack; str(error) is "name: message". The context stays open. |
ReentrantError |
A host callback attempted to enter the JavaScript context that is waiting on it. Subclass of RuntimeError. |
RuntimeError("ruyijs Context is closed") |
Any call on a closed context. |
TimeoutError |
A pipe operation or a host callback exceeded timeout. The context is closed. |
BrokenPipeError |
The shell exited during startup; the message carries the exit code and stderr tail. |
FileNotFoundError |
The shell or the runtime cannot be found. |
OSError |
get_runtime_path() on a platform other than Windows x64, macOS arm64 or Linux x86_64. |
ValueError, TypeError
|
Invalid arguments, values that cannot be converted, or a request larger than 16 MiB (ruyijs request exceeds 16 MiB). |
Any other exception raised while a request is in flight (a timeout, a pipe or protocol error, a host callback that times out) closes the context and kills its process. Argument errors raised before a request is sent, including the 16 MiB check, leave the context open.
Python → JavaScript (set(), data passed to expose(), arguments to JSFunction, assignments through JSObject):
| Python | JavaScript |
|---|---|
None |
null |
ruyijs.UNDEFINED |
undefined |
bool |
boolean |
str |
string |
int |
number; outside ±(2^53 − 1) a BigInt |
float |
number (NaN, ±Infinity and −0 preserved) |
list, tuple
|
Array |
dict with string keys |
Object |
JSObject / JSFunction of the same context |
the original object — JSFunction arguments and JSObject assignments only |
| a Python callable | a callable that calls back into Python — JSFunction arguments and JSObject assignments only |
Other types raise TypeError; cycles raise ValueError; nesting is limited to 64 levels.
JavaScript → Python (eval() without to_py, callback arguments):
| JavaScript | Python |
|---|---|
undefined |
ruyijs.UNDEFINED |
null |
None |
| boolean, string |
bool, str
|
| number |
int or float (NaN, ±Infinity and −0 preserved) |
| BigInt | int |
| Array | list |
| Object | dict |
With to_py=False (or True), references come back as JSObject / JSFunction instead.
Python views of original JavaScript objects owned by one context; no browser state is copied.
| Operation | Effect |
|---|---|
obj.key, obj["key"]
|
Read a property. The runtime reports a missing attribute as AttributeError. |
obj.key = value, obj["key"] = value
|
Set a property. |
del obj.key, del obj["key"]
|
Delete a property. |
"key" in obj |
Property check. |
dir(obj) |
Property keys. |
str(obj) |
The object's string form from JavaScript. |
obj.to_py() |
Convert to a Python value. |
fn(*args) |
Call a JSFunction with positional arguments; keyword arguments raise TypeError. |
A reference is released when its Python object is garbage-collected (the release is sent with the next call). References cannot be passed to a different context.
| Name | Description |
|---|---|
get_runtime_path() |
Return the runtime root containing dist and vendor. RUYIJS_SHELL selects an existing executable and its enclosing runtime root; otherwise a source checkout's shell is preferred to the runtime bundled in the installed package. Never downloads files. |
UNDEFINED |
Singleton for JavaScript undefined; its repr is UNDEFINED. |
__version__ |
Package version string ("0.3.0" on main). |
| Variable | Effect |
|---|---|
RUYIJS_SHELL |
Path of the shell executable (js.exe; js on macOS and Linux). Context(shell=...) takes precedence. |
NECKO_FIREFOX |
TLS profile used when tls=None. |
RUYIJS_NECKO_PYTHON |
macOS only: set to the running interpreter when unset and the runtime has no bundled helper Python. |
NECKO_CORE_LIBRARY |
macOS only: set when unset to dist/necko_tls/libnecko_core.dylib, else dist/necko/libnecko_core.dylib, if one exists. |
Context builds its child process environment from a copy of os.environ and always sets RUYIJS_HTTP_PROXY there from proxy=; it never modifies os.environ itself.
The same runtime is reachable through a C ABI client library, built by tools/client.py; Python and the C ABI share one runtime assembly, and contributors check behaviour through both (see Contributing and License).
ruyiJS · GitHub · PyPI · LinuxDO · License: AGPL-3.0-only or commercial