ai_old/js/common.go
Star 767d87ac3e update throw exception
add util.load and util.save
2024-09-24 13:34:32 +08:00

102 lines
2.1 KiB
Go

package js
import (
"apigo.cc/ai/ai/goja"
"errors"
"github.com/ssgo/u"
"path/filepath"
)
func toMap(data any) map[string]any {
return u.UnJsonMap(u.FixedJson(data))
}
type Args struct {
This goja.Value
Arguments []goja.Value
VM *goja.Runtime
}
func MakeArgs(args *goja.FunctionCall, vm *goja.Runtime) *Args {
return &Args{
This: args.This,
Arguments: args.Arguments,
VM: vm,
}
}
func (args *Args) Check(num int) *Args {
if len(args.Arguments) < num {
panic(args.VM.NewGoError(errors.New("arguments need " + u.String(num) + ", but given " + u.String(len(args.Arguments)))))
}
return args
}
func (args *Args) Int(index int) int {
if len(args.Arguments) > index {
return u.Int(args.Arguments[index].Export())
}
return 0
}
func (args *Args) Any(index int) any {
if len(args.Arguments) > index {
return args.Arguments[index].Export()
}
return nil
}
func (args *Args) Str(index int) string {
if len(args.Arguments) > index {
return u.String(args.Arguments[index].Export())
}
return ""
}
func (args *Args) Map(index int) map[string]any {
out := map[string]any{}
if len(args.Arguments) > index {
u.Convert(args.Arguments[index].Export(), &out)
}
return out
}
func (args *Args) StrArr(startIndex int) []string {
if len(args.Arguments) > startIndex {
a := make([]string, len(args.Arguments)-startIndex)
for index := startIndex; index < len(args.Arguments); index++ {
a[index-startIndex] = u.String(args.Arguments[index].Export())
}
return a
}
return make([]string, 0)
}
func (args *Args) Map2StrArr(index int) []string {
headerMap := args.Map(index)
headers := make([]string, len(headerMap)*2)
i := 0
for k, v := range headerMap {
headers[i] = k
headers[i+1] = u.String(v)
i += 2
}
return headers
}
func findPath(vm *goja.Runtime, filename string) string {
if u.FileExists(filename) {
return filename
}
if !filepath.IsAbs(filename) {
startPath := u.String(vm.GoData["startPath"])
if startPath != "" {
tryFilename := filepath.Join(startPath, filename)
if u.FileExists(tryFilename) {
return tryFilename
}
}
}
return filename
}