Skip to Content
V8-wasm
API Reference

Core Runtime & Realms

Initialization, platform & isolate lifecycle, LIFO RAII scopes, handles, GuestRealm, Membrane, and CDP InspectorBridge

Core APIs exported from @browser-ports/v8-wasm for bootstrapping V8-wasm, managing isolates and RAII scopes, marshaling strings and backing stores, isolating guest realms, and connecting to the Chrome DevTools Protocol inspector.

Initialization & Lifecycle

createContext

function createContext(isolate: Isolate, globalTemplate?: ObjectTemplate, globalObject?: Value): Context

Creates a fresh V8 execution Context (realm with its own built-in intrinsics), mirroring v8::Context::New().

Must be called inside an active HandleScope on isolate.

Returns: Newly created Context local handle.

Parameters

  • isolate (Isolate) — Target V8 Isolate.
  • globalTemplate (ObjectTemplate) — Optional ObjectTemplate describing the context's global object.
  • globalObject (Value) — Optional existing global object to reuse.

createDefaultPlatform

function createDefaultPlatform(threadPoolSize?: number): Platform

Creates a default V8 Platform backed by a background worker thread pool, mirroring v8::platform::NewDefaultPlatform().

Pass the returned handle to v8.V8.initializePlatform(platform) before calling v8.V8.initialize(). Dispose with deletePlatform after v8.V8.disposePlatform().

Returns: Handle to the allocated Platform.

Parameters

  • threadPoolSize (number) — Number of worker threads (0 selects V8's default concurrency).

createIsolate

function createIsolate(options?: CreateIsolateOptions): ManagedIsolate

Allocates and initializes a new V8 Isolate with a default (or caller-supplied) ArrayBufferAllocator, mirroring v8::Isolate::New(create_params).

Returns: A ManagedIsolate owning the isolate lifecycle.

Parameters

  • options (CreateIsolateOptions) — Optional isolate creation parameters.

createSingleThreadedDefaultPlatform

function createSingleThreadedDefaultPlatform(): Platform

Creates a single-threaded V8 Platform with no background worker threads, mirroring v8::platform::NewSingleThreadedDefaultPlatform().

Suited for main-thread or dedicated Web Worker embeddings where deterministic foreground pumping via pumpMessageLoop is preferred.

Returns: Handle to the allocated single-threaded Platform.

deletePlatform

function deletePlatform(platform: Platform): void

Destroys a Platform created by createDefaultPlatform or createSingleThreadedDefaultPlatform.

Call only after v8.V8.dispose() and v8.V8.disposePlatform().

Parameters

  • platform (Platform) — Platform handle to free.

initV8

function initV8(options: InitV8Options): Promise<V8WasmExports>

Initializes the V8-wasm runtime by instantiating (or attaching) the Emscripten module and registering its linear-memory scratch buffer.

Must be awaited once before calling v8.V8.initialize(), creating a platform, or allocating isolates and realms.

Returns: The initialized V8WasmExports module instance.

Throws: Error if options.module is omitted.

Parameters

  • options (InitV8Options) — Module factory or pre-instantiated exports and optional Emscripten overrides.

notifyIsolateShutdown

function notifyIsolateShutdown(platform: Platform, isolate: Isolate): void

Notifies platform that isolate is shutting down so queued background work for that isolate can be cancelled, mirroring v8::platform::NotifyIsolateShutdown().

Parameters

  • platform (Platform) — Active V8 Platform.
  • isolate (Isolate) — Isolate being shut down.

pumpMessageLoop

function pumpMessageLoop(platform: Platform, isolate: Isolate, waitForWork?: boolean): boolean

Runs pending foreground tasks queued for isolate on platform, mirroring v8::platform::PumpMessageLoop().

Returns: true if a task was executed; false if the queue was empty.

Parameters

  • platform (Platform) — Active V8 Platform.
  • isolate (Isolate) — Target Isolate whose foreground task queue should be pumped.
  • waitForWork (boolean) — When true, blocks until at least one task is available (default false).

runIdleTasks

function runIdleTasks(platform: Platform, isolate: Isolate, idleTimeSeconds: number): void

Runs pending idle tasks for isolate up to the given time budget, mirroring v8::platform::RunIdleTasks().

Parameters

  • platform (Platform) — Active V8 Platform.
  • isolate (Isolate) — Target Isolate.
  • idleTimeSeconds (number) — Maximum idle time budget in seconds.

Strings, Callbacks, Exceptions & Helpers

createFunction

function createFunction(context: Context, isolate: Isolate, callback: HostFunctionCallback, length?: number): MaybeLocal<V8Function>

Creates a V8 JavaScript Function directly inside context backed by a host TypeScript callback, mirroring v8::Function::New().

Returns: MaybeLocal<V8Function> local handle.

Parameters

  • context (Context) — Creation Context.
  • isolate (Isolate) — Owning V8 Isolate.
  • callback (HostFunctionCallback) — Host callback invoked when JavaScript calls the function.
  • length (number) — Reported Function.prototype.length value (default 0).

createFunctionTemplate

function createFunctionTemplate(isolate: Isolate, callback?: HostFunctionCallback, signature?: Signature, length?: number): FunctionTemplate

Creates a V8 FunctionTemplate bound to an optional host TypeScript callback, mirroring v8::FunctionTemplate::New().

Returns: FunctionTemplate local handle.

Parameters

  • isolate (Isolate) — Target V8 Isolate.
  • callback (HostFunctionCallback) — Optional host function invoked when instantiated functions are called.
  • signature (Signature) — Optional Signature enforcing receiver type checks.
  • length (number) — Reported Function.prototype.length value (default 0).

createGuestRealm

function createGuestRealm(options?: GuestRealmOptions): GuestRealm

Factory helper that creates a new GuestRealm.

Parameters

  • options (GuestRealmOptions) — Optional shared Isolate and pre-compile source transform hook.

getBackingStoreBytes

function getBackingStoreBytes(bsShared: SharedHandle): Uint8Array

Returns a zero-copy Uint8Array subarray directly over V8-wasm linear memory for a BackingStoreShared handle obtained from v8.ArrayBuffer.getBackingStore().

The returned view remains valid only until bsShared.dispose() is called and until Wasm linear memory grows.

Returns: Live Uint8Array view over the backing store's bytes in linear memory.

Parameters

  • bsShared (SharedHandle) — Shared handle to a V8 BackingStore.

getTryCatchException

function getTryCatchException(tc: TryCatch): Value

Returns the caught JavaScript exception from a TryCatch block as a typed Value.

Parameters

  • tc (TryCatch) — Active TryCatch instance with tc.hasCaught() === true.

getTryCatchMessage

function getTryCatchMessage(tc: TryCatch): Message

Returns the diagnostic Message (source line, column, resource name, stack frames) associated with a caught exception in tc.

Parameters

  • tc (TryCatch) — Active TryCatch instance.

getTryCatchStackTrace

function getTryCatchStackTrace(tc: TryCatch, ctx: Context): MaybeLocal<Value>

Returns the formatted stack trace Value for a caught exception in tc, mirroring v8::TryCatch::StackTrace(context).

Parameters

  • tc (TryCatch) — Active TryCatch instance.
  • ctx (Context) — Context used to format the stack trace.

serializeHeapSnapshot

function serializeHeapSnapshot(snapshot: HeapSnapshot): string

Serializes a V8 HeapSnapshot (obtained from isolate.getHeapProfiler().takeHeapSnapshot()) into a Chrome DevTools-compatible .heapsnapshot JSON string.

Returns: Complete JSON heap snapshot payload.

Parameters

  • snapshot (HeapSnapshot) — HeapSnapshot handle to serialize.

stringFromUtf8

function stringFromUtf8(isolate: Isolate, text: string, type?: NewStringType): MaybeLocal<V8String>

Allocates a V8 String from a host JavaScript string via UTF-8 encoding, mirroring v8::String::NewFromUtf8().

Must be called inside an active HandleScope on isolate.

Returns: MaybeLocal<V8String> (empty if allocation fails or exceeds max string length).

Parameters

  • isolate (Isolate) — Target V8 Isolate.
  • text (string) — Host string to copy into V8.
  • type (NewStringType) — String allocation type (NewStringType.kNormal or NewStringType.kInternalized).

stringFromUtf8Checked

function stringFromUtf8Checked(isolate: Isolate, text: string, type?: NewStringType): V8String

Convenience wrapper around stringFromUtf8 that unwraps via .toLocalChecked().

Returns: Non-empty V8String handle.

Parameters

  • isolate (Isolate) — Target V8 Isolate.
  • text (string) — Host string to copy into V8.
  • type (NewStringType) — String allocation type (default NewStringType.kNormal).

stringToUtf8

function stringToUtf8(isolate: Isolate, str: V8String): string

Copies a V8 String out of V8-wasm linear memory into a host JavaScript string using UTF-8 encoding, using the shared scratch buffer for short strings.

Returns: Decoded host JavaScript string.

Parameters

  • isolate (Isolate) — Owning V8 Isolate.
  • str (V8String) — V8 string handle to decode.

v8False

function v8False(isolate: Isolate): V8Boolean

Returns the V8 false boolean singleton for isolate, mirroring v8::False(isolate).

v8Null

function v8Null(isolate: Isolate): Primitive

Returns the V8 null primitive singleton for isolate, mirroring v8::Null(isolate).

v8True

function v8True(isolate: Isolate): V8Boolean

Returns the V8 true boolean singleton for isolate, mirroring v8::True(isolate).

v8Undefined

function v8Undefined(isolate: Isolate): Primitive

Returns the V8 undefined primitive singleton for isolate, mirroring v8::Undefined(isolate).

RAII Scopes (Strict LIFO)

All V8 scope wrappers enforce strict LIFO disposal order (throwing RangeError if exited out of order) and implement [Symbol.dispose]() for TypeScript using declarations.

ContextScope

Enters a V8 Context for JavaScript execution and exits it on disposal, mirroring C++ v8::Context::Scope.

Must be disposed in strict LIFO order (RangeError otherwise).

new ContextScope(context: WasmHandle)

Enters context as the current execution context.

Methods

  • [dispose](): void

    Disposable protocol hook for using declarations.

  • dispose(): void

    Exits the entered context.

    Throws: RangeError if disposed out of LIFO order.

EscapableHandleScope

A HandleScope that can promote a single local handle into the enclosing HandleScope via escape, mirroring C++ v8::EscapableHandleScope.

Must be disposed in strict LIFO order (RangeError otherwise).

new EscapableHandleScope(isolate: WasmHandle)

Enters a new EscapableHandleScope for isolate.

Methods

  • [dispose](): void

    Disposable protocol hook for using declarations.

  • dispose(): void

    Exits this EscapableHandleScope, freeing all non-escaped handles.

    Throws: RangeError if disposed out of LIFO order.

  • escape<T extends WasmHandle>(value: T, ctor?: (ptr: number) => T): T

    Promotes value into the enclosing handle scope so it remains valid after this scope is disposed. Can be called at most once per EscapableHandleScope.

    Returns: Escaped handle owned by the outer handle scope.

    • value (T) — Local handle created inside this scope.
    • ctor ((ptr: number) => T) — Optional target handle constructor (defaults to value.constructor).

HandleScope

Stack-disciplined container for V8 local handles, mirroring C++ v8::HandleScope.

All Local handles created while a HandleScope is active are bulk-released when dispose() is called. Scopes must be disposed in strict LIFO order or a RangeError is thrown.

Example:

HandleScope.run(isolate, () => {
  const s = stringFromUtf8Checked(isolate, 'hello');
  // `s` is automatically reclaimed when the callback exits.
});
new HandleScope(isolate: WasmHandle)

Enters a new HandleScope for isolate.

Static Methods

  • static run<R>(isolate: WasmHandle, fn: (scope: HandleScope) => R): R

    Executes fn inside a freshly created HandleScope and guarantees LIFO disposal in a finally block.

    Returns: The value returned by fn.

    • isolate (WasmHandle) — Active V8 Isolate.
    • fn ((scope: HandleScope) => R) — Callback executed within the handle scope.

Methods

  • [dispose](): void

    Disposable protocol hook for using declarations.

  • dispose(): void

    Exits this HandleScope and frees all local handles allocated within it.

    Throws: RangeError if disposed out of LIFO order.

IsolateScope

Enters a V8 Isolate on the current thread and exits it on disposal, mirroring C++ v8::Isolate::Scope.

Must be disposed in strict LIFO order (RangeError otherwise).

new IsolateScope(isolate: WasmHandle)

Enters isolate as the current isolate.

Methods

  • [dispose](): void

    Disposable protocol hook for using declarations.

  • dispose(): void

    Exits the entered isolate.

    Throws: RangeError if disposed out of LIFO order.

Locker

Acquires the V8 isolate lock for the current thread when sharing a single Isolate across multiple threads, mirroring C++ v8::Locker.

Must be disposed in strict LIFO order (RangeError otherwise).

new Locker(isolate: WasmHandle)

Locks isolate for exclusive access on the current thread.

Methods

  • [dispose](): void

    Disposable protocol hook for using declarations.

  • dispose(): void

    Releases the isolate lock.

    Throws: RangeError if disposed out of LIFO order.

SealHandleScope

Debug/safety scope that forbids allocating any new local handles while active, mirroring C++ v8::SealHandleScope.

Must be disposed in strict LIFO order (RangeError otherwise).

new SealHandleScope(isolate: WasmHandle)

Enters a SealHandleScope for isolate.

Methods

  • [dispose](): void

    Disposable protocol hook for using declarations.

  • dispose(): void

    Exits this SealHandleScope.

    Throws: RangeError if disposed out of LIFO order.

TryCatch

External exception handler that catches JavaScript exceptions thrown by V8 API calls within its lifetime, mirroring C++ v8::TryCatch.

Use getTryCatchException, getTryCatchMessage, and getTryCatchStackTrace from the package root for typed V8 handles. Must be disposed in strict LIFO order (RangeError otherwise).

new TryCatch(isolate: WasmHandle)

Creates and activates a new TryCatch handler for isolate.

Methods

  • [dispose](): void

    Disposable protocol hook for using declarations.

  • canContinue(): boolean

    Returns true if execution can safely continue in V8 (returns false for uncatchable exceptions such as Isolate.terminateExecution()).

  • dispose(): void

    Exits and destroys this TryCatch handler.

    Throws: RangeError if disposed out of LIFO order.

  • exceptionPtr(): number

    Returns the raw handle pointer to the caught exception Value (0 if none).

  • hasCaught(): boolean

    Returns true if an exception has been caught by this TryCatch block.

  • hasTerminated(): boolean

    Returns true if execution was terminated via Isolate.terminateExecution().

  • messagePtr(): number

    Returns the raw handle pointer to the associated v8.Message (0 if none).

  • reset(): void

    Clears any caught exception state so this TryCatch can be reused.

  • reThrowPtr(): number

    Rethrows the caught exception to an outer TryCatch handler, returning the raw handle pointer.

  • setCaptureMessage(value: boolean): void

    Controls whether a v8.Message object is captured for caught exceptions.

  • setVerbose(value: boolean): void

    Controls whether caught exceptions are also reported to the isolate's message listeners (verbose mode).

  • stackTracePtr(context: WasmHandle): number

    Returns the raw MaybeLocal<Value> handle pointer to the exception's stack trace string in context (0 if unavailable).

Unlocker

Temporarily releases a held Locker on the current thread and re-acquires it upon disposal, mirroring C++ v8::Unlocker.

Must be disposed in strict LIFO order (RangeError otherwise).

new Unlocker(isolate: WasmHandle)

Temporarily unlocks isolate on the current thread.

Methods

  • [dispose](): void

    Disposable protocol hook for using declarations.

  • dispose(): void

    Re-acquires the isolate lock.

    Throws: RangeError if disposed out of LIFO order.

Handles, Maybe & Callbacks

FunctionCallbackInfo

Low-level view of the arguments and receiver passed to a host callback from V8, mirroring C++ v8::FunctionCallbackInfo<v8::Value>.

Most callers use the typed wrapper TypedFunctionCallbackInfo delivered to createFunction and createFunctionTemplate.

new FunctionCallbackInfo(ptr: number)

Linear-memory pointer to the C++ v8::FunctionCallbackInfo<v8::Value> struct.

Properties

  • readonly ptr: number

Methods

  • getPtr(index: number): number

    Returns the raw Local<Value> handle pointer for argument index (or undefined if out of range).

  • getReturnValue(): ReturnValue

    Returns the ReturnValue object used to set the callback's JS return value.

  • isConstructCall(): boolean

    Returns true if the function was invoked as a constructor (new fn(...)).

  • isolatePtr(): number

    Returns the raw pointer to the calling v8::Isolate.

  • length(): number

    Returns the number of arguments passed by JavaScript.

  • newTargetPtr(): number

    Returns the raw Local<Value> handle pointer for new.target.

  • thisPtr(): number

    Returns the raw Local<Object> handle pointer for the this receiver.

Global

class Global<T extends WasmHandle>

Persistent handle that keeps a V8 heap object alive across HandleScope boundaries, mirroring C++ v8::Global<T>.

Call reset or dispose (or use using) when the handle is no longer needed so V8 can reclaim the object. Supports weak references with finalizer callbacks via setWeak.

new Global<T extends WasmHandle>(isolate: WasmHandle, local: T, ctor?: (ptr: number) => T)

Promotes a Local handle into a persistent Global<T> handle.

  • isolate (WasmHandle) — Owning V8 Isolate.
  • local (T) — Local handle to persist.
  • ctor ((ptr: number) => T) — Optional constructor for get (defaults to local.constructor).

Methods

  • [dispose](): void

    Disposable protocol hook for using declarations.

  • clearWeak(): void

    Restores this handle from weak back to strong and unregisters any weak callback.

  • dispose(): void

    Alias for reset.

  • get(isolate: WasmHandle): T

    Materializes a fresh Local handle in the currently active HandleScope.

    • isolate (WasmHandle) — Owning V8 Isolate.
  • isEmpty(): boolean

    Returns true if this persistent handle has been reset or is empty.

  • isWeak(): boolean

    Returns true if this handle is currently weak.

  • reset(): void

    Releases the persistent handle and any registered weak callback. Safe to call repeatedly.

  • setWeak(callback: () => void, type?: number): void

    Marks this persistent handle as weak so V8's garbage collector may reclaim the referenced object when no strong references remain, invoking callback upon collection.

    • callback (() => void) — Finalizer invoked when the referent is collected.
    • type (number) — Optional WeakCallbackType enum value (default 0).

Maybe

class Maybe<T>

Represents a primitive or enum result that may or may not hold a value, mirroring C++ v8::Maybe<T>.

A Maybe<T> is either Just(value) or Nothing (typically indicating that a JavaScript exception occurred inside V8).

Static Methods

  • static just<T>(value: T): Maybe<T>

    Constructs a present Maybe<T> containing value.

  • static nothing<T>(): Maybe<T>

    Constructs an empty (Nothing) Maybe<T>.

Methods

  • fromJust(): T

    Returns the contained value, throwing an Error if this Maybe is Nothing.

    Mirrors C++ v8::Maybe<T>::FromJust().

    Throws: Error when isNothing() is true.

  • fromMaybe(defaultValue: T): T

    Returns the contained value if isJust(), otherwise returns defaultValue.

    • defaultValue (T) — Fallback value returned when Nothing.
  • isJust(): boolean

    Returns true if this Maybe holds a value.

  • isNothing(): boolean

    Returns true if this Maybe is empty (Nothing).

  • toChecked(): T

    Alias for fromJust, mirroring C++ v8::Maybe<T>::ToChecked().

MaybeLocal

class MaybeLocal<T extends WasmHandle>

Wrapper around a V8 Local<T> that may or may not be empty, mirroring C++ v8::MaybeLocal<T>.

V8 API functions that can fail or throw a JavaScript exception return a MaybeLocal<T> to force callers to check for emptiness before accessing the handle.

new MaybeLocal<T extends WasmHandle>(ptr: number, ctor: (ptr: number) => T)

Creates a MaybeLocal<T> from raw handle bits and the target handle constructor.

  • ptr (number) — Raw handle bits (0 for empty).
  • ctor ((ptr: number) => T) — Constructor used to materialize the typed handle when non-empty.

Properties

  • readonly ptr: number

    Raw handle bits (0 when empty).

Methods

  • fromMaybe(defaultValue: T): T

    Returns the contained handle if non-empty, otherwise returns defaultValue.

    • defaultValue (T) — Fallback handle returned when empty.
  • isEmpty(): boolean

    Returns true if this MaybeLocal is empty (e.g., an exception was thrown).

  • toLocal(): T | null

    Converts this MaybeLocal<T> to T if non-empty, or null if empty.

  • toLocalChecked(): T

    Extracts the underlying T handle, throwing an Error if this MaybeLocal is empty.

    Mirrors C++ v8::MaybeLocal<T>::ToLocalChecked().

    Throws: Error when isEmpty() is true.

ReturnValue

Setter for the return value of a host callback invoked by V8, mirroring C++ v8::ReturnValue<v8::Value>.

new ReturnValue(infoPtr: number)

Methods

  • set(value: WasmHandle): void

    Sets the callback return value to a V8 Value handle.

  • setBoolean(value: boolean): void

    Sets the callback return value to a JavaScript boolean primitive.

  • setInt32(value: number): void

    Sets the callback return value to a 32-bit signed integer.

  • setNull(): void

    Sets the callback return value to JavaScript null.

  • setNumber(value: number): void

    Sets the callback return value to an IEEE-754 double-precision number.

  • setUndefined(): void

    Sets the callback return value to JavaScript undefined.

SharedHandle

class SharedHandle extends WasmHandle

Base class for heap-allocated std.shared_ptr<T> handles exported across V8-wasm (such as BackingStoreShared). Must be disposed explicitly or via using to release the underlying C++ reference count.

Methods

  • [dispose](): void

    Disposable protocol hook for using declarations.

  • dispose(): void

    Releases the underlying C++ std.shared_ptr reference. Safe to call multiple times.

WasmHandle

Base wrapper for every V8 C++ object pointer or Local<T> indirect handle represented as a 32-bit unsigned address in V8-wasm linear memory.

new WasmHandle(ptr: number)

Constructs a handle wrapper around a raw 32-bit Wasm pointer.

  • ptr (number) — Linear-memory pointer or handle bits (0 represents null/empty).

Properties

  • readonly ptr: number

    Raw unsigned 32-bit pointer or handle bits in V8-wasm linear memory.

Static Methods

  • static fromPtr(ptr: number): WasmHandle

    Wraps a raw 32-bit pointer as a WasmHandle.

    • ptr (number) — Linear-memory pointer or handle bits.

Methods

  • as<T extends WasmHandle>(ctor: (ptr: number) => T): T

    Reinterprets this handle as a more specific WasmHandle subclass without performing a runtime type check (caller should verify with V8 is*() predicates first).

    Returns: A new wrapper instance pointing to the same underlying V8 handle.

    • ctor ((ptr: number) => T) — Target WasmHandle subclass constructor (e.g., v8.String, v8.Object).
  • isNull(): boolean

    Returns true if the underlying pointer is null (0).

GuestRealm, Membrane & InspectorBridge

GuestRealm

High-level isolated JavaScript realm backed by a real V8-wasm Context (and an optional dedicated Isolate) paired with a bidirectional Membrane.

Each GuestRealm has completely disjoint built-in prototypes (Object, Array, Function, etc.) and supports deterministic cleanup via dispose() or using.

new GuestRealm(options?: GuestRealmOptions)

Constructs a new GuestRealm, creating a fresh V8 Context (and a dedicated Isolate unless options.isolate is provided).

  • options (GuestRealmOptions) — Optional shared isolate and pre-compile source hook.

Properties

  • readonly isolate: Isolate

    V8 Isolate hosting this realm (either owned or shared via options.isolate).

  • readonly membrane: Membrane

    Bidirectional Membrane marshaling values in and out of this realm.

Methods

  • [dispose](): void

    Disposable protocol hook for using declarations.

  • defineGlobal(name: string, value: unknown): void

    Defines a property on the guest realm's globalThis object, marshaling value across the Membrane into V8.

    • name (string) — Global property name in the guest realm.
    • value (unknown) — Host value (primitive, function, object, ArrayBuffer, etc.) to expose.
  • dispose(): void

    Disposes the membrane, releases the guest Context, and disposes the Isolate if owned.

  • evalInRealm(source: string, opts?: ScriptOpts): unknown

    Compiles and executes source inside the guest V8 realm and marshals the completion value back across the Membrane.

    Guest syntax and runtime exceptions are extracted and rethrown in the host realm.

    Returns: Marshaled result (primitive by value, guest function wrapper, or live Proxy).

    • source (string) — JavaScript source text to compile and evaluate.
    • opts (ScriptOpts) — Optional script URL and compilation mode.
  • runScript(source: string, opts?: ScriptOpts): unknown

    Alias for evalInRealm.

    • source (string) — JavaScript source text to compile and evaluate.
    • opts (ScriptOpts) — Optional script URL and compilation mode.

InspectorBridge

High-level TypeScript bridge for V8's built-in Chrome DevTools Protocol (CDP) inspector (v8_inspector.V8Inspector + V8InspectorClient).

Supports registering contexts, opening protocol sessions, dispatching CDP JSON commands (Runtime.enable, Debugger.enable, Profiler.start, etc.), and clean disposal via using.

new InspectorBridge(isolate: Isolate, clientHandlers?: InspectorClientHandlers)

Attaches a V8Inspector instance to isolate.

  • isolate (Isolate) — Target V8 Isolate to inspect.
  • clientHandlers (InspectorClientHandlers) — Optional pause-loop hooks for breakpoint handling.

Properties

  • readonly inspector: V8Inspector

    Underlying generated V8Inspector handle.

Methods

  • [dispose](): void

    Disposable protocol hook for using declarations.

  • connect(contextGroupId: number, handlers: InspectorChannelHandlers, trustLevel?: V8InspectorClientTrustLevel): InspectorSessionBridge

    Opens a new CDP InspectorSessionBridge attached to contextGroupId, mirroring v8_inspector::V8Inspector::connect().

    Returns: A disposable InspectorSessionBridge.

    • contextGroupId (number) — Context group ID previously passed to contextCreated.
    • handlers (InspectorChannelHandlers) — Callbacks receiving CDP responses and notifications.
    • trustLevel (V8InspectorClientTrustLevel) — Client trust level (defaults to V8InspectorClientTrustLevel.kFullyTrusted).
  • contextCreated(context: Context, contextGroupId: number, name: string): void

    Notifies the inspector that a new Context is available for inspection, mirroring v8_inspector::V8Inspector::contextCreated().

    • context (Context) — V8 Context handle to register.
    • contextGroupId (number) — Positive integer identifying the execution context group.
    • name (string) — Human-readable context name shown in DevTools.
  • dispose(): void

    Destroys the underlying V8Inspector, its client, and unregisters host callbacks.

InspectorSessionBridge

Active Chrome DevTools Protocol session returned by InspectorBridge.connect.

Wraps v8_inspector.V8InspectorSession and its associated V8Inspector.Channel.

new InspectorSessionBridge(sessionPtr: number, channelPtr: number, channelCbId: number)

Properties

  • readonly session: V8InspectorSession

    Underlying generated V8InspectorSession handle.

Methods

  • [dispose](): void

    Disposable protocol hook for using declarations.

  • dispatchProtocolMessage(jsonMessage: string): void

    Sends a JSON-encoded CDP command (e.g. {"id":1,"method":"Runtime.enable"}) to the V8 inspector session.

    • jsonMessage (string) — Serialized JSON CDP request payload.
  • dispose(): void

    Closes the CDP session, destroys its channel, and unregisters host callbacks.

Membrane

Bidirectional membrane marshaling values across the host JS and V8-wasm realm boundary.

  • Primitives (undefined, null, boolean, number, string, bigint, symbol) cross by value.
  • ArrayBuffer and ArrayBufferView instances are copied cleanly across linear memory.
  • Host functions are wrapped as V8 callbacks; guest functions become callable host functions.
  • Guest objects are exposed to the host as live Proxy objects (get, set, has, deleteProperty, ownKeys, getOwnPropertyDescriptor).
new Membrane(isolate: Isolate, contextGlobal: Global<Context>)

Creates a Membrane bound to a specific V8 Isolate and persistent Context.

  • isolate (Isolate) — Owning V8 Isolate.
  • contextGlobal (Global<Context>) — Persistent handle to the guest Context.

Methods

  • dispose(): void

    Resets all persistent V8 handles retained by this membrane.

  • extractThrown(ctx: Context, tc: TryCatch): unknown

    Converts a caught V8 exception from tc into a host Error (preserving name and message for guest error objects) or marshaled primitive.

    • ctx (Context) — Active guest Context.
    • tc (TryCatch) — TryCatch block that captured the exception.
  • toGuest(ctx: Context, value: unknown): Value

    Marshals a host JavaScript value into a guest V8 Value handle.

    Must be called inside an active HandleScope and ContextScope.

    Returns: Guest V8 Value handle.

    • ctx (Context) — Active guest V8 Context.
    • value (unknown) — Host value to marshal into the guest realm.
  • toHost(ctx: Context, val: Value): unknown

    Marshals a guest V8 Value handle to a host JavaScript value (primitives by value, ArrayBuffer by copy, functions as callable wrappers, and objects as live Proxy instances).

    Returns: Marshaled host value.

    • ctx (Context) — Active guest V8 Context.
    • val (Value) — Guest V8 Value handle to marshal.

Low-Level Wasm Memory & Bridge Helpers

getWasm

function getWasm(): V8WasmExports

Returns the currently active V8-wasm module exports.

Returns: The active V8WasmExports instance.

Throws: Error if initV8 or setWasmModule has not been called yet.

readStringView

function readStringView(ptr: number, len: number, isUtf8: boolean): string

Decodes a length-delimited UTF-8 or UTF-16LE string slice from Wasm linear memory (used for V8 strings and v8_inspector.StringView buffers).

Returns: Decoded JavaScript string (empty string if ptr === 0 or len === 0).

Parameters

  • ptr (number) — Linear-memory pointer to the character buffer.
  • len (number) — Number of bytes (when isUtf8 is true) or UTF-16 code units (when false).
  • isUtf8 (boolean) — true for UTF-8 bytes; false for UTF-16LE code units.

readUtf8Z

function readUtf8Z(ptr: number): string | null

Reads a null-terminated UTF-8 C string from Wasm linear memory.

Returns: Decoded JavaScript string, or null if ptr is 0.

Parameters

  • ptr (number) — Linear-memory pointer to the start of the string, or 0.

registerCallback

function registerCallback(cb: any): number

Registers a host JavaScript callback object or function in the global bridge table and returns a numeric handle ID that can be passed across the Wasm ABI boundary.

Returns: Unique positive callback ID.

Parameters

  • cb (any) — Host callback function or handler object to register.

setWasmModule

function setWasmModule(mod: V8WasmExports): void

Installs the active V8-wasm module instance and caches the shared linear-memory scratch buffer pointer and byte capacity.

Parameters

  • mod (V8WasmExports) — Instantiated V8-wasm Emscripten module exports.

unregisterCallback

function unregisterCallback(id: number): void

Removes a previously registered host callback ID from the global bridge table, allowing its closure to be garbage collected.

Parameters

  • id (number) — Callback ID returned by registerCallback.

withLocalArray

function withLocalArray<R>(handles: readonly WasmHandle[], fn: (ptr: number) => R): R

Temporarily packs an array of WasmHandle pointers into a contiguous uint32_t[] array in Wasm linear memory (matching v8::Local<T>* argument arrays) for the duration of fn.

Returns: The value returned by fn.

Parameters

  • handles (readonly WasmHandle[]) — Handles to pack into Wasm memory.
  • fn ((ptr: number) => R) — Callback receiving the base pointer (0 if handles is empty).

withUtf8Bytes

function withUtf8Bytes<R>(str: string, fn: (ptr: number, len: number) => R): R

Encodes a JavaScript string as UTF-8 bytes in Wasm linear memory for the duration of fn, passing both the byte pointer and exact byte length.

Uses the reusable scratch buffer when the encoded bytes fit; otherwise allocates and frees a temporary linear-memory buffer automatically.

Returns: The value returned by fn.

Parameters

  • str (string) — String to encode.
  • fn ((ptr: number, len: number) => R) — Callback receiving (ptr, byteLength) in Wasm linear memory.

withUtf8Z

function withUtf8Z<R>(str: string | null | undefined, fn: (ptr: number) => R): R

Encodes a JavaScript string as a null-terminated UTF-8 C string in Wasm linear memory for the duration of fn, using the reusable scratch buffer when it fits and falling back to temporary heap allocation otherwise.

Passing null or undefined forwards a null pointer (0).

Returns: The value returned by fn.

Parameters

  • str (string | null | undefined) — String to encode, or null/undefined for a null pointer.
  • fn ((ptr: number) => R) — Callback receiving the Wasm linear-memory pointer to the UTF-8 buffer.

Interfaces & Types

CreateIsolateOptions

Options for createIsolate.

interface CreateIsolateOptions {
  arrayBufferAllocator?: ArrayBufferAllocator;
}
  • arrayBufferAllocator — Custom ArrayBuffer.Allocator to attach to the isolate. If omitted, a default allocator is created and owned by the returned ManagedIsolate.

GuestRealmOptions

Configuration options for constructing a GuestRealm.

interface GuestRealmOptions {
  compileHook?: CompileHook;
  isolate?: Isolate;
}
  • compileHook — Optional source transform hook invoked before compilation.
  • isolate — Reuse an existing Isolate instead of creating a new dedicated Isolate.

InitV8Options

Configuration passed to initV8 to load or attach a V8-wasm module.

interface InitV8Options {
  emscriptenOptions?: Record<string, any>;
  module?: V8WasmExports | (opts?: Record<string, any>) => Promise<V8WasmExports>;
}
  • emscriptenOptions — Optional Emscripten module overrides (e.g. locateFile, wasmBinary).
  • module — Pre-loaded Emscripten module or modularized factory function () => Promise<Module>.

InspectorChannelHandlers

Host receiver callbacks for a Chrome DevTools Protocol (CDP) inspector channel, mirroring v8_inspector::V8Inspector::Channel.

interface InspectorChannelHandlers {
  flushProtocolNotifications?(): void;
  sendNotification(message: string): void;
  sendResponse(callId: number, message: string): void;
}
  • flushProtocolNotifications — Optional hook called when V8 flushes buffered protocol notifications.
  • sendNotification — Called by V8 with a JSON-encoded asynchronous CDP notification event.
  • sendResponse — Called by V8 with the JSON-encoded CDP response for command callId.

InspectorClientHandlers

Host callbacks implementing v8_inspector::V8InspectorClient pause-loop hooks.

interface InspectorClientHandlers {
  quitMessageLoopOnPause?(): void;
  runMessageLoopOnPause?(contextGroupId: number): void;
}
  • quitMessageLoopOnPause — Called when V8 resumes execution from a paused state.
  • runMessageLoopOnPause — Called when V8 pauses on a breakpoint or debugger statement in contextGroupId.

ManagedIsolate

Lifecycle wrapper returned by createIsolate that owns a v8.Isolate and (when auto-created) its ArrayBufferAllocator. Supports using disposal.

interface ManagedIsolate {
  allocator: ArrayBufferAllocator;
  isolate: Isolate;
  [dispose](): void;
  dispose(): void;
}
  • allocator — The ArrayBufferAllocator configured on the isolate.
  • isolate — The allocated V8 Isolate handle.
  • [dispose] — Disposable protocol hook for using declarations.
  • dispose — Disposes the Isolate and frees the default ArrayBufferAllocator (if owned). Idempotent.

ScriptOpts

Compilation metadata passed to GuestRealm.evalInRealm and GuestRealm.runScript.

interface ScriptOpts {
  type?: CompileType;
  url?: string;
}
  • type — Compilation mode ("classic" by default, or "module").
  • url — Source URL attached via v8.ScriptOrigin for stack traces and DevTools.

TypedFunctionCallbackInfo

Strongly typed wrapper around FunctionCallbackInfo passed to host functions created with createFunction and createFunctionTemplate.

interface TypedFunctionCallbackInfo {
  readonly raw: FunctionCallbackInfo;
  get(index: number): Value;
  getIsolate(): Isolate;
  getReturnValue(): ReturnValue;
  isConstructCall(): boolean;
  length(): number;
  newTarget(): Value;
  thisObject(): V8Object;
}
  • raw — Underlying raw FunctionCallbackInfo pointer wrapper.
  • get — Returns the index-th argument as a Value (or undefined if out of bounds).
  • getIsolate — Returns the calling V8 Isolate.
  • getReturnValue — Returns the ReturnValue handle used to set the JS return value.
  • isConstructCall — Returns true if invoked via new.
  • length — Number of JavaScript arguments passed to the call.
  • newTarget — Returns new.target (or undefined for non-constructor calls).
  • thisObject — Returns the this receiver object for the invocation.

V8WasmExports

Interface representing the instantiated Emscripten Wasm module exports produced by the V8-wasm API build (v8_wasm_api.mjs).

interface V8WasmExports {
  HEAPU32: Uint32Array;
  HEAPU8: Uint8Array;
  memory?: Memory;
}
  • HEAPU32 — Unsigned 32-bit view over the Wasm linear memory heap.
  • HEAPU8 — Unsigned 8-bit view over the Wasm linear memory heap.
  • memory — Underlying WebAssembly linear memory, if exposed separately from typed views.

CompileHook

type CompileHook = (source: string, type: CompileType, next: (source: string) => string) => string;

Optional source transformation hook invoked before guest JavaScript is compiled.

CompileType

type CompileType = "classic" | "module";

Script compilation mode for GuestRealm.evalInRealm and GuestRealm.runScript.

HostFunctionCallback

type HostFunctionCallback = (info: TypedFunctionCallbackInfo) => void;

Callback signature for host TypeScript functions exposed into V8 via createFunction or createFunctionTemplate.

Any exception thrown by the callback is automatically caught and rethrown into V8 as a v8.Exception.error(...).

v8 Namespace Export

Idiomatic v8 namespace matching V8's C++ class names with zero JS global collisions.

Re-exports every generated V8 class and enum, mapping JS-global collisions (V8Object -> v8.Object, V8String -> v8.String, V8Function -> v8.Function, V8Array -> v8.Array, V8Number -> v8.Number, V8Boolean -> v8.Boolean, V8Symbol -> v8.Symbol, V8BigInt -> v8.BigInt, V8Date -> v8.Date, V8RegExp -> v8.RegExp, V8Map -> v8.Map, V8Set -> v8.Set, V8Promise -> v8.Promise, V8Proxy -> v8.Proxy, V8ArrayBuffer -> v8.ArrayBuffer, V8SharedArrayBuffer -> v8.SharedArrayBuffer, V8DataView -> v8.DataView, V8JSON -> v8.JSON).

On this page