v8go

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 25, 2026 License: BSD-3-Clause Imports: 14 Imported by: 0

README ¶

v8go — Execute JavaScript from Go

Go Reference

A Go binding to the V8 JavaScript engine. Run JavaScript, expose Go functions to JS, and exchange data between Go and V8 with zero serialization overhead.

Install

go get github.com/iquirino/v8go

Prebuilt V8 static libraries are included for Linux and macOS (amd64/arm64) and Android.


Quick Start

package main

import (
    "fmt"
    v8 "github.com/iquirino/v8go"
)

func main() {
    ctx := v8.NewContext()
    defer ctx.Isolate().Dispose()
    defer ctx.Close()

    val, err := ctx.RunScript(`"Hello from V8!"`, "hello.js")
    if err != nil {
        panic(err)
    }
    fmt.Println(val.String()) // Hello from V8!
}

Core Concepts

Isolate (VM instance)

Think of an Isolate as a completely independent JavaScript universe. It has its own heap, garbage collector, and JIT compiler. Two Isolates share nothing — they can't see each other's variables, objects, or functions. This is the strongest isolation boundary V8 offers. One Isolate = one thread at a time (V8 is not thread-safe within a single Isolate).

iso := v8.NewIsolate()
defer iso.Dispose()
Context (execution environment)

A Context is a global scope within an Isolate. Think of it as a separate "tab" — it has its own global object, its own variables, but shares the underlying VM (JIT cache, GC) with other Contexts in the same Isolate. Contexts are cheap to create compared to Isolates.

ctx := v8.NewContext(iso)
defer ctx.Close()
One Isolate, many Contexts

Use this when you need multiple independent scopes but want to save memory. Each Context gets its own global object, so variables defined in one are invisible to another.

iso := v8.NewIsolate()
defer iso.Dispose()

ctx1 := v8.NewContext(iso)
ctx1.RunScript("var x = 1", "")

ctx2 := v8.NewContext(iso) // separate global scope
_, err := ctx2.RunScript("x", "") // ReferenceError: x is not defined

Lifecycle & Cleanup

Critical: V8 resources are NOT garbage collected by Go. You MUST explicitly dispose them or they'll leak.

// Always follow this pattern:
iso := v8.NewIsolate()
defer iso.Dispose()       // frees the entire VM + heap

ctx := v8.NewContext(iso)
defer ctx.Close()         // frees the context + all tracked values

// If you created a context without an explicit isolate:
ctx := v8.NewContext()
defer ctx.Isolate().Dispose() // don't forget the implicit isolate!
defer ctx.Close()

Order matters: Close contexts before disposing their isolate.


Running Scripts

Basic execution
val, err := ctx.RunScript(`1 + 2`, "math.js")
fmt.Println(val.String()) // "3"
🆕 Execution with timeout
val, err := ctx.RunScriptWithTimeout(`while(true){}`, "loop.js", 100*time.Millisecond)
if errors.Is(err, v8.ErrScriptTimeout) {
    fmt.Println("Script timed out")
}
Terminate long-running scripts manually
go func() {
    time.Sleep(200 * time.Millisecond)
    iso.TerminateExecution()
}()
val, err := ctx.RunScript(longScript, "slow.js")
// err: "ExecutionTerminated: script execution has been terminated"

Values

Creating values from Go
iso := v8.NewIsolate()

strVal, _ := v8.NewValue(iso, "hello")         // string
intVal, _ := v8.NewValue(iso, int32(42))        // int32
numVal, _ := v8.NewValue(iso, float64(3.14))    // float64
boolVal, _ := v8.NewValue(iso, true)            // bool
bigVal, _ := v8.NewValue(iso, big.NewInt(9999)) // BigInt
Type checking
val.IsString()    // true/false
val.IsNumber()
val.IsObject()
val.IsArray()
val.IsPromise()
val.IsDate()
val.IsRegExp()
// ... 40+ type checks available
🆕 Error-aware string conversion
s, err := val.StringErr() // returns error if conversion fails (e.g., Symbol coercion)
s := val.String()         // same but returns "" on failure (for fmt.Stringer compat)

Objects

Get and set properties
obj := ctx.Global()
obj.Set("version", "2.0.0")

val, _ := obj.Get("version")
fmt.Println(val.String()) // "2.0.0"

obj.Has("version")    // true
obj.Delete("version") // removes it
🆕 Property enumeration
val, _ := ctx.RunScript(`({name: "Alice", age: 30})`, "")
obj, _ := val.AsObject()

names, _ := obj.GetPropertyNames()       // includes prototype chain
ownNames, _ := obj.GetOwnPropertyNames() // own only

for i := 0; i < ownNames.Length(); i++ {
    key, _ := ownNames.GetIdx(uint32(i))
    fmt.Println(key.String())
}
🆕 Define properties with attributes
propVal, _ := v8.NewValue(iso, "immutable")
obj.DefineOwnProperty("locked", propVal, v8.ReadOnly|v8.DontDelete)
🆕 Private properties (invisible to JS)
obj.SetPrivate("internal_id", "abc123")
val, _ := obj.GetPrivate("internal_id") // "abc123"
obj.HasPrivate("internal_id")           // true

// JS cannot see it:
// Object.keys(obj)                    → doesn't include "internal_id"
// Object.getOwnPropertySymbols(obj)   → doesn't include it either

🆕 Arrays

arr, _ := v8.NewArray(ctx, 0)

v1, _ := v8.NewValue(iso, "hello")
v2, _ := v8.NewValue(iso, "world")

arr.Push(v1, v2)          // returns new length: 2
arr.Length()              // 2
val, _ := arr.Get(0)     // "hello"
arr.Pop()                 // removes and returns "world"
arr.Shift()               // removes and returns "hello"
arr.Unshift(v1)           // prepend, returns new length
arr.Includes(v1)          // true
arr.IndexOf(v1)           // 0

// Cast from Value:
val, _ = ctx.RunScript(`[1, 2, 3]`, "")
arr, _ = val.AsArray()

🆕 Dates

date, _ := v8.NewDate(ctx, time.Now())

t := date.Time()                // Go time.Time
iso, _ := date.ToISOString()    // "2024-06-15T10:30:00.000Z"
year, _ := date.GetFullYear()   // 2024
month, _ := date.GetMonth()     // 5 (0-indexed)
ms, _ := date.GetTime()         // Unix milliseconds

// Cast from Value:
val, _ = ctx.RunScript(`new Date()`, "")
d, _ := val.AsDate()

🆕 Map and Set

Map
m, _ := v8.NewMap(ctx)

key, _ := v8.NewValue(iso, "name")
val, _ := v8.NewValue(iso, "Alice")

m.MapSet(key, val)
m.MapSize()          // 1
m.MapHas(key)        // true
got, _ := m.MapGet(key) // "Alice"
m.MapDelete(key)
Set
s, _ := v8.NewSet(ctx)

val, _ := v8.NewValue(iso, "item")
s.SetAdd(val)
s.SetSize()    // 1
s.SetHas(val)  // true
s.SetDelete(val)

🆕 RegExp

re, _ := v8.NewRegExp(ctx, `\d+`, v8.RegExpGlobal|v8.RegExpIgnoreCase)

src, _ := re.Source() // `\d+`
flags, _ := re.Flags() // "gi"

str, _ := v8.NewValue(iso, "abc 123 def")
matched, _ := re.Test(str) // true

🆕 Binary Data (ArrayBuffer / TypedArray)

When to use this instead of JSON? If you're passing binary data (images, protobuf, crypto buffers) or large numeric arrays between Go and JS, ArrayBuffers avoid the serialize→parse round-trip entirely. The byte slice you get back points directly into V8's heap — zero copy. For structured objects (maps, nested structs), JSON is still the simplest path.

Create from Go bytes
data := []byte{0x48, 0x65, 0x6C, 0x6C, 0x6F}

// ArrayBuffer
buf, _ := v8.NewArrayBufferFromBytes(ctx, data)

// Uint8Array (JS can index it directly: arr[0], arr[1], etc.)
arr, _ := v8.NewUint8ArrayFromBytes(ctx, data)
Read V8 buffer into Go
val, _ := ctx.RunScript(`new ArrayBuffer(1024)`, "")
bytes, release, _ := val.ArrayBufferGetContents()
defer release()
// bytes is a []byte backed by V8 memory — zero copy!

// SharedArrayBuffer works too:
val2, _ := ctx.RunScript(`new SharedArrayBuffer(1024)`, "")
bytes2, release2, _ := val2.SharedArrayBufferGetContents()
defer release2()

Functions

Go function exposed to JS
printFn := v8.NewFunctionTemplate(iso, func(info *v8.FunctionCallbackInfo) *v8.Value {
    fmt.Println(info.Args()[0].String())
    return nil
})
global := v8.NewObjectTemplate(iso)
global.Set("print", printFn)

ctx := v8.NewContext(iso, global)
ctx.RunScript(`print("Hello from JS!")`, "")
Go function with error handling
fn := v8.NewFunctionTemplateWithError(iso, func(info *v8.FunctionCallbackInfo) (*v8.Value, error) {
    if len(info.Args()) == 0 {
        return nil, fmt.Errorf("argument required")
    }
    return info.Args()[0], nil
})
// If error is returned, it's thrown as a JS exception
🆕 Get function from template (returns error instead of panicking)
fn, err := tmpl.GetFunction(ctx)
if err != nil {
    // handle template instantiation error
}
result, err := fn.Call(v8.Undefined(iso), arg1, arg2)

Promises

What are microtasks? In a browser or Node.js, Promise callbacks (.then, .catch, async/await continuations) don't execute immediately — they go into a "microtask queue" that runs after the current script finishes. In v8go, there's no event loop running automatically. You must explicitly tell V8 to process the queue by calling ctx.PerformMicrotaskCheckpoint(). Without this call, your Promise callbacks will never fire.

resolver, _ := v8.NewPromiseResolver(ctx)
promise := resolver.GetPromise()

// Resolve from Go:
val, _ := v8.NewValue(iso, "done")
resolver.Resolve(val)

// IMPORTANT: Without this, .Then callbacks won't run!
ctx.PerformMicrotaskCheckpoint()

fmt.Println(promise.State())           // Fulfilled
fmt.Println(promise.Result().String()) // "done"
🆕 Then/Catch (returns error instead of panicking)
p, err := promise.Then(func(info *v8.FunctionCallbackInfo) *v8.Value {
    fmt.Println("Resolved:", info.Args()[0].String())
    return nil
})
if err != nil {
    // handle error
}
ctx.PerformMicrotaskCheckpoint()
🆕 Microtask policy control

By default, V8 runs microtasks (Promise callbacks) automatically after each script completes. If you want full control — for example, to batch multiple operations before resolving promises — switch to explicit mode.

// Explicit: YOU decide when promises resolve
iso.SetMicrotasksPolicy(v8.MicrotasksExplicit)

ctx.RunScript(`fetch('/api').then(r => console.log(r))`, "") // .then won't fire yet!
// ... do other work ...
ctx.PerformMicrotaskCheckpoint() // NOW all pending .then/.catch callbacks run

// Auto (default): promises resolve immediately after each RunScript
iso.SetMicrotasksPolicy(v8.MicrotasksAuto)

Error Handling

JavaScript errors
_, err := ctx.RunScript(`throw new TypeError("oops")`, "err.js")
if err != nil {
    jsErr := err.(*v8.JSError)
    fmt.Println(jsErr.Message)    // "TypeError: oops"
    fmt.Println(jsErr.Location)   // "err.js:1:1"
    fmt.Println(jsErr.StackTrace) // full stack trace
}
🆕 Exception value propagation
_, err := ctx.RunScript(`throw new TypeError("oops")`, "")
jsErr := err.(*v8.JSError)

// Access the original V8 error object:
fmt.Println(jsErr.Value.IsNativeError()) // true
fmt.Println(jsErr.Value.String())        // "TypeError: oops"

// Rethrow in a callback:
iso.ThrowException(jsErr.Value)

Modules (ES Modules)

Important: V8 is not Node.js. There's no require(), no module.exports, no CommonJS. If you're loading code that uses exports or require, it won't work — that's Node.js syntax, not JavaScript. V8 only supports ES Modules (import/export). If you need CommonJS compat, prepend a shim: var exports = {}; var module = {exports};

mod, err := v8.CompileModule(iso, `export const x = 42;`, "module.js")
if err != nil {
    panic(err)
}
err = mod.InstantiateModule(ctx, resolver)
val, err := mod.Evaluate(ctx)

Resource Limits

Memory limits

V8 can consume unbounded memory if scripts allocate without limit. WithResourceConstraints sets a hard ceiling. When the limit is approached, V8 calls a near-heap-limit callback that terminates execution — your RunScript call returns an error instead of the process being OOM-killed.

iso := v8.NewIsolate(v8.WithResourceConstraints(0, 50*1024*1024)) // max 50MB
// V8 calls TerminateExecution when limit is hit
🆕 Security tokens (multi-context isolation)

When would you use this? If you run multiple tenants' code in separate Contexts on the same Isolate (to save memory), security tokens prevent one Context from accessing another's globals through shared prototype chains. If you use one Isolate per tenant, you don't need this — Isolates are already fully isolated.

token, _ := v8.NewValue(iso, "tenant-A")
ctx.SetSecurityToken(token) // prevents cross-context access within same isolate

Pre-compiled Scripts (Code Cache)

Why use this? Parsing and compiling JavaScript has a real cost (especially for large scripts). If you run the same source code repeatedly in different contexts, you can compile it once and reuse the compiled bytecode. This skips the parsing+compilation step on subsequent runs — typically saving 20-40% of the first execution time.

source := "const add = (a, b) => a + b"
script, _ := iso.CompileUnboundScript(source, "math.js", v8.CompileOptions{Mode: v8.CompileModeEager})
cache := script.CreateCodeCache()

// Later, in a new isolate:
script2, _ := iso2.CompileUnboundScript(source, "math.js", v8.CompileOptions{CachedData: cache})
val, _ := script2.Run(ctx2)

CPU Profiler

profiler := v8.NewCPUProfiler(iso)
profiler.StartProfiling("my-profile")

ctx.RunScript(code, "app.js")

profile := profiler.StopProfiling("my-profile")
root := profile.GetTopDownRoot()
// Walk the call tree...

🆕 Leak Detection (build tag)

Why? If you create Isolates or Contexts without properly calling Dispose()/Close(), they leak V8 heap memory (each Isolate reserves ~4GB of virtual address space). This profiling integration lets you catch leaks using Go's standard pprof tooling.

Build with -tags v8go_profiling to enable pprof-based tracking of Isolate and Context creation/disposal:

// With the build tag active:
// pprof.Lookup("v8go.isolate") tracks live isolates
// pprof.Lookup("v8go.context") tracks live contexts

// Example: check for leaks in tests
import "runtime/pprof"

func TestNoLeaks(t *testing.T) {
    // ... create and dispose isolates/contexts ...

    if n := pprof.Lookup("v8go.isolate").Count(); n != 0 {
        t.Errorf("leaked %d isolates", n)
    }
}

Inspector (Console API)

type MyHandler struct{}
func (h *MyHandler) ConsoleAPIMessage(msg v8.ConsoleAPIMessage) {
    fmt.Printf("[%d] %s\n", msg.ErrorLevel, msg.Message)
}

client := v8.NewInspectorClient(&MyHandler{})
inspector := v8.NewInspector(iso, client)
inspector.ContextCreated(ctx)

ctx.RunScript(`console.log("hello")`, "") // triggers handler

Build Configuration

V8 is built with these GN flags (see deps/build.py):

Flag Value Purpose
v8_enable_sandbox false Disabled — requires libc++ hardening which conflicts with Go's CGo linking
v8_enable_pointer_compression true 🆕 ~50% heap memory reduction
v8_enable_maglev true 🆕 Mid-tier JIT for faster warmup
v8_enable_short_builtin_calls true 🆕 Shorter x64 call sequences
v8_enable_webassembly false 🆕 Reduced attack surface
v8_monolithic true Single static archive
v8_enable_i18n_support true Full Intl API support

v1 — Breaking Changes

These methods changed signatures to return errors instead of panicking:

Method Before After
Value.Object() *Object (*Object, error)
FunctionTemplate.GetFunction(ctx) *Function (*Function, error)
Promise.Then(cbs...) *Promise (*Promise, error)
Promise.Catch(cb) *Promise (*Promise, error)
Promise.ThenWithError(cbs...) *Promise (*Promise, error)
Promise.CatchWithError(cb) *Promise (*Promise, error)

Migration: Add , err to the left side of these calls and handle the error.

// Before:
fn := tmpl.GetFunction(ctx)
prom.Then(callback)

// After:
fn, err := tmpl.GetFunction(ctx)
_, err = prom.Then(callback)

v1 — New Features

Feature Description
Context.RunScriptWithTimeout Execute JS with a deadline — returns ErrScriptTimeout on expiry
Value.StringErr() String conversion that reports errors instead of returning empty
Value.AsArray(), Value.AsDate(), Value.AsMap(), Value.AsSet() Type-safe casting
NewArray, Array.Push/Pop/Shift/Unshift/Includes/IndexOf Full Array API
NewDate, Date.Time(), Date.ToISOString(), Date.GetFullYear() Date ↔ time.Time
NewMap, Map.MapGet/MapSet/MapHas/MapDelete/MapSize Native Map without eval
NewSet, Set.SetAdd/SetHas/SetDelete/SetSize Native Set without eval
NewRegExp, RegExp.Test(), RegExp.Source(), RegExp.Flags() Create and use regex from Go
NewArrayBufferFromBytes, NewUint8ArrayFromBytes Inject binary data into V8
Value.ArrayBufferGetContents() Zero-copy read of ArrayBuffer bytes
Object.GetPropertyNames(), Object.GetOwnPropertyNames() Enumerate object keys
Object.DefineOwnProperty(key, val, attrs) Define properties with ReadOnly/DontDelete
Object.SetPrivate/GetPrivate/HasPrivate/DeletePrivate Properties invisible to JS
Isolate.SetMicrotasksPolicy() Control when Promise callbacks execute
Context.SetSecurityToken/GetSecurityToken Cross-context access control
JSError.Value Access original V8 exception object for rethrowing
Value.DetailString() No longer panics — returns fallback string on failure
Value.Release() Nil-safe, double-call safe
Build tag v8go_profiling pprof profiles for tracking Isolate/Context leaks
V8 sandbox (v8_enable_sandbox) Disabled — requires libc++ hardening incompatible with CGo
Maglev JIT (v8_enable_maglev) Faster warmup for short-lived scripts
WebAssembly disabled Reduced binary size and attack surface
Null-byte safe strings RunScript, CompileModule, JSONParse handle \x00 correctly
malloc safety All C++ allocations check for NULL

Supported Platforms

OS Arch Status
Linux amd64, arm64 ✅
macOS amd64, arm64 ✅
Android amd64, arm64 ✅
Windows — Community contribution needed

License

See LICENSE.

V8 Gopher image based on original artwork from Renee French.

Documentation ¶

Overview ¶

Package v8go provides an API to execute JavaScript.

Example (WrappingNativeGoObject) ¶
package main

import (
	"fmt"
	"runtime/cgo"
	"strings"

	v8 "github.com/iquirino/v8go"
)

func main() {
	// This example shows how to create a JavaScript class that is a wrapper for
	// a native Go type.
	//
	// This example uses a FunctionTemplate to expose a class that can be
	// constructed from JavaScript.

	iso := v8.NewIsolate()
	defer iso.Dispose()

	// The JavaScript object need to have some kind of "handle" referring to the
	// original object. This example uses cgo handles which exist for this very
	// purpose.
	//
	// We keep a list of created handles in order to clean up, as active handle
	// will prevent the Go value from being gargabe collected.
	var handles []cgo.Handle
	defer func() {
		for _, h := range handles {
			h.Delete()
		}
	}()

	constructor := v8.NewFunctionTemplateWithError(iso,
		func(info *v8.FunctionCallbackInfo) (*v8.Value, error) {
			handle := cgo.NewHandle(&strings.Builder{})
			handles = append(handles, handle)
			info.This().SetInternalField(0, v8.NewValueExternalHandle(iso, handle))
			return nil, nil
		})

	// A simple helper to retrieve the internal value. The checks for internal
	// field count is necessary to protect against this type of misuse:
	//
	// 	const notABuilder = { __proto__: Builder }
	// 	notABuilder.writeString("value")
	//
	// The idiomatic result should be a JavaScript TypeError thrown.
	getInstance := func(info *v8.FunctionCallbackInfo) (*strings.Builder, error) {
		if info.This().InternalFieldCount() > 0 {
			if handle := info.This().GetInternalField(0).ExternalHandle(); handle != 0 {
				if builder, ok := handle.Value().(*strings.Builder); ok {
					return builder, nil
				}
			}
		}
		return nil, v8.NewTypeError(iso, "Object is not an instance of the Builder interface")
	}

	// You must call SetInternalFieldCount on the InstanceTemplate before
	// setting an internal field on an actual instance.
	constructor.InstanceTemplate().SetInternalFieldCount(1)

	// Methods are added to the PrototypeTemplate
	constructor.PrototypeTemplate().Set("writeString", v8.NewFunctionTemplateWithError(iso,
		func(info *v8.FunctionCallbackInfo) (*v8.Value, error) {
			builder, err := getInstance(info)
			if err != nil {
				return nil, err
			}
			if len(info.Args()) == 0 {
				return nil, v8.NewTypeError(iso, "Missing argument, s")
			}
			builder.WriteString(info.Args()[0].String())
			return nil, nil
		}))
	constructor.PrototypeTemplate().Set("toString", v8.NewFunctionTemplateWithError(iso,
		func(info *v8.FunctionCallbackInfo) (*v8.Value, error) {
			builder, err := getInstance(info)
			if err != nil {
				return nil, err
			}
			return v8.NewValue(iso, builder.String())
		}))

	// Create a template for global scope, and add the builder to it
	global := v8.NewObjectTemplate(iso)
	global.Set("StringBuilder", constructor)

	ctx := v8.NewContext(iso, global)
	defer ctx.Close()

	val, _ := ctx.RunScript(`
		const b = new StringBuilder()
		b.writeString("Hello ")
		b.writeString("from ")
		b.writeString("JavaScript!")
		b.toString()
	`, "")
	fmt.Println("First batch")
	fmt.Println(val.String())

}
Output:
First batch
Hello from JavaScript!

Index ¶

Examples ¶

Constants ¶

This section is empty.

Variables ¶

View Source
var ErrScriptTimeout = errors.New("v8go: script execution timed out")

ErrScriptTimeout is returned when a script execution exceeds the given deadline.

View Source
var NotIntercepted = errors.New("v8go: NotIntercepted")

NotIntercepted is the error returned by property handler callbacks when they did not intercept the property.

Functions ¶

func JSONStringify ¶

func JSONStringify(ctx *Context, val Valuer) (string, error)

JSONStringify tries to stringify the JSON-serializable object value and returns it as string.

Example ¶
package main

import (
	"fmt"

	v8 "github.com/iquirino/v8go"
)

func main() {
	ctx := v8.NewContext()
	defer ctx.Isolate().Dispose()
	defer ctx.Close()
	val, _ := v8.JSONParse(ctx, `{
		"a": 1,
		"b": "foo"
	}`)
	jsonStr, _ := v8.JSONStringify(ctx, val)
	fmt.Println(jsonStr)
}
Output:
{"a":1,"b":"foo"}

func SetFlags ¶

func SetFlags(flags ...string)

SetFlags sets flags for V8. For possible flags: https://github.com/v8/v8/blob/master/src/flags/flag-definitions.h Flags are expected to be prefixed with `--`, for example: `--harmony`. Flags can be reverted using the `--no` prefix equivalent, for example: `--use_strict` vs `--nouse_strict`. Flags will affect all Isolates created, even after creation.

func Version ¶

func Version() string

Version returns the version of the V8 Engine with the -v8go suffix

Types ¶

type Array ¶

type Array struct {
	*Object
}

Array is a JavaScript Array object.

func NewArray ¶

func NewArray(ctx *Context, length int) (*Array, error)

NewArray creates a new JavaScript Array with the given length.

func (*Array) Get ¶

func (a *Array) Get(idx uint32) (*Value, error)

Get returns the value at the given index.

func (*Array) Includes ¶

func (a *Array) Includes(val Valuer) (bool, error)

Includes returns true if the array contains the given value.

func (*Array) IndexOf ¶

func (a *Array) IndexOf(val Valuer) (int, error)

IndexOf returns the first index of the given value, or -1 if not found.

func (*Array) Length ¶

func (a *Array) Length() int

Length returns the length of the array.

func (*Array) Pop ¶

func (a *Array) Pop() (*Value, error)

Pop removes and returns the last element of the array.

func (*Array) Push ¶

func (a *Array) Push(args ...Valuer) (int, error)

Push appends one or more values to the end of the array and returns the new length.

func (*Array) Set ¶

func (a *Array) Set(idx uint32, val interface{}) error

Set sets the value at the given index.

func (*Array) Shift ¶

func (a *Array) Shift() (*Value, error)

Shift removes and returns the first element of the array.

func (*Array) Unshift ¶

func (a *Array) Unshift(args ...Valuer) (int, error)

Unshift prepends one or more values to the beginning of the array and returns the new length.

type CPUProfile ¶

type CPUProfile struct {
	// contains filtered or unexported fields
}

func (*CPUProfile) Delete ¶

func (c *CPUProfile) Delete()

Deletes the profile and removes it from CpuProfiler's list. All pointers to nodes previously returned become invalid.

func (*CPUProfile) GetDuration ¶

func (c *CPUProfile) GetDuration() time.Duration

Returns the duration of the profile.

func (*CPUProfile) GetTitle ¶

func (c *CPUProfile) GetTitle() string

Returns CPU profile title.

func (*CPUProfile) GetTopDownRoot ¶

func (c *CPUProfile) GetTopDownRoot() *CPUProfileNode

Returns the root node of the top down call tree.

type CPUProfileNode ¶

type CPUProfileNode struct {
	// contains filtered or unexported fields
}

func (*CPUProfileNode) GetBailoutReason ¶

func (c *CPUProfileNode) GetBailoutReason() string

Returns the bailout reason for the function if the optimization was disabled for it.

func (*CPUProfileNode) GetChild ¶

func (c *CPUProfileNode) GetChild(index int) *CPUProfileNode

Retrieves a child node by index.

func (*CPUProfileNode) GetChildrenCount ¶

func (c *CPUProfileNode) GetChildrenCount() int

func (*CPUProfileNode) GetColumnNumber ¶

func (c *CPUProfileNode) GetColumnNumber() int

Returns number of the column where the function originates.

func (*CPUProfileNode) GetFunctionName ¶

func (c *CPUProfileNode) GetFunctionName() string

Returns function name (empty string for anonymous functions.)

func (*CPUProfileNode) GetHitCount ¶

func (c *CPUProfileNode) GetHitCount() int

Returns count of samples where the function was currently executing.

func (*CPUProfileNode) GetLineNumber ¶

func (c *CPUProfileNode) GetLineNumber() int

Returns number of the line where the function originates.

func (*CPUProfileNode) GetNodeId ¶

func (c *CPUProfileNode) GetNodeId() int

Returns node id.

func (*CPUProfileNode) GetParent ¶

func (c *CPUProfileNode) GetParent() *CPUProfileNode

Retrieves the ancestor node, or nil if the root.

func (*CPUProfileNode) GetScriptId ¶

func (c *CPUProfileNode) GetScriptId() int

Returns id for script from where the function originates.

func (*CPUProfileNode) GetScriptResourceName ¶

func (c *CPUProfileNode) GetScriptResourceName() string

Returns resource name for script from where the function originates.

type CPUProfiler ¶

type CPUProfiler struct {
	// contains filtered or unexported fields
}

func NewCPUProfiler ¶

func NewCPUProfiler(iso *Isolate) *CPUProfiler

CPUProfiler is used to control CPU profiling.

func (*CPUProfiler) Dispose ¶

func (c *CPUProfiler) Dispose()

Dispose will dispose the profiler.

func (*CPUProfiler) StartProfiling ¶

func (c *CPUProfiler) StartProfiling(title string)

StartProfiling starts collecting a CPU profile. Title may be an empty string. Several profiles may be collected at once. Attempts to start collecting several profiles with the same title are silently ignored.

func (*CPUProfiler) StopProfiling ¶

func (c *CPUProfiler) StopProfiling(title string) *CPUProfile

Stops collecting CPU profile with a given title and returns it. If the title given is empty, finishes the last profile started.

type CompileMode ¶

type CompileMode C.int

type CompileOptions ¶

type CompileOptions struct {
	CachedData *CompilerCachedData

	Mode CompileMode
}

type CompilerCachedData ¶

type CompilerCachedData struct {
	Bytes    []byte
	Rejected bool
}

type ConsoleAPIMessage ¶

type ConsoleAPIMessage struct {
	ErrorLevel   MessageErrorLevel
	Message      string
	Url          string
	LineNumber   uint
	ColumnNumber uint
	// contains filtered or unexported fields
}

ConsoleAPIMessage contains the information from v8 from console function calls.

The fields correspond to the arguments for the C++ function v8_inspector::InspectorClient::consoleAPIMessage

Note: Stack traces are not supported.

See also: https://v8.github.io/api/head/classv8__inspector_1_1V8InspectorClient.html

type ConsoleAPIMessageHandler ¶

type ConsoleAPIMessageHandler interface {
	ConsoleAPIMessage(message ConsoleAPIMessage)
}

A ConsoleAPIMessageHandler will receive JavaScript `console` API calls.

type Context ¶

type Context struct {
	// contains filtered or unexported fields
}

Context is a global root execution environment that allows separate, unrelated, JavaScript applications to run in a single instance of V8.

Example ¶
package main

import (
	"fmt"

	v8 "github.com/iquirino/v8go"
)

func main() {
	ctx := v8.NewContext()
	defer ctx.Isolate().Dispose()
	defer ctx.Close()
	ctx.RunScript("const add = (a, b) => a + b", "math.js")
	ctx.RunScript("const result = add(3, 4)", "main.js")
	val, _ := ctx.RunScript("result", "value.js")
	fmt.Println(val)
}
Output:
7
Example (GlobalTemplate) ¶
package main

import (
	"fmt"

	v8 "github.com/iquirino/v8go"
)

func main() {
	iso := v8.NewIsolate()
	defer iso.Dispose()
	obj := v8.NewObjectTemplate(iso)
	obj.Set("version", "v1.0.0")
	ctx := v8.NewContext(iso, obj)
	defer ctx.Close()
	val, _ := ctx.RunScript("version", "main.js")
	fmt.Println(val)
}
Output:
v1.0.0
Example (Isolate) ¶
package main

import (
	"fmt"

	v8 "github.com/iquirino/v8go"
)

func main() {
	iso := v8.NewIsolate()
	defer iso.Dispose()
	ctx1 := v8.NewContext(iso)
	defer ctx1.Close()
	ctx1.RunScript("const foo = 'bar'", "context_one.js")
	val, _ := ctx1.RunScript("foo", "foo.js")
	fmt.Println(val)

	ctx2 := v8.NewContext(iso)
	defer ctx2.Close()
	_, err := ctx2.RunScript("foo", "context_two.js")
	fmt.Println(err)
}
Output:
bar
ReferenceError: foo is not defined

func NewContext ¶

func NewContext(opt ...ContextOption) *Context

NewContext creates a new JavaScript context; if no Isolate is passed as a ContextOption than a new Isolate will be created.

func (*Context) Close ¶

func (c *Context) Close()

Close will dispose the context and free the memory. Access to any values associated with the context after calling Close may panic.

func (*Context) GetSecurityToken ¶

func (c *Context) GetSecurityToken() *Value

GetSecurityToken returns the security token for this context.

func (*Context) Global ¶

func (c *Context) Global() *Object

Global returns the global proxy object. Global proxy object is a thin wrapper whose prototype points to actual context's global object with the properties like Object, etc. This is done that way for security reasons. Please note that changes to global proxy object prototype most probably would break the VM — V8 expects only global object as a prototype of global proxy object.

func (*Context) Isolate ¶

func (c *Context) Isolate() *Isolate

Isolate gets the current context's parent isolate.

func (*Context) PerformMicrotaskCheckpoint ¶

func (c *Context) PerformMicrotaskCheckpoint()

PerformMicrotaskCheckpoint runs the default MicrotaskQueue until empty. This is used to make progress on Promises.

func (*Context) RetainedValueCount ¶

func (c *Context) RetainedValueCount() int

func (*Context) RunScript ¶

func (c *Context) RunScript(source string, origin string) (*Value, error)

RunScript executes the source JavaScript; origin (a.k.a. filename) provides a reference for the script and used in the stack trace if there is an error. error will be of type `JSError` if not nil.

func (*Context) RunScriptWithTimeout ¶

func (c *Context) RunScriptWithTimeout(source, origin string, timeout time.Duration) (*Value, error)

RunScriptWithTimeout executes the source JavaScript with a timeout. If the script does not complete within the given duration, execution is terminated and ErrScriptTimeout is returned.

func (*Context) SetSecurityToken ¶

func (c *Context) SetSecurityToken(token *Value)

SetSecurityToken sets the security token for this context. Contexts with different security tokens cannot access each other's properties when sharing the same isolate. Only relevant for multi-context-per-isolate patterns.

type ContextOption ¶

type ContextOption interface {
	// contains filtered or unexported methods
}

ContextOption sets options such as Isolate and Global Template to the NewContext

type Date ¶

type Date struct {
	*Object
}

Date is a JavaScript Date object.

func NewDate ¶

func NewDate(ctx *Context, t time.Time) (*Date, error)

NewDate creates a new Date from a Go time.Time.

func (*Date) GetDate ¶

func (d *Date) GetDate() (int, error)

GetDate returns the day of the month (1-31).

func (*Date) GetFullYear ¶

func (d *Date) GetFullYear() (int, error)

GetFullYear returns the year (4 digits for dates between 1000 and 9999).

func (*Date) GetHours ¶

func (d *Date) GetHours() (int, error)

GetHours returns the hour (0-23).

func (*Date) GetMonth ¶

func (d *Date) GetMonth() (int, error)

GetMonth returns the month (0-11).

func (*Date) GetTime ¶

func (d *Date) GetTime() (int64, error)

GetTime returns the number of milliseconds since Unix epoch.

func (*Date) Time ¶

func (d *Date) Time() time.Time

Time returns the Go time.Time equivalent of this Date.

func (*Date) ToISOString ¶

func (d *Date) ToISOString() (string, error)

ToISOString returns the date as an ISO 8601 string (e.g., "2024-01-15T10:30:00.000Z").

type Exception ¶

type Exception struct {
	*Value
}

An Exception is a JavaScript exception.

func NewError ¶

func NewError(iso *Isolate, msg string) *Exception

NewError creates an Error, which is the common thing to throw from user code.

func NewRangeError ¶

func NewRangeError(iso *Isolate, msg string) *Exception

NewRangeError creates a RangeError.

func NewReferenceError ¶

func NewReferenceError(iso *Isolate, msg string) *Exception

NewReferenceError creates a ReferenceError.

func NewSyntaxError ¶

func NewSyntaxError(iso *Isolate, msg string) *Exception

NewSyntaxError creates a SyntaxError.

func NewTypeError ¶

func NewTypeError(iso *Isolate, msg string) *Exception

NewTypeError creates a TypeError.

func NewWasmCompileError ¶

func NewWasmCompileError(iso *Isolate, msg string) *Exception

NewWasmCompileError creates a WasmCompileError.

func NewWasmLinkError ¶

func NewWasmLinkError(iso *Isolate, msg string) *Exception

NewWasmLinkError creates a WasmLinkError.

func NewWasmRuntimeError ¶

func NewWasmRuntimeError(iso *Isolate, msg string) *Exception

NewWasmRuntimeError creates a WasmRuntimeError.

func (*Exception) As ¶

func (e *Exception) As(target interface{}) bool

As provides support for errors.As.

func (*Exception) Error ¶

func (e *Exception) Error() string

Error implements error.

func (*Exception) Is ¶

func (e *Exception) Is(err error) bool

Is provides support for errors.Is.

func (*Exception) String ¶

func (e *Exception) String() string

String implements fmt.Stringer.

type FixedArray ¶

type FixedArray struct{}

type Function ¶

type Function struct {
	*Value
}

Function is a JavaScript function.

func (*Function) Call ¶

func (fn *Function) Call(recv Valuer, args ...Valuer) (*Value, error)

Call this JavaScript function with the given arguments.

func (*Function) NewInstance ¶

func (fn *Function) NewInstance(args ...Valuer) (*Object, error)

Invoke a constructor function to create an object instance.

func (*Function) SourceMapUrl ¶

func (fn *Function) SourceMapUrl() *Value

Return the source map url for a function.

type FunctionCallback ¶

type FunctionCallback func(info *FunctionCallbackInfo) *Value

FunctionCallback is a callback that is executed in Go when a function is executed in JS.

type FunctionCallbackInfo ¶

type FunctionCallbackInfo struct {
	// contains filtered or unexported fields
}

FunctionCallbackInfo is the argument that is passed to a FunctionCallback.

func (*FunctionCallbackInfo) Args ¶

func (i *FunctionCallbackInfo) Args() []*Value

Args returns a slice of the value arguments that are passed to the JS function.

func (*FunctionCallbackInfo) Context ¶

func (i *FunctionCallbackInfo) Context() *Context

Context is the current context that the callback is being executed in.

func (*FunctionCallbackInfo) Index ¶

func (i *FunctionCallbackInfo) Index() uint32

func (*FunctionCallbackInfo) Release ¶

func (i *FunctionCallbackInfo) Release()

func (*FunctionCallbackInfo) This ¶

func (i *FunctionCallbackInfo) This() *Object

This returns the receiver object "this".

type FunctionCallbackWithError ¶

type FunctionCallbackWithError func(info *FunctionCallbackInfo) (*Value, error)

FunctionCallbackWithError is a callback that is executed in Go when a function is executed in JS. If a ValueError is returned, its value will be thrown as an exception in V8, otherwise Error() is invoked, and the string is thrown.

type FunctionTemplate ¶

type FunctionTemplate struct {
	// contains filtered or unexported fields
}

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.

A FunctionTemplate can be used to create "constructors", and add methods to the "class". FunctionTemplate.PrototypeTemplate can be used to add normal methods on the class, and FunctionTemplate.InstanceTemplate can be used to add fields automatically to new instances of a class.

V8 API Docs: https://v8.github.io/api/head/classv8_1_1FunctionTemplate.html

Example ¶
package main

import (
	"fmt"

	v8 "github.com/iquirino/v8go"
)

func main() {
	iso := v8.NewIsolate()
	defer iso.Dispose()
	global := v8.NewObjectTemplate(iso)
	printfn := v8.NewFunctionTemplate(iso, func(info *v8.FunctionCallbackInfo) *v8.Value {
		fmt.Printf("%+v\n", info.Args())
		return nil
	})
	global.Set("print", printfn, v8.ReadOnly)
	ctx := v8.NewContext(iso, global)
	defer ctx.Close()
	ctx.RunScript("print('foo', 'bar', 0, 1)", "")
}
Output:
[foo bar 0 1]
Example (Fetch) ¶
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"

	v8 "github.com/iquirino/v8go"
)

func main() {
	iso := v8.NewIsolate()
	defer iso.Dispose()
	global := v8.NewObjectTemplate(iso)

	fetchfn := v8.NewFunctionTemplate(iso, func(info *v8.FunctionCallbackInfo) *v8.Value {
		args := info.Args()
		url := args[0].String()

		resolver, _ := v8.NewPromiseResolver(info.Context())

		go func() {
			res, _ := http.Get(url)
			body, _ := ioutil.ReadAll(res.Body)
			val, _ := v8.NewValue(iso, string(body))
			resolver.Resolve(val)
		}()
		return resolver.GetPromise().Value
	})
	global.Set("fetch", fetchfn, v8.ReadOnly)

	ctx := v8.NewContext(iso, global)
	defer ctx.Close()
	val, _ := ctx.RunScript("fetch('https://rogchap.com/v8go')", "")
	prom, _ := val.AsPromise()

	// wait for the promise to resolve
	for prom.State() == v8.Pending {
		continue
	}
	fmt.Printf("%s\n", strings.Split(prom.Result().String(), "\n")[0])
}
Output:
<!DOCTYPE html>

func NewFunctionTemplate ¶

func NewFunctionTemplate(iso *Isolate, callback FunctionCallback) *FunctionTemplate

NewFunctionTemplate creates a FunctionTemplate for a given callback. Prefer using NewFunctionTemplateWithError.

func NewFunctionTemplateWithError ¶

func NewFunctionTemplateWithError(
	iso *Isolate,
	callback FunctionCallbackWithError,
) *FunctionTemplate

NewFunctionTemplateWithError creates a FunctionTemplate for a given callback. If the callback returns an error, it will be thrown as a JS error.

func (*FunctionTemplate) GetFunction ¶

func (tmpl *FunctionTemplate) GetFunction(ctx *Context) (*Function, error)

GetFunction returns an instance of this function template bound to the given context.

func (*FunctionTemplate) Inherit ¶

func (tmpl *FunctionTemplate) Inherit(base *FunctionTemplate)

func (*FunctionTemplate) InstanceTemplate ¶

func (tmpl *FunctionTemplate) InstanceTemplate() *ObjectTemplate

InstanceTemplate gets the ObjectTemplate that is used for new object instances created when this function is used as a constructor.

You can add functions and values to new instance using ObjectTemplate.Set and ObjectTemplate.SetSymbol. Those values will become own properties on the instance, not the prototype.

Adding a function to an instance template corresponds to the following JavaScript:

class Example() {
	constructor() {
		this.foo = function() { /* creates a function on the instance */ }
	}
}

func (*FunctionTemplate) PrototypeTemplate ¶

func (tmpl *FunctionTemplate) PrototypeTemplate() *ObjectTemplate

PrototypeTemplate gets the ObjectTemplate that is used to create the prototype object associated with the function.

You can call ObjectTemplate.Set or ObjectTemplate.SetSymbol, passing a FunctionTemplate to add a "method" to the class.

Adding a function to a prototype template corresponds normal method on a JavaScript "class":

class Example {
	foo() { /* this is a method on the prototype */ }
}

Or the old-school way

function Example() {}
Example.prototype.foo = function() { }

The function becomes an own property on the prototype, not the instance.

func (FunctionTemplate) Set ¶

func (t FunctionTemplate) Set(name string, val interface{}, attributes ...PropertyAttribute) error

Set adds a property to each instance created by this template. The property must be defined either as a primitive value, or a template. If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a value will be created and set as the value property.

func (FunctionTemplate) SetSymbol ¶

func (t FunctionTemplate) SetSymbol(key *Symbol, val interface{}, attributes ...PropertyAttribute) error

SetSymbol adds a property to each instance created by this template. The property must be defined either as a primitive value, or a template. If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a value will be created and set as the value property.

type HeapStatistics ¶

type HeapStatistics struct {
	TotalHeapSize            uint64
	TotalHeapSizeExecutable  uint64
	TotalPhysicalSize        uint64
	TotalAvailableSize       uint64
	UsedHeapSize             uint64
	HeapSizeLimit            uint64
	MallocedMemory           uint64
	ExternalMemory           uint64
	PeakMallocedMemory       uint64
	NumberOfNativeContexts   uint64
	NumberOfDetachedContexts uint64
}

HeapStatistics represents V8 isolate heap statistics

type ImportAttribute ¶

type ImportAttribute struct {
	Key   string
	Value string
	// Location is the zero-based index in the string where the key is found
	Location int
}

ImportAttribute represents a single import attribute in a module import statement. E.g., the following script has a single import attribute.

import foo from "foo.js" with { data: "value" }

type ImportAttributes ¶

type ImportAttributes struct {
	// contains filtered or unexported fields
}

ImportAttributes represents the attributes for each module import.

NOTE: ImportAttributes cannot be used AFTER ResolveModule returns

func (ImportAttributes) All ¶

type Inspector ¶

type Inspector struct {
	// contains filtered or unexported fields
}

An Inspector in v8 provides access to internals of the engine, such as console output

To receive console output, you need to first create an InspectorClient which will handle the interaction for a specific Context.

After a Context is created, you need to register it with the Inspector using Inspector.ContextCreated, and cleanup using Inspector.ContextDestroyed.

See also: https://v8.github.io/api/head/classv8__inspector_1_1V8Inspector.html

func NewInspector ¶

func NewInspector(iso *Isolate, client *InspectorClient) *Inspector

NewInspector creates an Inspector for a specific Isolate iso communicating with the InspectorClient client.

Before disposing the iso, be sure to dispose the inspector using Inspector.Dispose

func (*Inspector) ContextCreated ¶

func (i *Inspector) ContextCreated(ctx *Context)

ContextCreated tells the inspector that a new Context has been created. This must be called before the InspectorClient can be used.

func (*Inspector) ContextDestroyed ¶

func (i *Inspector) ContextDestroyed(ctx *Context)

ContextDestroyed must be called before a Context is closed.

func (*Inspector) Dispose ¶

func (i *Inspector) Dispose()

Dispose the Inspector. Call this before disposing the Isolate and the InspectorClient that this is connected to.

type InspectorClient ¶

type InspectorClient struct {
	// contains filtered or unexported fields
}

An InspectorClient is the bridge from the Inspector to your code.

func NewInspectorClient ¶

func NewInspectorClient(handler ConsoleAPIMessageHandler) *InspectorClient

Create a new InspectorClient passing a handler that will receive the callbacks from v8.

func (*InspectorClient) Dispose ¶

func (c *InspectorClient) Dispose()

Dispose frees up resources taken up by the InspectorClient. Be sure to call this after calling Inspector.Dispose

type Isolate ¶

type Isolate struct {
	// contains filtered or unexported fields
}

Isolate is a JavaScript VM instance with its own heap and garbage collector. Most applications will create one isolate with many V8 contexts for execution.

func NewIsolate ¶

func NewIsolate(opts ...IsolateOption) *Isolate

NewIsolate creates a new V8 isolate with the provided options. Only one thread may access a given isolate at a time, but different threads may access different isolates simultaneously. When an isolate is no longer used its resources should be freed by calling iso.Dispose(). An *Isolate can be used as a v8go.ContextOption to create a new Context, rather than creating a new default Isolate.

func (*Isolate) Close deprecated

func (i *Isolate) Close()

Deprecated: use `iso.Dispose()`.

func (*Isolate) CompileUnboundScript ¶

func (i *Isolate) CompileUnboundScript(
	source, origin string,
	opts CompileOptions,
) (*UnboundScript, error)

CompileUnboundScript will create an UnboundScript (i.e. context-indepdent) using the provided source JavaScript, origin (a.k.a. filename), and options. If options contain a non-null CachedData, compilation of the script will use that code cache. error will be of type `JSError` if not nil.

func (*Isolate) Dispose ¶

func (i *Isolate) Dispose()

Dispose will dispose the Isolate VM; subsequent calls will panic.

func (*Isolate) GetHeapStatistics ¶

func (i *Isolate) GetHeapStatistics() HeapStatistics

GetHeapStatistics returns heap statistics for an isolate.

func (*Isolate) IsExecutionTerminating ¶

func (i *Isolate) IsExecutionTerminating() bool

IsExecutionTerminating returns whether V8 is currently terminating Javascript execution. If true, there are still JavaScript frames on the stack and the termination exception is still active.

func (*Isolate) SetMicrotasksPolicy ¶

func (i *Isolate) SetMicrotasksPolicy(policy MicrotasksPolicy)

SetMicrotasksPolicy sets when microtasks (Promise callbacks) are executed. Use MicrotasksExplicit to have full control via PerformMicrotaskCheckpoint.

func (*Isolate) SetPromiseRejectedCallback ¶

func (i *Isolate) SetPromiseRejectedCallback(cb RejectedPromiseCallback)

SetPromiseRejectedCallback installs a callback to be called when a promise is rejected. This includes rejections that may occur after a script value has been evaluated and V8 is running microtasks.

func (*Isolate) TerminateExecution ¶

func (i *Isolate) TerminateExecution()

TerminateExecution terminates forcefully the current thread of JavaScript execution in the given isolate.

func (*Isolate) ThrowException ¶

func (i *Isolate) ThrowException(value *Value) *Value

ThrowException schedules an exception to be thrown when returning to JavaScript. When an exception has been scheduled it is illegal to invoke any JavaScript operation; the caller must return immediately and only after the exception has been handled does it become legal to invoke JavaScript operations.

type IsolateOption ¶

type IsolateOption func(*isolateConfig)

IsolateOption configures an Isolate on creation.

func WithResourceConstraints ¶

func WithResourceConstraints(initialHeapSizeInBytes, maxHeapSizeInBytes uint64) IsolateOption

WithResourceConstraints sets memory constraints for the isolate. If constraints are set, v8go will try to call `TerminateExecution` when the hard limit is hit.

type JSError ¶

type JSError struct {
	Message    string
	Location   string
	StackTrace string
	// Value holds the original JavaScript exception value, if available.
	// This can be used to rethrow the error via iso.ThrowException(err.Value)
	// or inspect the error object from Go.
	Value *Value
}

JSError is an error that is returned if there is are any JavaScript exceptions handled in the context. When used with the fmt verb `%+v`, will output the JavaScript stack trace, if available.

func (*JSError) Error ¶

func (e *JSError) Error() string

func (*JSError) Format ¶

func (e *JSError) Format(s fmt.State, verb rune)

Format implements the fmt.Formatter interface to provide a custom formatter primarily to output the javascript stack trace with %+v

type Map ¶

type Map struct {
	*Object
}

Map is a JavaScript Map object.

func NewMap ¶

func NewMap(ctx *Context) (*Map, error)

NewMap creates a new empty Map.

func (*Map) MapDelete ¶

func (m *Map) MapDelete(key Valuer) bool

MapDelete removes a key from the Map. Returns true if the key was present.

func (*Map) MapGet ¶

func (m *Map) MapGet(key Valuer) (*Value, error)

MapGet returns the value for the given key, or undefined if not present.

func (*Map) MapHas ¶

func (m *Map) MapHas(key Valuer) bool

MapHas returns true if the key exists in the Map.

func (*Map) MapSet ¶

func (m *Map) MapSet(key, val Valuer) error

MapSet sets a key-value pair and returns the Map (for chaining).

func (*Map) MapSize ¶

func (m *Map) MapSize() int

MapSize returns the number of entries in the Map.

type MessageErrorLevel ¶

type MessageErrorLevel uint8

Represents the level of console output from JavaScript. E.g., `console.log`, `console.error`, etc.

The values reflect the values of v8::Isolate::MessageErrorLevel

See also: https://v8.github.io/api/head/classv8_1_1Isolate.html

const (
	ErrorLevelLog MessageErrorLevel = 1 << iota
	ErrorLevelDebug
	ErrorLevelInfo
	ErrorLevelError
	ErrorLevelWarning
	ErrorLevelAll = ErrorLevelLog | ErrorLevelDebug | ErrorLevelInfo | ErrorLevelError | ErrorLevelWarning
)

func (MessageErrorLevel) String ¶

func (lvl MessageErrorLevel) String() string

type MicrotasksPolicy ¶

type MicrotasksPolicy int

MicrotasksPolicy controls when microtasks (Promise callbacks, etc.) are executed.

const (
	// MicrotasksExplicit means microtasks are only run when PerformMicrotaskCheckpoint is called.
	MicrotasksExplicit MicrotasksPolicy = 0
	// MicrotasksScoped means microtasks run when the outermost script scope exits (default V8 behavior).
	MicrotasksScoped MicrotasksPolicy = 1
	// MicrotasksAuto means microtasks run automatically after each script/callback (Chrome behavior).
	MicrotasksAuto MicrotasksPolicy = 2
)

type Module ¶

type Module struct {
	// contains filtered or unexported fields
}

Module represents an ECMAScript Module (ESM). A module is obtained from CompileModule. Before a module can be used, it must be instantiated by calling Module.InstantiateModule, after which it can be evaluated with Module.Evaluate.

func CompileModule ¶

func CompileModule(iso *Isolate, source, origin string) (*Module, error)

func (Module) Delete ¶

func (m Module) Delete()

func (Module) Evaluate ¶

func (m Module) Evaluate(ctx *Context) (*Value, error)

Evaluate evaluates the module.

The returned valus is a promise. If the module is evaluated synchronously, the promise will have settled upon return.

If evaluating the script fails, the promise will be rejected; but if an imported module cannot be evaluated, Evaluate will return an error.

func (Module) GetModuleNamespace ¶

func (m Module) GetModuleNamespace() *Value

GetModuleNamespace returns the module namespace. This is an exotic object containing the exports of the module.

See also: https://tc39.es/ecma262/#sec-module-namespace-exotic-objects

func (Module) GetStatus ¶

func (m Module) GetStatus() int

func (Module) InstantiateModule ¶

func (m Module) InstantiateModule(ctx *Context, resolver ResolveModuler) error

func (Module) IsSourceTextModule ¶

func (m Module) IsSourceTextModule() bool

func (Module) ScriptID ¶

func (m Module) ScriptID() int

type NamedPropertyDefinerer ¶

type NamedPropertyDefinerer interface {
	NamedPropertyDefiner(property *Value, desc *PropertyDescriptor, info PropertyCallbackInfo) error
}

type NamedPropertyDeleter ¶

type NamedPropertyDeleter interface {
	NamedPropertyDelete(property *Value, info PropertyCallbackInfo) (success bool, err error)
}

type NamedPropertyDescriptorer ¶

type NamedPropertyDescriptorer interface {
	NamedPropertyDescriptor(property *Value, info PropertyCallbackInfo) (*Value, error)
}

type NamedPropertyEnumeratorer ¶

type NamedPropertyEnumeratorer interface {
	NamedPropertyEnumerator(info PropertyCallbackInfo) (names []*Value, err error)
}

type NamedPropertyGetter ¶

type NamedPropertyGetter interface {
	NamedPropertyGet(property *Value, info PropertyCallbackInfo) (*Value, error)
}

type NamedPropertyQueryer ¶

type NamedPropertyQueryer interface {
	NamedPropertyQuery(property *Value, info PropertyCallbackInfo) (int, error)
}

type NamedPropertySetter ¶

type NamedPropertySetter interface {
	NamedPropertySet(property *Value, value *Value, info PropertyCallbackInfo) error
}

type Object ¶

type Object struct {
	*Value
}

Object is a JavaScript object (ECMA-262, 4.3.3)

Example (Global) ¶
package main

import (
	"fmt"

	v8 "github.com/iquirino/v8go"
)

func main() {
	iso := v8.NewIsolate()
	defer iso.Dispose()
	ctx := v8.NewContext(iso)
	defer ctx.Close()
	global := ctx.Global()

	console := v8.NewObjectTemplate(iso)
	logfn := v8.NewFunctionTemplate(iso, func(info *v8.FunctionCallbackInfo) *v8.Value {
		fmt.Println(info.Args()[0])
		return nil
	})
	console.Set("log", logfn)
	consoleObj, _ := console.NewInstance(ctx)

	global.Set("console", consoleObj)
	ctx.RunScript("console.log('foo')", "")
}
Output:
foo

func (*Object) DefineOwnProperty ¶

func (o *Object) DefineOwnProperty(key string, val Valuer, attributes PropertyAttribute) bool

DefineOwnProperty defines an own property on this object with the given attributes. Attributes can be combined with | (OR): None, ReadOnly, DontEnum, DontDelete.

func (*Object) Delete ¶

func (o *Object) Delete(key string) bool

Delete returns true if successful in deleting a named property on the object.

func (*Object) DeleteIdx ¶

func (o *Object) DeleteIdx(idx uint32) bool

DeleteIdx returns true if successful in deleting a value at a given index of the object.

func (*Object) DeletePrivate ¶

func (o *Object) DeletePrivate(key string) bool

DeletePrivate removes a private property from this object.

func (*Object) DeleteSymbol ¶

func (o *Object) DeleteSymbol(key *Symbol) bool

DeleteSymbol returns true if successful in deleting a named property on the object.

func (*Object) Get ¶

func (o *Object) Get(key string) (*Value, error)

Get tries to get a Value for a given Object property key.

func (*Object) GetIdx ¶

func (o *Object) GetIdx(idx uint32) (*Value, error)

GetIdx tries to get a Value at a give Object index.

func (*Object) GetInternalField ¶

func (o *Object) GetInternalField(idx uint32) *Value

GetInternalField gets the Value set by SetInternalField for the given index or the JS undefined value if the index hadn't been set. Panics if given an out of range index, or the field contains a Data other than a Value.

func (*Object) GetOwnPropertyNames ¶

func (o *Object) GetOwnPropertyNames() (*Array, error)

GetOwnPropertyNames returns an array of own property names (not from prototype).

func (*Object) GetPrivate ¶

func (o *Object) GetPrivate(key string) (*Value, error)

GetPrivate retrieves a private property from this object.

func (*Object) GetPropertyNames ¶

func (o *Object) GetPropertyNames() (*Array, error)

GetPropertyNames returns an array of property names (including prototype chain).

func (*Object) GetPrototype ¶

func (o *Object) GetPrototype() *Object

GetPrototype is equivalent to `Object.GetPrototypeOf(o)` in JavaScript.

NOTE: This uses Object::GetPrototypeV2 internally, as GetPrototype is deprecated.

func (*Object) GetSymbol ¶

func (o *Object) GetSymbol(key *Symbol) (*Value, error)

GetSymbol tries to get a Value for a given Object property key.

func (*Object) Has ¶

func (o *Object) Has(key string) bool

Has calls the abstract operation HasProperty(O, P) described in ECMA-262, 7.3.10. Returns true, if the object has the property, either own or on the prototype chain.

func (*Object) HasIdx ¶

func (o *Object) HasIdx(idx uint32) bool

HasIdx returns true if the object has a value at the given index.

func (*Object) HasPrivate ¶

func (o *Object) HasPrivate(key string) bool

HasPrivate returns true if this object has the given private property.

func (*Object) HasSymbol ¶

func (o *Object) HasSymbol(key *Symbol) bool

HasSymbol calls the abstract operation HasProperty(O, P) described in ECMA-262, 7.3.10. Returns true, if the object has the property, either own or on the prototype chain.

func (*Object) InternalFieldCount ¶

func (o *Object) InternalFieldCount() uint32

InternalFieldCount returns the number of internal fields this Object has.

func (*Object) MethodCall ¶

func (o *Object) MethodCall(methodName string, args ...Valuer) (*Value, error)

func (*Object) Set ¶

func (o *Object) Set(key string, val interface{}) error

Set will set a property on the Object to a given value. Supports all value types, eg: Object, Array, Date, Set, Map etc If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a *Value will be created and set as the value property.

func (*Object) SetIdx ¶

func (o *Object) SetIdx(idx uint32, val interface{}) error

Set will set a given index on the Object to a given value. Supports all value types, eg: Object, Array, Date, Set, Map etc If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a *Value will be created and set as the value property.

func (*Object) SetInternalField ¶

func (o *Object) SetInternalField(idx uint32, val interface{}) error

SetInternalField sets the value of an internal field for an ObjectTemplate instance. The object must be created from an ObjectTemplate, either from a call to ObjectTemplate.NewInstance, or as a new instance of a class. In which case the object template is the FunctionTemplate.InstanceTemplate of the constructor.

Before setting the internal field, is is necessary to call ObjectTemplate.SetInternalFieldCount indicating how many internal fields exist.

The function panics if the object is not created from an object template, or the index is outside the range of internal field count.

Example use cases:

  • An object implementing a javascript iterator can store the current index being iterated.
  • An object that exposes a native Go object to script code can store a reference. See also NewValueExternalHandle for this case

func (*Object) SetPrivate ¶

func (o *Object) SetPrivate(key string, val interface{}) error

SetPrivate sets a private property on this object. Private properties are invisible to JavaScript code — they cannot be accessed via Object.getOwnPropertySymbols() or any other reflection API.

func (*Object) SetPrototype ¶

func (o *Object) SetPrototype(proto *Object)

SetPrototype is equivalent to `Object.SetPrototype(o, proto)` in JavaScript. `Object.GetPrototypeOf(...)` in JavaScript.

NOTE: This uses Object::SetPrototypeV2 internally, as SetPrototype is deprecated.

func (*Object) SetSymbol ¶

func (o *Object) SetSymbol(key *Symbol, val interface{}) error

SetSymbol will set a property on the Object to a given value. Supports all value types, eg: Object, Array, Date, Set, Map etc If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a *Value will be created and set as the value property.

type ObjectTemplate ¶

type ObjectTemplate struct {
	// contains filtered or unexported fields
}

ObjectTemplate is used to create objects at runtime. Properties added to an ObjectTemplate are added to each object created from the ObjectTemplate.

func NewObjectTemplate ¶

func NewObjectTemplate(iso *Isolate) *ObjectTemplate

NewObjectTemplate creates a new ObjectTemplate. The *ObjectTemplate can be used as a v8go.ContextOption to create a global object in a Context.

func (*ObjectTemplate) InternalFieldCount ¶

func (o *ObjectTemplate) InternalFieldCount() uint32

InternalFieldCount returns the number of internal fields that instances of this template will have.

func (*ObjectTemplate) MarkAsUndetectable ¶

func (o *ObjectTemplate) MarkAsUndetectable()

MarkAsUndetectable marks object instances of the template as undetectable. Undetectable objects behave like undefined, but you can access properties defined on undetectable objects.

Note: Undetectable objects MUST have a CallAsFunctionHandler, see ObjectTemplate.SetCallAsFunctionHandler

func (*ObjectTemplate) NewInstance ¶

func (o *ObjectTemplate) NewInstance(ctx *Context) (*Object, error)

NewInstance creates a new Object based on the template.

func (ObjectTemplate) Set ¶

func (t ObjectTemplate) Set(name string, val interface{}, attributes ...PropertyAttribute) error

Set adds a property to each instance created by this template. The property must be defined either as a primitive value, or a template. If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a value will be created and set as the value property.

func (*ObjectTemplate) SetAccessorProperty ¶

func (o *ObjectTemplate) SetAccessorProperty(
	key string,
	get *FunctionTemplate,
	set *FunctionTemplate,
	attributes PropertyAttribute,
)

SetAccessorProperty creates a named accessor property, i.e., a property that is implemented as a function call. Arguments get and set represents the getter and setter, and can both be nil.

Note: The ReadOnly should not be used with a readonly property. If set is nil, the property will be readonly, and passing None is a sensible default.

This corresponds to ObjectTemplate::SetAccessorProperty in the C++ API.

Example ¶
package main

import (
	"fmt"

	v8 "github.com/iquirino/v8go"
)

func main() {
	iso := v8.NewIsolate()
	defer iso.Dispose()
	tmpl := v8.NewObjectTemplate(iso)
	tmpl.SetAccessorProperty(
		"prop",
		// Getter
		v8.NewFunctionTemplateWithError(
			iso,
			func(*v8.FunctionCallbackInfo) (*v8.Value, error) {
				return v8.NewValue(iso, "Value")
			},
		),
		nil, // Setter
		v8.None,
	)

	global := v8.NewObjectTemplate(iso)
	global.Set("obj", tmpl)
	ctx := v8.NewContext(iso, global)
	defer ctx.Close()

	value, _ := ctx.RunScript("obj.prop", "")
	fmt.Printf("Property value: %s\n", value.String())
}
Output:
Property value: Value
Example (Helpers) ¶
package main

import (
	"fmt"

	v8 "github.com/iquirino/v8go"
)

// SetObjectTemplateAccessorProperty shows an example of a helper that client
// code could optionally introduce.
//
// ObjectTemplate.SetAccessorProperty requires FunctionTemplate instances as
// arguments, but you rarely need the actual function template outside the
// scope of setting an accessor property.
//
// If many accessor properties must be created, this example could reduce
// repetitive trivial code.
func SetObjectTemplateAccessorProperty(
	iso *v8.Isolate,
	templ *v8.ObjectTemplate,
	key string,
	get v8.FunctionCallbackWithError,
	set v8.FunctionCallbackWithError,
	attributes v8.PropertyAttribute,
) {
	var (
		v8get *v8.FunctionTemplate
		v8set *v8.FunctionTemplate
	)
	if get != nil {
		v8get = v8.NewFunctionTemplateWithError(iso, get)
	}
	if set != nil {
		v8set = v8.NewFunctionTemplateWithError(iso, set)
	}
	templ.SetAccessorProperty(key, v8get, v8set, attributes)
}

func main() {
	iso := v8.NewIsolate()
	defer iso.Dispose()
	tmpl := v8.NewObjectTemplate(iso)

	current, _ := v8.NewValue(iso, "current")
	SetObjectTemplateAccessorProperty(iso, tmpl,
		"prop",
		// Getter
		func(*v8.FunctionCallbackInfo) (*v8.Value, error) {
			return current, nil
		},
		// Setter
		func(info *v8.FunctionCallbackInfo) (*v8.Value, error) {
			current = info.Args()[0]
			return nil, nil
		},
		v8.None,
	)

	global := v8.NewObjectTemplate(iso)
	global.Set("obj", tmpl)
	ctx := v8.NewContext(iso, global)
	defer ctx.Close()

	value, _ := ctx.RunScript("obj.prop", "")
	fmt.Printf("Property value before set: %s\n", value.String())

	value, _ = ctx.RunScript("obj.prop = 'new value'; obj.prop", "")
	fmt.Printf("Property value after set: %s\n", value.String())

}
Output:
Property value before set: current
Property value after set: new value

func (*ObjectTemplate) SetCallAsFunctionHandler ¶

func (o *ObjectTemplate) SetCallAsFunctionHandler(callback FunctionCallbackWithError)

SetCallAsFunctionHandler sets the callback to be used when calling instances created from this template. If no callback is set, instances behave like normal JavaScript objects that cannot be called as a function.

func (*ObjectTemplate) SetIndexedHandler ¶

func (o *ObjectTemplate) SetIndexedHandler(callback FunctionCallbackWithError)

func (*ObjectTemplate) SetInternalFieldCount ¶

func (o *ObjectTemplate) SetInternalFieldCount(fieldCount uint32)

SetInternalFieldCount sets the number of internal fields that instances of this template will have.

func (*ObjectTemplate) SetNamedHandler ¶

func (t *ObjectTemplate) SetNamedHandler(handler NamedPropertyGetter)

SetNamedHandler allows the embedder to calculate the properties at runtime, for example where the embedder is exposing a map/dictionary type to JavaScript. The caller must provide a type implementing NamedPropertyGetter, but it can optionally also support the following types

- NamedPropertySetter to handle when a property is assigned in JavaScript - NamedPropertyQueryer to handle when property details are inspected - NamedPropertyDeleter to handle when a property is deleted - NamedPropertyEnumeratorer to return the names of the properties - [NamedPropertyDefiner] to handler Object.defineProperty() calls - [NamedPropertyDescriptor] to generate a PropertyDescriptor for a property

With the exception of [NamedPropertyEnumerator] the methods accept a property of type *Value. The name can be either a string or a *Symbol. If the embedder does want to handle the callback, it must communicate this back to V8 by returning an [ErrNotIntercepted]. When thie is returned, the function must not produce any side effects.

func (ObjectTemplate) SetSymbol ¶

func (t ObjectTemplate) SetSymbol(key *Symbol, val interface{}, attributes ...PropertyAttribute) error

SetSymbol adds a property to each instance created by this template. The property must be defined either as a primitive value, or a template. If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a value will be created and set as the value property.

type Promise ¶

type Promise struct {
	*Object
}

Promise is the JavaScript promise object defined in ES6

func (*Promise) Catch ¶

func (p *Promise) Catch(cb FunctionCallback) (*Promise, error)

Catch invokes the given function if the promise is rejected. See Then for other details.

func (*Promise) CatchWithError ¶

func (p *Promise) CatchWithError(cb FunctionCallbackWithError) (*Promise, error)

func (*Promise) Result ¶

func (p *Promise) Result() *Value

Result is the value result of the Promise. The Promise must NOT be in a Pending state, otherwise may panic. Call promise.State() to validate state before calling for the result.

func (*Promise) State ¶

func (p *Promise) State() PromiseState

State returns the current state of the Promise.

func (*Promise) Then ¶

func (p *Promise) Then(cbs ...FunctionCallback) (*Promise, error)

Then accepts 1 or 2 callbacks. The first is invoked when the promise has been fulfilled. The second is invoked when the promise has been rejected. The returned Promise resolves after the callback finishes execution.

V8 only invokes the callback when processing "microtasks". The default MicrotaskPolicy processes them when the call depth decreases to 0. Call (*Context).PerformMicrotaskCheckpoint to trigger it manually.

func (*Promise) ThenWithError ¶

func (p *Promise) ThenWithError(cbs ...FunctionCallbackWithError) (*Promise, error)

type PromiseRejectEvent ¶

type PromiseRejectEvent uint8

PromiseRejectEvent represents the type of event passed to RejectedPromiseCallback. The values reflect the values of v8::PromiseRejectEvent.

See also: https://v8.github.io/api/head/classv8_1_1PromiseRejectMessage.html

const (
	// PromiseRejectWithNoHandler is the event that represents an unhandled
	// rejection.
	PromiseRejectWithNoHandler PromiseRejectEvent = 0
	// PromiseHandlerAddedAfterReject is sent when a rejection handler is added
	// to a promise that has already rejected. E.g., the following code will
	// result in a kPromiseRejectWithNoHandler event followed by an
	// PromiseHandlerAddedAfterReject event.
	//
	// 	Promise.reject("dummy").catch(e => {})
	//
	// The promise has already rejected when catch is called.
	PromiseHandlerAddedAfterReject PromiseRejectEvent = 1
	// PromiseRejectAfterResolved is sent when a project is rejected after it
	// has settled, e.g., the following will generate a
	// PromiseRejectAfterResolved event.
	//
	// 	new Promise((resolve, reject) => {
	// 		resolve()
	// 		reject()
	// 	})
	//
	// If the first resolve call is replaced with a reject, a
	// kPromiseRejectWithNoHandler event is sent first, followed by the
	// PromiseRejectAfterResolved event.
	PromiseRejectAfterResolved PromiseRejectEvent = 2
	// PromiseResolveAfterResolved is sent when a project is resolves after it
	// has settled, e.g., the following will generate a
	// PromiseResolveAfterResolved event.
	//
	// 	new Promise((resolve, reject) => {
	// 		resolve() // or reject()
	// 		resolve()
	// 	})
	//
	// If the first resolve call is replaced with a reject, a
	// kPromiseRejectWithNoHandler event is sent first, followed by the
	// PromiseResolveAfterResolved event.
	PromiseResolveAfterResolved PromiseRejectEvent = 3
)

func (PromiseRejectEvent) String ¶

func (u PromiseRejectEvent) String() string

type PromiseRejectMessage ¶

type PromiseRejectMessage struct {
	// Context contains the execution context where the promise was rejected
	Context *Context
	Promise *Promise
	Event   PromiseRejectEvent
	// Value contains the rejected value
	Value *Value
}

PromiseRejectMessage is passed to a RejectedPromiseCallback that is installed using Isolate.SetPromiseRejectedCallback. The values reflect the values in V8::PromiseRejectMessage

See also: https://v8.github.io/api/head/classv8_1_1PromiseRejectMessage.html

type PromiseResolver ¶

type PromiseResolver struct {
	*Object
	// contains filtered or unexported fields
}

PromiseResolver is the resolver object for the promise. Most cases will create a new PromiseResolver and return the associated Promise from the resolver.

func NewPromiseResolver ¶

func NewPromiseResolver(ctx *Context) (*PromiseResolver, error)

NewPromiseResolver creates a new Promise resolver for the given context. The associated Promise will be in a Pending state.

func (*PromiseResolver) GetPromise ¶

func (r *PromiseResolver) GetPromise() *Promise

GetPromise returns the associated Promise object for this resolver. The Promise object is unique to the resolver and returns the same object on multiple calls.

func (*PromiseResolver) Reject ¶

func (r *PromiseResolver) Reject(err *Value) bool

Reject invokes the Promise reject state with the given value. The Promise state will transition from Pending to Rejected.

func (*PromiseResolver) Resolve ¶

func (r *PromiseResolver) Resolve(val Valuer) bool

Resolve invokes the Promise resolve state with the given value. The Promise state will transition from Pending to Fulfilled.

type PromiseState ¶

type PromiseState int

PromiseState is the state of the Promise.

const (
	Pending PromiseState = iota
	Fulfilled
	Rejected
)

type PropertyAttribute ¶

type PropertyAttribute uint8

PropertyAttribute are the attribute flags for a property on an Object. Typical usage when setting an Object or TemplateObject property, and can also be validated when accessing a property.

const (
	// None.
	None PropertyAttribute = 0
	// ReadOnly, ie. not writable.
	ReadOnly PropertyAttribute = 1 << iota
	// DontEnum, ie. not enumerable.
	DontEnum
	// DontDelete, ie. not configurable.
	DontDelete
)

type PropertyCallbackInfo ¶

type PropertyCallbackInfo struct {
	// contains filtered or unexported fields
}

func (PropertyCallbackInfo) Context ¶

func (c PropertyCallbackInfo) Context() *Context

This returns the JavaScript object on which a property was accessed

func (PropertyCallbackInfo) Holder ¶

func (c PropertyCallbackInfo) Holder() *Object

Holder returns the object in the prototype chain where the property handler was defined.

func (PropertyCallbackInfo) This ¶

func (c PropertyCallbackInfo) This() *Object

This returns the JavaScript object on which a property was accessed

type PropertyDescriptor ¶

type PropertyDescriptor struct{}

type RegExp ¶

type RegExp struct {
	*Object
}

RegExp is a JavaScript RegExp object.

func NewRegExp ¶

func NewRegExp(ctx *Context, pattern string, flags RegExpFlags) (*RegExp, error)

NewRegExp creates a new RegExp object with the given pattern and flags.

func (*RegExp) Flags ¶

func (r *RegExp) Flags() (string, error)

Flags returns the flags string (e.g., "gi") of this RegExp.

func (*RegExp) Source ¶

func (r *RegExp) Source() (string, error)

Source returns the pattern source text of this RegExp.

func (*RegExp) Test ¶

func (r *RegExp) Test(str Valuer) (bool, error)

Test tests the given string against this RegExp. Returns true if it matches.

type RegExpFlags ¶

type RegExpFlags int

RegExpFlags are flags that can be passed to NewRegExp.

const (
	RegExpNone       RegExpFlags = 0
	RegExpGlobal     RegExpFlags = 1
	RegExpIgnoreCase RegExpFlags = 2
	RegExpMultiline  RegExpFlags = 4
	RegExpSticky     RegExpFlags = 8
	RegExpUnicode    RegExpFlags = 16
	RegExpDotAll     RegExpFlags = 32
)

type RejectedPromiseCallback ¶

type RejectedPromiseCallback = func(PromiseRejectMessage)

RejectedPromiseCallback is the type for a callback clients can supply to be notified of rejected promises.

type ResolveModuler ¶

type ResolveModuler interface {
	ResolveModule(ctx *Context, spec string, attr ImportAttributes, referrer *Module) (*Module, error)
}

type Set ¶

type Set struct {
	*Object
}

Set is a JavaScript Set object.

func NewSet ¶

func NewSet(ctx *Context) (*Set, error)

NewSet creates a new empty Set.

func (*Set) SetAdd ¶

func (s *Set) SetAdd(val Valuer)

SetAdd adds a value to the Set.

func (*Set) SetDelete ¶

func (s *Set) SetDelete(val Valuer) bool

SetDelete removes a value from the Set. Returns true if it was present.

func (*Set) SetHas ¶

func (s *Set) SetHas(val Valuer) bool

SetHas returns true if the value exists in the Set.

func (*Set) SetSize ¶

func (s *Set) SetSize() int

SetSize returns the number of elements in the Set.

type Symbol ¶

type Symbol struct {
	*Value
}

A Symbol represents a JavaScript symbol (ECMA-262 edition 6).

func SymbolAsyncIterator ¶

func SymbolAsyncIterator(
	iso *Isolate,
) *Symbol

func SymbolHasInstance ¶

func SymbolHasInstance(iso *Isolate) *Symbol

func SymbolIsConcatSpreadable ¶

func SymbolIsConcatSpreadable(iso *Isolate) *Symbol

func SymbolIterator ¶

func SymbolIterator(iso *Isolate) *Symbol

func SymbolMatch ¶

func SymbolMatch(iso *Isolate) *Symbol

func SymbolReplace ¶

func SymbolReplace(iso *Isolate) *Symbol

func SymbolSearch ¶

func SymbolSearch(iso *Isolate) *Symbol

func SymbolSplit ¶

func SymbolSplit(iso *Isolate) *Symbol

func SymbolToPrimitive ¶

func SymbolToPrimitive(iso *Isolate) *Symbol

func SymbolToStringTag ¶

func SymbolToStringTag(iso *Isolate) *Symbol

func SymbolUnscopables ¶

func SymbolUnscopables(iso *Isolate) *Symbol

func (*Symbol) Description ¶

func (sym *Symbol) Description() string

Description returns the string representation of the symbol, e.g. "Symbol.asyncIterator".

func (*Symbol) String ¶

func (sym *Symbol) String() string

String returns Description().

type UnboundScript ¶

type UnboundScript struct {
	// contains filtered or unexported fields
}

func (*UnboundScript) CreateCodeCache ¶

func (u *UnboundScript) CreateCodeCache() *CompilerCachedData

Create a code cache from the unbound script.

func (*UnboundScript) Run ¶

func (u *UnboundScript) Run(ctx *Context) (*Value, error)

Run will bind the unbound script to the provided context and run it. If the context provided does not belong to the same isolate that the script was compiled in, Run will panic. If an error occurs, it will be of type `JSError`.

type Value ¶

type Value struct {
	// contains filtered or unexported fields
}

Value represents all Javascript values and objects

func JSONParse ¶

func JSONParse(ctx *Context, str string) (*Value, error)

JSONParse tries to parse the string and returns it as *Value if successful. Any JS errors will be returned as `JSError`.

Example ¶
package main

import (
	"fmt"

	v8 "github.com/iquirino/v8go"
)

func main() {
	ctx := v8.NewContext()
	defer ctx.Isolate().Dispose()
	defer ctx.Close()
	val, _ := v8.JSONParse(ctx, `{"foo": "bar"}`)
	fmt.Println(val)
}
Output:
[object Object]

func NewArrayBufferFromBytes ¶

func NewArrayBufferFromBytes(ctx *Context, data []byte) (*Value, error)

NewArrayBufferFromBytes creates a new ArrayBuffer containing a copy of the given bytes. The data is copied into V8's heap — modifications to the original slice won't affect it.

func NewUint8ArrayFromBytes ¶

func NewUint8ArrayFromBytes(ctx *Context, data []byte) (*Value, error)

NewUint8ArrayFromBytes creates a new Uint8Array containing a copy of the given bytes. This is the equivalent of `new Uint8Array([...data])` in JS.

func NewValue ¶

func NewValue(iso *Isolate, val interface{}) (*Value, error)

NewValue will create a primitive value. Supported values types to create are:

string -> V8::String
int32 -> V8::Integer
uint32 -> V8::Integer
int64 -> V8::BigInt
uint64 -> V8::BigInt
bool -> V8::Boolean
*big.Int -> V8::BigInt

func NewValueExternal ¶

func NewValueExternal(iso *Isolate, val unsafe.Pointer) *Value

NewValueExternal allows storing an unsafe.Pointer in a value. This function is discouraged, prefer using NewValueExternalHandle instead. This function exists primarily for code that already uses unsafe pointers.

An unsafe pointer can be read using Value.External

func NewValueExternalHandle ¶

func NewValueExternalHandle(iso *Isolate, val cgo.Handle) *Value

NewValueExternalHandle can store a reference to a Go object as an "external" v8 value, by using a cgo.Handle. The primary use case is when exposing native Go objects to JavaScript code.

Native external values can be stored as "internal fields" on v8 objects; using Object.SetInternalField.

Warning: A cgo handle should be deleted through a call to cgo.Handle.Delete when you are done with the object. Unfortunately v8go doesn't yet support a callback when a JavaScript object is garbage collected.

For a v8 context that is not short lived, this will cause a memory leak if new objects are created continuously. For a short-lived context, be sure to delete the cgo handles when the context is disposed.

func Null ¶

func Null(iso *Isolate) *Value

Null returns the `null` JS value

func Undefined ¶

func Undefined(iso *Isolate) *Value

Undefined returns the `undefined` JS value

func (*Value) ArrayBufferGetContents ¶

func (v *Value) ArrayBufferGetContents() ([]byte, func(), error)

ArrayBufferGetContents returns the contents of an ArrayBuffer as a byte slice. The returned slice is backed by V8's memory — do not use after calling release.

func (*Value) ArrayIndex ¶

func (v *Value) ArrayIndex() (idx uint32, ok bool)

ArrayIndex attempts to converts a string to an array index. Returns ok false if conversion fails.

func (*Value) AsArray ¶

func (v *Value) AsArray() (*Array, error)

AsArray will cast the value to the Array type. If the value is not an Array then an error is returned.

func (*Value) AsDate ¶

func (v *Value) AsDate() (*Date, error)

AsDate will cast the value to the Date type. If the value is not a Date then an error is returned.

func (*Value) AsException ¶

func (v *Value) AsException() (*Exception, error)

func (*Value) AsFunction ¶

func (v *Value) AsFunction() (*Function, error)

func (*Value) AsMap ¶

func (v *Value) AsMap() (*Map, error)

AsMap casts the value to a Map. Returns error if not a Map.

func (*Value) AsObject ¶

func (v *Value) AsObject() (*Object, error)

AsObject will cast the value to the Object type. If the value is not an Object then an error is returned. Use `value.Object()` to do the JS equivalent of `Object(value)`.

func (*Value) AsPromise ¶

func (v *Value) AsPromise() (*Promise, error)

func (*Value) AsSet ¶

func (v *Value) AsSet() (*Set, error)

AsSet casts the value to a Set. Returns error if not a Set.

func (*Value) AsSymbol ¶

func (v *Value) AsSymbol() (*Symbol, error)

AsSymbol will cast the value to the Symbol type. If the value is not a Symbol then an error is returned.

func (*Value) BigInt ¶

func (v *Value) BigInt() *big.Int

BigInt perform the equivalent of `BigInt(value)` in JS.

func (*Value) Boolean ¶

func (v *Value) Boolean() bool

Boolean perform the equivalent of `Boolean(value)` in JS. This can never fail.

func (*Value) DetailString ¶

func (v *Value) DetailString() string

DetailString provide a string representation of this value usable for debugging.

func (*Value) External ¶

func (v *Value) External() unsafe.Pointer

External retrieves an unsafe.Pointer. This value must have been created using NewValueExternal.

The use of this pair of functions is discouraged. Prefer using NewValueExternalHandle/Value.ExternalHandle instead.

This will return nil, if the value does not contain an external value.

func (*Value) ExternalHandle ¶

func (v *Value) ExternalHandle() cgo.Handle

ExternalHandle retrieves the cgo.Handle from a Value that was created using NewValueExternalHandle.

This will return an zero handle if the value is not an external value.

Warning, reading a value that was created using NewValueExternal is invalid, but will not be detected by v8go. Prefer using only handles if possible.

func (*Value) Format ¶

func (v *Value) Format(s fmt.State, verb rune)

Format implements the fmt.Formatter interface to provide a custom formatter primarily to output the detail string (for debugging) with `%+v` verb.

func (*Value) Int32 ¶

func (v *Value) Int32() int32

Int32 perform the equivalent of `Number(value)` in JS and convert the result to a signed 32-bit integer by performing the steps in https://tc39.es/ecma262/#sec-toint32.

func (*Value) Integer ¶

func (v *Value) Integer() int64

Integer perform the equivalent of `Number(value)` in JS and convert the result to an integer. Negative values are rounded up, positive values are rounded down. NaN is converted to 0. Infinite values yield undefined results.

func (*Value) IsArgumentsObject ¶

func (v *Value) IsArgumentsObject() bool

IsArgumentsObject returns true if this value is an Arguments object.

func (*Value) IsArray ¶

func (v *Value) IsArray() bool

IsArray returns true if this value is an array. Note that it will return false for a `Proxy` of an array.

func (*Value) IsArrayBuffer ¶

func (v *Value) IsArrayBuffer() bool

IsArrayBuffer returns true if this value is an `ArrayBuffer`.

func (*Value) IsArrayBufferView ¶

func (v *Value) IsArrayBufferView() bool

IsArrayBufferView returns true if this value is an `ArrayBufferView`.

func (*Value) IsAsyncFunction ¶

func (v *Value) IsAsyncFunction() bool

IsAsyncFunc returns true if this value is an async function.

func (*Value) IsBigInt ¶

func (v *Value) IsBigInt() bool

IsBigInt returns true if this value is a bigint. This is equivalent to `typeof value === 'bigint'` in JS.

func (*Value) IsBigInt64Array ¶

func (v *Value) IsBigInt64Array() bool

IsBigInt64Array returns true if this value is a `BigInt64Array`.

func (*Value) IsBigIntObject ¶

func (v *Value) IsBigIntObject() bool

IsBigIntObject returns true if this value is a BigInt object.

func (*Value) IsBigUint64Array ¶

func (v *Value) IsBigUint64Array() bool

IsBigUint64Array returns true if this value is a BigUint64Array`.

func (*Value) IsBoolean ¶

func (v *Value) IsBoolean() bool

IsBoolean returns true if this value is boolean. This is equivalent to `typeof value === 'boolean'` in JS.

func (*Value) IsDataView ¶

func (v *Value) IsDataView() bool

IsDataView returns true if this value is a `DataView`.

func (*Value) IsDate ¶

func (v *Value) IsDate() bool

IsDate returns true if this value is a `Date`.

func (*Value) IsExternal ¶

func (v *Value) IsExternal() bool

IsExternal returns true if this value is an `External` object.

func (*Value) IsFalse ¶

func (v *Value) IsFalse() bool

IsFalse returns true if this value is false. This is not the same as `!BooleanValue()`. The latter performs a conversion to boolean, i.e. the result of `!Boolean(value)` in JS, whereas this checks `value === false`.

func (*Value) IsFloat32Array ¶

func (v *Value) IsFloat32Array() bool

IsFloat32Array returns true if this value is a `Float32Array`.

func (*Value) IsFloat64Array ¶

func (v *Value) IsFloat64Array() bool

IsFloat64Array returns true if this value is a `Float64Array`.

func (*Value) IsFunction ¶

func (v *Value) IsFunction() bool

IsFunction returns true if this value is a function. This is equivalent to `typeof value === 'function'` in JS.

func (*Value) IsGeneratorFunction ¶

func (v *Value) IsGeneratorFunction() bool

Is IsGeneratorFunc returns true if this value is a Generator function.

func (*Value) IsGeneratorObject ¶

func (v *Value) IsGeneratorObject() bool

IsGeneratorObject returns true if this value is a Generator object (iterator).

func (*Value) IsInt8Array ¶

func (v *Value) IsInt8Array() bool

IsInt8Array returns true if this value is an `Int8Array`.

func (*Value) IsInt16Array ¶

func (v *Value) IsInt16Array() bool

IsInt16Array returns true if this value is an `Int16Array`.

func (*Value) IsInt32 ¶

func (v *Value) IsInt32() bool

IsInt32 returns true if this value is a 32-bit signed integer.

func (*Value) IsInt32Array ¶

func (v *Value) IsInt32Array() bool

IsInt32Array returns true if this value is an `Int32Array`.

func (*Value) IsMap ¶

func (v *Value) IsMap() bool

IsMap returns true if this value is a `Map`.

func (*Value) IsMapIterator ¶

func (v *Value) IsMapIterator() bool

IsMapIterator returns true if this value is a `Map` Iterator.

func (*Value) IsModuleNamespaceObject ¶

func (v *Value) IsModuleNamespaceObject() bool

IsModuleNamespaceObject returns true if the value is a `Module` Namespace `Object`.

func (*Value) IsName ¶

func (v *Value) IsName() bool

IsName returns true if this value is a symbol or a string. This is equivalent to `typeof value === 'string' || typeof value === 'symbol'` in JS.

func (*Value) IsNativeError ¶

func (v *Value) IsNativeError() bool

IsNativeError returns true if this value is a NativeError.

func (*Value) IsNull ¶

func (v *Value) IsNull() bool

IsNull returns true if this value is the null value. See ECMA-262 4.3.11.

func (*Value) IsNullOrUndefined ¶

func (v *Value) IsNullOrUndefined() bool

IsNullOrUndefined returns true if this value is either the null or the undefined value. See ECMA-262 4.3.11. and 4.3.12 This is equivalent to `value == null` in JS.

func (*Value) IsNumber ¶

func (v *Value) IsNumber() bool

IsNumber returns true if this value is a number. This is equivalent to `typeof value === 'number'` in JS.

func (*Value) IsNumberObject ¶

func (v *Value) IsNumberObject() bool

IsNumberObject returns true if this value is a `Number` object.

func (*Value) IsObject ¶

func (v *Value) IsObject() bool

IsObject returns true if this value is an object.

func (*Value) IsPromise ¶

func (v *Value) IsPromise() bool

IsPromise returns true if this value is a `Promise`.

func (*Value) IsProxy ¶

func (v *Value) IsProxy() bool

IsProxy returns true if this value is a JavaScript `Proxy`.

func (*Value) IsRegExp ¶

func (v *Value) IsRegExp() bool

IsRegExp returns true if this value is a `RegExp`.

func (*Value) IsSet ¶

func (v *Value) IsSet() bool

IsSet returns true if this value is a `Set`.

func (*Value) IsSetIterator ¶

func (v *Value) IsSetIterator() bool

IsSetIterator returns true if this value is a `Set` Iterator.

func (*Value) IsSharedArrayBuffer ¶

func (v *Value) IsSharedArrayBuffer() bool

IsSharedArrayBuffer returns true if this value is a `SharedArrayBuffer`.

func (*Value) IsString ¶

func (v *Value) IsString() bool

IsString returns true if this value is an instance of the String type. See ECMA-262 8.4. This is equivalent to `typeof value === 'string'` in JS.

func (*Value) IsStringObject ¶

func (v *Value) IsStringObject() bool

IsStringObject returns true if this value is a `String` object.

func (*Value) IsSymbol ¶

func (v *Value) IsSymbol() bool

IsSymbol returns true if this value is a symbol. This is equivalent to `typeof value === 'symbol'` in JS.

func (*Value) IsSymbolObject ¶

func (v *Value) IsSymbolObject() bool

IsSymbolObject returns true if this value is a `Symbol` object.

func (*Value) IsTrue ¶

func (v *Value) IsTrue() bool

IsTrue returns true if this value is true. This is not the same as `BooleanValue()`. The latter performs a conversion to boolean, i.e. the result of `Boolean(value)` in JS, whereas this checks `value === true`.

func (*Value) IsTypedArray ¶

func (v *Value) IsTypedArray() bool

IsTypedArray returns true if this value is one of TypedArrays.

func (*Value) IsUint8Array ¶

func (v *Value) IsUint8Array() bool

IsUint8Array returns true if this value is an `Uint8Array`.

func (*Value) IsUint8ClampedArray ¶

func (v *Value) IsUint8ClampedArray() bool

IsUint8ClampedArray returns true if this value is an `Uint8ClampedArray`.

func (*Value) IsUint16Array ¶

func (v *Value) IsUint16Array() bool

IsUint16Array returns true if this value is an `Uint16Array`.

func (*Value) IsUint32 ¶

func (v *Value) IsUint32() bool

IsUint32 returns true if this value is a 32-bit unsigned integer.

func (*Value) IsUint32Array ¶

func (v *Value) IsUint32Array() bool

IsUint32Array returns true if this value is an `Uint32Array`.

func (*Value) IsUndefined ¶

func (v *Value) IsUndefined() bool

IsUndefined returns true if this value is the undefined value. See ECMA-262 4.3.10.

func (*Value) IsWasmModuleObject ¶

func (v *Value) IsWasmModuleObject() bool

IsWasmModuleObject returns true if this value is a `WasmModuleObject`.

func (*Value) IsWeakMap ¶

func (v *Value) IsWeakMap() bool

IsWeakMap returns true if this value is a `WeakMap`.

func (*Value) IsWeakSet ¶

func (v *Value) IsWeakSet() bool

IsWeakSet returns true if this value is a `WeakSet`.

func (*Value) MarshalJSON ¶

func (v *Value) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*Value) Number ¶

func (v *Value) Number() float64

Number perform the equivalent of `Number(value)` in JS.

func (*Value) Object ¶

func (v *Value) Object() (*Object, error)

Object perform the equivalent of Object(value) in JS. To just cast this value as an Object use AsObject() instead.

func (*Value) Release ¶

func (v *Value) Release()

Release this value. Using the value after calling this function will result in undefined behavior.

func (*Value) SameValue ¶

func (v *Value) SameValue(other *Value) bool

SameValue returns true if the other value is the same value. This is equivalent to `Object.is(v, other)` in JS.

func (*Value) SharedArrayBufferGetContents ¶

func (v *Value) SharedArrayBufferGetContents() ([]byte, func(), error)

func (*Value) StrictEquals ¶

func (v *Value) StrictEquals(other *Value) bool

func (*Value) String ¶

func (v *Value) String() string

String perform the equivalent of `String(value)` in JS. Primitive values are returned as-is, objects will return `[object Object]` and functions will print their definition. If the conversion fails (e.g., a proxy throws in toString()), an empty string is returned. Use StringErr for error-aware conversion.

func (*Value) StringErr ¶

func (v *Value) StringErr() (string, error)

StringErr performs the equivalent of `String(value)` in JS, returning an error if the conversion fails (e.g., a Symbol cannot be implicitly converted, or a proxy's toString() throws).

func (*Value) TypeOf ¶

func (v *Value) TypeOf() string

func (*Value) Uint32 ¶

func (v *Value) Uint32() uint32

Uint32 perform the equivalent of `Number(value)` in JS and convert the result to an unsigned 32-bit integer by performing the steps in https://tc39.es/ecma262/#sec-touint32.

type ValueError ¶

type ValueError interface {
	error
	Valuer
}

A ValueError can be returned from a FunctionCallbackWithError, and its value will be thrown as an exception in V8.

type Valuer ¶

type Valuer interface {
	// contains filtered or unexported methods
}

Valuer is an interface that reperesents anything that extends from a Value eg. Object, Array, Date etc

Directories ¶

Path Synopsis
deps
include
Generated by deps/upgrade_v8.py, DO NOT REMOVE/EDIT MANUALLY.
Generated by deps/upgrade_v8.py, DO NOT REMOVE/EDIT MANUALLY.
include/cppgc
Generated by deps/upgrade_v8.py, DO NOT REMOVE/EDIT MANUALLY.
Generated by deps/upgrade_v8.py, DO NOT REMOVE/EDIT MANUALLY.
include/libplatform
Generated by deps/upgrade_v8.py, DO NOT REMOVE/EDIT MANUALLY.
Generated by deps/upgrade_v8.py, DO NOT REMOVE/EDIT MANUALLY.
android_amd64 module
android_arm64 module
darwin_amd64 module
darwin_arm64 module
linux_amd64 module
linux_arm64 module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL