fx/pkg/reducer/js.go

99 lines
1.8 KiB
Go
Raw Normal View History

2022-05-03 22:00:52 +00:00
package reducer
import (
_ "embed"
2022-05-08 13:13:09 +00:00
"encoding/json"
2022-05-03 22:00:52 +00:00
"fmt"
"strings"
2022-05-08 13:13:09 +00:00
. "github.com/antonmedv/fx/pkg/json"
. "github.com/antonmedv/fx/pkg/theme"
"github.com/dop251/goja"
2022-05-03 22:00:52 +00:00
)
2022-05-08 13:13:09 +00:00
//go:embed js.js
var templateJs string
func js(args []string, fxrc string) string {
2022-05-03 22:00:52 +00:00
rs := "\n"
for i, a := range args {
rs += " try {"
switch {
case flatMapRegex.MatchString(a):
code := fold(strings.Split(a, "[]"))
rs += fmt.Sprintf(
`
x = (
%v
)(x)
`, code)
case strings.HasPrefix(a, ".["):
rs += fmt.Sprintf(
`
x = function ()
{ return this%v }
.call(x)
`, a[1:])
case strings.HasPrefix(a, "."):
rs += fmt.Sprintf(
`
x = function ()
{ return this%v }
.call(x)
`, a)
default:
rs += fmt.Sprintf(
`
let f = function ()
{ return %v }
.call(x)
x = typeof f === 'function' ? f(x) : f
`, a)
}
// Generate a beautiful error message.
rs += " } catch (e) {\n"
pre, post, pointer := trace(args, i)
rs += fmt.Sprintf(
" throw `\\n ${%q} ${%q} ${%q}\\n %v\\n\\n${e.stack || e}`\n",
pre, a, post, pointer,
)
rs += " }\n"
}
2022-05-08 13:13:09 +00:00
return fmt.Sprintf(templateJs, fxrc, rs)
}
2022-05-03 22:00:52 +00:00
2022-05-08 13:13:09 +00:00
func CreateJS(args []string, fxrc string) (*goja.Runtime, goja.Callable, error) {
vm := goja.New()
_, err := vm.RunString(js(args, fxrc))
if err != nil {
return nil, nil, err
}
fn, ok := goja.AssertFunction(vm.Get("reduce"))
if !ok {
panic("Not a function")
}
return vm, fn, nil
2022-05-03 22:00:52 +00:00
}
2022-05-08 13:13:09 +00:00
func ReduceJS(vm *goja.Runtime, reduce goja.Callable, input interface{}, theme Theme) int {
value, err := reduce(goja.Undefined(), vm.ToValue(Stringify(input)))
if err != nil {
fmt.Println(err)
return 1
}
output := value.String()
dec := json.NewDecoder(strings.NewReader(output))
dec.UseNumber()
object, err := Parse(dec)
if err != nil {
fmt.Print(output)
return 0
}
Echo(object, theme)
2022-05-08 13:13:09 +00:00
return 0
2022-05-03 22:00:52 +00:00
}