-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
cli_impl.go
1383 lines (1240 loc) · 41.4 KB
/
cli_impl.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
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cli
import (
"errors"
"fmt"
"io/ioutil"
"net"
"os"
"sort"
"strconv"
"strings"
"github.com/evanw/esbuild/internal/cli_helpers"
"github.com/evanw/esbuild/internal/fs"
"github.com/evanw/esbuild/internal/logger"
"github.com/evanw/esbuild/pkg/api"
)
func newBuildOptions() api.BuildOptions {
return api.BuildOptions{
Banner: make(map[string]string),
Define: make(map[string]string),
Footer: make(map[string]string),
Loader: make(map[string]api.Loader),
LogOverride: make(map[string]api.LogLevel),
Supported: make(map[string]bool),
}
}
func newTransformOptions() api.TransformOptions {
return api.TransformOptions{
Define: make(map[string]string),
LogOverride: make(map[string]api.LogLevel),
Supported: make(map[string]bool),
}
}
type parseOptionsKind uint8
const (
// This means we're parsing it for our own internal use
kindInternal parseOptionsKind = iota
// This means the result is returned through a public API
kindExternal
)
type parseOptionsExtras struct {
metafile *string
mangleCache *string
}
func isBoolFlag(arg string, flag string) bool {
if strings.HasPrefix(arg, flag) {
remainder := arg[len(flag):]
return len(remainder) == 0 || remainder[0] == '='
}
return false
}
func parseBoolFlag(arg string, defaultValue bool) (bool, *cli_helpers.ErrorWithNote) {
equals := strings.IndexByte(arg, '=')
if equals == -1 {
return defaultValue, nil
}
value := arg[equals+1:]
switch value {
case "false":
return false, nil
case "true":
return true, nil
}
return false, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Invalid value %q in %q", value, arg),
"Valid values are \"true\" or \"false\".",
)
}
func parseOptionsImpl(
osArgs []string,
buildOpts *api.BuildOptions,
transformOpts *api.TransformOptions,
kind parseOptionsKind,
) (extras parseOptionsExtras, err *cli_helpers.ErrorWithNote) {
hasBareSourceMapFlag := false
// Parse the arguments now that we know what we're parsing
for _, arg := range osArgs {
switch {
case isBoolFlag(arg, "--bundle") && buildOpts != nil:
if value, err := parseBoolFlag(arg, true); err != nil {
return parseOptionsExtras{}, err
} else {
buildOpts.Bundle = value
}
case isBoolFlag(arg, "--preserve-symlinks") && buildOpts != nil:
if value, err := parseBoolFlag(arg, true); err != nil {
return parseOptionsExtras{}, err
} else {
buildOpts.PreserveSymlinks = value
}
case isBoolFlag(arg, "--splitting") && buildOpts != nil:
if value, err := parseBoolFlag(arg, true); err != nil {
return parseOptionsExtras{}, err
} else {
buildOpts.Splitting = value
}
case isBoolFlag(arg, "--allow-overwrite") && buildOpts != nil:
if value, err := parseBoolFlag(arg, true); err != nil {
return parseOptionsExtras{}, err
} else {
buildOpts.AllowOverwrite = value
}
case isBoolFlag(arg, "--watch") && buildOpts != nil:
if value, err := parseBoolFlag(arg, true); err != nil {
return parseOptionsExtras{}, err
} else if value {
buildOpts.Watch = &api.WatchMode{}
} else {
buildOpts.Watch = nil
}
case isBoolFlag(arg, "--minify"):
if value, err := parseBoolFlag(arg, true); err != nil {
return parseOptionsExtras{}, err
} else if buildOpts != nil {
buildOpts.MinifySyntax = value
buildOpts.MinifyWhitespace = value
buildOpts.MinifyIdentifiers = value
} else {
transformOpts.MinifySyntax = value
transformOpts.MinifyWhitespace = value
transformOpts.MinifyIdentifiers = value
}
case isBoolFlag(arg, "--minify-syntax"):
if value, err := parseBoolFlag(arg, true); err != nil {
return parseOptionsExtras{}, err
} else if buildOpts != nil {
buildOpts.MinifySyntax = value
} else {
transformOpts.MinifySyntax = value
}
case isBoolFlag(arg, "--minify-whitespace"):
if value, err := parseBoolFlag(arg, true); err != nil {
return parseOptionsExtras{}, err
} else if buildOpts != nil {
buildOpts.MinifyWhitespace = value
} else {
transformOpts.MinifyWhitespace = value
}
case isBoolFlag(arg, "--minify-identifiers"):
if value, err := parseBoolFlag(arg, true); err != nil {
return parseOptionsExtras{}, err
} else if buildOpts != nil {
buildOpts.MinifyIdentifiers = value
} else {
transformOpts.MinifyIdentifiers = value
}
case isBoolFlag(arg, "--mangle-quoted"):
if value, err := parseBoolFlag(arg, true); err != nil {
return parseOptionsExtras{}, err
} else {
var mangleQuoted *api.MangleQuoted
if buildOpts != nil {
mangleQuoted = &buildOpts.MangleQuoted
} else {
mangleQuoted = &transformOpts.MangleQuoted
}
if value {
*mangleQuoted = api.MangleQuotedTrue
} else {
*mangleQuoted = api.MangleQuotedFalse
}
}
case strings.HasPrefix(arg, "--mangle-props="):
value := arg[len("--mangle-props="):]
if buildOpts != nil {
buildOpts.MangleProps = value
} else {
transformOpts.MangleProps = value
}
case strings.HasPrefix(arg, "--reserve-props="):
value := arg[len("--reserve-props="):]
if buildOpts != nil {
buildOpts.ReserveProps = value
} else {
transformOpts.ReserveProps = value
}
case strings.HasPrefix(arg, "--mangle-cache=") && buildOpts != nil && kind == kindInternal:
value := arg[len("--mangle-cache="):]
extras.mangleCache = &value
case strings.HasPrefix(arg, "--drop:"):
value := arg[len("--drop:"):]
switch value {
case "console":
if buildOpts != nil {
buildOpts.Drop |= api.DropConsole
} else {
transformOpts.Drop |= api.DropConsole
}
case "debugger":
if buildOpts != nil {
buildOpts.Drop |= api.DropDebugger
} else {
transformOpts.Drop |= api.DropDebugger
}
default:
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Invalid value %q in %q", value, arg),
"Valid values are \"console\" or \"debugger\".",
)
}
case strings.HasPrefix(arg, "--legal-comments="):
value := arg[len("--legal-comments="):]
var legalComments api.LegalComments
switch value {
case "none":
legalComments = api.LegalCommentsNone
case "inline":
legalComments = api.LegalCommentsInline
case "eof":
legalComments = api.LegalCommentsEndOfFile
case "linked":
legalComments = api.LegalCommentsLinked
case "external":
legalComments = api.LegalCommentsExternal
default:
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Invalid value %q in %q", value, arg),
"Valid values are \"none\", \"inline\", \"eof\", \"linked\", or \"external\".",
)
}
if buildOpts != nil {
buildOpts.LegalComments = legalComments
} else {
transformOpts.LegalComments = legalComments
}
case strings.HasPrefix(arg, "--charset="):
var value *api.Charset
if buildOpts != nil {
value = &buildOpts.Charset
} else {
value = &transformOpts.Charset
}
name := arg[len("--charset="):]
switch name {
case "ascii":
*value = api.CharsetASCII
case "utf8":
*value = api.CharsetUTF8
default:
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Invalid value %q in %q", name, arg),
"Valid values are \"ascii\" or \"utf8\".",
)
}
case isBoolFlag(arg, "--tree-shaking"):
if value, err := parseBoolFlag(arg, true); err != nil {
return parseOptionsExtras{}, err
} else {
var treeShaking *api.TreeShaking
if buildOpts != nil {
treeShaking = &buildOpts.TreeShaking
} else {
treeShaking = &transformOpts.TreeShaking
}
if value {
*treeShaking = api.TreeShakingTrue
} else {
*treeShaking = api.TreeShakingFalse
}
}
case isBoolFlag(arg, "--ignore-annotations"):
if value, err := parseBoolFlag(arg, true); err != nil {
return parseOptionsExtras{}, err
} else if buildOpts != nil {
buildOpts.IgnoreAnnotations = value
} else {
transformOpts.IgnoreAnnotations = value
}
case isBoolFlag(arg, "--keep-names"):
if value, err := parseBoolFlag(arg, true); err != nil {
return parseOptionsExtras{}, err
} else if buildOpts != nil {
buildOpts.KeepNames = value
} else {
transformOpts.KeepNames = value
}
case arg == "--sourcemap":
if buildOpts != nil {
buildOpts.Sourcemap = api.SourceMapLinked
} else {
transformOpts.Sourcemap = api.SourceMapInline
}
hasBareSourceMapFlag = true
case strings.HasPrefix(arg, "--sourcemap="):
value := arg[len("--sourcemap="):]
var sourcemap api.SourceMap
switch value {
case "linked":
sourcemap = api.SourceMapLinked
case "inline":
sourcemap = api.SourceMapInline
case "external":
sourcemap = api.SourceMapExternal
case "both":
sourcemap = api.SourceMapInlineAndExternal
default:
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Invalid value %q in %q", value, arg),
"Valid values are \"inline\", \"external\", or \"both\".",
)
}
if buildOpts != nil {
buildOpts.Sourcemap = sourcemap
} else {
transformOpts.Sourcemap = sourcemap
}
hasBareSourceMapFlag = false
case strings.HasPrefix(arg, "--source-root="):
sourceRoot := arg[len("--source-root="):]
if buildOpts != nil {
buildOpts.SourceRoot = sourceRoot
} else {
transformOpts.SourceRoot = sourceRoot
}
case isBoolFlag(arg, "--sources-content"):
if value, err := parseBoolFlag(arg, true); err != nil {
return parseOptionsExtras{}, err
} else {
var sourcesContent *api.SourcesContent
if buildOpts != nil {
sourcesContent = &buildOpts.SourcesContent
} else {
sourcesContent = &transformOpts.SourcesContent
}
if value {
*sourcesContent = api.SourcesContentInclude
} else {
*sourcesContent = api.SourcesContentExclude
}
}
case strings.HasPrefix(arg, "--sourcefile="):
if buildOpts != nil {
if buildOpts.Stdin == nil {
buildOpts.Stdin = &api.StdinOptions{}
}
buildOpts.Stdin.Sourcefile = arg[len("--sourcefile="):]
} else {
transformOpts.Sourcefile = arg[len("--sourcefile="):]
}
case strings.HasPrefix(arg, "--resolve-extensions=") && buildOpts != nil:
buildOpts.ResolveExtensions = splitWithEmptyCheck(arg[len("--resolve-extensions="):], ",")
case strings.HasPrefix(arg, "--main-fields=") && buildOpts != nil:
buildOpts.MainFields = splitWithEmptyCheck(arg[len("--main-fields="):], ",")
case strings.HasPrefix(arg, "--conditions=") && buildOpts != nil:
buildOpts.Conditions = splitWithEmptyCheck(arg[len("--conditions="):], ",")
case strings.HasPrefix(arg, "--public-path=") && buildOpts != nil:
buildOpts.PublicPath = arg[len("--public-path="):]
case strings.HasPrefix(arg, "--global-name="):
if buildOpts != nil {
buildOpts.GlobalName = arg[len("--global-name="):]
} else {
transformOpts.GlobalName = arg[len("--global-name="):]
}
case arg == "--metafile" && buildOpts != nil && kind == kindExternal:
buildOpts.Metafile = true
case strings.HasPrefix(arg, "--metafile=") && buildOpts != nil && kind == kindInternal:
value := arg[len("--metafile="):]
buildOpts.Metafile = true
extras.metafile = &value
case strings.HasPrefix(arg, "--outfile=") && buildOpts != nil:
buildOpts.Outfile = arg[len("--outfile="):]
case strings.HasPrefix(arg, "--outdir=") && buildOpts != nil:
buildOpts.Outdir = arg[len("--outdir="):]
case strings.HasPrefix(arg, "--outbase=") && buildOpts != nil:
buildOpts.Outbase = arg[len("--outbase="):]
case strings.HasPrefix(arg, "--tsconfig=") && buildOpts != nil:
buildOpts.Tsconfig = arg[len("--tsconfig="):]
case strings.HasPrefix(arg, "--tsconfig-raw=") && transformOpts != nil:
transformOpts.TsconfigRaw = arg[len("--tsconfig-raw="):]
case strings.HasPrefix(arg, "--entry-names=") && buildOpts != nil:
buildOpts.EntryNames = arg[len("--entry-names="):]
case strings.HasPrefix(arg, "--chunk-names=") && buildOpts != nil:
buildOpts.ChunkNames = arg[len("--chunk-names="):]
case strings.HasPrefix(arg, "--asset-names=") && buildOpts != nil:
buildOpts.AssetNames = arg[len("--asset-names="):]
case strings.HasPrefix(arg, "--define:"):
value := arg[len("--define:"):]
equals := strings.IndexByte(value, '=')
if equals == -1 {
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Missing \"=\" in %q", arg),
"You need to use \"=\" to specify both the original value and the replacement value. "+
"For example, \"--define:DEBUG=true\" replaces \"DEBUG\" with \"true\".",
)
}
if buildOpts != nil {
buildOpts.Define[value[:equals]] = value[equals+1:]
} else {
transformOpts.Define[value[:equals]] = value[equals+1:]
}
case strings.HasPrefix(arg, "--log-override:"):
value := arg[len("--log-override:"):]
equals := strings.IndexByte(value, '=')
if equals == -1 {
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Missing \"=\" in %q", arg),
"You need to use \"=\" to specify both the message name and the log level. "+
"For example, \"--log-override:css-syntax-error=error\" turns all \"css-syntax-error\" log messages into errors.",
)
}
logLevel, err := parseLogLevel(value[equals+1:], arg)
if err != nil {
return parseOptionsExtras{}, err
}
if buildOpts != nil {
buildOpts.LogOverride[value[:equals]] = logLevel
} else {
transformOpts.LogOverride[value[:equals]] = logLevel
}
case strings.HasPrefix(arg, "--supported:"):
value := arg[len("--supported:"):]
equals := strings.IndexByte(value, '=')
if equals == -1 {
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Missing \"=\" in %q", arg),
"You need to use \"=\" to specify both the name of the feature and whether it is supported or not. "+
"For example, \"--supported:arrow=false\" marks arrow functions as unsupported.",
)
}
if isSupported, err := parseBoolFlag(arg, true); err != nil {
return parseOptionsExtras{}, err
} else if buildOpts != nil {
buildOpts.Supported[value[:equals]] = isSupported
} else {
transformOpts.Supported[value[:equals]] = isSupported
}
case strings.HasPrefix(arg, "--pure:"):
value := arg[len("--pure:"):]
if buildOpts != nil {
buildOpts.Pure = append(buildOpts.Pure, value)
} else {
transformOpts.Pure = append(transformOpts.Pure, value)
}
case strings.HasPrefix(arg, "--loader:") && buildOpts != nil:
value := arg[len("--loader:"):]
equals := strings.IndexByte(value, '=')
if equals == -1 {
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Missing \"=\" in %q", arg),
"You need to specify the file extension that the loader applies to. "+
"For example, \"--loader:.js=jsx\" applies the \"jsx\" loader to files with the \".js\" extension.",
)
}
ext, text := value[:equals], value[equals+1:]
loader, err := cli_helpers.ParseLoader(text)
if err != nil {
return parseOptionsExtras{}, err
}
buildOpts.Loader[ext] = loader
case strings.HasPrefix(arg, "--loader="):
value := arg[len("--loader="):]
loader, err := cli_helpers.ParseLoader(value)
if err != nil {
return parseOptionsExtras{}, err
}
if loader == api.LoaderFile || loader == api.LoaderCopy {
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("%q is not supported when transforming stdin", arg),
fmt.Sprintf("Using esbuild to transform stdin only generates one output file, so you cannot use the %q loader "+
"since that needs to generate two output files.", value),
)
}
if buildOpts != nil {
if buildOpts.Stdin == nil {
buildOpts.Stdin = &api.StdinOptions{}
}
buildOpts.Stdin.Loader = loader
} else {
transformOpts.Loader = loader
}
case strings.HasPrefix(arg, "--target="):
target, engines, err := parseTargets(splitWithEmptyCheck(arg[len("--target="):], ","), arg)
if err != nil {
return parseOptionsExtras{}, err
}
if buildOpts != nil {
buildOpts.Target = target
buildOpts.Engines = engines
} else {
transformOpts.Target = target
transformOpts.Engines = engines
}
case strings.HasPrefix(arg, "--out-extension:") && buildOpts != nil:
value := arg[len("--out-extension:"):]
equals := strings.IndexByte(value, '=')
if equals == -1 {
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Missing \"=\" in %q", arg),
"You need to use either \"--out-extension:.js=...\" or \"--out-extension:.css=...\" "+
"to specify the file type that the output extension applies to .",
)
}
if buildOpts.OutExtensions == nil {
buildOpts.OutExtensions = make(map[string]string)
}
buildOpts.OutExtensions[value[:equals]] = value[equals+1:]
case strings.HasPrefix(arg, "--platform=") && buildOpts != nil:
value := arg[len("--platform="):]
switch value {
case "browser":
buildOpts.Platform = api.PlatformBrowser
case "node":
buildOpts.Platform = api.PlatformNode
case "neutral":
buildOpts.Platform = api.PlatformNeutral
default:
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Invalid value %q in %q", value, arg),
"Valid values are \"browser\", \"node\", or \"neutral\".",
)
}
case strings.HasPrefix(arg, "--format="):
value := arg[len("--format="):]
switch value {
case "iife":
if buildOpts != nil {
buildOpts.Format = api.FormatIIFE
} else {
transformOpts.Format = api.FormatIIFE
}
case "cjs":
if buildOpts != nil {
buildOpts.Format = api.FormatCommonJS
} else {
transformOpts.Format = api.FormatCommonJS
}
case "esm":
if buildOpts != nil {
buildOpts.Format = api.FormatESModule
} else {
transformOpts.Format = api.FormatESModule
}
default:
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Invalid value %q in %q", value, arg),
"Valid values are \"iife\", \"cjs\", or \"esm\".",
)
}
case strings.HasPrefix(arg, "--external:") && buildOpts != nil:
buildOpts.External = append(buildOpts.External, arg[len("--external:"):])
case strings.HasPrefix(arg, "--inject:") && buildOpts != nil:
buildOpts.Inject = append(buildOpts.Inject, arg[len("--inject:"):])
case strings.HasPrefix(arg, "--jsx="):
value := arg[len("--jsx="):]
var mode api.JSXMode
switch value {
case "transform":
mode = api.JSXModeTransform
case "preserve":
mode = api.JSXModePreserve
default:
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Invalid value %q in %q", value, arg),
"Valid values are \"transform\" or \"preserve\".",
)
}
if buildOpts != nil {
buildOpts.JSXMode = mode
} else {
transformOpts.JSXMode = mode
}
case strings.HasPrefix(arg, "--jsx-factory="):
value := arg[len("--jsx-factory="):]
if buildOpts != nil {
buildOpts.JSXFactory = value
} else {
transformOpts.JSXFactory = value
}
case strings.HasPrefix(arg, "--jsx-fragment="):
value := arg[len("--jsx-fragment="):]
if buildOpts != nil {
buildOpts.JSXFragment = value
} else {
transformOpts.JSXFragment = value
}
case strings.HasPrefix(arg, "--banner=") && transformOpts != nil:
transformOpts.Banner = arg[len("--banner="):]
case strings.HasPrefix(arg, "--footer=") && transformOpts != nil:
transformOpts.Footer = arg[len("--footer="):]
case strings.HasPrefix(arg, "--banner:") && buildOpts != nil:
value := arg[len("--banner:"):]
equals := strings.IndexByte(value, '=')
if equals == -1 {
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Missing \"=\" in %q", arg),
"You need to use either \"--banner:js=...\" or \"--banner:css=...\" to specify the language that the banner applies to.",
)
}
buildOpts.Banner[value[:equals]] = value[equals+1:]
case strings.HasPrefix(arg, "--footer:") && buildOpts != nil:
value := arg[len("--footer:"):]
equals := strings.IndexByte(value, '=')
if equals == -1 {
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Missing \"=\" in %q", arg),
"You need to use either \"--footer:js=...\" or \"--footer:css=...\" to specify the language that the footer applies to.",
)
}
buildOpts.Footer[value[:equals]] = value[equals+1:]
case strings.HasPrefix(arg, "--log-limit="):
value := arg[len("--log-limit="):]
limit, err := strconv.Atoi(value)
if err != nil || limit < 0 {
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Invalid value %q in %q", value, arg),
"The log limit must be a non-negative integer.",
)
}
if buildOpts != nil {
buildOpts.LogLimit = limit
} else {
transformOpts.LogLimit = limit
}
// Make sure this stays in sync with "PrintErrorToStderr"
case isBoolFlag(arg, "--color"):
if value, err := parseBoolFlag(arg, true); err != nil {
return parseOptionsExtras{}, err
} else {
var color *api.StderrColor
if buildOpts != nil {
color = &buildOpts.Color
} else {
color = &transformOpts.Color
}
if value {
*color = api.ColorAlways
} else {
*color = api.ColorNever
}
}
// Make sure this stays in sync with "PrintErrorToStderr"
case strings.HasPrefix(arg, "--log-level="):
value := arg[len("--log-level="):]
logLevel, err := parseLogLevel(value, arg)
if err != nil {
return parseOptionsExtras{}, err
}
if buildOpts != nil {
buildOpts.LogLevel = logLevel
} else {
transformOpts.LogLevel = logLevel
}
case strings.HasPrefix(arg, "'--"):
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Unexpected single quote character before flag: %s", arg),
"This typically happens when attempting to use single quotes to quote arguments with a shell that doesn't recognize single quotes. "+
"Try using double quote characters to quote arguments instead.",
)
case !strings.HasPrefix(arg, "-") && buildOpts != nil:
if equals := strings.IndexByte(arg, '='); equals != -1 {
buildOpts.EntryPointsAdvanced = append(buildOpts.EntryPointsAdvanced, api.EntryPoint{
OutputPath: arg[:equals],
InputPath: arg[equals+1:],
})
} else {
buildOpts.EntryPoints = append(buildOpts.EntryPoints, arg)
}
default:
bare := map[string]bool{
"allow-overwrite": true,
"bundle": true,
"ignore-annotations": true,
"keep-names": true,
"minify-identifiers": true,
"minify-syntax": true,
"minify-whitespace": true,
"minify": true,
"preserve-symlinks": true,
"sourcemap": true,
"splitting": true,
"watch": true,
}
equals := map[string]bool{
"allow-overwrite": true,
"asset-names": true,
"banner": true,
"bundle": true,
"charset": true,
"chunk-names": true,
"color": true,
"conditions": true,
"entry-names": true,
"footer": true,
"format": true,
"global-name": true,
"ignore-annotations": true,
"jsx-factory": true,
"jsx-fragment": true,
"jsx": true,
"keep-names": true,
"legal-comments": true,
"loader": true,
"log-level": true,
"log-limit": true,
"main-fields": true,
"mangle-cache": true,
"mangle-props": true,
"mangle-quoted": true,
"metafile": true,
"minify-identifiers": true,
"minify-syntax": true,
"minify-whitespace": true,
"minify": true,
"outbase": true,
"outdir": true,
"outfile": true,
"platform": true,
"preserve-symlinks": true,
"public-path": true,
"reserve-props": true,
"resolve-extensions": true,
"source-root": true,
"sourcefile": true,
"sourcemap": true,
"sources-content": true,
"splitting": true,
"target": true,
"tree-shaking": true,
"tsconfig-raw": true,
"tsconfig": true,
"watch": true,
}
colon := map[string]bool{
"banner": true,
"define": true,
"drop": true,
"external": true,
"footer": true,
"inject": true,
"loader": true,
"log-override": true,
"out-extension": true,
"pure": true,
"supported": true,
}
note := ""
// Try to provide helpful hints when we can recognize the mistake
switch {
case arg == "-o":
note = "Use \"--outfile=\" to configure the output file instead of \"-o\"."
case arg == "-v":
note = "Use \"--log-level=verbose\" to generate verbose logs instead of \"-v\"."
case strings.HasPrefix(arg, "--"):
if i := strings.IndexByte(arg, '='); i != -1 && colon[arg[2:i]] {
note = fmt.Sprintf("Use %q instead of %q. Flags that can be re-specified multiple times use \":\" instead of \"=\".",
arg[:i]+":"+arg[i+1:], arg)
}
if i := strings.IndexByte(arg, ':'); i != -1 && equals[arg[2:i]] {
note = fmt.Sprintf("Use %q instead of %q. Flags that can only be specified once use \"=\" instead of \":\".",
arg[:i]+"="+arg[i+1:], arg)
}
case strings.HasPrefix(arg, "-"):
isValid := bare[arg[1:]]
fix := "-" + arg
if i := strings.IndexByte(arg, '='); i != -1 && equals[arg[1:i]] {
isValid = true
} else if i != -1 && colon[arg[1:i]] {
isValid = true
fix = fmt.Sprintf("-%s:%s", arg[:i], arg[i+1:])
} else if i := strings.IndexByte(arg, ':'); i != -1 && colon[arg[1:i]] {
isValid = true
} else if i != -1 && equals[arg[1:i]] {
isValid = true
fix = fmt.Sprintf("-%s=%s", arg[:i], arg[i+1:])
}
if isValid {
note = fmt.Sprintf("Use %q instead of %q. Flags are always specified with two dashes instead of one dash.",
fix, arg)
}
}
if buildOpts != nil {
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(fmt.Sprintf("Invalid build flag: %q", arg), note)
} else {
return parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(fmt.Sprintf("Invalid transform flag: %q", arg), note)
}
}
}
// If we're building, the last source map flag is "--sourcemap", and there
// is no output path, change the source map option to "inline" because we're
// going to be writing to stdout which can only represent a single file.
if buildOpts != nil && hasBareSourceMapFlag && buildOpts.Outfile == "" && buildOpts.Outdir == "" {
buildOpts.Sourcemap = api.SourceMapInline
}
return
}
func parseTargets(targets []string, arg string) (target api.Target, engines []api.Engine, err *cli_helpers.ErrorWithNote) {
validTargets := map[string]api.Target{
"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,
}
outer:
for _, value := range targets {
if valid, ok := validTargets[strings.ToLower(value)]; ok {
target = valid
continue
}
for engine, name := range validEngines {
if strings.HasPrefix(value, engine) {
version := value[len(engine):]
if version == "" {
return 0, nil, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Target %q is missing a version number in %q", value, arg),
"",
)
}
engines = append(engines, api.Engine{Name: name, Version: version})
continue outer
}
}
engines := make([]string, 0, len(validEngines))
engines = append(engines, "\"esN\"")
for key := range validEngines {
engines = append(engines, fmt.Sprintf("%q", key+"N"))
}
sort.Strings(engines)
return 0, nil, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Invalid target %q in %q", value, arg),
fmt.Sprintf("Valid values are %s, or %s where N is a version number.",
strings.Join(engines[:len(engines)-1], ", "), engines[len(engines)-1]),
)
}
return
}
// This returns either BuildOptions, TransformOptions, or an error
func parseOptionsForRun(osArgs []string) (*api.BuildOptions, *api.TransformOptions, parseOptionsExtras, *cli_helpers.ErrorWithNote) {
// If there's an entry point or we're bundling, then we're building
for _, arg := range osArgs {
if !strings.HasPrefix(arg, "-") || arg == "--bundle" {
options := newBuildOptions()
// Apply defaults appropriate for the CLI
options.LogLimit = 6
options.LogLevel = api.LogLevelInfo
options.Write = true
extras, err := parseOptionsImpl(osArgs, &options, nil, kindInternal)
if err != nil {
return nil, nil, parseOptionsExtras{}, err
}
return &options, nil, extras, nil
}
}
// Otherwise, we're transforming
options := newTransformOptions()
// Apply defaults appropriate for the CLI
options.LogLimit = 6
options.LogLevel = api.LogLevelInfo
_, err := parseOptionsImpl(osArgs, nil, &options, kindInternal)
if err != nil {
return nil, nil, parseOptionsExtras{}, err
}
if options.Sourcemap != api.SourceMapNone && options.Sourcemap != api.SourceMapInline {
var sourceMapMode string
switch options.Sourcemap {
case api.SourceMapExternal:
sourceMapMode = "external"
case api.SourceMapInlineAndExternal:
sourceMapMode = "both"
case api.SourceMapLinked:
sourceMapMode = "linked"
}
return nil, nil, parseOptionsExtras{}, cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Use \"--sourcemap\" instead of \"--sourcemap=%s\" when transforming stdin", sourceMapMode),
fmt.Sprintf("Using esbuild to transform stdin only generates one output file. You cannot use the %q source map mode "+
"since that needs to generate two output files.", sourceMapMode),
)
}
return nil, &options, parseOptionsExtras{}, nil
}
func splitWithEmptyCheck(s string, sep string) []string {
// Special-case the empty string to return [] instead of [""]
if s == "" {
return []string{}
}
return strings.Split(s, sep)
}
func runImpl(osArgs []string) int {
analyze := false
analyzeVerbose := false
end := 0
for _, arg := range osArgs {
// Special-case running a server
if arg == "--serve" || strings.HasPrefix(arg, "--serve=") || strings.HasPrefix(arg, "--servedir=") {
if err := serveImpl(osArgs); err != nil {
logger.PrintErrorToStderr(osArgs, err.Error())
return 1
}
return 0
}
// Special-case analyze just for our CLI
if arg == "--analyze" {