package bundler

import (
	
	
	
	
	
	
	
	
	

	
	
	
	
	
	
	
	
	
	
	
	
	
	
)

type bitSet struct {
	entries []byte
}

func ( uint) bitSet {
	return bitSet{make([]byte, (+7)/8)}
}

func ( bitSet) ( uint) bool {
	return (.entries[/8] & (1 << ( & 7))) != 0
}

func ( bitSet) ( uint) {
	.entries[/8] |= 1 << ( & 7)
}

func ( bitSet) ( bitSet) bool {
	return bytes.Equal(.entries, .entries)
}

func ( bitSet) ( bitSet) {
	copy(.entries, .entries)
}

func ( *bitSet) ( bitSet) {
	for  := range .entries {
		.entries[] |= .entries[]
	}
}

type linkerContext struct {
	options     *config.Options
	log         logger.Log
	fs          fs.FS
	res         resolver.Resolver
	symbols     js_ast.SymbolMap
	entryPoints []uint32
	files       []file
	hasErrors   bool
This is the relative path for automatically-generated code splitting chunks relative to the output directory
This helps avoid an infinite loop when matching imports to exports
We should avoid traversing all files in the bundle, because the linker should be able to run a linking operation on a large bundle where only a few files are needed (e.g. an incremental compilation scenario). This holds all files that could possibly be reached through the entry points. If you need to iterate over all files in the linking operation, iterate over this array. This array is also sorted in a deterministic ordering to help ensure deterministic builds (source indices are random).
This maps from unstable source index to stable reachable file index. This is useful as a deterministic key for sorting if you need to sort something containing a source index (such as "js_ast.Ref" symbol references).
We may need to refer to the CommonJS "module" symbol for exports
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.
This contains linker-specific metadata corresponding to a "file" struct from the initial scan phase of the bundler. It's separated out because it's conceptually only used for a single linking operation and because multiple linking operations may be happening in parallel with different metadata for the same file.
type fileMeta struct {
	partMeta []partMeta
This is the index to the automatically-generated part containing code that calls "__export(exports, { ... getters ... })". This is used to generate getters on an exports object for ES6 export statements, and is both for ES6 star imports and CommonJS-style modules.
The index of the automatically-generated part containing export statements for every export in the entry point. This also contains the call to the require wrapper for CommonJS-style entry points.
This is only for TypeScript files. If an import symbol is in this map, it means the import couldn't be found and doesn't actually exist. This is not an error in TypeScript because the import is probably just a type. Normally we remove all unused imports for TypeScript files during parsing, which automatically removes type-only imports. But there are certain re- export situations where it's impossible to tell if an import is a type or not: import {typeOrNotTypeWhoKnows} from 'path'; export {typeOrNotTypeWhoKnows}; Really people should be using the TypeScript "isolatedModules" flag with bundlers like this one that compile TypeScript files independently without type checking. That causes the TypeScript type checker to emit the error "Re-exporting a type when the '--isolatedModules' flag is provided requires using 'export type'." But we try to be robust to such code anyway.
Imports are matched with exports in a separate pass from when the matched exports are actually bound to the imports. Here "binding" means adding non- local dependencies on the parts in the exporting file that declare the exported symbol to all parts in the importing file that use the imported symbol. This must be a separate pass because of the "probably TypeScript type" check above. We can't generate the part for the export namespace until we've matched imports with exports because the generated code must omit type-only imports in the export namespace code. And we can't bind exports to imports until the part for the export namespace is generated since that part needs to participate in the binding. This array holds the deferred imports to bind so the pass can be split into two separate passes.
If true, the module must be bundled CommonJS-style like this: // foo.ts let require_foo = __commonJS((exports, module) => { ... }); // bar.ts let foo = flag ? require_foo() : null;
If true, all exports must be reached via property accesses off a call to the CommonJS wrapper for this module. In addition, all ES6 exports for this module must be added as getters to the CommonJS "exports" object.
WARNING: This is an interop mess. Different tools do different things and there really isn't a good solution that will always work. More information: https://github.com/evanw/esbuild/issues/532. The value of the "default" export differs between node's ESM implementation and Babel's cross-compiled ESM-to-CommonJS implementation. The default export will always be "module.exports" in node but will be "module.exports.default" with Babel if the property "module.exports.__esModule" is true (indicating a cross-compiled ESM file): // esm-file.mjs import defaultValue from "./import.cjs" console.log(defaultValue) // import.cjs (cross-compiled from "import.esm") Object.defineProperty(exports, '__esModule', { value: true }) exports.default = 'default' // import.mjs (original source code for "import.cjs") export default 'default' Code that respects the "__esModule" flag will print "default" but node will print "{ default: 'default' }". There is no way to work with both. Damned if you do, damned if you don't. It would have been ideal if node behaved consistently with the rest of the ecosystem, but they decided to do their own thing instead. Arguably no approach is "more correct" than the other one. We need to behave like Babel when we cross-compile ESM to CommonJS but we need to behave like a mix of Babel and node for compatibility with existing libraries on npm. So we deliberately skip calling "__toModule" only for ESM files that we ourselves have converted to CommonJS during the build so that we at least don't break ourselves.
If true, the "__export(exports, { ... })" call will be force-included even if there are no parts that reference "exports". Otherwise this call will be removed due to the tree shaking pass. This is used when for entry point files when code related to the current output format needs to reference the "exports" variable.
This is set when we need to pull in the "__export" symbol in to the part at "nsExportPartIndex". This can't be done in "createExportsForFile" because of concurrent map hazards. Instead, it must be done later.
The index of the automatically-generated part used to represent the CommonJS wrapper. This part is empty and is only useful for tree shaking and code splitting. The CommonJS wrapper can't be inserted into the part because the wrapper contains other parts, which can't be represented by the current part system.
This includes both named exports and re-exports. Named exports come from explicit export statements in the original file, and are copied from the "NamedExports" field in the AST. Re-exports come from other files and are the result of resolving export star statements (i.e. "export * from 'foo'").
Never iterate over "resolvedExports" directly. Instead, iterate over this array. Some exports in that map aren't meant to end up in generated code. This array excludes these exports and is also sorted, which avoids non- determinism due to random map iteration order.
	sortedAndFilteredExportAliases []string
}

type importToBind struct {
	sourceIndex uint32
	nameLoc     logger.Loc // Optional, goes with sourceIndex, ignore if zero
	ref         js_ast.Ref
}

type exportData struct {
	ref js_ast.Ref
Export star resolution happens first before import resolution. That means it cannot yet determine if duplicate names from export star resolution are ambiguous (point to different symbols) or not (point to the same symbol). This issue can happen in the following scenario: // entry.js export * from './a' export * from './b' // a.js export * from './c' // b.js export {x} from './c' // c.js export let x = 1, y = 2 In this case "entry.js" should have two exports "x" and "y", neither of which are ambiguous. To handle this case, ambiguity resolution must be deferred until import resolution time. That is done using this array.
This is the file that the named export above came from. This will be different from the file that contains this object if this is a re-export.
	sourceIndex uint32
	nameLoc     logger.Loc // Optional, goes with sourceIndex, ignore if zero
}
This contains linker-specific metadata corresponding to a "js_ast.Part" struct from the initial scan phase of the bundler. It's separated out because it's conceptually only used for a single linking operation and because multiple linking operations may be happening in parallel with different metadata for the same part in the same file.
This holds all entry points that can reach this part. It will be used to assign this part to a chunk.
If present, this is a circular doubly-linked list of all other parts in this file that need to be in the same chunk as this part to avoid cross- chunk assignments, which are not allowed in ES6 modules. This used to be an array but that was generating lots of allocations. Changing this to a circular doubly-linked list was a substantial speedup.
These are dependencies that come from other files via import statements.
The path of this chunk's directory relative to the output directory. Note: this must have OS-independent path separators (i.e. '/' not '\').
The name of this chunk. This is initially empty for non-entry point chunks because the file name contains a hash of the file contents, which haven't been generated yet. Don't access this directly. Instead call "relPath()" which first checks that the base name is not empty.
This information is only useful if "isEntryPoint" is true
	isEntryPoint  bool
	sourceIndex   uint32 // An index into "c.sources"
	entryPointBit uint   // An index into "c.entryPoints"
For code splitting
This is the representation-specific information
Returns the path of this chunk relative to the output directory. Note: this must have OS-independent path separators (i.e. '/' not '\').
func ( *chunkInfo) () string {
	if .baseNameOrEmpty == "" {
		panic("Internal error")
	}
	return path.Join(.relDir, .baseNameOrEmpty)
}

func (
	 *config.Options,
	 logger.Log,
	 fs.FS,
	 resolver.Resolver,
	 []file,
	 []uint32,
	 []uint32,
	 func() []dataForSourceMap,
Clone information about symbols and files so we don't mutate the input data
	 := linkerContext{
		options:           ,
		log:               ,
		fs:                ,
		res:               ,
		entryPoints:       append([]uint32{}, ...),
		files:             make([]file, len()),
		symbols:           js_ast.NewSymbolMap(len()),
		reachableFiles:    ,
		dataForSourceMaps: ,
Note: This contains placeholders instead of what the placeholders are substituted with. That should be fine though because this should only ever be used for figuring out how many "../" to add to a relative path from a chunk whose final path hasn't been calculated yet to a chunk whose final path has already been calculated. That and placeholders are never substituted with something containing a "/" so substitution should never change the "../" count.
Clone various things since we may mutate them later
	for ,  := range .reachableFiles {
		 := []

		switch repr := .repr.(type) {
Clone the representation
			{
				 := *
				 = &
				.repr = 
			}
Clone the symbol map
			 := append([]js_ast.Symbol{}, .ast.Symbols...)
			.symbols.Outer[] = 
			.ast.Symbols = nil
Clone the parts
			.ast.Parts = append([]js_ast.Part{}, .ast.Parts...)
			for ,  := range .ast.Parts {
				 := make(map[js_ast.Ref]js_ast.SymbolUse, len(.SymbolUses))
				for ,  := range .SymbolUses {
					[] = 
				}
				.ast.Parts[].SymbolUses = 
			}
Clone the import records
Clone the import map
			 := make(map[js_ast.Ref]js_ast.NamedImport, len(.ast.NamedImports))
			for ,  := range .ast.NamedImports {
				[] = 
			}
			.ast.NamedImports = 
Clone the export map
			 := make(map[string]exportData)
			for ,  := range .ast.NamedExports {
				[] = exportData{
					ref:         .Ref,
					sourceIndex: ,
					nameLoc:     .AliasLoc,
				}
			}
Clone the top-level symbol-to-parts map
			 := make(map[js_ast.Ref][]uint32)
			for ,  := range .ast.TopLevelSymbolToParts {
				[] = 
			}
			.ast.TopLevelSymbolToParts = 
Clone the top-level scope so we can generate more variables
			{
				 := &js_ast.Scope{}
				* = *.ast.ModuleScope
				.Generated = append([]js_ast.Ref{}, .Generated...)
				.ast.ModuleScope = 
			}
Clone the representation
			{
				 := *
				 = &
				.repr = 
			}
Clone the import records
All files start off as far as possible from an entry point
Update the file in our copy of the file array
		.files[] = 
	}
Create a way to convert source indices to a stable ordering
	.stableSourceIndices = make([]uint32, len(.files))
	for ,  := range .reachableFiles {
		.stableSourceIndices[] = uint32()
	}
Mark all entry points so we don't add them again for import() expressions
	for ,  := range  {
		 := &.files[]
		.isEntryPoint = true

Lazy exports default to CommonJS-style for the transform API
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.
Allocate a new unbound symbol called "module" in case we need it later
	if .options.OutputFormat == config.FormatCommonJS {
		 := &.symbols.Outer[runtime.SourceIndex]
		 := .files[runtime.SourceIndex].repr.(*reprJS).ast.ModuleScope
		.unboundModuleRef = js_ast.Ref{OuterIndex: runtime.SourceIndex, InnerIndex: uint32(len(*))}
		.Generated = append(.Generated, .unboundModuleRef)
		* = append(*, js_ast.Symbol{
			Kind:         js_ast.SymbolUnbound,
			OriginalName: "module",
			Link:         js_ast.InvalidRef,
		})
	} else {
		.unboundModuleRef = js_ast.InvalidRef
	}

	return 
}
Find all files reachable from all entry points. This order should be deterministic given that the entry point order is deterministic, since the returned order is the postorder of the graph traversal and import record order within a given file is deterministic.
func ( []file,  []uint32) []uint32 {
	 := make(map[uint32]bool)
	var  []uint32
	var  func(uint32)
Include this file and all files it imports
	 = func( uint32) {
		if ![] {
			[] = true
			 := &[]
			if ,  := .repr.(*reprJS);  && .cssSourceIndex.IsValid() {
				(.cssSourceIndex.GetIndex())
			}
			for ,  := range *.repr.importRecords() {
				if .SourceIndex.IsValid() {
					(.SourceIndex.GetIndex())
				}
			}
Each file must come after its dependencies
			 = append(, )
		}
	}
The runtime is always included in case it's needed
Include all files reachable from any entry point
	for ,  := range  {
		()
	}

	return 
}

func ( *linkerContext) ( logger.Source,  logger.Range,  string) {
	.log.AddRangeError(&, , )
	.hasErrors = true
}

func ( *linkerContext) ( logger.Source,  logger.Range,  string,  []logger.MsgData) {
	.log.AddRangeErrorWithNotes(&, , , )
	.hasErrors = true
}

func ( *linkerContext) ( uint32,  js_ast.Part,  partMeta) uint32 {
	if .LocalDependencies == nil {
		.LocalDependencies = make(map[uint32]bool)
	}
	if .SymbolUses == nil {
		.SymbolUses = make(map[js_ast.Ref]js_ast.SymbolUse)
	}
	if .entryBits.entries == nil {
		.entryBits = newBitSet(uint(len(.entryPoints)))
	}
	 := .files[].repr.(*reprJS)
	 := uint32(len(.ast.Parts))
	.prevSibling = 
	.nextSibling = 
	.ast.Parts = append(.ast.Parts, )
	.meta.partMeta = append(.meta.partMeta, )
	return 
}

func ( *linkerContext) () []OutputFile {
	.scanImportsAndExports()
Stop now if there were errors
Make sure calls to "js_ast.FollowSymbols()" in parallel goroutines after this won't hit concurrent map mutation hazards
Determine the order of files within the chunk ahead of time. This may generate additional CSS chunks from JS chunks that import CSS files.
	{
		 := 
		for ,  := range  {
			, ,  := .chunkFileOrder(&)

			switch .chunkRepr.(type) {
			case *chunkReprJS:
				[].filesInChunkInOrder = 
				[].partsInChunkInOrder = 
If JS files include CSS files, make a sibling chunk for the CSS
				if len() > 0 {
					 := .baseNameOrEmpty
					if  != "" {
						if  := .options.OutputExtensionJS; strings.HasSuffix(, ) {
							 = [:len()-len()]
						}
						 += .options.OutputExtensionCSS
					}
					 = append(, chunkInfo{
						filesInChunkInOrder:   ,
						entryBits:             .entryBits,
						isEntryPoint:          .isEntryPoint,
						sourceIndex:           .sourceIndex,
						entryPointBit:         .entryPointBit,
						relDir:                .relDir,
						baseNameOrEmpty:       ,
						filesWithPartsInChunk: make(map[uint32]bool),
						chunkRepr:             &chunkReprCSS{},
					})
				}

			case *chunkReprCSS:
				[].filesInChunkInOrder = 
			}
		}
	}
We want to process chunks with as much parallelism as possible. However, content hashing means chunks that import other chunks must be completed after the imported chunks are completed because the import paths contain the content hash. It's only safe to process a chunk when the dependency count reaches zero.
	type  struct {
		 sync.WaitGroup
		   []uint32
	}
	 := make([], len())
	for ,  := range  {
		[]..Add(len(.crossChunkImports))
		for ,  := range .crossChunkImports {
			 := &[].
			* = append(*, uint32())
		}
	}
Check for loops in the dependency graph since they cause a deadlock
	var  func(int, []int)
	 = func( int,  []int) {
		for ,  := range  {
			if  ==  {
				panic("Internal error: Chunk import graph contains a cycle")
			}
		}
		 = append(, )
		for ,  := range [].crossChunkImports {
			(int(), )
		}
	}
	for  := range  {
		(, nil)
	}

	 := make([][]OutputFile, len())
	 := sync.WaitGroup{}
	.Add(len())
Generate each chunk on a separate goroutine
	for  := range  {
		go func( int) {
			 := &[]
			 := &[]
Start generating the chunk without dependencies, but stop when dependencies are needed. This returns a callback that is called later to resume generating the chunk once dependencies are known.
			 := .chunkRepr.generate(, )
Wait for all dependencies to be resolved first
			..Wait()
Fill in the cross-chunk import records now that the paths are known
			 := make([]ast.ImportRecord, len(.crossChunkImports))
			 := make([]string, len(.crossChunkImports))
			for ,  := range .crossChunkImports {
				 := [].relPath()
				[] = .fs.Join(.options.AbsOutputDir, )
				[] = ast.ImportRecord{
					Kind: ast.ImportStmt,
					Path: logger.Path{Text: .pathBetweenChunks(.relDir, )},
				}
			}
Generate the chunk
			[] = (generateContinue{
				crossChunkAbsPaths:      ,
				crossChunkImportRecords: ,
			})
Wake up any dependents now that we're done
			for ,  := range . {
				[]..Done()
			}
			.Done()
		}()
	}
Join the results in chunk order for determinism
	.Wait()
	var  []OutputFile
	for ,  := range  {
		 = append(, ...)
	}
	return 
}

Return an absolute path if a public path has been configured
	if .options.PublicPath != "" {
		return .options.PublicPath + 
	}
Otherwise, return a relative path
	,  := .fs.Rel(, )
	if ! {
		.log.AddError(nil, logger.Loc{},
			fmt.Sprintf("Cannot traverse from directory %q to chunk %q", , ))
		return ""
	}
Make sure to always use forward slashes, even on Windows
	 = strings.ReplaceAll(, "\\", "/")
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(, "./") && !strings.HasPrefix(, "../") {
		 = "./" + 
	}

	return 
}

func ( *linkerContext) ( []chunkInfo) {
No need to compute cross-chunk dependencies if there can't be any
		return
	}

	type  struct {
		 map[js_ast.Ref]bool
		 map[js_ast.Ref]bool
	}

	 := make([], len())
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.
	 := sync.WaitGroup{}
	.Add(len())
	for ,  := range  {
		go func( int,  chunkInfo) {
			 := string(.entryBits.entries)
			 := make(map[js_ast.Ref]bool)
			[] = {: , : make(map[js_ast.Ref]bool)}
Go over each file in this chunk
Go over each part in this file that's marked for inclusion in this chunk
				switch repr := .files[].repr.(type) {
				case *reprJS:
					for ,  := range .meta.partMeta {
						if string(.entryBits.entries) !=  {
							continue
						}
						 := &.ast.Parts[]
Rewrite external dynamic imports to point to the chunk for that entry point
						for ,  := range .ImportRecordIndices {
							 := &.ast.ImportRecords[]
							if .SourceIndex.IsValid() && .isExternalDynamicImport() {
								.Path.Text = .pathBetweenChunks(.relDir, .files[.SourceIndex.GetIndex()].entryPointRelPath)
								.SourceIndex = ast.Index32{}
							}
						}
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 ,  := range .DeclaredSymbols {
							if .IsTopLevel {
								.symbols.Get(.Ref).ChunkIndex = ast.MakeIndex32(uint32())
							}
						}
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  := range .SymbolUses {
							 := .symbols.Get()
Ignore unbound symbols, which don't have declarations
							if .Kind == js_ast.SymbolUnbound {
								continue
							}
Ignore symbols that are going to be replaced by undefined
							if .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 ,  := .meta.importsToBind[];  {
								 = .ref
								 = .symbols.Get()
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 .NamespaceAlias != nil {
								 = .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.
							[] = true
						}
					}
				}
			}
			.Done()
		}(, )
	}
	.Wait()
Mark imported symbols as exported in the chunk from which they are declared
	for  := range  {
		 := &[]
		,  := .chunkRepr.(*chunkReprJS)
		if ! {
			continue
		}
Find all uses in this chunk of symbols from other chunks
Ignore uses that aren't top-level symbols
			if  := .symbols.Get().ChunkIndex; .IsValid() {
				if  := .GetIndex();  != uint32() {
					.importsFromOtherChunks[] =
						append(.importsFromOtherChunks[], crossChunkImportItem{ref: })
					[].[] = 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 .isEntryPoint {
			for ,  := range  {
				if  !=  && .entryBits.hasBit(.entryPointBit) {
					 := .importsFromOtherChunks[uint32()]
					.importsFromOtherChunks[uint32()] = 
				}
			}
		}
	}
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  := range  {
		 := &[]
		,  := .chunkRepr.(*chunkReprJS)
		if ! {
			continue
		}

		.exportsToOtherChunks = make(map[js_ast.Ref]string)
		switch .options.OutputFormat {
		case config.FormatESModule:
			 := renamer.ExportRenamer{}
			var  []js_ast.ClauseItem
			for ,  := range .sortedCrossChunkExportItems([].) {
				var  string
				if .options.MinifyIdentifiers {
					 = .NextMinifiedName()
				} else {
					 = .NextRenamedName(.symbols.Get(.ref).OriginalName)
				}
				 = append(, js_ast.ClauseItem{Name: js_ast.LocRef{Ref: .ref}, Alias: })
				.exportsToOtherChunks[.ref] = 
			}
			if len() > 0 {
				.crossChunkSuffixStmts = []js_ast.Stmt{{Data: &js_ast.SExportClause{
					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  := range  {
		 := &[]
		,  := .chunkRepr.(*chunkReprJS)
		if ! {
			continue
		}

		var  []uint32
		var  []js_ast.Stmt

		for ,  := range .sortedCrossChunkImports(, .importsFromOtherChunks) {
			switch .options.OutputFormat {
			case config.FormatESModule:
				var  []js_ast.ClauseItem
				for ,  := range .sortedImportItems {
					 = append(, js_ast.ClauseItem{Name: js_ast.LocRef{Ref: .ref}, Alias: .exportAlias})
				}
				 := uint32(len())
				 = append(, .chunkIndex)
"import {a, b} from './chunk.js'"
					 = append(, js_ast.Stmt{Data: &js_ast.SImport{
						Items:             &,
						ImportRecordIndex: ,
					}})
"import './chunk.js'"
					 = append(, js_ast.Stmt{Data: &js_ast.SImport{
						ImportRecordIndex: ,
					}})
				}

			default:
				panic("Internal error")
			}
		}

		.crossChunkImports = 
		.crossChunkPrefixStmts = 
	}
}

type crossChunkImport struct {
	chunkIndex        uint32
	sortingKey        string
	sortedImportItems crossChunkImportItemArray
}
This type is just so we can use Go's native sort function
type crossChunkImportArray []crossChunkImport

func ( crossChunkImportArray) () int          { return len() }
func ( crossChunkImportArray) ( int,  int) { [], [] = [], [] }

func ( crossChunkImportArray) ( int,  int) bool {
	return [].sortingKey < [].sortingKey
}
Sort cross-chunk imports by chunk name for determinism
func ( *linkerContext) ( []chunkInfo,  map[uint32]crossChunkImportItemArray) crossChunkImportArray {
	 := make(crossChunkImportArray, 0, len())

Sort imports from a single chunk by alias for determinism
		 := [].chunkRepr.(*chunkReprJS).exportsToOtherChunks
		for ,  := range  {
			[].exportAlias = [.ref]
		}
		sort.Sort()
		 = append(, crossChunkImport{
			chunkIndex:        ,
			sortingKey:        string([].entryBits.entries),
			sortedImportItems: ,
		})
	}

	sort.Sort()
	return 
}

type crossChunkImportItem struct {
	ref         js_ast.Ref
	exportAlias string
}
This type is just so we can use Go's native sort function
type crossChunkImportItemArray []crossChunkImportItem

func ( crossChunkImportItemArray) () int          { return len() }
func ( crossChunkImportItemArray) ( int,  int) { [], [] = [], [] }

func ( crossChunkImportItemArray) ( int,  int) bool {
	return [].exportAlias < [].exportAlias
}

type crossChunkExportItem struct {
	ref     js_ast.Ref
	keyPath logger.Path
}
This type is just so we can use Go's native sort function
type crossChunkExportItemArray []crossChunkExportItem

func ( crossChunkExportItemArray) () int          { return len() }
func ( crossChunkExportItemArray) ( int,  int) { [], [] = [], [] }

func ( crossChunkExportItemArray) ( int,  int) bool {
	 := []
	 := []
The sort order here is arbitrary but needs to be consistent between builds. The InnerIndex should be stable because the parser for a single file is single-threaded and deterministically assigns out InnerIndex values sequentially. But the OuterIndex (i.e. source index) should be unstable because the main thread assigns out source index values sequentially to newly-discovered dependencies in a multi-threaded producer/consumer relationship. So instead we use the key path from the source at OuterIndex for stability. This compares using the InnerIndex first before the key path because it's a less expensive comparison test.
Sort cross-chunk exports by chunk name for determinism
func ( *linkerContext) ( map[js_ast.Ref]bool) crossChunkExportItemArray {
	 := make(crossChunkExportItemArray, 0, len())
	for  := range  {
		 = append(, crossChunkExportItem{ref: , keyPath: .files[.OuterIndex].source.KeyPath})
	}
	sort.Sort()
	return 
}

Step 1: Figure out what modules must be CommonJS
	for ,  := range .reachableFiles {
		 := &.files[]
		switch repr := .repr.(type) {
We shouldn't need to clone this because it should be empty for CSS files
			if .additionalFiles != nil {
				panic("Internal error")
			}
Inline URLs for non-CSS files into the CSS file
			for  := range .ast.ImportRecords {
				if  := &.ast.ImportRecords[]; .SourceIndex.IsValid() {
					 := &.files[.SourceIndex.GetIndex()]
					if ,  := .repr.(*reprJS);  {
						.Path.Text = .ast.URLForCSS
						.Path.Namespace = ""
						.SourceIndex = ast.Index32{}
Copy the additional files to the output directory
						.additionalFiles = append(.additionalFiles, .additionalFiles...)
					}
				}
			}

		case *reprJS:
			for  := range .ast.ImportRecords {
				 := &.ast.ImportRecords[]
				if !.SourceIndex.IsValid() {
					continue
				}

				 := &.files[.SourceIndex.GetIndex()]
				 := .repr.(*reprJS)

				switch .Kind {
Importing using ES6 syntax from a file without any ES6 syntax causes that module to be considered CommonJS-style, even if it doesn't have any CommonJS exports. That means the ES6 imports will become undefined instead of causing errors. This is for compatibility with older CommonJS- style bundlers. We emit a warning in this case but try to avoid turning the module into a CommonJS module if possible. This is possible with named imports (the module stays an ECMAScript module but the imports are rewritten with undefined) but is not possible with star imports: import * as ns from './empty-file' console.log(ns) In that case the module *is* considered a CommonJS module because the namespace object must be created.
					if .ContainsImportStar && !.ast.HasESMFeatures() && !.ast.HasLazyExport {
						.meta.cjsStyleExports = true
					}

Files that are imported with require() must be CommonJS modules
Files that are imported with import() must be entry points
						if !.isEntryPoint {
							.entryPoints = append(.entryPoints, .SourceIndex.GetIndex())
							.isEntryPoint = true
						}
If we're not splitting, then import() is just a require() that returns a promise, so the imported file must be a CommonJS module
						.meta.cjsStyleExports = true
					}
				}
			}
		}
	}
Step 2: Propagate CommonJS status for export star statements that are re- exports from a CommonJS module. Exports from a CommonJS module are not statically analyzable, so the export star must be evaluated at run time instead of at bundle time.
	for ,  := range .reachableFiles {
		if ,  := .files[].repr.(*reprJS);  && len(.ast.ExportStarImportRecords) > 0 {
			 := make(map[uint32]bool)
			.isCommonJSDueToExportStar(, )
		}
	}
Step 3: Resolve "export * from" statements. This must be done after we discover all modules that can be CommonJS because export stars are ignored for CommonJS modules.
	 := make([]uint32, 0, 32)
	for ,  := range .reachableFiles {
		 := &.files[]
		,  := .repr.(*reprJS)
		if ! {
			continue
		}
Expression-style loaders defer code generation until linking. Code generation is done here because at this point we know that the "cjsStyleExports" flag has its final value and will not be changed.
		if .ast.HasLazyExport {
			.generateCodeForLazyExport()
		}
If the output format doesn't have an implicit CommonJS wrapper, any file that uses CommonJS features will need to be wrapped, even though the resulting wrapper won't be invoked by other files.
Even if the output file is CommonJS-like, we may still need to wrap CommonJS-style files. Any file that imports a CommonJS-style file will cause that file to need to be wrapped. This is because the import method, whatever it is, will need to invoke the wrapper. Note that this can include entry points (e.g. an entry point that imports a file that imports that entry point).
		for ,  := range .ast.ImportRecords {
			if .SourceIndex.IsValid() {
				 := .files[.SourceIndex.GetIndex()].repr.(*reprJS)
				if .meta.cjsStyleExports {
					.meta.cjsWrap = true
				}
			}
		}
Propagate exports for export star statements
		if len(.ast.ExportStarImportRecords) > 0 {
			.addExportsForExportStar(.meta.resolvedExports, , )
		}
Add an empty part for the namespace export that we can fill in later
Also add a special export called "*" so import stars can bind to it. This must be done in this step because it must come after CommonJS module discovery but before matching imports with exports.
Step 4: Match imports with exports. This must be done after we process all export stars because imports can bind to export star re-exports.
	for ,  := range .reachableFiles {
		 := &.files[]
		,  := .repr.(*reprJS)
		if ! {
			continue
		}

		if len(.ast.NamedImports) > 0 {
			.matchImportsWithExportsForFile(uint32())
		}
If we're exporting as CommonJS and this file doesn't need a wrapper, then we'll be using the actual CommonJS "exports" and/or "module" symbols. In that case make sure to mark them as such so they don't get minified.
Step 5: Create namespace exports for every file. This is always necessary for CommonJS files, and is also necessary for other files if they are imported using an import star statement.
	 := sync.WaitGroup{}
	for ,  := range .reachableFiles {
		,  := .files[].repr.(*reprJS)
		if ! {
			continue
		}
This is the slowest step and is also parallelizable, so do this in parallel.
		.Add(1)
Now that all exports have been resolved, sort and filter them to create something we can iterate over later.
			 := make([]string, 0, len(.meta.resolvedExports))
		:
The automatically-generated namespace export is just for internal binding purposes and isn't meant to end up in generated code.
				if  == "*" {
					continue
				}
Re-exporting multiple symbols with the same name causes an ambiguous export. These names cannot be used and should not end up in generated code.
				 := .files[.sourceIndex].repr.(*reprJS)
				if len(.potentiallyAmbiguousExportStarRefs) > 0 {
					 := .ref
					if ,  := .meta.importsToBind[.ref];  {
						 = .ref
					}
					for ,  := range .potentiallyAmbiguousExportStarRefs {
						 := .files[.sourceIndex].repr.(*reprJS)
						 := .ref
						if ,  := .meta.importsToBind[.ref];  {
							 = .ref
						}
						if  !=  {
							continue 
						}
					}
				}
Ignore re-exported imports in TypeScript files that failed to be resolved. These are probably just type-only imports so the best thing to do is to silently omit them from the export list.
				if .meta.isProbablyTypeScriptType[.ref] {
					continue
				}

				 = append(, )
			}
			sort.Strings()
			.meta.sortedAndFilteredExportAliases = 
Export creation uses "sortedAndFilteredExportAliases" so this must come second after we fill in that array
			.createExportsForFile(uint32())
			.Done()
		}(, )
	}
	.Wait()
Step 6: Bind imports to exports. This adds non-local dependencies on the parts that declare the export to all parts that use the import.
	for ,  := range .reachableFiles {
		 := &.files[]
		,  := .repr.(*reprJS)
		if ! {
			continue
		}
If this isn't CommonJS, then rename the unused "exports" and "module" variables to avoid them causing the identically-named variables in actual CommonJS files from being renamed. This is purely about aesthetics and is not about correctness. This is done here because by this point, we know the CommonJS status will not change further.
		if !.meta.cjsWrap && !.meta.cjsStyleExports && (!.isEntryPoint ||
			.options.OutputFormat != config.FormatCommonJS) {
			 := .source.IdentifierName
			.symbols.Get(.ast.ExportsRef).OriginalName =  + "_exports"
			.symbols.Get(.ast.ModuleRef).OriginalName =  + "_module"
		}
Include the "__export" symbol from the runtime if it was used in the previous step. The previous step can't do this because it's running in parallel and can't safely mutate the "importsToBind" map of another file.
		if .meta.needsExportSymbolFromRuntime || .meta.needsMarkAsModuleSymbolFromRuntime {
			 := .files[runtime.SourceIndex].repr.(*reprJS)
			 := &.ast.Parts[.meta.nsExportPartIndex]
			if .meta.needsExportSymbolFromRuntime {
				 := .ast.ModuleScope.Members["__export"].Ref
				.generateUseOfSymbolForInclude(, &.meta, 1, , runtime.SourceIndex)
			}
			if .meta.needsMarkAsModuleSymbolFromRuntime {
				 := .ast.ModuleScope.Members["__markAsModule"].Ref
				.generateUseOfSymbolForInclude(, &.meta, 1, , runtime.SourceIndex)
			}
		}

		for ,  := range .meta.importsToBind {
			 := .files[.sourceIndex].repr.(*reprJS)
			 := .ast.TopLevelSymbolToParts[.ref]

			for ,  := range .ast.NamedImports[].LocalPartsWithUses {
				 := &.meta.partMeta[]

				for ,  := range  {
					.nonLocalDependencies = append(.nonLocalDependencies, partRef{
						sourceIndex: .sourceIndex,
						partIndex:   ,
					})
				}
			}
Merge these symbols so they will share the same name
			js_ast.MergeSymbols(.symbols, , .ref)
		}
	}
}

func ( *linkerContext) ( uint32) {
	 := &.files[]
	 := .repr.(*reprJS)
Grab the lazy expression
	if len(.ast.Parts) < 1 {
		panic("Internal error")
	}
	 := &.ast.Parts[0]
	if len(.Stmts) != 1 {
		panic("Internal error")
	}
	,  := .Stmts[0].Data.(*js_ast.SLazyExport)
	if ! {
		panic("Internal error")
	}
Use "module.exports = value" for CommonJS-style modules
Otherwise, generate ES6 export statements. These are added as additional parts so they can be tree shaken individually.
	.Stmts = nil

	type  struct {
		       js_ast.Ref
		 uint32
	}

Generate a new symbol
		 := &.symbols.Outer[]
		 := js_ast.Ref{OuterIndex: , InnerIndex: uint32(len(*))}
		* = append(*, js_ast.Symbol{Kind: js_ast.SymbolOther, OriginalName: , Link: js_ast.InvalidRef})
		.ast.ModuleScope.Generated = append(.ast.ModuleScope.Generated, )
Generate an ES6 export
		var  js_ast.Stmt
		if  == "default" {
			 = js_ast.Stmt{Loc: .Loc, Data: &js_ast.SExportDefault{
				DefaultName: js_ast.LocRef{Loc: .Loc, Ref: },
				Value:       js_ast.ExprOrStmt{Expr: &},
			}}
		} else {
			 = js_ast.Stmt{Loc: .Loc, Data: &js_ast.SLocal{
				IsExport: true,
				Decls: []js_ast.Decl{{
					Binding: js_ast.Binding{Loc: .Loc, Data: &js_ast.BIdentifier{Ref: }},
					Value:   &,
				}},
			}}
		}
Link the export into the graph for tree shaking
		 := .addPartToFile(, js_ast.Part{
			Stmts:                []js_ast.Stmt{},
			SymbolUses:           map[js_ast.Ref]js_ast.SymbolUse{.ast.ModuleRef: {CountEstimate: 1}},
			DeclaredSymbols:      []js_ast.DeclaredSymbol{{Ref: , IsTopLevel: true}},
			CanBeRemovedIfUnused: true,
		}, partMeta{})
		.ast.TopLevelSymbolToParts[] = []uint32{}
		.meta.resolvedExports[] = exportData{ref: , sourceIndex: }
		 := &.ast.Parts[]
		for ,  := range  {
			.SymbolUses[.] = js_ast.SymbolUse{CountEstimate: 1}
			.LocalDependencies[.] = true
		}
		return {: , : }
	}
Unwrap JSON objects into separate top-level variables
	var  []
	 := .Value
	if ,  := .Data.(*js_ast.EObject);  {
		 := *
		.Properties = append(make([]js_ast.Property, 0, len(.Properties)), .Properties...)
		for ,  := range .Properties {
			if ,  := .Key.Data.(*js_ast.EString);  && (!.isEntryPoint || js_lexer.IsIdentifierUTF16(.Value)) {
				 := js_lexer.UTF16ToString(.Value)
				 := (, , *.Value, nil)
				 = append(, )
				.Properties[].Value = &js_ast.Expr{Loc: .Key.Loc, Data: &js_ast.EIdentifier{Ref: .}}
			}
		}
		.Data = &
	}
Generate the default export
	(.source.IdentifierName+"_default", "default", , )
}

////////////////////////////////////////////////////////////////////////////// WARNING: This method is run in parallel over all files. Do not mutate data for other files within this method or you will create a data race. //////////////////////////////////////////////////////////////////////////////

	var  []js_ast.ClauseItem
	var  []js_ast.Stmt
	 := &.files[]
	 := .repr.(*reprJS)
If the output format is ES6 modules and we're an entry point, generate an ES6 export statement containing all exports. Except don't do that if this entry point is a CommonJS-style module, since that would generate an ES6 export statement that's not top-level. Instead, we will export the CommonJS exports as a default export later on.
	 := .isEntryPoint && !.meta.cjsWrap &&
		.options.OutputFormat == config.FormatESModule && len(.meta.sortedAndFilteredExportAliases) > 0
Generate a getter per export
	 := []js_ast.Property{}
	 := []partRef{}
	 := []partRef{}
	 := make(map[js_ast.Ref]js_ast.SymbolUse)
	 := make(map[js_ast.Ref]js_ast.SymbolUse)
	for ,  := range .meta.sortedAndFilteredExportAliases {
		 := .meta.resolvedExports[]
If this is an export of an import, reference the symbol that the import was eventually resolved to. We need to do this because imports have already been resolved by this point, so we can't generate a new import and have that be resolved later.
		if ,  := .files[.sourceIndex].repr.(*reprJS).meta.importsToBind[.ref];  {
			.ref = .ref
			.sourceIndex = .sourceIndex
		}
Exports of imports need EImportIdentifier in case they need to be re- written to a property access later on
		var  js_ast.Expr
		if .symbols.Get(.ref).NamespaceAlias != nil {
			 = js_ast.Expr{Data: &js_ast.EImportIdentifier{Ref: .ref}}
Imported identifiers must be assigned to a local variable to be exported using an ES6 export clause. The import needs to be an EImportIdentifier in case it's imported from a CommonJS module.
Generate a temporary variable
				 := &.symbols.Outer[]
				 := js_ast.Ref{OuterIndex: , InnerIndex: uint32(len(*))}
				* = append(*, js_ast.Symbol{
					Kind:         js_ast.SymbolOther,
					OriginalName: "export_" + ,
					Link:         js_ast.InvalidRef,
				})
Stick it on the module scope so it gets renamed and minified
				 := &.ast.ModuleScope.Generated
				* = append(*, )
Create both a local variable and an export clause for that variable. The local variable is initialized with the initial value of the export. This isn't fully correct because it's a "dead" binding and doesn't update with the "live" value as it changes. But ES6 modules don't have any syntax for bare named getter functions so this is the best we can do. These input files: // entry_point.js export {foo} from './cjs-format.js' // cjs-format.js Object.defineProperty(exports, 'foo', { enumerable: true, get: () => Math.random(), }) Become this output file: // cjs-format.js var require_cjs_format = __commonJS((exports) => { Object.defineProperty(exports, "foo", { enumerable: true, get: () => Math.random() }); }); // entry_point.js var cjs_format = __toModule(require_cjs_format()); var export_foo = cjs_format.foo; export { export_foo as foo };
				 = append(, js_ast.Stmt{Data: &js_ast.SLocal{
					Decls: []js_ast.Decl{{
						Binding: js_ast.Binding{Data: &js_ast.BIdentifier{Ref: }},
						Value:   &js_ast.Expr{Data: &js_ast.EImportIdentifier{Ref: .ref}},
					}},
				}})
				 = append(, js_ast.ClauseItem{
					Name:  js_ast.LocRef{Ref: },
					Alias: ,
				})
				[] = js_ast.SymbolUse{CountEstimate: 2}
			}
		} else {
			 = js_ast.Expr{Data: &js_ast.EIdentifier{Ref: .ref}}

Local identifiers can be exported using an export clause. This is done this way instead of leaving the "export" keyword on the local declaration itself both because it lets the local identifier be minified and because it works transparently for re-exports across files. These input files: // entry_point.js export * from './esm-format.js' // esm-format.js export let foo = 123 Become this output file: // esm-format.js let foo = 123; // entry_point.js export { foo };
				 = append(, js_ast.ClauseItem{
					Name:  js_ast.LocRef{Ref: .ref},
					Alias: ,
				})
			}
		}
Add a getter property
		var  js_ast.Expr
		 := js_ast.FnBody{Stmts: []js_ast.Stmt{{Loc: .Loc, Data: &js_ast.SReturn{Value: &}}}}
		if .options.UnsupportedJSFeatures.Has(compat.Arrow) {
			 = js_ast.Expr{Data: &js_ast.EFunction{Fn: js_ast.Fn{Body: }}}
		} else {
			 = js_ast.Expr{Data: &js_ast.EArrow{PreferExpr: true, Body: }}
		}
		 = append(, js_ast.Property{
			Key:   js_ast.Expr{Data: &js_ast.EString{Value: js_lexer.StringToUTF16()}},
			Value: &,
		})
		[.ref] = js_ast.SymbolUse{CountEstimate: 1}
		if .isEntryPoint {
			[.ref] = js_ast.SymbolUse{CountEstimate: 1}
		}
Make sure the part that declares the export is included
Use a non-local dependency since this is likely from a different file if it came in through an export star
			 := partRef{sourceIndex: .sourceIndex, partIndex: }
			 = append(, )
			if .isEntryPoint {
				 = append(, )
			}
		}
	}
Prefix this part with "var exports = {}" if this isn't a CommonJS module
	 := []js_ast.DeclaredSymbol{}
	var  []js_ast.Stmt
	if !.meta.cjsStyleExports && (!.isEntryPoint || .options.OutputFormat != config.FormatCommonJS) {
		 = append(, js_ast.Stmt{Data: &js_ast.SLocal{Decls: []js_ast.Decl{{
			Binding: js_ast.Binding{Data: &js_ast.BIdentifier{Ref: .ast.ExportsRef}},
			Value:   &js_ast.Expr{Data: &js_ast.EObject{}},
		}}}})
		 = append(, js_ast.DeclaredSymbol{
			Ref:        .ast.ExportsRef,
			IsTopLevel: true,
		})
	}
If this file was originally ESM but is now in CommonJS, add a call to "__markAsModule" which sets the "__esModule" property to true. This must be done before any to "require()" or circular imports of multiple modules that have been each converted from ESM to CommonJS may not work correctly.
	if .ast.ExportKeyword.Len > 0 && (.meta.cjsStyleExports || (.isEntryPoint && .options.OutputFormat == config.FormatCommonJS)) {
		 := .files[runtime.SourceIndex].repr.(*reprJS)
		 := .ast.ModuleScope.Members["__markAsModule"].Ref
		 = append(, js_ast.Stmt{Data: &js_ast.SExpr{Value: js_ast.Expr{Data: &js_ast.ECall{
			Target: js_ast.Expr{Data: &js_ast.EIdentifier{Ref: }},
			Args:   []js_ast.Expr{{Data: &js_ast.EIdentifier{Ref: .ast.ExportsRef}}},
		}}}})
Make sure this file depends on the "__markAsModule" symbol
		for ,  := range .ast.TopLevelSymbolToParts[] {
			 := partRef{sourceIndex: runtime.SourceIndex, partIndex: }
			 = append(, )
		}
Pull in the "__markAsModule" symbol later. Also make sure the "exports" variable is marked as used because we used it above.
"__export(exports, { foo: () => foo })"
	 := js_ast.InvalidRef
	if len() > 0 {
		 := .files[runtime.SourceIndex].repr.(*reprJS)
		 = .ast.ModuleScope.Members["__export"].Ref
		 = append(, js_ast.Stmt{Data: &js_ast.SExpr{Value: js_ast.Expr{Data: &js_ast.ECall{
			Target: js_ast.Expr{Data: &js_ast.EIdentifier{Ref: }},
			Args: []js_ast.Expr{
				{Data: &js_ast.EIdentifier{Ref: .ast.ExportsRef}},
				{Data: &js_ast.EObject{
					Properties: ,
				}},
			},
		}}}})
Make sure this file depends on the "__export" symbol
		for ,  := range .ast.TopLevelSymbolToParts[] {
			 := partRef{sourceIndex: runtime.SourceIndex, partIndex: }
			 = append(, )
		}
Make sure the CommonJS closure, if there is one, includes "exports"
No need to generate a part if it'll be empty
Initialize the part that was allocated for us earlier. The information here will be used after this during tree shaking.
		 := &.ast.Parts[.meta.nsExportPartIndex]
		* = js_ast.Part{
			Stmts:             ,
			LocalDependencies: make(map[uint32]bool),
			SymbolUses:        ,
			DeclaredSymbols:   ,
This can be removed if nothing uses it. Except if we're a CommonJS module, in which case it's always necessary.
Put the export definitions first before anything else gets evaluated
Make sure this is trimmed if unused even if tree shaking is disabled
			ForceTreeShaking: true,
		}
		.meta.partMeta[.meta.nsExportPartIndex].nonLocalDependencies = 
Pull in the "__export" symbol if it was used
		if  != js_ast.InvalidRef {
			.meta.needsExportSymbolFromRuntime = true
		}
	}

	if len() > 0 {
		 = append(,
			js_ast.Stmt{Data: &js_ast.SExportClause{Items: }})
	}
If we're an entry point, call the require function at the end of the bundle right before bundle evaluation ends
	var  js_ast.Stmt
	if .isEntryPoint {
		if .meta.cjsWrap {
			switch .options.OutputFormat {
"require_foo();"
"return require_foo();"
"require_foo();"
"module.exports = require_foo();"
"export default require_foo();"
"return exports;"
Trigger evaluation of the CommonJS wrapper
		if .Data != nil {
			[.ast.WrapperRef] = js_ast.SymbolUse{CountEstimate: 1}
			 = append(, )
		}
Add a part for this export clause
		 := .addPartToFile(, js_ast.Part{
			Stmts:      ,
			SymbolUses: ,
		}, partMeta{
			nonLocalDependencies: append([]partRef{}, ...),
		})
		.meta.entryPointExportPartIndex = ast.MakeIndex32()
	}
}

func ( *linkerContext) ( uint32) {
	 := &.files[]
	 := .repr.(*reprJS)
Sort imports for determinism. Otherwise our unit tests will randomly fail sometimes when error messages are reordered.
	 := make([]int, 0, len(.ast.NamedImports))
	for  := range .ast.NamedImports {
		 = append(, int(.InnerIndex))
	}
	sort.Ints()
Pair imports with their matching exports
Re-use memory for the cycle detector
		.cycleDetector = .cycleDetector[:0]

		 := js_ast.Ref{OuterIndex: , InnerIndex: uint32()}
		 := .matchImportWithExport(importTracker{sourceIndex: , importRef: })
		switch .kind {
		case matchImportNormal:
			.meta.importsToBind[] = importToBind{
				sourceIndex: .sourceIndex,
				ref:         .ref,
			}

		case matchImportNamespace:
			.symbols.Get().NamespaceAlias = &js_ast.NamespaceAlias{
				NamespaceRef: .namespaceRef,
				Alias:        .alias,
			}

		case matchImportNormalAndNamespace:
			.meta.importsToBind[] = importToBind{
				sourceIndex: .sourceIndex,
				ref:         .ref,
			}

			.symbols.Get().NamespaceAlias = &js_ast.NamespaceAlias{
				NamespaceRef: .namespaceRef,
				Alias:        .alias,
			}

		case matchImportCycle:
			 := .ast.NamedImports[]
			.addRangeError(.source, js_lexer.RangeOfIdentifier(.source, .AliasLoc),
				fmt.Sprintf("Detected cycle while resolving import %q", .Alias))

		case matchImportProbablyTypeScriptType:
			.meta.isProbablyTypeScriptType[] = true

		case matchImportAmbiguous:
			 := .ast.NamedImports[]
			 := js_lexer.RangeOfIdentifier(.source, .AliasLoc)
			var  []logger.MsgData
Provide the locations of both ambiguous exports if possible
			if .nameLoc.Start != 0 && .otherNameLoc.Start != 0 {
				 := .files[.sourceIndex].source
				 := .files[.otherSourceIndex].source
				 = []logger.MsgData{
					logger.RangeData(&, js_lexer.RangeOfIdentifier(, .nameLoc), "One matching export is here"),
					logger.RangeData(&, js_lexer.RangeOfIdentifier(, .otherNameLoc), "Another matching export is here"),
				}
			}

			 := .symbols.Get()
This is a warning instead of an error because although it appears to be a named import, it's actually an automatically-generated named import that was originally a property access on an import star namespace object. Normally this property access would just resolve to undefined at run-time instead of failing at binding- time, so we emit a warning and rewrite the value to the literal "undefined" instead of emitting an error.
				.ImportItemStatus = js_ast.ImportItemMissing
				 := fmt.Sprintf("Import %q will always be undefined because there are multiple matching exports", .Alias)
				.log.AddRangeWarningWithNotes(&.source, , , )
			} else {
				 := fmt.Sprintf("Ambiguous import %q has multiple matching exports", .Alias)
				.addRangeErrorWithNotes(.source, , , )
			}
		}
	}
}

type matchImportKind uint8

The import is either external or undefined
"sourceIndex" and "ref" are in use
"namespaceRef" and "alias" are in use
Both "matchImportNormal" and "matchImportNamespace"
The import could not be evaluated due to a cycle
The import is missing but came from a TypeScript file
The import resolved to multiple symbols via "export * from"
	matchImportAmbiguous
)

type matchImportResult struct {
	kind             matchImportKind
	namespaceRef     js_ast.Ref
	alias            string
	sourceIndex      uint32
	nameLoc          logger.Loc // Optional, goes with sourceIndex, ignore if zero
	otherSourceIndex uint32
	otherNameLoc     logger.Loc // Optional, goes with otherSourceIndex, ignore if zero
	ref              js_ast.Ref
}

func ( *linkerContext) ( importTracker) ( matchImportResult) {
	var  []matchImportResult

:
Make sure we avoid infinite loops trying to resolve cycles: // foo.js export {a as b} from './foo.js' export {b as c} from './foo.js' export {c as a} from './foo.js' This uses a O(n^2) array scan instead of a O(n) map because the vast majority of cases have one or two elements and Go arrays are cheap to reuse without allocating.
		for ,  := range .cycleDetector {
			if  ==  {
				 = matchImportResult{kind: matchImportCycle}
				break 
			}
		}
		.cycleDetector = append(.cycleDetector, )
Resolve the import by one step
		, ,  := .advanceImportTracker()
		switch  {
		case importCommonJS, importCommonJSWithoutExports, importExternal, importDisabled:
Imports from external modules should not be converted to CommonJS if the output format preserves the original ES6 import statements
				break
			}
If it's a CommonJS or external file, rewrite the import to a property access. Don't do this if the namespace reference is invalid though. This is the case for star imports, where the import is the namespace.
			 := &.files[.sourceIndex]
			 := .repr.(*reprJS).ast.NamedImports[.importRef]
			if .NamespaceRef != js_ast.InvalidRef {
				if .kind == matchImportNormal {
					.kind = matchImportNormalAndNamespace
					.namespaceRef = .NamespaceRef
					.alias = .Alias
				} else {
					 = matchImportResult{
						kind:         matchImportNamespace,
						namespaceRef: .NamespaceRef,
						alias:        .Alias,
					}
				}
			}
Warn about importing from a file that is known to not have any exports
			if  == importCommonJSWithoutExports {
				 := .source
				 := .symbols.Get(.importRef)
				.ImportItemStatus = js_ast.ImportItemMissing
				.log.AddRangeWarning(&, js_lexer.RangeOfIdentifier(, .AliasLoc),
					fmt.Sprintf("Import %q will always be undefined because the file %q has no exports",
						.Alias, .files[.sourceIndex].source.PrettyPath))
			}

		case importNoMatch:
			 := .symbols.Get(.importRef)
			 := &.files[.sourceIndex]
			 := .source
			 := .repr.(*reprJS).ast.NamedImports[.importRef]
			 := js_lexer.RangeOfIdentifier(, .AliasLoc)
Report mismatched imports and exports
This is a warning instead of an error because although it appears to be a named import, it's actually an automatically-generated named import that was originally a property access on an import star namespace object. Normally this property access would just resolve to undefined at run-time instead of failing at binding- time, so we emit a warning and rewrite the value to the literal "undefined" instead of emitting an error.
				.ImportItemStatus = js_ast.ImportItemMissing
				.log.AddRangeWarning(&, , fmt.Sprintf("Import %q will always be undefined because there is no matching export", .Alias))
			} else {
				.addRangeError(, , fmt.Sprintf("No matching export for import %q", .Alias))
			}

Omit this import from any namespace export code we generate for import star statements (i.e. "import * as ns from 'path'")
If there are multiple ambiguous results due to use of "export * from" statements, trace them all to see if they point to different things.
If this is a re-export of another import, follow the import
				if ,  := .files[.sourceIndex].repr.(*reprJS).ast.NamedImports[.ref];  {
					 = append(, .(importTracker{
						sourceIndex: .sourceIndex,
						importRef:   .ref,
					}))
				} else {
					 = append(, matchImportResult{
						kind:        matchImportNormal,
						sourceIndex: .sourceIndex,
						ref:         .ref,
						nameLoc:     .nameLoc,
					})
				}
			}
Defer the actual binding of this import until after we generate namespace export code for all files. This has to be done for all import-to-export matches, not just the initial import to the final export, since all imports and re-exports must be merged together for correctness.
			 = matchImportResult{
				kind:        matchImportNormal,
				sourceIndex: .sourceIndex,
				ref:         .importRef,
				nameLoc:     .nameLoc,
			}
If this is a re-export of another import, continue for another iteration of the loop to resolve that import as well
			if ,  := .files[.sourceIndex].repr.(*reprJS).ast.NamedImports[.importRef];  {
				 = 
				continue
			}

		default:
			panic("Internal error")
		}
Stop now if we didn't explicitly "continue" above
		break
	}
If there is a potential ambiguity, all results must be the same
	for ,  := range  {
		if  !=  {
			if .kind == matchImportNormal && .kind == matchImportNormal &&
				.nameLoc.Start != 0 && .nameLoc.Start != 0 {
				return matchImportResult{
					kind:             matchImportAmbiguous,
					sourceIndex:      .sourceIndex,
					nameLoc:          .nameLoc,
					otherSourceIndex: .sourceIndex,
					otherNameLoc:     .nameLoc,
				}
			}
			return matchImportResult{kind: matchImportAmbiguous}
		}
	}

	return
}

Terminate the traversal now if this file is CommonJS
	 := .files[].repr.(*reprJS)
	if .meta.cjsStyleExports {
		return true
	}
Avoid infinite loops due to cycles in the export star graph
	if [] {
		return false
	}
	[] = true
Scan over the export star graph
	for ,  := range .ast.ExportStarImportRecords {
		 := &.ast.ImportRecords[]
This file is CommonJS if the exported imports are from a file that is either CommonJS directly or transitively by itself having an export star from a CommonJS file.
		if (!.SourceIndex.IsValid() && (!.files[].isEntryPoint || !.options.OutputFormat.KeepES6ImportExportSyntax())) ||
			(.SourceIndex.IsValid() && .SourceIndex.GetIndex() !=  && .(.SourceIndex.GetIndex(), )) {
			.meta.cjsStyleExports = true
			return true
		}
	}

	return false
}

func ( *linkerContext) (
	 map[string]exportData,
	 uint32,
	 []uint32,
Avoid infinite loops due to cycles in the export star graph
	for ,  := range  {
		if  ==  {
			return
		}
	}
	 = append(, )
	 := .files[].repr.(*reprJS)

	for ,  := range .ast.ExportStarImportRecords {
		 := &.ast.ImportRecords[]
This will be resolved at run time instead
			continue
		}
		 := .SourceIndex.GetIndex()
Export stars from a CommonJS module don't work because they can't be statically discovered. Just silently ignore them in this case. We could attempt to check whether the imported file still has ES6 exports even though it still uses CommonJS features. However, when doing this we'd also have to rewrite any imports of these export star re-exports as property accesses off of a generated require() call.
		 := .files[].repr.(*reprJS)
This will be resolved at run time instead
			continue
		}
Accumulate this file's exports
	:
ES6 export star statements ignore exports named "default"
			if  == "default" {
				continue
			}
This export star is shadowed if any file in the stack has a matching real named export
			for ,  := range  {
				 := .files[].repr.(*reprJS)
				if ,  := .ast.NamedExports[];  {
					continue 
				}
			}

Initialize the re-export
				[] = exportData{
					ref:         .Ref,
					sourceIndex: ,
					nameLoc:     .AliasLoc,
				}
Make sure the symbol is marked as imported so that code splitting imports it correctly if it ends up being shared with another chunk
				.meta.importsToBind[.Ref] = importToBind{
					ref:         .Ref,
					sourceIndex: ,
				}
Two different re-exports colliding makes it potentially ambiguous
				.potentiallyAmbiguousExportStarRefs =
					append(.potentiallyAmbiguousExportStarRefs, importToBind{
						sourceIndex: ,
						ref:         .Ref,
						nameLoc:     .AliasLoc,
					})
				[] = 
			}
		}
Search further through this file's export stars
		.(, , )
	}
}

type importTracker struct {
	sourceIndex uint32
	nameLoc     logger.Loc // Optional, goes with sourceIndex, ignore if zero
	importRef   js_ast.Ref
}

type importStatus uint8

The imported file has no matching export
The imported file has a matching export
The imported file is CommonJS and has unknown exports
The import was treated as a CommonJS import but the file is known to have no exports
The imported file was disabled by mapping it to false in the "browser" field of package.json
The imported file is external and has unknown exports
This is a missing re-export in a TypeScript file, so it's probably a type
	importProbablyTypeScriptType
)

func ( *linkerContext) ( importTracker) (importTracker, importStatus, []importToBind) {
	 := &.files[.sourceIndex]
	 := .repr.(*reprJS)
	 := .ast.NamedImports[.importRef]
Is this an external file?
	 := &.ast.ImportRecords[.ImportRecordIndex]
	if !.SourceIndex.IsValid() {
		return importTracker{}, importExternal, nil
	}
Is this a disabled file?
	 := .SourceIndex.GetIndex()
	if .files[].source.KeyPath.IsDisabled() {
		return importTracker{sourceIndex: , importRef: js_ast.InvalidRef}, importDisabled, nil
	}
Is this a named import of a file without any exports?
	 := .files[].repr.(*reprJS)
Just warn about it and replace the import with "undefined"
Is this a CommonJS file?
	if .meta.cjsStyleExports {
		return importTracker{sourceIndex: , importRef: js_ast.InvalidRef}, importCommonJS, nil
	}
Match this import up with an export from the imported file
Check to see if this is a re-export of another import
		return importTracker{
			sourceIndex: .sourceIndex,
			importRef:   .ref,
			nameLoc:     .nameLoc,
		}, importFound, .potentiallyAmbiguousExportStarRefs
	}
Missing re-exports in TypeScript files are indistinguishable from types
Allocate bit sets
	 := uint(len(.entryPoints))
	for ,  := range .reachableFiles {
		 := &.files[]
		.entryBits = newBitSet()

		switch repr := .repr.(type) {
		case *reprJS:
			for  := range .meta.partMeta {
				 := &.meta.partMeta[]
				.entryBits = newBitSet()
				.prevSibling = uint32()
				.nextSibling = uint32()
			}
If this is a CommonJS file, we're going to need to generate a wrapper for the CommonJS closure. That will end up looking something like this: var require_foo = __commonJS((exports, module) => { ... }); However, that generation is special-cased for various reasons and is done later on. Still, we're going to need to ensure that this file both depends on the "__commonJS" symbol and declares the "require_foo" symbol. Instead of special-casing this during the reachablity analysis below, we just append a dummy part to the end of the file with these dependencies and let the general-purpose reachablity analysis take care of it.
			if .meta.cjsWrap {
				 := .files[runtime.SourceIndex].repr.(*reprJS)
				 := .ast.NamedExports["__commonJS"].Ref
				 := .ast.TopLevelSymbolToParts[]
Generate the dummy part
				 := make([]partRef, len())
				for ,  := range  {
					[] = partRef{sourceIndex: runtime.SourceIndex, partIndex: }
				}
				 := .addPartToFile(, js_ast.Part{
					SymbolUses: map[js_ast.Ref]js_ast.SymbolUse{
						.ast.WrapperRef: {CountEstimate: 1},
						:         {CountEstimate: 1},
					},
					DeclaredSymbols: []js_ast.DeclaredSymbol{
						{Ref: .ast.ExportsRef, IsTopLevel: true},
						{Ref: .ast.ModuleRef, IsTopLevel: true},
						{Ref: .ast.WrapperRef, IsTopLevel: true},
					},
				}, partMeta{
					nonLocalDependencies: ,
				})
				.meta.cjsWrapperPartIndex = ast.MakeIndex32()
				.ast.TopLevelSymbolToParts[.ast.WrapperRef] = []uint32{}
				.meta.importsToBind[] = importToBind{
					ref:         ,
					sourceIndex: runtime.SourceIndex,
				}
			}
		}
	}
Each entry point marks all files reachable from itself
	for ,  := range .entryPoints {
		.includeFile(, uint(), 0)
	}
}
Code splitting may cause an assignment to a local variable to end up in a separate chunk from the variable. This is bad because that will generate an assignment to an import, which will fail. Make sure these parts end up in the same chunk in these cases.
No need to do this if there cannot be cross-chunk assignments
		return
	}
	 := newBitSet(uint(len(.entryPoints)))

	for ,  := range .reachableFiles {
		 := &.files[]
		,  := .repr.(*reprJS)
		if ! {
			continue
		}

Ignore this part if it's dead code
			if .meta.partMeta[].entryBits.equals() {
				continue
			}
If this part assigns to a local variable, make sure the parts for the variable's declaration are in the same chunk as this part
			for ,  := range .SymbolUses {
				if .IsAssigned {
					if ,  := .ast.TopLevelSymbolToParts[];  {
						for ,  := range  {
							 := &.meta.partMeta[]
							 := &.meta.partMeta[]
Make sure both sibling subsets have the same entry points
							for  := range .entryPoints {
								 := .entryBits.hasBit(uint())
								 := .entryBits.hasBit(uint())
								if  && ! {
									.includePart(, , uint(), .distanceFromEntryPoint)
								} else if  && ! {
									.includePart(, uint32(), uint(), .distanceFromEntryPoint)
								}
							}
Perform the merge
							.meta.partMeta[.nextSibling].prevSibling = .prevSibling
							.meta.partMeta[.prevSibling].nextSibling = .nextSibling
							.nextSibling = 
							.prevSibling = uint32()
						}
					}
				}
			}
		}
	}
}

func ( *linkerContext) ( uint32,  uint,  uint32) {
	 := &.files[]
Track the minimum distance to an entry point
	if  < .distanceFromEntryPoint {
		.distanceFromEntryPoint = 
	}
	++
Don't mark this file more than once
	if .entryBits.hasBit() {
		return
	}
	.entryBits.setBit()

	switch repr := .repr.(type) {
	case *reprJS:
		 := config.IsTreeShakingEnabled(.options.Mode, .options.OutputFormat)
If the JavaScript stub for a CSS file is included, also include the CSS file
		if .cssSourceIndex.IsValid() {
			.(.cssSourceIndex.GetIndex(), , )
		}

		for ,  := range .ast.Parts {
			 := .CanBeRemovedIfUnused
Don't include the entry point part if we're not the entry point
			if uint32() == .meta.entryPointExportPartIndex.GetIndex() &&
				 != .entryPoints[] {
				continue
			}
Also include any statement-level imports
			for ,  := range .ImportRecordIndices {
				 := &.ast.ImportRecords[]
				if .Kind != ast.ImportStmt {
					continue
				}

				if .SourceIndex.IsValid() {
					 := .SourceIndex.GetIndex()
Don't include this module for its side effects if it can be considered to have no side effects
					if  := &.files[]; .ignoreIfUnused && !.options.IgnoreDCEAnnotations {
						continue
					}
Otherwise, include this module for its side effects
					.(, , )
				}
If we get here then the import was included for its side effects, so we must also keep this part
				 = false
			}
Include all parts in this file with side effects, or just include everything if tree-shaking is disabled. Note that we still want to perform tree-shaking on the runtime even if tree-shaking is disabled.
			if ! || (!.ForceTreeShaking && ! && .isEntryPoint) {
				.includePart(, uint32(), , )
			}
		}
If this is an entry point, include all exports
		if .isEntryPoint {
			for ,  := range .meta.sortedAndFilteredExportAliases {
				 := .meta.resolvedExports[]
				 := .sourceIndex
				 := .ref
If this is an import, then target what the import points to
				 := .files[].repr.(*reprJS)
				if ,  := .meta.importsToBind[];  {
					 = .sourceIndex
					 = .ref
				}
Pull in all declarations of this symbol
				for ,  := range .ast.TopLevelSymbolToParts[] {
					.includePart(, , , )
				}
			}
Ensure "exports" is included if the current output format needs it
			if .meta.forceIncludeExportsForEntryPoint {
				.includePart(, .meta.nsExportPartIndex, , )
			}
		}

Include all "@import" rules
		for ,  := range .ast.ImportRecords {
			if .SourceIndex.IsValid() {
				.(.SourceIndex.GetIndex(), , )
			}
		}
	}
}

func ( *linkerContext) (
	 *js_ast.Part,  *fileMeta,  uint32,
	 string,  uint,  uint32,
) {
	if  > 0 {
		 := .files[runtime.SourceIndex].repr.(*reprJS)
		 := .ast.NamedExports[].Ref
Depend on the symbol from the runtime
		.generateUseOfSymbolForInclude(, , , , runtime.SourceIndex)
Since this part was included, also include the parts from the runtime that declare this symbol
		for ,  := range .ast.TopLevelSymbolToParts[] {
			.includePart(runtime.SourceIndex, , , )
		}
	}
}

func ( *linkerContext) (
	 *js_ast.Part,  *fileMeta,  uint32,
	 js_ast.Ref,  uint32,
) {
	 := .SymbolUses[]
	.CountEstimate += 
	.SymbolUses[] = 
	.importsToBind[] = importToBind{
		sourceIndex: ,
		ref:         ,
	}
}

func ( *linkerContext) ( *ast.ImportRecord) bool {
	return .Kind == ast.ImportDynamic && .files[.SourceIndex.GetIndex()].isEntryPoint
}

func ( *linkerContext) ( uint32,  uint32,  uint,  uint32) {
	 := &.files[]
	 := .repr.(*reprJS)
	 := &.meta.partMeta[]
Don't mark this part more than once
	if .entryBits.hasBit() {
		return
	}
	.entryBits.setBit()

	 := &.ast.Parts[]
Include the file containing this part
	.includeFile(, , )
Also include any local dependencies
	for  := range .LocalDependencies {
		.(, , , )
	}
Also include any non-local dependencies
	for ,  := range .nonLocalDependencies {
		.(.sourceIndex, .partIndex, , )
	}
Also include any cross-chunk assignment siblings
	for  := .nextSibling;  != ;  = .meta.partMeta[].nextSibling {
		.(, , , )
	}
Also include any require() imports
	 := uint32(0)
	for ,  := range .ImportRecordIndices {
		 := &.ast.ImportRecords[]
Don't follow external imports (this includes import() expressions)
This is an external import, so it needs the "__toModule" wrapper as long as it's not a bare "require()"
			if .Kind != ast.ImportRequire && !.options.OutputFormat.KeepES6ImportExportSyntax() {
				.WrapWithToModule = true
				++
			}
			continue
		}

		 := .SourceIndex.GetIndex()
		 := .files[].repr.(*reprJS)
Skip this since it's not a require() import
			continue
		}
This is a require() import
		.includeFile(, , )
Depend on the automatically-generated require wrapper symbol
		 := .ast.WrapperRef
		.generateUseOfSymbolForInclude(, &.meta, 1, , )
This is an ES6 import of a CommonJS module, so it needs the "__toModule" wrapper as long as it's not a bare "require()"
		if .Kind != ast.ImportRequire && !.meta.skipCallingToModule {
			.WrapWithToModule = true
			++
		}
	}
If there's an ES6 import of a non-ES6 module, then we're going to need the "__toModule" symbol from the runtime to wrap the result of "require()"
	.includePartsForRuntimeSymbol(, &.meta, , "__toModule", , )
If there's an ES6 export star statement of a non-ES6 module, then we're going to need the "__exportStar" symbol from the runtime
	 := uint32(0)
	for ,  := range .ast.ExportStarImportRecords {
		 := &.ast.ImportRecords[]
Is this export star evaluated at run time?
		if (!.SourceIndex.IsValid() && (!.isEntryPoint || !.options.OutputFormat.KeepES6ImportExportSyntax())) ||
			(.SourceIndex.IsValid() && .SourceIndex.GetIndex() !=  && .files[.SourceIndex.GetIndex()].repr.(*reprJS).meta.cjsStyleExports) {
			.CallsRunTimeExportStarFn = true
			.ast.UsesExportsRef = true
			++
		}
	}
	.includePartsForRuntimeSymbol(, &.meta, , "__exportStar", , )
}

func ( string) string {
	, ,  := logger.PlatformIndependentPathDirBaseExt()
Convert it to a safe file name. See: https://stackoverflow.com/a/31976060
	 := strings.Builder{}
	 := false
	for ,  := range  +  {
		switch  {
These characters are forbidden on Unix and Windows

These characters are forbidden on Windows

		default:
These characters are forbidden on Windows
				break
			}
Turn runs of invalid characters into a '_'
			if  {
				.WriteByte('_')
				 = false
			}

			.WriteRune()
			continue
		}

		if .Len() > 0 {
			 = true
		}
	}
Make sure the name isn't empty
	if .Len() == 0 {
		return "_"
	}
Note: An extension will be added to this base name, so there is no need to avoid forbidden file names such as ".." since ".js" is a valid file name.
	return .String()
}

func ( *linkerContext) () []chunkInfo {
	 := make(map[string]chunkInfo)
	 := string(newBitSet(uint(len(.entryPoints))).entries)
Compute entry point names
	for ,  := range .entryPoints {
		var  string
		var  string
		var  chunkRepr
		 := &.files[]

		switch .repr.(type) {
		case *reprJS:
			 = &chunkReprJS{}
		case *reprCSS:
			 = &chunkReprCSS{}
		}

		if .options.AbsOutputFile != "" {
			 = .fs.Base(.options.AbsOutputFile)
		} else {
			 := .source
			if .KeyPath.Namespace != "file" {
				 = baseFileNameForVirtualModulePath(.KeyPath.Text)
			} else if ,  := .fs.Rel(.options.AbsOutputBase, .KeyPath.Text);  {
				 = .fs.Dir()
				 = .fs.Base()
				 = strings.ReplaceAll(, "\\", "/")
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.
				 := 0
				for strings.HasPrefix([*3:], "../") {
					++
				}
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.
					 = strings.Repeat("_.._/", ) + [*3:]
				}
			} else {
				 = .fs.Base(.KeyPath.Text)
			}
Swap the extension for the standard one
			 := .fs.Ext()
			 = [:len()-len()]
			switch .(type) {
			case *chunkReprJS:
				 += .options.OutputExtensionJS
			case *chunkReprCSS:
				 += .options.OutputExtensionCSS
			}
		}
Always use cross-platform path separators to avoid problems with Windows
		.entryPointRelPath = path.Join(, )
Create a chunk for the entry point here to ensure that the chunk is always generated even if the resulting file is empty
		 := newBitSet(uint(len(.entryPoints)))
		.setBit(uint())
		[string(.entries)] = chunkInfo{
			entryBits:             ,
			isEntryPoint:          true,
			sourceIndex:           ,
			entryPointBit:         uint(),
			relDir:                ,
			baseNameOrEmpty:       ,
			filesWithPartsInChunk: make(map[uint32]bool),
			chunkRepr:             ,
		}
	}
Figure out which files are in which chunk
	for ,  := range .reachableFiles {
		 := &.files[]
		switch repr := .repr.(type) {
		case *reprJS:
			for ,  := range .meta.partMeta {
				 := string(.entryBits.entries)
Ignore this part if it was never reached
					continue
				}
				,  := []
				if ! {
					.entryBits = .entryBits
					.filesWithPartsInChunk = make(map[uint32]bool)
					.relDir = .generatedChunkRelDir
					.chunkRepr = &chunkReprJS{}
					[] = 
				}
				.filesWithPartsInChunk[uint32()] = true
			}

		case *reprCSS:
			 := string(.entryBits.entries)
Ignore this file if it was never reached
				continue
			}
			,  := []
			if ! {
				.entryBits = .entryBits
				.filesWithPartsInChunk = make(map[uint32]bool)
				.relDir = .generatedChunkRelDir
				.chunkRepr = &chunkReprJS{}
				[] = 
			}
			.filesWithPartsInChunk[uint32()] = true
		}
	}
Sort the chunks for determinism. This mostly doesn't matter because each chunk is a separate file, but it matters for error messages in tests since tests stop on the first output mismatch.
	 := make([]string, 0, len())
	for  := range  {
		 = append(, )
	}
	sort.Strings()
	 := make([]chunkInfo, len())
	for ,  := range  {
		[] = []
	}
	return 
}

type chunkOrder struct {
	sourceIndex uint32
	distance    uint32
	path        logger.Path
}
This type is just so we can use Go's native sort function
type chunkOrderArray []chunkOrder

func ( chunkOrderArray) () int          { return len() }
func ( chunkOrderArray) ( int,  int) { [], [] = [], [] }

func ( chunkOrderArray) ( int,  int) bool {
	return [].distance < [].distance || ([].distance == [].distance && [].path.ComesBeforeInSortedOrder([].path))
}

func ( []partRange,  uint32,  uint32) []partRange {
	if  := len() - 1;  >= 0 {
		if  := &[]; .sourceIndex ==  && .partIndexEnd ==  {
			.partIndexEnd =  + 1
			return 
		}
	}

	return append(, partRange{
		sourceIndex:    ,
		partIndexBegin: ,
		partIndexEnd:    + 1,
	})
}

As an optimization, ignore parts containing a single import statement to an internal non-CommonJS file. These will be ignored anyway and it's a performance hit to spin up a goroutine only to discover this later.
	if len(.Stmts) == 1 {
		if ,  := .Stmts[0].Data.(*js_ast.SImport);  {
			 := &.ast.ImportRecords[.ImportRecordIndex]
			if .SourceIndex.IsValid() && !.files[.SourceIndex.GetIndex()].repr.(*reprJS).meta.cjsStyleExports {
				return false
			}
		}
	}
	return true
}

func ( *linkerContext) ( *chunkInfo) ( []uint32,  []partRange,  []uint32) {
	 := make(chunkOrderArray, 0, len(.filesWithPartsInChunk))
Attach information to the files for use with sorting
	for  := range .filesWithPartsInChunk {
		 := &.files[]
		 = append(, chunkOrder{
			sourceIndex: ,
			distance:    .distanceFromEntryPoint,
			path:        .source.KeyPath,
		})
	}
Sort so files closest to an entry point come first. If two files are equidistant to an entry point, then break the tie by sorting on the absolute path.
	sort.Sort()

	 := make(map[uint32]bool)
	 := []partRange{}
Traverse the graph using this stable order and linearize the files with dependencies before dependents
	var  func(uint32)
	 = func( uint32) {
		if [] {
			return
		}

		[] = true
		 := &.files[]
		 := .entryBits.equals(.entryBits)

		switch repr := .repr.(type) {
CommonJS files can't be split because they are all inside the wrapper
			 := !.meta.cjsWrap
Make sure the generated call to "__export(exports, ...)" comes first before anything else in this file
			if  && .entryBits.equals(.meta.partMeta[.meta.nsExportPartIndex].entryBits) {
				 = appendOrExtendPartRange(, , .meta.nsExportPartIndex)
			}

			for ,  := range .ast.Parts {
				 := .entryBits.equals(.meta.partMeta[].entryBits)
Also traverse any files imported by this part
				for ,  := range .ImportRecordIndices {
					 := &.ast.ImportRecords[]
					if .SourceIndex.IsValid() && (.Kind == ast.ImportStmt || ) {
Don't follow import() dependencies
							continue
						}
						(.SourceIndex.GetIndex())
					}
				}
Then include this part after the files it imports
				if  {
					 = true
					if  && uint32() != .meta.nsExportPartIndex && .shouldIncludePart(, ) {
						if  == runtime.SourceIndex {
							 = appendOrExtendPartRange(, , uint32())
						} else {
							 = appendOrExtendPartRange(, , uint32())
						}
					}
				}
			}

			if  {
				 = append(, )
CommonJS files are all-or-nothing so all parts must be contiguous
				if ! {
					 = append(, partRange{
						sourceIndex:    ,
						partIndexBegin: 0,
						partIndexEnd:   uint32(len(.ast.Parts)),
					})
				}
			}

		case *reprCSS:
All imported files come first
				for ,  := range .ast.ImportRecords {
					if .SourceIndex.IsValid() {
						(.SourceIndex.GetIndex())
					}
				}
Then this file comes afterward
				 = append(, )
			}
		}
	}
Always put the runtime code first before anything else
	(runtime.SourceIndex)
	for ,  := range  {
		(.sourceIndex)
	}
	 = append(, ...)
	return
}

func ( *linkerContext) (
	 uint32,
	 *stmtList,
	 []js_ast.Stmt,
	 logger.Loc,
	 js_ast.Ref,
	 uint32,
Is this an import from another module inside this bundle?
	 := .files[].repr.(*reprJS)
	 := &.ast.ImportRecords[]
	if .SourceIndex.IsValid() {
Remove the statement entirely if this is not a CommonJS module
			return true
		}
If this is an external module and the output format allows ES6 import/export syntax, then just keep the statement
		return false
	}
We don't need a call to "require()" if this is a self-import inside a CommonJS-style module, since we can just reference the exports directly.
	if .meta.cjsStyleExports && js_ast.FollowSymbols(.symbols, ) == .ast.ExportsRef {
		return true
	}
Replace the statement with a call to "require()"
	.prefixStmts = append(.prefixStmts, js_ast.Stmt{
		Loc: ,
		Data: &js_ast.SLocal{Decls: []js_ast.Decl{{
			Binding: js_ast.Binding{Loc: , Data: &js_ast.BIdentifier{Ref: }},
			Value:   &js_ast.Expr{Loc: .Range.Loc, Data: &js_ast.ERequire{ImportRecordIndex: }},
		}}},
	})
	return true
}

func ( *linkerContext) ( uint32,  *stmtList,  []js_ast.Stmt) {
	 := &.files[]
	 := .options.Mode != config.ModePassThrough || !.isEntryPoint
	 := .repr.(*reprJS)
	 := .meta.cjsWrap

	for ,  := range  {
		switch s := .Data.(type) {
"import * as ns from 'path'" "import {foo} from 'path'"
			if .shouldRemoveImportExportStmt(, , , .Loc, .NamespaceRef, .ImportRecordIndex) {
				continue
			}
Make sure these don't end up in a CommonJS wrapper
			if  {
				.es6StmtsForCJSWrap = append(.es6StmtsForCJSWrap, )
				continue
			}

		case *js_ast.SExportStar:
"export * from 'path'"
				if  {
					 := &.ast.ImportRecords[.ImportRecordIndex]
Is this export star evaluated at run time?
Turn this statement into "import * as ns from 'path'"
Prefix this module with "__exportStar(exports, ns)"
							 := .files[runtime.SourceIndex].repr.(*reprJS).ast.ModuleScope.Members["__exportStar"].Ref
							.prefixStmts = append(.prefixStmts, js_ast.Stmt{
								Loc: .Loc,
								Data: &js_ast.SExpr{Value: js_ast.Expr{Loc: .Loc, Data: &js_ast.ECall{
									Target: js_ast.Expr{Loc: .Loc, Data: &js_ast.EIdentifier{Ref: }},
									Args: []js_ast.Expr{
										{Loc: .Loc, Data: &js_ast.EIdentifier{Ref: .ast.ExportsRef}},
										{Loc: .Loc, Data: &js_ast.EIdentifier{Ref: .NamespaceRef}},
									},
								}}},
							})
Make sure these don't end up in a CommonJS wrapper
							if  {
								.es6StmtsForCJSWrap = append(.es6StmtsForCJSWrap, )
								continue
							}
						}
					} else {
Prefix this module with "__exportStar(exports, require(path))"
							 := .files[runtime.SourceIndex].repr.(*reprJS).ast.ModuleScope.Members["__exportStar"].Ref
							.prefixStmts = append(.prefixStmts, js_ast.Stmt{
								Loc: .Loc,
								Data: &js_ast.SExpr{Value: js_ast.Expr{Loc: .Loc, Data: &js_ast.ECall{
									Target: js_ast.Expr{Loc: .Loc, Data: &js_ast.EIdentifier{Ref: }},
									Args: []js_ast.Expr{
										{Loc: .Loc, Data: &js_ast.EIdentifier{Ref: .ast.ExportsRef}},
										{Loc: .Range.Loc, Data: &js_ast.ERequire{ImportRecordIndex: .ImportRecordIndex}},
									},
								}}},
							})
						}
Remove the export star statement
						continue
					}
				}
"export * as ns from 'path'"
				if .shouldRemoveImportExportStmt(, , , .Loc, .NamespaceRef, .ImportRecordIndex) {
					continue
				}

Turn this statement into "import * as ns from 'path'"
Make sure these don't end up in a CommonJS wrapper
				if  {
					.es6StmtsForCJSWrap = append(.es6StmtsForCJSWrap, )
					continue
				}
			}

"export {foo} from 'path'"
			if .shouldRemoveImportExportStmt(, , , .Loc, .NamespaceRef, .ImportRecordIndex) {
				continue
			}

Turn this statement into "import {foo} from 'path'"
Make sure these don't end up in a CommonJS wrapper
			if  {
				.es6StmtsForCJSWrap = append(.es6StmtsForCJSWrap, )
				continue
			}

		case *js_ast.SExportClause:
Remove export statements entirely
				continue
			}
Make sure these don't end up in a CommonJS wrapper
			if  {
				.es6StmtsForCJSWrap = append(.es6StmtsForCJSWrap, )
				continue
			}

Strip the "export" keyword while bundling
Be careful to not modify the original statement
				 := *
				.IsExport = false
				.Data = &
			}

		case *js_ast.SClass:
Be careful to not modify the original statement
				 := *
				.IsExport = false
				.Data = &
			}

		case *js_ast.SLocal:
Be careful to not modify the original statement
				 := *
				.IsExport = false
				.Data = &
			}

If we're bundling, convert "export default" into a normal declaration
			if  {
"export default foo;" => "var default = foo;"
					 = js_ast.Stmt{Loc: .Loc, Data: &js_ast.SLocal{Decls: []js_ast.Decl{
						{Binding: js_ast.Binding{Loc: .DefaultName.Loc, Data: &js_ast.BIdentifier{Ref: .DefaultName.Ref}}, Value: .Value.Expr},
					}}}
				} else {
					switch s2 := .Value.Stmt.Data.(type) {
"export default function() {}" => "function default() {}" "export default function foo() {}" => "function foo() {}"
Be careful to not modify the original statement
						 = &js_ast.SFunction{Fn: .Fn}
						.Fn.Name = &.DefaultName

						 = js_ast.Stmt{Loc: .Value.Stmt.Loc, Data: }

"export default class {}" => "class default {}" "export default class Foo {}" => "class Foo {}"
Be careful to not modify the original statement
						 = &js_ast.SClass{Class: .Class}
						.Class.Name = &.DefaultName

						 = js_ast.Stmt{Loc: .Value.Stmt.Loc, Data: }

					default:
						panic("Internal error")
					}
				}
			}
		}

		.normalStmts = append(.normalStmts, )
	}
}
"var a = 1; var b = 2;" => "var a = 1, b = 2;"
func ( []js_ast.Stmt) []js_ast.Stmt {
	if len() == 0 {
		return 
	}

	 := false
	 := 1

Try to merge with the previous variable statement
		if ,  := .Data.(*js_ast.SLocal);  {
It must be the same kind of variable statement (i.e. let/var/const)
				if .Kind == .Kind && .IsExport == .IsExport {
Avoid O(n^2) behavior for repeated variable declarations
						.Decls = append(.Decls, .Decls...)
Be careful to not modify the original statement
						 = true
						 := *
						.Decls = make([]js_ast.Decl, 0, len(.Decls)+len(.Decls))
						.Decls = append(.Decls, .Decls...)
						.Decls = append(.Decls, .Decls...)
						[-1].Data = &
					}
					continue
				}
			}
		}
Otherwise, append a normal statement
		 = false
		[] = 
		++
	}

	return [:]
}

These statements come first, and can be inside the CommonJS wrapper
These statements come last, and can be inside the CommonJS wrapper
Order doesn't matter for these statements, but they must be outside any CommonJS wrapper since they are top-level ES6 import/export statements
These statements are for an entry point and come at the end of the chunk
If this is an entry point, this is optional code to stick on the end of the chunk. This is used to for example trigger the lazily-evaluated CommonJS wrapper for the entry point.
This is the line and column offset since the previous JavaScript string or the start of the file if this is the first JavaScript string.
	generatedOffset lineColumnOffset
}

func ( *linkerContext) (
	 renamer.Renamer,
	 *sync.WaitGroup,
	 partRange,
	 bitSet,
	 string,
	 js_ast.Ref,
	 js_ast.Ref,
	 *compileResultJS,
	 []dataForSourceMap,
) {
	 := &.files[.sourceIndex]
	 := .repr.(*reprJS)
	 := .meta.nsExportPartIndex
	 := false
	 := stmtList{}
Make sure the generated call to "__export(exports, ...)" comes first before anything else.
	if  >= .partIndexBegin &&  < .partIndexEnd &&
		.equals(.meta.partMeta[].entryBits) {
		.convertStmtsForChunk(.sourceIndex, &, .ast.Parts[].Stmts)
Move everything to the prefix list
		.prefixStmts = append(.prefixStmts, .normalStmts...)
		.normalStmts = nil
	}
Add all other parts in this chunk
	for  := .partIndexBegin;  < .partIndexEnd; ++ {
		 := .ast.Parts[]
Skip the part if it's not in this chunk
			continue
		}

Skip the generated call to "__export()" that was extracted above
			continue
		}
Mark if we hit the dummy part representing the CommonJS wrapper
		if uint32() == .meta.cjsWrapperPartIndex.GetIndex() {
			 = true
			continue
		}
Emit export statements in the entry point part verbatim
		if uint32() == .meta.entryPointExportPartIndex.GetIndex() {
			.entryPointTail = append(.entryPointTail, .Stmts...)
			continue
		}

		.convertStmtsForChunk(.sourceIndex, &, .Stmts)
	}
Hoist all import statements before any normal statements. ES6 imports are different than CommonJS imports. All modules imported via ES6 import statements are evaluated before the module doing the importing is evaluated (well, except for cyclic import scenarios). We need to preserve these semantics even when modules imported via ES6 import statements end up being CommonJS modules.
	 := .normalStmts
	if len(.prefixStmts) > 0 {
		 = append(.prefixStmts, ...)
	}
	if .options.MangleSyntax {
		 = mergeAdjacentLocalStmts()
	}
Optionally wrap all statements in a closure for CommonJS
Only include the arguments that are actually used
"__commonJS((exports, module) => { ... })"
		var  js_ast.Expr
		if .options.UnsupportedJSFeatures.Has(compat.Arrow) {
			 = js_ast.Expr{Data: &js_ast.ECall{
				Target: js_ast.Expr{Data: &js_ast.EIdentifier{Ref: }},
				Args:   []js_ast.Expr{{Data: &js_ast.EFunction{Fn: js_ast.Fn{Args: , Body: js_ast.FnBody{Stmts: }}}}},
			}}
		} else {
			 = js_ast.Expr{Data: &js_ast.ECall{
				Target: js_ast.Expr{Data: &js_ast.EIdentifier{Ref: }},
				Args:   []js_ast.Expr{{Data: &js_ast.EArrow{Args: , Body: js_ast.FnBody{Stmts: }}}},
			}}
		}
"var require_foo = __commonJS((exports, module) => { ... });"
Only generate a source map if needed
	var  bool
	var  *sourcemap.SourceMap
	var  []js_printer.LineOffsetTable
	if .loader.CanHaveSourceMap() && .options.SourceMap != config.SourceMapNone {
		 = true
		 = .sourceMap
		 = [.sourceIndex].lineOffsetTables
	}
Indent the file if everything is wrapped in an IIFE
	 := 0
	if .options.OutputFormat == config.FormatIIFE {
		++
	}
Convert the AST to JavaScript code
	 := js_printer.Options{
		Indent:              ,
		OutputFormat:        .options.OutputFormat,
		RemoveWhitespace:    .options.RemoveWhitespace,
		MangleSyntax:        .options.MangleSyntax,
		ASCIIOnly:           .options.ASCIIOnly,
		ToModuleRef:         ,
		ExtractComments:     .options.Mode == config.ModeBundle && .options.RemoveWhitespace,
		UnsupportedFeatures: .options.UnsupportedJSFeatures,
		AddSourceMappings:   ,
		InputSourceMap:      ,
		LineOffsetTables:    ,
		WrapperRefForSource: func( uint32) js_ast.Ref {
			return .files[].repr.(*reprJS).ast.WrapperRef
		},
	}
	 := .ast
	.Directive = "" // This is handled elsewhere
	.Parts = []js_ast.Part{{Stmts: }}
	* = compileResultJS{
		PrintResult: js_printer.Print(, .symbols, , ),
		sourceIndex: .sourceIndex,
	}
Write this separately as the entry point tail so it can be split off from the main entry point code. This is sometimes required to deal with CommonJS import cycles.
	if len(.entryPointTail) > 0 {
		 := .ast
		.Parts = []js_ast.Part{{Stmts: .entryPointTail}}
		 := js_printer.Print(, .symbols, , )
		.entryPointTail = &
	}

	.Done()
}

Determine the reserved names (e.g. can't generate the name "if")
	 := make([]*js_ast.Scope, len())
	for ,  := range  {
		[] = .files[].repr.(*reprJS).ast.ModuleScope
	}
	 := renamer.ComputeReservedNames(, .symbols)
These are used to implement bundling, and need to be free for use
	if .options.Mode != config.ModePassThrough {
		["require"] = 1
		["Promise"] = 1
	}
Minification uses frequency analysis to give shorter names to more frequent symbols
Determine the first top-level slot (i.e. not in a nested scope)
		var  js_ast.SlotCounts
		for ,  := range  {
			.UnionMax(.files[].repr.(*reprJS).ast.NestedScopeSlotCounts)
		}
		 := renamer.NewMinifyRenamer(.symbols, , )
Accumulate symbol usage counts into their slots
		 := js_ast.CharFreq{}
		for ,  := range  {
			 := .files[].repr.(*reprJS)
			if .ast.CharFreq != nil {
				.Include(.ast.CharFreq)
			}
			if .ast.UsesExportsRef {
				.AccumulateSymbolCount(.ast.ExportsRef, 1)
			}
			if .ast.UsesModuleRef {
				.AccumulateSymbolCount(.ast.ModuleRef, 1)
			}

			for ,  := range .ast.Parts {
Skip the part if it's not in this chunk
					continue
				}
Accumulate symbol use counts
Make sure to also count the declaration in addition to the uses
				for ,  := range .DeclaredSymbols {
					.AccumulateSymbolCount(.Ref, 1)
				}
			}
		}
Add all of the character frequency histograms for all files in this chunk together, then use it to compute the character sequence used to generate minified names. This results in slightly better gzip compression over assigning minified names in order (i.e. "a b c ..."). Even though it's a very small win, we still do it because it's simple to do and very cheap to compute.
		 := .Compile()
		.AssignNamesByFrequency(&)
		return 
	}
When we're not minifying, just append numbers to symbol names to avoid collisions
	 := renamer.NewNumberRenamer(.symbols, )
	 := make(map[uint32][]*js_ast.Scope)
Make sure imports get a chance to be renamed
	var  renamer.StableRefArray
	for ,  := range .chunkRepr.(*chunkReprJS).importsFromOtherChunks {
		for ,  := range  {
			 = append(, renamer.StableRef{
				StableOuterIndex: .stableSourceIndices[.ref.OuterIndex],
				Ref:              .ref,
			})
		}
	}
	sort.Sort()
	for ,  := range  {
		.AddTopLevelSymbol(.Ref)
	}

	for ,  := range  {
		 := .files[].repr.(*reprJS)
		var  []*js_ast.Scope
Modules wrapped in a CommonJS closure look like this: // foo.js var require_foo = __commonJS((exports, module) => { ... }); The symbol "require_foo" is stored in "file.ast.WrapperRef". We want to be able to minify everything inside the closure without worrying about collisions with other CommonJS modules. Set up the scopes such that it appears as if the file was structured this way all along. It's not completely accurate (e.g. we don't set the parent of the module scope to this new top-level scope) but it's good enough for the renaming code.
External import statements will be hoisted outside of the CommonJS wrapper if the output format supports import statements. We need to add those symbols to the top-level scope to avoid causing name collisions. This code special-cases only those symbols.
			if .options.OutputFormat.KeepES6ImportExportSyntax() {
				for ,  := range .ast.Parts {
					for ,  := range .Stmts {
						switch s := .Data.(type) {
						case *js_ast.SImport:
							if !.ast.ImportRecords[.ImportRecordIndex].SourceIndex.IsValid() {
								.AddTopLevelSymbol(.NamespaceRef)
								if .DefaultName != nil {
									.AddTopLevelSymbol(.DefaultName.Ref)
								}
								if .Items != nil {
									for ,  := range *.Items {
										.AddTopLevelSymbol(.Name.Ref)
									}
								}
							}

						case *js_ast.SExportStar:
							if !.ast.ImportRecords[.ImportRecordIndex].SourceIndex.IsValid() {
								.AddTopLevelSymbol(.NamespaceRef)
							}

						case *js_ast.SExportFrom:
							if !.ast.ImportRecords[.ImportRecordIndex].SourceIndex.IsValid() {
								.AddTopLevelSymbol(.NamespaceRef)
								for ,  := range .Items {
									.AddTopLevelSymbol(.Name.Ref)
								}
							}
						}
					}
				}
			}

			[] = []*js_ast.Scope{.ast.ModuleScope}
			continue
		}
Rename each top-level symbol declaration in this chunk
		for ,  := range .ast.Parts {
			if .entryBits.equals(.meta.partMeta[].entryBits) {
				for ,  := range .DeclaredSymbols {
					if .IsTopLevel {
						.AddTopLevelSymbol(.Ref)
					}
				}
				 = append(, .Scopes...)
			}
		}

		[] = 
	}
Recursively rename symbols in child scopes now that all top-level symbols have been renamed. This is done in parallel because the symbols inside nested scopes are independent and can't conflict.
	.AssignNamesByScope()
	return 
}

func ( *chunkReprJS) ( *linkerContext,  *chunkInfo) func(generateContinue) []OutputFile {
	var  []OutputFile
	 := make([]compileResultJS, 0, len(.partsInChunkInOrder))
	 := .files[runtime.SourceIndex].repr.(*reprJS).ast.ModuleScope.Members
	 := js_ast.FollowSymbols(.symbols, ["__commonJS"].Ref)
	 := js_ast.FollowSymbols(.symbols, ["__toModule"].Ref)
	 := .renameSymbolsInChunk(, .filesInChunkInOrder)
	 := .fs.Join(.options.AbsOutputDir, .relDir)
	 := .dataForSourceMaps()
Generate JavaScript for each file in parallel
	 := sync.WaitGroup{}
Skip the runtime in test output
		if .sourceIndex == runtime.SourceIndex && .options.OmitRuntimeForTests {
			continue
		}
Create a goroutine for this file
		 = append(, compileResultJS{})
		 := &[len()-1]
		.Add(1)
		go .generateCodeForFileInChunkJS(
			,
			&,
			,
			.entryBits,
			,
			,
			,
			,
			,
		)
	}
Each file may optionally contain additional files to be copied to the output directory. This is used by the "file" loader.
	for ,  := range .filesInChunkInOrder {
		 = append(, .files[].additionalFiles...)
	}
Wait for cross-chunk import records before continuing
Also generate the cross-chunk binding code
		var  []byte
		var  []byte
Indent the file if everything is wrapped in an IIFE
			 := 0
			if .options.OutputFormat == config.FormatIIFE {
				++
			}
			 := js_printer.Options{
				Indent:           ,
				OutputFormat:     .options.OutputFormat,
				RemoveWhitespace: .options.RemoveWhitespace,
				MangleSyntax:     .options.MangleSyntax,
			}
			 = js_printer.Print(js_ast.AST{
				ImportRecords: .crossChunkImportRecords,
				Parts:         []js_ast.Part{{Stmts: .crossChunkPrefixStmts}},
			}, .symbols, , ).JS
			 = js_printer.Print(js_ast.AST{
				Parts: []js_ast.Part{{Stmts: .crossChunkSuffixStmts}},
			}, .symbols, , ).JS
		}

		.Wait()

		 := js_printer.Joiner{}
		 := lineColumnOffset{}
Optionally strip whitespace
		 := ""
		 := " "
		 := "\n"
		if .options.RemoveWhitespace {
			 = ""
			 = ""
		}
		 := false
		 := false

		if .isEntryPoint {
			 := .files[.sourceIndex].repr.(*reprJS)
Start with the hashbang if there is one
			if .ast.Hashbang != "" {
				 := .ast.Hashbang + "\n"
				.advanceString()
				.AddString()
				 = true
				 = true
			}
Add the top-level directive if present
			if .ast.Directive != "" {
				 := string(js_printer.QuoteForJSON(.ast.Directive, .options.ASCIIOnly)) + ";" + 
				.advanceString()
				.AddString()
				 = true
			}
		}

		if len(.options.Banner) > 0 {
			.advanceString(.options.Banner)
			.advanceString("\n")
			.AddString(.options.Banner)
			.AddString("\n")
		}
Optionally wrap with an IIFE
		if .options.OutputFormat == config.FormatIIFE {
			var  string
			 = "  "
			if len(.options.GlobalName) > 0 {
				 = .generateGlobalNamePrefix()
			}
			if .options.UnsupportedJSFeatures.Has(compat.Arrow) {
				 += "(function()" +  + "{" + 
			} else {
				 += "(()" +  + "=>" +  + "{" + 
			}
			.advanceString()
			.AddString()
			 = false
		}
Put the cross-chunk prefix inside the IIFE
		if len() > 0 {
			 = true
			.advanceBytes()
			.AddBytes()
		}
Start the metadata
		 := js_printer.Joiner{}
Print imports
			 := true
			.AddString("{\n      \"imports\": [")
			for ,  := range .crossChunkAbsPaths {
				if  {
					 = false
				} else {
					.AddString(",")
				}
				.AddString(fmt.Sprintf("\n        {\n          \"path\": %s,\n          \"kind\": %s\n        }",
					js_printer.QuoteForJSON(.res.PrettyPath(logger.Path{Text: , Namespace: "file"}), .options.ASCIIOnly),
					js_printer.QuoteForJSON(.crossChunkImportRecords[].Kind.StringForMetafile(), .options.ASCIIOnly)))
			}
			if ! {
				.AddString("\n      ")
			}
Print exports
			.AddString("],\n      \"exports\": [")
			var  []string
			if .options.OutputFormat.KeepES6ImportExportSyntax() {
				if .isEntryPoint {
					if  := .files[.sourceIndex].repr.(*reprJS); .meta.cjsWrap {
						 = []string{"default"}
					} else {
						 := .meta.resolvedExports
						 = make([]string, 0, len())
						for  := range  {
							if  != "*" {
								 = append(, )
							}
						}
					}
				} else {
					 = make([]string, 0, len(.exportsToOtherChunks))
					for ,  := range .exportsToOtherChunks {
						 = append(, )
					}
				}
			}
			 = true
			sort.Strings() // Sort for determinism
			for ,  := range  {
				if  {
					 = false
				} else {
					.AddString(",")
				}
				.AddString(fmt.Sprintf("\n        %s",
					js_printer.QuoteForJSON(, .options.ASCIIOnly)))
			}
			if ! {
				.AddString("\n      ")
			}
			if .isEntryPoint {
				 := .files[.sourceIndex].source.PrettyPath
				.AddString(fmt.Sprintf("],\n      \"entryPoint\": %s,\n      \"inputs\": {", js_printer.QuoteForJSON(, .options.ASCIIOnly)))
			} else {
				.AddString("],\n      \"inputs\": {")
			}
		}
Concatenate the generated JavaScript chunks together
		var  []compileResultJS
		var  *js_printer.PrintResult
		var  []string
		var  []string
		var  map[string]int
		 := make(map[string]bool)
		 := uint32(0)
		if .options.AbsMetadataFile != "" {
			 = make([]string, 0, len())
			 = make(map[string]int, len())
		}
		for ,  := range  {
			 := .sourceIndex == runtime.SourceIndex
			for  := range .ExtractedComments {
				if ![] {
					[] = true
					 = append(, )
				}
			}
If this is the entry point, it may have some extra code to stick at the end of the chunk after all modules have evaluated
			if .entryPointTail != nil {
				 = .entryPointTail
			}
Add a comment with the file path before the file contents
			if .options.Mode == config.ModeBundle && !.options.RemoveWhitespace &&  != .sourceIndex && len(.JS) > 0 {
				if  {
					.advanceString("\n")
					.AddString("\n")
				}

				 := .files[.sourceIndex].source.PrettyPath
Make sure newlines in the path can't cause a syntax error. This does not minimize allocations because it's expected that this case never comes up in practice.
				 = strings.ReplaceAll(, "\r", "\\r")
				 = strings.ReplaceAll(, "\n", "\\n")
				 = strings.ReplaceAll(, "\u2028", "\\u2028")
				 = strings.ReplaceAll(, "\u2029", "\\u2029")

				 := fmt.Sprintf("%s// %s\n", , )
				.advanceString()
				.AddString()
				 = .sourceIndex
			}
Don't include the runtime in source maps
			if  {
				.advanceString(string(.JS))
				.AddBytes(.JS)
Save the offset to the start of the stored JavaScript
				.generatedOffset = 
				.AddBytes(.JS)
Ignore empty source map chunks
				if .SourceMapChunk.ShouldIgnore {
					.advanceBytes(.JS)
				} else {
					 = lineColumnOffset{}
Include this file in the source map
					if .options.SourceMap != config.SourceMapNone {
						 = append(, )
					}
				}
Include this file in the metadata
Accumulate file sizes since a given file may be split into multiple parts
					 := .files[.sourceIndex].source.PrettyPath
					if ,  := [];  {
						[] =  + len(.JS)
					} else {
						 = append(, )
						[] = len(.JS)
					}
				}
			}
Put a newline before the next file path comment
			if len(.JS) > 0 {
				 = true
			}
		}
Stick the entry point tail at the end of the file. Deliberately don't include any source mapping information for this because it's automatically generated and doesn't correspond to a location in the input file.
		if  != nil {
			.AddBytes(.JS)
		}
Put the cross-chunk suffix inside the IIFE
		if len() > 0 {
			if  {
				.AddString()
			}
			.AddBytes()
		}
Optionally wrap with an IIFE
		if .options.OutputFormat == config.FormatIIFE {
			.AddString("})();" + )
		}
Make sure the file ends with a newline
		if .Length() > 0 && .LastByte() != '\n' {
			.AddString("\n")
		}
Add all unique license comments to the end of the file. These are deduplicated because some projects have thousands of files with the same comment. The comment must be preserved in the output for legal reasons but at the same time we want to generate a small bundle when minifying.
		sort.Strings()
		for ,  := range  {
			.AddString()
			.AddString("\n")
		}

		if len(.options.Footer) > 0 {
			.AddString(.options.Footer)
			.AddString("\n")
		}

		if .options.SourceMap != config.SourceMapNone {
			 := .generateSourceMapForChunk(, , )
			var  bool
			var  bool
			switch .options.SourceMap {
			case config.SourceMapInline:
				 = true
			case config.SourceMapLinkedWithComment, config.SourceMapExternalWithoutComment:
				 = true
			case config.SourceMapInlineAndExternal:
				 = true
				 = true
			}
Write the generated source map as an inline comment
			if  {
				.AddString("//# sourceMappingURL=data:application/json;base64,")
				.AddString(base64.StdEncoding.EncodeToString())
				.AddString("\n")
			}
Write the generated source map as an external file
Optionally add metadata about the file
				var  []byte
				if .options.AbsMetadataFile != "" {
					 = []byte(fmt.Sprintf(
						"{\n      \"imports\": [],\n      \"exports\": [],\n      \"inputs\": {},\n      \"bytes\": %d\n    }", len()))
				}
Figure out the base name for the source map which may include the content hash
				 := .baseNameOrEmpty
				 := .relDir
				if  == "" {
					var  string
					 := "chunk"
					if config.HasPlaceholder(.options.ChunkPathTemplate, config.HashPlaceholder) {
						 = .chunkHashForFileName(, )
					}

					 := config.TemplateToString(config.SubstituteTemplate(.options.ChunkPathTemplate, config.PathPlaceholders{
						Name: &,
						Hash: &,
					})) + .options.OutputExtensionJS

					 = path.Base()
					 = [:len()-len()]
				}
				 += ".map"
Add a comment linking the source to its map
				if .options.SourceMap == config.SourceMapLinkedWithComment {
					.AddString("//# sourceMappingURL=")
					.AddString()
					.AddString("\n")
				}

				 = append(, OutputFile{
					AbsPath:           .fs.Join(.options.AbsOutputDir, , ),
					Contents:          ,
					jsonMetadataChunk: ,
				})
			}
		}
The JavaScript contents are done now that the source map comment is in
		 := .Done()
Figure out the base name for this chunk now that the content hash is known
		if .baseNameOrEmpty == "" {
			var  string
			 := "chunk"
			if config.HasPlaceholder(.options.ChunkPathTemplate, config.HashPlaceholder) {
				 = .chunkHashForFileName(, )
			}

			 := config.TemplateToString(config.SubstituteTemplate(.options.ChunkPathTemplate, config.PathPlaceholders{
				Name: &,
				Hash: &,
			})) + .options.OutputExtensionJS

			.baseNameOrEmpty = path.Base()
			.relDir = [:len()-len(.baseNameOrEmpty)]
		}
End the metadata
		var  []byte
		if .options.AbsMetadataFile != "" {
			 := true
			for ,  := range  {
				if  {
					 = false
				} else {
					.AddString(",")
				}
				.AddString(fmt.Sprintf("\n        %s: {\n          \"bytesInOutput\": %d\n        }",
					js_printer.QuoteForJSON(, .options.ASCIIOnly), []))
			}
			if ! {
				.AddString("\n      ")
			}
			.AddString(fmt.Sprintf("},\n      \"bytes\": %d\n    }", len()))
			 = .Done()
		}

		 = append(, OutputFile{
			AbsPath:           .fs.Join(.options.AbsOutputDir, .relPath()),
			Contents:          ,
			jsonMetadataChunk: ,
			IsExecutable:      ,
		})
		return 
	}
}

func ( *linkerContext) () string {
	var  string
	 := .options.GlobalName[0]
	 := " "
	 := ";\n"

	if .options.RemoveWhitespace {
		 = ""
		 = ";"
	}

	if js_printer.CanQuoteIdentifier(, .options.UnsupportedJSFeatures, .options.ASCIIOnly) {
		if .options.ASCIIOnly {
			 = string(js_printer.QuoteIdentifier(nil, , .options.UnsupportedJSFeatures))
		}
		 = fmt.Sprintf("var %s%s=%s", , , )
	} else {
		 = fmt.Sprintf("this[%s]", js_printer.QuoteForJSON(, .options.ASCIIOnly))
		 = fmt.Sprintf("%s%s=%s", , , )
	}

	for ,  := range .options.GlobalName[1:] {
		 := 
		if js_printer.CanQuoteIdentifier(, .options.UnsupportedJSFeatures, .options.ASCIIOnly) {
			if .options.ASCIIOnly {
				 = string(js_printer.QuoteIdentifier(nil, , .options.UnsupportedJSFeatures))
			}
			 = fmt.Sprintf("%s.%s", , )
		} else {
			 = fmt.Sprintf("%s[%s]", , js_printer.QuoteForJSON(, .options.ASCIIOnly))
		}
		 += fmt.Sprintf("%s%s||%s{}%s%s%s=%s", , , , , , , )
	}

	return 
}

type compileResultCSS struct {
	printedCSS            string
	sourceIndex           uint32
	hasCharset            bool
	externalImportRecords []ast.ImportRecord
}

func ( *chunkReprCSS) ( *linkerContext,  *chunkInfo) func(generateContinue) []OutputFile {
	var  []OutputFile
	 := make([]compileResultCSS, 0, len(.filesInChunkInOrder))
Generate CSS for each file in parallel
	 := sync.WaitGroup{}
Each file may optionally contain additional files to be copied to the output directory. This is used by the "file" loader.
		 = append(, .files[].additionalFiles...)
Create a goroutine for this file
		 = append(, compileResultCSS{})
		 := &[len()-1]
		.Add(1)
		go func( uint32,  *compileResultCSS) {
			 := &.files[]
			 := .repr.(*reprCSS).ast
Filter out "@import" rules
			 := make([]css_ast.R, 0, len(.Rules))
			for ,  := range .Rules {
				switch r := .(type) {
				case *css_ast.RAtCharset:
					.hasCharset = true
					continue
				case *css_ast.RAtImport:
					if  := .ImportRecords[.ImportRecordIndex]; !.SourceIndex.IsValid() {
						.externalImportRecords = append(.externalImportRecords, )
					}
					continue
				}
				 = append(, )
			}
			.Rules = 

			.printedCSS = css_printer.Print(, css_printer.Options{
				MangleSyntax:     .options.MangleSyntax,
				RemoveWhitespace: .options.RemoveWhitespace,
				ASCIIOnly:        .options.ASCIIOnly,
			})
			.sourceIndex = 
			.Done()
		}(, )
	}
Wait for cross-chunk import records before continuing
	return func( generateContinue) []OutputFile {
		.Wait()
		 := js_printer.Joiner{}
		 := false
Generate any prefix rules now
		{
			 := css_ast.AST{}
"@charset" is the only thing that comes before "@import"
			for ,  := range  {
				if .hasCharset {
					.Rules = append(.Rules, &css_ast.RAtCharset{Encoding: "UTF-8"})
					break
				}
			}
Insert all external "@import" rules at the front. In CSS, all "@import" rules must come first or the browser will just ignore them.
			for ,  := range  {
				for ,  := range .externalImportRecords {
					.Rules = append(.Rules, &css_ast.RAtImport{ImportRecordIndex: uint32(len(.ImportRecords))})
					.ImportRecords = append(.ImportRecords, )
				}
			}

			if len(.Rules) > 0 {
				 := css_printer.Print(, css_printer.Options{
					RemoveWhitespace: .options.RemoveWhitespace,
				})
				if len() > 0 {
					.AddString()
					 = true
				}
			}
		}
Start the metadata
		 := js_printer.Joiner{}
		if .options.AbsMetadataFile != "" {
			 := true
			.AddString("{\n      \"imports\": [")
			for ,  := range .crossChunkAbsPaths {
				if  {
					 = false
				} else {
					.AddString(",")
				}
				.AddString(fmt.Sprintf("\n        {\n          \"path\": %s,\n          \"kind\": %s\n        }",
					js_printer.QuoteForJSON(.res.PrettyPath(logger.Path{Text: , Namespace: "file"}), .options.ASCIIOnly),
					js_printer.QuoteForJSON(.crossChunkImportRecords[].Kind.StringForMetafile(), .options.ASCIIOnly)))
			}
			if ! {
				.AddString("\n      ")
			}
			if .isEntryPoint {
				 := &.files[.sourceIndex]
Do not generate "entryPoint" for CSS files that are the result of importing CSS into JavaScript. We want this to be a 1:1 relationship and there is already an output file for the JavaScript entry point.
				if ,  := .repr.(*reprCSS);  {
					.AddString(fmt.Sprintf("],\n      \"entryPoint\": %s,\n      \"inputs\": {",
						js_printer.QuoteForJSON(.source.PrettyPath, .options.ASCIIOnly)))
				} else {
					.AddString("],\n      \"inputs\": {")
				}
			} else {
				.AddString("],\n      \"inputs\": {")
			}
		}
		 := true
Concatenate the generated CSS chunks together
		for ,  := range  {
			if .options.Mode == config.ModeBundle && !.options.RemoveWhitespace {
				if  {
					.AddString("\n")
				}
				.AddString(fmt.Sprintf("/* %s */\n", .files[.sourceIndex].source.PrettyPath))
			}
			if len(.printedCSS) > 0 {
				 = true
			}
			.AddString(.printedCSS)
Include this file in the metadata
			if .options.AbsMetadataFile != "" {
				if  {
					 = false
				} else {
					.AddString(",")
				}
				.AddString(fmt.Sprintf("\n        %s: {\n          \"bytesInOutput\": %d\n        }",
					js_printer.QuoteForJSON(.files[.sourceIndex].source.PrettyPath, .options.ASCIIOnly),
					len(.printedCSS)))
			}
		}
Make sure the file ends with a newline
		if .Length() > 0 && .LastByte() != '\n' {
			.AddString("\n")
		}
The CSS contents are done now that the source map comment is in
		 := .Done()
Figure out the base name for this chunk now that the content hash is known
		if .baseNameOrEmpty == "" {
			var  string
			 := "chunk"
			if config.HasPlaceholder(.options.ChunkPathTemplate, config.HashPlaceholder) {
				 = .chunkHashForFileName(, )
			}

			 := config.TemplateToString(config.SubstituteTemplate(.options.ChunkPathTemplate, config.PathPlaceholders{
				Name: &,
				Hash: &,
			})) + .options.OutputExtensionCSS

			.baseNameOrEmpty = path.Base()
			.relDir = [:len()-len(.baseNameOrEmpty)]
		}
End the metadata
		var  []byte
		if .options.AbsMetadataFile != "" {
			if ! {
				.AddString("\n      ")
			}
			.AddString(fmt.Sprintf("},\n      \"bytes\": %d\n    }", len()))
			 = .Done()
		}

		 = append(, OutputFile{
			AbsPath:           .fs.Join(.options.AbsOutputDir, .relPath()),
			Contents:          ,
			jsonMetadataChunk: ,
		})
		return 
	}
}

func ( *lineColumnOffset) ( []byte) {
	for ,  := 0, len();  < ; ++ {
		if [] == '\n' {
			.lines++
			.columns = 0
		} else {
			.columns++
		}
	}
}

func ( *lineColumnOffset) ( string) {
	for ,  := 0, len();  < ; ++ {
		if [] == '\n' {
			.lines++
			.columns = 0
		} else {
			.columns++
		}
	}
}

func ( js_ast.Binding,  js_ast.SymbolMap) {
	switch b := .Data.(type) {
	case *js_ast.BMissing:

	case *js_ast.BIdentifier:
		.Get(.Ref).MustNotBeRenamed = true

	case *js_ast.BArray:
		for ,  := range .Items {
			(.Binding, )
		}

	case *js_ast.BObject:
		for ,  := range .Properties {
			(.Value, )
		}

	default:
		panic(fmt.Sprintf("Unexpected binding of type %T", .Data))
	}
}
Marking a symbol as unbound prevents it from being renamed or minified. This is only used when a module is compiled independently. We use a very different way of handling exports and renaming/minifying when bundling.
func ( *linkerContext) ( uint32) {
	,  := .files[].repr.(*reprJS)
	if ! {
		return
	}
	 := false

	for ,  := range .ast.Parts {
		for ,  := range .Stmts {
			switch s := .Data.(type) {
Ignore imports from the internal runtime code. These are generated automatically and aren't part of the original source code. We shouldn't consider the file a module if the only ES6 import or export is the automatically generated one.
				 := &.ast.ImportRecords[.ImportRecordIndex]
				if .SourceIndex.IsValid() && .SourceIndex.GetIndex() == runtime.SourceIndex {
					continue
				}

				 = true

			case *js_ast.SLocal:
				if .IsExport {
					for ,  := range .Decls {
						preventBindingsFromBeingRenamed(.Binding, .symbols)
					}
					 = true
				}

			case *js_ast.SFunction:
				if .IsExport {
					.symbols.Get(.Fn.Name.Ref).Kind = js_ast.SymbolUnbound
					 = true
				}

			case *js_ast.SClass:
				if .IsExport {
					.symbols.Get(.Class.Name.Ref).Kind = js_ast.SymbolUnbound
					 = true
				}

			case *js_ast.SExportClause, *js_ast.SExportDefault, *js_ast.SExportStar:
				 = true

			case *js_ast.SExportFrom:
				 = true
			}
		}
	}
Heuristic: If this module has top-level import or export statements, we consider this an ES6 module and only preserve the names of the exported symbols. Everything else is minified since the names are private. Otherwise, we consider this potentially a script-type file instead of an ES6 module. In that case, preserve the names of all top-level symbols since they are all potentially exported (e.g. if this is used in a <script> tag). All symbols in nested scopes are still minified.
	if ! {
		for ,  := range .ast.ModuleScope.Members {
			.symbols.Get(.Ref).MustNotBeRenamed = true
		}
	}
}

func ( *linkerContext) (
	 []compileResultJS,
	 string,
	 []dataForSourceMap,
) []byte {
	 := js_printer.Joiner{}
	.AddString("{\n  \"version\": 3")
Only write out the sources for a given source index once
	 := make(map[uint32]int)
Generate the "sources" and "sourcesContent" arrays
	type  struct {
		           logger.Path
		     string
		 []byte
	}
	 := make([], 0, len())
	 := 0
	for ,  := range  {
		if ,  := [.sourceIndex];  {
			continue
		}
		[.sourceIndex] = 
		 := &.files[.sourceIndex]
Simple case: no nested source map
		if .sourceMap == nil {
			var  []byte
			if !.options.ExcludeSourcesContent {
				 = [.sourceIndex].quotedContents[0]
			}
			 = append(, {
				:           .source.KeyPath,
				:     .source.PrettyPath,
				: ,
			})
			++
			continue
		}
Complex case: nested source map
		 := .sourceMap
		for ,  := range .Sources {
			 := logger.Path{
				Namespace: .source.KeyPath.Namespace,
				Text:      ,
			}
If this file is in the "file" namespace, change the relative path in the source map into an absolute path using the directory of this file
			if .Namespace == "file" {
				.Text = .fs.Join(.fs.Dir(.source.KeyPath.Text), )
			}

			var  []byte
			if !.options.ExcludeSourcesContent {
				 = [.sourceIndex].quotedContents[]
			}
			 = append(, {
				:           ,
				:     ,
				: ,
			})
		}
		 += len(.Sources)
	}
Write the sources
	.AddString(",\n  \"sources\": [")
	for ,  := range  {
		if  != 0 {
			.AddString(", ")
		}
Modify the absolute path to the original file to be relative to the directory that will contain the output file for this chunk
		if ..Namespace == "file" {
Make sure to always use forward slashes, even on Windows
				. = strings.ReplaceAll(, "\\", "/")
			}
		}

		.AddBytes(js_printer.QuoteForJSON(., .options.ASCIIOnly))
	}
	.AddString("]")
Write the sourcesContent
	if !.options.ExcludeSourcesContent {
		.AddString(",\n  \"sourcesContent\": [")
		for ,  := range  {
			if  != 0 {
				.AddString(", ")
			}
			.AddBytes(.)
		}
		.AddString("]")
	}
Write the mappings
	.AddString(",\n  \"mappings\": \"")
	 := js_printer.SourceMapState{}
	 := 0
	for ,  := range  {
		 := .SourceMapChunk
		 := .generatedOffset
		 := [.sourceIndex]
This should have already been checked earlier
		if .ShouldIgnore {
			panic("Internal error")
		}
Because each file for the bundle is converted to a source map once, the source maps are shared between all entry points in the bundle. The easiest way of getting this to work is to have all source maps generate as if their source index is 0. We then adjust the source index per entry point by modifying the first source mapping. This is done by AppendSourceMapChunk() using the source index passed here.
		 := js_printer.SourceMapState{
			SourceIndex:     ,
			GeneratedLine:   .lines,
			GeneratedColumn: .columns,
		}
		if .lines == 0 {
			.GeneratedColumn += 
		}
Append the precomputed source map chunk
		js_printer.AppendSourceMapChunk(&, , , .Buffer)
Generate the relative offset to start from next time
		 = .EndState
		.SourceIndex += 
		 = .FinalGeneratedColumn
If this was all one line, include the column offset from the start
		if .GeneratedLine == 0 {
			.GeneratedColumn += .GeneratedColumn
			 += .GeneratedColumn
		}
	}
	.AddString("\"")
Finish the source map
	.AddString(",\n  \"names\": []\n}\n")
	return .Done()
}

func ( *linkerContext) ( *chunkInfo,  []byte) string {
	 := sha1.New()
Hash the data in length-prefixed form because boundary locations are important. We don't want "a" + "bc" to hash the same as "ab" + "c".
	var  [4]byte
Mix the file names and part ranges of all of the files in this chunk into the hash. Objects that appear identical but that live in separate files or that live in separate parts in the same file must not be merged. This only needs to be done for JavaScript files, not CSS files.
	for ,  := range .partsInChunkInOrder {
		var  string
		 := &.files[.sourceIndex]

Use the pretty path as the file name since it should be platform- independent (relative paths and the "/" path separator)
			 = .source.PrettyPath
If this isn't in the "file" namespace, just use the full path text verbatim. This could be a source of cross-platform differences if plugins are storing platform-specific information in here, but then that problem isn't caused by esbuild itself.
			 = .source.KeyPath.Text
		}
Include the path namespace in the hash
		binary.LittleEndian.PutUint32([:], uint32(len(.source.KeyPath.Namespace)))
		.Write([:])
		.Write([]byte(.source.KeyPath.Namespace))
Then include the file path
		binary.LittleEndian.PutUint32([:], uint32(len()))
		.Write([:])
		.Write([]byte())
Also write the part range. These numbers are deterministic and allocated per-file so this should be a well-behaved base for a hash.
		binary.LittleEndian.PutUint32([:], .partIndexBegin)
		.Write([:])
		binary.LittleEndian.PutUint32([:], .partIndexEnd)
		.Write([:])
	}
Then mix the contents of the chunk itself into the hash
	.Write()

	var  [sha1.Size]byte
	.Sum([:0])
	return hashForFileName()