120 lines
2.5 KiB
Go
120 lines
2.5 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
|
|
"github.com/dop251/goja"
|
|
"github.com/evanw/esbuild/pkg/api"
|
|
)
|
|
|
|
func executeTypeScript(filePath string, stdout, stderr io.Writer) error {
|
|
tsContent, err := os.ReadFile(filePath)
|
|
if err != nil {
|
|
_, _ = fmt.Fprintf(stderr, "Error reading file: %v\n", err)
|
|
return err
|
|
}
|
|
|
|
result := api.Transform(string(tsContent), api.TransformOptions{
|
|
Loader: api.LoaderTS,
|
|
Target: api.ES2020,
|
|
Format: api.FormatIIFE,
|
|
Sourcemap: api.SourceMapNone,
|
|
TreeShaking: api.TreeShakingFalse,
|
|
})
|
|
|
|
if len(result.Errors) > 0 {
|
|
_, _ = fmt.Fprintf(stderr, "Transpilation errors:\n")
|
|
for _, err := range result.Errors {
|
|
_, _ = fmt.Fprintf(stderr, " %s\n", err.Text)
|
|
}
|
|
return fmt.Errorf("transpilation failed")
|
|
}
|
|
|
|
vm := goja.New()
|
|
|
|
RegisterBuiltins(vm)
|
|
|
|
console := vm.NewObject()
|
|
_ = vm.Set("console", console)
|
|
|
|
_ = console.Set("log", func(call goja.FunctionCall) goja.Value {
|
|
args := call.Arguments
|
|
for i, arg := range args {
|
|
if i > 0 {
|
|
_, _ = fmt.Fprint(stdout, " ")
|
|
}
|
|
_, _ = fmt.Fprint(stdout, arg.String())
|
|
}
|
|
_, _ = fmt.Fprintln(stdout)
|
|
return goja.Undefined()
|
|
})
|
|
|
|
_, err = vm.RunString(string(result.Code))
|
|
if err != nil {
|
|
_, _ = fmt.Fprintf(stderr, "Execution error: %v\n", err)
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func executeTypeScriptContent(tsContent string, stdout, stderr io.Writer) error {
|
|
result := api.Transform(tsContent, api.TransformOptions{
|
|
Loader: api.LoaderTS,
|
|
Target: api.ES2020,
|
|
Format: api.FormatIIFE,
|
|
Sourcemap: api.SourceMapNone,
|
|
TreeShaking: api.TreeShakingFalse,
|
|
})
|
|
|
|
if len(result.Errors) > 0 {
|
|
_, _ = fmt.Fprintf(stderr, "Transpilation errors:\n")
|
|
for _, err := range result.Errors {
|
|
_, _ = fmt.Fprintf(stderr, " %s\n", err.Text)
|
|
}
|
|
return fmt.Errorf("transpilation failed")
|
|
}
|
|
|
|
vm := goja.New()
|
|
|
|
RegisterBuiltins(vm)
|
|
|
|
console := vm.NewObject()
|
|
_ = vm.Set("console", console)
|
|
|
|
_ = console.Set("log", func(call goja.FunctionCall) goja.Value {
|
|
args := call.Arguments
|
|
for i, arg := range args {
|
|
if i > 0 {
|
|
_, _ = fmt.Fprint(stdout, " ")
|
|
}
|
|
_, _ = fmt.Fprint(stdout, arg.String())
|
|
}
|
|
_, _ = fmt.Fprintln(stdout)
|
|
return goja.Undefined()
|
|
})
|
|
|
|
_, err := vm.RunString(string(result.Code))
|
|
if err != nil {
|
|
_, _ = fmt.Fprintf(stderr, "Execution error: %v\n", err)
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func main() {
|
|
if len(os.Args) < 2 {
|
|
fmt.Fprintln(os.Stderr, "Usage: program <typescript-file>")
|
|
os.Exit(1)
|
|
}
|
|
|
|
filePath := os.Args[1]
|
|
|
|
if err := executeTypeScript(filePath, os.Stdout, os.Stderr); err != nil {
|
|
os.Exit(1)
|
|
}
|
|
}
|