### Install Goja Source: https://github.com/dop251/goja/blob/master/_autodocs/REFERENCE.md Install the Goja library using the go get command. ```bash go get github.com/dop251/goja ``` -------------------------------- ### Get File Source Code Source: https://github.com/dop251/goja/blob/master/file/README.markdown Returns the source code string of the file. ```go func (fl *File) Source() string ``` -------------------------------- ### Date Constructor Integer Overflow Example Source: https://github.com/dop251/goja/blob/master/README.md Shows an example of potential incorrect results from the Date() constructor when arguments cause integer overflow, due to Go's use of 'int' instead of 'float' for epoch timestamps. ```javascript Date.UTC(1970, 0, 1, 80063993375, 29, 1, -288230376151711740) // returns 29256 instead of 29312 ``` -------------------------------- ### ToFloat Conversion Example Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/value.md Shows how to convert a Goja Value to a float64. Returns NaN for non-numeric values. ```go val := vm.ToValue("3.14") f := val.ToFloat() // 3.14 ``` -------------------------------- ### Call JavaScript Function from Go Source: https://github.com/dop251/goja/blob/master/_autodocs/REFERENCE.md Define a JavaScript function and then call it from Go. Use AssertFunction to get a callable function object and Export to get the result. ```go vm := goja.New() vm.RunString(" function add(a, b) { return a + b } ") fn, _ := goja.AssertFunction(vm.Get("add")) result, _ := fn(goja.Undefined(), vm.ToValue(10), vm.ToValue(20)) fmt.Println(result.Export()) // 30 ``` -------------------------------- ### Start CPU Profiling Source: https://github.com/dop251/goja/blob/master/_autodocs/configuration.md Begins CPU profiling and writes output to the provided writer. Ensure to close the file and stop profiling when done. ```go file, _ := os.Create("cpu.prof") defer file.Close() goja.StartProfile(file) defers goja.StopProfile() vm := goja.New() vm.RunString(" var sum = 0 for (var i = 0; i < 1000000; i++) { sum += i } ") ``` -------------------------------- ### ToInteger Conversion Example Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/value.md Demonstrates converting various Goja values to a signed 64-bit integer using ECMAScript coercion rules. ```go vm := goja.New() vals := []interface{}{3.7, true, "42", "abc", nil} for _, v := range vals { val := vm.ToValue(v) fmt.Println(val.ToInteger()) // Output: // 3 // 1 // 42 // 0 // 0 } ``` -------------------------------- ### Example: Interrupt JavaScript Execution Source: https://github.com/dop251/goja/blob/master/_autodocs/errors.md Demonstrates interrupting a long-running JavaScript loop from a Go goroutine using vm.Interrupt(). ```go vm := goja.New() go func() { time.Sleep(100 * time.Millisecond) vm.Interrupt("timeout") }() _, err := vm.RunString(` var i = 0 for (;;) i++ `) if intErr, ok := err.(*goja.InterruptedError); ok { fmt.Println(intErr.Value()) // "timeout" } ``` -------------------------------- ### ConstructorCall Example Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/object.md Demonstrates how to use the ConstructorCall type within a Goja constructor function to access arguments and the newly created object. ```go vm := goja.New() vm.Set("MyClass", func(call goja.ConstructorCall) *goja.Object { call.This.Set("value", call.Argument(0)) return call.This }) vm.RunString( "var obj = new MyClass(42) console.log(obj.value) // 42" ) ``` -------------------------------- ### Example: Implementing a JavaScript Function in Go Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/object.md Demonstrates how to define a JavaScript function ('add') in Go using goja. This function takes two arguments, converts them to numbers, and returns their sum. ```go vm := goja.New() vm.Set("add", func(call goja.FunctionCall) goja.Value { a := call.Argument(0).ToNumber().(goja.Value) b := call.Argument(1).ToNumber().(goja.Value) return vm.ToValue(a.ToFloat() + b.ToFloat()) }) vm.RunString("add(10, 20)") ``` -------------------------------- ### Run Basic JavaScript and Get Result Source: https://github.com/dop251/goja/blob/master/README.md Demonstrates how to initialize a Goja runtime, execute a simple JavaScript expression, and retrieve the result in Go. Ensure error handling for the execution. ```go vm := goja.New() v, err := vm.RunString("2 + 2") if err != nil { panic(err) } if num := v.Export().(int64); num != 4 { panic(num) } ``` -------------------------------- ### Handle Promise Rejections with Tracker Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/functions-promises.md Example of handling promise rejections using the `SetPromiseRejectionTracker` method. Unhandled rejections are captured and logged. ```go vm := goja.New() rejections := make([]string, 0) vm.SetPromiseRejectionTracker(func(p *goja.Promise, op goja.PromiseRejectionOperation) { if op == goja.PromiseRejectionReject { rejections = append(rejections, fmt.Sprintf("%v", p.Result())) } }) vm.RunString(" Promise.reject("Operation failed") ") // Process queued promise jobs vm.RunString("") // Trigger job queue processing for _, err := range rejections { fmt.Println("Unhandled:", err) } ``` -------------------------------- ### Get File Base Offset Source: https://github.com/dop251/goja/blob/master/file/README.markdown Retrieves the base offset of the file. ```go func (fl *File) Base() int ``` -------------------------------- ### Custom Dynamic Object Implementation Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/object.md Provides an example of implementing the DynamicObject interface in Go to create custom JavaScript objects with dynamic property access. This allows Go data structures to be exposed as JavaScript objects. ```go type CustomMap struct { data map[string]interface{}, } func (m *CustomMap) Get(key string) interface{} { return m.data[key] } func (m *CustomMap) Set(key string, val interface{}) bool { m.data[key] = val return true } func (m *CustomMap) Has(key string) bool { _, ok := m.data[key] return ok } func (m *CustomMap) Delete(key string) bool { delete(m.data, key) return true } func (m *CustomMap) Keys() []string { var keys []string for k := range m.data { keys = append(keys, k) } return keys } vm := goja.New() custom := &CustomMap{data: make(map[string]interface{})} jsObj := vm.NewDynamicObject(custom) vm.Set("custom", jsObj) ``` -------------------------------- ### Get File Name Source: https://github.com/dop251/goja/blob/master/file/README.markdown Retrieves the filename associated with the File object. ```go func (fl *File) Name() string ``` -------------------------------- ### Call JavaScript Function from Go Source: https://github.com/dop251/goja/blob/master/_autodocs/INDEX.md Retrieve a JavaScript function from the VM using `Get` and assert its type with `AssertFunction`. The function can then be invoked with arguments. ```go fn, _ := goja.AssertFunction(vm.Get("myFunc")) result, _ := fn(goja.Undefined(), vm.ToValue(42)) ``` -------------------------------- ### Implement Async Context Tracking in Goja Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/functions-promises.md Example implementation of the `AsyncContextTracker` interface to maintain a stack of string contexts during asynchronous operations. This allows tracking context across promise callbacks. ```go type ContextTracker struct { contextStack []string } func (ct *ContextTracker) Grab() interface{} { if len(ct.contextStack) > 0 { return ct.contextStack[len(ct.contextStack)-1] } return nil } func (ct *ContextTracker) Resumed(ctx interface{}) { if ctx != nil { ct.contextStack = append(ct.contextStack, ctx.(string)) } } func (ct *ContextTracker) Exited() { if len(ct.contextStack) > 0 { ct.contextStack = ct.contextStack[:len(ct.contextStack)-1] } } vm := goja.New() tracker := &ContextTracker{} vm.SetAsyncContextTracker(tracker) vm.RunString(" Promise.resolve(1).then(() => { console.log(\"Inside promise\") }) ") ``` -------------------------------- ### Get Enumerable Property Keys Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/object.md Returns a slice of strings containing the names of all enumerable properties directly on the object. ```go obj := vm.NewObject() obj.Set("a", 1) obj.Set("b", 2) obj.Set("c", 3) keys := obj.Keys() fmt.Println(keys) // [a b c] or similar permutation ``` -------------------------------- ### ToString Conversion Example Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/value.md Converts a Goja Value to a JavaScript String Value. For numbers, it uses the minimal string representation. ```go vm := goja.New() stringVal := vm.ToValue(42).ToString() fmt.Println(stringVal.String()) // "42" ``` -------------------------------- ### Track Unhandled Promise Rejections in Goja Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/functions-promises.md Example demonstrating how to set a `PromiseRejectionTracker` to detect and log unhandled promise rejections. It distinguishes between rejections and handled rejections. ```go vm := goja.New() unhandledRejections := make(map[*goja.Promise]goja.Value) vm.SetPromiseRejectionTracker(func(p *goja.Promise, op goja.PromiseRejectionOperation) { if op == goja.PromiseRejectionReject { unhandledRejections[p] = p.Result() fmt.Println("Unhandled rejection detected") } else if op == goja.PromiseRejectionHandle { delete(unhandledRejections, p) fmt.Println("Rejection handled") } }) vm.RunString(" Promise.reject(\"error\").then(() => {}) ") ``` -------------------------------- ### Flag Conversion Example Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/object.md Shows how to convert boolean values to Goja's Flag type for property descriptors and vice versa. Use ToFlag to create flags from booleans and the Bool() method to convert flags back to booleans. ```go writable := goja.ToFlag(true) // FLAG_TRUE enumerable := goja.ToFlag(false) // FLAG_FALSE configurable := goja.FLAG_NOT_SET ``` -------------------------------- ### Node interface definition Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Defines the base Node interface for all AST nodes, providing methods to get the start and end indices of the node in the source code. ```go type Node interface { Idx0() file.Idx // The index of the first character belonging to the node Idx1() file.Idx // The index of the first character immediately after the node } ``` -------------------------------- ### Example: Trigger Stack Overflow Source: https://github.com/dop251/goja/blob/master/_autodocs/errors.md Demonstrates triggering a StackOverflowError by exceeding the maximum call stack size with a deeply recursive JavaScript function. ```go vm := goja.New() vm.SetMaxCallStackSize(100) _, err := vm.RunString(` function recurse(n) { return recurse(n + 1) } recurse(0) `) if _, ok := err.(*goja.StackOverflowError); ok { fmt.Println("Overflow after 100 calls") } ``` -------------------------------- ### Get Global JavaScript Property (Get) Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/runtime.md Use Get to retrieve a property from the global JavaScript scope. If the property does not exist, it returns an undefined Value. You can check for undefined values using goja.IsUndefined. ```go vm := goja.New() vm.RunString("var x = 42") val := vm.Get("x") fmt.Println(val.Export()) // 42 val2 := vm.Get("nonexistent") fmt.Println(goja.IsUndefined(val2)) // true ``` -------------------------------- ### Create a New File Instance Source: https://github.com/dop251/goja/blob/master/file/README.markdown Constructs a new File object with the specified filename, source code, and base offset. ```go func NewFile(filename, src string, base int) *File ``` -------------------------------- ### Get JavaScript NaN Value Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/value.md Use NaN() to get the singleton JavaScript NaN (Not-a-Number) value. ```go func NaN() Value ``` -------------------------------- ### Pre-compiled Scripts with Goja Source: https://github.com/dop251/goja/blob/master/_autodocs/REFERENCE.md Illustrates how to pre-compile JavaScript scripts into programs for faster execution, storing them in a map for later use. ```go var scripts = map[string]*goja.Program{} func init() { scripts["math"] = goja.MustCompile("math.js", " Math.add = function(a, b) { return a + b } ", false) scripts["utils"] = goja.MustCompile("utils.js", " function formatDate(d) { return d.toISOString() } ", false) } func executeScript(name string) goja.Value { vm := goja.New() vm.RunProgram(scripts[name]) // ... } ``` -------------------------------- ### WeakMap Value Retention Example Source: https://github.com/dop251/goja/blob/master/README.md Demonstrates how values in a WeakMap remain reachable even after the map is dereferenced, until the key becomes unreachable. This is due to Go runtime limitations. ```javascript var m = new WeakMap(); var key = {}; var value = {/* a very large object */}; m.set(key, value); value = undefined; m = undefined; // The value does NOT become garbage-collectable at this point key = undefined; // Now it does // m.delete(key); // This would work too ``` -------------------------------- ### Asserting and Using a JavaScript Constructor in Go Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/functions-promises.md Use AssertConstructor to extract a JavaScript constructor function from a Value. The example shows how to create a new object using the constructor. ```go vm := goja.New() vm.RunString("function MyClass(value) { this.value = value }") val := vm.Get("MyClass") ctor, ok := goja.AssertConstructor(val) if !ok { panic("MyClass is not a constructor") } obj, err := ctor(nil, vm.ToValue(42)) if err != nil { panic(err) } fmt.Println(obj.Get("value").Export()) // 42 ``` -------------------------------- ### Persistent State with Goja Source: https://github.com/dop251/goja/blob/master/_autodocs/REFERENCE.md Demonstrates how to initialize a Goja runtime once and reuse it across multiple calls to maintain global state like counters. ```go vm := goja.New() // Initialize once vm.RunString(" var globalCounter = 0; function increment() { return ++globalCounter; } ") // Reuse across calls for i := 1; i <= 3; i++ { fn, _ := goja.AssertFunction(vm.Get("increment")) result, _ := fn(goja.Undefined()) fmt.Println(result.Export()) // 1, 2, 3 } ``` -------------------------------- ### GetSymbol Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/object.md Gets a property by Symbol key. ```APIDOC ## GetSymbol ### Description Gets a property by Symbol key. ### Method ```go func (o *Object) GetSymbol(s *Symbol) Value ``` ### Parameters #### Path Parameters - **s** (`*Symbol`) - Required - Symbol key ### Returns `Value` at property, or `Undefined()` if not found ### Example ```go sym := goja.NewSymbol("id") obj := vm.NewObject() obj.SetSymbol(sym, 42) val := obj.GetSymbol(sym) fmt.Println(val.Export()) // 42 ``` ``` -------------------------------- ### Get Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/runtime.md Retrieves a named property from the global object. ```APIDOC ## Get ### Description Retrieves a named property from the global object. ### Method Signature ```go func (r *Runtime) Get(name string) Value ``` ### Parameters #### Path Parameters - **name** (string) - Required - Property name in global scope ### Returns #### Success Response - **Value** - The value, or `Undefined()` if not found ### Example ```go vm := goja.New() vm.RunString("var x = 42") val := vm.Get("x") fmt.Println(val.Export()) // 42 val2 := vm.Get("nonexistent") fmt.Println(goja.IsUndefined(val2)) // true ``` ``` -------------------------------- ### String Representation Example Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/value.md Retrieves a Go string representation of a Goja Value, useful for debugging. This is equivalent to calling `.ToString().Export().(string)`. ```go val := vm.ToValue(123) fmt.Println(val.String()) // "123" ``` -------------------------------- ### ToBoolean Conversion Example Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/value.md Demonstrates converting various Goja values to a boolean based on ECMAScript truthy/falsy rules. Falsy values include false, 0, NaN, empty string, null, and undefined. ```go vm := goja.New() falsy := []Value{ goja.Undefined(), goja.Null(), vm.ToValue(false), vm.ToValue(0), vm.ToValue(""), } for _, v := range falsy { fmt.Println(v.ToBoolean()) // false } ``` -------------------------------- ### Prototype Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/object.md Gets the object's prototype (internal [[Prototype]]). ```APIDOC ## Prototype ### Description Gets the object's prototype (internal [[Prototype]]). ### Method ```go func (o *Object) Prototype() *Object ``` ### Returns `*Object` prototype, or nil ### Example ```go vm := goja.New() arr := vm.NewArray(1, 2, 3) proto := arr.Prototype() fmt.Println(proto != nil) // true (Array.prototype) ``` ``` -------------------------------- ### DynamicObject Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/object.md An interface for creating custom JavaScript objects in Go with dynamic property access. Implementations define how properties are Get, Set, Checked for existence, Deleted, and listed. ```APIDOC ### DynamicObject Interface for creating custom JavaScript objects from Go with dynamic property access. ```go interface DynamicObject { Get(key string) interface{} Set(key string, val interface{}) bool Has(key string) bool Delete(key string) bool Keys() []string } ``` ### NewDynamicObject Creates a JavaScript object backed by a `DynamicObject` implementation. ```go func (r *Runtime) NewDynamicObject(d DynamicObject) *Object ``` **Parameters:** | Parameter | Type | Description | |-----------|------|-------------| | d | `DynamicObject` | Custom dynamic object implementation | **Returns:** `*Object` proxy to the dynamic object **Example:** ```go type CustomMap struct { data map[string]interface{} } func (m *CustomMap) Get(key string) interface{} { return m.data[key] } func (m *CustomMap) Set(key string, val interface{}) bool { m.data[key] = val return true } func (m *CustomMap) Has(key string) bool { _, ok := m.data[key] return ok } func (m *CustomMap) Delete(key string) bool { delete(m.data, key) return true } func (m *CustomMap) Keys() []string { var keys []string for k := range m.data { keys = append(keys, k) } return keys } vm := goja.New() custom := &CustomMap{data: make(map[string]interface{})} jsObj := vm.NewDynamicObject(custom) vm.Set("custom", jsObj) ``` **Source:** `object_dynamic.go` ``` -------------------------------- ### Get Own Property Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/object.md Retrieves the property descriptor for an own property of the object. ```APIDOC ## Get Own Property ### Description Gets the property descriptor for an own property. ### Method `GetOwnProperty(key string) PropertyDescriptor` ### Parameters #### Path Parameters - **key** (string) - Required - Property name ### Returns `PropertyDescriptor` with the property attributes, empty if not found ### Example ```go obj := vm.NewObject() obj.Set("x", 10) desc := obj.GetOwnProperty("x") fmt.Println(desc.Value.Export()) // 10 fmt.Println(desc.Writable) // FLAG_TRUE ``` ``` -------------------------------- ### Handle Goja CompilerError Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/compilation.md Example of how to compile JavaScript code and handle potential compilation errors, specifically checking for and printing the message of a CompilerError. ```go _, err := goja.Compile("test.js", "var x = ", false) if err != nil { if compErr, ok := err.(*goja.CompilerError); ok { fmt.Println(compErr.Message) } } ``` -------------------------------- ### StartProfile Source: https://github.com/dop251/goja/blob/master/_autodocs/configuration.md Begins CPU profiling and writes output to the provided writer. It's recommended to call StopProfile when done. ```APIDOC ## StartProfile ### Description Begins CPU profiling and writes output to the provided writer. ### Method ```go func StartProfile(w io.Writer) error ``` ### Parameters #### Path Parameters - **w** (io.Writer) - Required - Output writer for profile data ### Returns - `error` if profiling cannot be started ### Request Example ```go file, _ := os.Create("cpu.prof") defer file.Close() goja.StartProfile(file) defer goja.StopProfile() vm := goja.New() vm.RunString(` var sum = 0 for (var i = 0; i < 1000000; i++) { sum += i } `) ``` ``` -------------------------------- ### Handle JavaScript Exception in Goja Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/compilation.md Example of running JavaScript code that throws an error and catching it as a Goja Exception. It demonstrates how to retrieve the thrown value using the Value() method. ```go vm := goja.New() _, err := vm.RunString(`throw "error message"`) if jsErr, ok := err.(*goja.Exception); ok { val := jsErr.Value() fmt.Println(val.Export()) // "error message" } ``` -------------------------------- ### Implementing Native Constructors in Go Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/functions-promises.md Shows how to define a native constructor in Go that can be instantiated using 'new' in JavaScript. Set properties on `call.This` to initialize the new object. ```go vm := goja.New() vm.Set("Point", func(call goja.ConstructorCall) *goja.Object { call.This.Set("x", call.Argument(0)) call.This.Set("y", call.Argument(1)) return nil // Return nil to use call.This }) vm.RunString(" var p = new Point(3, 4) console.log(p.x, p.y) // 3, 4 ") ``` -------------------------------- ### Goja TagFieldNameMapper Example Source: https://github.com/dop251/goja/blob/master/_autodocs/types.md Demonstrates setting a FieldNameMapper using struct tags to control JavaScript property access. Ensures that JavaScript can access fields like `person.first_name`. ```go vm := goja.New() vm.SetFieldNameMapper(goja.TagFieldNameMapper("json", true)) type Person struct { FirstName string `json:"first_name"` LastName string `json:"last_name"` } vm.Set("person", Person{FirstName: "John", LastName: "Doe"}) // JavaScript can access: person.first_name, person.last_name ``` -------------------------------- ### Get Argument from ConstructorCall in Goja Source: https://github.com/dop251/goja/blob/master/_autodocs/types.md Method to retrieve a specific argument from a ConstructorCall context. ```go func (c ConstructorCall) Argument(idx int) Value ``` -------------------------------- ### Create and Use Symbols in Goja Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/value.md Demonstrates creating unique symbols using `NewSymbol` and using them as keys for JavaScript objects within the Goja VM. Note that each call to `NewSymbol` creates a unique symbol, even with the same description. ```go sym1 := goja.NewSymbol("id") sym2 := goja.NewSymbol("id") fmt.Println(sym1 == sym2) // false (each symbol is unique) vm.Set("sym1", sym1) obj := vm.NewObject() obj.Set(sym1, 42) // Use symbol as key fmt.Println(obj.Get(sym1).Export()) // 42 ``` -------------------------------- ### Get JavaScript Null Value Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/value.md Use Null() to obtain the singleton JavaScript null value. ```go func Null() Value ``` -------------------------------- ### Reuse Runtime Instances Source: https://github.com/dop251/goja/blob/master/_autodocs/configuration.md Demonstrates the efficient way to reuse a Goja runtime instance for multiple script executions. ```go // Good vim := goja.New() for i := 0; i < 100; i++ { vm.RunString("// script") } // Avoid for i := 0; i < 100; i++ { vm := goja.New() // New instance each time vm.RunString("// script") } ``` -------------------------------- ### Expose Go Function to JavaScript Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/functions-promises.md Shows how to make a Go function available for execution within the JavaScript environment. Arguments are passed from JavaScript and returned as Goja values. ```go vm := goja.New() vm.Set("multiply", func(call goja.FunctionCall) goja.Value { a := call.Argument(0).ToNumber().ToFloat() b := call.Argument(1).ToNumber().ToFloat() return vm.ToValue(a * b) }) result, _ := vm.RunString("multiply(6, 7)") fmt.Println(result.Export()) // 42.0 ``` -------------------------------- ### Get JavaScript Undefined Value Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/value.md Use Undefined() to retrieve the singleton JavaScript undefined value. ```go func Undefined() Value ``` -------------------------------- ### Get JavaScript Negative Infinity Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/value.md Use NegativeInf() to retrieve the singleton JavaScript negative infinity value. ```go func NegativeInf() Value ``` -------------------------------- ### Set Limits and Options Early Source: https://github.com/dop251/goja/blob/master/_autodocs/configuration.md Configures limits such as call stack size, random source, and parser options before running untrusted code for security. ```go vm := goja.New() vm.SetMaxCallStackSize(1000) vm.SetRandSource(securRandSource) vm.SetParserOptions(parser.WithDisableSourceMaps) // Now safe to run untrusted code vm.RunString(userProvidedCode) ``` -------------------------------- ### Get JavaScript Positive Infinity Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/value.md Use PositiveInf() to retrieve the singleton JavaScript positive infinity value. ```go func PositiveInf() Value ``` -------------------------------- ### Create Native JavaScript Constructor Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/functions-promises.md Illustrates defining a JavaScript constructor in Go. This allows creating new objects in JavaScript using a Go-defined constructor, setting properties on the new instance. ```go vm := goja.New() vm.Set("Rectangle", func(call goja.ConstructorCall) *goja.Object { width := call.Argument(0).ToNumber().ToFloat() height := call.Argument(1).ToNumber().ToFloat() call.This.Set("width", width) call.This.Set("height", height) call.This.Set("area", width*height) return nil }) vm.RunString(" var r = new Rectangle(5, 10) console.log(r.area) // 50 ") ``` -------------------------------- ### Get Object Prototype Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/object.md Retrieves the internal prototype of a Goja object. Returns nil if the object has no prototype. ```go vm := goja.New() arr := vm.NewArray(1, 2, 3) proto := arr.Prototype() fmt.Println(proto != nil) // true (Array.prototype) ``` -------------------------------- ### Pre-compile and Cache Programs Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/compilation.md Demonstrates how to compile a JavaScript program once and reuse it multiple times for different user contexts, improving performance by avoiding repeated compilation. ```APIDOC ## Pre-compile and Cache Programs ### Description Compiles a JavaScript program once and caches it for subsequent executions. This pattern is useful for shared JavaScript code that needs to be executed in multiple VM instances. ### Method goja.Compile (used in init) goja.New() goja.RunProgram() ### Parameters None directly for the pattern, but `goja.Compile` takes filename, src, and strict. ### Request Example ```go var globalProgram *goja.Program func init() { var err error globalProgram, err = goja.Compile("global.js", ` function sharedFunction() { return "shared" } `, false) if err != nil { panic(err) } } func executeForUser(userID string) goja.Value { vm := goja.New() vm.Set("userID", userID) vm.RunProgram(globalProgram) result, _ := vm.RunString(`sharedFunction()`) return result } ``` ### Response #### Success Response (200) - **goja.Value** - The result of executing the cached program. #### Response Example ```go // Assuming executeForUser is called, the result would be the return value of sharedFunction() // e.g., a goja.Value representing the string "shared" ``` ``` -------------------------------- ### Now Function Type Source: https://github.com/dop251/goja/blob/master/_autodocs/types.md A function type for getting the current time. It is used by `Runtime.SetTimeSource()` and `Date.now()` to provide the current time. ```APIDOC ## Now ### Description Function type for getting current time. ### Returns Current time ### Usage `Runtime.SetTimeSource()`, `Date.now()`. ``` -------------------------------- ### Get String Representation of Object Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/object.md Returns a string that represents the Goja object, typically in the format '[object Type]'. ```go obj := vm.NewObject() fmt.Println(obj.String()) // "[object Object]" ``` -------------------------------- ### Use Native Go Functions for Hot Paths in Goja Source: https://github.com/dop251/goja/blob/master/_autodocs/REFERENCE.md For performance-critical sections, implement logic directly in Go using `vm.Set()` to expose native functions to the JavaScript environment. This is generally faster than executing equivalent JavaScript code. ```go // Fast - native Go vm.Set("sum", func(call goja.FunctionCall) goja.Value { // Direct computation in Go return vm.ToValue(42) }) // Slower - JavaScript function called repeatedly vm.RunString(` function sum(arr) { var result = 0; for (var i = 0; i < arr.length; i++) { result += arr[i]; } return result; } `) ``` -------------------------------- ### Get Property Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/object.md Retrieves a property value from an object using its string key. Returns `Undefined()` if the property does not exist. ```APIDOC ## Get Property ### Description Retrieves a property value by string key. ### Method `Get(key string) Value` ### Parameters #### Path Parameters - **key** (string) - Required - Property name ### Returns `Value` at property, or `Undefined()` if not found ### Example ```go vm := goja.New() obj := vm.NewObject() obj.Set("x", 42) val := obj.Get("x") fmt.Println(val.Export()) // 42 ``` ``` -------------------------------- ### Isolated Execution Contexts with Goja Source: https://github.com/dop251/goja/blob/master/_autodocs/REFERENCE.md Shows how to create sandboxed environments for JavaScript execution using a struct to encapsulate the Goja runtime and its configuration. ```go type Sandbox struct { vm *goja.Runtime } func NewSandbox() *Sandbox { vm := goja.New() vm.SetMaxCallStackSize(1000) return &Sandbox{vm: vm} } func (s *Sandbox) Execute(code string) (goja.Value, error) { return s.RunString(code) } ``` -------------------------------- ### Expose Go Function to JavaScript Source: https://github.com/dop251/goja/blob/master/_autodocs/INDEX.md Expose Go functions to the JavaScript environment using `vm.Set`. The exposed function can accept arguments from JavaScript and return a value. ```go vm.Set("goFunc", func(call goja.FunctionCall) goja.Value { return vm.ToValue(call.Argument(0).ToNumber() * 2) }) ``` -------------------------------- ### Creating an Object from a JavaScript Class Constructor in Go Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/functions-promises.md Demonstrates creating a new instance of a JavaScript class using its constructor obtained via AssertConstructor. This is suitable for ES6 classes. ```go vm := goja.New() vm.RunString(" class Animal { constructor(name) { this.name = name } } ") ctor, _ := goja.AssertConstructor(vm.Get("Animal")) animal, _ := ctor(nil, vm.ToValue("Dog")) fmt.Println(animal.Get("name").Export()) // "Dog" ``` -------------------------------- ### Get Object Class Name Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/object.md Returns the internal JavaScript class name of a Goja object, such as 'Object', 'Array', or 'Function'. ```go vm := goja.New() obj := vm.NewObject() arr := vm.NewArray() fmt.Println(obj.ClassName()) // "Object" fmt.Println(arr.ClassName()) // "Array" ``` -------------------------------- ### Get Own Property Descriptor Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/object.md Retrieves the PropertyDescriptor for a property directly defined on the object. Returns an empty descriptor if the property is not found. ```go obj := vm.NewObject() obj.Set("x", 10) desc := obj.GetOwnProperty("x") fmt.Println(desc.Value.Export()) // 10 fmt.Println(desc.Writable) // FLAG_TRUE ``` -------------------------------- ### Get Property Value Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/object.md Retrieves a property value from an object using its string key. Returns Undefined() if the property is not found. ```go vm := goja.New() obj := vm.NewObject() obj.Set("x", 42) val := obj.Get("x") fmt.Println(val.Export()) // 42 ``` -------------------------------- ### Create a Goja Runtime Source: https://github.com/dop251/goja/blob/master/_autodocs/00-START-HERE.md Instantiate a new JavaScript execution environment. This is the primary object for interacting with Goja. ```go vm := goja.New() result, err := vm.RunString("1 + 2") ``` -------------------------------- ### Get first index of ObjectLiteral Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the first character of an ObjectLiteral node. This is part of the Node interface implementation. ```go func (self *ObjectLiteral) Idx0() file.Idx ``` -------------------------------- ### Instantiate Object with Constructor Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/runtime.md Create a new object instance by calling a JavaScript constructor function. This method is analogous to the JavaScript `new` operator. ```go vm := goja.New() vm.RunString(" function MyClass(value) { this.value = value } ") constructor := vm.Get("MyClass") instance, err := vm.New(constructor, vm.ToValue(42)) if err != nil { panic(err) } fmt.Println(instance.Get("value").Export()) // 42 ``` -------------------------------- ### Get first index of NumberLiteral Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the first character of a NumberLiteral node. This is part of the Node interface implementation. ```go func (self *NumberLiteral) Idx0() file.Idx ``` -------------------------------- ### Get first index of NullLiteral Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the first character of a NullLiteral node. This is part of the Node interface implementation. ```go func (self *NullLiteral) Idx0() file.Idx ``` -------------------------------- ### Provide Custom Time Source Source: https://github.com/dop251/goja/blob/master/_autodocs/configuration.md Replaces the default time source for `Date.now()` and `new Date()` with a custom function, essential for testing time-dependent logic. Requires importing `time`. ```go import "time" vm := goja.New() // Mock time for testing mockTime := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) vm.SetTimeSource(func() time.Time { return mockTime }) result, _ := vm.RunString(`new Date().getFullYear()`) fmt.Println(result.Export()) // 2020 ``` -------------------------------- ### Get first index of NewExpression Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the first character of a NewExpression node. This is part of the Node interface implementation. ```go func (self *NewExpression) Idx0() file.Idx ``` -------------------------------- ### Create a new JavaScript Runtime Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/runtime.md Instantiate a new, independent JavaScript runtime. Each runtime is not goroutine-safe and should only be used by a single goroutine at a time. ```go vm := goja.New() v, err := vm.RunString("2 + 2") if err != nil { panic(err) } result := v.Export().(int64) // 4 ``` -------------------------------- ### Get first index of LabelledStatement Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the first character of a LabelledStatement node. This is part of the Node interface implementation. ```go func (self *LabelledStatement) Idx0() file.Idx ``` -------------------------------- ### Trap and Log JavaScript Errors in Go Source: https://github.com/dop251/goja/blob/master/_autodocs/errors.md Shows how to set up a Go function that can be called from JavaScript to trap and log errors occurring during script execution, providing a centralized error reporting mechanism. ```go vm := goja.New() vm.Set("onError", func(call goja.FunctionCall) goja.Value { msg := call.Argument(0).String() fmt.Printf("JavaScript error: %s\n", msg) return goja.Undefined() }) vm.RunString(` try { // risky code throw new Error("test error") } catch (e) { onError(e.message) } `) ``` -------------------------------- ### Get first index of IfStatement Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the first character of an IfStatement node. This is part of the Node interface implementation. ```go func (self *IfStatement) Idx0() file.Idx ``` -------------------------------- ### Create and Set Properties on Goja Objects Source: https://github.com/dop251/goja/blob/master/_autodocs/00-START-HERE.md Create new JavaScript objects and dynamically set their properties from Go. ```go obj := vm.NewObject() obj.Set("key", "value") ``` -------------------------------- ### Define a File Structure Source: https://github.com/dop251/goja/blob/master/file/README.markdown Defines the basic structure for a source file, holding its name, source code, and base offset. ```go type File struct { } ``` -------------------------------- ### Get first index of Identifier Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the first character of an Identifier node. This is part of the Node interface implementation. ```go func (self *Identifier) Idx0() file.Idx ``` -------------------------------- ### Execute Basic JavaScript String Source: https://github.com/dop251/goja/blob/master/_autodocs/REFERENCE.md Create a new Goja runtime and execute a simple JavaScript expression. The result is exported to a Go type. ```go import "github.com/dop251/goja" vm := goja.New() result, err := vm.RunString("2 + 2") if err != nil { panic(err) } fmt.Println(result.Export()) // 4 ``` -------------------------------- ### Get first index of FunctionLiteral Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the first character of a FunctionLiteral node. This is part of the Node interface implementation. ```go func (self *FunctionLiteral) Idx0() file.Idx ``` -------------------------------- ### Compile and Run JavaScript Programs Source: https://github.com/dop251/goja/blob/master/_autodocs/00-START-HERE.md Pre-compile JavaScript code into bytecode for potential reuse across multiple runtimes, improving performance for frequently executed scripts. ```go prog := goja.MustCompile("script.js", code, false) vm.RunProgram(prog) ``` -------------------------------- ### Get first index of ForStatement Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the first character of a ForStatement node. This is part of the Node interface implementation. ```go func (self *ForStatement) Idx0() file.Idx ``` -------------------------------- ### Create JavaScript Object with Prototype Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/runtime.md Use `CreateObject` to instantiate a new JavaScript object with a specified prototype. Pass `nil` for the prototype if none is required. ```go vm := goja.New() arrayProto := vm.Get("Array").ToObject(vm).Get("prototype").(*Object) arr := vm.CreateObject(arrayProto) ``` -------------------------------- ### Get first index of ForInStatement Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the first character of a ForInStatement node. This is part of the Node interface implementation. ```go func (self *ForInStatement) Idx0() file.Idx ``` -------------------------------- ### Get first index of ExpressionStatement Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the first character of an ExpressionStatement node. This is part of the Node interface implementation. ```go func (self *ExpressionStatement) Idx0() file.Idx ``` -------------------------------- ### Accessing Function Arguments in Go Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/functions-promises.md Demonstrates how to access and use arguments passed to a Go function exposed to JavaScript. Ensure arguments are converted to the appropriate Go types. ```go vm := goja.New() vm.Set("sum", func(call goja.FunctionCall) goja.Value { a := call.Argument(0).ToNumber().ToFloat() b := call.Argument(1).ToNumber().ToFloat() return vm.ToValue(a + b) }) result, _ := vm.RunString("sum(10, 32)") fmt.Println(result.Export()) // 42.0 ``` -------------------------------- ### Get first index of EmptyStatement Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the first character of an EmptyStatement node. This is part of the Node interface implementation. ```go func (self *EmptyStatement) Idx0() file.Idx ``` -------------------------------- ### Retrieve File by Index Source: https://github.com/dop251/goja/blob/master/file/README.markdown Fetches a File object from the FileSet using its index. ```go func (self *FileSet) File(idx Idx) *File ``` -------------------------------- ### Get first index of DotExpression Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the first character of a DotExpression node. This is part of the Node interface implementation. ```go func (self *DotExpression) Idx0() file.Idx ``` -------------------------------- ### Get first index of DoWhileStatement Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the first character of a DoWhileStatement node. This is part of the Node interface implementation. ```go func (self *DoWhileStatement) Idx0() file.Idx ``` -------------------------------- ### Call JavaScript Function Using ExportTo Source: https://github.com/dop251/goja/blob/master/README.md Demonstrates calling a JavaScript function from Go by exporting it to a Go function signature using ExportTo. This provides a more idiomatic Go function call experience. ```go const SCRIPT = "\nfunction sum(a, b) {\n return +a + b;\n}\n" vm := goja.New() _, err := vm.RunString(SCRIPT) if err != nil { panic(err) } var sum func(int, int) int err = vm.ExportTo(vm.Get("sum"), &sum) if err != nil { panic(err) } fmt.Println(sum(40, 2)) ``` -------------------------------- ### Call Go Methods from JavaScript Source: https://github.com/dop251/goja/blob/master/_autodocs/REFERENCE.md Make Go methods available for invocation from JavaScript. Ensure the Go type has methods with appropriate signatures that can be called by the JavaScript environment. ```go type Logger struct { prefix string } func (l *Logger) Info(msg string) { fmt.Printf("[%s] INFO: %s\n", l.prefix, msg) } vm := goja.New() logger := &Logger{prefix: "app"} vm.Set("logger", logger) vm.RunString( ` logger.Info("Application started") ` ) ``` -------------------------------- ### ToNumber Conversion Example Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/value.md Illustrates converting various JavaScript values to a numeric Value using ECMAScript coercion rules. ```javascript vm := goja.New() vm.RunString(" var results = [ Number(true), // 1 Number(false), // 0 Number(\"3.14\"), // 3.14 Number(\"\"), // 0 Number(\"abc\"), // NaN Number(null), // 0 Number(undefined) // NaN ] ") ``` -------------------------------- ### Sharing Objects Across Runtimes (Unsafe vs. Safe) Source: https://github.com/dop251/goja/blob/master/_autodocs/REFERENCE.md Highlights the limitation that standard JavaScript objects are tied to their originating runtime. Demonstrates the unsafe method of attempting to share them and the correct approach using `NewSharedDynamicObject` for cross-runtime compatibility. ```go // UNSAFE - Objects tied to runtime vm1 := goja.New() obj1 := vm1.NewObject() vm2 := goja.New() vm2.Set("obj", obj1) // ERROR - different runtime // SAFE - Use shared dynamic objects shared := goja.NewSharedDynamicObject(&customObj) vm1.Set("shared", shared) vm2.Set("shared", shared) ``` -------------------------------- ### Get last index of ObjectLiteral Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the character immediately following an ObjectLiteral node. This is part of the Node interface implementation. ```go func (self *ObjectLiteral) Idx1() file.Idx ``` -------------------------------- ### Get last index of NumberLiteral Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the character immediately following a NumberLiteral node. This is part of the Node interface implementation. ```go func (self *NumberLiteral) Idx1() file.Idx ``` -------------------------------- ### Get last index of NullLiteral Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the character immediately following a NullLiteral node. This is part of the Node interface implementation. ```go func (self *NullLiteral) Idx1() file.Idx ``` -------------------------------- ### New Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/runtime.md Calls a JavaScript constructor function, similar to the `new` operator in JavaScript. It returns the newly created object or an error if construction fails. ```APIDOC ## New ### Description Calls a constructor function (similar to JavaScript's `new` operator). ### Method func (r *Runtime) New(construct Value, args ...Value) (*Object, error) ### Parameters #### Path Parameters - **construct** (`Value`) - Required - Constructor function - **args** (`...Value`) - Optional - Arguments to pass to constructor ### Returns - **`*Object`**: The newly created object - **`error`**: Non-nil if construction fails ### Request Example ```go vm := goja.New() vm.RunString(` function MyClass(value) { this.value = value } `) constructor := vm.Get("MyClass") instance, err := vm.New(constructor, vm.ToValue(42)) if err != nil { panic(err) } fmt.Println(instance.Get("value").Export()) // 42 ``` ``` -------------------------------- ### Get last index of NewExpression Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the character immediately following a NewExpression node. This is part of the Node interface implementation. ```go func (self *NewExpression) Idx1() file.Idx ``` -------------------------------- ### Goja StackFrame Methods Source: https://github.com/dop251/goja/blob/master/_autodocs/types.md Provides methods to retrieve the source name, function name, and position of a StackFrame. ```go func (f *StackFrame) SrcName() string func (f *StackFrame) FuncName() string func (f *StackFrame) Position() file.Position ``` -------------------------------- ### Get last index of LabelledStatement Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the character immediately following a LabelledStatement node. This is part of the Node interface implementation. ```go func (self *LabelledStatement) Idx1() file.Idx ``` -------------------------------- ### Expose Go Function to JavaScript Source: https://github.com/dop251/goja/blob/master/_autodocs/00-START-HERE.md Make a Go function available for execution within the JavaScript environment. The function signature must match `func(call goja.FunctionCall) goja.Value`. ```go vm.Set("multiply", func(call goja.FunctionCall) goja.Value { a := call.Argument(0).ToNumber().ToFloat() b := call.Argument(1).ToNumber().ToFloat() return vm.ToValue(a * b) }) ``` -------------------------------- ### Calling a JavaScript Method with 'this' Context in Go Source: https://github.com/dop251/goja/blob/master/_autodocs/api-reference/functions-promises.md Demonstrates calling a JavaScript method from Go, ensuring the correct 'this' context is provided. This is useful for object methods. ```go vm := goja.New() vm.RunString(" var obj = { value: 42, getValue: function() { return this.value } } ") val := vm.Get("obj").(*goja.Object) getValueFn, _ := goja.AssertFunction(val.Get("getValue")) // Call method with correct 'this' context result, _ := getValueFn(val) fmt.Println(result.Export()) // 42 ``` -------------------------------- ### Get last index of IfStatement Source: https://github.com/dop251/goja/blob/master/ast/README.markdown Retrieves the index of the character immediately following an IfStatement node. This is part of the Node interface implementation. ```go func (self *IfStatement) Idx1() file.Idx ```