feat: init js-core

This commit is contained in:
Skyxim
2022-06-04 23:51:13 +08:00
parent 8ff7e180a4
commit 91b4176557
5 changed files with 117 additions and 7 deletions

32
component/js/core.go Normal file
View File

@@ -0,0 +1,32 @@
package js
import (
"github.com/dop251/goja"
"sync"
)
var JS sync.Map
var mux sync.Mutex
func NewJS(name, code string) error {
program, err := compiler(name, code)
if err != nil {
return err
}
if _, ok := JS.Load(name); !ok {
mux.Lock()
defer mux.Unlock()
if _, ok := JS.Load(name); !ok {
JS.Store(name, program)
}
}
return nil
}
func Run(name string, args map[string]any, callback func(any, error)) {
if value, ok := JS.Load(name); ok {
run(getLoop(), value.(*goja.Program), args, callback)
}
}

42
component/js/js.go Normal file
View File

@@ -0,0 +1,42 @@
package js
import (
"github.com/dop251/goja"
"github.com/dop251/goja_nodejs/console"
"github.com/dop251/goja_nodejs/eventloop"
"github.com/dop251/goja_nodejs/require"
)
func preSetting(rt *goja.Runtime) {
registry := new(require.Registry)
registry.Enable(rt)
logPrinter := console.RequireWithPrinter(&JsLog{})
require.RegisterNativeModule("console", logPrinter)
console.Enable(rt)
eventloop.EnableConsole(true)
}
func getLoop() *eventloop.EventLoop {
loop := eventloop.NewEventLoop(func(loop *eventloop.EventLoop) {
loop.Run(func(runtime *goja.Runtime) {
preSetting(runtime)
})
})
return loop
}
func compiler(name, code string) (*goja.Program, error) {
return goja.Compile(name, code, false)
}
func run(loop *eventloop.EventLoop, program *goja.Program, args map[string]any, callback func(any, error)) {
loop.RunOnLoop(func(runtime *goja.Runtime) {
for k, v := range args {
runtime.Set(k, v)
}
v, err := runtime.RunProgram(program)
callback(v, err)
})
}

18
component/js/log.go Normal file
View File

@@ -0,0 +1,18 @@
package js
import "github.com/Dreamacro/clash/log"
type JsLog struct {
}
func (j JsLog) Log(s string) {
log.Infoln("[JS] %s", s)
}
func (j JsLog) Warn(s string) {
log.Warnln("[JS] %s", s)
}
func (j JsLog) Error(s string) {
log.Errorln("[JS] %s", s)
}