Documentation
¶
Overview ¶
Package quickjs Go bindings to QuickJS: a fast, small, and embeddable ES2020 JavaScript interpreter
Example ¶
package main
import (
"fmt"
"github.com/buke/quickjs-go"
)
// User represents a common user struct for demonstrating Marshal and Class features
type User struct {
ID int64 `js:"id"`
Name string `js:"name"`
Email string `js:"email"`
Age int `js:"age"`
IsActive bool `js:"is_active"`
Scores []float32 `js:"scores"` // Demonstrates TypedArray support
}
// GetFullInfo returns the user's full information
func (u *User) GetFullInfo() string {
return fmt.Sprintf("%s (%s) - Age: %d", u.Name, u.Email, u.Age)
}
// GetAverageScore calculates the average score
func (u *User) GetAverageScore() float64 {
if len(u.Scores) == 0 {
return 0
}
var sum float32
for _, score := range u.Scores {
sum += score
}
return float64(sum) / float64(len(u.Scores))
}
func main() {
// Create a new runtime
rt := quickjs.NewRuntime()
defer rt.Close()
// Create a new context
ctx := rt.NewContext()
defer ctx.Close()
// Create a new object
test := ctx.Object()
defer test.Free()
// bind properties to the object
test.Set("A", test.Context().String("String A"))
test.Set("B", ctx.Int32(0))
test.Set("C", ctx.Bool(false))
// bind go function to js object
test.Set("hello", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
return ctx.String("Hello " + args[0].String())
}))
// bind "test" object to global object
ctx.Globals().Set("test", test)
// call js function by js
js_ret, _ := ctx.Eval(`test.hello("Javascript!")`)
defer js_ret.Free()
fmt.Println(js_ret.String())
// call js function by go
go_ret := ctx.Globals().Get("test").Call("hello", ctx.String("Golang!"))
defer go_ret.Free()
fmt.Println(go_ret.String())
// bind go function to Javascript async function using Function + Promise
ctx.Globals().Set("testAsync", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
return ctx.Promise(func(resolve, reject func(quickjs.Value)) {
resolve(ctx.String("Hello Async Function!"))
})
}))
ret, _ := ctx.Eval(`
var ret;
testAsync().then(v => ret = v)
`)
defer ret.Free()
// wait for promise resolve
ctx.Loop()
asyncRet, _ := ctx.Eval("ret")
defer asyncRet.Free()
fmt.Println(asyncRet.String())
// Demonstrate TypedArray functionality
floatData := []float32{95.5, 87.2, 92.0}
typedArray := ctx.Float32Array(floatData)
ctx.Globals().Set("floatData", typedArray)
arrayResult, _ := ctx.Eval(`floatData instanceof Float32Array`)
defer arrayResult.Free()
fmt.Println("TypedArray:", arrayResult.Bool())
// Demonstrate Marshal/Unmarshal functionality with User struct
user := User{
ID: 123,
Name: "Alice",
Email: "alice@example.com",
Age: 25,
IsActive: true,
Scores: []float32{95.5, 87.2, 92.0},
}
jsVal, _ := ctx.Marshal(user)
ctx.Globals().Set("userData", jsVal)
marshalResult, _ := ctx.Eval(`userData.name + " avg: " + (userData.scores.reduce((s,v) => s+v) / userData.scores.length).toFixed(1)`)
defer marshalResult.Free()
fmt.Println("Marshal:", marshalResult.String())
// Demonstrate Class Binding functionality with the same User struct
userConstructor, _, _ := ctx.BindClass(&User{})
ctx.Globals().Set("User", userConstructor)
classResult, _ := ctx.Eval(`
const user = new User({
id: 456,
name: "Bob",
email: "bob@example.com",
age: 30,
is_active: true,
scores: [88.0, 92.5, 85.0]
});
user.GetAverageScore().toFixed(1)
`)
defer classResult.Free()
fmt.Println("Class binding:", classResult.String())
}
Output: Hello Javascript! Hello Golang! Hello Async Function! TypedArray: true Marshal: Alice avg: 91.6 Class binding: 88.5
Index ¶
- Constants
- type AccessorEntry
- type Atom
- type ClassBuilder
- func (cb *ClassBuilder) Accessor(name string, getter ClassGetterFunc, setter ClassSetterFunc) *ClassBuilder
- func (cb *ClassBuilder) Build(ctx *Context) (Value, uint32, error)
- func (cb *ClassBuilder) Constructor(fn ClassConstructorFunc) *ClassBuilder
- func (cb *ClassBuilder) Method(name string, fn ClassMethodFunc) *ClassBuilder
- func (cb *ClassBuilder) Property(name string, value Value, flags ...int) *ClassBuilder
- func (cb *ClassBuilder) StaticAccessor(name string, getter ClassGetterFunc, setter ClassSetterFunc) *ClassBuilder
- func (cb *ClassBuilder) StaticMethod(name string, fn ClassMethodFunc) *ClassBuilder
- func (cb *ClassBuilder) StaticProperty(name string, value Value, flags ...int) *ClassBuilder
- type ClassConstructorFunc
- type ClassFinalizer
- type ClassGetterFunc
- type ClassMethodFunc
- type ClassSetterFunc
- type Context
- func (ctx *Context) ArrayBuffer(binaryData []byte) Value
- func (ctx *Context) AsyncFunction(asyncFn func(ctx *Context, this Value, promise Value, args []Value) Value) Valuedeprecated
- func (ctx *Context) Atom(v string) Atom
- func (ctx *Context) AtomIdx(idx uint32) Atom
- func (ctx *Context) Await(v Value) (Value, error)
- func (ctx *Context) BigInt64(v int64) Value
- func (ctx *Context) BigInt64Array(data []int64) Value
- func (ctx *Context) BigUint64(v uint64) Value
- func (ctx *Context) BigUint64Array(data []uint64) Value
- func (ctx *Context) BindClass(structType interface{}, options ...ReflectOption) (Value, uint32, error)
- func (ctx *Context) BindClassBuilder(structType interface{}, options ...ReflectOption) (*ClassBuilder, error)
- func (ctx *Context) Bool(b bool) Value
- func (ctx *Context) Close()
- func (ctx *Context) Compile(code string, opts ...EvalOption) ([]byte, error)
- func (ctx *Context) CompileFile(filePath string, opts ...EvalOption) ([]byte, error)
- func (ctx *Context) CompileModule(filePath string, moduleName string, opts ...EvalOption) ([]byte, error)
- func (ctx *Context) Error(err error) Value
- func (ctx *Context) Eval(code string, opts ...EvalOption) (Value, error)
- func (ctx *Context) EvalBytecode(buf []byte) (Value, error)
- func (ctx *Context) EvalFile(filePath string, opts ...EvalOption) (Value, error)
- func (ctx *Context) Exception() error
- func (ctx *Context) Float32Array(data []float32) Value
- func (ctx *Context) Float64(v float64) Value
- func (ctx *Context) Float64Array(data []float64) Value
- func (ctx *Context) Function(fn func(*Context, Value, []Value) Value) Value
- func (ctx *Context) Globals() Value
- func (ctx *Context) HasException() bool
- func (ctx *Context) Int16Array(data []int16) Value
- func (ctx *Context) Int32(v int32) Value
- func (ctx *Context) Int32Array(data []int32) Value
- func (ctx *Context) Int64(v int64) Value
- func (ctx *Context) Int8Array(data []int8) Value
- func (ctx *Context) Invoke(fn Value, this Value, args ...Value) Value
- func (ctx *Context) LoadModule(code string, moduleName string, opts ...EvalOption) (Value, error)
- func (ctx *Context) LoadModuleBytecode(buf []byte, opts ...EvalOption) (Value, error)
- func (ctx *Context) LoadModuleFile(filePath string, moduleName string) (Value, error)
- func (ctx *Context) Loop()
- func (ctx *Context) Marshal(v interface{}) (Value, error)
- func (ctx *Context) Null() Value
- func (ctx *Context) Object() Value
- func (ctx *Context) ParseJSON(v string) Value
- func (ctx *Context) Promise(executor func(resolve, reject func(Value))) Value
- func (ctx *Context) Runtime() *Runtime
- func (ctx *Context) SetInterruptHandler(handler InterruptHandler)deprecated
- func (ctx *Context) String(v string) Value
- func (ctx *Context) Throw(v Value) Value
- func (ctx *Context) ThrowError(err error) Value
- func (ctx *Context) ThrowInternalError(format string, args ...interface{}) Value
- func (ctx *Context) ThrowRangeError(format string, args ...interface{}) Value
- func (ctx *Context) ThrowReferenceError(format string, args ...interface{}) Value
- func (ctx *Context) ThrowSyntaxError(format string, args ...interface{}) Value
- func (ctx *Context) ThrowTypeError(format string, args ...interface{}) Value
- func (ctx *Context) Uint16Array(data []uint16) Value
- func (ctx *Context) Uint32(v uint32) Value
- func (ctx *Context) Uint32Array(data []uint32) Value
- func (ctx *Context) Uint8Array(data []uint8) Value
- func (ctx *Context) Uint8ClampedArray(data []uint8) Value
- func (ctx *Context) Undefined() Value
- func (ctx *Context) Uninitialized() Value
- func (ctx *Context) Unmarshal(jsVal Value, v interface{}) error
- type Error
- type EvalOption
- func EvalAwait(await bool) EvalOption
- func EvalFileName(filename string) EvalOption
- func EvalFlagCompileOnly(compileOnly bool) EvalOption
- func EvalFlagGlobal(global bool) EvalOption
- func EvalFlagModule(module bool) EvalOption
- func EvalFlagStrict(strict bool) EvalOption
- func EvalLoadOnly(loadOnly bool) EvalOption
- type EvalOptions
- type FieldTagInfo
- type InterruptHandler
- type Marshaler
- type MethodEntry
- type Option
- func WithCanBlock(canBlock bool) Option
- func WithExecuteTimeout(timeout uint64) Option
- func WithGCThreshold(gcThreshold int64) Option
- func WithMaxStackSize(maxStackSize uint64) Option
- func WithMemoryLimit(memoryLimit uint64) Option
- func WithModuleImport(moduleImport bool) Option
- func WithStripInfo(strip int) Option
- type Options
- type PromiseState
- type PropertyEntry
- type ReflectOption
- type ReflectOptions
- type Runtime
- func (r *Runtime) ClearInterruptHandler()
- func (r *Runtime) Close()
- func (r *Runtime) NewContext() *Context
- func (r *Runtime) RunGC()
- func (r *Runtime) SetCanBlock(canBlock bool)
- func (r *Runtime) SetExecuteTimeout(timeout uint64)
- func (r *Runtime) SetGCThreshold(threshold int64)
- func (r *Runtime) SetInterruptHandler(handler InterruptHandler)
- func (r *Runtime) SetMaxStackSize(stack_size uint64)
- func (r *Runtime) SetMemoryLimit(limit uint64)
- func (r *Runtime) SetStripInfo(strip int)
- type Unmarshaler
- type Value
- func (v Value) Await() (Value, error)
- func (v Value) BigInt() *big.Intdeprecated
- func (v Value) Bool() booldeprecated
- func (v Value) ByteLen() int64
- func (v Value) Call(fname string, args ...Value) Value
- func (v Value) CallConstructor(args ...Value) Value
- func (v Value) Context() *Context
- func (v Value) Delete(name string) bool
- func (v Value) DeleteIdx(idx uint32) bool
- func (v Value) Error() errordeprecated
- func (v Value) Execute(this Value, args ...Value) Value
- func (v Value) Float64() float64deprecated
- func (v Value) Free()
- func (v Value) Get(name string) Value
- func (v Value) GetClassID() uint32
- func (v Value) GetGoObject() (interface{}, error)
- func (v Value) GetIdx(idx int64) Value
- func (v Value) GlobalInstanceof(name string) bool
- func (v Value) Has(name string) bool
- func (v Value) HasIdx(idx uint32) bool
- func (v Value) HasInstanceData() bool
- func (v Value) Int32() int32deprecated
- func (v Value) Int64() int64deprecated
- func (v Value) IsArray() bool
- func (v Value) IsBigInt() bool
- func (v Value) IsBigInt64Array() bool
- func (v Value) IsBigUint64Array() bool
- func (v Value) IsBool() bool
- func (v Value) IsByteArray() bool
- func (v Value) IsClassInstance() bool
- func (v Value) IsConstructor() bool
- func (v Value) IsError() bool
- func (v Value) IsException() bool
- func (v Value) IsFloat32Array() bool
- func (v Value) IsFloat64Array() bool
- func (v Value) IsFunction() bool
- func (v Value) IsInstanceOfClassID(expectedClassID uint32) bool
- func (v Value) IsInstanceOfConstructor(constructor Value) bool
- func (v Value) IsInt16Array() bool
- func (v Value) IsInt32Array() bool
- func (v Value) IsInt8Array() bool
- func (v Value) IsNull() bool
- func (v Value) IsNumber() bool
- func (v Value) IsObject() bool
- func (v Value) IsPromise() bool
- func (v Value) IsString() bool
- func (v Value) IsSymbol() bool
- func (v Value) IsTypedArray() bool
- func (v Value) IsUint16Array() bool
- func (v Value) IsUint32Array() bool
- func (v Value) IsUint8Array() bool
- func (v Value) IsUint8ClampedArray() bool
- func (v Value) IsUndefined() bool
- func (v Value) IsUninitialized() bool
- func (v Value) JSONStringify() string
- func (v Value) Len() int64
- func (v Value) New(args ...Value) Value
- func (v Value) PromiseState() PromiseState
- func (v Value) PropertyNames() ([]string, error)
- func (v Value) Set(name string, val Value)
- func (v Value) SetIdx(idx int64, val Value)
- func (v Value) String() string
- func (v Value) ToBigInt() *big.Int
- func (v Value) ToBigInt64Array() ([]int64, error)
- func (v Value) ToBigUint64Array() ([]uint64, error)
- func (v Value) ToBool() bool
- func (v Value) ToByteArray(size uint) ([]byte, error)
- func (v Value) ToError() error
- func (v Value) ToFloat32Array() ([]float32, error)
- func (v Value) ToFloat64() float64
- func (v Value) ToFloat64Array() ([]float64, error)
- func (v Value) ToInt16Array() ([]int16, error)
- func (v Value) ToInt32() int32
- func (v Value) ToInt32Array() ([]int32, error)
- func (v Value) ToInt64() int64
- func (v Value) ToInt8Array() ([]int8, error)
- func (v Value) ToString() string
- func (v Value) ToUint16Array() ([]uint16, error)
- func (v Value) ToUint32() uint32
- func (v Value) ToUint32Array() ([]uint32, error)
- func (v Value) ToUint8Array() ([]uint8, error)
- func (v Value) Uint32() uint32deprecated
Examples ¶
Constants ¶
const ( PropertyConfigurable = 1 << 0 // JS_PROP_CONFIGURABLE PropertyWritable = 1 << 1 // JS_PROP_WRITABLE PropertyEnumerable = 1 << 2 // JS_PROP_ENUMERABLE // Default property flags (writable, enumerable, configurable) PropertyDefault = PropertyConfigurable | PropertyWritable | PropertyEnumerable )
Property flags constants matching QuickJS - unchanged
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AccessorEntry ¶ added in v0.5.7
type AccessorEntry struct {
Name string // Accessor name in JavaScript
Getter ClassGetterFunc // Optional getter function
Setter ClassSetterFunc // Optional setter function
Static bool // true for static accessors, false for instance accessors
}
AccessorEntry represents an accessor binding configuration - unchanged
type Atom ¶
type Atom struct {
// contains filtered or unexported fields
}
Atom represents a QuickJS atom - unique strings used for object property names. Object property names and some strings are stored as Atoms (unique strings) to save memory and allow fast comparison. Atoms are represented as a 32 bit integer. Half of the atom range is reserved for immediate integer literals from 0 to 2^{31}-1.
type ClassBuilder ¶ added in v0.5.6
type ClassBuilder struct {
// contains filtered or unexported fields
}
ClassBuilder provides a fluent API for building JavaScript classes Uses builder pattern for easy and readable class definition MODIFIED FOR SCHEME C: Now stores complete class definition including instance properties
func NewClassBuilder ¶ added in v0.5.6
func NewClassBuilder(name string) *ClassBuilder
NewClassBuilder creates a new ClassBuilder with the specified name This is the entry point for building JavaScript classes
func (*ClassBuilder) Accessor ¶ added in v0.5.7
func (cb *ClassBuilder) Accessor(name string, getter ClassGetterFunc, setter ClassSetterFunc) *ClassBuilder
Accessor adds a read-write accessor to the class instance - unchanged Pass nil for getter to create write-only accessor Pass nil for setter to create read-only accessor
func (*ClassBuilder) Build ¶ added in v0.5.6
func (cb *ClassBuilder) Build(ctx *Context) (Value, uint32, error)
Build creates and registers the JavaScript class in the given context Returns the constructor function and classID for NewInstance
func (*ClassBuilder) Constructor ¶ added in v0.5.6
func (cb *ClassBuilder) Constructor(fn ClassConstructorFunc) *ClassBuilder
Constructor sets the constructor function for the class MODIFIED FOR SCHEME C: Now uses new constructor signature The constructor function will be called with pre-created instance
func (*ClassBuilder) Method ¶ added in v0.5.6
func (cb *ClassBuilder) Method(name string, fn ClassMethodFunc) *ClassBuilder
Method adds an instance method to the class - unchanged Instance methods are called on object instances
func (*ClassBuilder) Property ¶ added in v0.5.6
func (cb *ClassBuilder) Property(name string, value Value, flags ...int) *ClassBuilder
Property adds a data property to the class instance - unchanged Default flags: writable, enumerable, configurable SCHEME C: Instance properties will be bound during instance creation
func (*ClassBuilder) StaticAccessor ¶ added in v0.5.7
func (cb *ClassBuilder) StaticAccessor(name string, getter ClassGetterFunc, setter ClassSetterFunc) *ClassBuilder
StaticAccessor adds a read-write static accessor to the class constructor - unchanged Pass nil for getter to create write-only accessor Pass nil for setter to create read-only accessor
func (*ClassBuilder) StaticMethod ¶ added in v0.5.6
func (cb *ClassBuilder) StaticMethod(name string, fn ClassMethodFunc) *ClassBuilder
StaticMethod adds a static method to the class - unchanged Static methods are called on the constructor function itself
func (*ClassBuilder) StaticProperty ¶ added in v0.5.6
func (cb *ClassBuilder) StaticProperty(name string, value Value, flags ...int) *ClassBuilder
StaticProperty adds a data property to the class constructor - unchanged Default flags: writable, enumerable, configurable
type ClassConstructorFunc ¶ added in v0.5.6
MODIFIED FOR SCHEME C: ClassConstructorFunc signature changed Constructor now receives pre-created instance and returns Go object to associate This aligns with Scheme C design where instances are pre-created with bound properties
type ClassFinalizer ¶ added in v0.5.6
type ClassFinalizer interface {
Finalize()
}
Optional cleanup interface for class instances Objects implementing this interface will have Finalize() called automatically when the JavaScript object is garbage collected
type ClassGetterFunc ¶ added in v0.5.6
ClassGetterFunc represents accessor getter functions - unchanged Corresponds to QuickJS JSCFunctionType.getter_magic
type ClassMethodFunc ¶ added in v0.5.6
ClassMethodFunc represents both instance and static methods - unchanged this parameter represents the object instance for instance methods, or the constructor function for static methods Corresponds to QuickJS JSCFunctionType.generic_magic
type ClassSetterFunc ¶ added in v0.5.6
ClassSetterFunc represents accessor setter functions - unchanged Returns the set value or an exception Corresponds to QuickJS JSCFunctionType.setter_magic
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context represents a Javascript context (or Realm). Each JSContext has its own global objects and system objects. There can be several JSContexts per JSRuntime and they can share objects, similar to frames of the same origin sharing Javascript objects in a web browser.
func (*Context) ArrayBuffer ¶ added in v0.1.13
ArrayBuffer returns a ArrayBuffer value with given binary data.
func (*Context) AsyncFunction
deprecated
added in
v0.1.2
func (ctx *Context) AsyncFunction(asyncFn func(ctx *Context, this Value, promise Value, args []Value) Value) Value
AsyncFunction returns a js async function value with given function template
Deprecated: Use Context.Function + Context.Promise instead for better memory management and thread safety. Example:
asyncFn := ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
return ctx.Promise(func(resolve, reject func(quickjs.Value)) {
// async work here
resolve(ctx.String("result"))
})
})
func (*Context) Await ¶ added in v0.4.8
Wait for a promise and execute pending jobs while waiting for it. Return the promise result or JS_EXCEPTION in case of promise rejection.
func (*Context) BigInt64Array ¶ added in v0.5.4
BigInt64Array returns a BigInt64Array value with given int64 slice.
func (*Context) BigUint64Array ¶ added in v0.5.4
BigUint64Array returns a BigUint64Array value with given uint64 slice.
func (*Context) BindClass ¶ added in v0.5.6
func (ctx *Context) BindClass(structType interface{}, options ...ReflectOption) (Value, uint32, error)
BindClass automatically creates and builds a JavaScript class from a Go struct type using reflection. This is a convenience method that combines BindClassBuilder and Build. Only exported fields and methods are bound to maintain Go encapsulation principles.
Example usage:
constructor, classID, err := ctx.BindClass(&MyStruct{})
if err != nil { return err }
ctx.Globals().Set("MyStruct", constructor)
func (*Context) BindClassBuilder ¶ added in v0.5.6
func (ctx *Context) BindClassBuilder(structType interface{}, options ...ReflectOption) (*ClassBuilder, error)
BindClassBuilder automatically creates a ClassBuilder from a Go struct type using reflection. Returns a ClassBuilder that can be further customized using chain methods before Build(). Only exported fields and methods are analyzed to maintain Go encapsulation principles.
Example usage:
builder, err := ctx.BindClassBuilder(&MyStruct{})
if err != nil { return err }
constructor, classID, err := builder.Build(ctx)
// Or with additional customization:
builder, err := ctx.BindClassBuilder(&MyStruct{})
if err != nil { return err }
constructor, classID, err := builder.
StaticMethod("Create", myCreateFunc).
ReadOnlyAccessor("version", myVersionGetter).
Build(ctx)
func (*Context) Close ¶
func (ctx *Context) Close()
Free will free context and all associated objects.
func (*Context) Compile ¶
func (ctx *Context) Compile(code string, opts ...EvalOption) ([]byte, error)
Compile returns a compiled bytecode with given code.
func (*Context) CompileFile ¶
func (ctx *Context) CompileFile(filePath string, opts ...EvalOption) ([]byte, error)
Compile returns a compiled bytecode with given filename.
func (*Context) CompileModule ¶ added in v0.4.14
func (ctx *Context) CompileModule(filePath string, moduleName string, opts ...EvalOption) ([]byte, error)
CompileModule returns a compiled bytecode with given code and module name.
func (*Context) Eval ¶
func (ctx *Context) Eval(code string, opts ...EvalOption) (Value, error)
Eval returns a js value with given code. Need call Free() `quickjs.Value`'s returned by `Eval()` and `EvalFile()` and `EvalBytecode()`. func (ctx *Context) Eval(code string) (Value, error) { return ctx.EvalFile(code, "code") }
func (*Context) EvalBytecode ¶
EvalBytecode returns a js value with given bytecode. Need call Free() `quickjs.Value`'s returned by `Eval()` and `EvalFile()` and `EvalBytecode()`.
func (*Context) EvalFile ¶
func (ctx *Context) EvalFile(filePath string, opts ...EvalOption) (Value, error)
EvalFile returns a js value with given code and filename. Need call Free() `quickjs.Value`'s returned by `Eval()` and `EvalFile()` and `EvalBytecode()`.
func (*Context) Float32Array ¶ added in v0.5.4
Float32Array returns a Float32Array value with given float32 slice.
func (*Context) Float64Array ¶ added in v0.5.4
Float64Array returns a Float64Array value with given float64 slice.
func (*Context) Function ¶
Function returns a js function value with given function template New implementation using HandleStore and JS_NewCFunction2 with magic parameter
func (*Context) HasException ¶ added in v0.5.3
HasException checks if the context has an exception set.
func (*Context) Int16Array ¶ added in v0.5.4
Int16Array returns a Int16Array value with given int16 slice.
func (*Context) Int32Array ¶ added in v0.5.4
Int32Array returns a Int32Array value with given int32 slice.
func (*Context) Int8Array ¶ added in v0.5.4
Int8Array returns a Int8Array value with given int8 slice.
func (*Context) Invoke ¶ added in v0.1.3
Invoke invokes a function with given this value and arguments. Deprecated: Use Value.Execute() instead for better API consistency.
func (*Context) LoadModule ¶ added in v0.4.10
LoadModule returns a js value with given code and module name.
func (*Context) LoadModuleBytecode ¶ added in v0.4.10
func (ctx *Context) LoadModuleBytecode(buf []byte, opts ...EvalOption) (Value, error)
LoadModuleByteCode returns a js value with given bytecode and module name.
func (*Context) LoadModuleFile ¶ added in v0.4.10
LoadModuleFile returns a js value with given file path and module name.
func (*Context) Loop ¶ added in v0.3.3
func (ctx *Context) Loop()
Loop runs the context's event loop.
func (*Context) Marshal ¶ added in v0.5.3
Marshal returns the JavaScript value encoding of v. It traverses the value v recursively and creates corresponding JavaScript values.
Marshal uses the following type mappings:
- bool -> JavaScript boolean
- int, int8, int16, int32 -> JavaScript number (32-bit)
- int64 -> JavaScript number (64-bit)
- uint, uint8, uint16, uint32 -> JavaScript number (32-bit unsigned)
- uint64 -> JavaScript BigInt
- float32, float64 -> JavaScript number
- string -> JavaScript string
- []byte -> JavaScript ArrayBuffer
- []int8 -> JavaScript Int8Array
- []int16 -> JavaScript Int16Array
- []uint16 -> JavaScript Uint16Array
- []int32 -> JavaScript Int32Array
- []uint32 -> JavaScript Uint32Array
- []float32 -> JavaScript Float32Array
- []float64 -> JavaScript Float64Array
- []int64 -> JavaScript BigInt64Array
- []uint64 -> JavaScript BigUint64Array
- slice/array -> JavaScript Array
- map -> JavaScript Object
- struct -> JavaScript Object
- pointer -> recursively marshal the pointed value (nil becomes null)
Struct fields are marshaled using their field names unless a tag is present. The "js" and "json" tags are supported. Fields with tag "-" are ignored.
Types implementing the Marshaler interface are marshaled using their MarshalJS method.
func (*Context) ParseJSON ¶ added in v0.1.11
ParseJson parses given json string and returns a object value.
func (*Context) Promise ¶ added in v0.5.5
Promise creates a new Promise with executor function Executor runs synchronously in current thread for thread safety
func (*Context) SetInterruptHandler
deprecated
added in
v0.1.14
func (ctx *Context) SetInterruptHandler(handler InterruptHandler)
SetInterruptHandler sets a interrupt handler.
Deprecated: Use SetInterruptHandler on runtime instead
func (*Context) ThrowError ¶
ThrowError returns a context's exception value with given error message.
func (*Context) ThrowInternalError ¶
ThrowInternalError returns a context's exception value with given error message.
func (*Context) ThrowRangeError ¶
ThrowRangeError returns a context's exception value with given error message.
func (*Context) ThrowReferenceError ¶
ThrowReferenceError returns a context's exception value with given error message.
func (*Context) ThrowSyntaxError ¶
ThrowSyntaxError returns a context's exception value with given error message.
func (*Context) ThrowTypeError ¶
ThrowTypeError returns a context's exception value with given error message.
func (*Context) Uint16Array ¶ added in v0.5.4
Uint16Array returns a Uint16Array value with given uint16 slice.
func (*Context) Uint32Array ¶ added in v0.5.4
Uint32Array returns a Uint32Array value with given uint32 slice.
func (*Context) Uint8Array ¶ added in v0.5.4
Uint8Array returns a Uint8Array value with given uint8 slice.
func (*Context) Uint8ClampedArray ¶ added in v0.5.4
Uint8ClampedArray returns a Uint8ClampedArray value with given uint8 slice.
func (*Context) Uninitialized ¶
Uninitialized returns a uninitialized value.
func (*Context) Unmarshal ¶ added in v0.5.3
Unmarshal parses the JavaScript value and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an error.
Unmarshal uses the inverse of the encodings that Marshal uses, with the following additional rules:
- JavaScript null/undefined -> Go nil pointer or zero value
- JavaScript Array -> Go slice/array
- JavaScript Object -> Go map/struct
- JavaScript number -> Go numeric types (with appropriate conversion)
- JavaScript BigInt -> Go uint64/int64/*big.Int
- JavaScript ArrayBuffer -> Go []byte
- JavaScript Int8Array -> Go []int8
- JavaScript Int16Array -> Go []int16
- JavaScript Uint16Array -> Go []uint16
- JavaScript Int32Array -> Go []int32
- JavaScript Uint32Array -> Go []uint32
- JavaScript Float32Array -> Go []float32
- JavaScript Float64Array -> Go []float64
- JavaScript BigInt64Array -> Go []int64
- JavaScript BigUint64Array -> Go []uint64
When unmarshaling into an interface{}, Unmarshal stores one of:
- nil for JavaScript null/undefined
- bool for JavaScript boolean
- int64 for JavaScript integer numbers
- float64 for JavaScript floating-point numbers
- string for JavaScript string
- []interface{} for JavaScript Array
- map[string]interface{} for JavaScript Object
Types implementing the Unmarshaler interface are unmarshaled using their UnmarshalJS method.
type Error ¶
type Error struct {
Name string // Error name (e.g., "TypeError", "ReferenceError")
Message string // Error message
Cause string // Error cause
Stack string // Stack trace
JSONString string // Serialized JSON string
}
Error represents a JavaScript error with detailed information.
type EvalOption ¶ added in v0.4.10
type EvalOption func(*EvalOptions)
func EvalAwait ¶ added in v0.4.10
func EvalAwait(await bool) EvalOption
func EvalFileName ¶ added in v0.4.10
func EvalFileName(filename string) EvalOption
func EvalFlagCompileOnly ¶ added in v0.4.10
func EvalFlagCompileOnly(compileOnly bool) EvalOption
func EvalFlagGlobal ¶ added in v0.4.10
func EvalFlagGlobal(global bool) EvalOption
func EvalFlagModule ¶ added in v0.4.10
func EvalFlagModule(module bool) EvalOption
func EvalFlagStrict ¶ added in v0.4.10
func EvalFlagStrict(strict bool) EvalOption
func EvalLoadOnly ¶ added in v0.5.3
func EvalLoadOnly(loadOnly bool) EvalOption
type EvalOptions ¶ added in v0.4.10
type EvalOptions struct {
// contains filtered or unexported fields
}
type FieldTagInfo ¶ added in v0.5.6
type FieldTagInfo struct {
Name string // JavaScript property name
Skip bool // Whether to skip this field
OmitEmpty bool // Whether to omit empty values (for serialization)
}
FieldTagInfo contains parsed field tag information
type InterruptHandler ¶ added in v0.1.14
type InterruptHandler func() int
InterruptHandler is a function type for interrupt handler. Return != 0 if the JS code needs to be interrupted
type Marshaler ¶ added in v0.5.3
Marshaler is the interface implemented by types that can marshal themselves into a JavaScript value.
type MethodEntry ¶ added in v0.5.6
type MethodEntry struct {
Name string // Method name in JavaScript
Func ClassMethodFunc // Method implementation function
Static bool // true for static methods, false for instance methods
Length int // Expected parameter count, 0 for default
}
MethodEntry represents a method binding configuration - unchanged
type Option ¶ added in v0.4.7
type Option func(*Options)
func WithCanBlock ¶ added in v0.4.7
WithCanBlock will set the runtime's can block; default is true
func WithExecuteTimeout ¶ added in v0.4.7
WithExecuteTimeout will set the runtime's execute timeout; default is 0
func WithGCThreshold ¶ added in v0.4.7
WithGCThreshold will set the runtime's GC threshold; default is -1 to disable automatic GC.
func WithMaxStackSize ¶ added in v0.4.7
WithMaxStackSize will set max runtime's stack size; default is 0 disable maximum stack size check
func WithMemoryLimit ¶ added in v0.4.7
WithMemoryLimit will set the runtime memory limit; if not set, it will be unlimit.
func WithModuleImport ¶ added in v0.4.10
func WithStripInfo ¶ added in v0.5.0
type PromiseState ¶ added in v0.5.5
type PromiseState int
Promise state enumeration matching QuickJS
const ( PromisePending PromiseState = iota PromiseFulfilled PromiseRejected )
type PropertyEntry ¶ added in v0.5.6
type PropertyEntry struct {
Name string // Property name in JavaScript
Value Value // Property value (JavaScript Value)
Static bool // true for static properties, false for instance properties
Flags int // Property flags (writable, enumerable, configurable)
}
PropertyEntry represents a property binding configuration - unchanged
type ReflectOption ¶ added in v0.5.6
type ReflectOption func(*ReflectOptions)
ReflectOption configures ReflectOptions using functional options pattern
func WithIgnoredFields ¶ added in v0.5.6
func WithIgnoredFields(fields ...string) ReflectOption
WithIgnoredFields specifies field names to skip during binding
func WithIgnoredMethods ¶ added in v0.5.6
func WithIgnoredMethods(methods ...string) ReflectOption
WithIgnoredMethods specifies method names to skip during binding
func WithMethodPrefix ¶ added in v0.5.6
func WithMethodPrefix(prefix string) ReflectOption
WithMethodPrefix filters methods by name prefix
type ReflectOptions ¶ added in v0.5.6
type ReflectOptions struct {
// MethodPrefix filters methods by prefix (empty = all methods)
MethodPrefix string
// IgnoredMethods lists method names to skip during binding
IgnoredMethods []string
// IgnoredFields lists field names to skip during binding
IgnoredFields []string
}
ReflectOptions configures automatic class binding behavior
type Runtime ¶
type Runtime struct {
// contains filtered or unexported fields
}
Runtime represents a Javascript runtime with simplified interrupt handling
func NewRuntime ¶
NewRuntime creates a new quickjs runtime with simplified interrupt handling.
func (*Runtime) ClearInterruptHandler ¶ added in v0.5.5
func (r *Runtime) ClearInterruptHandler()
ClearInterruptHandler clears the user interrupt handler
func (*Runtime) Close ¶
func (r *Runtime) Close()
Close will free the runtime pointer with proper cleanup.
func (*Runtime) NewContext ¶
NewContext creates a new JavaScript context.
func (*Runtime) SetCanBlock ¶ added in v0.4.7
SetCanBlock will set the runtime's can block; default is true
func (*Runtime) SetExecuteTimeout ¶ added in v0.4.7
SetExecuteTimeout will set the runtime's execute timeout; This will override any user interrupt handler (expected behavior)
func (*Runtime) SetGCThreshold ¶
SetGCThreshold the runtime's GC threshold; use -1 to disable automatic GC.
func (*Runtime) SetInterruptHandler ¶ added in v0.5.0
func (r *Runtime) SetInterruptHandler(handler InterruptHandler)
SetInterruptHandler sets a user interrupt handler using simplified approach. This will override any timeout handler (expected behavior)
func (*Runtime) SetMaxStackSize ¶
SetMaxStackSize will set max runtime's stack size;
func (*Runtime) SetMemoryLimit ¶
SetMemoryLimit the runtime memory limit; if not set, it will be unlimit.
func (*Runtime) SetStripInfo ¶ added in v0.5.0
type Unmarshaler ¶ added in v0.5.3
Unmarshaler is the interface implemented by types that can unmarshal a JavaScript value into themselves.
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value represents a Javascript value which can be a primitive type or an object. Reference counting is used, so it is important to explicitly duplicate (JS_DupValue(), increment the reference count) or free (JS_FreeValue(), decrement the reference count) JSValues.
func (Value) Await ¶ added in v0.5.5
Await waits for promise resolution and executes pending jobs Similar to Context.Await but called on Value directly
func (Value) CallConstructor ¶ added in v0.4.15
CallConstructor calls the constructor with the given arguments. SCHEME C: For class instances, use this method to create instances. The class constructor function will receive a pre-created instance and initialize it. Instance properties declared in ClassBuilder.Property() are automatically bound to the instance.
Example usage:
constructor := ctx.Eval("MyClass")
instance := constructor.CallConstructor(arg1, arg2)
This replaces the previous NewInstance method and provides automatic property binding and simplified constructor semantics where constructors work with pre-created instances.
func (Value) GetClassID ¶ added in v0.5.6
GetClassID returns the class ID of the value if it's a class instance Returns JS_INVALID_CLASS_ID (0) if not a class instance
func (Value) GetGoObject ¶ added in v0.5.6
GetGoObject retrieves Go object from JavaScript class instance This method extracts the opaque data stored by the constructor proxy
func (Value) GlobalInstanceof ¶ added in v0.5.0
GlobalInstanceof checks if the value is an instance of the given global constructor
func (Value) HasInstanceData ¶ added in v0.5.6
HasInstanceData checks if the value has associated Go object data This is the most reliable way to identify our class instances
func (Value) IsBigInt64Array ¶ added in v0.5.4
func (Value) IsBigUint64Array ¶ added in v0.5.4
func (Value) IsByteArray ¶ added in v0.1.13
IsByteArray returns true if the value is array buffer
func (Value) IsClassInstance ¶ added in v0.5.6
IsClassInstance checks if the value is an instance of any user-defined class This method uses opaque data validation for maximum reliability
func (Value) IsConstructor ¶ added in v0.4.15
func (Value) IsException ¶
func (Value) IsFloat32Array ¶ added in v0.5.4
func (Value) IsFloat64Array ¶ added in v0.5.4
func (Value) IsFunction ¶
func (Value) IsInstanceOfClassID ¶ added in v0.5.6
IsInstanceOfClassID checks if the value is an instance of a specific class ID This provides type-safe class instance checking with double validation
func (Value) IsInstanceOfConstructor ¶ added in v0.5.6
IsInstanceOfConstructor checks if the value is an instance of a specific constructor This uses JavaScript's instanceof operator semantics
func (Value) IsInt16Array ¶ added in v0.5.4
func (Value) IsInt32Array ¶ added in v0.5.4
func (Value) IsInt8Array ¶ added in v0.5.4
func (Value) IsTypedArray ¶ added in v0.5.4
TypedArray detection methods
func (Value) IsUint16Array ¶ added in v0.5.4
func (Value) IsUint32Array ¶ added in v0.5.4
func (Value) IsUint8Array ¶ added in v0.5.4
func (Value) IsUint8ClampedArray ¶ added in v0.5.4
func (Value) IsUndefined ¶
func (Value) IsUninitialized ¶
func (Value) JSONStringify ¶ added in v0.1.11
JSONStringify returns the JSON string representation of the value.
func (Value) PromiseState ¶ added in v0.5.5
func (v Value) PromiseState() PromiseState
PromiseState returns the state of the Promise
func (Value) PropertyNames ¶
PropertyNames returns the names of the properties of the value.
func (Value) String ¶
String returns the string representation of the value. This method implements the fmt.Stringer interface.
func (Value) ToBigInt64Array ¶ added in v0.5.4
ToBigInt64Array converts the value to int64 slice if it's a BigInt64Array.
func (Value) ToBigUint64Array ¶ added in v0.5.4
ToBigUint64Array converts the value to uint64 slice if it's a BigUint64Array.
func (Value) ToFloat32Array ¶ added in v0.5.4
ToFloat32Array converts the value to float32 slice if it's a Float32Array.
func (Value) ToFloat64Array ¶ added in v0.5.4
ToFloat64Array converts the value to float64 slice if it's a Float64Array.
func (Value) ToInt16Array ¶ added in v0.5.4
ToInt16Array converts the value to int16 slice if it's an Int16Array.
func (Value) ToInt32Array ¶ added in v0.5.4
ToInt32Array converts the value to int32 slice if it's an Int32Array.
func (Value) ToInt8Array ¶ added in v0.5.4
ToInt8Array converts the value to int8 slice if it's an Int8Array.
func (Value) ToUint16Array ¶ added in v0.5.4
ToUint16Array converts the value to uint16 slice if it's a Uint16Array.
func (Value) ToUint32Array ¶ added in v0.5.4
ToUint32Array converts the value to uint32 slice if it's a Uint32Array.
func (Value) ToUint8Array ¶ added in v0.5.4
ToUint8Array converts the value to uint8 slice if it's a Uint8Array or Uint8ClampedArray.