package goja

Import Path
	github.com/dop251/goja (on go.dev)

Dependency Relation
	imports 35 packages, and imported by one package


Package-Level Type Names (total 34)
/* sort by: | */
ArrayBuffer is a Go wrapper around ECMAScript ArrayBuffer. Calling Runtime.ToValue() on it returns the underlying ArrayBuffer. Calling Export() on an ECMAScript ArrayBuffer returns a wrapper. Use Runtime.NewArrayBuffer([]byte) to create one. Bytes returns the underlying []byte for this ArrayBuffer. For detached ArrayBuffers returns nil. Detach the ArrayBuffer. After this, the underlying []byte becomes unreferenced and any attempt to use this ArrayBuffer results in a TypeError. Returns false if it was already detached, true otherwise. Note, this method may only be called from the goroutine that 'owns' the Runtime, it may not be called concurrently. Detached returns true if the ArrayBuffer is detached. ArrayBuffer : github.com/apache/arrow-go/v18/internal/hashing.ByteSlice func (*Runtime).NewArrayBuffer(data []byte) ArrayBuffer
AsyncContextTracker is a handler that allows to track an async execution context to ensure it remains consistent across all callback invocations. Whenever a Promise reaction job is scheduled the Grab method is called. It is supposed to return the current context. The same context will be supplied to the Resumed method before the reaction job is executed. The Exited method is called after the reaction job is finished. This means that for each invocation of the Grab method there will be exactly one subsequent invocation of Resumed and then Exited methods (assuming the Promise is fulfilled or rejected). Also, the Resumed/Exited calls cannot be nested, so Exited can simply clear the current context instead of popping from a stack. Note, this works for both async functions and regular Promise.then()/Promise.catch() callbacks. See TestAsyncContextTracker for more insight. To register it call Runtime.SetAsyncContextTracker(). ( AsyncContextTracker) Exited() ( AsyncContextTracker) Grab() (trackingObject interface{}) ( AsyncContextTracker) Resumed(trackingObject interface{}) func (*Runtime).SetAsyncContextTracker(tracker AsyncContextTracker)
Callable represents a JavaScript function that can be called from Go. func AssertFunction(v Value) (Callable, bool)
File *file.File Message string Offset int
CompilerError CompilerError CompilerError.File *file.File CompilerError.Message string CompilerError.Offset int (*CompilerReferenceError) Error() string *CompilerReferenceError : error
CompilerError CompilerError CompilerError.File *file.File CompilerError.Message string CompilerError.Offset int (*CompilerSyntaxError) Error() string *CompilerSyntaxError : error
Constructor is a type that can be used to call constructors. The first argument (newTarget) can be nil which sets it to the constructor function itself. func AssertConstructor(v Value) (Constructor, bool)
Arguments []Value NewTarget *Object This *Object ( ConstructorCall) Argument(idx int) Value
DynamicArray is an interface representing a handler for a dynamic array Object. Such an object can be created using the Runtime.NewDynamicArray() method. Any integer property key or a string property key that can be parsed into an int value (including negative ones) is treated as an index and passed to the trap methods of the DynamicArray. Note this is different from the regular ECMAScript arrays which only support positive indexes up to 2^32-1. DynamicArray cannot be sparse, i.e. hasOwnProperty(num) will return true for num >= 0 && num < Len(). Deleting such a property is equivalent to setting it to undefined. Note that this creates a slight peculiarity because hasOwnProperty() will still return true, even after deletion. Note that Runtime.ToValue() does not have any special treatment for DynamicArray. The only way to create a dynamic array is by using the Runtime.NewDynamicArray() method. This is done deliberately to avoid silent code breaks when this interface changes. Get an item at index idx. Note that idx may be any integer, negative or beyond the current length. Len returns the current array length. Set an item at index idx. Note that idx may be any integer, negative or beyond the current length. The expected behaviour when it's beyond length is that the array's length is increased to accommodate the item. All elements in the 'new' section of the array should be zeroed. SetLen is called when the array's 'length' property is changed. If the length is increased all elements in the 'new' section of the array should be zeroed. func NewSharedDynamicArray(a DynamicArray) *Object func (*Runtime).NewDynamicArray(a DynamicArray) *Object
DynamicObject is an interface representing a handler for a dynamic Object. Such an object can be created using the Runtime.NewDynamicObject() method. Note that Runtime.ToValue() does not have any special treatment for DynamicObject. The only way to create a dynamic object is by using the Runtime.NewDynamicObject() method. This is done deliberately to avoid silent code breaks when this interface changes. Delete the property for the key. Returns true on success (note, that includes missing property). Get a property value for the key. May return nil if the property does not exist. Has should return true if and only if the property exists. Keys returns a list of all existing property keys. There are no checks for duplicates or to make sure that the order conforms to https://262.ecma-international.org/#sec-ordinaryownpropertykeys Set a property value for the key. Return true if success, false otherwise. func NewSharedDynamicObject(d DynamicObject) *Object func (*Runtime).NewDynamicObject(d DynamicObject) *Object
(*Exception) Error() string (*Exception) Stack() []StackFrame (*Exception) String() string (*Exception) Unwrap() error (*Exception) Value() Value *Exception : error *Exception : expvar.Var *Exception : fmt.Stringer *Exception : golang.org/x/xerrors.Wrapper func (*Runtime).Try(f func()) *Exception
FieldNameMapper provides custom mapping between Go and JavaScript property names. FieldName returns a JavaScript name for the given struct field in the given type. If this method returns "" the field becomes hidden. MethodName returns a JavaScript name for the given method in the given type. If this method returns "" the method becomes hidden. func TagFieldNameMapper(tagName string, uncapMethods bool) FieldNameMapper func UncapFieldNameMapper() FieldNameMapper func (*Runtime).SetFieldNameMapper(mapper FieldNameMapper)
( Flag) Bool() bool func ToFlag(b bool) Flag func (*Object).DefineAccessorProperty(name string, getter, setter Value, configurable, enumerable Flag) error func (*Object).DefineAccessorPropertySymbol(name *Symbol, getter, setter Value, configurable, enumerable Flag) error func (*Object).DefineDataProperty(name string, value Value, writable, configurable, enumerable Flag) error func (*Object).DefineDataPropertySymbol(name *Symbol, value Value, writable, configurable, enumerable Flag) error const FLAG_FALSE const FLAG_NOT_SET const FLAG_TRUE
Arguments []Value This Value ( FunctionCall) Argument(idx int) Value
baseUncatchableException.Exception Exception (*InterruptedError) Error() string (*InterruptedError) Stack() []StackFrame (*InterruptedError) String() string (*InterruptedError) Unwrap() error (*InterruptedError) Value() interface{} *InterruptedError : error *InterruptedError : expvar.Var *InterruptedError : fmt.Stringer *InterruptedError : golang.org/x/xerrors.Wrapper
JsonEncodable allows custom JSON encoding by JSON.stringify() Note that if the returned value itself also implements JsonEncodable, it won't have any effect. ( JsonEncodable) JsonEncodable() interface{}
func (*Runtime).SetTimeSource(now Now)
ClassName returns the class name DefineAccessorProperty is a Go equivalent of Object.defineProperty(o, name, {get: getter, set: setter, configurable: configurable, enumerable: enumerable}) DefineAccessorPropertySymbol is a Go equivalent of Object.defineProperty(o, name, {get: getter, set: setter, configurable: configurable, enumerable: enumerable}) DefineDataProperty is a Go equivalent of Object.defineProperty(o, name, {value: value, writable: writable, configurable: configurable, enumerable: enumerable}) DefineDataPropertySymbol is a Go equivalent of Object.defineProperty(o, name, {value: value, writable: writable, configurable: configurable, enumerable: enumerable}) (*Object) Delete(name string) error (*Object) DeleteSymbol(name *Symbol) error (*Object) Equals(other Value) bool Export the Object to a plain Go type. If the Object is a wrapped Go value (created using ToValue()) returns the original value. If the Object is a function, returns func(FunctionCall) Value. Note that exceptions thrown inside the function result in panics, which can also leave the Runtime in an unusable state. Therefore, these values should only be used inside another ES function implemented in Go. For calling a function from Go, use AssertFunction() or Runtime.ExportTo() as described in the README. For a Map, returns the list of entries as [][2]interface{}. For a Set, returns the list of elements as []interface{}. For a Proxy, returns Proxy. For a Promise, returns Promise. For a DynamicObject or a DynamicArray, returns the underlying handler. For typed arrays it returns a slice of the corresponding type backed by the original data (i.e. it does not copy). For an untyped array, returns its items exported into a newly created []interface{}. In all other cases returns own enumerable non-symbol properties as map[string]interface{}. This method will panic with an *Exception if a JavaScript exception is thrown in the process. Use Runtime.Try to catch these. ExportType returns the type of the value that is returned by Export(). Get an object's property by name. This method will panic with an *Exception if a JavaScript exception is thrown in the process. Use Runtime.Try to catch these. GetOwnPropertyNames returns a list of all own string properties of the Object, similar to Object.getOwnPropertyNames() This method will panic with an *Exception if a JavaScript exception is thrown in the process. Use Runtime.Try to catch these. GetSymbol returns the value of a symbol property. Use one of the Sym* values for well-known symbols (such as SymIterator, SymToStringTag, etc...). This method will panic with an *Exception if a JavaScript exception is thrown in the process. Use Runtime.Try to catch these. Keys returns a list of Object's enumerable keys. This method will panic with an *Exception if a JavaScript exception is thrown in the process. Use Runtime.Try to catch these. MarshalJSON returns JSON representation of the Object. It is equivalent to JSON.stringify(o). Note, this implements json.Marshaler so that json.Marshal() can be used without the need to Export(). Prototype returns the Object's prototype, same as Object.getPrototypeOf(). If the prototype is null returns nil. (*Object) SameAs(other Value) bool (*Object) Set(name string, value interface{}) error SetPrototype sets the Object's prototype, same as Object.setPrototypeOf(). Setting proto to nil is an equivalent of Object.setPrototypeOf(null). (*Object) SetSymbol(name *Symbol, value interface{}) error (*Object) StrictEquals(other Value) bool (*Object) String() string Symbols returns a list of Object's enumerable symbol properties. This method will panic with an *Exception if a JavaScript exception is thrown in the process. Use Runtime.Try to catch these. (*Object) ToBoolean() bool (*Object) ToFloat() float64 (*Object) ToInteger() int64 (*Object) ToNumber() Value (*Object) ToObject(*Runtime) *Object (*Object) ToString() Value UnmarshalJSON implements the json.Unmarshaler interface. It is added to compliment MarshalJSON, because some alternative JSON encoders refuse to use MarshalJSON unless UnmarshalJSON is also present. It is a no-op and always returns nil. *Object : Value *Object : github.com/goccy/go-json.Marshaler *Object : github.com/goccy/go-json.Unmarshaler *Object : encoding/json.Marshaler *Object : encoding/json.Unmarshaler *Object : expvar.Var *Object : fmt.Stringer *Object : oss.terrastruct.com/d2/lib/jsrunner.JSObject *Object : oss.terrastruct.com/d2/lib/jsrunner.JSValue func NewSharedDynamicArray(a DynamicArray) *Object func NewSharedDynamicObject(d DynamicObject) *Object func (*Object).Prototype() *Object func (*Object).ToObject(*Runtime) *Object func Proxy.Handler() *Object func Proxy.Target() *Object func (*Runtime).CreateObject(proto *Object) *Object func (*Runtime).GlobalObject() *Object func (*Runtime).New(construct Value, args ...Value) (o *Object, err error) func (*Runtime).NewArray(items ...interface{}) *Object func (*Runtime).NewDynamicArray(a DynamicArray) *Object func (*Runtime).NewDynamicObject(d DynamicObject) *Object func (*Runtime).NewGoError(err error) *Object func (*Runtime).NewObject() (v *Object) func (*Runtime).NewTypeError(args ...interface{}) *Object func String.ToObject(*Runtime) *Object func (*Symbol).ToObject(r *Runtime) *Object func Value.ToObject(*Runtime) *Object func (*Object).SetPrototype(proto *Object) error func (*Runtime).CreateObject(proto *Object) *Object func (*Runtime).InstanceOf(left Value, right *Object) (res bool) func (*Runtime).NewProxy(target *Object, nativeHandler *ProxyTrapConfig) Proxy
Program is an internal, compiled representation of code which is produced by the Compile function. This representation is not linked to a runtime in any way and can be used concurrently. It is always preferable to use a Program over a string when running code as it skips the compilation step. func Compile(name, src string, strict bool) (*Program, error) func CompileAST(prg *js_ast.Program, strict bool) (*Program, error) func MustCompile(name, src string, strict bool) *Program func (*Runtime).RunProgram(p *Program) (result Value, err error)
Promise is a Go wrapper around ECMAScript Promise. Calling Runtime.ToValue() on it returns the underlying Object. Calling Export() on a Promise Object returns a Promise. Use Runtime.NewPromise() to create one. Calling Runtime.ToValue() on a zero object or nil returns null Value. WARNING: Instances of Promise are not goroutine-safe. See Runtime.NewPromise() for more details. (*Promise) Result() Value (*Promise) State() PromiseState func (*Runtime).NewPromise() (promise *Promise, resolve func(result interface{}), reject func(reason interface{}))
const PromiseRejectionHandle const PromiseRejectionReject
func (*Runtime).SetPromiseRejectionTracker(tracker PromiseRejectionTracker)
func (*Promise).State() PromiseState const PromiseStateFulfilled const PromiseStatePending const PromiseStateRejected
Configurable Flag Enumerable Flag Getter Value Setter Value Value Value Writable Flag (*PropertyDescriptor) Empty() bool (*PropertyDescriptor) IsAccessor() bool (*PropertyDescriptor) IsData() bool (*PropertyDescriptor) IsGeneric() bool
Proxy is a Go wrapper around ECMAScript Proxy. Calling Runtime.ToValue() on it returns the underlying Proxy. Calling Export() on an ECMAScript Proxy returns a wrapper. Use Runtime.NewProxy() to create one. ( Proxy) Handler() *Object ( Proxy) Revoke() ( Proxy) Target() *Object func (*Runtime).NewProxy(target *Object, nativeHandler *ProxyTrapConfig) Proxy
ProxyTrapConfig provides a simplified Go-friendly API for implementing Proxy traps. If an *Idx trap is defined it gets called for integer property keys, including negative ones. Note that this only includes string property keys that represent a canonical integer (i.e. "0", "123", but not "00", "01", " 1" or "-0"). For efficiency strings representing integers exceeding 2^53 are not checked to see if they are canonical, i.e. the *Idx traps will receive "9007199254740993" as well as "9007199254740994", even though the former is not a canonical representation in ECMAScript (Number("9007199254740993") === 9007199254740992). See https://262.ecma-international.org/#sec-canonicalnumericindexstring If an *Idx trap is not set, the corresponding string one is used. A trap for a function call, Function.prototype.apply, Function.prototype.call, Reflect.apply A trap for the new operator, Reflect.construct A trap for Object.defineProperty, Reflect.defineProperty (string properties) A trap for Object.defineProperty, Reflect.defineProperty (integer properties) A trap for Object.defineProperty, Reflect.defineProperty (Symbol properties) A trap for the delete operator, Reflect.deleteProperty (string properties) A trap for the delete operator, Reflect.deleteProperty (integer properties) A trap for the delete operator, Reflect.deleteProperty (Symbol properties) A trap for getting property values, Reflect.get (string properties) A trap for getting property values, Reflect.get (integer properties) A trap for Object.getOwnPropertyDescriptor, Reflect.getOwnPropertyDescriptor (string properties) A trap for Object.getOwnPropertyDescriptor, Reflect.getOwnPropertyDescriptor (integer properties) A trap for Object.getOwnPropertyDescriptor, Reflect.getOwnPropertyDescriptor (Symbol properties) A trap for Object.getPrototypeOf, Reflect.getPrototypeOf, __proto__, Object.prototype.isPrototypeOf, instanceof A trap for getting property values, Reflect.get (Symbol properties) A trap for the in operator, with operator, Reflect.has (string properties) A trap for the in operator, with operator, Reflect.has (integer properties) A trap for the in operator, with operator, Reflect.has (Symbol properties) A trap for Object.isExtensible, Reflect.isExtensible A trap for Object.getOwnPropertyNames, Object.getOwnPropertySymbols, Object.keys, Reflect.ownKeys A trap for Object.preventExtensions, Reflect.preventExtensions A trap for setting property values, Reflect.set (string properties) A trap for setting property values, Reflect.set (integer properties) A trap for Object.setPrototypeOf, Reflect.setPrototypeOf A trap for setting property values, Reflect.set (Symbol properties) func (*Runtime).NewProxy(target *Object, nativeHandler *ProxyTrapConfig) Proxy
func (*Runtime).SetRandSource(source RandSource)
CaptureCallStack appends the current call stack frames to the stack slice (which may be nil) up to the specified depth. The most recent frame will be the first one. If depth <= 0 or more than the number of available frames, returns the entire stack. This method is not safe for concurrent use and should only be called by a Go function that is called from a running script. ClearInterrupt resets the interrupt flag. Typically this needs to be called before the runtime is made available for re-use if there is a chance it could have been interrupted with Interrupt(). Otherwise if Interrupt() was called when runtime was not running (e.g. if it had already finished) so that Interrupt() didn't actually trigger, an attempt to use the runtime will immediately cause an interruption. It is up to the user to ensure proper synchronisation so that ClearInterrupt() is only called when the runtime has finished and there is no chance of a concurrent Interrupt() call. CreateObject creates an object with given prototype. Equivalent of Object.create(proto). ExportTo converts a JavaScript value into the specified Go value. The second parameter must be a non-nil pointer. Returns error if conversion is not possible. Notes on specific cases: # Empty interface Exporting to an interface{} results in a value of the same type as Value.Export() would produce. # Numeric types Exporting to numeric types uses the standard ECMAScript conversion operations, same as used when assigning values to non-clamped typed array items, e.g. https://262.ecma-international.org/#sec-toint32. # Functions Exporting to a 'func' creates a strictly typed 'gateway' into an ES function which can be called from Go. The arguments are converted into ES values using Runtime.ToValue(). If the func has no return values, the return value is ignored. If the func has exactly one return value, it is converted to the appropriate type using ExportTo(). If the last return value is 'error', exceptions are caught and returned as *Exception (instances of GoError are unwrapped, i.e. their 'value' is returned instead). In all other cases exceptions result in a panic. Any extra return values are zeroed. 'this' value will always be set to 'undefined'. For a more low-level mechanism see AssertFunction(). # Map types An ES Map can be exported into a Go map type. If any exported key value is non-hashable, the operation panics (as reflect.Value.SetMapIndex() would). Symbol.iterator is ignored. Exporting an ES Set into a map type results in the map being populated with (element) -> (zero value) key/value pairs. If any value is non-hashable, the operation panics (as reflect.Value.SetMapIndex() would). Symbol.iterator is ignored. Any other Object populates the map with own enumerable non-symbol properties. # Slice types Exporting an ES Set into a slice type results in its elements being exported. Exporting any Object that implements the iterable protocol (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) into a slice type results in the slice being populated with the results of the iteration. Array is treated as iterable (i.e. overwriting Symbol.iterator affects the result). If an object has a 'length' property and is not a function it is treated as array-like. The resulting slice will contain obj[0], ... obj[length-1]. ArrayBuffer and ArrayBuffer-backed types (i.e. typed arrays and DataView) can be exported into []byte. The result is backed by the original data, no copy is performed. For any other Object an error is returned. # Array types Anything that can be exported to a slice type can also be exported to an array type, as long as the lengths match. If they do not, an error is returned. # Proxy Proxy objects are treated the same way as if they were accessed from ES code in regard to their properties (such as 'length' or [Symbol.iterator]). This means exporting them to slice types works, however exporting a proxied Map into a map type does not produce its contents, because the Proxy is not recognised as a Map. Same applies to a proxied Set. ForOf is a Go equivalent of for-of loop. The function panics if an exception is thrown at any point while iterating, including if the supplied value is not iterable (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol). When using outside of Runtime.Run (i.e. when calling directly from Go code, not from a JS function implemented in Go) it must be enclosed in Try. See the example. Get the specified variable in the global context. Equivalent to dereferencing a variable by name in non-strict mode. If variable is not defined returns nil. Note, this is not the same as GlobalObject().Get(name), because if a global lexical binding (let or const) exists, it is used instead. This method will panic with an *Exception if a JavaScript exception is thrown in the process. Use Runtime.Try to catch these. GlobalObject returns the global object. InstanceOf is an equivalent of "left instanceof right". This method will panic with an *Exception if a JavaScript exception is thrown in the process. Use Runtime.Try to catch these. Interrupt a running JavaScript. The corresponding Go call will return an *InterruptedError containing v. If the interrupt propagates until the stack is empty the currently queued promise resolve/reject jobs will be cleared without being executed. This is the same time they would be executed otherwise. Note, it only works while in JavaScript code, it does not interrupt native Go functions (which includes all built-ins). If the runtime is currently not running, it will be immediately interrupted on the next Run*() call. To avoid that use ClearInterrupt() New is an equivalent of the 'new' operator allowing to call it directly from Go. (*Runtime) NewArray(items ...interface{}) *Object NewArrayBuffer creates a new instance of ArrayBuffer backed by the provided byte slice. Warning: be careful when using unaligned slices (sub-slices that do not start at word boundaries). If later a typed array of a multibyte type (uint16, uint32, etc.) is created from a buffer backed by an unaligned slice, using this typed array will result in unaligned access which may cause performance degradation or runtime panics on some architectures or configurations. NewDynamicArray creates an array Object backed by the provided DynamicArray handler. It is similar to NewDynamicObject, the differences are: - the Object is an array (i.e. Array.isArray() will return true and it will have the length property). - the prototype will be initially set to Array.prototype. - the Object cannot have any own string properties except for the 'length'. NewDynamicObject creates an Object backed by the provided DynamicObject handler. All properties of this Object are Writable, Enumerable and Configurable data properties. Any attempt to define a property that does not conform to this will fail. The Object is always extensible and cannot be made non-extensible. Object.preventExtensions() will fail. The Object's prototype is initially set to Object.prototype, but can be changed using regular mechanisms (Object.SetPrototype() in Go or Object.setPrototypeOf() in JS). The Object cannot have own Symbol properties, however its prototype can. If you need an iterator support for example, you could create a regular object, set Symbol.iterator on that object and then use it as a prototype. See TestDynamicObjectCustomProto for more details. Export() returns the original DynamicObject. This mechanism is similar to ECMAScript Proxy, however because all properties are enumerable and the object is always extensible there is no need for invariant checks which removes the need to have a target object and makes it a lot more efficient. (*Runtime) NewGoError(err error) *Object (*Runtime) NewObject() (v *Object) NewPromise creates and returns a Promise and resolving functions for it. WARNING: The returned values are not goroutine-safe and must not be called in parallel with VM running. In order to make use of this method you need an event loop such as the one in goja_nodejs (https://github.com/dop251/goja_nodejs) where it can be used like this: loop := NewEventLoop() loop.Start() defer loop.Stop() loop.RunOnLoop(func(vm *goja.Runtime) { p, resolve, _ := vm.NewPromise() vm.Set("p", p) go func() { time.Sleep(500 * time.Millisecond) // or perform any other blocking operation loop.RunOnLoop(func(*goja.Runtime) { // resolve() must be called on the loop, cannot call it here resolve(result) }) }() } (*Runtime) NewProxy(target *Object, nativeHandler *ProxyTrapConfig) Proxy (*Runtime) NewTypeError(args ...interface{}) *Object RunProgram executes a pre-compiled (see Compile()) code in the global context. RunScript executes the given string in the global context. RunString executes the given string in the global context. Set the specified variable in the global context. Equivalent to running "name = value" in non-strict mode. The value is first converted using ToValue(). Note, this is not the same as GlobalObject().Set(name, value), because if a global lexical binding (let or const) exists, it is set instead. SetAsyncContextTracker registers a handler that allows to track async execution contexts. See AsyncContextTracker documentation for more details. Setting it to nil disables the functionality. This method (as Runtime in general) is not goroutine-safe. SetFieldNameMapper sets a custom field name mapper for Go types. It can be called at any time, however the mapping for any given value is fixed at the point of creation. Setting this to nil restores the default behaviour which is all exported fields and methods are mapped to their original unchanged names. SetMaxCallStackSize sets the maximum function call depth. When exceeded, a *StackOverflowError is thrown and returned by RunProgram or by a Callable call. This is useful to prevent memory exhaustion caused by an infinite recursion. The default value is math.MaxInt32. This method (as the rest of the Set* methods) is not safe for concurrent use and may only be called from the vm goroutine or when the vm is not running. SetParserOptions sets parser options to be used by RunString, RunScript and eval() within the code. SetPromiseRejectionTracker registers a function that will be called in two scenarios: when a promise is rejected without any handlers (with operation argument set to PromiseRejectionReject), and when a handler is added to a rejected promise for the first time (with operation argument set to PromiseRejectionHandle). Setting a tracker replaces any existing one. Setting it to nil disables the functionality. See https://tc39.es/ecma262/#sec-host-promise-rejection-tracker for more details. SetRandSource sets random source for this Runtime. If not called, the default math/rand is used. SetTimeSource sets the current time source for this Runtime. If not called, the default time.Now() is used. ToValue converts a Go value into a JavaScript value of a most appropriate type. Structural types (such as structs, maps and slices) are wrapped so that changes are reflected on the original value which can be retrieved using Value.Export(). WARNING! These wrapped Go values do not behave in the same way as native ECMAScript values. If you plan to modify them in ECMAScript, bear in mind the following caveats: 1. If a regular JavaScript Object is assigned as an element of a wrapped Go struct, map or array, it is Export()'ed and therefore copied. This may result in an unexpected behaviour in JavaScript: m := map[string]interface{}{} vm.Set("m", m) vm.RunString(` var obj = {test: false}; m.obj = obj; // obj gets Export()'ed, i.e. copied to a new map[string]interface{} and then this map is set as m["obj"] obj.test = true; // note, m.obj.test is still false `) fmt.Println(m["obj"].(map[string]interface{})["test"]) // prints "false" 2. Be careful with nested non-pointer compound types (structs, slices and arrays) if you modify them in ECMAScript. Better avoid it at all if possible. One of the fundamental differences between ECMAScript and Go is in the former all Objects are references whereas in Go you can have a literal struct or array. Consider the following example: type S struct { Field int } a := []S{{1}, {2}} // slice of literal structs vm.Set("a", &a) vm.RunString(` let tmp = {Field: 1}; a[0] = tmp; a[1] = tmp; tmp.Field = 2; `) In ECMAScript one would expect a[0].Field and a[1].Field to be equal to 2, but this is really not possible (or at least non-trivial without some complex reference tracking). To cover the most common use cases and to avoid excessive memory allocation, the following 'copy-on-change' mechanism is implemented (for both arrays and structs): * When a nested compound value is accessed, the returned ES value becomes a reference to the literal value. This ensures that things like 'a[0].Field = 1' work as expected and simple access to 'a[0].Field' does not result in copying of a[0]. * The original container ('a' in our case) keeps track of the returned reference value and if a[0] is reassigned (e.g. by direct assignment, deletion or shrinking the array) the old a[0] is copied and the earlier returned value becomes a reference to the copy: let tmp = a[0]; // no copy, tmp is a reference to a[0] tmp.Field = 1; // a[0].Field === 1 after this a[0] = {Field: 2}; // tmp is now a reference to a copy of the old value (with Field === 1) a[0].Field === 2 && tmp.Field === 1; // true * Array value swaps caused by in-place sort (using Array.prototype.sort()) do not count as re-assignments, instead the references are adjusted to point to the new indices. * Assignment to an inner compound value always does a copy (and sometimes type conversion): a[1] = tmp; // a[1] is now a copy of tmp tmp.Field = 3; // does not affect a[1].Field 3. Non-addressable structs, slices and arrays get copied. This sometimes may lead to a confusion as assigning to inner fields does not appear to work: a1 := []interface{}{S{1}, S{2}} vm.Set("a1", &a1) vm.RunString(` a1[0].Field === 1; // true a1[0].Field = 2; a1[0].Field === 2; // FALSE, because what it really did was copy a1[0] set its Field to 2 and immediately drop it `) An alternative would be making a1[0].Field a non-writable property which would probably be more in line with ECMAScript, however it would require to manually copy the value if it does need to be modified which may be impractical. Note, the same applies to slices. If a slice is passed by value (not as a pointer), resizing the slice does not reflect on the original value. Moreover, extending the slice may result in the underlying array being re-allocated and copied. For example: a := []interface{}{1} vm.Set("a", a) vm.RunString(`a.push(2); a[0] = 0;`) fmt.Println(a[0]) // prints "1" Notes on individual types: # Primitive types Primitive types (numbers, string, bool) are converted to the corresponding JavaScript primitives. These values are goroutine-safe and can be transferred between runtimes. # Strings Because of the difference in internal string representation between ECMAScript (which uses UTF-16) and Go (which uses UTF-8) conversion from JS to Go may be lossy. In particular, code points that can be part of UTF-16 surrogate pairs (0xD800-0xDFFF) cannot be represented in UTF-8 unless they form a valid surrogate pair and are replaced with utf8.RuneError. The string value must be a valid UTF-8. If it is not, invalid characters are replaced with utf8.RuneError, but the behaviour of a subsequent Export() is unspecified (it may return the original value, or a value with replaced invalid characters). # Nil Nil is converted to null. # Functions func(FunctionCall) Value is treated as a native JavaScript function. This increases performance because there are no automatic argument and return value type conversions (which involves reflect). Attempting to use the function as a constructor will result in a TypeError. Note: implementations must not retain and use references to FunctionCall.Arguments after the function returns. func(FunctionCall, *Runtime) Value is treated as above, except the *Runtime is also passed as a parameter. func(ConstructorCall) *Object is treated as a native constructor, allowing to use it with the new operator: func MyObject(call goja.ConstructorCall) *goja.Object { // call.This contains the newly created object as per http://www.ecma-international.org/ecma-262/5.1/index.html#sec-13.2.2 // call.Arguments contain arguments passed to the function call.This.Set("method", method) //... // If return value is a non-nil *Object, it will be used instead of call.This // This way it is possible to return a Go struct or a map converted // into goja.Value using ToValue(), however in this case // instanceof will not work as expected, unless you set the prototype: // // instance := &myCustomStruct{} // instanceValue := vm.ToValue(instance).(*Object) // instanceValue.SetPrototype(call.This.Prototype()) // return instanceValue return nil } runtime.Set("MyObject", MyObject) Then it can be used in JS as follows: var o = new MyObject(arg); var o1 = MyObject(arg); // same thing o instanceof MyObject && o1 instanceof MyObject; // true When a native constructor is called directly (without the new operator) its behavior depends on this value: if it's an Object, it is passed through, otherwise a new one is created exactly as if it was called with the new operator. In either case call.NewTarget will be nil. func(ConstructorCall, *Runtime) *Object is treated as above, except the *Runtime is also passed as a parameter. Any other Go function is wrapped so that the arguments are automatically converted into the required Go types and the return value is converted to a JavaScript value (using this method). If conversion is not possible, a TypeError is thrown. Functions with multiple return values return an Array. If the last return value is an `error` it is not returned but converted into a JS exception. If the error is *Exception, it is thrown as is, otherwise it's wrapped in a GoEerror. Note that if there are exactly two return values and the last is an `error`, the function returns the first value as is, not an Array. # Structs Structs are converted to Object-like values. Fields and methods are available as properties, their values are results of this method (ToValue()) applied to the corresponding Go value. Field properties are writable and non-configurable. Method properties are non-writable and non-configurable. Attempt to define a new property or delete an existing property will fail (throw in strict mode) unless it's a Symbol property. Symbol properties only exist in the wrapper and do not affect the underlying Go value. Note that because a wrapper is created every time a property is accessed it may lead to unexpected results such as this: type Field struct{ } type S struct { Field *Field } var s = S{ Field: &Field{}, } vm := New() vm.Set("s", &s) res, err := vm.RunString(` var sym = Symbol(66); var field1 = s.Field; field1[sym] = true; var field2 = s.Field; field1 === field2; // true, because the equality operation compares the wrapped values, not the wrappers field1[sym] === true; // true field2[sym] === undefined; // also true `) The same applies to values from maps and slices as well. # Handling of time.Time time.Time does not get special treatment and therefore is converted just like any other `struct` providing access to all its methods. This is done deliberately instead of converting it to a `Date` because these two types are not fully compatible: `time.Time` includes zone, whereas JS `Date` doesn't. Doing the conversion implicitly therefore would result in a loss of information. If you need to convert it to a `Date`, it can be done either in JS: var d = new Date(goval.UnixNano()/1e6); ... or in Go: now := time.Now() vm := New() val, err := vm.New(vm.Get("Date").ToObject(vm), vm.ToValue(now.UnixNano()/1e6)) if err != nil { ... } vm.Set("d", val) Note that Value.Export() for a `Date` value returns time.Time in local timezone. # Maps Maps with string, integer, or float key types are converted into host objects that largely behave like a JavaScript Object. One noticeable difference is that the key order is not stable, as with maps in Go. Keys are converted to strings following the fmt.Sprintf("%v") convention. # Maps with methods If a map type has at least one method defined, the properties of the resulting Object represent methods, not map keys. This is because in JavaScript there is no distinction between 'object.key` and `object[key]`, unlike Go. If access to the map values is required, it can be achieved by defining another method or, if it's not possible, by defining an external getter function. # Slices Slices are converted into host objects that behave largely like JavaScript Array. It has the appropriate prototype and all the usual methods should work. There is, however, a caveat: converted Arrays may not contain holes (because Go slices cannot). This means that hasOwnProperty(n) always returns `true` if n < length. Deleting an item with an index < length will set it to a zero value (but the property will remain). Nil slice elements are be converted to `null`. Accessing an element beyond `length` returns `undefined`. Also see the warning above about passing slices as values (as opposed to pointers). # Arrays Arrays are converted similarly to slices, except the resulting Arrays are not resizable (and therefore the 'length' property is non-writable). Any other type is converted to a generic reflect based host object. Depending on the underlying type it behaves similar to a Number, String, Boolean or Object. Note that the underlying type is not lost, calling Export() returns the original Go value. This applies to all reflect based types. Try runs a given function catching and returning any JS exception. Use this method to run any code that may throw exceptions (such as Object.Get, Object.String, Object.ToInteger, Object.Export, Runtime.Get, Runtime.InstanceOf, etc.) outside the Runtime execution context (i.e. when calling directly from Go, not from a JS function implemented in Go). func New() *Runtime func (*Object).ToObject(*Runtime) *Object func String.ToObject(*Runtime) *Object func (*Symbol).ToObject(r *Runtime) *Object func Value.ToObject(*Runtime) *Object
(*StackFrame) FuncName() string (*StackFrame) Position() file.Position (*StackFrame) SrcName() string (*StackFrame) Write(b *bytes.Buffer) (*StackFrame) WriteToValueBuilder(b *StringBuilder) func (*Exception).Stack() []StackFrame func (*Runtime).CaptureCallStack(depth int, stack []StackFrame) []StackFrame func (*Runtime).CaptureCallStack(depth int, stack []StackFrame) []StackFrame
baseUncatchableException.Exception Exception (*StackOverflowError) Error() string (*StackOverflowError) Stack() []StackFrame (*StackOverflowError) String() string (*StackOverflowError) Unwrap() error (*StackOverflowError) Value() Value *StackOverflowError : error *StackOverflowError : expvar.Var *StackOverflowError : fmt.Stringer *StackOverflowError : golang.org/x/xerrors.Wrapper
String represents an ECMAScript string Value. Its internal representation depends on the contents of the string, but in any case it is capable of holding any UTF-16 string, either valid or invalid. Instances of this type, as any other primitive values, are goroutine-safe and can be passed between runtimes. Strings can be created using Runtime.ToValue(goString) or StringFromUTF16. ( String) CharAt(int) uint16 ( String) CompareTo(String) int ( String) Concat(String) String ( String) Equals(Value) bool ( String) Export() interface{} ( String) ExportType() reflect.Type ( String) Length() int ( String) Reader() io.RuneReader ( String) SameAs(Value) bool ( String) StrictEquals(Value) bool ( String) String() string ( String) Substring(start, end int) String ( String) ToBoolean() bool ( String) ToFloat() float64 ( String) ToInteger() int64 ( String) ToNumber() Value ( String) ToObject(*Runtime) *Object ( String) ToString() Value String : Value String : expvar.Var String : fmt.Stringer String : oss.terrastruct.com/d2/lib/jsrunner.JSObject String : oss.terrastruct.com/d2/lib/jsrunner.JSValue func StringFromUTF16(chars []uint16) String func String.Concat(String) String func String.Substring(start, end int) String func (*StringBuilder).String() String func String.CompareTo(String) int func String.Concat(String) String func (*StringBuilder).WriteString(s String) func (*StringBuilder).WriteSubstring(source String, start int, end int)
StringBuilder serves similar purpose to strings.Builder, except it works with ECMAScript String. Use it to efficiently build 'native' ECMAScript values that either contain invalid UTF-16 surrogate pairs (and therefore cannot be represented as UTF-8) or never expected to be exported to Go. See also StringFromUTF16. (*StringBuilder) Grow(n int) LikelyUnicode hints to the builder that the resulting string is likely to contain Unicode (non-ASCII) characters. The argument is an extra capacity (in characters) to reserve on top of the current length (it's like calling Grow() afterwards). This method may be called at any point (not just when the buffer is empty), although for efficiency it should be called as early as possible. (*StringBuilder) String() String (*StringBuilder) WriteRune(r rune) (*StringBuilder) WriteString(s String) (*StringBuilder) WriteSubstring(source String, start int, end int) (*StringBuilder) WriteUTF8String(s string) func (*StackFrame).WriteToValueBuilder(b *StringBuilder)
*Symbol is a Value containing ECMAScript Symbol primitive. Symbols must only be created using NewSymbol(). Zero values and copying of values (i.e. *s1 = *s2) are not permitted. Well-known Symbols can be accessed using Sym* package variables (SymIterator, etc...) Symbols can be shared by multiple Runtimes. (*Symbol) Equals(o Value) bool (*Symbol) Export() interface{} (*Symbol) ExportType() reflect.Type (*Symbol) SameAs(other Value) bool (*Symbol) StrictEquals(o Value) bool (*Symbol) String() string (*Symbol) ToBoolean() bool (*Symbol) ToFloat() float64 (*Symbol) ToInteger() int64 (*Symbol) ToNumber() Value (*Symbol) ToObject(r *Runtime) *Object (*Symbol) ToString() Value *Symbol : Value *Symbol : expvar.Var *Symbol : fmt.Stringer *Symbol : oss.terrastruct.com/d2/lib/jsrunner.JSObject *Symbol : oss.terrastruct.com/d2/lib/jsrunner.JSValue func NewSymbol(s string) *Symbol func (*Object).Symbols() []*Symbol func (*Object).DefineAccessorPropertySymbol(name *Symbol, getter, setter Value, configurable, enumerable Flag) error func (*Object).DefineDataPropertySymbol(name *Symbol, value Value, writable, configurable, enumerable Flag) error func (*Object).DeleteSymbol(name *Symbol) error func (*Object).GetSymbol(sym *Symbol) Value func (*Object).SetSymbol(name *Symbol, value interface{}) error var SymHasInstance *Symbol var SymIsConcatSpreadable *Symbol var SymIterator *Symbol var SymMatch *Symbol var SymMatchAll *Symbol var SymReplace *Symbol var SymSearch *Symbol var SymSpecies *Symbol var SymSplit *Symbol var SymToPrimitive *Symbol var SymToStringTag *Symbol var SymUnscopables *Symbol
Value represents an ECMAScript value. Export returns a "plain" Go value which type depends on the type of the Value. For integer numbers it's int64. For any other numbers (including Infinities, NaN and negative zero) it's float64. For string it's a string. Note that unicode strings are converted into UTF-8 with invalid code points replaced with utf8.RuneError. For boolean it's bool. For null and undefined it's nil. For Object it depends on the Object type, see Object.Export() for more details. ( Value) Equals(Value) bool ( Value) Export() interface{} ( Value) ExportType() reflect.Type ( Value) SameAs(Value) bool ( Value) StrictEquals(Value) bool ( Value) String() string ( Value) ToBoolean() bool ( Value) ToFloat() float64 ( Value) ToInteger() int64 ( Value) ToNumber() Value ( Value) ToObject(*Runtime) *Object ( Value) ToString() Value *Object String (interface) *Symbol Value : expvar.Var Value : fmt.Stringer Value : oss.terrastruct.com/d2/lib/jsrunner.JSObject Value : oss.terrastruct.com/d2/lib/jsrunner.JSValue func NaN() Value func NegativeInf() Value func Null() Value func PositiveInf() Value func Undefined() Value func ConstructorCall.Argument(idx int) Value func DynamicArray.Get(idx int) Value func DynamicObject.Get(key string) Value func (*Exception).Value() Value func FunctionCall.Argument(idx int) Value func (*Object).Get(name string) Value func (*Object).GetSymbol(sym *Symbol) Value func (*Object).ToNumber() Value func (*Object).ToString() Value func (*Promise).Result() Value func (*Runtime).Get(name string) Value func (*Runtime).RunProgram(p *Program) (result Value, err error) func (*Runtime).RunScript(name, src string) (Value, error) func (*Runtime).RunString(str string) (Value, error) func (*Runtime).ToValue(i interface{}) Value func String.ToNumber() Value func String.ToString() Value func (*Symbol).ToNumber() Value func (*Symbol).ToString() Value func Value.ToNumber() Value func Value.ToString() Value func AssertConstructor(v Value) (Constructor, bool) func AssertFunction(v Value) (Callable, bool) func IsInfinity(v Value) bool func IsNaN(v Value) bool func IsNull(v Value) bool func IsUndefined(v Value) bool func DynamicArray.Set(idx int, val Value) bool func DynamicObject.Set(key string, val Value) bool func (*Object).DefineAccessorProperty(name string, getter, setter Value, configurable, enumerable Flag) error func (*Object).DefineAccessorPropertySymbol(name *Symbol, getter, setter Value, configurable, enumerable Flag) error func (*Object).DefineDataProperty(name string, value Value, writable, configurable, enumerable Flag) error func (*Object).DefineDataPropertySymbol(name *Symbol, value Value, writable, configurable, enumerable Flag) error func (*Object).Equals(other Value) bool func (*Object).SameAs(other Value) bool func (*Object).StrictEquals(other Value) bool func (*Runtime).ExportTo(v Value, target interface{}) error func (*Runtime).ForOf(iterable Value, step func(curValue Value) (continueIteration bool)) func (*Runtime).InstanceOf(left Value, right *Object) (res bool) func (*Runtime).New(construct Value, args ...Value) (o *Object, err error) func (*Runtime).New(construct Value, args ...Value) (o *Object, err error) func String.Equals(Value) bool func String.SameAs(Value) bool func String.StrictEquals(Value) bool func (*Symbol).Equals(o Value) bool func (*Symbol).SameAs(other Value) bool func (*Symbol).StrictEquals(o Value) bool func Value.Equals(Value) bool func Value.SameAs(Value) bool func Value.StrictEquals(Value) bool
Package-Level Functions (total 25)
AssertConstructor checks if the Value is a constructor and returns a Constructor.
AssertFunction checks if the Value is a function and returns a Callable. Note, for classes this returns a callable and a 'true', however calling it will always result in a TypeError. For classes use AssertConstructor().
Compile creates an internal representation of the JavaScript code that can be later run using the Runtime.RunProgram() method. This representation is not linked to a runtime in any way and can be run in multiple runtimes (possibly at the same time).
CompileAST creates an internal representation of the JavaScript code that can be later run using the Runtime.RunProgram() method. This representation is not linked to a runtime in any way and can be run in multiple runtimes (possibly at the same time).
IsInfinity returns true if the supplied is (+/-)Infinity
IsNaN returns true if the supplied value is NaN.
IsNull returns true if the supplied Value is null.
IsUndefined returns true if the supplied Value is undefined. Note, it checks against the real undefined, not against the global object's 'undefined' property.
MustCompile is like Compile but panics if the code cannot be compiled. It simplifies safe initialization of global variables holding compiled JavaScript code.
NaN returns a JS NaN value.
NegativeInf returns a JS -Inf value.
New creates an instance of a Javascript runtime that can be used to run code. Multiple instances may be created and used simultaneously, however it is not possible to pass JS values across runtimes.
NewSharedDynamicArray is similar to Runtime.NewDynamicArray but the resulting Object can be shared across multiple Runtimes. The Object's prototype will be null. If you need to run Array's methods on it, use Array.prototype.[...].call(a, ...). The provided DynamicArray must be goroutine-safe.
NewSharedDynamicObject is similar to Runtime.NewDynamicObject but the resulting Object can be shared across multiple Runtimes. The Object's prototype will be null. The provided DynamicObject must be goroutine-safe.
Null returns JS null value.
Parse takes a source string and produces a parsed AST. Use this function if you want to pass options to the parser, e.g.: p, err := Parse("test.js", "var a = true", parser.WithDisableSourceMaps) if err != nil { /* ... */ } prg, err := CompileAST(p, true) // ... Otherwise use Compile which combines both steps.
PositiveInf returns a JS +Inf value.
StartProfile enables execution time profiling for all Runtimes within the current process. This works similar to pprof.StartCPUProfile and produces the same format which can be consumed by `go tool pprof`. There are, however, a few notable differences. Firstly, it's not a CPU profile, rather "execution time" profile. It measures the time the VM spends executing an instruction. If this instruction happens to be a call to a blocking Go function, the waiting time will be measured. Secondly, the 'cpu' sample isn't simply `count*period`, it's the time interval between when sampling was requested and when the instruction has finished. If a VM is still executing the same instruction when the time comes for the next sample, the sampling is skipped (i.e. `count` doesn't grow). If there are multiple functions with the same name, their names get a '.N' suffix, where N is a unique number, because otherwise the graph view merges them together (even if they are in different mappings). This includes "<anonymous>" functions. The sampling period is set to 10ms. It returns an error if profiling is already active.
StopProfile stops the current profile initiated by StartProfile, if any.
StringFromUTF16 creates a string value from an array of UTF-16 code units. The result is a copy, so the initial slice can be modified after calling this function (but it must not be modified while the function is running). No validation of any kind is performed.
TagFieldNameMapper returns a FieldNameMapper that uses the given tagName for struct fields and optionally uncapitalises (making the first letter lower case) method names. The common tag value syntax is supported (name[,options]), however options are ignored. Setting name to anything other than a valid ECMAScript identifier makes the field hidden.
func ToFlag(b bool) Flag
UncapFieldNameMapper returns a FieldNameMapper that uncapitalises struct field and method names making the first letter lower case.
Undefined returns JS undefined value. Note if global 'undefined' property is changed this still returns the original value.