i wanna use rusty v8 to make a lightweight desktop app in preact. i.e deno uses it,   i.e for a three.js app in preact So the idea here is that Rustv8, which comes with Deno, has an entire... basically has the gist, the core of Chrome, of how Chrome renders websites. But Chrome is a very large program, and we don't need to ship the whole thing in order to make a UI. But we still need to ship the V8 engine. And we want the safety of Rust. So Rustv8 is an ideal candidate for, let's say, making a...  A 3JS app in React that shows a spinning globe on the screen, with a Mercator map of the world, map to it, spinning around as an animation. And because we're using the Rustv8 bindings, we should only need about 60 megabytes to include the entire V8 JavaScript engine, and a little bit more to wrap it, basically. Instead of using Chromium or anything, or Electron, which makes the app very large, we can make it quite a lot smaller for this. So I've attached the docs for Rustv8, and again, I want you to make an app using it. So the app just has to work on Mac OS and on Ubuntu, and we want to use this raw Rustv8 engine. So, let's do it all to completion please. 


DOCS.RS
 v8-129.0.0 
 Platform 
 Feature flags
Rust
 
Find crate
v8
129.0.0
All Items
Sections
Example
Crate Items
Re-exports
Modules
Structs
Enums
Constants
Traits
Functions
Type Aliases
Unions
Crates
v8
Type ‘S’ or ‘/’ to search, ‘?’ for more options…
?
Settings
Crate v8Copy item path
source · [−]
Example
let platform = v8::new_default_platform(0, false).make_shared();
v8::V8::initialize_platform(platform);
v8::V8::initialize();

let isolate = &mut v8::Isolate::new(Default::default());

let scope = &mut v8::HandleScope::new(isolate);
let context = v8::Context::new(scope, Default::default());
let scope = &mut v8::ContextScope::new(scope, context);

let code = v8::String::new(scope, "'Hello' + ' World!'").unwrap();
println!("javascript code: {}", code.to_rust_string_lossy(scope));

let script = v8::Script::compile(scope, code, None).unwrap();
let result = script.run(scope).unwrap();
let result = result.to_string(scope).unwrap();
println!("result: {}", result.to_rust_string_lossy(scope));
Re-exports
pub use script_compiler::CachedData;
Modules
V8
cppgc
fast_api
icu
inspector	Bindings to the V8 Inspector API. Documentation for the V8 inspector API is very sparse, so here are a few references for the next sorry soul who has to dig into it.
json	A JSON Parser and Stringifier.
script_compiler
Structs
AccessorConfiguration
AccessorSignature	An AccessorSignature specifies which receivers are valid parameters to an accessor callback.
Allocator	A thread-safe allocator that V8 uses to allocate |ArrayBuffer|’s memory. The allocator is a global V8 setting. It has to be set via Isolate::CreateParams.
AllowJavascriptExecutionScope
Array	An instance of the built-in array constructor (ECMA-262, 15.4.2).
ArrayBuffer	An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
ArrayBufferView	A base class for an instance of one of “views” over ArrayBuffer, including TypedArrays and DataView (ES6 draft 15.13).
BackingStore	A wrapper around the backing store (i.e. the raw memory) of an array buffer. See a document linked in http://crbug.com/v8/9908 for more information.
BigInt	A JavaScript BigInt value (https://tc39.github.io/proposal-bigint)
BigInt64Array	An instance of BigInt64Array constructor.
BigIntObject	A BigInt object (https://tc39.github.io/proposal-bigint)
BigUint64Array	An instance of BigUint64Array constructor.
Boolean	A primitive boolean value (ECMA-262, 4.3.14). Either the true or false value.
BooleanObject	A Boolean object (ECMA-262, 4.3.15).
CallbackScope	A CallbackScope can be used to bootstrap a HandleScope and ContextScope inside a callback function that gets called by V8. Bootstrapping a scope inside a callback is the only valid use case of this type; using it in other places leads to undefined behavior, which is also the reason CallbackScope::new() is marked as being an unsafe function.
CompiledWasmModule	Wrapper around a compiled WebAssembly module, which is potentially shared by different WasmModuleObjects.
Context	A sandboxed execution context with its own set of built-in objects and functions.
ContextOptions
ContextScope	Stack-allocated class which sets the execution context for all operations executed within a local scope. After entering a context, all code compiled and run is compiled and run in this context.
CreateParams	Initial configuration parameters for a new Isolate.
Data	The superclass of objects that can reside on V8’s heap.
DataView	An instance of DataView constructor (ES6 draft 15.13.7).
Date	An instance of the built-in Date constructor (ECMA-262, 15.9).
DisallowJavascriptExecutionScope
EscapableHandleScope	A HandleScope which first allocates a handle in the current scope which will be later filled with the escape value.
Exception	Create new error objects by calling the corresponding error object constructor with the message.
External	A JavaScript value that wraps a C++ void*. This type of value is mainly used to associate C++ data structures with JavaScript objects.
ExternalReferences
FixedArray	A fixed-sized array with elements of type Data.
Float32Array	An instance of Float32Array constructor (ES6 draft 15.13.6).
Float64Array	An instance of Float64Array constructor (ES6 draft 15.13.6).
Function	A JavaScript function object (ECMA-262, 15.3).
FunctionBuilder	A builder to construct the properties of a Function or FunctionTemplate.
FunctionCallbackArguments
FunctionCallbackInfo	The argument information given to function call callbacks. This class provides access to information about the context of the call, including the receiver, the number and values of arguments, and the holder of the function.
FunctionTemplate	A FunctionTemplate is used to create functions at runtime. There can only be one function created from a FunctionTemplate in a context. The lifetime of the created function is equal to the lifetime of the context. So in case the embedder needs to create temporary functions that can be collected using Scripts is preferred.
GCCallbackFlags	GCCallbackFlags is used to notify additional information about the GC callback.
GCType	Applications can register callback functions which will be called before and after certain garbage collection operations. Allocations are not allowed in the callback functions, you therefore cannot manipulate objects (set or delete properties for example) since it is possible such operations will result in the allocation of objects.
GetPropertyNamesArgs
GetPropertyNamesArgsBuilder
Global	An object reference that is independent of any handle scope. Where a Local handle only lives as long as the HandleScope in which it was allocated, a global handle remains valid until it is dropped.
HandleScope	A stack-allocated class that governs a number of local handles. After a handle scope has been created, all local handles will be allocated within that handle scope until either the handle scope is deleted or another handle scope is created. If there is already a handle scope and a new one is created, all allocations will take place in the new handle scope until it is deleted. After that, new handles will again be allocated in the original handle scope.
HeapStatistics	Collection of V8 heap information.
IndexedPropertyHandlerConfiguration
Int8Array	An instance of Int8Array constructor (ES6 draft 15.13.6).
Int32	A JavaScript value representing a 32-bit signed integer.
Int16Array	An instance of Int16Array constructor (ES6 draft 15.13.6).
Int32Array	An instance of Int32Array constructor (ES6 draft 15.13.6).
Integer	A JavaScript value representing a signed integer.
Isolate	Isolate represents an isolated instance of the V8 engine. V8 isolates have completely separate states. Objects from one isolate must not be used in other isolates. The embedder can create multiple isolates and use them in parallel in multiple threads. An isolate can be entered by at most one thread at any given time. The Locker/Unlocker API must be used to synchronize.
IsolateHandle	IsolateHandle is a thread-safe reference to an Isolate. It’s main use is to terminate execution of a running isolate from another thread.
Local	An object reference managed by the v8 garbage collector.
Location	A location in JavaScript source.
Map	An instance of the built-in Map constructor (ECMA-262, 6th Edition, 23.1.1).
Message	An error message.
MessageErrorLevel
MicrotaskQueue	Represents the microtask queue, where microtasks are stored and processed. https://html.spec.whatwg.org/multipage/webappapis.html#microtask-queue https://html.spec.whatwg.org/multipage/webappapis.html#enqueuejob(queuename,-job,-arguments) https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint
Module	A compiled JavaScript module.
ModuleRequest
Name	A superclass for symbols and strings.
NamedPropertyHandlerConfiguration
Number	A JavaScript number value (ECMA-262, 4.3.20)
NumberObject	A Number object (ECMA-262, 4.3.21).
Object	A JavaScript object (ECMA-262, 4.3.3)
ObjectTemplate	An ObjectTemplate is used to create objects at runtime.
OneByteConst	A static ASCII string resource for usage in V8, created at build time.
OomDetails
OwnedIsolate	Same as Isolate but gets disposed when it goes out of scope.
Platform
Primitive	The superclass of primitive values. See ECMA-262 4.3.2.
PrimitiveArray	An array to hold Primitive values. This is used by the embedder to pass host defined options to the ScriptOptions during compilation.
Private	A private symbol
Promise	An instance of the built-in Promise constructor (ES6 draft).
PromiseRejectMessage
PromiseResolver
PropertyAttribute
PropertyCallbackArguments
PropertyCallbackInfo	The information passed to a property callback about the context of the property access.
PropertyDescriptor
PropertyFilter
PropertyHandlerFlags
Proxy	An instance of the built-in Proxy constructor (ECMA-262, 6th Edition, 26.2.1).
RegExp	An instance of the built-in RegExp constructor (ECMA-262, 15.10).
ResolveModuleCallbackRet	Called during Module::instantiate_module. Provided with arguments: (context, specifier, import_assertions, referrer). Return None on error.
ReturnValue
RustAllocatorVtable	A wrapper around the V8 Allocator class.
Script	A compiled JavaScript script, tied to a Context which was active when the script was compiled.
ScriptOrModule	A container type that holds relevant metadata for module loading.
ScriptOrigin	The origin, within a file, of a script.
Set	An instance of the built-in Set constructor (ECMA-262, 6th Edition, 23.2.1).
SharedArrayBuffer	An instance of the built-in SharedArrayBuffer constructor.
SharedPtr	Wrapper around a C++ shared_ptr. A shared_ptr may be be null.
SharedRef	Wrapper around a C++ shared_ptr. The shared_ptr is assumed to contain a value and may not be null.
Signature	A Signature specifies which receiver is valid for a function.
StackFrame	A single JavaScript stack frame.
StackTrace	Representation of a JavaScript stack trace. The information collected is a snapshot of the execution stack and the information remains valid after execution continues.
StalledTopLevelAwaitMessage
StartupData
String	A JavaScript string value (ECMA-262, 4.3.17).
StringObject	A String object (ECMA-262, 4.3.18).
Symbol	A JavaScript symbol (ECMA-262 edition 6)
SymbolObject	A Symbol object (ECMA-262 edition 6).
SyntheticModuleEvaluationStepsRet
Template	The superclass of object and function templates.
TracedReference	A traced handle without destructor that clears the handle. The embedder needs to ensure that the handle is not accessed once the V8 object has been reclaimed. For more details see BasicTracedReference.
TryCatch	An external exception handler.
TypedArray	A base class for an instance of TypedArray series of constructors (ES6 draft 15.13.6).
Uint8Array	An instance of Uint8Array constructor (ES6 draft 15.13.6).
Uint8ClampedArray	An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
Uint32	A JavaScript value representing a 32-bit unsigned integer.
Uint16Array	An instance of Uint16Array constructor (ES6 draft 15.13.6).
Uint32Array	An instance of Uint32Array constructor (ES6 draft 15.13.6).
UnboundModuleScript	A compiled JavaScript module, not yet tied to a Context.
UnboundScript	A compiled JavaScript script, not yet tied to a Context.
UniquePtr	Pointer to object allocated on the C++ heap. The pointer may be null.
UniqueRef	Pointer to object allocated on the C++ heap. The pointer may not be null.
Value	The superclass of all JavaScript values and objects.
ValueDeserializer	ValueDeserializer is a stack object used as entry-point for an owned and pinned heap object ValueDeserializerHeap. The ’a lifetime is the lifetime of the ValueDeserializerImpl implementation. The ’s lifetime is the lifetime of the HandleScope which is used to retrieve a Local<’s, Context> for the CallbackScopes
ValueSerializer
ValueView	Returns a view onto a string’s contents.
WasmMemoryObject
WasmModuleObject
WasmStreaming	The V8 interface for WebAssembly streaming compilation. When streaming compilation is initiated, V8 passes a Self object to the embedder such that the embedder can pass the input bytes for streaming compilation to V8.
Weak	An object reference that does not prevent garbage collection for the object, and which allows installing finalization callbacks which will be called after the object has been GC’d.
WriteOptions
Enums
ConstructorBehavior	ConstructorBehavior::Allow creates a regular API function.
DataError
Encoding
FunctionCodeHandling
GarbageCollectionType	Types of garbage collections that can be requested via Isolate::request_garbage_collection_for_testing.
IndexFilter
IntegrityLevel	Object integrity levels can be used to restrict what can be done to an object’s properties.
Intercepted	Interceptor callbacks use this value to indicate whether the request was intercepted or not.
Intrinsic
KeyCollectionMode	Keys/Properties filter enums:
KeyConversionMode
MemoryPressureLevel	Memory pressure level for the MemoryPressureNotification. None hints V8 that there is no memory pressure. Moderate hints V8 to speed up incremental garbage collection at the cost of higher latency due to garbage collection pauses. Critical hints V8 to free memory as soon as possible. Garbage collection pauses at this level will be large.
MicrotasksPolicy	Policy for running microtasks:
ModuleStatus	The different states a module can be in.
NewStringType
OnFailure
PromiseHookType	PromiseHook with type Init is called when a new promise is created. When a new promise is created as part of the chain in the case of Promise.then or in the intermediate promises created by Promise.{race, all}/AsyncFunctionAwait, we pass the parent promise otherwise we pass undefined.
PromiseRejectEvent
PromiseState
SideEffectType	Options for marking whether callbacks may trigger JS-observable side effects. Side-effect-free callbacks are allowlisted during debug evaluation with throwOnSideEffect. It applies when calling a Function, FunctionTemplate, or an Accessor callback. For Interceptors, please see PropertyHandlerFlags’s kHasNoSideEffect. Callbacks that only cause side effects to the receiver are allowlisted if invoked on receiver objects that are created within the same debug-evaluate call, as these objects are temporary and the side effect does not escape.
TimeZoneDetection	Time zone redetection indicator for DateTimeConfigurationChangeNotification.
ValueViewData
WasmAsyncSuccess
Constants
BUILD_NUMBER	https://v8.dev/docs/version-numbers
MAJOR_VERSION	https://v8.dev/docs/version-numbers
MINOR_VERSION	https://v8.dev/docs/version-numbers
PATCH_LEVEL	https://v8.dev/docs/version-numbers
VERSION_STRING	https://v8.dev/docs/version-numbers
Traits
Handle
HostImportModuleDynamicallyCallback	HostImportModuleDynamicallyCallback is called when we require the embedder to load a module. This is used as part of the dynamic import syntax.
MapFnTo
ValueDeserializerHelper	Trait used for direct read from the deserialization buffer. Mostly used by the read_host_object callback function in the ValueDeserializerImpl trait to create custom deserialization logic.
ValueDeserializerImpl	The ValueDeserializerImpl trait allows for custom callback functions used by v8.
ValueSerializerHelper	Trait used for direct write to the serialization buffer. Mostly used by the write_host_object callback function in the ValueSerializerImpl trait to create custom serialization logic.
ValueSerializerImpl	The ValueSerializerImpl trait allows for custom callback functions used by v8.
Functions
new_default_allocator	malloc/free based convenience allocator.
new_default_platform	Returns a new instance of the default v8::Platform implementation.
new_rust_allocator⚠	Creates an allocator managed by Rust code.
new_single_threaded_default_platform	The same as new_default_platform() but disables the worker thread pool. It must be used with the –single-threaded V8 flag.
new_unprotected_default_platform	Creates a platform that is identical to the default platform, but does not enforce thread-isolated allocations. This may reduce security in some cases, so this method should be used with caution in cases where the threading guarantees of new_default_platform cannot be upheld (generally for tests).
null
undefined
Type Aliases
AccessorNameGetterCallback
AccessorNameSetterCallback	Note: [ReturnValue] is ignored for accessors.
BackingStoreDeleterCallback
FunctionCallback
HostCreateShadowRealmContextCallback	HostCreateShadowRealmContextCallback is called each time a ShadowRealm is being constructed. You can use HandleScope::get_current_context to get the Context in which the constructor is being run.
HostInitializeImportMetaObjectCallback	HostInitializeImportMetaObjectCallback is called the first time import.meta is accessed for a module. Subsequent access will reuse the same value.
IndexedPropertyDefinerCallback	See [GenericNamedPropertyDefinerCallback].
IndexedPropertyDeleterCallback	See [GenericNamedPropertyDeleterCallback].
IndexedPropertyDescriptorCallback	See [GenericNamedPropertyDescriptorCallback].
IndexedPropertyEnumeratorCallback	See [GenericNamedPropertyEnumeratorCallback].
IndexedPropertyGetterCallback	See [GenericNamedPropertyGetterCallback].
IndexedPropertyQueryCallback	See [GenericNamedPropertyQueryCallback].
IndexedPropertySetterCallback	See [GenericNamedPropertySetterCallback].
MessageCallback
NamedPropertyDefinerCallback	Interceptor for defineProperty requests on an object.
NamedPropertyDeleterCallback	Interceptor for delete requests on an object.
NamedPropertyDescriptorCallback	Interceptor for getOwnPropertyDescriptor requests on an object.
NamedPropertyEnumeratorCallback	Returns an array containing the names of the properties the named property getter intercepts.
NamedPropertyGetterCallback	Interceptor for get requests on an object.
NamedPropertyQueryCallback	Intercepts all requests that query the attributes of the property, e.g., getOwnPropertyDescriptor(), propertyIsEnumerable(), and defineProperty().
NamedPropertySetterCallback	Interceptor for set requests on an object.
NearHeapLimitCallback
OomErrorCallback
PromiseHook
PromiseRejectCallback
ResolveModuleCallback
SyntheticModuleEvaluationSteps
UseCounterCallback
UseCounterFeature
Unions
ExternalReference

Announcing Stable V8 Bindings for Rust
September 24, 2024


Ryan Dahl
Product Update
Deno is a modern, zero-config JavaScript runtime written in Rust. At its core is Rusty V8, a library that provides high-quality, zero-overhead Rust bindings to V8’s C++ API. Over the past five years, Rusty V8 has undergone nearly 150 releases, racking up more than 3.1 million downloads on crates.io. Today, we’re excited to announce a major milestone: Rusty V8 is now stable and production-ready.

While we’d love to mark this moment with a “1.0” release, Rusty V8 is skipping version 1.0 entirely. Instead, we’re aligning with Chrome’s versioning scheme to stay in sync with V8. The first stable release of Rusty V8 will be version 129.0.0, in line with Chrome 129. This version guarantees API stability, moving us beyond years of 0.x releases, and solidifies Rusty V8 as a dependable tool for developers building on top of V8.

What Makes Rusty V8 Special?
Rusty V8 gives Rust developers direct, zero-overhead access to V8’s C++ API. It stands out for its completeness and seamless integration with high-performance environments. A key feature is Rusty V8’s automatic integration of V8’s complex build system into Cargo, allowing developers to easily embed V8 in Rust projects without manual setup. With Rusty V8, you can:

Build custom JavaScript runtimes: Rusty V8 is ideal for crafting your own JavaScript runtime, whether for embedded devices, serverless environments, or plugin systems.
Run WebAssembly modules: Rusty V8 seamlessly executes WebAssembly (Wasm) modules, allowing you to run high-performance code alongside JavaScript.
Leverage the V8 Inspector: Add debugging capabilities like breakpoints and profiling to your JavaScript runtime with the V8 Inspector.
Use the V8 Fast API: Rusty V8 allows you to call Rust functions from JavaScript with minimal overhead, perfect for high-performance applications.
Automatic memory management: V8’s cppgc garbage collector helps manage memory efficiently, reducing the need for manual memory handling in complex applications.
Origin Story
The journey to Rusty V8 started in 2015, when I was experimenting with building a JavaScript runtime in Go using a library called v8worker. Eventually, v8worker was used in the first Deno demo. However, as Deno evolved, it became clear that Go wasn’t the right fit for the project because of worries that Go’s own GC would conflict poorly with V8’s.

In late 2019, Deno co-founder Bert Belder led the effort to create a direct Rust binding to V8. The challenge was to bind V8’s complex C++ API to Rust without compromising on performance or safety. After much effort, Rusty V8 was born—a zero-overhead Rust binding to V8 that provides full control over V8, while ensuring memory safety through Rust’s ownership model.

Using Rusty V8
Here’s a simple example of how you can embed JavaScript in a Rust program using Rusty V8:

fn main() {
  // Initialize V8.
  let platform = v8::new_default_platform(0, false).make_shared();
  v8::V8::initialize_platform(platform);
  v8::V8::initialize();

  // Create a new Isolate and make it the current one.
  let isolate = &mut v8::Isolate::new(v8::CreateParams::default());

  // Create a stack-allocated handle scope.
  let handle_scope = &mut v8::HandleScope::new(isolate);

  // Create a new context.
  let context = v8::Context::new(handle_scope, Default::default());

  // Enter the context for compiling and running the hello world script.
  let scope = &mut v8::ContextScope::new(handle_scope, context);

  // Create a string containing the JavaScript source code.
  let code = v8::String::new(scope, "'Hello' + ' World!'").unwrap();

  // Compile the source code.
  let script = v8::Script::compile(scope, code, None).unwrap();

  // Run the script to get the result.
  let result = script.run(scope).unwrap();

  // Convert the result to a string and print it.
  let result = result.to_string(scope).unwrap();
  println!("{}", result.to_rust_string_lossy(scope));
}
Rusty V8’s memory safety features are a core advantage over the C++ API. For example, in Rust, handles like Local<T> are tied to specific scopes and enforced at compile time. This prevents bugs caused by using or returning invalid handles—something that C++ developers must manage manually. In Rust, if you attempt to use a Local<T> outside its scope, the compiler will catch the mistake.

Here’s a quick example of Rust preventing invalid handle usage:

let isolate = &mut v8::Isolate::new(Default::default());
{
  let scope1 = &mut v8::HandleScope::new(isolate);
  let local = v8::Integer::new(scope1, 123);

  // Attempting to use 'local' outside the scope will fail at compile time
  let invalid_local = {
    let scope2 = &mut v8::HandleScope::new(scope1);
    v8::Integer::new(scope2, 456) // Safe to use in this scope
  };

  // Rust will not allow 'invalid_local' to be accessed here.
}
Versioning
To keep in sync with V8, Rusty V8 will follow Chrome’s versioning scheme. The first stable release is version 129.0.0, corresponding to Chrome 129. While V8 does not follow semantic versioning (semver) and can introduce breaking changes even in minor versions, Rusty V8 will follow semver to ensure compatibility and stability for Rust developers.

Every 4 weeks, Rusty V8 will upgrade its V8 dependency and bump its major version. This means breaking changes to the Rusty V8 API will only happen when V8 upgrades, and the version will always reflect the underlying V8 version.

Ready for Production
Rusty V8 is now a stable, production-ready library for building high-performance JavaScript and WebAssembly runtimes in Rust. Whether you’re creating custom JavaScript runtimes, embedding JS in Rust-backed apps, or exploring server-side JavaScript applications, Rusty V8 provides the flexibility of V8 with the safety and performance guarantees of Rust.

Dive deeper by exploring the full documentation at docs.rs/v8.
again So the idea here is that Rustv8, which comes with Deno, has an entire... basically has the gist, the core of Chrome, of how Chrome renders websites. But Chrome is a very large program, and we don't need to ship the whole thing in order to make a UI. But we still need to ship the V8 engine. And we want the safety of Rust. So Rustv8 is an ideal candidate for, let's say, making a...  A 3JS app in React that shows a spinning globe on the screen, with a Mercator map of the world, map to it, spinning around as an animation. And because we're using the Rustv8 bindings, we should only need about 60 megabytes to include the entire V8 JavaScript engine, and a little bit more to wrap it, basically. Instead of using Chromium or anything, or Electron, which makes the app very large, we can make it quite a lot smaller for this. So I've attached the docs for Rustv8, and again, I want you to make an app using it. So the app just has to work on Mac OS and on Ubuntu, and we want to use this raw Rustv8 engine. So, let's do it all to completion please.