-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibjs.go
77 lines (65 loc) · 1.97 KB
/
libjs.go
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
package frizzante
import (
"fmt"
"github.com/evanw/esbuild/pkg/api"
"rogchap.com/v8go"
)
type JavaScriptContext struct {
isolate *v8go.Isolate
global *v8go.ObjectTemplate
context *v8go.Context
}
func newJavaScriptContext(globals map[string]v8go.FunctionCallback) (*JavaScriptContext, error) {
isolate := v8go.NewIsolate()
global := v8go.NewObjectTemplate(isolate)
for key, callback := range globals {
template := v8go.NewFunctionTemplate(isolate, callback)
setError := global.Set(key, template)
if setError != nil {
return nil, setError
}
}
context := v8go.NewContext(isolate, global)
return &JavaScriptContext{
isolate: isolate,
global: global,
context: context,
}, nil
}
// JavaScriptRun runs a javascript module.
//
// It returns the last expression of the script and a destroyer function.
//
// You should always call the destroyer function as soon as possible to limit memory usage.
//
// Each global function will be injected into the context of the module automatically so that you can invoke them from the script.
func JavaScriptRun(source string, globals map[string]v8go.FunctionCallback) (*v8go.Value, func(), error) {
js, createError := newJavaScriptContext(globals)
if createError != nil {
return nil, nil, createError
}
exports, runError := js.context.RunScript(source, "frizzante.js")
if runError != nil {
return nil, nil, runError
}
return exports, func() { JavaScriptDestroy(js) }, nil
}
func JavaScriptDestroy(js *JavaScriptContext) {
js.context.Close()
js.isolate.Dispose()
}
func JavaScriptBundle(root string, format api.Format, source string) (string, error) {
result := api.Build(api.BuildOptions{
Bundle: true,
Format: format,
Write: false,
Stdin: &api.StdinOptions{
Contents: source,
ResolveDir: root,
},
})
for _, err := range result.Errors {
return "", fmt.Errorf("%s in %s:%d:%d", err.Text, err.Location.File, err.Location.Line, err.Location.Column)
}
return string(result.OutputFiles[0].Contents), nil
}