Repository navigation
Expand file tree
/
Copy pathjsfunc_goja.go
More file actions
84 lines (78 loc) · 1.72 KB
/
Copy pathjsfunc_goja.go
File metadata and controls
84 lines (78 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//go:build goja
package ramune
import (
"fmt"
"sync/atomic"
"github.com/dop251/goja"
)
// JSFunc wraps a goja function reference, allowing it to be called from Go.
type JSFunc struct {
noCopy noCopy
rt *Runtime
refName string // global name holding the JS function
closed atomic.Bool
}
// Call invokes the JavaScript function with the given arguments.
func (f *JSFunc) Call(args ...any) (any, error) {
if f == nil || f.closed.Load() {
return nil, ErrNilValue
}
var result any
var err error
f.rt.dispatch(func() {
v := f.rt.vm.Get(f.refName)
if v == nil {
err = &JSError{Context: "JSFunc.Call", Message: "function reference missing"}
return
}
fn, ok := goja.AssertFunction(v)
if !ok {
err = &JSError{Context: "JSFunc.Call", Message: "not a function"}
return
}
jsArgs := make([]goja.Value, len(args))
for i, arg := range args {
jv, e := f.rt.goToJS(arg)
if e != nil {
err = fmt.Errorf("ramune: JSFunc.Call arg %d: %w", i, e)
return
}
jsArgs[i] = jv
}
ret, e := fn(goja.Undefined(), jsArgs...)
if e != nil {
err = &JSError{Context: "JSFunc.Call", Message: e.Error()}
return
}
if ret == nil {
result = nil
return
}
exp := ret.Export()
// Normalize numbers to float64 for parity with JSC/QuickJS JSFunc.Call.
switch n := exp.(type) {
case int:
result = float64(n)
case int64:
result = float64(n)
case int32:
result = float64(n)
default:
result = exp
}
})
return result, err
}
// Close releases the JavaScript function reference.
func (f *JSFunc) Close() error {
if f == nil || f.closed.Swap(true) {
return nil
}
if f.rt.closed.Load() {
return nil
}
f.rt.dispatch(func() {
f.rt.vm.Set(f.refName, goja.Undefined())
})
return nil
}