-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathlinker.go
5532 lines (4875 loc) · 197 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 bundler
import (
"bytes"
"encoding/base64"
"encoding/binary"
"fmt"
"hash"
"path"
"sort"
"strings"
"sync"
"github.com/evanw/esbuild/internal/ast"
"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_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
// This helps avoid an infinite loop when matching imports to exports
cycleDetector []importTracker
// We may need to refer to the CommonJS "module" symbol for exports
unboundModuleRef js_ast.Ref
// We may need to refer to the "__esm" and/or "__commonJS" runtime symbols
cjsRuntimeRef js_ast.Ref
esmRuntimeRef js_ast.Ref
// 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() []dataForSourceMap
// This is passed to us from the bundling phase
uniqueKeyPrefix string
uniqueKeyPrefixBytes []byte // This is just "uniqueKeyPrefix" in byte form
}
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
// This information is only useful if "isEntryPoint" is true
isEntryPoint bool
sourceIndex uint32 // An index into "c.sources"
entryPointBit uint // An index into "c.graph.EntryPoints"
// 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
// 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 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
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 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
// Otherwise, "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
}
type chunkRepr interface{ isChunk() }
func (*chunkReprJS) isChunk() {}
func (*chunkReprCSS) isChunk() {}
type chunkReprJS struct {
filesInChunkInOrder []uint32
partsInChunkInOrder []partRange
// For code splitting
crossChunkPrefixStmts []js_ast.Stmt
crossChunkSuffixStmts []js_ast.Stmt
exportsToOtherChunks map[js_ast.Ref]string
importsFromOtherChunks map[uint32]crossChunkImportItemArray
}
type chunkReprCSS struct {
externalImportsInOrder []externalImportCSS
filesInChunkInOrder []uint32
}
type externalImportCSS struct {
path logger.Path
conditions []css_ast.Token
}
// 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() []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
}
for _, entryPoint := range entryPoints {
if repr, ok := c.graph.Files[entryPoint.SourceIndex].InputFile.Repr.(*graph.JSRepr); ok {
// 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.KeepES6ImportExportSyntax())) {
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
}
}
}
// 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, js_ast.SymbolUnbound, "module")
} else {
c.unboundModuleRef = js_ast.InvalidRef
}
c.scanImportsAndExports()
// Stop now if there were errors
if c.log.HasErrors() {
return []graph.OutputFile{}
}
c.treeShakingAndCodeSplitting()
if c.options.Mode == config.ModePassThrough {
for _, entryPoint := range c.graph.EntryPoints() {
c.preventExportsFromBeingRenamed(entryPoint.SourceIndex)
}
}
chunks := c.computeChunks()
c.computeCrossChunkDependencies(chunks)
// Make sure calls to "js_ast.FollowSymbols()" in parallel goroutines after this
// won't hit concurrent map mutation hazards
js_ast.FollowAllSymbols(c.graph.Symbols)
return c.generateChunksInParallel(chunks)
}
// 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(chunks []chunkInfo) {
var validate func(int, []int)
validate = func(chunkIndex int, path []int) {
for _, otherChunkIndex := range path {
if chunkIndex == otherChunkIndex {
c.log.AddError(nil, logger.Loc{}, "Internal error: generated chunks contain a circular import")
return
}
}
path = append(path, chunkIndex)
for _, chunkImport := range 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 {
validate(int(chunkImport.chunkIndex), path)
}
}
}
path := make([]int, 0, len(chunks))
for i := range chunks {
validate(i, path)
}
}
func (c *linkerContext) generateChunksInParallel(chunks []chunkInfo) []graph.OutputFile {
c.timer.Begin("Generate chunks")
defer c.timer.End("Generate chunks")
// Generate each chunk on a separate goroutine
generateWaitGroup := sync.WaitGroup{}
generateWaitGroup.Add(len(chunks))
for chunkIndex := range chunks {
switch chunks[chunkIndex].chunkRepr.(type) {
case *chunkReprJS:
go c.generateChunkJS(chunks, chunkIndex, &generateWaitGroup)
case *chunkReprCSS:
go c.generateChunkCSS(chunks, chunkIndex, &generateWaitGroup)
}
}
c.enforceNoCyclicChunkImports(chunks)
generateWaitGroup.Wait()
// Compute the final hashes 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(chunks))
var finalBytes []byte
for chunkIndex := range chunks {
chunk := &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()
appendIsolatedHashesForImportedChunks(hash, chunks, uint32(chunkIndex), visited, ^uint32(chunkIndex))
finalBytes = hash.Sum(finalBytes[:0])
finalString := 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
c.timer.Begin("Generate final output files")
var resultsWaitGroup sync.WaitGroup
results := make([][]graph.OutputFile, len(chunks))
resultsWaitGroup.Add(len(chunks))
for chunkIndex, chunk := range 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" loader.
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(chunks, 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.breakOutputIntoPieces(chunk.jsonMetadataChunkCallback(len(outputContents)), uint32(len(chunks)))
jsonMetadataChunkBytes, _ := c.substituteFinalPaths(chunks, jsonMetadataChunkPieces, func(finalRelPathForImport string) string {
return c.res.PrettyPath(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 := 0
for _, result := range results {
outputFilesLen += len(result)
}
outputFiles := make([]graph.OutputFile, 0, outputFilesLen)
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(
chunks []chunkInfo,
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.UniqueKeyForFileLoader)
shift.After.AdvanceString(importPath)
shifts = append(shifts, shift)
case outputPieceChunkIndex:
chunk := 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) 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.Loc{},
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
}
// Returns the path of this file relative to "outbase", which is then ready to
// be joined with the absolute output directory path. The directory and name
// components are returned separately for convenience.
func pathRelativeToOutbase(
inputFile *graph.InputFile,
options *config.Options,
fs fs.FS,
stdExt string,
avoidIndex bool,
customFilePath string,
) (relDir string, baseName string, baseExt string) {
relDir = "/"
baseExt = stdExt
absPath := inputFile.Source.KeyPath.Text
if customFilePath != "" {
// Use the configured output path if present
absPath = customFilePath
if !fs.IsAbs(absPath) {
absPath = fs.Join(options.AbsOutputBase, absPath)
}
} else if inputFile.Source.KeyPath.Namespace != "file" {
// Come up with a path for virtual paths (i.e. non-file-system paths)
dir, base, _ := logger.PlatformIndependentPathDirBaseExt(absPath)
if avoidIndex && base == "index" {
_, base, _ = logger.PlatformIndependentPathDirBaseExt(dir)
}
baseName = sanitizeFilePathForVirtualModulePath(base)
return
} else {
// Heuristic: If the file is named something like "index.js", then use
// the name of the parent directory instead. This helps avoid the
// situation where many chunks are named "index" because of people
// dynamically-importing npm packages that make use of node's implicit
// "index" file name feature.
if avoidIndex {
base := fs.Base(absPath)
base = base[:len(base)-len(fs.Ext(base))]
if base == "index" {
absPath = fs.Dir(absPath)
}
}
}
// Try to get a relative path to the base directory
relPath, ok := fs.Rel(options.AbsOutputBase, absPath)
if !ok {
// This can fail in some situations such as on different drives on
// Windows. In that case we just use the file name.
baseName = fs.Base(absPath)
} else {
// Now we finally have a relative path
relDir = fs.Dir(relPath) + "/"
baseName = fs.Base(relPath)
// Use platform-independent slashes
relDir = strings.ReplaceAll(relDir, "\\", "/")
// Replace leading "../" so we don't try to write outside of the output
// directory. This normally can't happen because "AbsOutputBase" is
// automatically computed to contain all entry point files, but it can
// happen if someone sets it manually via the "outbase" API option.
//
// Note that we can't just strip any leading "../" because that could
// cause two separate entry point paths to collide. For example, there
// could be both "src/index.js" and "../src/index.js" as entry points.
dotDotCount := 0
for strings.HasPrefix(relDir[dotDotCount*3:], "../") {
dotDotCount++
}
if dotDotCount > 0 {
// The use of "_.._" here is somewhat arbitrary but it is unlikely to
// collide with a folder named by a human and it works on Windows
// (Windows doesn't like names that end with a "."). And not starting
// with a "." means that it will not be hidden on Unix.
relDir = strings.Repeat("_.._/", dotDotCount) + relDir[dotDotCount*3:]
}
for strings.HasSuffix(relDir, "/") {
relDir = relDir[:len(relDir)-1]
}
relDir = "/" + relDir
if strings.HasSuffix(relDir, "/.") {
relDir = relDir[:len(relDir)-1]
}
}
// Strip the file extension if the output path is an input file
if customFilePath == "" {
ext := fs.Ext(baseName)
baseName = baseName[:len(baseName)-len(ext)]
}
return
}
func (c *linkerContext) computeCrossChunkDependencies(chunks []chunkInfo) {
c.timer.Begin("Compute cross-chunk dependencies")
defer c.timer.End("Compute cross-chunk dependencies")
jsChunks := 0
for _, chunk := range chunks {
if _, ok := chunk.chunkRepr.(*chunkReprJS); ok {
jsChunks++
}
}
if jsChunks < 2 {
// No need to compute cross-chunk dependencies if there can't be any
return
}
type chunkMeta struct {
imports map[js_ast.Ref]bool
exports map[js_ast.Ref]bool
dynamicImports map[int]bool
}
chunkMetas := make([]chunkMeta, len(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(chunks))
for chunkIndex, chunk := range chunks {
go func(chunkIndex int, chunk chunkInfo) {
chunkMeta := &chunkMetas[chunkIndex]
imports := make(map[js_ast.Ref]bool)
chunkMeta.imports = imports
chunkMeta.exports = make(map[js_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 = chunks[otherChunkIndex].uniqueKey
record.SourceIndex = ast.Index32{}
// 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 == js_ast.SymbolUnbound {
continue
}
// Ignore symbols that are going to be replaced by undefined
if symbol.ImportItemStatus == js_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()".
if symbol.NamespaceAlias != nil {
ref = symbol.NamespaceAlias.NamespaceRef
}
// We must record this relationship even for symbols that are not
// imports. Due to code splitting, the definition of a symbol may
// be moved to a separate chunk than the use of a symbol even if
// the definition and use of that symbol are originally from the
// same source file.
imports[ref] = true
}
}
}
}
// Include the exports if this is an entry point chunk
if chunk.isEntryPoint {
if repr, ok := c.graph.Files[chunk.sourceIndex].InputFile.Repr.(*graph.JSRepr); ok {
if repr.Meta.Wrap != graph.WrapCJS {
for _, alias := range repr.Meta.SortedAndFilteredExportAliases {
export := repr.Meta.ResolvedExports[alias]
targetRef := export.Ref
// If this is an import, then target what the import points to
if importData, ok := c.graph.Files[export.SourceIndex].InputFile.Repr.(*graph.JSRepr).Meta.ImportsToBind[targetRef]; ok {
targetRef = importData.Ref
}
// 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()".
if symbol := c.graph.Symbols.Get(targetRef); symbol.NamespaceAlias != nil {
targetRef = symbol.NamespaceAlias.NamespaceRef
}
imports[targetRef] = true
}
}
// Ensure "exports" is included if the current output format needs it
if repr.Meta.ForceIncludeExportsForEntryPoint {
imports[repr.AST.ExportsRef] = true
}
// Include the wrapper if present
if repr.Meta.Wrap != graph.WrapNone {
imports[repr.AST.WrapperRef] = true
}
}
}
waitGroup.Done()
}(chunkIndex, chunk)
}
waitGroup.Wait()
// Mark imported symbols as exported in the chunk from which they are declared
for chunkIndex := range chunks {
chunk := &chunks[chunkIndex]
chunkRepr, ok := chunk.chunkRepr.(*chunkReprJS)
if !ok {
continue
}
chunkMeta := chunkMetas[chunkIndex]
// Find all uses in this chunk of symbols from other chunks
chunkRepr.importsFromOtherChunks = make(map[uint32]crossChunkImportItemArray)
for importRef := range chunkMeta.imports {
// Ignore uses that aren't top-level symbols
if otherChunkIndex := c.graph.Symbols.Get(importRef).ChunkIndex; otherChunkIndex.IsValid() {
if otherChunkIndex := otherChunkIndex.GetIndex(); otherChunkIndex != uint32(chunkIndex) {
chunkRepr.importsFromOtherChunks[otherChunkIndex] =
append(chunkRepr.importsFromOtherChunks[otherChunkIndex], crossChunkImportItem{ref: importRef})
chunkMetas[otherChunkIndex].exports[importRef] = true
}
}
}
// If this is an entry point, make sure we import all chunks belonging to
// this entry point, even if there are no imports. We need to make sure
// these chunks are evaluated for their side effects too.
if chunk.isEntryPoint {
for otherChunkIndex, otherChunk := range chunks {
if _, ok := otherChunk.chunkRepr.(*chunkReprJS); ok && chunkIndex != otherChunkIndex && otherChunk.entryBits.HasBit(chunk.entryPointBit) {
imports := chunkRepr.importsFromOtherChunks[uint32(otherChunkIndex)]
chunkRepr.importsFromOtherChunks[uint32(otherChunkIndex)] = imports
}
}
}
// Make sure we also track dynamic cross-chunk imports. These need to be
// tracked so we count them as dependencies of this chunk for the purpose
// of hash calculation.
if chunkMeta.dynamicImports != nil {
sortedDynamicImports := make([]int, 0, len(chunkMeta.dynamicImports))
for chunkIndex := range chunkMeta.dynamicImports {
sortedDynamicImports = append(sortedDynamicImports, chunkIndex)
}
sort.Ints(sortedDynamicImports)
for _, chunkIndex := range sortedDynamicImports {
chunk.crossChunkImports = append(chunk.crossChunkImports, chunkImport{
importKind: ast.ImportDynamic,
chunkIndex: uint32(chunkIndex),
})
}
}
}
// Generate cross-chunk exports. These must be computed before cross-chunk
// imports because of export alias renaming, which must consider all export
// aliases simultaneously to avoid collisions.
for chunkIndex := range chunks {
chunk := &chunks[chunkIndex]
chunkRepr, ok := chunk.chunkRepr.(*chunkReprJS)
if !ok {
continue
}
chunkRepr.exportsToOtherChunks = make(map[js_ast.Ref]string)
switch c.options.OutputFormat {
case config.FormatESModule:
r := renamer.ExportRenamer{}
var items []js_ast.ClauseItem
for _, export := range c.sortedCrossChunkExportItems(chunkMetas[chunkIndex].exports) {
var alias string
if c.options.MinifyIdentifiers {
alias = r.NextMinifiedName()
} else {
alias = r.NextRenamedName(c.graph.Symbols.Get(export.Ref).OriginalName)
}
items = append(items, js_ast.ClauseItem{Name: js_ast.LocRef{Ref: export.Ref}, Alias: alias})
chunkRepr.exportsToOtherChunks[export.Ref] = alias
}
if len(items) > 0 {
chunkRepr.crossChunkSuffixStmts = []js_ast.Stmt{{Data: &js_ast.SExportClause{
Items: items,
}}}
}
default:
panic("Internal error")
}
}
// Generate cross-chunk imports. These must be computed after cross-chunk
// exports because the export aliases must already be finalized so they can
// be embedded in the generated import statements.
for chunkIndex := range chunks {
chunk := &chunks[chunkIndex]
chunkRepr, ok := chunk.chunkRepr.(*chunkReprJS)
if !ok {
continue
}
var crossChunkPrefixStmts []js_ast.Stmt
for _, crossChunkImport := range c.sortedCrossChunkImports(chunks, chunkRepr.importsFromOtherChunks) {
switch c.options.OutputFormat {
case config.FormatESModule:
var items []js_ast.ClauseItem
for _, item := range crossChunkImport.sortedImportItems {
items = append(items, js_ast.ClauseItem{Name: js_ast.LocRef{Ref: item.ref}, Alias: item.exportAlias})
}
importRecordIndex := uint32(len(chunk.crossChunkImports))
chunk.crossChunkImports = append(chunk.crossChunkImports, chunkImport{
importKind: ast.ImportStmt,
chunkIndex: crossChunkImport.chunkIndex,
})
if len(items) > 0 {
// "import {a, b} from './chunk.js'"
crossChunkPrefixStmts = append(crossChunkPrefixStmts, js_ast.Stmt{Data: &js_ast.SImport{
Items: &items,
ImportRecordIndex: importRecordIndex,
}})
} else {
// "import './chunk.js'"
crossChunkPrefixStmts = append(crossChunkPrefixStmts, js_ast.Stmt{Data: &js_ast.SImport{
ImportRecordIndex: importRecordIndex,
}})
}
default:
panic("Internal error")
}
}
chunkRepr.crossChunkPrefixStmts = crossChunkPrefixStmts
}
}
type crossChunkImport struct {
chunkIndex uint32
sortedImportItems crossChunkImportItemArray
}