-
Notifications
You must be signed in to change notification settings - Fork 13
/
transpiler.go
66 lines (62 loc) · 2.12 KB
/
transpiler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package typescript
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"strings"
)
// Transpile transpiles the bytes read from reader using the provided config and options
func Transpile(reader io.Reader, opts ...TranspileOptionFunc) (string, error) {
return TranspileCtx(context.Background(), reader, opts...)
}
// TranspileString compiles the provided typescript string and returns the
func TranspileString(script string, opts ...TranspileOptionFunc) (string, error) {
return TranspileCtx(context.Background(), strings.NewReader(script), opts...)
}
// TranspileCtx compiles the bytes read from script using the provided context. Note that due to a limitation
// in goja, context cancellation only works while in JavaScript code, it does not interrupt native Go functions.
func TranspileCtx(ctx context.Context, script io.Reader, opts ...TranspileOptionFunc) (string, error) {
cfg := NewDefaultConfig()
for _, fn := range opts {
fn(cfg)
}
// Handle context cancellation
if !cfg.PreventCancellation {
done := startInterruptable(ctx, cfg.Runtime)
defer close(done)
}
err := cfg.Initialize()
if err != nil {
return "", fmt.Errorf("initializing config: %w", err)
}
src, err := cfg.Registry.Get(cfg.TypescriptVersion)
if err != nil {
return "", fmt.Errorf("getting typescript source: %w", err)
}
_, err = cfg.Runtime.RunProgram(src)
if err != nil {
return "", fmt.Errorf("running typescript compiler: %w", err)
}
optionBytes, err := json.Marshal(cfg.CompileOptions)
if err != nil {
return "", fmt.Errorf("marshalling compile options: %w", err)
}
scriptBytes, err := ioutil.ReadAll(script)
if err != nil {
return "", fmt.Errorf("reading script from reader: %w", err)
}
s := fmt.Sprintf("ts.transpile(%s('%s'), %s, /*fileName*/ undefined, /*diagnostics*/ undefined, /*moduleName*/ \"%s\")",
cfg.decoderName, base64.StdEncoding.EncodeToString(scriptBytes), optionBytes, cfg.ModuleName)
if cfg.Verbose {
log.Println(s)
}
value, err := cfg.Runtime.RunString(s)
if err != nil {
return "", fmt.Errorf("running compiler: %w", err)
}
return strings.TrimSuffix(value.String(), "\r\n"), nil
}