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): ContextCreates 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 V8Isolate.globalTemplate(ObjectTemplate) — OptionalObjectTemplatedescribing the context's global object.globalObject(Value) — Optional existing global object to reuse.
createDefaultPlatform
function createDefaultPlatform(threadPoolSize?: number): PlatformCreates 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 (0selects V8's default concurrency).
createIsolate
function createIsolate(options?: CreateIsolateOptions): ManagedIsolateAllocates 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(): PlatformCreates 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): voidDestroys 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): voidNotifies platform that isolate is shutting down so queued background work
for that isolate can be cancelled, mirroring v8::platform::NotifyIsolateShutdown().
Parameters
platform(Platform) — Active V8Platform.isolate(Isolate) —Isolatebeing shut down.
pumpMessageLoop
function pumpMessageLoop(platform: Platform, isolate: Isolate, waitForWork?: boolean): booleanRuns 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 V8Platform.isolate(Isolate) — TargetIsolatewhose foreground task queue should be pumped.waitForWork(boolean) — Whentrue, blocks until at least one task is available (defaultfalse).
runIdleTasks
function runIdleTasks(platform: Platform, isolate: Isolate, idleTimeSeconds: number): voidRuns pending idle tasks for isolate up to the given time budget,
mirroring v8::platform::RunIdleTasks().
Parameters
platform(Platform) — Active V8Platform.isolate(Isolate) — TargetIsolate.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) — CreationContext.isolate(Isolate) — Owning V8Isolate.callback(HostFunctionCallback) — Host callback invoked when JavaScript calls the function.length(number) — ReportedFunction.prototype.lengthvalue (default0).
createFunctionTemplate
function createFunctionTemplate(isolate: Isolate, callback?: HostFunctionCallback, signature?: Signature, length?: number): FunctionTemplateCreates a V8 FunctionTemplate bound to an optional host TypeScript callback,
mirroring v8::FunctionTemplate::New().
Returns: FunctionTemplate local handle.
Parameters
isolate(Isolate) — Target V8Isolate.callback(HostFunctionCallback) — Optional host function invoked when instantiated functions are called.signature(Signature) — OptionalSignatureenforcing receiver type checks.length(number) — ReportedFunction.prototype.lengthvalue (default0).
createGuestRealm
function createGuestRealm(options?: GuestRealmOptions): GuestRealmFactory helper that creates a new GuestRealm.
Parameters
options(GuestRealmOptions) — Optional sharedIsolateand pre-compile source transform hook.
getBackingStoreBytes
function getBackingStoreBytes(bsShared: SharedHandle): Uint8ArrayReturns 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 V8BackingStore.
getTryCatchException
function getTryCatchException(tc: TryCatch): ValueReturns the caught JavaScript exception from a TryCatch block as a typed Value.
Parameters
tc(TryCatch) — ActiveTryCatchinstance withtc.hasCaught() === true.
getTryCatchMessage
function getTryCatchMessage(tc: TryCatch): MessageReturns the diagnostic Message (source line, column, resource name, stack frames)
associated with a caught exception in tc.
Parameters
tc(TryCatch) — ActiveTryCatchinstance.
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) — ActiveTryCatchinstance.ctx(Context) —Contextused to format the stack trace.
serializeHeapSnapshot
function serializeHeapSnapshot(snapshot: HeapSnapshot): stringSerializes 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) —HeapSnapshothandle 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 V8Isolate.text(string) — Host string to copy into V8.type(NewStringType) — String allocation type (NewStringType.kNormalorNewStringType.kInternalized).
stringFromUtf8Checked
function stringFromUtf8Checked(isolate: Isolate, text: string, type?: NewStringType): V8StringConvenience wrapper around stringFromUtf8 that unwraps via .toLocalChecked().
Returns: Non-empty V8String handle.
Parameters
isolate(Isolate) — Target V8Isolate.text(string) — Host string to copy into V8.type(NewStringType) — String allocation type (defaultNewStringType.kNormal).
stringToUtf8
function stringToUtf8(isolate: Isolate, str: V8String): stringCopies 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 V8Isolate.str(V8String) — V8 string handle to decode.
v8False
function v8False(isolate: Isolate): V8BooleanReturns the V8 false boolean singleton for isolate, mirroring v8::False(isolate).
v8Null
function v8Null(isolate: Isolate): PrimitiveReturns the V8 null primitive singleton for isolate, mirroring v8::Null(isolate).
v8True
function v8True(isolate: Isolate): V8BooleanReturns the V8 true boolean singleton for isolate, mirroring v8::True(isolate).
v8Undefined
function v8Undefined(isolate: Isolate): PrimitiveReturns 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](): voidDisposable protocol hook for
usingdeclarations. -
dispose(): voidExits the entered context.
Throws:
RangeErrorif 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](): voidDisposable protocol hook for
usingdeclarations. -
dispose(): voidExits this
EscapableHandleScope, freeing all non-escaped handles.Throws:
RangeErrorif disposed out of LIFO order. -
escape<T extends WasmHandle>(value: T, ctor?: (ptr: number) => T): TPromotes
valueinto the enclosing handle scope so it remains valid after this scope is disposed. Can be called at most once perEscapableHandleScope.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 tovalue.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): RExecutes
fninside a freshly createdHandleScopeand guarantees LIFO disposal in afinallyblock.Returns: The value returned by
fn.isolate(WasmHandle) — Active V8Isolate.fn((scope: HandleScope) => R) — Callback executed within the handle scope.
Methods
-
[dispose](): voidDisposable protocol hook for
usingdeclarations. -
dispose(): voidExits this
HandleScopeand frees all local handles allocated within it.Throws:
RangeErrorif 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](): voidDisposable protocol hook for
usingdeclarations. -
dispose(): voidExits the entered isolate.
Throws:
RangeErrorif 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](): voidDisposable protocol hook for
usingdeclarations. -
dispose(): voidReleases the isolate lock.
Throws:
RangeErrorif 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](): voidDisposable protocol hook for
usingdeclarations. -
dispose(): voidExits this
SealHandleScope.Throws:
RangeErrorif 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](): voidDisposable protocol hook for
usingdeclarations. -
canContinue(): booleanReturns
trueif execution can safely continue in V8 (returnsfalsefor uncatchable exceptions such asIsolate.terminateExecution()). -
dispose(): voidExits and destroys this
TryCatchhandler.Throws:
RangeErrorif disposed out of LIFO order. -
exceptionPtr(): numberReturns the raw handle pointer to the caught exception
Value(0if none). -
hasCaught(): booleanReturns
trueif an exception has been caught by thisTryCatchblock. -
hasTerminated(): booleanReturns
trueif execution was terminated viaIsolate.terminateExecution(). -
messagePtr(): numberReturns the raw handle pointer to the associated
v8.Message(0if none). -
reset(): voidClears any caught exception state so this
TryCatchcan be reused. -
reThrowPtr(): numberRethrows the caught exception to an outer
TryCatchhandler, returning the raw handle pointer. -
setCaptureMessage(value: boolean): voidControls whether a
v8.Messageobject is captured for caught exceptions. -
setVerbose(value: boolean): voidControls whether caught exceptions are also reported to the isolate's message listeners (verbose mode).
-
stackTracePtr(context: WasmHandle): numberReturns the raw
MaybeLocal<Value>handle pointer to the exception's stack trace string incontext(0if 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](): voidDisposable protocol hook for
usingdeclarations. -
dispose(): voidRe-acquires the isolate lock.
Throws:
RangeErrorif 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): numberReturns the raw
Local<Value>handle pointer for argumentindex(orundefinedif out of range). -
getReturnValue(): ReturnValueReturns the
ReturnValueobject used to set the callback's JS return value. -
isConstructCall(): booleanReturns
trueif the function was invoked as a constructor (new fn(...)). -
isolatePtr(): numberReturns the raw pointer to the calling
v8::Isolate. -
length(): numberReturns the number of arguments passed by JavaScript.
-
newTargetPtr(): numberReturns the raw
Local<Value>handle pointer fornew.target. -
thisPtr(): numberReturns the raw
Local<Object>handle pointer for thethisreceiver.
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 V8Isolate.local(T) — Local handle to persist.ctor((ptr: number) => T) — Optional constructor forget(defaults tolocal.constructor).
Methods
-
[dispose](): voidDisposable protocol hook for
usingdeclarations. -
clearWeak(): voidRestores this handle from weak back to strong and unregisters any weak callback.
-
dispose(): voidAlias for
reset. -
get(isolate: WasmHandle): TMaterializes a fresh
Localhandle in the currently activeHandleScope.isolate(WasmHandle) — Owning V8Isolate.
-
isEmpty(): booleanReturns
trueif this persistent handle has been reset or is empty. -
isWeak(): booleanReturns
trueif this handle is currently weak. -
reset(): voidReleases the persistent handle and any registered weak callback. Safe to call repeatedly.
-
setWeak(callback: () => void, type?: number): voidMarks this persistent handle as weak so V8's garbage collector may reclaim the referenced object when no strong references remain, invoking
callbackupon collection.callback(() => void) — Finalizer invoked when the referent is collected.type(number) — OptionalWeakCallbackTypeenum value (default0).
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>containingvalue. -
static nothing<T>(): Maybe<T>Constructs an empty (
Nothing)Maybe<T>.
Methods
-
fromJust(): TReturns the contained value, throwing an
Errorif thisMaybeisNothing.Mirrors C++
v8::Maybe<T>::FromJust().Throws:
ErrorwhenisNothing()istrue. -
fromMaybe(defaultValue: T): TReturns the contained value if
isJust(), otherwise returnsdefaultValue.defaultValue(T) — Fallback value returned whenNothing.
-
isJust(): booleanReturns
trueif thisMaybeholds a value. -
isNothing(): booleanReturns
trueif thisMaybeis empty (Nothing). -
toChecked(): TAlias 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 (0for empty).ctor((ptr: number) => T) — Constructor used to materialize the typed handle when non-empty.
Properties
-
readonly ptr: numberRaw handle bits (
0when empty).
Methods
-
fromMaybe(defaultValue: T): TReturns the contained handle if non-empty, otherwise returns
defaultValue.defaultValue(T) — Fallback handle returned when empty.
-
isEmpty(): booleanReturns
trueif thisMaybeLocalis empty (e.g., an exception was thrown). -
toLocal(): T | nullConverts this
MaybeLocal<T>toTif non-empty, ornullif empty. -
toLocalChecked(): TExtracts the underlying
Thandle, throwing anErrorif thisMaybeLocalis empty.Mirrors C++
v8::MaybeLocal<T>::ToLocalChecked().Throws:
ErrorwhenisEmpty()istrue.
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): voidSets the callback return value to a V8
Valuehandle. -
setBoolean(value: boolean): voidSets the callback return value to a JavaScript boolean primitive.
-
setInt32(value: number): voidSets the callback return value to a 32-bit signed integer.
-
setNull(): voidSets the callback return value to JavaScript
null. -
setNumber(value: number): voidSets the callback return value to an IEEE-754 double-precision number.
-
setUndefined(): voidSets 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](): voidDisposable protocol hook for
usingdeclarations. -
dispose(): voidReleases the underlying C++
std.shared_ptrreference. 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 (0represents null/empty).
Properties
-
readonly ptr: numberRaw unsigned 32-bit pointer or handle bits in V8-wasm linear memory.
Static Methods
-
static fromPtr(ptr: number): WasmHandleWraps 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): TReinterprets this handle as a more specific
WasmHandlesubclass without performing a runtime type check (caller should verify with V8is*()predicates first).Returns: A new wrapper instance pointing to the same underlying V8 handle.
ctor((ptr: number) => T) — TargetWasmHandlesubclass constructor (e.g.,v8.String,v8.Object).
-
isNull(): booleanReturns
trueif 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: IsolateV8
Isolatehosting this realm (either owned or shared viaoptions.isolate). -
readonly membrane: MembraneBidirectional
Membranemarshaling values in and out of this realm.
Methods
-
[dispose](): voidDisposable protocol hook for
usingdeclarations. -
defineGlobal(name: string, value: unknown): voidDefines a property on the guest realm's
globalThisobject, marshalingvalueacross theMembraneinto V8.name(string) — Global property name in the guest realm.value(unknown) — Host value (primitive, function, object,ArrayBuffer, etc.) to expose.
-
dispose(): voidDisposes the membrane, releases the guest
Context, and disposes theIsolateif owned. -
evalInRealm(source: string, opts?: ScriptOpts): unknownCompiles and executes
sourceinside the guest V8 realm and marshals the completion value back across theMembrane.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): unknownAlias 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 V8Isolateto inspect.clientHandlers(InspectorClientHandlers) — Optional pause-loop hooks for breakpoint handling.
Properties
-
readonly inspector: V8InspectorUnderlying generated
V8Inspectorhandle.
Methods
-
[dispose](): voidDisposable protocol hook for
usingdeclarations. -
connect(contextGroupId: number, handlers: InspectorChannelHandlers, trustLevel?: V8InspectorClientTrustLevel): InspectorSessionBridgeOpens a new CDP
InspectorSessionBridgeattached tocontextGroupId, mirroringv8_inspector::V8Inspector::connect().Returns: A disposable
InspectorSessionBridge.contextGroupId(number) — Context group ID previously passed tocontextCreated.handlers(InspectorChannelHandlers) — Callbacks receiving CDP responses and notifications.trustLevel(V8InspectorClientTrustLevel) — Client trust level (defaults toV8InspectorClientTrustLevel.kFullyTrusted).
-
contextCreated(context: Context, contextGroupId: number, name: string): voidNotifies the inspector that a new
Contextis available for inspection, mirroringv8_inspector::V8Inspector::contextCreated().context(Context) — V8Contexthandle to register.contextGroupId(number) — Positive integer identifying the execution context group.name(string) — Human-readable context name shown in DevTools.
-
dispose(): voidDestroys 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: V8InspectorSessionUnderlying generated
V8InspectorSessionhandle.
Methods
-
[dispose](): voidDisposable protocol hook for
usingdeclarations. -
dispatchProtocolMessage(jsonMessage: string): voidSends 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(): voidCloses 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. ArrayBufferandArrayBufferViewinstances 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
Proxyobjects (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 V8Isolate.contextGlobal(Global<Context>) — Persistent handle to the guestContext.
Methods
-
dispose(): voidResets all persistent V8 handles retained by this membrane.
-
extractThrown(ctx: Context, tc: TryCatch): unknownConverts a caught V8 exception from
tcinto a hostError(preservingnameandmessagefor guest error objects) or marshaled primitive.ctx(Context) — Active guestContext.tc(TryCatch) —TryCatchblock that captured the exception.
-
toGuest(ctx: Context, value: unknown): ValueMarshals a host JavaScript value into a guest V8
Valuehandle.Must be called inside an active
HandleScopeandContextScope.Returns: Guest V8
Valuehandle.ctx(Context) — Active guest V8Context.value(unknown) — Host value to marshal into the guest realm.
-
toHost(ctx: Context, val: Value): unknownMarshals a guest V8
Valuehandle to a host JavaScript value (primitives by value,ArrayBufferby copy, functions as callable wrappers, and objects as liveProxyinstances).Returns: Marshaled host value.
ctx(Context) — Active guest V8Context.val(Value) — Guest V8Valuehandle to marshal.
Low-Level Wasm Memory & Bridge Helpers
getWasm
function getWasm(): V8WasmExportsReturns 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): stringDecodes 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 (whenisUtf8istrue) or UTF-16 code units (whenfalse).isUtf8(boolean) —truefor UTF-8 bytes;falsefor UTF-16LE code units.
readUtf8Z
function readUtf8Z(ptr: number): string | nullReads 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, or0.
registerCallback
function registerCallback(cb: any): numberRegisters 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): voidInstalls 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): voidRemoves a previously registered host callback ID from the global bridge table, allowing its closure to be garbage collected.
Parameters
id(number) — Callback ID returned byregisterCallback.
withLocalArray
function withLocalArray<R>(handles: readonly WasmHandle[], fn: (ptr: number) => R): RTemporarily 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 (0ifhandlesis empty).
withUtf8Bytes
function withUtf8Bytes<R>(str: string, fn: (ptr: number, len: number) => R): REncodes 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): REncodes 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, ornull/undefinedfor 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— CustomArrayBuffer.Allocatorto attach to the isolate. If omitted, a default allocator is created and owned by the returnedManagedIsolate.
GuestRealmOptions
Configuration options for constructing a GuestRealm.
interface GuestRealmOptions {
compileHook?: CompileHook;
isolate?: Isolate;
}compileHook— Optional source transform hook invoked before compilation.isolate— Reuse an existingIsolateinstead of creating a new dedicatedIsolate.
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 commandcallId.
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 ordebuggerstatement incontextGroupId.
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— TheArrayBufferAllocatorconfigured on the isolate.isolate— The allocated V8Isolatehandle.[dispose]— Disposable protocol hook forusingdeclarations.dispose— Disposes theIsolateand frees the defaultArrayBufferAllocator(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 viav8.ScriptOriginfor 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 rawFunctionCallbackInfopointer wrapper.get— Returns theindex-th argument as aValue(orundefinedif out of bounds).getIsolate— Returns the calling V8Isolate.getReturnValue— Returns theReturnValuehandle used to set the JS return value.isConstructCall— Returnstrueif invoked vianew.length— Number of JavaScript arguments passed to the call.newTarget— Returnsnew.target(orundefinedfor non-constructor calls).thisObject— Returns thethisreceiver 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).