-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
linker.go
6570 lines (5804 loc) · 235 KB
/
linker.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 linker
// This package implements the second phase of the bundling operation that
// generates the output files when given a module graph. It has been split off
// into separate package to allow two linkers to cleanly exist in the same code
// base. This will be useful when rewriting the linker because the new one can
// be off by default to minimize disruption, but can still be enabled by anyone
// to assist in giving feedback on the rewrite.
import (
"bytes"
"encoding/base64"
"encoding/binary"
"fmt"
"hash"
"path"
"sort"
"strconv"
"strings"
"sync"
"github.com/evanw/esbuild/internal/ast"
"github.com/evanw/esbuild/internal/bundler"
"github.com/evanw/esbuild/internal/compat"
"github.com/evanw/esbuild/internal/config"
"github.com/evanw/esbuild/internal/css_ast"
"github.com/evanw/esbuild/internal/css_lexer"
"github.com/evanw/esbuild/internal/css_parser"
"github.com/evanw/esbuild/internal/css_printer"
"github.com/evanw/esbuild/internal/fs"
"github.com/evanw/esbuild/internal/graph"
"github.com/evanw/esbuild/internal/helpers"
"github.com/evanw/esbuild/internal/js_ast"
"github.com/evanw/esbuild/internal/js_lexer"
"github.com/evanw/esbuild/internal/js_printer"
"github.com/evanw/esbuild/internal/logger"
"github.com/evanw/esbuild/internal/renamer"
"github.com/evanw/esbuild/internal/resolver"
"github.com/evanw/esbuild/internal/runtime"
"github.com/evanw/esbuild/internal/sourcemap"
"github.com/evanw/esbuild/internal/xxhash"
)
type linkerContext struct {
options *config.Options
timer *helpers.Timer
log logger.Log
fs fs.FS
res *resolver.Resolver
graph graph.LinkerGraph
chunks []chunkInfo
// This helps avoid an infinite loop when matching imports to exports
cycleDetector []importTracker
// This represents the parallel computation of source map related data.
// Calling this will block until the computation is done. The resulting value
// is shared between threads and must be treated as immutable.
dataForSourceMaps func() []bundler.DataForSourceMap
// This is passed to us from the bundling phase
uniqueKeyPrefix string
uniqueKeyPrefixBytes []byte // This is just "uniqueKeyPrefix" in byte form
// Property mangling results go here
mangledProps map[ast.Ref]string
// We may need to refer to the CommonJS "module" symbol for exports
unboundModuleRef ast.Ref
// We may need to refer to the "__esm" and/or "__commonJS" runtime symbols
cjsRuntimeRef ast.Ref
esmRuntimeRef ast.Ref
}
type partRange struct {
sourceIndex uint32
partIndexBegin uint32
partIndexEnd uint32
}
type chunkInfo struct {
// This is a random string and is used to represent the output path of this
// chunk before the final output path has been computed.
uniqueKey string
filesWithPartsInChunk map[uint32]bool
entryBits helpers.BitSet
// For code splitting
crossChunkImports []chunkImport
// This is the representation-specific information
chunkRepr chunkRepr
// This is the final path of this chunk relative to the output directory, but
// without the substitution of the final hash (since it hasn't been computed).
finalTemplate []config.PathTemplate
// This is the final path of this chunk relative to the output directory. It
// is the substitution of the final hash into "finalTemplate".
finalRelPath string
// If non-empty, this chunk needs to generate an external legal comments file.
externalLegalComments []byte
// This contains the hash for just this chunk without including information
// from the hashes of other chunks. Later on in the linking process, the
// final hash for this chunk will be constructed by merging the isolated
// hashes of all transitive dependencies of this chunk. This is separated
// into two phases like this to handle cycles in the chunk import graph.
waitForIsolatedHash func() []byte
// Other fields relating to the output file for this chunk
jsonMetadataChunkCallback func(finalOutputSize int) helpers.Joiner
outputSourceMap sourcemap.SourceMapPieces
// When this chunk is initially generated in isolation, the output pieces
// will contain slices of the output with the unique keys of other chunks
// omitted.
intermediateOutput intermediateOutput
// This information is only useful if "isEntryPoint" is true
entryPointBit uint // An index into "c.graph.EntryPoints"
sourceIndex uint32 // An index into "c.sources"
isEntryPoint bool
isExecutable bool
}
type chunkImport struct {
chunkIndex uint32
importKind ast.ImportKind
}
type outputPieceIndexKind uint8
const (
outputPieceNone outputPieceIndexKind = iota
outputPieceAssetIndex
outputPieceChunkIndex
)
// This is a chunk of source code followed by a reference to another chunk. For
// example, the file "@import 'CHUNK0001'; body { color: black; }" would be
// represented by two pieces, one with the data "@import '" and another with the
// data "'; body { color: black; }". The first would have the chunk index 1 and
// the second would have an invalid chunk index.
type outputPiece struct {
data []byte
// Note: The "kind" may be "outputPieceNone" in which case there is one piece
// with data and no chunk index. For example, the chunk may not contain any
// imports.
index uint32
kind outputPieceIndexKind
}
type intermediateOutput struct {
// If the chunk has references to other chunks, then "pieces" contains the
// contents of the chunk and "joiner" should not be used. Another joiner
// will have to be constructed later when merging the pieces together.
pieces []outputPiece
// If the chunk doesn't have any references to other chunks, then "pieces" is
// nil and "joiner" contains the contents of the chunk. This is more efficient
// because it avoids doing a join operation twice.
joiner helpers.Joiner
}
type chunkRepr interface{ isChunk() }
func (*chunkReprJS) isChunk() {}
func (*chunkReprCSS) isChunk() {}
type chunkReprJS struct {
filesInChunkInOrder []uint32
partsInChunkInOrder []partRange
// For code splitting
exportsToOtherChunks map[ast.Ref]string
importsFromOtherChunks map[uint32]crossChunkImportItemArray
crossChunkPrefixStmts []js_ast.Stmt
crossChunkSuffixStmts []js_ast.Stmt
cssChunkIndex uint32
hasCSSChunk bool
}
type chunkReprCSS struct {
externalImportsInOrder []externalImportCSS
filesInChunkInOrder []uint32
}
type externalImportCSS struct {
path logger.Path
conditions []css_ast.Token
conditionImportRecords []ast.ImportRecord
}
// Returns a log where "log.HasErrors()" only returns true if any errors have
// been logged since this call. This is useful when there have already been
// errors logged by other linkers that share the same log.
func wrappedLog(log logger.Log) logger.Log {
var mutex sync.Mutex
var hasErrors bool
addMsg := log.AddMsg
log.AddMsg = func(msg logger.Msg) {
if msg.Kind == logger.Error {
mutex.Lock()
defer mutex.Unlock()
hasErrors = true
}
addMsg(msg)
}
log.HasErrors = func() bool {
mutex.Lock()
defer mutex.Unlock()
return hasErrors
}
return log
}
func Link(
options *config.Options,
timer *helpers.Timer,
log logger.Log,
fs fs.FS,
res *resolver.Resolver,
inputFiles []graph.InputFile,
entryPoints []graph.EntryPoint,
uniqueKeyPrefix string,
reachableFiles []uint32,
dataForSourceMaps func() []bundler.DataForSourceMap,
) []graph.OutputFile {
timer.Begin("Link")
defer timer.End("Link")
log = wrappedLog(log)
timer.Begin("Clone linker graph")
c := linkerContext{
options: options,
timer: timer,
log: log,
fs: fs,
res: res,
dataForSourceMaps: dataForSourceMaps,
uniqueKeyPrefix: uniqueKeyPrefix,
uniqueKeyPrefixBytes: []byte(uniqueKeyPrefix),
graph: graph.CloneLinkerGraph(
inputFiles,
reachableFiles,
entryPoints,
options.CodeSplitting,
),
}
timer.End("Clone linker graph")
// Use a smaller version of these functions if we don't need profiler names
runtimeRepr := c.graph.Files[runtime.SourceIndex].InputFile.Repr.(*graph.JSRepr)
if c.options.ProfilerNames {
c.cjsRuntimeRef = runtimeRepr.AST.NamedExports["__commonJS"].Ref
c.esmRuntimeRef = runtimeRepr.AST.NamedExports["__esm"].Ref
} else {
c.cjsRuntimeRef = runtimeRepr.AST.NamedExports["__commonJSMin"].Ref
c.esmRuntimeRef = runtimeRepr.AST.NamedExports["__esmMin"].Ref
}
var additionalFiles []graph.OutputFile
for _, entryPoint := range entryPoints {
file := &c.graph.Files[entryPoint.SourceIndex].InputFile
switch repr := file.Repr.(type) {
case *graph.JSRepr:
// Loaders default to CommonJS when they are the entry point and the output
// format is not ESM-compatible since that avoids generating the ESM-to-CJS
// machinery.
if repr.AST.HasLazyExport && (c.options.Mode == config.ModePassThrough ||
(c.options.Mode == config.ModeConvertFormat && !c.options.OutputFormat.KeepESMImportExportSyntax())) {
repr.AST.ExportsKind = js_ast.ExportsCommonJS
}
// Entry points with ES6 exports must generate an exports object when
// targeting non-ES6 formats. Note that the IIFE format only needs this
// when the global name is present, since that's the only way the exports
// can actually be observed externally.
if repr.AST.ExportKeyword.Len > 0 && (options.OutputFormat == config.FormatCommonJS ||
(options.OutputFormat == config.FormatIIFE && len(options.GlobalName) > 0)) {
repr.AST.UsesExportsRef = true
repr.Meta.ForceIncludeExportsForEntryPoint = true
}
case *graph.CopyRepr:
// If an entry point uses the copy loader, then copy the file manually
// here. Other uses of the copy loader will automatically be included
// along with the corresponding bundled chunk but that doesn't happen
// for entry points.
additionalFiles = append(additionalFiles, file.AdditionalFiles...)
}
}
// Allocate a new unbound symbol called "module" in case we need it later
if c.options.OutputFormat == config.FormatCommonJS {
c.unboundModuleRef = c.graph.GenerateNewSymbol(runtime.SourceIndex, ast.SymbolUnbound, "module")
} else {
c.unboundModuleRef = ast.InvalidRef
}
c.scanImportsAndExports()
// Stop now if there were errors
if c.log.HasErrors() {
c.options.ExclusiveMangleCacheUpdate(func(mangleCache map[string]interface{}) {
// Always do this so that we don't cause other entry points when there are errors
})
return []graph.OutputFile{}
}
c.treeShakingAndCodeSplitting()
if c.options.Mode == config.ModePassThrough {
for _, entryPoint := range c.graph.EntryPoints() {
c.preventExportsFromBeingRenamed(entryPoint.SourceIndex)
}
}
c.computeChunks()
c.computeCrossChunkDependencies()
// Merge mangled properties before chunks are generated since the names must
// be consistent across all chunks, or the generated code will break
c.timer.Begin("Waiting for mangle cache")
c.options.ExclusiveMangleCacheUpdate(func(mangleCache map[string]interface{}) {
c.timer.End("Waiting for mangle cache")
c.mangleProps(mangleCache)
c.mangleLocalCSS()
})
// Make sure calls to "ast.FollowSymbols()" in parallel goroutines after this
// won't hit concurrent map mutation hazards
ast.FollowAllSymbols(c.graph.Symbols)
return c.generateChunksInParallel(additionalFiles)
}
func (c *linkerContext) mangleProps(mangleCache map[string]interface{}) {
c.timer.Begin("Mangle props")
defer c.timer.End("Mangle props")
mangledProps := make(map[ast.Ref]string)
c.mangledProps = mangledProps
// Reserve all JS keywords
reservedProps := make(map[string]bool)
for keyword := range js_lexer.Keywords {
reservedProps[keyword] = true
}
// Reserve all target properties in the cache
for original, remapped := range mangleCache {
if remapped == false {
reservedProps[original] = true
} else {
reservedProps[remapped.(string)] = true
}
}
// Merge all mangled property symbols together
freq := ast.CharFreq{}
mergedProps := make(map[string]ast.Ref)
for _, sourceIndex := range c.graph.ReachableFiles {
// Don't mangle anything in the runtime code
if sourceIndex == runtime.SourceIndex {
continue
}
// For each file
if repr, ok := c.graph.Files[sourceIndex].InputFile.Repr.(*graph.JSRepr); ok {
// Reserve all non-mangled properties
for prop := range repr.AST.ReservedProps {
reservedProps[prop] = true
}
// Merge each mangled property with other ones of the same name
for name, ref := range repr.AST.MangledProps {
if existing, ok := mergedProps[name]; ok {
ast.MergeSymbols(c.graph.Symbols, ref, existing)
} else {
mergedProps[name] = ref
}
}
// Include this file's frequency histogram, which affects the mangled names
if repr.AST.CharFreq != nil {
freq.Include(repr.AST.CharFreq)
}
}
}
// Sort by use count (note: does not currently account for live vs. dead code)
sorted := make(renamer.StableSymbolCountArray, 0, len(mergedProps))
stableSourceIndices := c.graph.StableSourceIndices
for _, ref := range mergedProps {
sorted = append(sorted, renamer.StableSymbolCount{
StableSourceIndex: stableSourceIndices[ref.SourceIndex],
Ref: ref,
Count: c.graph.Symbols.Get(ref).UseCountEstimate,
})
}
sort.Sort(sorted)
// Assign names in order of use count
minifier := ast.DefaultNameMinifierJS.ShuffleByCharFreq(freq)
nextName := 0
for _, symbolCount := range sorted {
symbol := c.graph.Symbols.Get(symbolCount.Ref)
// Don't change existing mappings
if existing, ok := mangleCache[symbol.OriginalName]; ok {
if existing != false {
mangledProps[symbolCount.Ref] = existing.(string)
}
continue
}
// Generate a new name
name := minifier.NumberToMinifiedName(nextName)
nextName++
// Avoid reserved properties
for reservedProps[name] {
name = minifier.NumberToMinifiedName(nextName)
nextName++
}
// Track the new mapping
if mangleCache != nil {
mangleCache[symbol.OriginalName] = name
}
mangledProps[symbolCount.Ref] = name
}
}
func (c *linkerContext) mangleLocalCSS() {
c.timer.Begin("Mangle local CSS")
defer c.timer.End("Mangle local CSS")
mangledProps := c.mangledProps
globalNames := make(map[string]bool)
localNames := make(map[ast.Ref]struct{})
// Collect all local and global CSS names
freq := ast.CharFreq{}
for _, sourceIndex := range c.graph.ReachableFiles {
if repr, ok := c.graph.Files[sourceIndex].InputFile.Repr.(*graph.CSSRepr); ok {
for innerIndex, symbol := range c.graph.Symbols.SymbolsForSource[sourceIndex] {
if symbol.Kind == ast.SymbolGlobalCSS {
globalNames[symbol.OriginalName] = true
} else {
ref := ast.Ref{SourceIndex: sourceIndex, InnerIndex: uint32(innerIndex)}
ref = ast.FollowSymbols(c.graph.Symbols, ref)
localNames[ref] = struct{}{}
}
}
// Include this file's frequency histogram, which affects the mangled names
if repr.AST.CharFreq != nil {
freq.Include(repr.AST.CharFreq)
}
}
}
// Sort by use count (note: does not currently account for live vs. dead code)
sorted := make(renamer.StableSymbolCountArray, 0, len(localNames))
stableSourceIndices := c.graph.StableSourceIndices
for ref := range localNames {
sorted = append(sorted, renamer.StableSymbolCount{
StableSourceIndex: stableSourceIndices[ref.SourceIndex],
Ref: ref,
Count: c.graph.Symbols.Get(ref).UseCountEstimate,
})
}
sort.Sort(sorted)
// Rename all local names to avoid collisions
if c.options.MinifyIdentifiers {
minifier := ast.DefaultNameMinifierCSS.ShuffleByCharFreq(freq)
nextName := 0
for _, symbolCount := range sorted {
name := minifier.NumberToMinifiedName(nextName)
for globalNames[name] {
nextName++
name = minifier.NumberToMinifiedName(nextName)
}
// Turn this local name into a global one
mangledProps[symbolCount.Ref] = name
globalNames[name] = true
}
} else {
nameCounts := make(map[string]uint32)
for _, symbolCount := range sorted {
symbol := c.graph.Symbols.Get(symbolCount.Ref)
name := fmt.Sprintf("%s_%s", c.graph.Files[symbolCount.Ref.SourceIndex].InputFile.Source.IdentifierName, symbol.OriginalName)
// If the name is already in use, generate a new name by appending a number
if globalNames[name] {
// To avoid O(n^2) behavior, the number must start off being the number
// that we used last time there was a collision with this name. Otherwise
// if there are many collisions with the same name, each name collision
// would have to increment the counter past all previous name collisions
// which is a O(n^2) time algorithm.
tries, ok := nameCounts[name]
if !ok {
tries = 1
}
prefix := name
// Keep incrementing the number until the name is unused
for {
tries++
name = prefix + strconv.Itoa(int(tries))
// Make sure this new name is unused
if !globalNames[name] {
// Store the count so we can start here next time instead of starting
// from 1. This means we avoid O(n^2) behavior.
nameCounts[prefix] = tries
break
}
}
}
// Turn this local name into a global one
mangledProps[symbolCount.Ref] = name
globalNames[name] = true
}
}
}
// Currently the automatic chunk generation algorithm should by construction
// never generate chunks that import each other since files are allocated to
// chunks based on which entry points they are reachable from.
//
// This will change in the future when we allow manual chunk labels. But before
// we allow manual chunk labels, we'll need to rework module initialization to
// allow code splitting chunks to be lazily-initialized.
//
// Since that work hasn't been finished yet, cycles in the chunk import graph
// can cause initialization bugs. So let's forbid these cycles for now to guard
// against code splitting bugs that could cause us to generate buggy chunks.
func (c *linkerContext) enforceNoCyclicChunkImports() {
var validate func(int, map[int]int) bool
// DFS memoization with 3-colors, more space efficient
// 0: white (unvisited), 1: gray (visiting), 2: black (visited)
colors := make(map[int]int)
validate = func(chunkIndex int, colors map[int]int) bool {
if colors[chunkIndex] == 1 {
c.log.AddError(nil, logger.Range{}, "Internal error: generated chunks contain a circular import")
return true
}
if colors[chunkIndex] == 2 {
return false
}
colors[chunkIndex] = 1
for _, chunkImport := range c.chunks[chunkIndex].crossChunkImports {
// Ignore cycles caused by dynamic "import()" expressions. These are fine
// because they don't necessarily cause initialization order issues and
// they don't indicate a bug in our chunk generation algorithm. They arise
// normally in real code (e.g. two files that import each other).
if chunkImport.importKind != ast.ImportDynamic {
// Recursively validate otherChunkIndex
if validate(int(chunkImport.chunkIndex), colors) {
return true
}
}
}
colors[chunkIndex] = 2
return false
}
for i := range c.chunks {
if validate(i, colors) {
break
}
}
}
func (c *linkerContext) generateChunksInParallel(additionalFiles []graph.OutputFile) []graph.OutputFile {
c.timer.Begin("Generate chunks")
defer c.timer.End("Generate chunks")
// Generate each chunk on a separate goroutine. When a chunk needs to
// reference the path of another chunk, it will use a temporary path called
// the "uniqueKey" since the final path hasn't been computed yet (and is
// in general uncomputable at this point because paths have hashes that
// include information about chunk dependencies, and chunk dependencies
// can be cyclic due to dynamic imports).
generateWaitGroup := sync.WaitGroup{}
generateWaitGroup.Add(len(c.chunks))
for chunkIndex := range c.chunks {
switch c.chunks[chunkIndex].chunkRepr.(type) {
case *chunkReprJS:
go c.generateChunkJS(chunkIndex, &generateWaitGroup)
case *chunkReprCSS:
go c.generateChunkCSS(chunkIndex, &generateWaitGroup)
}
}
c.enforceNoCyclicChunkImports()
generateWaitGroup.Wait()
// Compute the final hashes of each chunk, then use those to create the final
// paths of each chunk. This can technically be done in parallel but it
// probably doesn't matter so much because we're not hashing that much data.
visited := make([]uint32, len(c.chunks))
var finalBytes []byte
for chunkIndex := range c.chunks {
chunk := &c.chunks[chunkIndex]
var hashSubstitution *string
// Only wait for the hash if necessary
if config.HasPlaceholder(chunk.finalTemplate, config.HashPlaceholder) {
// Compute the final hash using the isolated hashes of the dependencies
hash := xxhash.New()
c.appendIsolatedHashesForImportedChunks(hash, uint32(chunkIndex), visited, ^uint32(chunkIndex))
finalBytes = hash.Sum(finalBytes[:0])
finalString := bundler.HashForFileName(finalBytes)
hashSubstitution = &finalString
}
// Render the last remaining placeholder in the template
chunk.finalRelPath = config.TemplateToString(config.SubstituteTemplate(chunk.finalTemplate, config.PathPlaceholders{
Hash: hashSubstitution,
}))
}
// Generate the final output files by joining file pieces together and
// substituting the temporary paths for the final paths. This substitution
// can be done in parallel for each chunk.
c.timer.Begin("Generate final output files")
var resultsWaitGroup sync.WaitGroup
results := make([][]graph.OutputFile, len(c.chunks))
resultsWaitGroup.Add(len(c.chunks))
for chunkIndex, chunk := range c.chunks {
go func(chunkIndex int, chunk chunkInfo) {
var outputFiles []graph.OutputFile
// Each file may optionally contain additional files to be copied to the
// output directory. This is used by the "file" and "copy" loaders.
var commentPrefix string
var commentSuffix string
switch chunkRepr := chunk.chunkRepr.(type) {
case *chunkReprJS:
for _, sourceIndex := range chunkRepr.filesInChunkInOrder {
outputFiles = append(outputFiles, c.graph.Files[sourceIndex].InputFile.AdditionalFiles...)
}
commentPrefix = "//"
case *chunkReprCSS:
for _, sourceIndex := range chunkRepr.filesInChunkInOrder {
outputFiles = append(outputFiles, c.graph.Files[sourceIndex].InputFile.AdditionalFiles...)
}
commentPrefix = "/*"
commentSuffix = " */"
}
// Path substitution for the chunk itself
finalRelDir := c.fs.Dir(chunk.finalRelPath)
outputContentsJoiner, outputSourceMapShifts := c.substituteFinalPaths(chunk.intermediateOutput,
func(finalRelPathForImport string) string {
return c.pathBetweenChunks(finalRelDir, finalRelPathForImport)
})
// Generate the optional legal comments file for this chunk
if chunk.externalLegalComments != nil {
finalRelPathForLegalComments := chunk.finalRelPath + ".LEGAL.txt"
// Link the file to the legal comments
if c.options.LegalComments == config.LegalCommentsLinkedWithComment {
importPath := c.pathBetweenChunks(finalRelDir, finalRelPathForLegalComments)
importPath = strings.TrimPrefix(importPath, "./")
outputContentsJoiner.EnsureNewlineAtEnd()
outputContentsJoiner.AddString("/*! For license information please see ")
outputContentsJoiner.AddString(importPath)
outputContentsJoiner.AddString(" */\n")
}
// Write the external legal comments file
outputFiles = append(outputFiles, graph.OutputFile{
AbsPath: c.fs.Join(c.options.AbsOutputDir, finalRelPathForLegalComments),
Contents: chunk.externalLegalComments,
JSONMetadataChunk: fmt.Sprintf(
"{\n \"imports\": [],\n \"exports\": [],\n \"inputs\": {},\n \"bytes\": %d\n }", len(chunk.externalLegalComments)),
})
}
// Generate the optional source map for this chunk
if c.options.SourceMap != config.SourceMapNone && chunk.outputSourceMap.HasContent() {
outputSourceMap := chunk.outputSourceMap.Finalize(outputSourceMapShifts)
finalRelPathForSourceMap := chunk.finalRelPath + ".map"
// Potentially write a trailing source map comment
switch c.options.SourceMap {
case config.SourceMapLinkedWithComment:
importPath := c.pathBetweenChunks(finalRelDir, finalRelPathForSourceMap)
importPath = strings.TrimPrefix(importPath, "./")
outputContentsJoiner.EnsureNewlineAtEnd()
outputContentsJoiner.AddString(commentPrefix)
outputContentsJoiner.AddString("# sourceMappingURL=")
outputContentsJoiner.AddString(importPath)
outputContentsJoiner.AddString(commentSuffix)
outputContentsJoiner.AddString("\n")
case config.SourceMapInline, config.SourceMapInlineAndExternal:
outputContentsJoiner.EnsureNewlineAtEnd()
outputContentsJoiner.AddString(commentPrefix)
outputContentsJoiner.AddString("# sourceMappingURL=data:application/json;base64,")
outputContentsJoiner.AddString(base64.StdEncoding.EncodeToString(outputSourceMap))
outputContentsJoiner.AddString(commentSuffix)
outputContentsJoiner.AddString("\n")
}
// Potentially write the external source map file
switch c.options.SourceMap {
case config.SourceMapLinkedWithComment, config.SourceMapInlineAndExternal, config.SourceMapExternalWithoutComment:
outputFiles = append(outputFiles, graph.OutputFile{
AbsPath: c.fs.Join(c.options.AbsOutputDir, finalRelPathForSourceMap),
Contents: outputSourceMap,
JSONMetadataChunk: fmt.Sprintf(
"{\n \"imports\": [],\n \"exports\": [],\n \"inputs\": {},\n \"bytes\": %d\n }", len(outputSourceMap)),
})
}
}
// Finalize the output contents
outputContents := outputContentsJoiner.Done()
// Path substitution for the JSON metadata
var jsonMetadataChunk string
if c.options.NeedsMetafile {
jsonMetadataChunkPieces := c.breakJoinerIntoPieces(chunk.jsonMetadataChunkCallback(len(outputContents)))
jsonMetadataChunkBytes, _ := c.substituteFinalPaths(jsonMetadataChunkPieces, func(finalRelPathForImport string) string {
return resolver.PrettyPath(c.fs, logger.Path{Text: c.fs.Join(c.options.AbsOutputDir, finalRelPathForImport), Namespace: "file"})
})
jsonMetadataChunk = string(jsonMetadataChunkBytes.Done())
}
// Generate the output file for this chunk
outputFiles = append(outputFiles, graph.OutputFile{
AbsPath: c.fs.Join(c.options.AbsOutputDir, chunk.finalRelPath),
Contents: outputContents,
JSONMetadataChunk: jsonMetadataChunk,
IsExecutable: chunk.isExecutable,
})
results[chunkIndex] = outputFiles
resultsWaitGroup.Done()
}(chunkIndex, chunk)
}
resultsWaitGroup.Wait()
c.timer.End("Generate final output files")
// Merge the output files from the different goroutines together in order
outputFilesLen := len(additionalFiles)
for _, result := range results {
outputFilesLen += len(result)
}
outputFiles := make([]graph.OutputFile, 0, outputFilesLen)
outputFiles = append(outputFiles, additionalFiles...)
for _, result := range results {
outputFiles = append(outputFiles, result...)
}
return outputFiles
}
// Given a set of output pieces (i.e. a buffer already divided into the spans
// between import paths), substitute the final import paths in and then join
// everything into a single byte buffer.
func (c *linkerContext) substituteFinalPaths(
intermediateOutput intermediateOutput,
modifyPath func(string) string,
) (j helpers.Joiner, shifts []sourcemap.SourceMapShift) {
// Optimization: If there can be no substitutions, just reuse the initial
// joiner that was used when generating the intermediate chunk output
// instead of creating another one and copying the whole file into it.
if intermediateOutput.pieces == nil {
return intermediateOutput.joiner, []sourcemap.SourceMapShift{{}}
}
var shift sourcemap.SourceMapShift
shifts = make([]sourcemap.SourceMapShift, 0, len(intermediateOutput.pieces))
shifts = append(shifts, shift)
for _, piece := range intermediateOutput.pieces {
var dataOffset sourcemap.LineColumnOffset
j.AddBytes(piece.data)
dataOffset.AdvanceBytes(piece.data)
shift.Before.Add(dataOffset)
shift.After.Add(dataOffset)
switch piece.kind {
case outputPieceAssetIndex:
file := c.graph.Files[piece.index]
if len(file.InputFile.AdditionalFiles) != 1 {
panic("Internal error")
}
relPath, _ := c.fs.Rel(c.options.AbsOutputDir, file.InputFile.AdditionalFiles[0].AbsPath)
// Make sure to always use forward slashes, even on Windows
relPath = strings.ReplaceAll(relPath, "\\", "/")
importPath := modifyPath(relPath)
j.AddString(importPath)
shift.Before.AdvanceString(file.InputFile.UniqueKeyForAdditionalFile)
shift.After.AdvanceString(importPath)
shifts = append(shifts, shift)
case outputPieceChunkIndex:
chunk := c.chunks[piece.index]
importPath := modifyPath(chunk.finalRelPath)
j.AddString(importPath)
shift.Before.AdvanceString(chunk.uniqueKey)
shift.After.AdvanceString(importPath)
shifts = append(shifts, shift)
}
}
return
}
func (c *linkerContext) accurateFinalByteCount(output intermediateOutput, chunkFinalRelDir string) int {
count := 0
// Note: The paths generated here must match "substituteFinalPaths" above
for _, piece := range output.pieces {
count += len(piece.data)
switch piece.kind {
case outputPieceAssetIndex:
file := c.graph.Files[piece.index]
if len(file.InputFile.AdditionalFiles) != 1 {
panic("Internal error")
}
relPath, _ := c.fs.Rel(c.options.AbsOutputDir, file.InputFile.AdditionalFiles[0].AbsPath)
// Make sure to always use forward slashes, even on Windows
relPath = strings.ReplaceAll(relPath, "\\", "/")
importPath := c.pathBetweenChunks(chunkFinalRelDir, relPath)
count += len(importPath)
case outputPieceChunkIndex:
chunk := c.chunks[piece.index]
importPath := c.pathBetweenChunks(chunkFinalRelDir, chunk.finalRelPath)
count += len(importPath)
}
}
return count
}
func (c *linkerContext) pathBetweenChunks(fromRelDir string, toRelPath string) string {
// Join with the public path if it has been configured
if c.options.PublicPath != "" {
return joinWithPublicPath(c.options.PublicPath, toRelPath)
}
// Otherwise, return a relative path
relPath, ok := c.fs.Rel(fromRelDir, toRelPath)
if !ok {
c.log.AddError(nil, logger.Range{},
fmt.Sprintf("Cannot traverse from directory %q to chunk %q", fromRelDir, toRelPath))
return ""
}
// Make sure to always use forward slashes, even on Windows
relPath = strings.ReplaceAll(relPath, "\\", "/")
// Make sure the relative path doesn't start with a name, since that could
// be interpreted as a package path instead of a relative path
if !strings.HasPrefix(relPath, "./") && !strings.HasPrefix(relPath, "../") {
relPath = "./" + relPath
}
return relPath
}
func (c *linkerContext) computeCrossChunkDependencies() {
c.timer.Begin("Compute cross-chunk dependencies")
defer c.timer.End("Compute cross-chunk dependencies")
if !c.options.CodeSplitting {
// No need to compute cross-chunk dependencies if there can't be any
return
}
type chunkMeta struct {
imports map[ast.Ref]bool
exports map[ast.Ref]bool
dynamicImports map[int]bool
}
chunkMetas := make([]chunkMeta, len(c.chunks))
// For each chunk, see what symbols it uses from other chunks. Do this in
// parallel because it's the most expensive part of this function.
waitGroup := sync.WaitGroup{}
waitGroup.Add(len(c.chunks))
for chunkIndex, chunk := range c.chunks {
go func(chunkIndex int, chunk chunkInfo) {
chunkMeta := &chunkMetas[chunkIndex]
imports := make(map[ast.Ref]bool)
chunkMeta.imports = imports
chunkMeta.exports = make(map[ast.Ref]bool)
// Go over each file in this chunk
for sourceIndex := range chunk.filesWithPartsInChunk {
// Go over each part in this file that's marked for inclusion in this chunk
switch repr := c.graph.Files[sourceIndex].InputFile.Repr.(type) {
case *graph.JSRepr:
for partIndex, partMeta := range repr.AST.Parts {
if !partMeta.IsLive {
continue
}
part := &repr.AST.Parts[partIndex]
// Rewrite external dynamic imports to point to the chunk for that entry point
for _, importRecordIndex := range part.ImportRecordIndices {
record := &repr.AST.ImportRecords[importRecordIndex]
if record.SourceIndex.IsValid() && c.isExternalDynamicImport(record, sourceIndex) {
otherChunkIndex := c.graph.Files[record.SourceIndex.GetIndex()].EntryPointChunkIndex
record.Path.Text = c.chunks[otherChunkIndex].uniqueKey
record.SourceIndex = ast.Index32{}
record.Flags |= ast.ShouldNotBeExternalInMetafile | ast.ContainsUniqueKey
// Track this cross-chunk dynamic import so we make sure to
// include its hash when we're calculating the hashes of all
// dependencies of this chunk.
if int(otherChunkIndex) != chunkIndex {
if chunkMeta.dynamicImports == nil {
chunkMeta.dynamicImports = make(map[int]bool)
}
chunkMeta.dynamicImports[int(otherChunkIndex)] = true
}
}
}
// Remember what chunk each top-level symbol is declared in. Symbols
// with multiple declarations such as repeated "var" statements with
// the same name should already be marked as all being in a single
// chunk. In that case this will overwrite the same value below which
// is fine.
for _, declared := range part.DeclaredSymbols {
if declared.IsTopLevel {
c.graph.Symbols.Get(declared.Ref).ChunkIndex = ast.MakeIndex32(uint32(chunkIndex))
}
}
// Record each symbol used in this part. This will later be matched up
// with our map of which chunk a given symbol is declared in to
// determine if the symbol needs to be imported from another chunk.
for ref := range part.SymbolUses {
symbol := c.graph.Symbols.Get(ref)
// Ignore unbound symbols, which don't have declarations
if symbol.Kind == ast.SymbolUnbound {
continue
}
// Ignore symbols that are going to be replaced by undefined
if symbol.ImportItemStatus == ast.ImportItemMissing {
continue
}
// If this is imported from another file, follow the import
// reference and reference the symbol in that file instead
if importData, ok := repr.Meta.ImportsToBind[ref]; ok {
ref = importData.Ref
symbol = c.graph.Symbols.Get(ref)
} else if repr.Meta.Wrap == graph.WrapCJS && ref != repr.AST.WrapperRef {
// The only internal symbol that wrapped CommonJS files export
// is the wrapper itself.
continue
}
// If this is an ES6 import from a CommonJS file, it will become a
// property access off the namespace symbol instead of a bare
// identifier. In that case we want to pull in the namespace symbol
// instead. The namespace symbol stores the result of "require()".