-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime.go
More file actions
102 lines (86 loc) · 1.97 KB
/
Copy pathruntime.go
File metadata and controls
102 lines (86 loc) · 1.97 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package gowebi
import (
"context"
"fmt"
"log"
"github.com/dop251/goja"
)
var undefinedGojaFn = func(goja.FunctionCall) goja.Value {
return goja.Undefined()
}
var clg = func(args ...any) {
log.Println(append([]any{"[JS]:"}, args...)...)
}
type Runtime struct {
VM *goja.Runtime
Render goja.Callable
Meta goja.Callable
}
// runWithVM runs the loaded program in the provided vm.
// meta function is optional and can be nil.
//
// WARN: re-using existing vms can leak data across requests.
func runWithVM(vm *goja.Runtime, program *goja.Program) (*Runtime, error) {
_, err := vm.RunProgram(program)
if err != nil {
return nil, fmt.Errorf("failed to run program: %w", err)
}
render, ok := goja.AssertFunction(vm.Get("render"))
if !ok {
return nil, fmt.Errorf("failed to get the render function from vm")
}
meta, _ := goja.AssertFunction(vm.Get("meta"))
return &Runtime{
VM: vm,
Render: render,
Meta: meta,
}, nil
}
func newVM(suppressConsoleLogs bool) *goja.Runtime {
vm := goja.New()
vm.SetFieldNameMapper(goja.TagFieldNameMapper("json", true))
_, _ = vm.RunString(`
Object.freeze(Object);
Object.freeze(Object.prototype);
Object.freeze(Array.prototype);
Object.freeze(Function.prototype);
`)
vm.Set("setTimeout", undefinedGojaFn)
vm.Set("clearTimeout", undefinedGojaFn)
vm.Set("eval", undefinedGojaFn)
vm.Set("Function", undefinedGojaFn)
vm.Set("process", undefinedGojaFn)
if suppressConsoleLogs {
l := func(...any) {}
vm.Set("console", map[string]func(...any){
"log": l,
"error": l,
"warn": l,
})
} else {
vm.Set("console", map[string]func(...any){
"log": clg,
"error": clg,
"warn": clg,
})
}
return vm
}
func attachVMInterrupt(ctx context.Context, vm *goja.Runtime) func() {
var (
done = make(chan struct{})
exited = make(chan struct{})
)
go func() {
defer close(exited)
select {
case <-ctx.Done():
vm.Interrupt(ctx.Err())
case <-done:
}
}()
return func() {
close(done)
<-exited
}
}