82 lines
2.0 KiB
Go
82 lines
2.0 KiB
Go
package js
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/dop251/goja"
|
|
"github.com/ssgo/u"
|
|
"strings"
|
|
)
|
|
|
|
func requireConsole() map[string]any {
|
|
return map[string]any{
|
|
"print": func(args goja.FunctionCall) goja.Value {
|
|
consolePrint(args, "print", nil)
|
|
return nil
|
|
},
|
|
"println": func(args goja.FunctionCall) goja.Value {
|
|
consolePrint(args, "log", nil)
|
|
return nil
|
|
},
|
|
"log": func(args goja.FunctionCall) goja.Value {
|
|
consolePrint(args, "log", nil)
|
|
return nil
|
|
},
|
|
"info": func(args goja.FunctionCall) goja.Value {
|
|
consolePrint(args, "info", nil)
|
|
return nil
|
|
},
|
|
"warn": func(args goja.FunctionCall, vm *goja.Runtime) goja.Value {
|
|
consolePrint(args, "warn", vm)
|
|
return nil
|
|
},
|
|
"error": func(args goja.FunctionCall, vm *goja.Runtime) goja.Value {
|
|
consolePrint(args, "error", vm)
|
|
return nil
|
|
},
|
|
"debug": func(args goja.FunctionCall, vm *goja.Runtime) goja.Value {
|
|
consolePrint(args, "debug", vm)
|
|
return nil
|
|
},
|
|
"input": func(args goja.FunctionCall, vm *goja.Runtime) goja.Value {
|
|
consolePrint(args, "print", nil)
|
|
line := ""
|
|
_, _ = fmt.Scanln(&line)
|
|
return vm.ToValue(line)
|
|
},
|
|
}
|
|
}
|
|
|
|
func consolePrint(args goja.FunctionCall, typ string, vm *goja.Runtime) {
|
|
arr := make([]any, len(args.Arguments))
|
|
textColor := u.TextNone
|
|
switch typ {
|
|
case "info":
|
|
textColor = u.TextCyan
|
|
case "warn":
|
|
textColor = u.TextYellow
|
|
case "error":
|
|
textColor = u.TextRed
|
|
}
|
|
|
|
for i, arg := range args.Arguments {
|
|
if textColor != u.TextNone {
|
|
arr[i] = u.Color(u.StringP(arg.Export()), textColor, u.BgNone)
|
|
} else {
|
|
arr[i] = u.StringP(arg.Export())
|
|
}
|
|
}
|
|
|
|
if (typ == "warn" || typ == "error" || typ == "debug") && vm != nil {
|
|
callStacks := make([]string, 0)
|
|
for _, stack := range vm.CaptureCallStack(0, nil) {
|
|
callStacks = append(callStacks, u.Color(" "+stack.Position().String(), textColor, u.BgNone))
|
|
}
|
|
fmt.Println(arr...)
|
|
fmt.Println(strings.Join(callStacks, "\n"))
|
|
} else if typ == "print" {
|
|
fmt.Print(arr...)
|
|
} else {
|
|
fmt.Println(arr...)
|
|
}
|
|
}
|