Documentation
¶
Overview ¶
Package ekuma is a JavaScript engine written in pure Go.
The API follows syscall/js where possible. The differences come from JavaScript running inside the process: there can be several VMs, an exception is returned as an error and not thrown as a panic, and the methods that run a script or call a function take a context.Context that stops them.
A context stops everything that runs under it: when a Func reads a property or calls a function, that is stopped by the context of the call that led to the Func. When a Func makes a call with another context and that context stops the call, everything stops: the outermost Go call that executes JavaScript returns the cause of that context, and the Func does not continue. A Func that recovers the stop runs no more JavaScript, and the stop continues when it returns. A context that becomes done after its call returns has no effect.
Internal operation failures return an *InternalError from the outermost Go call executing JavaScript. They stop execution without running JavaScript catch or finally blocks, discard pending jobs, and reject unfinished module evaluations. Side effects remain.
Pending promise jobs run before the outermost Go call that executes JavaScript returns, including property operations and calls that throw. Calls reentered from host callbacks leave jobs to the outermost call. An interruption discards pending jobs and closes generators whose execution it unwinds. Operations without a context can run JavaScript and jobs without a cancellation limit, unless reentered under a call with a context. VM.AwaitJobs waits for asynchronous notifications and runs their jobs.
A panic in a Func, or in another host function called by JavaScript, passes through Go calls unchanged after restoring the VM's execution state. Host callbacks may recover panics from reentrant calls. At the outermost boundary, pending jobs and unhandled rejection reports are discarded and unfinished module evaluations are rejected. Abandoned synchronous module evaluations are rejected before returning to the host. Aborted generators are closed without running JavaScript catch or finally blocks. Side effects remain, and promises for abandoned async work may remain pending. Host callbacks must not call runtime.Goexit, which leaves the VM unusable.
The ekumavalidate build tag enables internal checks on the bytecode the compiler emits and on its execution by the VM.
Example (Modules) ¶
This example runs a module that imports a module and a JSON module from a file system.
package main
import (
"context"
"fmt"
"io/fs"
"path"
"testing/fstest"
"github.com/hajimehoshi/ekuma"
)
func main() {
fsys := fstest.MapFS{
"main.js": {Data: []byte(`
import { greet } from "./lib/greet.js";
import config from "./config.json" with { type: "json" };
export const message = greet(config.name);`)},
"lib/greet.js": {Data: []byte(`
export function greet(name) { return "Hello, " + name; }`)},
"config.json": {Data: []byte(`{"name": "modules"}`)},
}
var vm ekuma.VM
modules := map[string]*ekuma.Module{}
load := func(req ekuma.ModuleRequest) (*ekuma.Module, error) {
// A specifier is relative to the importing module.
name := path.Join(path.Dir(req.ReferrerName), req.Specifier)
if m, ok := modules[name]; ok {
return m, nil
}
src, err := fs.ReadFile(fsys, name)
if err != nil {
return nil, err
}
var m *ekuma.Module
if req.Attributes["type"] == "json" {
m, err = vm.ParseJSONModule(name, string(src))
} else {
m, err = vm.ParseModule(name, string(src))
}
if err != nil {
return nil, err
}
modules[name] = m
return m, nil
}
vm.SetModuleLoader(load)
m, err := load(ekuma.ModuleRequest{Specifier: "main.js"})
if err != nil {
panic(err)
}
// Evaluate loads and links the modules first.
p, err := m.Evaluate(context.Background())
if err != nil {
panic(err)
}
state, _ := p.PromiseState()
fmt.Println(state)
ns, err := m.Namespace()
if err != nil {
panic(err)
}
msg, err := ns.Get("message")
if err != nil {
panic(err)
}
fmt.Println(msg.String())
}
Output: fulfilled Hello, modules
Index ¶
- Variables
- func CopyBytesToGo(dst []byte, src Value) int
- func CopyBytesToJS(dst Value, src []byte) int
- type Func
- type InternalError
- type Module
- type ModuleRequest
- type PromiseResolver
- type PromiseState
- type Realm
- func (r *Realm) BindScript(u *UnboundScript) *Script
- func (r *Realm) FuncOf(name string, f Func) Value
- func (r *Realm) Global() Value
- func (r *Realm) NewArrayBuffer(b []byte) Value
- func (r *Realm) NewPromise() (Value, *PromiseResolver)
- func (r *Realm) NewSyntheticModule(name string, v Value) *Module
- func (r *Realm) ParseJSONModule(name, src string) (*Module, error)
- func (r *Realm) ParseModule(name, src string) (*Module, error)
- func (r *Realm) ParseScript(name, src string) (*Script, error)
- func (r *Realm) ValueOf(x any) Value
- type Script
- type ScriptError
- type SharedDataBlock
- type SyntaxError
- type Type
- type UnboundScript
- type VM
- func (vm *VM) AwaitJobs(ctx context.Context) (bool, error)
- func (vm *VM) BindScript(u *UnboundScript) *Script
- func (vm *VM) ContinuationData() any
- func (vm *VM) DetachArrayBuffer(v Value)
- func (vm *VM) FuncOf(name string, f Func) Value
- func (vm *VM) Global() Value
- func (vm *VM) InitialRealm() *Realm
- func (vm *VM) NewArrayBuffer(b []byte) Value
- func (vm *VM) NewPromise() (Value, *PromiseResolver)
- func (vm *VM) NewRealm() *Realm
- func (vm *VM) NewSyntheticModule(name string, v Value) *Module
- func (vm *VM) ParseJSONModule(name, src string) (*Module, error)
- func (vm *VM) ParseModule(name, src string) (*Module, error)
- func (vm *VM) ParseScript(name, src string) (*Script, error)
- func (vm *VM) SetCanBlock(canBlock bool)
- func (vm *VM) SetClock(now func() time.Time)
- func (vm *VM) SetImportMeta(f func(m *Module) map[string]any)
- func (vm *VM) SetLocale(locale string) error
- func (vm *VM) SetModuleLoader(f func(req ModuleRequest) (*Module, error))
- func (vm *VM) SetRandomSource(src rand.Source)
- func (vm *VM) SetTimeZone(loc *time.Location)
- func (vm *VM) SetUnhandledRejection(f func(promise, reason Value))
- func (vm *VM) ValueOf(x any) Value
- func (vm *VM) WithContinuationData(data any, f func())
- type Value
- func (v Value) BigInt() *big.Int
- func (v Value) Bool() bool
- func (v Value) Call(ctx context.Context, name string, args ...any) (Value, error)
- func (v Value) CallWithValueKey(ctx context.Context, key Value, args ...any) (Value, error)
- func (v Value) Delete(name string) error
- func (v Value) DeleteWithValueKey(key Value) error
- func (v Value) Equal(w Value) bool
- func (v Value) Float() float64
- func (v Value) Get(name string) (Value, error)
- func (v Value) GetWithValueKey(key Value) (Value, error)
- func (v Value) Index(i int) (Value, error)
- func (v Value) InstanceOf(t Value) (bool, error)
- func (v Value) Int() int
- func (v Value) Invoke(ctx context.Context, args ...any) (Value, error)
- func (v Value) IsNaN() bool
- func (v Value) IsNull() bool
- func (v Value) IsPromise() bool
- func (v Value) IsUndefined() bool
- func (v Value) New(ctx context.Context, args ...any) (Value, error)
- func (v Value) PromiseState() (PromiseState, Value)
- func (v Value) Set(name string, x any) error
- func (v Value) SetIndex(i int, x any) error
- func (v Value) SetWithValueKey(key Value, x any) error
- func (v Value) SharedDataBlock() *SharedDataBlock
- func (v Value) String() string
- func (v Value) Truthy() bool
- func (v Value) Type() Type
- type ValueError
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrRunning = errors.New("ekuma: AwaitJobs called while JavaScript runs")
ErrRunning is returned by VM.AwaitJobs when the VM is running JavaScript.
Functions ¶
func CopyBytesToGo ¶
CopyBytesToGo copies bytes from the Uint8Array or Uint8ClampedArray src to dst and returns the number of bytes copied, which is the minimum of their lengths. A detached or out of bounds src has no bytes. It panics with a *ValueError when src is neither a Uint8Array nor a Uint8ClampedArray.
func CopyBytesToJS ¶
CopyBytesToJS copies bytes from src to the Uint8Array or Uint8ClampedArray dst and returns the number of bytes copied, which is the minimum of their lengths. A detached or out of bounds dst has no bytes. It panics with a *ValueError when dst is neither a Uint8Array nor a Uint8ClampedArray, or is backed by an immutable ArrayBuffer.
Types ¶
type Func ¶
Func is a function implemented in Go.
args is valid only until the function returns. The result is converted with Realm.ValueOf of the realm of the function, except that a *big.Int result of more than 2^30 bits throws a RangeError, as a BigInt operation of JavaScript with such a result does.
A non-nil error is thrown as a JavaScript exception: a *ScriptError throws its value, and any other error throws a new Error object made from the error, with its message. ScriptError.Unwrap of a *ScriptError holding that object returns the error.
type InternalError ¶
type InternalError struct {
// Err is the underlying failure.
Err error
}
InternalError is a failure of an internal engine operation.
func (*InternalError) Error ¶
func (e *InternalError) Error() string
func (*InternalError) Unwrap ¶
func (e *InternalError) Unwrap() error
Unwrap returns the underlying failure.
type Module ¶
type Module struct {
// contains filtered or unexported fields
}
Module is a module record of a VM.
Running a module involves three steps: Module.LoadRequestedModules, Module.Link and Module.Evaluate. Each step first completes any unfinished prerequisites. Module.Namespace performs the first two steps. These methods may be called in any order; completed steps are not repeated. A call from inside the module loader that has to load a module that is still being loaded returns a *ScriptError holding a TypeError.
func (*Module) Evaluate ¶
Evaluate evaluates m and its dependencies and returns a promise for the evaluation. It calls Module.Link first. An exception thrown by a module rejects the promise. Evaluating a source text module again returns the same promise. A synthetic or JSON module returns a new fulfilled promise each time.
Pending promise jobs run before the outermost Go call that executes JavaScript returns. An Evaluate call made from a host callback can return with jobs still pending. An interruption discards pending jobs.
The error is the error of Module.Link. When ctx is done, the evaluation stops at its next loop iteration or call, and the error is the cause of ctx. Any call that a context stops ends the evaluations in progress with an Error, which rejects their promises: ScriptError.Unwrap of a *ScriptError holding such a reason returns the cause of ctx. Internal operation failures return an *InternalError.
func (*Module) Link ¶
Link links m and its dependencies: it resolves their imports without evaluating module code. It calls Module.LoadRequestedModules first. Module.Evaluate and Module.Namespace call it, so calling it is needed only to link before evaluating. The error is the error of Module.LoadRequestedModules, or a *ScriptError holding a JavaScript SyntaxError for an import that does not resolve. Link may be retried after a failure.
func (*Module) LoadRequestedModules ¶
LoadRequestedModules loads the modules that m and its dependencies import, with the loader of the VM. Module.Link, Module.Evaluate and Module.Namespace call it, so calling it is needed only to load before linking. A failed import returns a *ScriptError holding the value thrown as described by VM.SetModuleLoader. When the loader returns an ordinary Go error, errors.Is matches that error through the returned *ScriptError.
func (*Module) Namespace ¶
Namespace returns the module namespace object of m. It calls Module.Link first, and the error is the error of Module.Link. Before m is evaluated, reading an export that is not initialized yet throws a ReferenceError.
type ModuleRequest ¶
type ModuleRequest struct {
// Realm is the realm of the code requesting the import.
Realm *Realm
// Referrer is the importing module, or nil if the import is not requested by a module.
Referrer *Module
// ReferrerName is the name of the importing script or module, or empty.
ReferrerName string
// Specifier is the module specifier of the import.
Specifier string
// Attributes are the import attributes of the with clause.
Attributes map[string]string
}
ModuleRequest is a request to load a module.
type PromiseResolver ¶
type PromiseResolver struct {
// contains filtered or unexported fields
}
PromiseResolver resolves or rejects the promise that Realm.NewPromise returns with it, as the resolving functions of the promise do: once the promise is resolved, later calls of PromiseResolver.Resolve and PromiseResolver.Reject have no effect. A PromiseResolver must not be used while its VM is used on another goroutine.
func (*PromiseResolver) Reject ¶
func (r *PromiseResolver) Reject(ctx context.Context, v any) error
Reject is like PromiseResolver.Resolve, but rejects the promise with v. A rejected promise without a handler is reported to the callback of VM.SetUnhandledRejection after the jobs ran, unless ctx stops them.
func (*PromiseResolver) Resolve ¶
func (r *PromiseResolver) Resolve(ctx context.Context, v any) error
Resolve resolves the promise with VM.ValueOf(v), or with Realm.ValueOf(v) of its realm for a promise of another realm. A thenable is adopted, and reading its then property can run JavaScript. The pending jobs run before Resolve returns, unless it is called from a host callback.
If ctx is already done, Resolve does not attempt to settle the promise. If ctx stops JavaScript at a loop iteration or call, pending jobs are discarded. An interruption after resolution begins can leave the promise pending even though later calls to the resolver have no effect.
If ctx stops an outermost call to Resolve, Resolve returns the cause of ctx. If ctx stops a call from a host callback, the interruption unwinds the callback and the outermost call reports the cause. Internal operation failures return an *InternalError.
type PromiseState ¶
type PromiseState int
PromiseState is the state of a promise.
const ( PromisePending PromiseState = iota PromiseFulfilled PromiseRejected )
func (PromiseState) String ¶
func (s PromiseState) String() string
type Realm ¶
type Realm struct {
// contains filtered or unexported fields
}
Realm is a realm of a VM: a global object with its own standard built-in objects.
The realms of a VM share its promise jobs, settings and other state, except for their global objects and built-in objects. Values may pass between realms. A realm is not a security boundary: an object of a realm gives access to the built-in objects of its realm.
func (*Realm) BindScript ¶
func (r *Realm) BindScript(u *UnboundScript) *Script
BindScript returns the script of u for r: the script that Realm.ParseScript of r returns for the name and source text of u.
func (*Realm) FuncOf ¶
FuncOf is like VM.FuncOf, but the function belongs to and runs in r. If f returns a *ScriptError, directly or wrapped, the function throws its stored value, which may be a primitive or an object from any realm of the same VM. For any other non-nil error, the function throws a new Error object in r.
func (*Realm) NewArrayBuffer ¶
NewArrayBuffer is like VM.NewArrayBuffer, but the ArrayBuffer belongs to r.
func (*Realm) NewPromise ¶
func (r *Realm) NewPromise() (Value, *PromiseResolver)
NewPromise returns a new pending promise of r and the resolver that settles it.
func (*Realm) NewSyntheticModule ¶
NewSyntheticModule returns a module of r whose only export is default, with the value v. It panics if v belongs to another VM.
func (*Realm) ParseJSONModule ¶
ParseJSONModule returns a JSON module of r: a module whose only export is default, with the value returned by JSON.parse in r for src. The error is a *ScriptError holding a JavaScript SyntaxError when src is not valid JSON.
func (*Realm) ParseModule ¶
ParseModule parses src as the source text of a module of r. name identifies the module in error messages and stack traces, and in the ModuleRequest.ReferrerName of its imports. The error is a *SyntaxError when src is not a valid module.
func (*Realm) ParseScript ¶
ParseScript parses src as the source text of a script of r. name identifies the script in error messages and stack traces, and in the ModuleRequest.ReferrerName of its import() calls. The error is a *SyntaxError when src is not a valid script.
type Script ¶
type Script struct {
// contains filtered or unexported fields
}
Script is a script of a realm, from Realm.ParseScript or Realm.BindScript.
func (*Script) Evaluate ¶
Evaluate evaluates s and returns its completion value. A script may be evaluated more than once, but evaluating it again throws a JavaScript SyntaxError when s declares a top-level let, const or class.
Pending promise jobs run before the outermost Go call that executes JavaScript returns. An Evaluate call made from a host callback can return with jobs still pending. An interruption discards pending jobs.
The error is a *ScriptError when the script throws. When ctx is done, the script stops at its next loop iteration or call, and the error is the cause of ctx. Internal operation failures return an *InternalError.
type ScriptError ¶
type ScriptError struct {
// Value is the thrown value.
Value Value
}
ScriptError is a JavaScript exception: one that reached Go, or one for a Func to throw.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"github.com/hajimehoshi/ekuma"
)
func main() {
var vm ekuma.VM
s, err := vm.ParseScript("order.js", `throw { code: "OUT_OF_STOCK" }`)
if err != nil {
panic(err)
}
_, err = s.Evaluate(context.Background())
exception, ok := errors.AsType[*ekuma.ScriptError](err)
if !ok {
panic(fmt.Sprintf("expected a JavaScript exception, got %v", err))
}
code, err := exception.Value.Get("code")
if err != nil {
panic(err)
}
fmt.Println(code.String())
}
Output: OUT_OF_STOCK
func (*ScriptError) Error ¶
func (e *ScriptError) Error() string
Error returns the stack trace or the message of a thrown error object, and a description of any other thrown value. It runs no JavaScript.
func (*ScriptError) Unwrap ¶
func (e *ScriptError) Unwrap() error
Unwrap returns the Go error that e.Value was made from, or nil when it was not.
type SharedDataBlock ¶
type SharedDataBlock struct {
// contains filtered or unexported fields
}
SharedDataBlock is the memory of a SharedArrayBuffer, usable by any VM on any goroutine.
type SyntaxError ¶
type SyntaxError struct {
// File is the name of the script or module.
File string
// Line is the 1-based line number of the error.
Line int
Message string
}
SyntaxError reports a failure to parse or compile a script or module.
func (*SyntaxError) Error ¶
func (e *SyntaxError) Error() string
type Type ¶
type Type int
Type is the type of a JavaScript value. Null has type TypeNull, and callable objects have type TypeFunction, including those with [[IsHTMLDDA]].
type UnboundScript ¶
type UnboundScript struct {
// contains filtered or unexported fields
}
UnboundScript is a script parsed for no particular VM, which Realm.BindScript binds to a realm. An UnboundScript is immutable: any number of VMs and realms may bind it, also from different goroutines at the same time.
func ParseUnboundScript ¶
func ParseUnboundScript(name, src string) (*UnboundScript, error)
ParseUnboundScript parses src as the source text of a script, as Realm.ParseScript does, but for no particular VM. The error is a *SyntaxError when src is not a valid script.
Example ¶
package main
import (
"context"
"fmt"
"github.com/hajimehoshi/ekuma"
)
func main() {
s, err := ekuma.ParseUnboundScript("greeting.js", `"Hello, " + name`)
if err != nil {
panic(err)
}
for _, name := range []string{"Alice", "Bob"} {
var vm ekuma.VM
if err := vm.Global().Set("name", name); err != nil {
panic(err)
}
v, err := vm.BindScript(s).Evaluate(context.Background())
if err != nil {
panic(err)
}
fmt.Println(v.String())
}
}
Output: Hello, Alice Hello, Bob
type VM ¶
type VM struct {
// contains filtered or unexported fields
}
VM is a JavaScript virtual machine with the standard built-in objects. The zero value is ready to use. A VM must not be copied after first use. A VM and its values and realms must not be used from more than one goroutine at a time.
func (*VM) AwaitJobs ¶
AwaitJobs runs pending jobs, waiting for an Atomics.waitAsync waiter to be notified or time out if necessary. It reports true if jobs were run, or false without blocking if there are no pending jobs or asynchronous waiters. It returns ErrRunning if the VM is running JavaScript, or the cause of ctx if ctx is already done or interrupts the wait or job execution.
func (*VM) BindScript ¶
func (vm *VM) BindScript(u *UnboundScript) *Script
BindScript is Realm.BindScript of the initial realm.
func (*VM) ContinuationData ¶
ContinuationData returns the continuation data set by the innermost VM.WithContinuationData call or running job, or nil if there is none.
func (*VM) DetachArrayBuffer ¶
DetachArrayBuffer detaches the ArrayBuffer v, so that v and its views have no bytes. Detaching a detached ArrayBuffer does nothing. DetachArrayBuffer panics with a *ValueError when v is not a mutable ArrayBuffer.
func (*VM) FuncOf ¶
FuncOf returns a JavaScript function of the initial realm that calls f. name is the name of the function, which stack traces show. FuncOf panics when f is nil.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"strings"
"github.com/hajimehoshi/ekuma"
)
func main() {
var vm ekuma.VM
uppercase := vm.FuncOf("uppercase", func(_ ekuma.Value, args []ekuma.Value) (any, error) {
if len(args) != 1 || args[0].Type() != ekuma.TypeString {
return nil, errors.New("uppercase expects one string")
}
return strings.ToUpper(args[0].String()), nil
})
if err := vm.Global().Set("uppercase", uppercase); err != nil {
panic(err)
}
s, err := vm.ParseScript("greeting.js", `"Hello, " + uppercase("Ekuma")`)
if err != nil {
panic(err)
}
v, err := s.Evaluate(context.Background())
if err != nil {
panic(err)
}
fmt.Println(v.String())
}
Output: Hello, EKUMA
func (*VM) InitialRealm ¶
InitialRealm returns the realm created with vm, in which the methods of vm operate.
func (*VM) NewArrayBuffer ¶
NewArrayBuffer returns an ArrayBuffer of the initial realm whose bytes are b, without copying. Its length is len(b) and does not change.
The VM reads and writes b only during calls into this package, and never after the ArrayBuffer is detached with VM.DetachArrayBuffer. Go may read and write b whenever it may call the VM, including in a Func, and either side sees the writes of the other at once.
JavaScript cannot detach the ArrayBuffer: its transfer, transferToFixedLength and transferToImmutable methods throw a TypeError. NewArrayBuffer panics when b is longer than an ArrayBuffer may be.
Example ¶
package main
import (
"context"
"fmt"
"github.com/hajimehoshi/ekuma"
)
func main() {
var vm ekuma.VM
pixels := []byte{10, 20, 30, 255}
if err := vm.Global().Set("pixels", vm.NewArrayBuffer(pixels)); err != nil {
panic(err)
}
s, err := vm.ParseScript("invert.js", `
const rgba = new Uint8Array(pixels);
for (let i = 0; i < 3; i++) {
rgba[i] = 255 - rgba[i];
}
`)
if err != nil {
panic(err)
}
if _, err := s.Evaluate(context.Background()); err != nil {
panic(err)
}
fmt.Println(pixels)
}
Output: [245 235 225 255]
func (*VM) NewPromise ¶
func (vm *VM) NewPromise() (Value, *PromiseResolver)
NewPromise is Realm.NewPromise of the initial realm.
Example ¶
package main
import (
"context"
"fmt"
"github.com/hajimehoshi/ekuma"
)
func main() {
ctx := context.Background()
var vm ekuma.VM
promise, resolver := vm.NewPromise()
if err := vm.Global().Set("message", promise); err != nil {
panic(err)
}
s, err := vm.ParseScript("greeting.js", `message.then((name) => "Hello, " + name)`)
if err != nil {
panic(err)
}
greeting, err := s.Evaluate(ctx)
if err != nil {
panic(err)
}
state, _ := greeting.PromiseState()
fmt.Println(state)
if err := resolver.Resolve(ctx, "Ekuma"); err != nil {
panic(err)
}
state, value := greeting.PromiseState()
fmt.Println(state, value.String())
}
Output: pending fulfilled Hello, Ekuma
func (*VM) NewRealm ¶
NewRealm returns a new realm of vm.
Example ¶
package main
import (
"context"
"fmt"
"github.com/hajimehoshi/ekuma"
)
func main() {
var vm ekuma.VM
r := vm.NewRealm()
if err := vm.Global().Set("other", r.Global()); err != nil {
fmt.Println(err)
return
}
s, err := vm.ParseScript("main.js", `
Array.prototype.first = function() { return this[0]; };
[typeof [].first, typeof other.eval("[]").first, other.Array === Array].join()`)
if err != nil {
fmt.Println(err)
return
}
v, err := s.Evaluate(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(v)
}
Output: function,undefined,false
func (*VM) NewSyntheticModule ¶
NewSyntheticModule is Realm.NewSyntheticModule of the initial realm.
func (*VM) ParseJSONModule ¶
ParseJSONModule is Realm.ParseJSONModule of the initial realm.
func (*VM) ParseModule ¶
ParseModule is Realm.ParseModule of the initial realm.
func (*VM) ParseScript ¶
ParseScript is Realm.ParseScript of the initial realm.
Example ¶
This example parses a script once and evaluates it several times.
package main
import (
"context"
"fmt"
"github.com/hajimehoshi/ekuma"
)
func main() {
var vm ekuma.VM
s, err := vm.ParseScript("count.js", `globalThis.n = (globalThis.n ?? 0) + 1`)
if err != nil {
fmt.Println(err)
return
}
for range 3 {
v, err := s.Evaluate(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(v.Int())
}
}
Output: 1 2 3
func (*VM) SetCanBlock ¶
SetCanBlock sets whether Atomics.wait may block the VM. The default is false.
func (*VM) SetClock ¶
SetClock sets now as the clock that gives the current time to Date, Temporal.Now, the default date of Intl.DateTimeFormat, and the timeouts of Atomics.wait and Atomics.waitAsync. A nil now restores time.Now. Only the instant of a time matters, not its location; VM.SetTimeZone sets the time zone. A timeout ends no earlier than the clock passes it, and for Atomics.wait no earlier than its duration in real time. A time outside the range of Date reads as the nearest end of the range. now is called on the goroutine that runs JavaScript in the VM.
func (*VM) SetImportMeta ¶
SetImportMeta sets f as the implementation of HostGetImportMetaProperties. On first use of import.meta in a module, f supplies its properties, which are converted with Realm.ValueOf in the module's realm. A nil f supplies no properties.
A reentrant access during f sees the same object, which receives the properties after f returns. If f panics, the next access retries initialization on that object.
func (*VM) SetLocale ¶
SetLocale sets the default locale for locale-sensitive operations in every realm. A locale that is not available uses its longest available prefix, such as "ja" for "ja-XX", and an empty locale or one without an available prefix uses the host default. Existing Intl instances keep their locale. A malformed locale returns an error without changing the default.
func (*VM) SetModuleLoader ¶
func (vm *VM) SetModuleLoader(f func(req ModuleRequest) (*Module, error))
SetModuleLoader sets f as the implementation of HostLoadImportedModule, which import declarations and import() use. f must return a *Module belonging to vm and return the same *Module for repeated requests for the same module.
The error of f is thrown the way the error of a Func is, except that a *SyntaxError throws a JavaScript SyntaxError. import() rejects its promise with it, and the methods of Module return it as a *ScriptError.
Unsupported attributes cause a SyntaxError when loading a static import and cause import() to reject its promise with a TypeError.
An import fails with a TypeError when there is no loader, when f returns a nil *Module without an error, or when the module is being loaded by a call that has not finished. A nil f removes the loader. The loader applies to subsequent module loads. Already loaded modules retain their loaded dependencies.
func (*VM) SetRandomSource ¶
SetRandomSource sets src as the source of random numbers for Math.random. A nil src restores the default, a source that is seeded randomly. The source applies to the later calls of Math.random, which return the numbers that rand.New(src).Float64 would.
func (*VM) SetTimeZone ¶
SetTimeZone sets loc as the local time zone for Date, the system time zone for Temporal, and the default time zone for new Intl.DateTimeFormat instances. A nil loc restores the local time zone of the host. Date uses loc's rules when loc is time.Local or the platform does not recognize its name. Otherwise Date uses the platform's rules for that name. Temporal and Intl resolve the zone by identifier even for time.Local. If loc has no usable identifier, they use its current UTC offset.
func (*VM) SetUnhandledRejection ¶
SetUnhandledRejection sets f as the callback for each promise rejected with reason that has no rejection handler. f is called when the outermost call from Go into vm has run the pending jobs, once for each such promise, in the order of rejection. A promise is reported once, and a handler added later does not undo the report. This includes the promise that Module.Evaluate returns for a module that throws.
f may call into vm and run JavaScript. The jobs that this queues, and the reports of the promises that this rejects, run before the outermost call returns.
The reports that are made after the call go to f, including those of promises that were rejected earlier in a call that is running. A nil f stops the reports, and the promises that would have been reported are discarded.
func (*VM) ValueOf ¶
ValueOf returns x as a JavaScript value:
| Go | JavaScript | | ---------------------- | ---------------------- | | Value | [its value] | | Func | function | | nil | null | | bool | boolean | | integers and floats | number | | *big.Int | bigint | | *SharedDataBlock | new SharedArrayBuffer | | string | string | | []any | new array | | map[string]any | new object |
A string is taken to be UTF-8. The keys of a map become properties in sorted order. A function of the type underlying Func is taken as a Func. ValueOf panics when x is not one of the expected types, or is a nil pointer or a nil Func, or a *big.Int of more than 2^30 bits, the largest BigInt. It panics for a string, symbol, object or function of another VM, including values nested in arrays and maps, and for a map or slice that contains itself.
The objects that ValueOf creates belong to the initial realm.
func (*VM) WithContinuationData ¶
WithContinuationData calls f with data as the continuation data, and restores the previous continuation data when f returns or panics.
A promise job runs with the continuation data that was current when it was registered: when then was called, await was reached, or a promise was resolved with a thenable. The cleanup callback of a FinalizationRegistry runs with the continuation data that was current when the registry was made.
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value is a JavaScript value. The zero value is undefined.
Values cannot be compared with ==. Use Value.Equal to compare them with JavaScript === semantics.
Strings, symbols, objects and functions belong to their creating VM and may pass between its realms. Passing them into another VM panics, including through host callback results and exceptions. Other primitives may pass between VMs. To share SharedArrayBuffer memory, pass its SharedDataBlock to VM.ValueOf.
func (Value) BigInt ¶
BigInt returns the BigInt v as a new *big.Int. It panics with a *ValueError when v is not a BigInt.
func (Value) Bool ¶
Bool returns the boolean v. It panics with a *ValueError when v is not a boolean.
func (Value) Call ¶
Call calls the method named name on v with v as this. The arguments are converted with VM.ValueOf. The errors are those of Value.Get, and a method that does not exist is a *ScriptError holding a TypeError. When ctx is done, the call stops at its next loop iteration or call, and the error is the cause of ctx.
func (Value) CallWithValueKey ¶
CallWithValueKey is like Value.Call, but takes key as Value.GetWithValueKey does.
func (Value) Delete ¶
Delete deletes the property named name from v, as the delete operator in strict mode does. The errors are those of Value.Get.
func (Value) DeleteWithValueKey ¶
DeleteWithValueKey is like Value.Delete, but takes key as Value.GetWithValueKey does.
func (Value) Equal ¶
Equal reports whether v and w are equal according to the JavaScript === operator.
func (Value) Float ¶
Float returns the number v. A NaN always has the bits 0x7ff8000000000000. Float panics with a *ValueError when v is not a number.
func (Value) Get ¶
Get returns the value of the property named name on v.
The error is a *ValueError when v is not an object, a function or a string, and a *ScriptError when the operation throws a JavaScript exception.
func (Value) GetWithValueKey ¶
GetWithValueKey is like Value.Get, but key is converted to a property key the way the expression v[key] converts it, and a conversion that throws is a *ScriptError. It panics if key belongs to a different VM from v.
func (Value) Index ¶
Index returns the property of v named by the decimal representation of i. The errors are those of Value.Get.
func (Value) InstanceOf ¶
InstanceOf reports whether v is an instance of the constructor t, as the instanceof operator does. The errors are those of Value.Get, for t. It panics if v belongs to a different VM from t.
func (Value) Int ¶
Int returns the number v truncated toward zero to an int. NaN gives 0, and a number below or above the range of an int gives math.MinInt or math.MaxInt. It panics with a *ValueError when v is not a number.
func (Value) Invoke ¶
Invoke calls the function v with undefined as this. The arguments are converted with VM.ValueOf. The error is a *ValueError when v is not a function, and a *ScriptError when it throws. When ctx is done, the call stops at its next loop iteration or call, and the error is the cause of ctx.
Example ¶
package main
import (
"context"
"fmt"
"github.com/hajimehoshi/ekuma"
)
func main() {
ctx := context.Background()
var vm ekuma.VM
s, err := vm.ParseScript("total.js", `(order) => order.price * order.quantity`)
if err != nil {
panic(err)
}
total, err := s.Evaluate(ctx)
if err != nil {
panic(err)
}
v, err := total.Invoke(ctx, map[string]any{
"price": 12,
"quantity": 3,
})
if err != nil {
panic(err)
}
fmt.Println(v.Int())
}
Output: 36
func (Value) IsPromise ¶
IsPromise reports whether v is a Promise object. A mere thenable is not a Promise object.
func (Value) IsUndefined ¶
IsUndefined reports whether v is undefined.
func (Value) New ¶
New calls the function v as a constructor, as the new operator does. The arguments are converted with VM.ValueOf. The errors are those of Value.Invoke.
func (Value) PromiseState ¶
func (v Value) PromiseState() (PromiseState, Value)
PromiseState returns the state of the promise v and, unless it is pending, its result: the value it was fulfilled with or the reason it was rejected with. It runs no JavaScript and does not mark a rejected promise as handled. It panics with a *ValueError when v is not a promise.
func (Value) Set ¶
Set sets the property named name on v to VM.ValueOf(x), as an assignment in strict mode does. The errors are those of Value.Get.
func (Value) SetIndex ¶
SetIndex sets the property of v named by the decimal representation of i to VM.ValueOf(x). The errors are those of Value.Get.
func (Value) SetWithValueKey ¶
SetWithValueKey is like Value.Set, but takes key as Value.GetWithValueKey does.
func (Value) SharedDataBlock ¶
func (v Value) SharedDataBlock() *SharedDataBlock
SharedDataBlock returns the data block of the SharedArrayBuffer v. It panics with a *ValueError when v is not a SharedArrayBuffer.
type ValueError ¶
ValueError reports an operation that is unsupported for a Value's type. Operations that do not return an error panic with a *ValueError instead.
func (*ValueError) Error ¶
func (e *ValueError) Error() string
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
ast
Package ast defines the syntax tree and the scope records of ECMAScript source text.
|
Package ast defines the syntax tree and the scope records of ECMAScript source text. |
|
builtin
Package builtin installs the standard ECMAScript built-in objects in each realm.
|
Package builtin installs the standard ECMAScript built-in objects in each realm. |
|
builtin/intl
Package intl implements the Intl built-in objects of ECMA-402.
|
Package intl implements the Intl built-in objects of ECMA-402. |
|
bytecode
Package bytecode defines the instructions that the compiler emits and the interpreter executes.
|
Package bytecode defines the instructions that the compiler emits and the interpreter executes. |
|
collection
Package collection implements the ordered tables of the keyed collections Map and Set.
|
Package collection implements the ordered tables of the keyed collections Map and Set. |
|
compiler
Package compiler translates a syntax tree to bytecode.
|
Package compiler translates a syntax tree to bytecode. |
|
datetime
Package datetime implements the date and time operations of ECMAScript.
|
Package datetime implements the date and time operations of ECMAScript. |
|
element
Package element provides the element types of typed arrays and the encodings of their elements.
|
Package element provides the element types of typed arrays and the encodings of their elements. |
|
engine
Package engine implements the JavaScript virtual machine: the interpreter and the abstract operations of the language.
|
Package engine implements the JavaScript virtual machine: the interpreter and the abstract operations of the language. |
|
icutest
Package icutest runs ICU test data against Ekuma.
|
Package icutest runs ICU test data against Ekuma. |
|
intl/calendar
Package calendar implements the calendars of ECMA-402 other than ISO 8601: their arithmetic, month codes and eras.
|
Package calendar implements the calendars of ECMA-402 other than ISO 8601: their arithmetic, month codes and eras. |
|
intl/collate
Package collate implements the Unicode Collation Algorithm with the CLDR root collation and the tailorings of CLDR.
|
Package collate implements the Unicode Collation Algorithm with the CLDR root collation and the tailorings of CLDR. |
|
intl/date
Package date formats dates and times as Intl.DateTimeFormat does, with the CLDR data of package cldr.
|
Package date formats dates and times as Intl.DateTimeFormat does, with the CLDR data of package cldr. |
|
intl/displaynames
Package displaynames provides the display names of Intl.DisplayNames.
|
Package displaynames provides the display names of Intl.DisplayNames. |
|
intl/duration
Package duration formats durations as Intl.DurationFormat does.
|
Package duration formats durations as Intl.DurationFormat does. |
|
intl/list
Package list formats lists as Intl.ListFormat does.
|
Package list formats lists as Intl.ListFormat does. |
|
intl/locale
Package locale resolves Unicode BCP 47 locale identifiers against CLDR data.
|
Package locale resolves Unicode BCP 47 locale identifiers against CLDR data. |
|
intl/number
Package number implements the locale-independent and locale-dependent number formatting of ECMA-402: the Intl mathematical values, their rounding, and the parts that Intl.NumberFormat formats them into.
|
Package number implements the locale-independent and locale-dependent number formatting of ECMA-402: the Intl mathematical values, their rounding, and the parts that Intl.NumberFormat formats them into. |
|
intl/plural
Package plural implements the plural rules of the Unicode Common Locale Data Repository.
|
Package plural implements the plural rules of the Unicode Common Locale Data Repository. |
|
intl/reltime
Package reltime provides the patterns of relative times for Intl.RelativeTimeFormat.
|
Package reltime provides the patterns of relative times for Intl.RelativeTimeFormat. |
|
intl/segment
Package segment implements UAX #29 segmentation with dictionary word boundaries and locale tailorings.
|
Package segment implements UAX #29 segmentation with dictionary word boundaries and locale tailorings. |
|
json
Package json implements JSON for JavaScript values, whose strings are in WTF-8: parsing text into values, calling a reviver on them, converting values to text, and the lexical grammar.
|
Package json implements JSON for JavaScript values, whose strings are in WTF-8: parsing text into values, calling a reviver on them, converting values to text, and the lexical grammar. |
|
jstest
Package jstest runs Ekuma's JavaScript test suites from the repository root.
|
Package jstest runs Ekuma's JavaScript test suites from the repository root. |
|
localetag
Package localetag parses Unicode BCP 47 locale identifiers.
|
Package localetag parses Unicode BCP 47 locale identifiers. |
|
modulegraph
Package modulegraph resolves the exports of modules.
|
Package modulegraph resolves the exports of modules. |
|
numconv
Package numconv implements the conversions between JavaScript numbers and strings, the integer and binary16 conversions of numbers, and arithmetic of numbers and BigInts.
|
Package numconv implements the conversions between JavaScript numbers and strings, the integer and binary16 conversions of numbers, and arithmetic of numbers and BigInts. |
|
parser
Package parser parses ECMAScript source text into the syntax tree of package ast.
|
Package parser parses ECMAScript source text into the syntax tree of package ast. |
|
quiet
Package quiet holds the operations that run no script or host code, for the engine and for the built-in objects, and the fast forms of built-in functions made of them.
|
Package quiet holds the operations that run no script or host code, for the engine and for the built-in objects, and the fast forms of built-in functions made of them. |
|
regexp
Package regexp implements ECMAScript regular expressions.
|
Package regexp implements ECMAScript regular expressions. |
|
shortstrings
Package shortstrings operates on packed canonical WTF-8 strings.
|
Package shortstrings operates on packed canonical WTF-8 strings. |
|
srcpos
Package srcpos converts byte offsets in source text into lines and columns.
|
Package srcpos converts byte offsets in source text into lines and columns. |
|
storage
Package storage holds the values, the objects and the shapes of JavaScript, and the operations on them that run no code.
|
Package storage holds the values, the objects and the shapes of JavaScript, and the operations on them that run no code. |
|
temporal
Package temporal implements the abstract operations of the Temporal built-in objects: the ISO 8601 calendar, epoch nanoseconds, durations and their rounding, time zones, and the RFC 9557 string format.
|
Package temporal implements the abstract operations of the Temporal built-in objects: the ISO 8601 calendar, epoch nanoseconds, durations and their rounding, time zones, and the RFC 9557 string format. |
|
unorm
Package unorm implements the Unicode normalization forms of UAX #15 for any length of the runs of non-starters.
|
Package unorm implements the Unicode normalization forms of UAX #15 for any length of the runs of non-starters. |
|
waiterlist
Package waiterlist provides lists of waiters that refer to the waiters weakly.
|
Package waiterlist provides lists of waiters that refer to the waiters weakly. |
|
wtf8
Package wtf8 implements JavaScript string semantics on Go strings.
|
Package wtf8 implements JavaScript string semantics on Go strings. |
|
xerrors
Package xerrors carries failures that cannot be handled by JavaScript.
|
Package xerrors carries failures that cannot be handled by JavaScript. |
|
xmath
Package xmath implements floating-point functions more accurate than those of package math.
|
Package xmath implements floating-point functions more accurate than those of package math. |
|
xstrings
Package xstrings provides substring search and ECMAScript whitespace trimming for WTF-8 strings, and case mapping for valid UTF-8 strings.
|
Package xstrings provides substring search and ECMAScript whitespace trimming for WTF-8 strings, and case mapping for valid UTF-8 strings. |
|
Package intl adds the ECMAScript Internationalization API (ECMA-402) to the VMs of package github.com/hajimehoshi/ekuma.
|
Package intl adds the ECMAScript Internationalization API (ECMA-402) to the VMs of package github.com/hajimehoshi/ekuma. |