### Func Example Source: https://pkg.go.dev/github.com/dop251/goja Illustrates calling a JavaScript function from Go. ```go Output: 42 ``` -------------------------------- ### FuncVariadic Example Source: https://pkg.go.dev/github.com/dop251/goja Demonstrates calling a variadic JavaScript function from Go. ```go Output: a#b#42 ``` -------------------------------- ### SetToMap Example Source: https://pkg.go.dev/github.com/dop251/goja Illustrates converting a JavaScript Set to a Go map. ```go Output: map[1:{} 2:{} 3:{}] ``` -------------------------------- ### MapToMap Example Source: https://pkg.go.dev/github.com/dop251/goja Illustrates converting a JavaScript Map to a Go map. ```go Output: map[1:true 2:false] ``` -------------------------------- ### NewArray Example Source: https://pkg.go.dev/github.com/dop251/goja Demonstrates creating a new JavaScript array from Go values. ```go Output: 1 2 true ``` -------------------------------- ### DoWhileStatement Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a `do...while` statement. Provides methods to get the start and end indices. ```APIDOC ## DoWhileStatement Node ### Description Represents a do...while statement. ### Methods - `Idx0() file.Idx`: Returns the starting index of the do-while statement. - `Idx1() file.Idx`: Returns the ending index of the do-while statement. ``` -------------------------------- ### Manage Execution Profiling Source: https://pkg.go.dev/github.com/dop251/goja Functions to start and stop execution time profiling for the VM. ```go func StartProfile(w io.Writer) error ``` ```go func StopProfile() ``` -------------------------------- ### MapToSlice Example Source: https://pkg.go.dev/github.com/dop251/goja Demonstrates converting a JavaScript Map to a Go slice of key-value pairs. ```go Output: [[1 true] [2 false]] ``` -------------------------------- ### ArrayLikeToSlice Example Source: https://pkg.go.dev/github.com/dop251/goja Demonstrates converting an ArrayLike JavaScript object to a Go slice. ```go Output: [1 2 3] ``` -------------------------------- ### FuncThrow Example Source: https://pkg.go.dev/github.com/dop251/goja Shows how a JavaScript function throwing an error is handled. ```go Output: Error: testing at f (:3:9(3)) ``` -------------------------------- ### Get File Source Code Source: https://pkg.go.dev/github.com/dop251/goja/file Retrieves the source code string of the File. ```go func (fl *File) Source() string ``` -------------------------------- ### Get Enumerable Keys Source: https://pkg.go.dev/github.com/dop251/goja Returns a list of enumerable keys. ```go func (o *Object) Keys() (keys []string) ``` -------------------------------- ### Get Property Names Source: https://pkg.go.dev/github.com/dop251/goja Returns a list of own string properties. ```go func (o *Object) GetOwnPropertyNames() (keys []string) ``` -------------------------------- ### Position String Formatting Examples Source: https://pkg.go.dev/github.com/dop251/goja/file Illustrates the different string formats returned by the Position.String() method based on whether filename, line, and column information is available. Use this to understand how source positions are represented. ```text file:line:column A valid position with filename line:column A valid position without filename file An invalid position with filename - An invalid position without filename ``` -------------------------------- ### Run Basic JavaScript and Get Result Source: https://pkg.go.dev/github.com/dop251/goja Execute a simple JavaScript expression and retrieve its 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) } ``` -------------------------------- ### IterableToSlice Example Source: https://pkg.go.dev/github.com/dop251/goja Shows converting an iterable JavaScript object to a Go slice. ```go Output: [3 2 1] ``` -------------------------------- ### Get File Name Source: https://pkg.go.dev/github.com/dop251/goja/file Retrieves the filename associated with the File. ```go func (fl *File) Name() string ``` -------------------------------- ### ForOf Loop Example Source: https://pkg.go.dev/github.com/dop251/goja Provides a Go equivalent of a JavaScript for-of loop for iterating over iterable objects. Panics if the value is not iterable or if an exception occurs during iteration. Must be enclosed in Try when called directly from Go. ```go Output: a=1,b=2, ``` -------------------------------- ### ForLoopInitializerVarDeclList Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a variable declaration list (e.g., `var a = 1, b = 2`) as the initializer of a for loop. Provides methods to get the start and end indices. ```APIDOC ## ForLoopInitializerVarDeclList Node ### Description Represents a variable declaration list as the initializer of a for loop. ### Methods - `Idx0() file.Idx`: Returns the starting index of the variable declaration list. - `Idx1() file.Idx`: Returns the ending index of the variable declaration list. ``` -------------------------------- ### ForLoopInitializerLexicalDecl Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a lexical declaration (e.g., `let`, `const`) as the initializer of a for loop. Provides methods to get the start and end indices. ```APIDOC ## ForLoopInitializerLexicalDecl Node ### Description Represents a lexical declaration as the initializer of a for loop. ### Methods - `Idx0() file.Idx`: Returns the starting index of the lexical declaration. - `Idx1() file.Idx`: Returns the ending index of the lexical declaration. ``` -------------------------------- ### Get File Position by Offset Source: https://pkg.go.dev/github.com/dop251/goja/file Calculates the Position within the file for a given source code offset. ```go func (fl *File) Position(offset int) Position ``` -------------------------------- ### Get Property Value Source: https://pkg.go.dev/github.com/dop251/goja Retrieves a property value by name or symbol. ```go func (o *Object) Get(name string) Value ``` ```go func (o *Object) GetSymbol(sym *Symbol) Value ``` -------------------------------- ### FunctionDeclaration Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a function declaration. Provides methods to get the start and end indices. ```APIDOC ## FunctionDeclaration Node ### Description Represents a function declaration. ### Methods - `Idx0() file.Idx`: Returns the starting index of the function declaration. - `Idx1() file.Idx`: Returns the ending index of the function declaration. ``` -------------------------------- ### ForStatement Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a standard `for` statement. Provides methods to get the start and end indices. ```APIDOC ## ForStatement Node ### Description Represents a standard for statement. ### Methods - `Idx0() file.Idx`: Returns the starting index of the for statement. - `Idx1() file.Idx`: Returns the ending index of the for statement. ``` -------------------------------- ### Date UTC Integer Overflow Example Source: https://pkg.go.dev/github.com/dop251/goja Shows an example of incorrect Date calculation in Goja due to Go's standard library using `int` instead of `float` for epoch timestamps. Passing arguments that overflow `int` can lead to inaccurate results. ```javascript Date.UTC(1970, 0, 1, 80063993375, 29, 1, -288230376151711740) // returns 29256 instead of 29312 ``` -------------------------------- ### Get File Base Offset Source: https://pkg.go.dev/github.com/dop251/goja/file Retrieves the base offset of the file. ```go func (fl *File) Base() int ``` -------------------------------- ### ForOfStatement Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a `for...of` statement. Provides methods to get the start and end indices. ```APIDOC ## ForOfStatement Node ### Description Represents a for...of statement. ### Methods - `Idx0() file.Idx`: Returns the starting index of the for-of statement. - `Idx1() file.Idx`: Returns the ending index of the for-of statement. ``` -------------------------------- ### Create a New File Instance Source: https://pkg.go.dev/github.com/dop251/goja/file Creates a new File instance with the given filename, source code, and base offset. ```go func NewFile(filename, src string, base int) *File ``` -------------------------------- ### ForInStatement Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a `for...in` statement. Provides methods to get the start and end indices. ```APIDOC ## ForInStatement Node ### Description Represents a for...in statement. ### Methods - `Idx0() file.Idx`: Returns the starting index of the for-in statement. - `Idx1() file.Idx`: Returns the ending index of the for-in statement. ``` -------------------------------- ### DebuggerStatement Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a `debugger` statement. Provides methods to get the start and end indices. ```APIDOC ## DebuggerStatement Node ### Description Represents a debugger statement. ### Methods - `Idx0() file.Idx`: Returns the starting index of the debugger statement. - `Idx1() file.Idx`: Returns the ending index of the debugger statement. ``` -------------------------------- ### ClassDeclaration Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a class declaration. Provides methods to get the start and end indices. ```APIDOC ## ClassDeclaration Node ### Description Represents a class declaration. ### Methods - `Idx0() file.Idx`: Returns the starting index of the class declaration. - `Idx1() file.Idx`: Returns the ending index of the class declaration. ``` -------------------------------- ### WeakMap Value Retention Example Source: https://pkg.go.dev/github.com/dop251/goja Demonstrates how values in a WeakMap remain in memory even after the map and value variable are cleared, due to Go's garbage collection limitations with cycles. The value is only garbage collected when the key becomes unreachable. ```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 ``` -------------------------------- ### CallExpression Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a function call. Provides methods to get the start and end indices. ```APIDOC ## CallExpression Node ### Description Represents a function call. ### Methods - `Idx0() file.Idx`: Returns the starting index of the call expression. - `Idx1() file.Idx`: Returns the ending index of the call expression. ``` -------------------------------- ### ForDeclaration Idx0 Method Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the file index for the ForDeclaration. ```go func (self *ForDeclaration) Idx0() file.Idx ``` -------------------------------- ### AwaitExpression Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents an await expression. Provides methods to get the start and end indices. ```APIDOC ## AwaitExpression Node ### Description Represents an await expression. ### Methods - `Idx0() file.Idx`: Returns the starting index of the await expression. - `Idx1() file.Idx`: Returns the ending index of the await expression. ``` -------------------------------- ### DoWhileStatement Idx0 Method Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the file index for the DoWhileStatement. ```go func (self *DoWhileStatement) Idx0() file.Idx ``` -------------------------------- ### ForLoopInitializerExpression Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents an expression as the initializer of a for loop. Provides methods to get the start and end indices. ```APIDOC ## ForLoopInitializerExpression Node ### Description Represents an expression as the initializer of a for loop. ### Methods - `Idx0() file.Idx`: Returns the starting index of the initializer expression. - `Idx1() file.Idx`: Returns the ending index of the initializer expression. ``` -------------------------------- ### EmptyStatement Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents an empty statement (just a semicolon). Provides methods to get the start and end indices. ```APIDOC ## EmptyStatement Node ### Description Represents an empty statement. ### Methods - `Idx0() file.Idx`: Returns the starting index of the empty statement. - `Idx1() file.Idx`: Returns the ending index of the empty statement. ``` -------------------------------- ### DoWhileStatement Idx1 Method Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the file index for the DoWhileStatement. ```go func (self *DoWhileStatement) Idx1() file.Idx ``` -------------------------------- ### Binding Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a binding in declarations or assignments. Provides methods to get the start and end indices. ```APIDOC ## Binding Node ### Description Represents a binding. ### Methods - `Idx0() file.Idx`: Returns the starting index of the binding. - `Idx1() file.Idx`: Returns the ending index of the binding. ``` -------------------------------- ### ForDeclaration Idx1 Method Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the file index for the ForDeclaration. ```go func (self *ForDeclaration) Idx1() file.Idx ``` -------------------------------- ### ArrowFunctionLiteral Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents an arrow function expression. Provides methods to get the start and end indices. ```APIDOC ## ArrowFunctionLiteral Node ### Description Represents an arrow function expression. ### Methods - `Idx0() file.Idx`: Returns the starting index of the arrow function. - `Idx1() file.Idx`: Returns the ending index of the arrow function. ``` -------------------------------- ### ForIntoExpression Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents an expression used in a for...into loop. Provides methods to get the start and end indices. ```APIDOC ## ForIntoExpression Node ### Description Represents an expression used in a for...into loop. ### Methods - `Idx0() file.Idx`: Returns the starting index of the for-into expression. - `Idx1() file.Idx`: Returns the ending index of the for-into expression. ``` -------------------------------- ### Create String from Go String Source: https://pkg.go.dev/github.com/dop251/goja/unistring Initializes a String from a standard Go string. ```go func NewFromString(s string) String ``` -------------------------------- ### FieldDefinition Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a field definition within a class. Provides methods to get the start and end indices. ```APIDOC ## FieldDefinition Node ### Description Represents a field definition within a class. ### Methods - `Idx0() file.Idx`: Returns the starting index of the field definition. - `Idx1() file.Idx`: Returns the ending index of the field definition. ``` -------------------------------- ### ExpressionStatement Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a statement that consists of a single expression. Provides methods to get the start and end indices. ```APIDOC ## ExpressionStatement Node ### Description Represents a statement that consists of a single expression. ### Methods - `Idx0() file.Idx`: Returns the starting index of the expression statement. - `Idx1() file.Idx`: Returns the ending index of the expression statement. ``` -------------------------------- ### Demonstrate copy-on-change mechanism Source: https://pkg.go.dev/github.com/dop251/goja Shows how references to compound values are managed when the original container is modified. ```javascript 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 ``` -------------------------------- ### Create a New Object Source: https://pkg.go.dev/github.com/dop251/goja Creates a new empty Object. ```go func (r *Runtime) NewObject() (v *Object) ``` -------------------------------- ### ClassStaticBlock Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a static block within a class. Provides methods to get the start and end indices. ```APIDOC ## ClassStaticBlock Node ### Description Represents a static block within a class. ### Methods - `Idx0() file.Idx`: Returns the starting index of the static block. - `Idx1() file.Idx`: Returns the ending index of the static block. ``` -------------------------------- ### ClassLiteral Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a class literal (class expression). Provides methods to get the start and end indices. ```APIDOC ## ClassLiteral Node ### Description Represents a class literal (class expression). ### Methods - `Idx0() file.Idx`: Returns the starting index of the class literal. - `Idx1() file.Idx`: Returns the ending index of the class literal. ``` -------------------------------- ### Create a Proxy Object Source: https://pkg.go.dev/github.com/dop251/goja Creates a new Proxy object with the specified target and trap configuration. ```go func (r *Runtime) NewProxy(target *Object, nativeHandler *ProxyTrapConfig) Proxy ``` -------------------------------- ### BooleanLiteral Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a boolean literal (`true` or `false`). Provides methods to get the start and end indices. ```APIDOC ## BooleanLiteral Node ### Description Represents a boolean literal. ### Methods - `Idx0() file.Idx`: Returns the starting index of the boolean literal. - `Idx1() file.Idx`: Returns the ending index of the boolean literal. ``` -------------------------------- ### BinaryExpression Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a binary expression (e.g., `a + b`). Provides methods to get the start and end indices. ```APIDOC ## BinaryExpression Node ### Description Represents a binary expression. ### Methods - `Idx0() file.Idx`: Returns the starting index of the binary expression. - `Idx1() file.Idx`: Returns the ending index of the binary expression. ``` -------------------------------- ### Execute Script String Source: https://pkg.go.dev/github.com/dop251/goja Executes a script string in the global context. ```go func (r *Runtime) RunScript(name, src string) (Value, error) ``` ```go func (r *Runtime) RunString(str string) (Value, error) ``` -------------------------------- ### BadStatement Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents an invalid or malformed statement in the AST. Provides methods to get the start and end indices. ```APIDOC ## BadStatement Node ### Description Represents an invalid or malformed statement. ### Methods - `Idx0() file.Idx`: Returns the starting index of the bad statement. - `Idx1() file.Idx`: Returns the ending index of the bad statement. ``` -------------------------------- ### BadExpression Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents an invalid or malformed expression in the AST. Provides methods to get the start and end indices. ```APIDOC ## BadExpression Node ### Description Represents an invalid or malformed expression. ### Methods - `Idx0() file.Idx`: Returns the starting index of the bad expression. - `Idx1() file.Idx`: Returns the ending index of the bad expression. ``` -------------------------------- ### Demonstrate Export behavior with maps Source: https://pkg.go.dev/github.com/dop251/goja Shows how assigning a JavaScript object to a wrapped Go map results in an Exported copy. ```go 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" ``` -------------------------------- ### Execute Compiled Program Source: https://pkg.go.dev/github.com/dop251/goja Executes a pre-compiled Program in the global context. ```go func (r *Runtime) RunProgram(p *Program) (result Value, err error) ``` -------------------------------- ### AssignExpression Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents an assignment expression (e.g., `a = b`). Provides methods to get the start and end indices. ```APIDOC ## AssignExpression Node ### Description Represents an assignment expression. ### Methods - `Idx0() file.Idx`: Returns the starting index of the assignment expression. - `Idx1() file.Idx`: Returns the ending index of the assignment expression. ``` -------------------------------- ### ForIntoVar Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a variable declaration used in a for...into loop. Provides methods to get the start and end indices. ```APIDOC ## ForIntoVar Node ### Description Represents a variable declaration used in a for...into loop. ### Methods - `Idx0() file.Idx`: Returns the starting index of the for-into variable. - `Idx1() file.Idx`: Returns the ending index of the for-into variable. ``` -------------------------------- ### StackFrame Methods Source: https://pkg.go.dev/github.com/dop251/goja Methods to retrieve information from a StackFrame. ```go func (f *StackFrame) FuncName() string ``` ```go func (f *StackFrame) Position() file.Position ``` ```go func (f *StackFrame) SrcName() string ``` ```go func (f *StackFrame) Write(b *bytes.Buffer) ``` ```go func (f *StackFrame) WriteToValueBuilder(b *StringBuilder) ``` -------------------------------- ### Initialize a new Goja Runtime Source: https://pkg.go.dev/github.com/dop251/goja Creates a new JavaScript runtime instance. Runtimes are isolated and cannot share values. ```go func New() *Runtime ``` -------------------------------- ### CaseStatement Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a `case` clause within a `switch` statement. Provides methods to get the start and end indices. ```APIDOC ## CaseStatement Node ### Description Represents a case clause within a switch statement. ### Methods - `Idx0() file.Idx`: Returns the starting index of the case statement. - `Idx1() file.Idx`: Returns the ending index of the case statement. ``` -------------------------------- ### Import Goja Parser Package Source: https://pkg.go.dev/github.com/dop251/goja/parser Import the necessary parser package from Goja. ```go import ( "github.com/dop251/goja/parser" ) ``` -------------------------------- ### BranchStatement Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a branching statement like `break` or `continue`. Provides methods to get the start and end indices. ```APIDOC ## BranchStatement Node ### Description Represents a branching statement. ### Methods - `Idx0() file.Idx`: Returns the starting index of the branch statement. - `Idx1() file.Idx`: Returns the ending index of the branch statement. ``` -------------------------------- ### BlockStatement Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a block of statements enclosed in curly braces. Provides methods to get the start and end indices. ```APIDOC ## BlockStatement Node ### Description Represents a block of statements. ### Methods - `Idx0() file.Idx`: Returns the starting index of the block statement. - `Idx1() file.Idx`: Returns the ending index of the block statement. ``` -------------------------------- ### ArrayPattern Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents an array pattern used in destructuring assignments. Provides methods to get the start and end indices. ```APIDOC ## ArrayPattern Node ### Description Represents an array pattern used in destructuring assignments. ### Methods - `Idx0() file.Idx`: Returns the starting index of the array pattern. - `Idx1() file.Idx`: Returns the ending index of the array pattern. ``` -------------------------------- ### ForDeclaration Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents the declaration part of a `for` loop (e.g., `let i = 0`). Provides methods to get the start and end indices. ```APIDOC ## ForDeclaration Node ### Description Represents the declaration part of a for loop. ### Methods - `Idx0() file.Idx`: Returns the starting index of the for declaration. - `Idx1() file.Idx`: Returns the ending index of the for declaration. ``` -------------------------------- ### Create a Dynamic Object Source: https://pkg.go.dev/github.com/dop251/goja Creates an Object backed by a DynamicObject handler. Properties are always writable, enumerable, and configurable. ```go func (r *Runtime) NewDynamicObject(d DynamicObject) *Object ``` -------------------------------- ### DotExpression Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents an expression using dot notation (e.g., `obj.prop`). Provides methods to get the start and end indices. ```APIDOC ## DotExpression Node ### Description Represents an expression using dot notation. ### Methods - `Idx0() file.Idx`: Returns the starting index of the dot expression. - `Idx1() file.Idx`: Returns the ending index of the dot expression. ``` -------------------------------- ### Convert String to Standard Go String Source: https://pkg.go.dev/github.com/dop251/goja/unistring Returns the String's value as a standard Go string. ```go func (s String) String() string ``` -------------------------------- ### CatchStatement Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a `catch` clause in a `try...catch` statement. Provides methods to get the start and end indices. ```APIDOC ## CatchStatement Node ### Description Represents a catch clause in a try...catch statement. ### Methods - `Idx0() file.Idx`: Returns the starting index of the catch statement. - `Idx1() file.Idx`: Returns the ending index of the catch statement. ``` -------------------------------- ### ArrayLiteral Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents an array literal in the AST. Provides methods to get the start and end indices of the literal in the source code. ```APIDOC ## ArrayLiteral Node ### Description Represents an array literal in the AST. ### Methods - `Idx0() file.Idx`: Returns the starting index of the array literal. - `Idx1() file.Idx`: Returns the ending index of the array literal. ``` -------------------------------- ### ForInStatement Idx0 Method Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the file index for the ForInStatement. ```go func (self *ForInStatement) Idx0() file.Idx ``` -------------------------------- ### ForInStatement Idx1 Method Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the file index for the ForInStatement. ```go func (self *ForInStatement) Idx1() file.Idx ``` -------------------------------- ### Goja Runtime Initialization and Basic Operations Source: https://pkg.go.dev/github.com/dop251/goja This section covers the initialization of the Goja runtime and basic utility functions for checking JavaScript value types. ```APIDOC ## Goja Runtime API ### Initialization * **func New() *Runtime** * Creates and returns a new Goja runtime instance. ### Value Type Checks * **func IsBigInt(v Value) bool** * Checks if the given `Value` is a BigInt. * **func IsInfinity(v Value) bool** * Checks if the given `Value` is an Infinity. * **func IsNaN(v Value) bool** * Checks if the given `Value` is NaN. * **func IsNull(v Value) bool** * Checks if the given `Value` is null. * **func IsNumber(v Value) bool** * Checks if the given `Value` is a number. * **func IsString(v Value) bool** * Checks if the given `Value` is a string. * **func IsUndefined(v Value) bool** * Checks if the given `Value` is undefined. ``` -------------------------------- ### ConditionalExpression Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a conditional (ternary) expression (e.g., `condition ? expr1 : expr2`). Provides methods to get the start and end indices. ```APIDOC ## ConditionalExpression Node ### Description Represents a conditional (ternary) expression. ### Methods - `Idx0() file.Idx`: Returns the starting index of the conditional expression. - `Idx1() file.Idx`: Returns the ending index of the conditional expression. ``` -------------------------------- ### BracketExpression Node Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents an expression using bracket notation (e.g., `obj[key]`). Provides methods to get the start and end indices. ```APIDOC ## BracketExpression Node ### Description Represents an expression using bracket notation. ### Methods - `Idx0() file.Idx`: Returns the starting index of the bracket expression. - `Idx1() file.Idx`: Returns the ending index of the bracket expression. ``` -------------------------------- ### EmptyStatement Idx1 Method Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the file index for the EmptyStatement. ```go func (self *EmptyStatement) Idx1() file.Idx ``` -------------------------------- ### EmptyStatement Idx0 Method Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the file index for the EmptyStatement. ```go func (self *EmptyStatement) Idx0() file.Idx ``` -------------------------------- ### Create String from Rune Slice Source: https://pkg.go.dev/github.com/dop251/goja/unistring Creates a String from a slice of runes. ```go func NewFromRunes(s []rune) String ``` -------------------------------- ### Create a new JavaScript object Source: https://pkg.go.dev/github.com/dop251/goja Instantiates an object with a specified prototype, mirroring the behavior of Object.create(). ```go func (r *Runtime) CreateObject(proto *Object) *Object ``` -------------------------------- ### Function and Constructor Handling Source: https://pkg.go.dev/github.com/dop251/goja APIs for working with JavaScript functions and constructors, including assertions and function calls. ```APIDOC ## Function and Constructor Handling ### Function Assertions * **func AssertFunction(v Value) (Callable, bool)** * Asserts if a `Value` is a function. Returns the `Callable` interface and `true` if it is, otherwise `nil` and `false`. ### Constructor Assertions * **func AssertConstructor(v Value) (Constructor, bool)** * Asserts if a `Value` is a constructor. Returns the `Constructor` interface and `true` if it is, otherwise `nil` and `false`. ### Function Calls * **type FunctionCall** * Represents a call to a JavaScript function. * **func (f FunctionCall) Argument(idx int) Value** * Retrieves the argument at the specified index. ### Constructor Calls * **type ConstructorCall** * Represents a call to a JavaScript constructor. * **func (f ConstructorCall) Argument(idx int) Value** * Retrieves the argument at the specified index. ``` -------------------------------- ### Retrieve File by Index Source: https://pkg.go.dev/github.com/dop251/goja/file Retrieves a File from the FileSet using its index. ```go func (self *FileSet) File(idx Idx) *File ``` -------------------------------- ### Use Native Constructor in JavaScript Source: https://pkg.go.dev/github.com/dop251/goja Instantiate and use a Go-defined native constructor within JavaScript. Both `new` and direct calls (without `new`) are supported, with `instanceof` checks returning true. ```javascript var o = new MyObject(arg); var o1 = MyObject(arg); // same thing o instanceof MyObject && o1 instanceof MyObject; // true ``` -------------------------------- ### Create New Object with Constructor Source: https://pkg.go.dev/github.com/dop251/goja The New method is a Go equivalent of the JavaScript `new` operator. It allows you to instantiate a JavaScript object by calling a constructor function with provided arguments directly from Go code. ```APIDOC ## func (*Runtime) New ### Description Creates a new JavaScript object by calling a constructor function. Equivalent to the `new` operator in JavaScript. ### Method func (r *Runtime) New(construct Value, args ...Value) (o *Object, err error) ### Parameters #### Path Parameters - **construct** (Value) - Required - The JavaScript constructor function (as a Value). - **args** (...Value) - Optional - Arguments to pass to the constructor. ### Request Example ```go // Assuming 'r' is a *Runtime and 'MyClassConstructor' is a Value representing a JS constructor // Example with no arguments obj1, err := r.New(MyClassConstructor) if err != nil { // Handle error } // Example with arguments arg1 := r.ToValue("hello") arg2 := r.ToValue(123) obj2, err := r.New(MyClassConstructor, arg1, arg2) if err != nil { // Handle error } ``` ### Response #### Success Response (Object, error) - **o** (*Object) - A pointer to the newly created JavaScript object. - **err** (error) - An error if the object creation failed. #### Response Example ```json // If successful, 'o' will be a pointer to the created object. // If an error occurred, 'err' will contain the error details. ``` ``` -------------------------------- ### ExpressionStatement Idx1 Method Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the file index for the ExpressionStatement. ```go func (self *ExpressionStatement) Idx1() file.Idx ``` -------------------------------- ### Define Native Constructor in Go Source: https://pkg.go.dev/github.com/dop251/goja Implement a native JavaScript constructor in Go. Use `call.This` for the new object and `call.Arguments` for passed arguments. Returning `nil` uses the default object creation. ```go 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) ``` -------------------------------- ### Get Object Class Name Source: https://pkg.go.dev/github.com/dop251/goja Returns the class name of the object. ```go func (o *Object) ClassName() string ``` -------------------------------- ### ExpressionStatement Idx0 Method Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the file index for the ExpressionStatement. ```go func (self *ExpressionStatement) Idx0() file.Idx ``` -------------------------------- ### Get argument from ConstructorCall Source: https://pkg.go.dev/github.com/dop251/goja Retrieves an argument by index from a constructor call. ```go func (f ConstructorCall) Argument(idx int) Value ``` -------------------------------- ### ClassLiteral Idx1 Method Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the file index for the ClassLiteral. ```go func (self *ClassLiteral) Idx1() file.Idx ``` -------------------------------- ### Create a New Promise Source: https://pkg.go.dev/github.com/dop251/goja Creates a Promise and its resolution functions. Requires an event loop as the returned functions are not goroutine-safe. ```go func (r *Runtime) NewPromise() (promise *Promise, resolve, reject func(reason interface{}) error) ``` ```go 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 err := resolve(result) // Handle uncatchable errors (e.g. by stopping the loop, panicking or setting a flag) }) }() } ``` -------------------------------- ### Define a File Structure Source: https://pkg.go.dev/github.com/dop251/goja/file Defines the structure for a source file, used by the AST and parser. ```go type File struct { } ``` -------------------------------- ### Runtime Methods Source: https://pkg.go.dev/github.com/dop251/goja This section details the various methods available on the Goja Runtime object for interacting with JavaScript environments. ```APIDOC ## Runtime Methods ### ForOf Iterates over an iterable JavaScript object. ### Method func ### Parameters - **iterable** (Value) - The iterable JavaScript object. - **step** (func(curValue Value) (continueIteration bool)) - A callback function executed for each element. ### Get Retrieves the value of a global JavaScript variable. ### Method func ### Parameters - **name** (string) - The name of the variable. ### GlobalObject Returns the global object of the runtime. ### Method func ### InstanceOf Checks if a JavaScript value is an instance of a given constructor. ### Method func ### Parameters - **left** (Value) - The JavaScript value to check. - **right** (*Object) - The constructor object. ### Interrupt Interrupts the current JavaScript execution. ### Method func ### Parameters - **v** (interface{}) - The value to return upon interruption. ### New Creates a new JavaScript object using a constructor and arguments. ### Method func ### Parameters - **construct** (Value) - The constructor function. - **args** (...Value) - Arguments to pass to the constructor. ### NewArray Creates a new JavaScript array. ### Method func ### Parameters - **items** (...interface{}) - Elements to include in the array. ### NewArrayBuffer Creates a new JavaScript ArrayBuffer from a byte slice. ### Method func ### Parameters - **data** ([]byte) - The byte data for the buffer. ### NewDynamicArray Creates a new JavaScript array from a dynamic Go array. ### Method func ### Parameters - **a** (DynamicArray) - The dynamic Go array. ### NewDynamicObject Creates a new JavaScript object from a dynamic Go object. ### Method func ### Parameters - **d** (DynamicObject) - The dynamic Go object. ### NewGoError Creates a new JavaScript object representing a Go error. ### Method func ### Parameters - **err** (error) - The Go error to convert. ### NewObject Creates a new empty JavaScript object. ### Method func ### NewPromise Creates a new JavaScript Promise and its resolve/reject functions. ### Method func ### Returns - **promise** (*Promise) - The created Promise. - **resolve** (func(reason interface{}) error) - The function to resolve the promise. - **reject** (func(reason interface{}) error) - The function to reject the promise. ### NewProxy Creates a new JavaScript Proxy object. ### Method func ### Parameters - **target** (*Object) - The target object for the proxy. - **nativeHandler** (*ProxyTrapConfig) - The handler object for the proxy traps. ### NewTypeError Creates a new JavaScript TypeError object. ### Method func ### Parameters - **args** (...interface{}) - Arguments to include in the error message. ### RunProgram Executes a compiled JavaScript program. ### Method func ### Parameters - **p** (*Program) - The compiled JavaScript program. ### RunScript Executes a JavaScript script from a string. ### Method func ### Parameters - **name** (string) - The name of the script. - **src** (string) - The source code of the script. ### RunString Executes a JavaScript string. ### Method func ### Parameters - **str** (string) - The JavaScript code to execute. ### Set Sets the value of a global JavaScript variable. ### Method func ### Parameters - **name** (string) - The name of the variable. - **value** (interface{}) - The value to set. ### SetAsyncContextTracker Sets a tracker for asynchronous context. ### Method func ### Parameters - **tracker** (AsyncContextTracker) - The tracker to set. ### SetFieldNameMapper Sets a mapper for field names. ### Method func ### Parameters - **mapper** (FieldNameMapper) - The mapper to set. ### SetGlobalObject Sets the global object for the runtime. ### Method func ### Parameters - **object** (*Object) - The global object to set. ### SetMaxCallStackSize Sets the maximum call stack size for the runtime. ### Method func ### Parameters - **size** (int) - The maximum call stack size. ### SetParserOptions Sets parser options for the runtime. ### Method func ### Parameters - **opts** (...parser.Option) - The parser options. ### SetPromiseRejectionTracker Sets a tracker for promise rejections. ### Method func ### Parameters - **tracker** (PromiseRejectionTracker) - The tracker to set. ### SetRandSource Sets the random number source for the runtime. ### Method func ### Parameters - **source** (RandSource) - The random number source. ### SetTimeSource Sets the time source for the runtime. ### Method func ### Parameters - **now** (Now) - The time source. ### ToValue Converts a Go value to a JavaScript Value. ### Method func ### Parameters - **i** (interface{}) - The Go value to convert. ### Try Executes a function and catches any exceptions. ### Method func ### Parameters - **f** (func()) - The function to execute. ### Returns - **exception** (*Exception) - The caught exception, if any. ``` -------------------------------- ### ClassLiteral Idx0 Method Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the file index for the ClassLiteral. ```go func (self *ClassLiteral) Idx0() file.Idx ``` -------------------------------- ### ExpressionBody Idx0 Method Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the file index for the ExpressionBody. ```go func (self *ExpressionBody) Idx0() file.Idx ``` -------------------------------- ### Get Length of ErrorList Source: https://pkg.go.dev/github.com/dop251/goja/parser Return the number of errors in the `ErrorList` using the `Len` method. ```go func (self ErrorList) Len() int ``` -------------------------------- ### DoWhileStatement Struct Source: https://pkg.go.dev/github.com/dop251/goja/ast Represents a do-while statement in the AST, including the test condition and the body. ```go type DoWhileStatement struct { Do file.Idx Test Expression Body Statement RightParenthesis file.Idx } ``` -------------------------------- ### Get Error Equivalent for ErrorList Source: https://pkg.go.dev/github.com/dop251/goja/parser Return an `error` equivalent to the `ErrorList`. If the list is empty, `Err()` returns `nil`. ```go func (self ErrorList) Err() error ``` -------------------------------- ### CatchStatement Idx1 Method Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the file index for the CatchStatement. ```go func (self *CatchStatement) Idx1() file.Idx ``` -------------------------------- ### ExpressionBody Idx1 Method Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the file index for the ExpressionBody. ```go func (self *ExpressionBody) Idx1() file.Idx ``` -------------------------------- ### Get Global Variable Source: https://pkg.go.dev/github.com/dop251/goja The Get method retrieves the value of a specified variable from the global JavaScript context. It behaves like accessing a variable by name in non-strict mode. If the variable is not defined, it returns nil. This method differs from GlobalObject().Get() as it prioritizes global lexical bindings (let or const). It will panic with an *Exception if a JavaScript exception occurs during the process; use Runtime.Try to handle these exceptions. ```APIDOC ## func (*Runtime) Get ### Description Retrieves a variable from the global JavaScript context by name. Returns nil if undefined. Prioritizes global lexical bindings over properties of the global object. Panics on JavaScript exceptions. ### Method func (r *Runtime) Get(name string) Value ### Parameters #### Path Parameters - **name** (string) - Required - The name of the global variable to retrieve. ### Request Example ```go // Assuming 'r' is a *Runtime variableValue := r.Get("myGlobalVar") if variableValue == nil { // Variable not defined } ``` ### Response #### Success Response (Value) - **Value** - The JavaScript value of the variable, or nil if not defined. #### Response Example ```json // If myGlobalVar is 'hello', the Value might represent the string 'hello' // If myGlobalVar is undefined, the Value will be nil ``` ``` -------------------------------- ### FieldDefinition Idx0 Method Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the file index for the FieldDefinition. ```go func (self *FieldDefinition) Idx0() file.Idx ``` -------------------------------- ### Get Index 1 from WithStatement - Goja AST Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the index 1 from a WithStatement in the goja AST. This is part of the AST node definition. ```go func (self *WithStatement) Idx1() file.Idx ``` -------------------------------- ### Set Source Map Consumer Source: https://pkg.go.dev/github.com/dop251/goja/file Associates a sourcemap consumer with the file. ```go func (fl *File) SetSourceMap(m *sourcemap.Consumer) ``` -------------------------------- ### DotExpression Idx0 Method Source: https://pkg.go.dev/github.com/dop251/goja/ast Retrieves the file index for the DotExpression. ```go func (self *DotExpression) Idx0() file.Idx ``` -------------------------------- ### Node Interface Source: https://pkg.go.dev/github.com/dop251/goja/ast The base interface implemented by all AST nodes, providing methods to retrieve the start and end indices of the node in the source file. ```APIDOC ## Node Interface ### Description The Node interface is the fundamental building block for all AST elements in Goja. ### Methods - **Idx0()** (file.Idx) - Returns the index of the first character belonging to the node. - **Idx1()** (file.Idx) - Returns the index of the first character immediately after the node. ``` -------------------------------- ### Add File to FileSet Source: https://pkg.go.dev/github.com/dop251/goja/file Adds a new file with the given filename and source code to the FileSet. This is an internal method but exported for cross-package use. ```go func (self *FileSet) AddFile(filename, src string) int ``` -------------------------------- ### Get Global Object Source: https://pkg.go.dev/github.com/dop251/goja The GlobalObject method returns the global object of the JavaScript runtime. This object contains all global properties and functions available in the JavaScript environment. ```APIDOC ## func (*Runtime) GlobalObject ### Description Returns the global object of the JavaScript runtime. ### Method func (r *Runtime) GlobalObject() *Object ### Response #### Success Response (Object) - **Object** - A pointer to the global JavaScript object. ### Response Example ```go // Assuming 'r' is a *Runtime global := r.GlobalObject() // You can now interact with the global object, e.g., global.Get("console") ``` ``` -------------------------------- ### Global Variable and Context Management Source: https://pkg.go.dev/github.com/dop251/goja Methods for setting and managing global variables and execution context. ```APIDOC ## func (*Runtime) Set ### Description Sets a 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. ### Method func (*Runtime) Set(name string, value interface{}) error ### Endpoint N/A (Method within Runtime) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ``` // Example (Lexical) vm.Set("a", 1) val, _ := vm.RunString("a++") fmt.Println(val.String()) val, _ = vm.RunString("a") fmt.Println(val.String()) ``` ### Response #### Success Response (200) - **error** - An error if setting the variable failed. #### Response Example ``` Output: 1 ``` ``` ```APIDOC ## func (*Runtime) SetAsyncContextTracker ### Description Registers a handler that allows tracking of asynchronous execution contexts. Setting it to nil disables the functionality. This method (as Runtime in general) is not goroutine-safe. ### Method func (*Runtime) SetAsyncContextTracker(tracker AsyncContextTracker) ### Endpoint N/A (Method within Runtime) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response N/A ``` ```APIDOC ## func (*Runtime) SetFieldNameMapper ### Description 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. ### Method func (*Runtime) SetFieldNameMapper(mapper FieldNameMapper) ### Endpoint N/A (Method within Runtime) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response N/A ``` ```APIDOC ## func (*Runtime) SetGlobalObject ### Description Sets the global object to the given object. Note, any existing references to the previous global object will continue to reference that object. ### Method func (*Runtime) SetGlobalObject(object *Object) ### Endpoint N/A (Method within Runtime) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response N/A ```