Debian Codegraph @

internal/js/esbuild/options.go

raw
1 // Copyright 2024 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 esbuild
15
16 import (
17 "encoding/json"
18 "fmt"
19 "maps"
20 "path/filepath"
21 "sort"
22 "strings"
23
24 "github.com/gohugoio/hugo/common/hmaps"
25 "github.com/gohugoio/hugo/common/hugio"
26 "github.com/gohugoio/hugo/common/paths"
27 "github.com/gohugoio/hugo/identity"
28 "github.com/gohugoio/hugo/resources/resource_transformers/tocss/sass"
29
30 "github.com/evanw/esbuild/pkg/api"
31
32 "github.com/gohugoio/hugo/media"
33 "github.com/mitchellh/mapstructure"
34 )
35
36 var (
37 nameTarget = map[string]api.Target{
38 "": api.ESNext,
39 "esnext": api.ESNext,
40 "es5": api.ES5,
41 "es6": api.ES2015,
42 "es2015": api.ES2015,
43 "es2016": api.ES2016,
44 "es2017": api.ES2017,
45 "es2018": api.ES2018,
46 "es2019": api.ES2019,
47 "es2020": api.ES2020,
48 "es2021": api.ES2021,
49 "es2022": api.ES2022,
50 "es2023": api.ES2023,
51 "es2024": api.ES2024,
52 }
53
54 engineName = map[string]api.EngineName{
55 "chrome": api.EngineChrome,
56 "deno": api.EngineDeno,
57 "edge": api.EngineEdge,
58 "firefox": api.EngineFirefox,
59 "hermes": api.EngineHermes,
60 "ie": api.EngineIE,
61 "ios": api.EngineIOS,
62 "node": api.EngineNode,
63 "opera": api.EngineOpera,
64 "rhino": api.EngineRhino,
65 "safari": api.EngineSafari,
66 }
67
68 engineKeysSorted []string
69
70 // source names: https://github.com/evanw/esbuild/blob/9eca46464ed5615cb36a3beb3f7a7b9a8ffbe7cf/internal/config/config.go#L208
71 nameLoader = map[string]api.Loader{
72 "none": api.LoaderNone,
73 "base64": api.LoaderBase64,
74 "binary": api.LoaderBinary,
75 "copy": api.LoaderFile,
76 "css": api.LoaderCSS,
77 "dataurl": api.LoaderDataURL,
78 "default": api.LoaderDefault,
79 "empty": api.LoaderEmpty,
80 "file": api.LoaderFile,
81 "global-css": api.LoaderGlobalCSS,
82 "js": api.LoaderJS,
83 "json": api.LoaderJSON,
84 "jsx": api.LoaderJSX,
85 "local-css": api.LoaderLocalCSS,
86 "text": api.LoaderText,
87 "ts": api.LoaderTS,
88 "tsx": api.LoaderTSX,
89 }
90 )
91
92 func init() {
93 for k := range engineName {
94 engineKeysSorted = append(engineKeysSorted, k)
95 }
96 // Sort by length descending to match longest prefix first.
97 sort.Slice(engineKeysSorted, func(i, j int) bool {
98 return len(engineKeysSorted[i]) > len(engineKeysSorted[j])
99 })
100 }
101
102 // DecodeExternalOptions decodes the given map into ExternalOptions.
103 func DecodeExternalOptions(m map[string]any) (ExternalOptions, error) {
104 opts := ExternalOptions{
105 SourcesContent: true,
106 }
107
108 if err := mapstructure.WeakDecode(m, &opts); err != nil {
109 return opts, err
110 }
111
112 if opts.TargetPath != "" {
113 opts.TargetPath = paths.ToSlashTrimLeading(opts.TargetPath)
114 }
115
116 for i, t := range opts.Target {
117 opts.Target[i] = strings.ToLower(t)
118 }
119 opts.Format = strings.ToLower(opts.Format)
120
121 return opts, nil
122 }
123
124 // ErrorMessageResolved holds a resolved error message.
125 type ErrorMessageResolved struct {
126 Path string
127 Message string
128 Content hugio.ReadSeekCloser
129 }
130
131 // ExternalOptions holds user facing options for the js.Build template function.
132 type ExternalOptions struct {
133 // If not set, the source path will be used as the base target path.
134 // Note that the target path's extension may change if the target MIME type
135 // is different, e.g. when the source is TypeScript.
136 TargetPath string
137
138 // Whether to minify to output.
139 Minify bool
140
141 // One of "inline", "external", "linked" or "none".
142 SourceMap string
143
144 SourcesContent bool
145
146 // This sets the target environment for the generated JavaScript and/or CSS code.
147 // It can specify the JavaScript language version to target (es2015, es2016, es2017, es2018, es2019, es2020 or esnext; default is esnext),
148 // in addition to a set of environments to support, as slice of environment name followed by a version number. e.g. "chrome80", "firefox73", "safari13" or "edge80".
149 // See https://esbuild.github.io/api/#target
150 Target []string
151
152 // The output format.
153 // One of: iife, cjs, esm
154 // Default is to esm.
155 Format string
156
157 // One of browser, node, neutral.
158 // Default is browser.
159 // See https://esbuild.github.io/api/#platform
160 Platform string
161
162 // When you import a package in node, the main field in that package's package.json file
163 // determines which file is imported (along with a lot of other rules).
164 // The default main fields is controlled by ESBuild and depend on the current platform setting.
165 // See https://esbuild.github.io/api/#main-fields
166 MainFields []string
167
168 // External dependencies, e.g. "react".
169 Externals []string
170
171 // This option allows you to automatically replace a global variable with an import from another file.
172 // The filenames must be relative to /assets.
173 // See https://esbuild.github.io/api/#inject
174 Inject []string
175
176 // User defined symbols.
177 Defines map[string]any
178
179 // This tells esbuild to edit your source code before building to drop certain constructs.
180 // See https://esbuild.github.io/api/#drop
181 Drop string
182
183 // Maps a component import to another.
184 Shims map[string]string
185
186 // User provided import context. If set, we will look here first.
187 ImportContext any
188
189 // Configuring a loader for a given file type lets you load that file type with an
190 // import statement or a require call. For example, configuring the .png file extension
191 // to use the data URL loader means importing a .png file gives you a data URL
192 // containing the contents of that image
193 //
194 // See https://esbuild.github.io/api/#loader
195 Loaders map[string]string
196
197 // User defined params. Will be marshaled to JSON and available as "@params", e.g.
198 // import * as params from '@params';
199 Params any
200
201 // What to use instead of React.createElement.
202 JSXFactory string
203
204 // What to use instead of React.Fragment.
205 JSXFragment string
206
207 // What to do about JSX syntax.
208 // See https://esbuild.github.io/api/#jsx
209 JSX string
210
211 // Which library to use to automatically import JSX helper functions from. Only works if JSX is set to automatic.
212 // See https://esbuild.github.io/api/#jsx-import-source
213 JSXImportSource string
214
215 // User defined CSS variables. Will be available as CSS global scope CSS variables via @import "hugo:vars".
216 Vars map[string]any
217
218 // There is/was a bug in WebKit with severe performance issue with the tracking
219 // of TDZ checks in JavaScriptCore.
220 //
221 // Enabling this flag removes the TDZ and `const` assignment checks and
222 // may improve performance of larger JS codebases until the WebKit fix
223 // is in widespread use.
224 //
225 // See https://bugs.webkit.org/show_bug.cgi?id=199866
226 // Deprecated: This no longer have any effect and will be removed.
227 // TODO(bep) remove. See https://github.com/evanw/esbuild/commit/869e8117b499ca1dbfc5b3021938a53ffe934dba
228 AvoidTDZ bool
229 }
230
231 // InternalOptions holds internal options for the js.Build template function.
232 type InternalOptions struct {
233 MediaType media.Type
234 OutDir string
235 Contents string
236 SourceDir string
237 ResolveDir string
238 AbsWorkingDir string
239 Metafile bool
240
241 // Used as a prefix for asset references that go through the file loader.
242 // See https://esbuild.github.io/api/#public-path
243 PublicPath string
244
245 StdinSourcePath string
246
247 DependencyManager identity.Manager
248
249 Stdin bool // Set to true to pass in the entry point as a byte slice.
250 Splitting bool
251 IsCSS bool // Entry point is CSS.
252 TsConfig string
253 EntryPoints []string
254 ImportOnResolveFunc func(string, api.OnResolveArgs) string
255 ImportOnLoadFunc func(api.OnLoadArgs) (string, error)
256 ImportParamsOnLoadFunc func(args api.OnLoadArgs) json.RawMessage
257 ErrorMessageResolveFunc func(api.Message) *ErrorMessageResolved
258 ResolveSourceMapSource func(string) string // Used to resolve paths in error source maps.
259 }
260
261 // Options holds the options passed to Build.
262 type Options struct {
263 ExternalOptions
264 InternalOptions
265
266 compiled api.BuildOptions
267 }
268
269 func (opts *Options) compile() (err error) {
270 var target api.Target
271 for _, value := range opts.Target {
272 if v, found := nameTarget[value]; found {
273 if v > target {
274 target = v
275 }
276 }
277 }
278
279 var engines []api.Engine
280
281 OUTER:
282 for _, value := range opts.Target {
283 for _, engine := range engineKeysSorted {
284 if strings.HasPrefix(value, engine) {
285 version := value[len(engine):]
286 if version == "" {
287 return fmt.Errorf("invalid engine version: %q", value)
288 }
289 engines = append(engines, api.Engine{Name: engineName[engine], Version: version})
290 continue OUTER
291 }
292 }
293 }
294
295 if target == 0 && len(engines) == 0 && len(opts.Target) > 0 {
296 return fmt.Errorf("unsupported target: %v", opts.Target)
297 }
298
299 if target == 0 {
300 target = api.ESNext
301 }
302
303 var loaders map[string]api.Loader
304 if opts.IsCSS {
305 loaders = make(map[string]api.Loader)
306 // Add default CSS file loaders.
307 // May be overridden by opts.Loaders.
308 maps.Copy(loaders, extensionToLoaderMapCSS)
309 }
310 if opts.Loaders != nil {
311 if loaders == nil {
312 loaders = make(map[string]api.Loader)
313 }
314
315 for k, v := range opts.Loaders {
316 loader, found := nameLoader[v]
317 if !found {
318 err = fmt.Errorf("invalid loader: %q", v)
319 return
320 }
321 loaders[k] = loader
322 }
323 }
324
325 mediaType := opts.MediaType
326 if mediaType.IsZero() {
327 mediaType = media.Builtin.JavascriptType
328 }
329
330 var loader api.Loader
331 switch mediaType.SubType {
332 case media.Builtin.JavascriptType.SubType:
333 loader = api.LoaderJS
334 case media.Builtin.TypeScriptType.SubType:
335 loader = api.LoaderTS
336 case media.Builtin.TSXType.SubType:
337 loader = api.LoaderTSX
338 case media.Builtin.JSXType.SubType:
339 loader = api.LoaderJSX
340 case media.Builtin.CSSType.SubType:
341 loader = api.LoaderCSS
342 default:
343 err = fmt.Errorf("unsupported Media Type: %q", opts.MediaType)
344 return
345 }
346
347 var format api.Format
348 // One of: iife, cjs, esm
349 switch opts.Format {
350 case "", "iife":
351 format = api.FormatIIFE
352 case "esm":
353 format = api.FormatESModule
354 case "cjs":
355 format = api.FormatCommonJS
356 default:
357 err = fmt.Errorf("unsupported script output format: %q", opts.Format)
358 return
359 }
360
361 var jsx api.JSX
362 switch opts.JSX {
363 case "", "transform":
364 jsx = api.JSXTransform
365 case "preserve":
366 jsx = api.JSXPreserve
367 case "automatic":
368 jsx = api.JSXAutomatic
369 default:
370 err = fmt.Errorf("unsupported jsx type: %q", opts.JSX)
371 return
372 }
373
374 var platform api.Platform
375 switch opts.Platform {
376 case "", "browser":
377 platform = api.PlatformBrowser
378 case "node":
379 platform = api.PlatformNode
380 case "neutral":
381 platform = api.PlatformNeutral
382 default:
383 err = fmt.Errorf("unsupported platform type: %q", opts.Platform)
384 return
385 }
386
387 var defines map[string]string
388 if opts.Defines != nil {
389 defines = hmaps.ToStringMapString(opts.Defines)
390 }
391
392 var drop api.Drop
393 switch opts.Drop {
394 case "":
395 case "console":
396 drop = api.DropConsole
397 case "debugger":
398 drop = api.DropDebugger
399 default:
400 err = fmt.Errorf("unsupported drop type: %q", opts.Drop)
401 }
402
403 // By default we only need to specify outDir and no outFile
404 outDir := opts.OutDir
405 outFile := ""
406 var sourceMap api.SourceMap
407 switch opts.SourceMap {
408 case "inline":
409 sourceMap = api.SourceMapInline
410 case "external":
411 sourceMap = api.SourceMapExternal
412 case "linked":
413 sourceMap = api.SourceMapLinked
414 case "", "none":
415 sourceMap = api.SourceMapNone
416 default:
417 err = fmt.Errorf("unsupported sourcemap type: %q", opts.SourceMap)
418 return
419 }
420
421 sourcesContent := api.SourcesContentInclude
422 if !opts.SourcesContent {
423 sourcesContent = api.SourcesContentExclude
424 }
425
426 if opts.IsCSS && opts.MainFields == nil {
427 opts.MainFields = []string{"style", "main"}
428 }
429
430 opts.Vars = sass.PrepareVars(opts.Vars)
431
432 opts.compiled = api.BuildOptions{
433 Outfile: outFile,
434 Bundle: true,
435 Metafile: opts.Metafile,
436 AbsWorkingDir: opts.AbsWorkingDir,
437
438 Target: target,
439 Engines: engines,
440 Format: format,
441 MainFields: opts.MainFields,
442 Platform: platform,
443 Sourcemap: sourceMap,
444 SourcesContent: sourcesContent,
445
446 Loader: loaders,
447
448 MinifyWhitespace: opts.Minify,
449 MinifyIdentifiers: opts.Minify,
450 MinifySyntax: opts.Minify,
451
452 Outdir: outDir,
453 PublicPath: opts.PublicPath,
454 Splitting: opts.Splitting,
455
456 Define: defines,
457 External: opts.Externals,
458 Drop: drop,
459
460 JSXFactory: opts.JSXFactory,
461 JSXFragment: opts.JSXFragment,
462
463 JSX: jsx,
464 JSXImportSource: opts.JSXImportSource,
465
466 Tsconfig: opts.TsConfig,
467
468 EntryPoints: opts.EntryPoints,
469 }
470
471 if opts.Stdin {
472 // This makes ESBuild pass `stdin` as the Importer to the import.
473 opts.compiled.Stdin = &api.StdinOptions{
474 Contents: opts.Contents,
475 ResolveDir: opts.ResolveDir,
476 Loader: loader,
477 }
478 }
479 return
480 }
481
482 func (o Options) loaderFromFilename(filename string) api.Loader {
483 ext := filepath.Ext(filename)
484 if optsLoaders := o.compiled.Loader; optsLoaders != nil {
485 if l, found := optsLoaders[ext]; found {
486 return l
487 }
488 }
489 if !o.IsCSS {
490 if l, found := extensionToLoaderMapJS[ext]; found {
491 return l
492 }
493 }
494 return api.LoaderDefault
495 }
496
497 func (opts *Options) validate() error {
498 if opts.ImportOnResolveFunc != nil && opts.ImportOnLoadFunc == nil {
499 return fmt.Errorf("ImportOnLoadFunc must be set if ImportOnResolveFunc is set")
500 }
501 if opts.ImportOnResolveFunc == nil && opts.ImportOnLoadFunc != nil {
502 return fmt.Errorf("ImportOnResolveFunc must be set if ImportOnLoadFunc is set")
503 }
504 if opts.AbsWorkingDir == "" {
505 return fmt.Errorf("AbsWorkingDir must be set")
506 }
507 return nil
508 }