Debian Codegraph @

resources/resource_transformers/babel/babel.go

raw
1 // Copyright 2020 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package babel
15
16 import (
17 "bytes"
18 "encoding/base64"
19 "fmt"
20 "io"
21 "path"
22 "path/filepath"
23 "regexp"
24 "strconv"
25
26 "github.com/gohugoio/hugo/common/hexec"
27 "github.com/gohugoio/hugo/common/loggers"
28
29 "github.com/gohugoio/hugo/common/hugo"
30 "github.com/gohugoio/hugo/resources/internal"
31
32 "github.com/mitchellh/mapstructure"
33
34 "github.com/gohugoio/hugo/common/herrors"
35 "github.com/gohugoio/hugo/resources"
36 "github.com/gohugoio/hugo/resources/resource"
37 )
38
39 // Options from https://babeljs.io/docs/en/options
40 type Options struct {
41 Config string // Custom path to config file
42
43 Minified bool
44 NoComments bool
45 Compact *bool
46 Verbose bool
47 NoBabelrc bool
48 SourceMap string
49 }
50
51 // DecodeOptions decodes options to and generates command flags
52 func DecodeOptions(m map[string]any) (opts Options, err error) {
53 if m == nil {
54 return
55 }
56 err = mapstructure.WeakDecode(m, &opts)
57 return
58 }
59
60 func (opts Options) sourceMapEnabled() bool {
61 return opts.SourceMap != "" && opts.SourceMap != "none"
62 }
63
64 func (opts Options) toArgs() []any {
65 var args []any
66
67 // Always use inline source maps; Transform extracts to external file if needed.
68 if opts.sourceMapEnabled() {
69 args = append(args, "--source-maps=inline")
70 }
71 if opts.Minified {
72 args = append(args, "--minified")
73 }
74 if opts.NoComments {
75 args = append(args, "--no-comments")
76 }
77 if opts.Compact != nil {
78 args = append(args, "--compact="+strconv.FormatBool(*opts.Compact))
79 }
80 if opts.Verbose {
81 args = append(args, "--verbose")
82 }
83 if opts.NoBabelrc {
84 args = append(args, "--no-babelrc")
85 }
86 return args
87 }
88
89 // Client is the client used to do Babel transformations.
90 type Client struct {
91 rs *resources.Spec
92 }
93
94 // New creates a new Client with the given specification.
95 func New(rs *resources.Spec) *Client {
96 return &Client{rs: rs}
97 }
98
99 type babelTransformation struct {
100 options Options
101 rs *resources.Spec
102 }
103
104 func (t *babelTransformation) Key() internal.ResourceTransformationKey {
105 return internal.NewResourceTransformationKey("babel", t.options)
106 }
107
108 // Transform shells out to babel-cli to do the heavy lifting.
109 // For this to work, you need some additional tools. To install them globally:
110 // npm install -g @babel/core @babel/cli
111 // If you want to use presets or plugins such as @babel/preset-env
112 // Then you should install those globally as well. e.g:
113 // npm install -g @babel/preset-env
114 // Instead of installing globally, you can also install everything as a dev-dependency (--save-dev instead of -g)
115 func (t *babelTransformation) Transform(ctx *resources.ResourceTransformationCtx) error {
116 const binaryName = "babel"
117
118 ex := t.rs.ExecHelper
119
120 if err := ex.Sec().CheckAllowedExec(binaryName); err != nil {
121 return err
122 }
123
124 var configFile string
125 infol := t.rs.Logger.InfoCommand(binaryName)
126 infoW := loggers.LevelLoggerToWriter(infol)
127
128 var errBuf bytes.Buffer
129
130 if t.options.Config != "" {
131 configFile = t.options.Config
132 } else {
133 for _, name := range []string{"babel.config.js", "babel.config.mjs", "babel.config.cjs"} {
134 configFile = t.rs.BaseFs.ResolveJSConfigFile(name)
135 if configFile != "" {
136 break
137 }
138 }
139 }
140
141 if configFile != "" {
142 configFile = filepath.Clean(configFile)
143 // We need an absolute filename to the config file.
144 if !filepath.IsAbs(configFile) {
145 configFile = t.rs.BaseFs.ResolveJSConfigFile(configFile)
146 if configFile == "" && t.options.Config != "" {
147 // Only fail if the user specified config file is not found.
148 return fmt.Errorf("babel config %q not found", t.options.Config)
149 }
150 }
151 }
152
153 ctx.ReplaceOutPathExtension(".js")
154
155 var cmdArgs []any
156
157 if configFile != "" {
158 infol.Logf("use config file %q", configFile)
159 cmdArgs = []any{"--config-file", configFile}
160 }
161
162 if optArgs := t.options.toArgs(); len(optArgs) > 0 {
163 cmdArgs = append(cmdArgs, optArgs...)
164 }
165 cmdArgs = append(cmdArgs, "--filename="+ctx.SourcePath)
166
167 var outBuf bytes.Buffer
168 stderr := io.MultiWriter(infoW, &errBuf)
169 cmdArgs = append(cmdArgs, hexec.WithStderr(stderr))
170 cmdArgs = append(cmdArgs, hexec.WithStdout(&outBuf))
171 cmdArgs = append(cmdArgs, hexec.WithDir(t.rs.Cfg.BaseConfig().WorkingDir))
172 cmdArgs = append(cmdArgs, hexec.WithEnviron(hugo.GetExecEnviron(t.rs.Cfg.BaseConfig().WorkingDir, t.rs.Cfg, t.rs.BaseFs.Assets.Fs)))
173
174 cmd, err := ex.Npx(binaryName, cmdArgs...)
175 if err != nil {
176 if hexec.IsNotFound(err) {
177 // This may be on a CI server etc. Will fall back to pre-built assets.
178 return &herrors.FeatureNotAvailableError{Cause: err}
179 }
180 return err
181 }
182
183 stdin, err := cmd.StdinPipe()
184 if err != nil {
185 return err
186 }
187
188 go func() {
189 defer stdin.Close()
190 io.Copy(stdin, ctx.From)
191 }()
192
193 err = cmd.Run()
194 if err != nil {
195 if hexec.IsNotFound(err) {
196 return &herrors.FeatureNotAvailableError{Cause: err}
197 }
198 return fmt.Errorf(errBuf.String()+": %w", err)
199 }
200
201 content := outBuf.Bytes()
202
203 if t.options.SourceMap == "external" {
204 if sourceMap, stripped, ok := extractInlineSourceMap(content); ok {
205 if err = ctx.PublishSourceMap(sourceMap); err != nil {
206 return err
207 }
208 targetPath := path.Base(ctx.OutPath) + ".map"
209 content = append(stripped, ("//# sourceMappingURL=" + targetPath + "\n")...)
210 }
211 }
212
213 ctx.To.Write(content)
214
215 return nil
216 }
217
218 // Process transforms the given Resource with the Babel processor.
219 func (c *Client) Process(res resources.ResourceTransformer, options Options) (resource.Resource, error) {
220 return res.Transform(
221 &babelTransformation{rs: c.rs, options: options},
222 )
223 }
224
225 var inlineSourceMapRe = regexp.MustCompile(`(?m)//# sourceMappingURL=data:application/json[^,]*,([A-Za-z0-9+/=]+)\s*$`)
226
227 func extractInlineSourceMap(content []byte) (sourceMap, stripped []byte, ok bool) {
228 loc := inlineSourceMapRe.FindSubmatchIndex(content)
229 if loc == nil {
230 return nil, content, false
231 }
232 decoded, err := base64.StdEncoding.DecodeString(string(content[loc[2]:loc[3]]))
233 if err != nil {
234 return nil, content, false
235 }
236 return decoded, content[:loc[0]], true
237 }