|
| 1 | +package dartfmt |
| 2 | + |
| 3 | +import ( |
| 4 | + _ "embed" |
| 5 | + "fmt" |
| 6 | + "sync" |
| 7 | + |
| 8 | + "github.com/dop251/goja" |
| 9 | + "github.com/dop251/goja/parser" |
| 10 | + "golang.org/x/sync/singleflight" |
| 11 | +) |
| 12 | + |
| 13 | +//go:embed internal/entrypoint/dist/entrypoint.js |
| 14 | +var formatScript string |
| 15 | +var formatProgram *goja.Program |
| 16 | + |
| 17 | +const formatScriptFormat = ` |
| 18 | +var self = {location: {href: '/'}}; |
| 19 | +%s |
| 20 | +var formatDart = self.formatDart; |
| 21 | +` |
| 22 | + |
| 23 | +func compileFormatterForSingleflight() (interface{}, error) { |
| 24 | + if formatProgram != nil { |
| 25 | + return formatProgram, nil |
| 26 | + } |
| 27 | + |
| 28 | + prog, err := goja.Parse( |
| 29 | + "entrypoint.js", |
| 30 | + fmt.Sprintf(formatScriptFormat, formatScript), |
| 31 | + parser.WithDisableSourceMaps, |
| 32 | + ) |
| 33 | + |
| 34 | + if err != nil { |
| 35 | + return nil, fmt.Errorf("parsing a script failed: %w", err) |
| 36 | + } |
| 37 | + |
| 38 | + formatProgram, err = goja.CompileAST(prog, false) |
| 39 | + |
| 40 | + if err != nil { |
| 41 | + return nil, fmt.Errorf("compiling AST failed: %w", err) |
| 42 | + } |
| 43 | + |
| 44 | + return formatProgram, nil |
| 45 | +} |
| 46 | + |
| 47 | +var group singleflight.Group |
| 48 | +var pool = sync.Pool{ |
| 49 | + New: func() interface{} { |
| 50 | + fg, err, _ := group.Do("entrypoint.js", compileFormatterForSingleflight) |
| 51 | + |
| 52 | + if err != nil { |
| 53 | + panic(err) |
| 54 | + } |
| 55 | + |
| 56 | + vm := goja.New() |
| 57 | + |
| 58 | + _, err = vm.RunProgram(fg.(*goja.Program)) |
| 59 | + |
| 60 | + if err != nil { |
| 61 | + panic(err) |
| 62 | + } |
| 63 | + |
| 64 | + return vm |
| 65 | + }, |
| 66 | +} |
| 67 | + |
| 68 | +// FormatDartStandalone formats a script without dependencies on external commands |
| 69 | +func FormatDartStandalone(script string) (string, error) { |
| 70 | + vm := pool.Get().(*goja.Runtime) |
| 71 | + defer pool.Put(vm) |
| 72 | + |
| 73 | + dartFormat := vm.GlobalObject().Get("formatDart") |
| 74 | + |
| 75 | + if dartFormat == nil { |
| 76 | + return "", fmt.Errorf("formatDart is nil") |
| 77 | + } |
| 78 | + |
| 79 | + var fn func(string) string |
| 80 | + err := vm.ExportTo(dartFormat, &fn) |
| 81 | + if err != nil { |
| 82 | + return "", fmt.Errorf("failed to execute dart_style formatter: %w", err) |
| 83 | + } |
| 84 | + |
| 85 | + return fn(script), nil |
| 86 | +} |
0 commit comments