Documentation
¶
Overview ¶
Package beastjs is a JavaScript engine written for Go programs that render pages on a server: pure Go, with no cgo and no shared library, so that it builds and cross-compiles as any Go package does. It runs ES2023, modules, async generators, Proxy and BigInt among it. The engine, which started from QuickJS, is written in C and ships as Go assembly that is checked in, so building the package needs no C compiler.
Intl and time zones ¶
The engine has no Intl of its own, and its toLocale* methods look at no locale and no timeZone. The Register function of package github.com/liustack/beastjs/intl adds every Intl constructor to a VM and replaces toLocale* and localeCompare with ones that use them. The one of package github.com/liustack/beastjs/temporal adds Temporal. Without a locale they use en-US, and without a timeZone UTC. The time zone data is built in: the zoneinfo of the host is never read.
Platforms ¶
The package builds for darwin/amd64, darwin/arm64, linux/amd64, linux/arm64, windows/amd64 and windows/arm64. A build for any other target stops with an error that names these.
Bytecode across versions ¶
The bytecode of VM.Compile belongs to the release of QuickJS the engine is. Moving to QuickJS 2026-06-04 changed its format, so bytecode an older version compiled no longer loads, and so did the move to 2025-09-13 before it. Compile again after an upgrade.
Example (Ping) ¶
Two VMs run at once, each on a goroutine of its own, and talk over Go channels. A VM is used by one goroutine at a time, and VMs share nothing.
package main
import (
"fmt"
"github.com/liustack/beastjs"
)
// pipe is a VM with a send and a receive over two Go channels.
func pipe(out chan<- string, in <-chan string) *beastjs.VM {
m := newVM()
if err := m.RegisterFunc("send", func(s string) { out <- s }, false); err != nil {
panic(err)
}
if err := m.RegisterFunc("receive", func() string { return <-in }, false); err != nil {
panic(err)
}
return m
}
// Two VMs run at once, each on a goroutine of its own, and talk over Go
// channels. A VM is used by one goroutine at a time, and VMs share nothing.
func main() {
toServer := make(chan string, 1)
toClient := make(chan string, 1)
go func() {
server := pipe(toClient, toServer)
defer server.Close()
if _, err := server.Eval(`send(receive() + ' reply')`, beastjs.EvalGlobal); err != nil {
panic(err)
}
}()
client := pipe(toServer, toClient)
defer client.Close()
fmt.Println(client.Eval(`send('ping'); receive();`, beastjs.EvalGlobal))
}
Output: ping reply <nil>
Index ¶
- Constants
- Variables
- func Version() string
- type Args
- func (a Args) Bool(i int) (bool, bool)
- func (a Args) Latin1(i int) (b []byte, ok bool)
- func (a Args) Len() int
- func (a Args) Number(i int) (float64, bool)
- func (a Args) String(i int) (s string, ok bool)
- func (a Args) StringLen(i int) (n int, ok bool)
- func (a Args) This() Value
- func (a Args) UTF16(i int) (u []uint16, ok bool)
- func (a Args) VM() *VM
- func (a Args) Value(i int) Value
- func (a Args) WTF8(i int) (s string, ok bool)
- type Atom
- type Builtin
- type Error
- type HostFunc
- type MemoryUsage
- type Object
- type PromiseCapability
- type SharedBytecode
- type Strip
- type Undefined
- type Unsupported
- type VM
- func (m *VM) Call(function string, args ...any) (r any, err error)
- func (m *VM) CallValue(function string, args ...any) (r Value, err error)
- func (m *VM) Close() (err error)
- func (m *VM) Compile(javascript string, flags int) ([]byte, error)
- func (m *VM) Eval(javascript string, flags int) (r any, err error)
- func (m *VM) EvalBytecode(bytecode []byte) (r any, err error)
- func (m *VM) EvalBytecodeValue(bytecode []byte) (r Value, err error)
- func (m *VM) EvalFile(name, javascript string, flags int) (r Value, err error)
- func (m *VM) EvalSharedBytecode(b *SharedBytecode) (r any, err error)
- func (m *VM) EvalSharedBytecodeValue(b *SharedBytecode) (r Value, err error)
- func (m *VM) EvalThis(obj Value, javascript string, flags int) (r any, err error)
- func (m *VM) EvalThisValue(obj Value, javascript string, flags int) (r Value, err error)
- func (m *VM) EvalValue(javascript string, flags int) (r Value, err error)
- func (m *VM) ExecutePendingJobs() (n int, err error)
- func (m *VM) GCThreshold() uintptr
- func (m *VM) GetProperty(this Value, prop Atom) (r any, err error)
- func (m *VM) GetPropertyValue(this Value, prop Atom) (r Value, err error)
- func (m *VM) GlobalObject() (r Value)
- func (m *VM) Interrupt()
- func (m *VM) MemoryFree() uintptr
- func (m *VM) MemorySize() uintptr
- func (m *VM) MemoryUsage() MemoryUsage
- func (m *VM) NewArray(vals ...Value) (Value, error)
- func (m *VM) NewAtom(s string) (r Atom, err error)
- func (m *VM) NewBuiltinFunction(b *Builtin) (Value, error)
- func (m *VM) NewFloat64(n float64) Value
- func (m *VM) NewInt(n int) Value
- func (m *VM) NewMurmur2Function() (Value, error)
- func (m *VM) NewObjectValue() (r Value, err error)
- func (m *VM) NewPromiseCapability() (*PromiseCapability, error)
- func (m *VM) NewString(s string) (r Value, err error)
- func (m *VM) NewStringLatin1(b []byte) (Value, error)
- func (m *VM) NewStringUTF16(u []uint16) (Value, error)
- func (m *VM) Now() time.Time
- func (m *VM) OnClose(f func())
- func (m *VM) RegisterCopyProps(name string) error
- func (m *VM) RegisterEndTag(name string) error
- func (m *VM) RegisterEscapeText(name string) error
- func (m *VM) RegisterFunc(name string, f any, wantThis bool) error
- func (m *VM) RegisterHostFunc(name string, fn HostFunc) error
- func (m *VM) RegisterStartTag(name string) error
- func (m *VM) ReleaseMemory(keep uintptr) (uintptr, error)
- func (m *VM) RunGC()
- func (m *VM) RunYoungGC()
- func (m *VM) SetClock(now func() time.Time)
- func (m *VM) SetEvalTimeout(d time.Duration) error
- func (m *VM) SetGCThreshold(threshold uintptr)
- func (m *VM) SetMaxStackSize(threshold uintptr)
- func (m *VM) SetMemoryLimit(limit uintptr)
- func (m *VM) SetProperty(this Value, prop Atom, val any) (err error)
- func (m *VM) SetPropertyValue(this Value, prop Atom, val Value) (err error)
- func (m *VM) SetRegExpCache(n, bytes int) error
- func (m *VM) SetShapeCache(n int) error
- func (m *VM) SetStrip(s Strip)
- func (m *VM) TrackRejections(max int) (err error)
- func (m *VM) UnhandledRejections() (reasons []*Error, dropped int, err error)
- type Value
- func (v Value) Any() (r any, err error)
- func (v Value) Call(this Value, args ...any) (r any, err error)
- func (v Value) CallValue(this Value, args ...any) (r Value, err error)
- func (v Value) Dup() Value
- func (v *Value) Free()
- func (v Value) GetProperty(this Value, prop Atom) (r any, err error)deprecated
- func (v Value) GetPropertyValue(prop Atom) (r Value, err error)
- func (v Value) IsUndefined() bool
- func (v Value) MarshalJSON() (r []byte, err error)
- func (v Value) Property(prop Atom) (r any, err error)
- func (v Value) SetProperty(prop Atom, val any) (err error)
- func (v Value) SetPropertyValue(prop Atom, val Value) (err error)
- func (v Value) Then(onFulfilled, onRejected func(Value)) (_ Value, err error)
- func (v *Value) VM() *VM
Examples ¶
- Package (Ping)
- Object.Into
- Object.MarshalJSON
- Object.String
- VM.Call (Function)
- VM.Call (Method)
- VM.Eval (Exception)
- VM.Eval (Expression)
- VM.Eval (Object)
- VM.Interrupt
- VM.RegisterFunc (Error)
- VM.RegisterFunc (MultipleReturn)
- VM.RegisterFunc (SingleReturn)
- VM.RegisterFunc (ThisNonNull)
- VM.RegisterFunc (ThisNonNull2)
- VM.RegisterFunc (ThisNull)
- VM.RegisterFunc (ThisNull2)
- VM.RegisterFunc (Void)
- VM.SetEvalTimeout
Constants ¶
const ( EvalGlobal = 0 EvalModule = 1 )
The flags of the eval methods: a script, or an ES module. A program may add other flag bits of QuickJS, which the engine is given as they are.
const ( DefaultRegExpCache = 512 DefaultRegExpCacheBytes = 1 << 20 )
DefaultRegExpCache and DefaultRegExpCacheBytes are how many compiled regexps a new VM keeps at most, and in how many bytes (see VM.SetRegExpCache).
const DefaultShapeCache = 2048
DefaultShapeCache is how many shapes a new VM keeps (see VM.SetShapeCache).
const MaxTrackedRejections = 1024
MaxTrackedRejections is the most rejections VM.TrackRejections keeps. A host logs the few a script and its jobs left, and a read holds up to five texts of 8 KiB of each in Go (see VM.UnhandledRejections).
Variables ¶
var ( // GetAsyncContext returns the async context of the VM, undefined when it // has none. GetAsyncContext = NewBuiltin("getAsyncContext", 0, func(a Args) (Value, error) { return Value{vm: a.vm, v: a.vm.jsGetAsyncContext()}, nil }) // SetAsyncContext sets the async context of the VM to its first argument // when it is an object, and to none for any other value. SetAsyncContext = NewBuiltin("setAsyncContext", 1, func(a Args) (Value, error) { a.vm.jsSetAsyncContext(a.arg(0)) return UndefinedValue, nil }) )
The async context of a VM is an object javascript sets with SetAsyncContext and reads with GetAsyncContext, which promise jobs keep: a reaction, what then, catch, finally and await register, runs with the context the VM had when it was registered, and the VM gets back the context it had when the reaction ends. That is what an AsyncLocalStorage needs to follow an async function across await, and what V8 keeps for Node as the continuation preserved embedder data. A VM starts with no context, and promises then cost what they did before it.
The context is an object or none. An AsyncLocalStorage keeps the stores of each of its instances in the object, as a Map from the instance to its store, and makes a new object for each run, so the object of a context is not changed once it is set.
var ErrKilled = errors.New("beastjs: the script did not stop in time and was killed")
ErrKilled matches the error of a call whose script did not stop in time after the eval timeout or VM.Interrupt and was killed, with errors.Is. Such a VM is good only for VM.Close.
var UndefinedValue = Value{/* contains filtered or unexported fields */}
UndefinedValue is javascript's undefined as a Value. It belongs to no VM, so every VM takes it, it holds no reference, and freeing it does nothing. The zero Value is undefined too.
Functions ¶
Types ¶
type Args ¶
type Args struct {
// contains filtered or unexported fields
}
Args are the arguments of a call of a Builtin, and the VM that called it. What they return is borrowed: a Value is valid for the duration of the call (see Value.Dup to keep one longer).
func (Args) Latin1 ¶
Latin1 returns the characters of argument i, one byte each, when it is a string the engine holds that way: all its characters are below U+0100 and it was not left in pieces by concatenation (a rope). Nothing is copied: the bytes are the engine's, valid until the Builtin returns, and must not be changed. ok is false for any other argument, which Args.UTF16 or Args.String reads. A Builtin that looks at the characters of short strings, and often returns its argument as it is, reads them this way.
func (Args) Number ¶
Number returns argument i when it is a number. It converts nothing: a string or a Number object is not a number.
func (Args) String ¶
String returns argument i when it is a string, as UTF-8 with U+FFFD for each lone surrogate. It converts nothing else. ok is false too when there is no memory for the conversion, and the call then fails with the out of memory error whatever the Builtin returns. A long string ends the same way at Interrupt, the eval timeout or an uncatchable error of the call, as a loop of the engine does: ok is false, and the call fails with that error.
func (Args) StringLen ¶
StringLen returns the length of argument i, in UTF-16 code units as javascript counts it, when it is a string, without reading the string: a rope, a string the engine keeps as the pieces it was joined from, is not joined. A Builtin can so refuse a string too long for it before it converts any of it. It takes the same time for a string of any length and allocates nothing.
func (Args) UTF16 ¶
UTF16 returns the 16-bit units of argument i when it is a string the engine holds that way, lone surrogates as they are: a string with a character from U+0100 on, not left in pieces by concatenation (a rope). Nothing is copied: the units are the engine's, valid until the Builtin returns, and must not be changed. ok is false for any other argument, which Args.Latin1 or Args.String reads.
func (Args) VM ¶
VM returns the VM that called the Builtin. The Builtin may evaluate more javascript on it, which runs inside the time left to the call that got there (see VM.SetEvalTimeout).
func (Args) WTF8 ¶
WTF8 is String, but with each lone surrogate as the three bytes of its code point (0xED, then 0xA0 to 0xBF, then a continuation byte), the form the engine writes it in, which is not UTF-8. A surrogate pair is its one character in UTF-8, as in String. A Builtin that has to tell lone surrogates apart, as a collator orders them, reads its string this way. It ends at the limits of the call as String does.
type Atom ¶
type Atom = uint32
Atom is the number by which a VM knows a property name (see VM.NewAtom). It is a uint32.
type Builtin ¶
type Builtin struct {
// contains filtered or unexported fields
}
A Builtin is a Go function that javascript calls as a built-in function: VM.NewBuiltinFunction makes it a function object shaped like the engine's own built-ins, such as Math.max. It has a name and a length and no other property of its own, no prototype property, it cannot be called with new, and its toString shows [native code] rather than source.
Unlike VM.RegisterFunc and VM.RegisterHostFunc, nothing is converted on the way in and no reflection is involved: the Go function reads the arguments it wants from Args, which give a number only for a number and a string only for a string, and returns a Value. That makes a call about as cheap as a call of a javascript function, which suits functions called once per row of a table, as the formatters of package intl are.
A Builtin belongs to no VM. It is made once, typically into a package level variable, and every VM makes its own function objects of it: Args says which VM called. So a process can have at most 32768 Builtins, and they are never released. VMs on several goroutines call the same Builtin at once, so its function has to be safe for concurrent use, and state it keeps for each VM is found by Args.VM.
func NewBuiltin ¶
NewBuiltin returns a Builtin calling fn, for function objects named name whose length property is length.
fn owns the Value it returns, which goes to javascript: a Value fn did not make itself, such as an argument, is returned as its Dup. UndefinedValue and the zero Value return undefined. A Value of another VM is neither returned nor freed: the call throws a TypeError.
A non-nil error is thrown instead, and a Value of the VM returned with it is freed. An *Error, found with errors.As, is thrown as a new error of the constructor its Name says when that is one of Error, TypeError, RangeError, SyntaxError, ReferenceError and InternalError, and as an Error for any other name, with its Message. Any other error is thrown as a TypeError with the error's text, as RegisterHostFunc throws it. The engine cuts the message of a TypeError, RangeError, SyntaxError, ReferenceError or InternalError to 255 bytes. The stack of each starts at the Builtin, as that of an error a built-in of the engine throws does.
A panic in fn goes on in the Go code that called javascript, as one in a function of RegisterHostFunc does.
NewBuiltin panics when name has a NUL byte, when length is not in 0 to 255, when fn is nil, and when the process already has 32768 Builtins: all mistakes of the code making them, which runs once.
type Error ¶
type Error struct {
// Name and Message are the name and message properties of the exception,
// empty when it has none, as for throw 42. Stack is its stack property.
Name string
Message string
Stack string
// LineNumber, ColumnNumber and FileName are set for a syntax error only.
// The error of a script that ran has its place in Stack alone.
LineNumber int
ColumnNumber int
FileName string
// Uncatchable reports that the call ended with an exception that no
// catch or finally of the script got to see: the VM ran out of memory
// (OutOfMemory is set too), Interrupt or the eval timeout stopped the
// script (Interrupted is set too), or a Go function that javascript
// called panicked (neither is set). Nothing a script throws is
// uncatchable, whatever its name and message.
Uncatchable bool
OutOfMemory bool
Interrupted bool
// contains filtered or unexported fields
}
Error is a javascript exception that ended a call, read into Go. Get it from the error of a call with errors.As:
if _, err := m.Eval(js, beastjs.EvalGlobal); err != nil {
var e *beastjs.Error
if errors.As(err, &e) && e.Interrupted {
// the eval timeout or Interrupt stopped the script
}
}
The text of Error() is what the engine has always given for the exception, such as "TypeError: x is not a function", or the string of a value that is not an error, such as "42" for throw 42.
func ErrorFromValue ¶
ErrorFromValue reads the error value v, such as an exception a script caught, as the error of a call is read. It borrows v. Reading it runs javascript, a getter of its message or a toString of the page, inside the eval timeout (see VM.SetEvalTimeout). A field it cannot read stays empty. It panics when v belongs to no VM, and on a VM a kill left good only for Close.
type HostFunc ¶
HostFunc is a Go function for VM.RegisterHostFunc: it gets the arguments of the call as Go values, and returns the one value of the call, or an error to throw.
type MemoryUsage ¶
type MemoryUsage struct {
// MallocSize is what the VM's allocations take, which [VM.MemorySize]
// returns too, and MallocCount how many there are. MallocLimit is the
// limit of [VM.SetMemoryLimit], -1 for none.
MallocSize, MallocLimit, MallocCount int64
// MemoryUsedSize and MemoryUsedCount are what the objects below take,
// counted one by one.
MemoryUsedSize, MemoryUsedCount int64
AtomCount, AtomSize int64
StrCount, StrSize int64
ObjCount, ObjSize int64
PropCount, PropSize int64
ShapeCount int64
ShapeSize int64
// The functions of javascript, their bytecode and their line tables.
JSFuncCount, JSFuncSize, JSFuncCodeSize int64
JSFuncPC2LineCount, JSFuncPC2LineSize int64
// Functions of the engine and of Go.
CFuncCount int64
// ArrayCount counts the arrays, FastArrayCount those that keep their
// elements in a plain list, and FastArrayElements those elements.
ArrayCount, FastArrayCount, FastArrayElements int64
// ArrayBuffers and typed arrays.
BinaryObjectCount, BinaryObjectSize int64
// What the VM took from the system, its limit (0 for none), in how many
// chunks, and the bytes [VM.ReleaseMemory] offered back so far.
Footprint, FootprintLimit, Chunks, ReleaseCandidate int64
// The register code the engine made for the functions that ran, at the
// first call of each, kept as long as the function: how many functions
// and its bytes. JSFuncCodeSize is the bytecode alone. MemoryUsedSize
// counts both.
RegisterCodeCount, RegisterCodeSize int64
// FreeSize is [VM.MemoryFree]: the bytes of MallocSize no block in use
// holds.
FreeSize int64
}
MemoryUsage is what a VM holds, as its engine counts it (see VM.MemoryUsage). Sizes are in bytes.
type Object ¶
type Object struct {
// contains filtered or unexported fields
}
Object is the Go value of a javascript object, array or function: the JSON that JSON.stringify made of it when it was converted. It is a copy of what the object held then, not the object, so two Objects of one object are not the same and comparing them tells nothing. A value JSON.stringify gives undefined for, such as a function, has the JSON text undefined, which is not JSON.
The zero Object has no JSON at all: passed to javascript, as an argument or a result, it fails to parse.
func (*Object) Into ¶
Into decodes the JSON of o into v, as encoding/json.Unmarshal does.
Example ¶
package main
import (
"fmt"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
// object is the result of an object literal, as the examples of Object use it.
func object() *beastjs.Object {
m := newVM()
defer m.Close()
v, err := m.Eval(`({a: 42 + 314, b: 'foo'})`, beastjs.EvalGlobal)
if err != nil {
panic(err)
}
return v.(*beastjs.Object)
}
func main() {
var s struct {
A int `json:"a"`
B string `json:"b"`
}
if err := object().Into(&s); err != nil {
panic(err)
}
fmt.Printf("%#v\n", s)
}
Output: struct { A int "json:\"a\""; B string "json:\"b\"" }{A:356, B:"foo"}
func (*Object) MarshalJSON ¶
MarshalJSON returns the JSON of o. Its error is always nil.
Example ¶
package main
import (
"fmt"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
// object is the result of an object literal, as the examples of Object use it.
func object() *beastjs.Object {
m := newVM()
defer m.Close()
v, err := m.Eval(`({a: 42 + 314, b: 'foo'})`, beastjs.EvalGlobal)
if err != nil {
panic(err)
}
return v.(*beastjs.Object)
}
func main() {
b, err := object().MarshalJSON()
if err != nil {
panic(err)
}
fmt.Println(string(b))
}
Output: {"a":356,"b":"foo"}
func (*Object) String ¶
String returns the JSON of o.
Example ¶
package main
import (
"fmt"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
// object is the result of an object literal, as the examples of Object use it.
func object() *beastjs.Object {
m := newVM()
defer m.Close()
v, err := m.Eval(`({a: 42 + 314, b: 'foo'})`, beastjs.EvalGlobal)
if err != nil {
panic(err)
}
return v.(*beastjs.Object)
}
func main() {
fmt.Printf("%s\n", object())
}
Output: {"a":356,"b":"foo"}
type PromiseCapability ¶
PromiseCapability is a promise and the two functions that settle it. Each of the three is a reference, which Free gives up.
func (*PromiseCapability) Dup ¶
func (pc *PromiseCapability) Dup() *PromiseCapability
Dup returns a new PromiseCapability with a Dup of each value of pc, which is freed on its own.
func (*PromiseCapability) Free ¶
func (pc *PromiseCapability) Free()
Free frees the three values of pc.
type SharedBytecode ¶
type SharedBytecode struct {
// contains filtered or unexported fields
}
SharedBytecode is bytecode of VM.Compile that several VMs load with VM.EvalSharedBytecode from one copy. The source text of each function, which its toString returns, and the table that maps its bytecode to lines, which error stacks read, stay in that copy: a VM that loads it does not copy them into its own memory, as VM.EvalBytecode does. So they count once for the process, outside the memory of every VM: VM.SetMemoryLimit and VM.MemorySize do not count them. Everything else a VM reads from the bytecode, the code of its functions among it, is still its own.
The copy lives outside Go's heap. It stays while the SharedBytecode is open or a VM that loaded it is: Close gives up the hold of the SharedBytecode, and each VM gives up its own when it is closed. The last of them frees it.
A SharedBytecode is safe for use by several goroutines at once, and so several VMs on several goroutines can load it at the same time.
func NewSharedBytecode ¶
func NewSharedBytecode(bytecode []byte) (*SharedBytecode, error)
NewSharedBytecode copies bytecode, which VM.Compile returned, once, for VMs to load with VM.EvalSharedBytecode. As with VM.EvalBytecode, the bytecode is not checked, so it must not come from an untrusted source.
func (*SharedBytecode) Close ¶
func (b *SharedBytecode) Close() error
Close gives up the hold of b on its bytes: they are freed now if no VM that loaded them is open, or else when the last of them is closed. Loading b after Close fails. Closing b again does nothing.
func (*SharedBytecode) Len ¶
func (b *SharedBytecode) Len() int
Len returns the size of the bytecode in bytes, the memory it takes once for the process.
type Strip ¶
type Strip int
Strip says what the functions a VM compiles leave out (see VM.SetStrip).
const ( // StripSource leaves out the source text of each function, so that its // toString shows [native code]. StripSource Strip = 1 // StripDebug leaves out the file names and the line and column numbers, // so that a stack frame shows only the name of its function, and the // source text too. StripDebug Strip = 2 )
type Undefined ¶
type Undefined struct{}
Undefined is the Go value of javascript's undefined. As an argument it is undefined again.
type Unsupported ¶
type Unsupported struct{}
Unsupported is the Go value of a javascript value that has no Go form, such as a symbol.
func (Unsupported) String ¶
func (u Unsupported) String() string
String returns "unsupported Javascript type".
type VM ¶
type VM struct {
// contains filtered or unexported fields
}
VM is a javascript realm, with its global object, and the runtime that runs it. Each VM has its own memory and its own globals.
A VM is not safe for use by several goroutines at once: one goroutine uses it at a time. VM.Interrupt is the exception, and may be called from any goroutine at any time.
func (*VM) Call ¶
Call evaluates function, source that gives a function, such as "parseInt" or "obj.method", calls it with args and returns its value as VM.Eval does. this is the global object, also for "obj.method". function is run as a script: "var a = 42; a" runs, and the call fails as 42 is not a function. What function throws is the error, such as a ReferenceError for a name that is not defined.
Each argument becomes a javascript value by its dynamic Go type:
Go javascript
-- ----------
nil null
Value the value, borrowed
Undefined undefined
int8, uint8, int16, uint16, int32 a number
int, int64, uint, uint32, uint64 a number, a float when
outside int32 (past 2^53
it loses precision)
float64 a number
bool a boolean
string a string, U+FFFD for each
byte of invalid UTF-8
*big.Int a BigInt, null for nil
anything else the JSON of encoding/json
A type of its own, such as time.Duration, and float32, []byte (base64), structs, maps and *Object go through JSON. So does an error, which most often has no exported field and becomes {}: pass err.Error() instead. A Value of another VM is an error.
Example (Function) ¶
package main
import (
"fmt"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
func main() {
m := newVM()
defer m.Close()
fmt.Println(m.Call("parseInt", "1234"))
}
Output: 1234 <nil>
Example (Method) ¶
package main
import (
"fmt"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
func main() {
m := newVM()
defer m.Close()
fmt.Println(m.Call("Math.abs", -1234))
}
Output: 1234 <nil>
func (*VM) CallValue ¶
CallValue is VM.Call that returns the value as a Value, which the caller frees.
func (*VM) Close ¶
Close frees m and all it holds, then runs the functions of VM.OnClose.
Close of a closed VM does nothing and returns nil, so a deferred Close after an explicit one is fine. When the OS refuses to take some memory back, Close returns an error, and a Close after it tries what is left again: the error only says that some memory was not given back when Close returned.
A step of Close that panics does not keep the others from running: the other functions of OnClose run too. Close then panics with the first panic. Close from a function of OnClose returns nil. Close during a call into m, such as from a Go function that javascript called, returns an error and changes nothing: a Close after the call closes m.
func (*VM) Compile ¶
Compile compiles javascript, a script or with EvalModule a module, to bytecode, which VM.EvalBytecode or VM.EvalBytecodeValue runs. The format of the bytecode belongs to the release of QuickJS the engine is. Compiling is inside the eval timeout.
func (*VM) Eval ¶
Eval evaluates javascript, a script or, with EvalModule in flags, a module, and returns its value as a Go value:
javascript Go
---------- --
null nil
undefined Undefined{}
a boolean bool
a number that is int32 int
any other number float64
a string string, a lone surrogate as U+FFFD
a BigInt *big.Int
an object, an array *Object, its JSON
a symbol and the rest Unsupported{}
A number the engine holds as a float, such as the result of some arithmetic, is a float64 even when its value is whole. A module's value is the promise of its evaluation, which Eval does not wait for. An exception is returned as an *Error.
flags are given to the engine as they are, so other flag bits of QuickJS work too.
Example (Exception) ¶
package main
import (
"fmt"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
func main() {
m := newVM()
defer m.Close()
fmt.Println(m.Eval(`throw new Error('failed')`, beastjs.EvalGlobal))
}
Output: <nil> Error: failed
Example (Expression) ¶
package main
import (
"fmt"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
func main() {
m := newVM()
defer m.Close()
fmt.Println(m.Eval(`1 + 2`, beastjs.EvalGlobal))
}
Output: 3 <nil>
Example (Object) ¶
package main
import (
"fmt"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
func main() {
m := newVM()
defer m.Close()
fmt.Println(m.Eval(`({a: 42 + 314, b: 'foo'})`, beastjs.EvalGlobal))
}
Output: {"a":356,"b":"foo"} <nil>
func (*VM) EvalBytecode ¶
EvalBytecode loads bytecode that VM.Compile made, runs it and returns its value as VM.Eval does. this is the global object. A module's top-level await is waited for. Loading, running and converting the value are one call, inside the eval timeout.
The format of bytecode belongs to the release of QuickJS the engine is, and nothing in it is checked: never load bytecode from a source you do not trust.
func (*VM) EvalBytecodeValue ¶
EvalBytecodeValue is VM.EvalBytecode that returns the value as a Value, which the caller frees.
func (*VM) EvalFile ¶
EvalFile is VM.EvalValue with name as the file of the script: its stack frames and its syntax errors show name where those of the other Eval methods show <eval>, and a module has name as its module name. No file is read. name is cleaned first: to valid UTF-8 of one line, with no control character, U+2028 or U+2029 (each becomes U+FFFD), of at most 1,024 bytes (cut where a character starts). An empty name is <eval>.
The name of a module is what tells it apart, so a module name the cleaning would change is an error, and nothing runs. Two modules of the same name both run, and import.meta and an import of that name find the first.
func (*VM) EvalSharedBytecode ¶
func (m *VM) EvalSharedBytecode(b *SharedBytecode) (r any, err error)
EvalSharedBytecode is like VM.EvalBytecode, but loads b without copying the source text and line tables of its functions into m (see SharedBytecode). m holds b until it is closed.
func (*VM) EvalSharedBytecodeValue ¶
func (m *VM) EvalSharedBytecodeValue(b *SharedBytecode) (r Value, err error)
EvalSharedBytecodeValue is like VM.EvalBytecodeValue, but loads b as VM.EvalSharedBytecode does.
func (*VM) EvalThis ¶
EvalThis is VM.Eval with obj as this. It takes obj and frees it when it returns, whatever happens. A Value of another VM is an error, and is neither used nor freed.
func (*VM) EvalThisValue ¶
EvalThisValue is VM.EvalThis that returns the value as a Value, which the caller frees. It takes obj as EvalThis does.
func (*VM) EvalValue ¶
EvalValue is VM.Eval that returns the value as a Value, which the caller frees.
func (*VM) ExecutePendingJobs ¶
ExecutePendingJobs runs the jobs queued in m, the reactions of promises and what follows an await, until the queue is empty, and returns how many it ran. Nothing runs them on its own: a program that uses promises calls it, such as at the end of each turn of its event loop.
A job that throws does not stop the others, and the first such exception is the error. A throw in a then callback is no such job: it rejects the promise then returned. An uncatchable error, such as the eval timeout, ends the call at once, and the jobs after it stay queued. A queue that keeps feeding itself is cut after 1,048,576 jobs, with an error.
func (*VM) GCThreshold ¶
GCThreshold returns the threshold of the next collection the engine runs by itself. It counts the memory a collection can free: MemorySize without the stack of the register loop. After each full collection, of the engine or of VM.RunGC, the threshold is 1.5 times what that memory is then, unless it is ^uintptr(0): so a threshold other than the one SetGCThreshold set says a full collection ran since.
As every method of m, it is not for use by other goroutines at the same time. After Close it panics. After a kill it still answers.
func (*VM) GetProperty ¶
GetProperty returns the property prop of this as a Go value, as VM.Eval converts it. Reading it and converting it run inside one eval timeout.
func (*VM) GetPropertyValue ¶
GetPropertyValue returns the property prop of this, which the caller frees. A getter runs, inside the eval timeout. A Value of another VM is an error.
func (*VM) GlobalObject ¶
GlobalObject returns the global object of m, which the caller frees.
func (*VM) Interrupt ¶
func (m *VM) Interrupt()
Interrupt requests 'm' to interrupt Javascript evaluation. Interrupt can be called asynchronously, from any goroutine, at any time m is evaluating a script. The request stays pending until the outermost call into javascript returns, so javascript a host function evaluates on m meanwhile does not clear it. Interrupt is also safe while m closes and after Close, where it does nothing, so a watchdog need not know whether the script it guards has finished. A script that keeps the engine working past the grace of the host after it is killed (see ErrKilled): the call returns an interrupted error, and the VM is good only for Close.
Example ¶
Another goroutine stops a script that would run for ever.
package main
import (
"fmt"
"time"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
func main() {
m := newVM()
defer m.Close()
start := time.Now()
go func() {
time.Sleep(time.Second)
m.Interrupt()
}()
v, err := m.Eval(`for (;;) {}`, beastjs.EvalGlobal)
fmt.Println(v, err, time.Since(start).Truncate(200*time.Millisecond))
}
Output: <nil> InternalError: interrupted 1s
func (*VM) MemoryFree ¶
MemoryFree returns the bytes of MemorySize that no block in use holds: holes in the arenas, the free end of an arena, and the free blocks the caches keep. After VM.RunGC, MemorySize minus MemoryFree is what the objects javascript reaches and the structures of the runtime take, a figure that stays put while the same objects are kept: it is the one to judge when to replace a VM. It walks the arenas, some tens of microseconds for thousands of them, and may be read at any time, from a Go function javascript called and after a kill too.
func (*VM) MemorySize ¶
MemorySize returns the memory m takes, in bytes, as VM.SetMemoryLimit counts it. VM.MemoryFree says how much of it no block in use holds.
func (*VM) MemoryUsage ¶
func (m *VM) MemoryUsage() MemoryUsage
MemoryUsage returns what m holds, in more detail than VM.MemorySize. It walks every object, so it is for measurements, not for a hot path. Run VM.RunGC first to leave out what javascript can no longer reach.
As with SetGCThreshold, no other goroutine may use m meanwhile (see VM), and a call after Close panics.
func (*VM) NewArray ¶
NewArray returns a new array of vals, made as an array literal makes one: its elements are own properties, which no setter a page put on Array.prototype sees. It borrows vals, as VM.SetPropertyValue and Value.Call do: the caller still owns them. The zero Value is undefined. A Value of another VM, a number too, is an error, as it is for a Builtin to return one. In a Builtin, a long array ends at Interrupt, the eval timeout or an uncatchable error of the call, with that error, as a loop of the engine does.
func (*VM) NewAtom ¶
NewAtom returns the atom of the property name s, a number the VM knows the name by, the same for the same name. Invalid UTF-8 in s is U+FFFD a byte. An atom is never freed.
func (*VM) NewBuiltinFunction ¶
NewBuiltinFunction returns a new function object of b. The caller owns it: it passes it to javascript, for example as an argument of Value.Call or with VM.SetPropertyValue, and then frees it.
func (*VM) NewInt ¶
NewInt returns the number n. Outside int32 it is a float, which loses precision past 2^53.
func (*VM) NewMurmur2Function ¶
NewMurmur2Function returns a function of javascript, written in C inside the engine, that hashes a string as murmur2 of @emotion/hash 0.9 does, which emotion takes of every style it serializes: the low byte of each UTF-16 code unit, a lone surrogate as the unit it is, and the hash in base 36. It answers undefined for anything but a string. A rope, a string the engine keeps as the pieces it was joined from, is joined first, under the memory limit, and an interrupt or the eval timeout stops it on a long string. emotion's own function calls String.prototype.charCodeAt and Number.prototype.toString: a host that calls this one in its place checks that a page has not replaced them (package tifa does). The function is named murmur2 and its length is 1.
func (*VM) NewObjectValue ¶
NewObjectValue returns a new empty object, which the caller frees.
func (*VM) NewPromiseCapability ¶
func (m *VM) NewPromiseCapability() (*PromiseCapability, error)
NewPromiseCapability returns a new pending promise with its resolve and reject, without evaluating any source, for Go to settle later. It runs no javascript.
A Go function of VM.RegisterFunc that is to give javascript a promise returns pc.Promise, which hands its reference to the call, and keeps pc.Resolve and pc.Reject, which it frees once it has called one:
var waiting *beastjs.PromiseCapability
m.RegisterFunc("later", func() beastjs.Value {
pc, err := m.NewPromiseCapability()
if err != nil {
return beastjs.UndefinedValue
}
waiting = pc
return pc.Promise // the call takes this reference
}, false)
m.Eval(`later().then(v => globalThis.got = v)`, beastjs.EvalGlobal)
// Later, on the goroutine that uses m:
waiting.Resolve.Call(beastjs.UndefinedValue, "done")
waiting.Resolve.Free()
waiting.Reject.Free()
m.ExecutePendingJobs()
Only a function that returns pc.Promise.Dup(), and so keeps the promise, frees pc.Promise too.
func (*VM) NewString ¶
NewString returns the string s, with U+FFFD for each byte of invalid UTF-8, which the caller frees. In a Go function that javascript called, a long string stops at Interrupt, the eval timeout or an uncatchable error of the call, and NewString returns that error, as a loop of the engine stops.
func (*VM) NewStringLatin1 ¶
NewStringLatin1 returns a new string of the characters b, one byte each: a byte is the character of its value, U+0000 to U+00FF. Unlike VM.NewString it decodes no UTF-8, so a Builtin that read its argument with Args.Latin1 returns what it made of it this way, as one copy. It ends at the limits of the call as NewString does.
func (*VM) NewStringUTF16 ¶
NewStringUTF16 returns a new string of the 16-bit units u, lone surrogates as they are. A Builtin that read its argument with Args.UTF16 returns what it made of it this way, as one copy. It ends at the limits of the call as NewString does.
func (*VM) Now ¶
Now reads the VM's wall clock with time.Time precision. Date and Intl use whole milliseconds, while Temporal preserves nanoseconds. Like the VM, Now is not safe for concurrent use.
func (*VM) OnClose ¶
func (m *VM) OnClose(f func())
OnClose makes Close run f once m is freed, so f must not use m. Each function runs once, in the order given. Nothing else runs them: not the GC, and not for a VM that is never closed. A package that keeps something for each VM in a table of its own drops it here, so that the table does not keep the VM alive.
func (*VM) RegisterCopyProps ¶
RegisterCopyProps defines a function named name on the global object that does the work of the loop with which React's createElement and cloneElement copy the keys of their config into the props of an element:
for (propName in config)
hasOwnProperty.call(config, propName) && "key" !== propName &&
"__self" !== propName && "__source" !== propName &&
(props[propName] = config[propName])
(and for cloneElement also "ref" when config.ref is undefined). It is written in C inside the engine and copies all the keys in one call, a few times faster than the loop.
The function takes four arguments: config, props, React's hasOwnProperty (the Object.prototype.hasOwnProperty it took when it loaded) and whether the call is cloneElement's. It answers true when it copied, and false when it changed nothing and the script has to run its loop. It copies only where its result and the loop's cannot differ in anything a script can see: config an ordinary object whose prototype is Object.prototype, with no more than 32 own keys, none of them an array index, __proto__ or stack, and every key the loop reads a plain data property (a getter, a setter, a proxy, a symbol key and a key that is not enumerable never change the result, or send it to the loop); props an ordinary object that can be extended, with the same prototype and only plain writable data properties; Object.prototype with no setter and no read-only property but __proto__; and hasOwnProperty.call the built-in function calling the built-in. It throws only when the engine has no memory, with the error that adding the keys would have thrown.
A page that replaces any of these after React has loaded, or gives Object.prototype a setter or a read-only property, only sends the next calls to the loop. The function is not on the global object unless a host calls this. The property is writable, configurable and not enumerable, and it replaces a configurable property of that name, as RegisterFunc does. A property that is not configurable (undefined, NaN, Infinity, a var or function of a script) is kept and RegisterCopyProps returns an error, as it does when the global object is not extensible. The name is the one javascript sees: invalid UTF-8 is replaced as Go decodes it (see Eval), and a NUL byte in it is an error. Each call makes a function of its own, and calling it again with the same name makes another one that takes the place of the first.
func (*VM) RegisterEndTag ¶
RegisterEndTag defines a function named name on the global object that gives the end tag of an element the way React DOM's server renderer does in endChunkForTag: "</" + tag + ">" for its argument tag. It is written in C inside the engine and keeps the end tag of each string it was given, so that the same string gives the same end tag again without making it. An argument that is not a string becomes one as in "</" + tag, and the function throws what that throws. The rules of the name and of the property are those of RegisterStartTag.
func (*VM) RegisterEscapeText ¶
RegisterEscapeText defines a function named name on the global object that escapes text for HTML the way React DOM's string renderer does (escapeTextForBrowser in react-dom-server-legacy.browser.production.js). It is written in C inside the engine, so a call costs about what a call of an empty JavaScript function costs, and it does the work of the whole function of React: a script that calls it in place of the function of React gets the same text.
The argument becomes a string as in "" + text: a string stays as it is, numbers, booleans and bigints become their text, an object goes through valueOf and toString (or Symbol.toPrimitive) with the hint "default", and a symbol or a toString that throws makes the call throw the same error. Then each of & < > " and ' becomes & < > " or ', one UTF-16 code unit at a time, so a lone surrogate goes through as it is. The string it was given comes back when it has none of the five. Called with no argument it answers "undefined". A string of more than 1,073,741,823 units once escaped throws a RangeError, as the function of React does when it builds that string. An interrupt or the eval timeout stops it on a long string.
The function is not on the global object unless a host calls this. The property is writable, configurable and not enumerable, and it replaces a configurable property of that name, as RegisterFunc does. A property that is not configurable (undefined, NaN, Infinity, a var or function of a script) is kept and RegisterEscapeText returns an error, as it does when the global object is not extensible. The name is the one javascript sees: invalid UTF-8 is replaced as Go decodes it (see Eval), and a NUL byte in it is an error. Each call makes a function of its own, and calling it again with the same name makes another one that takes the place of the first.
func (*VM) RegisterFunc ¶
RegisterFunc makes the Go function f a function of the global object named name, which javascript calls.
f is any Go function: a function, a closure, a method expression or a method value, with any number of parameters, variadic or not. With wantThis, its first parameter gets the this of the call, which may be null or undefined: it is not replaced by the global object.
Each argument is converted to the type of its parameter, as VM.Eval converts a value: a number that is int32 is an int, other numbers float64, an object an *Object, null a nil of a parameter that takes one. A parameter of type Value gets the argument itself, valid only during the call: to keep it, such as a resolve to call later, keep a Dup. An argument that does not convert to its parameter, or a call with too few or too many arguments, throws a TypeError.
The result becomes a javascript value; several results become an array of them. A nil error is null, and a non-nil one the string of its Error: RegisterFunc throws nothing for an error. A result that fails to convert throws a TypeError, as do a Value of another VM in a result and a result that contains itself, such as a slice that is its own element. How the results convert:
- nil, a nil pointer, interface or map is null, a nil slice []. UndefinedValue and the zero Value are undefined, and so is Undefined.
- A bool, an integer, a float and a string become their javascript value, an integer outside int32 a float. *big.Int is a BigInt. *Object is its JSON parsed.
- A slice is an array. A map with string or integer keys is an object of own data properties, in the order of the keys as strings.
- A struct converts through encoding/json, and a value whose type has an Error method is the string of Error. A String method changes nothing.
- A Value of the VM in a result is handed to the call: the result, an element of a slice or an array, a key or a value of a map and the target of a pointer each hand over one reference, which the call frees when it is done, whether the conversion succeeds, fails or panics. A copy of a Value is no new reference, only a Dup is, and a slice, map or pointer the results reach twice is still one. So a Go function that returns one of its Value arguments returns its Dup. The Values inside a struct or a value with an Error method stay the caller's.
The results are looked at, for the Values they hold, a cycle and a Value of another VM, before the conversion runs any code of the program, such as an Error or a MarshalJSON method, which then cannot change which references are taken and freed. Results whose types can hold no Value are not looked at first: they are read as they convert.
A long string argument or result, and a result of many elements or properties, stops converting at Interrupt, the eval timeout or an uncatchable error of the call, which then ends with that error.
The function becomes the property name of the global object, writable and configurable, not enumerable. It replaces a configurable property, one a script set or a built-in such as Array. A property that is not configurable, such as undefined, NaN, Infinity or a var or function of a script, is kept, and RegisterFunc returns an error, as it does when the global object is not extensible. The length of the function is the number of parameters of f less one, and at least 0.
name is the name javascript sees: invalid UTF-8 in it is U+FFFD a byte, so two Go strings can name one function. A NUL byte is an error. name should be an identifier: it is not checked yet, and may be later. A name is registered once per VM, even after a script deleted or replaced its function. A VM holds about a billion Go functions at a time at most.
For a host object prefer VM.RegisterHostFunc. A function called often, or one that is to look like a built-in, is better as a Builtin, which converts nothing and uses no reflection, and costs far less.
Example (Error) ¶
A Go error a function returns is a string to javascript, not a throw.
package main
import (
"errors"
"fmt"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
func main() {
m := newVM()
defer m.Close()
if err := m.RegisterFunc("check", func(a int) error {
if a < 0 {
return errors.New("negative")
}
return nil
}, false); err != nil {
panic(err)
}
fmt.Println(m.Eval(`check(-1)`, beastjs.EvalGlobal))
fmt.Println(m.Eval(`check(1)`, beastjs.EvalGlobal))
}
Output: negative <nil> <nil> <nil>
Example (MultipleReturn) ¶
Several results are an array.
package main
import (
"fmt"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
func main() {
m := newVM()
defer m.Close()
if err := m.RegisterFunc("scale", func(a, b int) (int, int) { return 10 * a, 100 * b }, false); err != nil {
panic(err)
}
fmt.Println(m.Eval(`scale(2, 3)`, beastjs.EvalGlobal))
}
Output: [20,300] <nil>
Example (SingleReturn) ¶
package main
import (
"fmt"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
func main() {
m := newVM()
defer m.Close()
if err := m.RegisterFunc("madd", func(a, b, c int) int { return a + b*c }, false); err != nil {
panic(err)
}
fmt.Println(m.Eval(`madd(2, 3, 5)`, beastjs.EvalGlobal))
}
Output: 17 <nil>
Example (ThisNonNull) ¶
Called as a method, it gets the object, here as its JSON.
package main
import (
"fmt"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
func main() {
m := newVM()
defer m.Close()
if err := m.RegisterFunc("gofunc", func(this any) any { return this }, true); err != nil {
panic(err)
}
fmt.Println(m.Eval(`({foo: 314, gofunc}).gofunc()`, beastjs.EvalGlobal))
}
Output: {"foo":314} <nil>
Example (ThisNonNull2) ¶
package main
import (
"fmt"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
func main() {
m := newVM()
defer m.Close()
if err := m.RegisterFunc("gofunc", func(this any, a int) (any, int) { return this, 10 * a }, true); err != nil {
panic(err)
}
fmt.Println(m.Eval(`({foo: 314, gofunc}).gofunc(42)`, beastjs.EvalGlobal))
}
Output: [{"foo":314},420] <nil>
Example (ThisNull) ¶
Called on its own, a function that wants this gets undefined.
package main
import (
"fmt"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
func main() {
m := newVM()
defer m.Close()
if err := m.RegisterFunc("gofunc", func(this any) any { return this }, true); err != nil {
panic(err)
}
fmt.Println(m.Eval(`gofunc()`, beastjs.EvalGlobal))
}
Output: undefined <nil>
Example (ThisNull2) ¶
Undefined in an array is null in its JSON.
package main
import (
"fmt"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
func main() {
m := newVM()
defer m.Close()
if err := m.RegisterFunc("gofunc", func(this any, a int) (any, int) { return this, 10 * a }, true); err != nil {
panic(err)
}
fmt.Println(m.Eval(`gofunc(42)`, beastjs.EvalGlobal))
}
Output: [null,420] <nil>
Example (Void) ¶
A function with no result returns undefined.
package main
import (
"fmt"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
func main() {
m := newVM()
defer m.Close()
if err := m.RegisterFunc("show", func(a, b, c int) { fmt.Println(a + b*c) }, false); err != nil {
panic(err)
}
fmt.Println(m.Eval(`show(2, 3, 5)`, beastjs.EvalGlobal))
}
Output: 17 undefined <nil>
func (*VM) RegisterHostFunc ¶
RegisterHostFunc makes fn a function of the global object named name, which javascript calls. Each argument of the call is converted to a Go value, as VM.Eval converts a value, into the slice fn gets. The value fn returns is converted back, by the rules of the results of VM.RegisterFunc, Values and their references too. A non-nil error is thrown as a TypeError with the text of the error, and the value is not converted: the references it holds are freed before the Error method of the error runs. Unlike RegisterFunc, which makes the array [value, error] of the two, fn returns one value or throws. name is as for RegisterFunc.
Each call converts every argument by reflection: a function called often is better as a Builtin.
func (*VM) RegisterStartTag ¶
RegisterStartTag defines a function named name on the global object that writes the start tag of an element the way React DOM's server renderer does in pushStartGenericElement (react-dom-server-legacy.browser.production.js of react-dom 19.3), with the functions it calls: startChunkForTag, pushAttribute, pushStyleAttribute, escapeTextForBrowser and the others. It is written in C inside the engine and writes the whole tag in one call, a few times faster than those functions.
The function takes seven arguments: target, props, type and formatContext, those of pushStartGenericElement, then React's hasOwnProperty (the Object.prototype.hasOwnProperty it took when it loaded) and decline, an object only the caller holds. It pushes onto target one string, the start tag with its attributes and, when props.children is a string, the escaped text after it, and returns what pushStartGenericElement returns: null when children is a string, else props.children, or null when there is none. React pushes the same text in several strings. A seventh argument, the mode, makes it stand in for another function of React: 1 for pushSelfClosing, which React DOM writes img (after its image preload) and the void elements such as br and hr with: the attributes, "/>" and no text, null returned, and a decline when children is set, where React throws. 2 is the case "input" of pushStartInstance: the same, with name, formAction, formEncType, formMethod, formTarget, checked and value (or defaultChecked and defaultValue) written after the other props, as React writes them, and a decline when formAction is a function. 3 is the branch of the case "style" of pushStartInstance that writes the element where it is, as emotion's style elements are written: the attributes, ">", the __html of dangerouslySetInnerHTML as it is and the end tag, null returned, and a decline for children and for an __html that is not a string, null or undefined. undefined and 0 are pushStartGenericElement, and any other mode declines, so that a script that asks for a mode the engine does not have gets React's function. When it cannot be sure to write what React writes it returns decline, having changed nothing, and the script runs React's function. That is the case for an unusual target (not a plain array, an index property ever put on Array.prototype or Object.prototype, where push would set it, or Array.prototype.push replaced), a tag React refuses, a formatContext whose viewTransition is not null, props or a style that are not plain objects of Object.prototype with at most 32 keys, a getter, an array index key, dangerouslySetInnerHTML, the rare attributes xlinkHref, capture, download, cols, rows, size, span, rowSpan and start, a value that React would turn into a string by calling its toString (an object) or a bigint, a javascript: URL, a name of the default branch that is not ASCII or is 64 characters or more, a style name that is not ASCII and does not start with --, a tag that would be too long, and hasOwnProperty.call that is not the built-in function calling the built-in. The built-ins are found by their C function, so one replaced before registering is not taken for them, and registering runs no script. It assumes that the built-in methods of String, RegExp, Map and Set that React's functions call are still those of the engine. It throws only when the engine has no memory, or when an interrupt or the eval timeout stops it on a long string, and target is then unchanged.
The function is not on the global object unless a host calls this. The property is writable, configurable and not enumerable, and it replaces a configurable property of that name, as RegisterFunc does. A property that is not configurable (undefined, NaN, Infinity, a var or function of a script) is kept and RegisterStartTag returns an error, as it does when the global object is not extensible. The name is the one javascript sees: invalid UTF-8 is replaced as Go decodes it (see Eval), and a NUL byte in it is an error. Each call makes a function of its own, and calling it again with the same name makes another one that takes the place of the first.
func (*VM) ReleaseMemory ¶
ReleaseMemory gives memory that m keeps free back to the system, all but keep bytes of it, and returns how many bytes it gave back. The objects of m stay as they are. Call it when m has done a large piece of work, such as after loading a bundle or after VM.RunGC: the memory comes back when m needs it again.
It returns an error while m runs javascript, as from a Go function that javascript called. As with SetGCThreshold, no other goroutine may use m meanwhile (see VM).
func (*VM) RunGC ¶
func (m *VM) RunGC()
RunGC frees what javascript can no longer reach, cycles too, and gives the small blocks the runtime keeps for reuse back to its arenas. The GC threshold is then 1.5 times what is left, unless it is ^uintptr(0). It runs no javascript: the callbacks of a FinalizationRegistry are queued for the next VM.ExecutePendingJobs.
func (*VM) RunYoungGC ¶
func (m *VM) RunYoungGC()
RunYoungGC frees the cycles among the objects made since the last collection, young or full, and makes those it keeps old. It takes time in proportion to the young objects, which suits a run after each render.
It frees less than VM.RunGC: a cycle through an old object, and the value of a WeakMap entry whose map is reachable or old, wait for the next RunGC, so run RunGC now and then too. It treats weak references and FinalizationRegistry as RunGC does, and leaves the GC threshold as it is.
func (*VM) SetClock ¶
SetClock sets the wall clock of this VM. Date.now(), new Date(), Date(), Intl's current time and Temporal.Now (unless temporal.Clock overrides it) read now. nil restores time.Now. Set it only between calls into JavaScript, never concurrently with the VM or from a callback running inside it. The callback must not block. If several VMs share it, it must be safe for concurrent calls. Close releases it. It does not affect performance.now(), eval timeouts, Atomics.wait or the random seed.
func (*VM) SetEvalTimeout ¶
SetEvalTimeout sets how long a call into javascript may run, d, from the next call on: each outermost call has d from when it starts, on the monotonic clock, so setting the system clock changes nothing. d of 0 or less is no timeout, and so is one longer than the clock can count, about 292 years. A call that runs out of time ends with an *Error whose Interrupted is set.
The timeout holds for every method that runs javascript: the Eval methods, Compile, the Call methods, ExecutePendingJobs, Value.Then, the property methods GetProperty, GetPropertyValue, SetProperty and SetPropertyValue and the methods of Value that call them, Value.MarshalJSON, Value.Any and ErrorFromValue. A method that runs no javascript, such as NewAtom or NewObjectValue, has none. A call a Go function makes from javascript, on the same VM, runs in the time left to the outer call.
Example ¶
Each call has the whole timeout, and a loop that never ends stops when it runs out.
package main
import (
"fmt"
"time"
"github.com/liustack/beastjs"
)
// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
m, err := beastjs.NewVM()
if err != nil {
panic(err)
}
return m
}
func main() {
m := newVM()
defer m.Close()
for _, d := range []time.Duration{100 * time.Millisecond, time.Second, 3 * time.Second} {
m.SetEvalTimeout(d)
start := time.Now()
v, err := m.Eval(`for (;;) {}`, beastjs.EvalGlobal)
took := time.Since(start)
fmt.Println(v, err, d, took >= d/2 && took <= d*3/2)
}
}
Output: <nil> InternalError: interrupted 100ms true <nil> InternalError: interrupted 1s true <nil> InternalError: interrupted 3s true
func (*VM) SetGCThreshold ¶
SetGCThreshold sets how much memory m may take before the engine runs a collection by itself (see VM.GCThreshold). ^uintptr(0) keeps the engine from running one.
func (*VM) SetMaxStackSize ¶
SetMaxStackSize sets how deep javascript calls may nest, 0 for the default of 5000, at most 10000. A deeper recursion throws a RangeError the script can catch.
func (*VM) SetMemoryLimit ¶
SetMemoryLimit sets the most memory m may take, in bytes, as VM.MemorySize counts it. A limit below 128 KiB is taken as 128 KiB, 0 too: it is not "no limit". ^uintptr(0) is no limit. A call that would pass the limit ends with an *Error whose OutOfMemory is set.
A limit that is too small is not kept to, as m needs memory to make the error itself. How small that is is not promised.
func (*VM) SetProperty ¶
SetProperty sets the property prop of this to val, converted as an argument of VM.Call is, as VM.SetPropertyValue does.
func (*VM) SetPropertyValue ¶
SetPropertyValue sets the property prop of this to val, as an assignment in strict code does: a setter runs, and a write the object refuses, as a Proxy can, is a TypeError. val stays the caller's. UndefinedValue and the zero Value are undefined. A Value of another VM is an error.
func (*VM) SetRegExpCache ¶
SetRegExpCache sets how many compiled regexps m keeps at most, n, and in how many bytes, counting their patterns and flags. It lets go of the regexps kept so far. 0 for either keeps none. A new VM keeps DefaultRegExpCache in DefaultRegExpCacheBytes.
A regexp whose pattern and flags are strings, from a literal, new RegExp, RegExp, compile or the copy split makes, takes the bytecode kept for the same pattern and flags when it is compiled. The one used least recently goes when there is no room. What is kept counts toward the memory limit, and m does not let it go when an allocation fails, so a script that runs close to the limit can run out of memory with the cache on where it would not without it.
func (*VM) SetShapeCache ¶
SetShapeCache sets how many shapes m keeps once nothing uses them, n from 0, which keeps none, to math.MaxInt32/8. A shape is the list of an object's keys in their order. m keeps the shapes of plain objects: whose prototype is Object.prototype, with at most 32 keys and no symbol key that is not registered. The next object made with the same keys then finds its shape kept. A new VM keeps DefaultShapeCache.
The kept shapes count toward the memory limit (see VM.SetMemoryLimit), and each holds the atoms of its keys: about 100 bytes for a few keys, and about 3 KiB for 32 keys of ten characters each that no other object has, so 2048 such shapes take about 6 MiB. The table of atoms does not shrink once it grew. An allocation that would pass the memory limit lets go of all the kept shapes first.
func (*VM) SetStrip ¶
SetStrip sets what the functions m compiles from now on leave out: those of the Eval methods and Compile, and those of a script's own eval and new Function. With StripSource the toString of a function shows [native code]. StripDebug leaves out file names and line and column numbers, so that a stack frame shows only the name of its function, and the source too. Functions compiled before stay as they are.
The bytecode of VM.Compile keeps what it left out in every VM that loads it. Compiled on a VM of its own with both, a polyfill looks like a built-in function.
func (*VM) TrackRejections ¶
func (*VM) UnhandledRejections ¶
UnhandledRejections takes the rejections m kept when it is called (see VM.TrackRejections), oldest first, at most MaxTrackedRejections, and forgets them. Each reason is read as the error of a call that threw it is: an Error gives its Name, Message and Stack, any other value its text. Each text is cut to its first 8 KiB of UTF-8, or up to three bytes fewer so that no character is cut, followed by " [cut]" when it was longer: a reason is for a log, and javascript can make a string of hundreds of MiB, or a thousand references to one. dropped is how many rejections were not kept since the last call, past the limit or with no memory: a handler may have been attached to some of them since.
Reading a reason runs javascript, such as a getter of its message, inside the eval timeout. A rejection that this javascript makes is kept for the next call, after its jobs could attach a handler to it. The timeout and VM.Interrupt are read before each reason too. When one ends the call, UnhandledRejections returns the reasons read before it and the interrupt, and the rejections after the one it was reading stay kept.
What Go allocates for the reasons is taken from the room m has under its memory limit (see VM.SetMemoryLimit): before each reason, the most it may take, about 50 KiB, and then each text before it is copied, after the getters that ran before it. When the room left is less, UnhandledRejections returns the reasons read before and the out of memory error, and the rejections after the one it was reading stay kept. So a read allocates at most about 50 MiB in Go for 1,024 reasons, of which it keeps at most 40 MiB of texts. Javascript a getter runs after a text was copied can still use the room it took, so m and the read together may pass the limit by what the read holds in Go.
The error a read ends with has its texts cut the same way, so that all it returns is bounded. The errors of the other calls are not cut.
A read is the only one on m while it runs: called from javascript it runs, UnhandledRejections returns an error and takes nothing, as TrackRejections does.
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value is a javascript value that Go holds a reference to. The value lives as long as a reference to it does, and the javascript GC frees it once none does, so Go code that holds a Value keeps to these rules:
- Each Value is freed with Free once, and not used after. Dropping one unfreed leaks it, until the VM closes.
- A copy of a Value, by an assignment, is not a new reference. Dup makes one, which is freed on its own. Hand a Value on as a Dup, which the receiver frees, typically with defer.
- A Value does not outlive its VM.
Dup and Free pair up, and the pairs nest as calls do. That is easy to get wrong across goroutines or channels: say g1 hands a Value to g2 by assignment, not by Dup, and both free it when they are done. If g1 frees first, g2 then uses a value that may be gone, and frees it a second time. The fix is for g1 to wait until g2 is done before it frees, or to hand g2 a Dup.
Where a Go value does, as with Eval and Call, use it: it needs none of this.
UndefinedValue and the zero Value belong to no VM, hold no reference and are undefined to every VM: freeing one does nothing, and Dup of one panics, as that is most often a Value used after its Free.
func (Value) Any ¶
Any returns v as a Go value, as VM.Eval converts it. v stays the caller's. Converting an object or a BigInt runs javascript, inside the eval timeout. UndefinedValue and the zero Value are Undefined{}.
func (Value) Call ¶
Call calls v with this and args and returns its value as a Go value, as VM.Call does with the same arguments. this is used as it is, not replaced by the global object: UndefinedValue is undefined.
A Go error is not among the types an argument converts by, so it goes as its JSON, which for an error of the standard library is {}: pass err.Error(). A Value that a function of VM.RegisterFunc gets, such as the resolve of a promise, is valid only during the call it got it in: to call it later, keep a Dup and free it when done.
func (Value) CallValue ¶
CallValue is Value.Call that returns the value as a Value, which the caller frees.
func (Value) Dup ¶
Dup returns a new reference to v, which is freed on its own. It panics for a Value of no VM, which is most often one used after its Free.
func (*Value) Free ¶
func (v *Value) Free()
Free gives up the reference v holds, and makes v the zero Value. It does nothing for UndefinedValue and the zero Value.
func (Value) GetProperty
deprecated
func (Value) GetPropertyValue ¶
GetPropertyValue returns the property prop of v (see VM.GetPropertyValue).
func (Value) IsUndefined ¶
IsUndefined reports whether v is undefined. UndefinedValue and the zero Value are.
func (Value) MarshalJSON ¶
MarshalJSON returns the JSON of v, as JSON.stringify makes it, so that encoding/json writes a Value as the javascript value. For a value JSON.stringify gives undefined for, such as a function, it is the text undefined, which is not JSON. It runs javascript, such as toJSON, inside the eval timeout.
func (Value) Property ¶
Property returns the property prop of v as a Go value (see VM.GetProperty).
func (Value) SetProperty ¶
SetProperty sets the property prop of v to val (see VM.SetProperty).
func (Value) SetPropertyValue ¶
SetPropertyValue sets the property prop of v to val (see VM.SetPropertyValue).
func (Value) Then ¶
Then attaches onFulfilled and onRejected to the promise v, as v.then does, and returns the promise then returns, which the caller frees. Either may be nil. A handler gets the value or the reason, valid only during its call. Each is held until the engine frees the function that calls it, even when it never ran, or the VM closes.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
beastjs
command
Command beastjs runs a JavaScript file in the engine of this module, set up as tifa sets it up, without writing Go:
|
Command beastjs runs a JavaScript file in the engine of this module, set up as tifa sets it up, without writing Go: |
|
Package fmt gives a beastjs.VM some of Go's fmt: printf, println, sprint and sprintf.
|
Package fmt gives a beastjs.VM some of Go's fmt: printf, println, sprint and sprintf. |
|
internal
|
|
|
cengine
Package cengine is the C engine of engine/ generated as Go assembly, with its Go host.
|
Package cengine is the C engine of engine/ generated as Go assembly, with its Go host. |
|
cengine/cmd/gcpause
command
Command gcpause measures how long the Go garbage collector waits to stop the world while VMs run a script that stays in the engine.
|
Command gcpause measures how long the Go garbage collector waits to stop the world while VMs run a script that stays in the engine. |
|
cengine/cmd/interrupt
command
Command interrupt times how long a script takes to stop after Interrupt, for the scripts of package scenarios, each of which stays inside one long operation of the engine.
|
Command interrupt times how long a script takes to stop after Interrupt, for the scripts of package scenarios, each of which stays inside one long operation of the engine. |
|
cengine/cmd/jsrun
command
Command jsrun evaluates a JavaScript file and prints its result, how long the evaluation took and what memory the VM held.
|
Command jsrun evaluates a JavaScript file and prints its result, how long the evaluation took and what memory the VM held. |
|
cengine/cmd/scenarios
Package scenarios holds the scripts that the commands gcpause and interrupt run: each stays inside one long operation of the engine.
|
Package scenarios holds the scripts that the commands gcpause and interrupt run: each stays inside one long operation of the engine. |
|
dtoatable
command
Command dtoatable writes engine/dtoa-pow10.h, the table of powers of ten that the shortest conversion of a float64 to decimal in engine/dtoa.c uses (the Schubfach algorithm of Raffaello Giulietti, written from his paper "The Schubfach way to render doubles").
|
Command dtoatable writes engine/dtoa-pow10.h, the table of powers of ten that the shortest conversion of a float64 to decimal in engine/dtoa.c uses (the Schubfach algorithm of Raffaello Giulietti, written from his paper "The Schubfach way to render doubles"). |
|
faultstate
Package faultstate tells whether the state of the CPU that windows/arm64 writes below the stack pointer at a fault fits in the room Go keeps for it, so that a fault in the engine cannot write past a goroutine stack into the heap.
|
Package faultstate tells whether the state of the CPU that windows/arm64 writes below the stack pointer at a fault fits in the room Go keeps for it, so that a fault in the engine cannot write past a goroutine stack into the heap. |
|
faulttest
Package faulttest is for the tests that make a memory fault on purpose: a read through a wild pointer, or a write to a guard page or to read-only memory.
|
Package faulttest is for the tests that make a memory fault on purpose: a read through a wild pointer, or a write to a guard page or to read-only memory. |
|
goasm/cmd/cycles
command
Command cycles lists the cycles of the engine's call graph that no counted depth cuts.
|
Command cycles lists the cycles of the engine's call graph that no counted depth cuts. |
|
goasm/cmd/xform
command
Command xform moves the code of generated Go assembly, to measure how much a speed result depends on where the code sits (see "Code positions" in docs/internals/performance.md).
|
Command xform moves the code of generated Go assembly, to measure how much a speed result depends on where the code sits (see "Code positions" in docs/internals/performance.md). |
|
goasm/gen/cmd/engine
command
|
|
|
goasm/gen/cmd/gen
command
|
|
|
goasm/gen/cmd/gocalls
command
Command gocalls writes internal/cengine/gocalls.txt, the engine functions the Go code of the module names (gen.GoCalls).
|
Command gocalls writes internal/cengine/gocalls.txt, the engine functions the Go code of the module names (gen.GoCalls). |
|
gohost
Package gohost is the Go side of the callbacks the C engine asks of its host (engine/host.h and host_memory_grow in engine/heap.h), for the engine generated as Go assembly.
|
Package gohost is the Go side of the callbacks the C engine asks of its host (engine/host.h and host_memory_grow in engine/heap.h), for the engine generated as Go assembly. |
|
gointl/internal/qjspack/gen
command
|
|
|
goversion
Package goversion stops a build with a Go newer than the one the engine was checked with.
|
Package goversion stops a build with a Go newer than the one the engine was checked with. |
|
hostmem
Package hostmem is the memory the Go host gives the C engine.
|
Package hostmem is the memory the Go host gives the C engine. |
|
idtable
Package idtable gives things small ids, which the C engine passes back to the host on every callback, and finds a thing by its id with two atomic reads and no lock: callbacks of VMs on many goroutines do not wait for each other, and do not write to memory they share.
|
Package idtable gives things small ids, which the C engine passes back to the host on every callback, and finds a thing by its id with two atomic reads and no lock: callbacks of VMs on many goroutines do not wait for each other, and do not write to memory they share. |
|
intlhook
Package intlhook connects the Intl and Temporal shims.
|
Package intlhook connects the Intl and Temporal shims. |
|
measure
Package measure holds what the subcommands of go tool measure share: running a command with its output kept and timed.
|
Package measure holds what the subcommands of go tool measure share: running a command with its output kept and timed. |
|
measure/bench
Package bench builds the code-position variants of a program, times them in turn, and reads the result by the protocol of docs/internals/measuring.md.
|
Package bench builds the code-position variants of a program, times them in turn, and reads the result by the protocol of docs/internals/measuring.md. |
|
measure/cmd/measure
command
Command measure times builds of the C engine against each other.
|
Command measure times builds of the C engine against each other. |
|
measure/hwm
Package hwm reads the most memory the calling process held, from the process itself, for the programs that go tool measure times.
|
Package hwm reads the most memory the calling process held, from the process itself, for the programs that go tool measure times. |
|
rvgen
Package rvgen makes small random JavaScript programs for testing the register loop of the engine (engine/regvm.h): against Node (rvgen node) and in the tests of the Go package.
|
Package rvgen makes small random JavaScript programs for testing the register loop of the engine (engine/regvm.h): against Node (rvgen node) and in the tests of the Go package. |
|
rvgen/cmd/rvgen
command
Command rvgen makes random programs (package rvgen) and runs them through rvdiff, the runner of the native test host that compares each run with its golden (engine/test/regvm/rvdiff.c, built by engine/test/regvm/build.sh):
|
Command rvgen makes random programs (package rvgen) and runs them through rvdiff, the runner of the native test host that compares each run with its golden (engine/test/regvm/rvdiff.c, built by engine/test/regvm/build.sh): |
|
rvgen/v1
Package v1 is rvgen frozen as it was when the goldens of the fuzz seeds were recorded from the old loop (engine/test/regvm/golden/seeds, see rvgen check): the same seed must make the same program for good, so this copy is never changed.
|
Package v1 is rvgen frozen as it was when the goldens of the fuzz seeds were recorded from the old loop (engine/test/regvm/golden/seeds, see rvgen check): the same seed must make the same program for good, so this copy is never changed. |
|
stopsweep
Package stopsweep is for the tests of the packages that give a VM functions written in Go (intl, temporal, fmt and url): it stops a long call at many eval timeouts, so that a part of the call that does not check the limits shows wherever it lies in the call, not only where one fixed timeout falls.
|
Package stopsweep is for the tests of the packages that give a VM functions written in Go (intl, temporal, fmt and url): it stops a long call at many eval timeouts, so that a part of the call that does not check the limits shows wherever it lies in the call, not only where one fixed timeout falls. |
|
stress
command
Command stress renders tifa's pinned pages for a set time on pools of VMs kept as tifa's pool keeps them, with memory limits, eval timeouts, Interrupts and kills landing at random points of the renders, and checks that every VM stays correct and bounded: each render gives the page's HTML or the error its stop documents, a VM goes on after a stop that was not a kill, the memory of the engine, of the host and of Go and the goroutines stay bounded with no drift after the warm-up, and closing every VM gives all its memory back.
|
Command stress renders tifa's pinned pages for a set time on pools of VMs kept as tifa's pool keeps them, with memory limits, eval timeouts, Interrupts and kills landing at random points of the renders, and checks that every VM stays correct and bounded: each render gives the page's HTML or the error its stop documents, a VM goes on after a stop that was not a kill, the memory of the engine, of the host and of Go and the goroutines stay bounded with no drift after the warm-up, and closing every VM gives all its memory back. |
|
unsupported
Package unsupported stops a build on a target the C engine does not run on: it runs on linux, darwin and windows, on amd64 and arm64, only.
|
Package unsupported stops a build on a target the C engine does not run on: it runs on linux, darwin and windows, on amd64 and arm64, only. |
|
vmhook
Package vmhook lets the packages of this module that give a VM functions written in Go (intl, temporal, fmt and url) hold the work those functions do in Go to the limits of the VM: its eval timeout, Interrupt and its memory limit, which the engine's polls and allocator see only for the work done in the engine.
|
Package vmhook lets the packages of this module that give a VM functions written in Go (intl, temporal, fmt and url) hold the work those functions do in Go to the limits of the VM: its eval timeout, Interrupt and its memory limit, which the engine's polls and allocator see only for the work done in the engine. |
|
whatwgurl
Package whatwgurl is the URL parser of the WHATWG URL standard (https://url.spec.whatwg.org/), with the setters of its API and the serializer, for package url.
|
Package whatwgurl is the URL parser of the WHATWG URL standard (https://url.spec.whatwg.org/), with the setters of its API and the serializer, for package url. |
|
whatwgurl/bidi
Package bidi has the Bidi class of a rune and implements the Bidi Rule defined by RFC 5893.
|
Package bidi has the Bidi class of a rune and implements the Bidi Rule defined by RFC 5893. |
|
whatwgurl/idna
Package idna is the part of golang.org/x/net/idna v0.62.0 (IDNA2008 with the compatibility processing of UTS #46) that the URL standard needs: one profile, "domain to ASCII", which has Unicode 17's tables and the algorithm of UTS #46 revision 35.
|
Package idna is the part of golang.org/x/net/idna v0.62.0 (IDNA2008 with the compatibility processing of UTS #46) that the URL standard needs: one profile, "domain to ASCII", which has Unicode 17's tables and the algorithm of UTS #46 revision 35. |
|
Package intl gives a beastjs.VM the ECMA-402 Intl API, computed in Go.
|
Package intl gives a beastjs.VM the ECMA-402 Intl API, computed in Go. |
|
Package temporal implements Temporal, the ECMAScript date and time API, for a beastjs.VM.
|
Package temporal implements Temporal, the ECMAScript date and time API, for a beastjs.VM. |
|
Package tifa gives a beastjs.VM what tifa (github.com/liustack/tifa) gives each VM of its pool before it runs a bundle: URL and URLSearchParams, Intl and Temporal, and the functions named __tifa_* that the bundles tifa builds ask for.
|
Package tifa gives a beastjs.VM what tifa (github.com/liustack/tifa) gives each VM of its pool before it runs a bundle: URL and URLSearchParams, Intl and Temporal, and the functions named __tifa_* that the bundles tifa builds ask for. |
|
Package url gives a beastjs.VM the globals URL and URLSearchParams, as the URL standard (https://url.spec.whatwg.org/) defines them, with the parsing done in Go.
|
Package url gives a beastjs.VM the globals URL and URLSearchParams, as the URL standard (https://url.spec.whatwg.org/) defines them, with the parsing done in Go. |