Crate boa_runtime

Crate boa_runtime 

Source
Expand description

Boa’s boa_runtime crate contains an example runtime and basic runtime features and functionality for the boa_engine crate for runtime implementors.

§Example: Adding Web API’s Console Object

  1. Add boa_runtime as a dependency to your project along with boa_engine.
use boa_engine::{js_string, property::Attribute, Context, Source};
use boa_runtime::Console;
use boa_runtime::console::DefaultLogger;

// Create the context.
let mut context = Context::default();

// Register the Console object to the context. The DefaultLogger simply
// write errors to STDERR and all other logs to STDOUT.
Console::register_with_logger(DefaultLogger, &mut context)
    .expect("the console object shouldn't exist yet");

// JavaScript source for parsing.
let js_code = "console.log('Hello World from a JS code string!')";

// Parse the source code
match context.eval(Source::from_bytes(js_code)) {
    Ok(res) => {
        println!(
            "{}",
            res.to_string(&mut context).unwrap().to_std_string_escaped()
        );
    }
    Err(e) => {
        // Pretty print the error
        eprintln!("Uncaught {e}");
    }
};

§Example: Add all supported Boa’s Runtime Web API to your context

use boa_engine::{js_string, property::Attribute, Context, Source};

// Create the context.
let mut context = Context::default();

// Register all objects in the context. To conditionally register extensions,
// call `register()` directly on the extension.
boa_runtime::register(
    (
        // Register the default logger.
        boa_runtime::extensions::ConsoleExtension::default(),
        // A fetcher can be added if the `fetch` feature flag is enabled.
        // This fetcher uses the Reqwest blocking API to allow fetching using HTTP.
        boa_runtime::extensions::FetchExtension(
            boa_runtime::fetch::BlockingReqwestFetcher::default()
        ),
    ),
    None,
    &mut context,
);

// JavaScript source for parsing.
let js_code = r#"
    fetch("https://google.com/")
        .then(response => response.text())
        .then(html => console.log(html))
"#;

// Parse the source code
match context.eval(Source::from_bytes(js_code)) {
    Ok(res) => {
        // The result is a promise, so we need to await it.
        res
            .as_promise()
            .expect("Should be a promise")
            .await_blocking(&mut context)
            .expect("Should resolve()");
        println!(
            "{}",
            res.to_string(&mut context).unwrap().to_std_string_escaped()
        );
    }
    Err(e) => {
        // Pretty print the error
        eprintln!("Uncaught {e}");
    }
};

§About Boa

Boa is an open-source, experimental ECMAScript Engine written in Rust for lexing, parsing and executing ECMAScript/JavaScript. Currently, Boa supports some of the language. More information can be viewed at Boa’s website.

Try out the most recent release with Boa’s live demo playground.

§Boa Crates

  • boa_cli - Boa’s CLI && REPL implementation
  • boa_ast - Boa’s ECMAScript Abstract Syntax Tree.
  • boa_engine - Boa’s implementation of ECMAScript builtin objects and execution.
  • boa_gc - Boa’s garbage collector.
  • boa_icu_provider - Boa’s ICU4X data provider.
  • boa_interner - Boa’s string interner.
  • boa_macros - Boa’s macros.
  • boa_parser - Boa’s lexer and parser.
  • boa_runtime - Boa’s WebAPI features.
  • boa_string - Boa’s ECMAScript string implementation.
  • tag_ptr - Utility library that enables a pointer to be associated with a tag of type usize.
  • small_btree - Utility library that adds the SmallBTreeMap data structure.

Re-exports§

pub use extensions::RuntimeExtension;

Modules§

clone
Module containing all types and functions to implement structuredClone.
console
Boa’s implementation of JavaScript’s console Web API object.
extensions
This module contains all the Runtime extensions that can be registered.
fetch
Boa’s implementation of JavaScript’s fetch function.
interval
A module that declares any functions for dealing with intervals or timeouts.
message
Boa’s implementation of the Message API (mainly postMessage and supporting functions).
microtask
Microtask-related functions and types.
store
Module containing the types related to the JsValueStore.
text
Module implementing JavaScript classes to handle text encoding and decoding.
url
Boa’s implementation of JavaScript’s URL Web API class.

Structs§

Console
This is the internal console object state.
ConsoleState
The current state of the console, passed to the logger backend. This should not be copied or cloned. References are only valid for the current logging call.
DefaultLogger
The default implementation for logging from the console.
NullLogger
A logger that drops all logging. Useful for testing.

Traits§

Logger
A trait that can be used to forward console logs to an implementation.

Functions§

register
Register all the built-in objects and functions of the WebAPI runtime, plus any extensions defined.
register_extensions
Register only the extensions provided. An application can use this to register extensions that it previously hadn’t registered.