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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
|
// Copyright 2024 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package esbuild
import (
"encoding/json"
"fmt"
"path/filepath"
"strings"
"github.com/gohugoio/hugo/common/hugio"
"github.com/gohugoio/hugo/common/maps"
"github.com/gohugoio/hugo/common/paths"
"github.com/gohugoio/hugo/identity"
"github.com/evanw/esbuild/pkg/api"
"github.com/gohugoio/hugo/media"
"github.com/mitchellh/mapstructure"
)
var (
nameTarget = map[string]api.Target{
"": api.ESNext,
"esnext": api.ESNext,
"es5": api.ES5,
"es6": api.ES2015,
"es2015": api.ES2015,
"es2016": api.ES2016,
"es2017": api.ES2017,
"es2018": api.ES2018,
"es2019": api.ES2019,
"es2020": api.ES2020,
"es2021": api.ES2021,
"es2022": api.ES2022,
"es2023": api.ES2023,
}
// source names: https://github.com/evanw/esbuild/blob/9eca46464ed5615cb36a3beb3f7a7b9a8ffbe7cf/internal/config/config.go#L208
nameLoader = map[string]api.Loader{
"none": api.LoaderNone,
"base64": api.LoaderBase64,
"binary": api.LoaderBinary,
"copy": api.LoaderFile,
"css": api.LoaderCSS,
"dataurl": api.LoaderDataURL,
"default": api.LoaderDefault,
"empty": api.LoaderEmpty,
"file": api.LoaderFile,
"global-css": api.LoaderGlobalCSS,
"js": api.LoaderJS,
"json": api.LoaderJSON,
"jsx": api.LoaderJSX,
"local-css": api.LoaderLocalCSS,
"text": api.LoaderText,
"ts": api.LoaderTS,
"tsx": api.LoaderTSX,
}
)
// DecodeExternalOptions decodes the given map into ExternalOptions.
func DecodeExternalOptions(m map[string]any) (ExternalOptions, error) {
opts := ExternalOptions{
SourcesContent: true,
}
if err := mapstructure.WeakDecode(m, &opts); err != nil {
return opts, err
}
if opts.TargetPath != "" {
opts.TargetPath = paths.ToSlashTrimLeading(opts.TargetPath)
}
opts.Target = strings.ToLower(opts.Target)
opts.Format = strings.ToLower(opts.Format)
return opts, nil
}
// ErrorMessageResolved holds a resolved error message.
type ErrorMessageResolved struct {
Path string
Message string
Content hugio.ReadSeekCloser
}
// ExternalOptions holds user facing options for the js.Build template function.
type ExternalOptions struct {
// If not set, the source path will be used as the base target path.
// Note that the target path's extension may change if the target MIME type
// is different, e.g. when the source is TypeScript.
TargetPath string
// Whether to minify to output.
Minify bool
// One of "inline", "external", "linked" or "none".
SourceMap string
SourcesContent bool
// The language target.
// One of: es2015, es2016, es2017, es2018, es2019, es2020 or esnext.
// Default is esnext.
Target string
// The output format.
// One of: iife, cjs, esm
// Default is to esm.
Format string
// External dependencies, e.g. "react".
Externals []string
// This option allows you to automatically replace a global variable with an import from another file.
// The filenames must be relative to /assets.
// See https://esbuild.github.io/api/#inject
Inject []string
// User defined symbols.
Defines map[string]any
// Maps a component import to another.
Shims map[string]string
// Configuring a loader for a given file type lets you load that file type with an
// import statement or a require call. For example, configuring the .png file extension
// to use the data URL loader means importing a .png file gives you a data URL
// containing the contents of that image
//
// See https://esbuild.github.io/api/#loader
Loaders map[string]string
// User defined params. Will be marshaled to JSON and available as "@params", e.g.
// import * as params from '@params';
Params any
// What to use instead of React.createElement.
JSXFactory string
// What to use instead of React.Fragment.
JSXFragment string
// What to do about JSX syntax.
// See https://esbuild.github.io/api/#jsx
JSX string
// Which library to use to automatically import JSX helper functions from. Only works if JSX is set to automatic.
// See https://esbuild.github.io/api/#jsx-import-source
JSXImportSource string
// There is/was a bug in WebKit with severe performance issue with the tracking
// of TDZ checks in JavaScriptCore.
//
// Enabling this flag removes the TDZ and `const` assignment checks and
// may improve performance of larger JS codebases until the WebKit fix
// is in widespread use.
//
// See https://bugs.webkit.org/show_bug.cgi?id=199866
// Deprecated: This no longer have any effect and will be removed.
// TODO(bep) remove. See https://github.com/evanw/esbuild/commit/869e8117b499ca1dbfc5b3021938a53ffe934dba
AvoidTDZ bool
}
// InternalOptions holds internal options for the js.Build template function.
type InternalOptions struct {
MediaType media.Type
OutDir string
Contents string
SourceDir string
ResolveDir string
AbsWorkingDir string
Metafile bool
StdinSourcePath string
DependencyManager identity.Manager
Stdin bool // Set to true to pass in the entry point as a byte slice.
Splitting bool
TsConfig string
EntryPoints []string
ImportOnResolveFunc func(string, api.OnResolveArgs) string
ImportOnLoadFunc func(api.OnLoadArgs) string
ImportParamsOnLoadFunc func(args api.OnLoadArgs) json.RawMessage
ErrorMessageResolveFunc func(api.Message) *ErrorMessageResolved
ResolveSourceMapSource func(string) string // Used to resolve paths in error source maps.
}
// Options holds the options passed to Build.
type Options struct {
ExternalOptions
InternalOptions
compiled api.BuildOptions
}
func (opts *Options) compile() (err error) {
target, found := nameTarget[opts.Target]
if !found {
err = fmt.Errorf("invalid target: %q", opts.Target)
return
}
var loaders map[string]api.Loader
if opts.Loaders != nil {
loaders = make(map[string]api.Loader)
for k, v := range opts.Loaders {
loader, found := nameLoader[v]
if !found {
err = fmt.Errorf("invalid loader: %q", v)
return
}
loaders[k] = loader
}
}
mediaType := opts.MediaType
if mediaType.IsZero() {
mediaType = media.Builtin.JavascriptType
}
var loader api.Loader
switch mediaType.SubType {
case media.Builtin.JavascriptType.SubType:
loader = api.LoaderJS
case media.Builtin.TypeScriptType.SubType:
loader = api.LoaderTS
case media.Builtin.TSXType.SubType:
loader = api.LoaderTSX
case media.Builtin.JSXType.SubType:
loader = api.LoaderJSX
default:
err = fmt.Errorf("unsupported Media Type: %q", opts.MediaType)
return
}
var format api.Format
// One of: iife, cjs, esm
switch opts.Format {
case "", "iife":
format = api.FormatIIFE
case "esm":
format = api.FormatESModule
case "cjs":
format = api.FormatCommonJS
default:
err = fmt.Errorf("unsupported script output format: %q", opts.Format)
return
}
var jsx api.JSX
switch opts.JSX {
case "", "transform":
jsx = api.JSXTransform
case "preserve":
jsx = api.JSXPreserve
case "automatic":
jsx = api.JSXAutomatic
default:
err = fmt.Errorf("unsupported jsx type: %q", opts.JSX)
return
}
var defines map[string]string
if opts.Defines != nil {
defines = maps.ToStringMapString(opts.Defines)
}
// By default we only need to specify outDir and no outFile
outDir := opts.OutDir
outFile := ""
var sourceMap api.SourceMap
switch opts.SourceMap {
case "inline":
sourceMap = api.SourceMapInline
case "external":
sourceMap = api.SourceMapExternal
case "linked":
sourceMap = api.SourceMapLinked
case "", "none":
sourceMap = api.SourceMapNone
default:
err = fmt.Errorf("unsupported sourcemap type: %q", opts.SourceMap)
return
}
sourcesContent := api.SourcesContentInclude
if !opts.SourcesContent {
sourcesContent = api.SourcesContentExclude
}
opts.compiled = api.BuildOptions{
Outfile: outFile,
Bundle: true,
Metafile: opts.Metafile,
AbsWorkingDir: opts.AbsWorkingDir,
Target: target,
Format: format,
Sourcemap: sourceMap,
SourcesContent: sourcesContent,
Loader: loaders,
MinifyWhitespace: opts.Minify,
MinifyIdentifiers: opts.Minify,
MinifySyntax: opts.Minify,
Outdir: outDir,
Splitting: opts.Splitting,
Define: defines,
External: opts.Externals,
JSXFactory: opts.JSXFactory,
JSXFragment: opts.JSXFragment,
JSX: jsx,
JSXImportSource: opts.JSXImportSource,
Tsconfig: opts.TsConfig,
EntryPoints: opts.EntryPoints,
}
if opts.Stdin {
// This makes ESBuild pass `stdin` as the Importer to the import.
opts.compiled.Stdin = &api.StdinOptions{
Contents: opts.Contents,
ResolveDir: opts.ResolveDir,
Loader: loader,
}
}
return
}
func (o Options) loaderFromFilename(filename string) api.Loader {
ext := filepath.Ext(filename)
if optsLoaders := o.compiled.Loader; optsLoaders != nil {
if l, found := optsLoaders[ext]; found {
return l
}
}
l, found := extensionToLoaderMap[ext]
if found {
return l
}
return api.LoaderJS
}
func (opts *Options) validate() error {
if opts.ImportOnResolveFunc != nil && opts.ImportOnLoadFunc == nil {
return fmt.Errorf("ImportOnLoadFunc must be set if ImportOnResolveFunc is set")
}
if opts.ImportOnResolveFunc == nil && opts.ImportOnLoadFunc != nil {
return fmt.Errorf("ImportOnResolveFunc must be set if ImportOnLoadFunc is set")
}
if opts.AbsWorkingDir == "" {
return fmt.Errorf("AbsWorkingDir must be set")
}
return nil
}
|