diff --git a/tsc/internal/compiler/contentmapper_test.go b/tsc/internal/compiler/contentmapper_test.go
index 31b8f831870e8..d477022346274 100644
--- a/tsc/internal/compiler/contentmapper_test.go
+++ b/tsc/internal/compiler/contentmapper_test.go
@@ -13,6 +13,7 @@ import (
"github.com/microsoft/TypeScript/tsc/internal/core"
"github.com/microsoft/TypeScript/tsc/internal/diagnostics"
"github.com/microsoft/TypeScript/tsc/internal/locale"
+ "github.com/microsoft/TypeScript/tsc/internal/outputpaths"
"github.com/microsoft/TypeScript/tsc/internal/spanmap"
"github.com/microsoft/TypeScript/tsc/internal/tsoptions"
"github.com/microsoft/TypeScript/tsc/internal/tspath"
@@ -46,6 +47,11 @@ func newContentMapperProgram(t *testing.T, contentMapperProject contentmapper.Pr
}
func newContentMapperProgramWithOptions(t *testing.T, contentMapperProject contentmapper.Project, files map[string]string, rootFiles []string, options *core.CompilerOptions) *compiler.Program {
+ t.Helper()
+ return newContentMapperProgramWithOutputExtensions(t, contentMapperProject, files, rootFiles, options, nil)
+}
+
+func newContentMapperProgramWithOutputExtensions(t *testing.T, contentMapperProject contentmapper.Project, files map[string]string, rootFiles []string, options *core.CompilerOptions, outputExtensions map[string]string) *compiler.Program {
t.Helper()
if !bundled.Embedded {
t.Skip("bundled files are not embedded")
@@ -57,7 +63,7 @@ func newContentMapperProgramWithOptions(t *testing.T, contentMapperProject conte
}
config := tsoptions.NewParsedCommandLine(options, testFileNames(rootFiles...), nil, "/", fs.CaseSensitivity())
- config.ParsedConfig.ContentMappers = []*contentmapper.Mapper{{Package: "vue", Extensions: []string{".vue"}, Name: "vue-mapper", Version: "1.0.0"}}
+ config.ParsedConfig.ContentMappers = []*contentmapper.Mapper{{Package: "vue", Extensions: []string{".vue"}, OutputExtensions: outputExtensions, Name: "vue-mapper", Version: "1.0.0"}}
return compiler.NewProgram(compiler.ProgramOptions{
Config: config,
Host: compiler.NewCompilerHost(fs, bundled.LibPath(), nil, nil, contentMapperProject),
@@ -68,7 +74,7 @@ func newContentMapperProgramWithOptions(t *testing.T, contentMapperProject conte
func TestContentMapperVirtualExtensionSetsImpliedNodeFormat(t *testing.T) {
t.Parallel()
- program := newContentMapperProgramWithOptions(
+ program := newContentMapperProgramWithOutputExtensions(
t,
fakeContentMapperHost{transform: func(fileName string, content string) (contentmapper.Result, error) {
return contentmapper.Result{Text: "export {};", VirtualExtension: ".mts", Mappings: spanmap.New(nil)}, nil
@@ -80,6 +86,7 @@ func TestContentMapperVirtualExtensionSetsImpliedNodeFormat(t *testing.T) {
Module: core.ModuleKindNodeNext,
ModuleResolution: core.ModuleResolutionKindNodeNext,
},
+ map[string]string{".vue": ".mjs"},
)
file := program.GetSourceFile("/src/Component.vue")
@@ -87,6 +94,282 @@ func TestContentMapperVirtualExtensionSetsImpliedNodeFormat(t *testing.T) {
assert.Equal(t, program.GetSourceFileMetaData(file.PathKey()).ImpliedNodeFormat, core.ResolutionModeESM)
}
+func TestContentMapperVirtualExtensionDeterminesModuleFormat(t *testing.T) {
+ t.Parallel()
+ tests := []struct {
+ name string
+ virtualExtension string
+ text string
+ module core.ModuleKind
+ moduleResolution core.ModuleResolutionKind
+ expectedFormat core.ModuleKind
+ expectedDiagnostic int32
+ }{
+ {
+ name: "cts",
+ virtualExtension: ".cts",
+ text: `import type { Foo } from "./dep"; declare const styles: { foo: string }; export = styles;`,
+ module: core.ModuleKindESNext,
+ moduleResolution: core.ModuleResolutionKindNode10,
+ expectedFormat: core.ModuleKindCommonJS,
+ expectedDiagnostic: diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead.Code(),
+ },
+ {
+ name: "mts",
+ virtualExtension: ".mts",
+ text: `import type { Foo } from "./dep"; export const value = 1;`,
+ module: core.ModuleKindCommonJS,
+ moduleResolution: core.ModuleResolutionKindNode10,
+ expectedFormat: core.ModuleKindESNext,
+ expectedDiagnostic: diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled.Code(),
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ physicalFileName := "/src/physical" + tt.virtualExtension
+ program := newContentMapperProgramWithOutputExtensions(
+ t,
+ fakeContentMapperHost{transform: func(fileName string, content string) (contentmapper.Result, error) {
+ return contentmapper.Result{Text: content, VirtualExtension: tt.virtualExtension, Mappings: spanmap.New(nil)}, nil
+ }},
+ map[string]string{
+ "/src/Component.vue": tt.text,
+ physicalFileName: tt.text,
+ "/src/dep.ts": "export type Foo = {};",
+ },
+ []string{"/src/Component.vue", physicalFileName},
+ &core.CompilerOptions{
+ SkipLibCheck: core.TSTrue,
+ Module: tt.module,
+ ModuleResolution: tt.moduleResolution,
+ ResolvePackageJsonExports: core.TSTrue,
+ VerbatimModuleSyntax: core.TSTrue,
+ },
+ map[string]string{".vue": tt.virtualExtension},
+ )
+
+ mappedFile := program.GetSourceFile("/src/Component.vue")
+ assert.Assert(t, mappedFile != nil)
+ assert.Equal(t, mappedFile.VirtualFileName(), tspath.RootedFilePathFromNormalized("/src/Component.vue"+tt.virtualExtension))
+ assert.Equal(t, program.GetImpliedNodeFormatForEmit(mappedFile), tt.expectedFormat)
+ assert.Equal(t, program.GetEmitModuleFormatOfFile(mappedFile), tt.expectedFormat)
+ assert.Equal(t, program.GetDefaultResolutionModeForFile(mappedFile), tt.expectedFormat)
+
+ imports := mappedFile.Imports()
+ assert.Equal(t, len(imports), 1)
+ assert.Equal(t, program.GetModeForUsageLocation(mappedFile, imports[0]), tt.expectedFormat)
+ assert.Equal(t, program.GetEmitSyntaxForUsageLocation(mappedFile, imports[0]), tt.expectedFormat)
+
+ mappedDiagnosticCodes := core.Map(program.GetSemanticDiagnostics(t.Context(), mappedFile), func(diagnostic *ast.Diagnostic) int32 {
+ return diagnostic.Code()
+ })
+ assert.Assert(t, !slices.Contains(mappedDiagnosticCodes, tt.expectedDiagnostic), "mapped file has the format diagnostic: %v", mappedDiagnosticCodes)
+
+ physicalFile := program.GetSourceFile(tspath.RootedFilePathFromNormalized(physicalFileName))
+ assert.Assert(t, physicalFile != nil)
+ physicalDiagnosticCodes := core.Map(program.GetSemanticDiagnostics(t.Context(), physicalFile), func(diagnostic *ast.Diagnostic) int32 {
+ return diagnostic.Code()
+ })
+ assert.Assert(t, !slices.Contains(physicalDiagnosticCodes, tt.expectedDiagnostic), "physical file has the format diagnostic: %v", physicalDiagnosticCodes)
+ })
+ }
+}
+
+func TestContentMapperDeclarationModuleFormat(t *testing.T) {
+ t.Parallel()
+ for _, test := range []struct {
+ outputExtension string
+ declarationName string
+ differentPackageScope bool
+ }{
+ {".cjs", "Component.d.cts", false},
+ {".cts", "Component.d.cts", false},
+ {".mjs", "Component.d.mts", false},
+ {".mts", "Component.d.mts", false},
+ {".custom.mjs", "Component.custom.d.mts", false},
+ {".custom.cts", "Component.custom.d.cts", false},
+ {".js", "Component.d.ts", false},
+ {"", "Component.d.vue.ts", false},
+ {".js", "Component.d.ts", true},
+ {"", "Component.d.vue.ts", true},
+ } {
+ for _, packageType := range []string{"module", "commonjs"} {
+ for _, virtualExtension := range []string{".cts", ".cjs", ".mts", ".mjs", ".ts", ".tsx", ".js", ".jsx"} {
+ name := test.outputExtension + "/" + packageType + "/" + virtualExtension
+ if test.differentPackageScope {
+ name += "/different-output-package"
+ }
+ t.Run(name, func(t *testing.T) {
+ t.Parallel()
+ outputPackageType := packageType
+ if test.differentPackageScope {
+ outputPackageType = core.IfElse(packageType == "module", "commonjs", "module")
+ }
+ outputExtensions := map[string]string{}
+ if test.outputExtension != "" {
+ outputExtensions[".vue"] = test.outputExtension
+ }
+ program := newContentMapperProgramWithOutputExtensions(t, fakeContentMapperHost{
+ transform: func(fileName string, content string) (contentmapper.Result, error) {
+ return contentmapper.Result{Text: "export const value = 1;", VirtualExtension: virtualExtension, Mappings: spanmap.New(nil)}, nil
+ },
+ }, map[string]string{
+ "/src/package.json": `{"type":"` + packageType + `"}`,
+ "/dist/package.json": `{"type":"` + outputPackageType + `"}`,
+ "/src/Component.vue": "",
+ }, []string{"/src/Component.vue"}, &core.CompilerOptions{
+ SkipLibCheck: core.TSTrue,
+ Module: core.ModuleKindNodeNext,
+ ModuleResolution: core.ModuleResolutionKindNodeNext,
+ Declaration: core.TSTrue,
+ OutDir: "/dist",
+ RewriteRelativeImportExtensions: core.TSTrue,
+ }, outputExtensions)
+ file := program.GetSourceFile("/src/Component.vue")
+ assert.Assert(t, file != nil)
+ declarationPath := tspath.RootedFilePathFromNormalized("/dist/" + test.declarationName)
+ expectedMode := ast.GetImpliedNodeFormatForFile(declarationPath, outputPackageType)
+ virtualMode := ast.GetImpliedNodeFormatForFile(tspath.RootedFilePathFromNormalized("/src/Component.vue"+virtualExtension), packageType)
+ fileDiagnostics := program.GetSyntacticDiagnostics(t.Context(), file)
+ if virtualMode != expectedMode {
+ assert.Equal(t, len(fileDiagnostics), 1)
+ assert.Equal(t, fileDiagnostics[0].Code(), diagnostics.The_content_mapper_0_returned_virtual_extension_1_whose_module_format_does_not_match_declaration_output_2.Code())
+ assert.Equal(t, file.Text(), "export const value = 1;")
+ } else {
+ assert.Equal(t, len(fileDiagnostics), 0)
+ assert.Equal(t, program.GetSourceFileMetaData(file.PathKey()).ImpliedNodeFormat, expectedMode)
+ paths := outputpaths.GetOutputPathsFor(file, program.Options(), program, outputpaths.ForceEmitPaths{Dts: true})
+ assert.Equal(t, paths.DeclarationFilePath(), declarationPath)
+ assert.Equal(t, outputpaths.GetOutputDeclarationFileNameWorker(file.FileName(), program.Options(), program), declarationPath)
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestContentMapperDeclarationModuleFormatSkipsJSON(t *testing.T) {
+ t.Parallel()
+ for _, packageType := range []string{"module", "commonjs"} {
+ t.Run(packageType, func(t *testing.T) {
+ t.Parallel()
+ program := newContentMapperProgramWithOptions(t, fakeContentMapperHost{
+ transform: func(fileName string, content string) (contentmapper.Result, error) {
+ return contentmapper.Result{Text: `{"value":1}`, VirtualExtension: ".json", Mappings: spanmap.New(nil)}, nil
+ },
+ }, map[string]string{
+ "/src/package.json": `{"type":"` + packageType + `"}`,
+ "/src/Component.vue": "",
+ }, []string{"/src/Component.vue"}, &core.CompilerOptions{
+ Module: core.ModuleKindNodeNext,
+ ModuleResolution: core.ModuleResolutionKindNodeNext,
+ ResolveJsonModule: core.TSTrue,
+ Declaration: core.TSTrue,
+ OutDir: "/dist",
+ })
+ file := program.GetSourceFile("/src/Component.vue")
+ assert.Assert(t, file != nil)
+ assert.Assert(t, ast.IsJsonSourceFile(file))
+ assert.Equal(t, len(program.GetSyntacticDiagnostics(t.Context(), file)), 0)
+ paths := outputpaths.GetOutputPathsFor(file, program.Options(), program, outputpaths.ForceEmitPaths{})
+ assert.Equal(t, paths.DeclarationFilePath(), tspath.RootedFilePath(""))
+ })
+ }
+}
+
+func TestContentMapperDeclarationModuleFormatWithoutNodeResolution(t *testing.T) {
+ t.Parallel()
+ for _, moduleResolution := range []core.ModuleResolutionKind{core.ModuleResolutionKindBundler, core.ModuleResolutionKindNode10} {
+ for _, virtualExtension := range []string{".ts", ".mts", ".cts"} {
+ t.Run(moduleResolution.String()+"/"+virtualExtension, func(t *testing.T) {
+ t.Parallel()
+ program := newContentMapperProgramWithOptions(t, fakeContentMapperHost{
+ transform: func(fileName string, content string) (contentmapper.Result, error) {
+ return contentmapper.Result{Text: "export const value = 1;", VirtualExtension: virtualExtension, Mappings: spanmap.New(nil)}, nil
+ },
+ }, map[string]string{
+ "/src/package.json": `{"type":"module"}`,
+ "/dist/package.json": `{"type":"module"}`,
+ "/src/Component.vue": "",
+ }, []string{"/src/Component.vue"}, &core.CompilerOptions{
+ Module: core.ModuleKindESNext,
+ ModuleResolution: moduleResolution,
+ OutDir: "/dist",
+ })
+ file := program.GetSourceFile("/src/Component.vue")
+ assert.Assert(t, file != nil)
+ fileDiagnostics := program.GetSyntacticDiagnostics(t.Context(), file)
+ if virtualExtension == ".cts" {
+ assert.Equal(t, len(fileDiagnostics), 1)
+ assert.Equal(t, fileDiagnostics[0].Code(), diagnostics.The_content_mapper_0_returned_virtual_extension_1_whose_module_format_does_not_match_declaration_output_2.Code())
+ } else {
+ assert.Equal(t, len(fileDiagnostics), 0)
+ assert.Equal(t, file.Text(), "export const value = 1;")
+ }
+ })
+ }
+ }
+}
+
+type missingContentMappedCompilerHost struct {
+ compiler.CompilerHost
+}
+
+func (missingContentMappedCompilerHost) GetContentMappedSourceFiles(ast.SourceFileParseOptions, *contentmapper.Mapper) (contentmapper.SourceFiles, error) {
+ return contentmapper.SourceFiles{}, nil
+}
+
+func TestContentMapperMissingSourceFile(t *testing.T) {
+ t.Parallel()
+ fs := vfstest.FromMap(map[string]any{"/src/Component.vue": "export {};"}, tspath.CaseSensitive)
+ config := tsoptions.NewParsedCommandLine(&core.CompilerOptions{NoLib: core.TSTrue}, testFileNames("/src/Component.vue"), nil, "/", fs.CaseSensitivity())
+ config.ParsedConfig.ContentMappers = []*contentmapper.Mapper{{Package: "vue", Extensions: []string{".vue"}, Name: "vue-mapper", Version: "1.0.0"}}
+ program := compiler.NewProgram(compiler.ProgramOptions{
+ Config: config,
+ Host: missingContentMappedCompilerHost{CompilerHost: compiler.NewCompilerHost(fs, "/", nil, nil, nil)},
+ })
+ assert.Assert(t, program.GetSourceFile("/src/Component.vue") == nil)
+}
+
+func TestContentMapperDeclarationModuleFormatUsesEmitRoot(t *testing.T) {
+ t.Parallel()
+ for _, virtualExtension := range []string{".ts", ".mts"} {
+ for _, outputPackageType := range []string{"module", "commonjs"} {
+ t.Run(virtualExtension+"/"+outputPackageType, func(t *testing.T) {
+ t.Parallel()
+ program := newContentMapperProgramWithOptions(t, fakeContentMapperHost{
+ transform: func(fileName string, content string) (contentmapper.Result, error) {
+ return contentmapper.Result{Text: "export const value = 1;", VirtualExtension: virtualExtension, Mappings: spanmap.New(nil)}, nil
+ },
+ }, map[string]string{
+ "/src/main.ts": `import "../shared/Component.vue";`,
+ "/shared/Component.vue": "",
+ "/shared/package.json": `{"type":"commonjs"}`,
+ "/dist/shared/package.json": `{"type":"` + outputPackageType + `"}`,
+ }, []string{"/src/main.ts"}, &core.CompilerOptions{
+ SkipLibCheck: core.TSTrue,
+ Module: core.ModuleKindNodeNext,
+ ModuleResolution: core.ModuleResolutionKindNodeNext,
+ Declaration: core.TSTrue,
+ OutDir: "/dist",
+ })
+ file := program.GetSourceFile("/shared/Component.vue")
+ assert.Assert(t, file != nil)
+ paths := outputpaths.GetOutputPathsFor(file, program.Options(), program, outputpaths.ForceEmitPaths{Dts: true})
+ assert.Equal(t, paths.DeclarationFilePath(), tspath.RootedFilePath("/dist/shared/Component.d.vue.ts"))
+ fileDiagnostics := program.GetSyntacticDiagnostics(t.Context(), file)
+ expectMismatch := (virtualExtension == ".mts") != (outputPackageType == "module")
+ assert.Equal(t, len(fileDiagnostics), core.IfElse(expectMismatch, 1, 0))
+ if expectMismatch {
+ assert.Equal(t, fileDiagnostics[0].Code(), diagnostics.The_content_mapper_0_returned_virtual_extension_1_whose_module_format_does_not_match_declaration_output_2.Code())
+ }
+ })
+ }
+ }
+}
+
func TestContentMapperDirectivesPreserveIncrementalGlobals(t *testing.T) {
t.Parallel()
for _, policy := range []ast.MappedDiagnosticDirectivePolicy{
diff --git a/tsc/internal/compiler/fileloader.go b/tsc/internal/compiler/fileloader.go
index e1a623e2f7746..6e430b63e4988 100644
--- a/tsc/internal/compiler/fileloader.go
+++ b/tsc/internal/compiler/fileloader.go
@@ -870,7 +870,7 @@ func (p *fileLoader) resolveImportsAndModuleAugmentations(t *parseTask) {
continue
}
- mode := getModeForUsageLocation(file.FileName(), meta, entry, optionsForFile)
+ mode := getModeForUsageLocation(getModuleFormatFileName(file), meta, entry, optionsForFile)
// We know moduleName resolves to an ambient module provided that moduleName:
// - is in the list of ambient modules locally declared in the current source file.
if slices.Contains(file.AmbientModuleNames, moduleName) {
@@ -1029,10 +1029,19 @@ func getModeForTypeReferenceDirectiveInFile(ref *ast.FileReference, file *ast.So
if ref.ResolutionMode != core.ResolutionModeNone {
return ref.ResolutionMode
} else {
- return getDefaultResolutionModeForFile(file.FileName(), meta, options)
+ return getDefaultResolutionModeForFile(getModuleFormatFileName(file), meta, options)
}
}
+func getModuleFormatFileName(file ast.HasFileName) tspath.RootedFilePath {
+ if sourceFile, ok := file.(*ast.SourceFile); ok {
+ if virtualFileName := sourceFile.VirtualFileName(); virtualFileName != "" {
+ return virtualFileName
+ }
+ }
+ return file.FileName()
+}
+
func getDefaultResolutionModeForFile(fileName tspath.RootedFilePath, meta ast.SourceFileMetaData, options *core.CompilerOptions) core.ResolutionMode {
if importSyntaxAffectsModuleResolution(options) {
return ast.GetImpliedNodeFormatForEmitWorker(fileName, options.GetEmitModuleKind(), meta)
diff --git a/tsc/internal/compiler/program.go b/tsc/internal/compiler/program.go
index 62b9de7ce981c..4c0bda12dbc7b 100644
--- a/tsc/internal/compiler/program.go
+++ b/tsc/internal/compiler/program.go
@@ -811,6 +811,9 @@ func (p *Program) collectCheckerDiagnosticsFromFiles(ctx context.Context, source
func (p *Program) GetSyntacticDiagnostics(ctx context.Context, sourceFile *ast.SourceFile) []*ast.Diagnostic {
return p.collectDiagnostics(ctx, sourceFile, false /*concurrent*/, func(_ context.Context, file *ast.SourceFile) []*ast.Diagnostic {
diags := core.Concatenate(file.Diagnostics(), file.JSDiagnostics())
+ if diagnostic := p.getContentMapperModuleFormatDiagnostic(file); diagnostic != nil {
+ diags = append(diags, diagnostic)
+ }
// For JS files that won't be checked by the checker (no checkJs/ts-check), we need
// program-level syntactic checks that require compiler options. This mirrors Strada's
// getJSSyntacticDiagnosticsForFile in program.ts.
@@ -821,6 +824,42 @@ func (p *Program) GetSyntacticDiagnostics(ctx context.Context, sourceFile *ast.S
})
}
+func (p *Program) getContentMapperModuleFormatDiagnostic(file *ast.SourceFile) *ast.Diagnostic {
+ if file.IsContentMapperFailureStub() || file.IsContentMapperSupplemental() || ast.IsJsonSourceFile(file) {
+ return nil
+ }
+ mapper := p.GetContentMapper(file)
+ if mapper == nil {
+ return nil
+ }
+ options := p.Options()
+ var host outputpaths.OutputPathsHost = p
+ if config := p.GetRedirectForResolution(file); config != nil {
+ options = config.CompilerOptions()
+ host = config
+ }
+ // Declaration paths depend on the complete source graph, so validate here rather than during loading.
+ declarationPath := outputpaths.GetOutputDeclarationFileNameWorker(file.FileName(), options, host)
+ virtualFileName := file.VirtualFileName()
+ if p.getContentMappedFileModuleFormat(virtualFileName) == p.getContentMappedFileModuleFormat(declarationPath) {
+ return nil
+ }
+ return ast.NewDiagnostic(file, core.NewTextRange(0, 0),
+ diagnostics.The_content_mapper_0_returned_virtual_extension_1_whose_module_format_does_not_match_declaration_output_2,
+ mapper.DiagnosticName(), virtualFileName.Extension(), declarationPath.BaseName())
+}
+
+func (p *Program) getContentMappedFileModuleFormat(fileName tspath.RootedFilePath) core.ModuleKind {
+ var packageJsonType string
+ if !p.opts.SkipModuleResolution {
+ scope := p.newResolver().GetPackageScopeForPath(fileName.Directory())
+ if scope.Exists() {
+ packageJsonType, _ = scope.Contents.Type.GetValue()
+ }
+ }
+ return ast.GetImpliedNodeFormatForFile(fileName, packageJsonType)
+}
+
// getAdditionalJSSyntacticDiagnostics produces option-dependent syntactic diagnostics for JS files
// that aren't covered by the parser or the checker. In Strada, the equivalent logic lives in
// getJSSyntacticDiagnosticsForFile in program.ts. In Corsa, most of that function's checks were
@@ -1838,19 +1877,19 @@ func (p *Program) GetSourceFileMetaData(path tspath.PathKey) ast.SourceFileMetaD
}
func (p *Program) GetEmitModuleFormatOfFile(sourceFile ast.HasFileName) core.ModuleKind {
- return ast.GetEmitModuleFormatOfFileWorker(sourceFile.FileName(), p.projectReferenceFileMapper.getCompilerOptionsForFile(sourceFile), p.GetSourceFileMetaData(sourceFile.PathKey()))
+ return ast.GetEmitModuleFormatOfFileWorker(getModuleFormatFileName(sourceFile), p.projectReferenceFileMapper.getCompilerOptionsForFile(sourceFile), p.GetSourceFileMetaData(sourceFile.PathKey()))
}
func (p *Program) GetEmitSyntaxForUsageLocation(sourceFile ast.HasFileName, location *ast.StringLiteralLike) core.ResolutionMode {
- return getEmitSyntaxForUsageLocationWorker(sourceFile.FileName(), p.sourceFileMetaDatas[sourceFile.PathKey()], location, p.projectReferenceFileMapper.getCompilerOptionsForFile(sourceFile))
+ return getEmitSyntaxForUsageLocationWorker(getModuleFormatFileName(sourceFile), p.sourceFileMetaDatas[sourceFile.PathKey()], location, p.projectReferenceFileMapper.getCompilerOptionsForFile(sourceFile))
}
func (p *Program) GetImpliedNodeFormatForEmit(sourceFile ast.HasFileName) core.ResolutionMode {
- return ast.GetImpliedNodeFormatForEmitWorker(sourceFile.FileName(), p.projectReferenceFileMapper.getCompilerOptionsForFile(sourceFile).GetEmitModuleKind(), p.GetSourceFileMetaData(sourceFile.PathKey()))
+ return ast.GetImpliedNodeFormatForEmitWorker(getModuleFormatFileName(sourceFile), p.projectReferenceFileMapper.getCompilerOptionsForFile(sourceFile).GetEmitModuleKind(), p.GetSourceFileMetaData(sourceFile.PathKey()))
}
func (p *Program) GetModeForUsageLocation(sourceFile ast.HasFileName, location *ast.StringLiteralLike) core.ResolutionMode {
- return getModeForUsageLocation(sourceFile.FileName(), p.sourceFileMetaDatas[sourceFile.PathKey()], location, p.projectReferenceFileMapper.getCompilerOptionsForFile(sourceFile))
+ return getModeForUsageLocation(getModuleFormatFileName(sourceFile), p.sourceFileMetaDatas[sourceFile.PathKey()], location, p.projectReferenceFileMapper.getCompilerOptionsForFile(sourceFile))
}
func (p *Program) GetModeForResolutionAtIndex(sourceFile *ast.SourceFile, index int) core.ResolutionMode {
@@ -1871,7 +1910,7 @@ func (p *Program) GetModeForResolutionAtIndex(sourceFile *ast.SourceFile, index
}
func (p *Program) GetDefaultResolutionModeForFile(sourceFile ast.HasFileName) core.ResolutionMode {
- return getDefaultResolutionModeForFile(sourceFile.FileName(), p.sourceFileMetaDatas[sourceFile.PathKey()], p.projectReferenceFileMapper.getCompilerOptionsForFile(sourceFile))
+ return getDefaultResolutionModeForFile(getModuleFormatFileName(sourceFile), p.sourceFileMetaDatas[sourceFile.PathKey()], p.projectReferenceFileMapper.getCompilerOptionsForFile(sourceFile))
}
func (p *Program) IsSourceFileDefaultLibrary(path tspath.PathKey) bool {
diff --git a/tsc/internal/contentmapper/contentmapper.go b/tsc/internal/contentmapper/contentmapper.go
index 158e6ee4be1b5..440057237c3f9 100644
--- a/tsc/internal/contentmapper/contentmapper.go
+++ b/tsc/internal/contentmapper/contentmapper.go
@@ -34,6 +34,7 @@ type Definition struct {
Package string `json:"package"`
Extensions []string `json:"extensions"`
// OutputExtensions contains the resolved mapping after applying manifest defaults and project overrides.
+ // It determines declaration filenames and their module format; canonical virtual outputs must agree.
OutputExtensions map[string]string `json:"outputExtensions,omitzero"`
Options json.Value `json:"options,omitempty"`
}
diff --git a/tsc/internal/contentmapper/host.go b/tsc/internal/contentmapper/host.go
index beef743f74423..36875da96e65b 100644
--- a/tsc/internal/contentmapper/host.go
+++ b/tsc/internal/contentmapper/host.go
@@ -167,7 +167,8 @@ func (e *InitializeError) Error() string {
type Result struct {
// Text is the virtual TypeScript source text that is parsed into the program.
Text string
- // VirtualExtension determines how Text is parsed.
+ // VirtualExtension determines how Text is parsed. Its module format must match the declaration
+ // output determined by OutputExtensions and the declaration's package.json scope.
VirtualExtension string
// Diagnostics are syntax errors in the original content.
Diagnostics []*ast.Diagnostic
diff --git a/tsc/internal/diagnostics/diagnosticMessages.generated.json b/tsc/internal/diagnostics/diagnosticMessages.generated.json
index 13e7ffe90d846..3e18f84def836 100644
--- a/tsc/internal/diagnostics/diagnosticMessages.generated.json
+++ b/tsc/internal/diagnostics/diagnosticMessages.generated.json
@@ -1960,6 +1960,7 @@
"The_typescript_contentMapper_outputExtensions_of_the_content_mapper_package_0_must_be_an_object_with_18122": "The 'typescript.contentMapper.outputExtensions' of the content mapper package '{0}' must be an object with string values.",
"Content_mapper_extension_0_must_not_contain_path_separators_18123": "Content mapper extension '{0}' must not contain path separators.",
"The_content_mapper_package_0_is_outside_the_open_workspace_and_will_not_be_loaded_18124": "The content mapper package '{0}' is outside the open workspace and will not be loaded.",
+ "The_content_mapper_0_returned_virtual_extension_1_whose_module_format_does_not_match_declaration_out_18125": "The content mapper '{0}' returned virtual extension '{1}', whose module format does not match declaration output '{2}'.",
"nodenext_if_module_is_nodenext_node16_if_module_is_node16_or_node18_otherwise_bundler_69010": "`nodenext` if `module` is `nodenext`; `node16` if `module` is `node16` or `node18`; otherwise, `bundler`.",
"File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "File is a CommonJS module; it may be converted to an ES module.",
"This_constructor_function_may_be_converted_to_a_class_declaration_80002": "This constructor function may be converted to a class declaration.",
diff --git a/tsc/internal/diagnostics/diagnosticMessages.json b/tsc/internal/diagnostics/diagnosticMessages.json
index 3cb32a21c7bc0..c3e7e8db845d6 100644
--- a/tsc/internal/diagnostics/diagnosticMessages.json
+++ b/tsc/internal/diagnostics/diagnosticMessages.json
@@ -8959,5 +8959,9 @@
"Content mapper extension '{0}' must not contain path separators.": {
"category": "Error",
"code": 18123
+ },
+ "The content mapper '{0}' returned virtual extension '{1}', whose module format does not match declaration output '{2}'.": {
+ "category": "Error",
+ "code": 18125
}
}
diff --git a/tsc/internal/diagnostics/diagnostics_generated.go b/tsc/internal/diagnostics/diagnostics_generated.go
index fe6657442d1e4..d6c677f5ed513 100644
--- a/tsc/internal/diagnostics/diagnostics_generated.go
+++ b/tsc/internal/diagnostics/diagnostics_generated.go
@@ -3924,6 +3924,8 @@ var Content_mapper_extension_0_must_not_contain_path_separators = &Message{code:
var The_content_mapper_package_0_is_outside_the_open_workspace_and_will_not_be_loaded = &Message{code: 18124, category: CategoryError, key: "The_content_mapper_package_0_is_outside_the_open_workspace_and_will_not_be_loaded_18124", text: "The content mapper package '{0}' is outside the open workspace and will not be loaded."}
+var The_content_mapper_0_returned_virtual_extension_1_whose_module_format_does_not_match_declaration_output_2 = &Message{code: 18125, category: CategoryError, key: "The_content_mapper_0_returned_virtual_extension_1_whose_module_format_does_not_match_declaration_out_18125", text: "The content mapper '{0}' returned virtual extension '{1}', whose module format does not match declaration output '{2}'."}
+
var X_nodenext_if_module_is_nodenext_node16_if_module_is_node16_or_node18_otherwise_bundler = &Message{code: 69010, category: CategoryMessage, key: "nodenext_if_module_is_nodenext_node16_if_module_is_node16_or_node18_otherwise_bundler_69010", text: "`nodenext` if `module` is `nodenext`; `node16` if `module` is `node16` or `node18`; otherwise, `bundler`."}
var File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module = &Message{code: 80001, category: CategorySuggestion, key: "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001", text: "File is a CommonJS module; it may be converted to an ES module."}
@@ -6426,6 +6428,7 @@ var allMessages = [...]**Message{
&The_typescript_contentMapper_outputExtensions_of_the_content_mapper_package_0_must_be_an_object_with_string_values,
&Content_mapper_extension_0_must_not_contain_path_separators,
&The_content_mapper_package_0_is_outside_the_open_workspace_and_will_not_be_loaded,
+ &The_content_mapper_0_returned_virtual_extension_1_whose_module_format_does_not_match_declaration_output_2,
&X_nodenext_if_module_is_nodenext_node16_if_module_is_node16_or_node18_otherwise_bundler,
&File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module,
&This_constructor_function_may_be_converted_to_a_class_declaration,
diff --git a/tsc/internal/fourslash/tests/contentMapperOutputExtensions_test.go b/tsc/internal/fourslash/tests/contentMapperOutputExtensions_test.go
index bc17e33790007..c01aa2de4780a 100644
--- a/tsc/internal/fourslash/tests/contentMapperOutputExtensions_test.go
+++ b/tsc/internal/fourslash/tests/contentMapperOutputExtensions_test.go
@@ -108,3 +108,67 @@ export const value = component;
})
}
}
+
+func TestContentMapperOutputExtensionsModuleFormatRedirects(t *testing.T) {
+ t.Parallel()
+ for _, mode := range []string{"cjs", "esm"} {
+ for _, disableRedirect := range []bool{false, true} {
+ name := mode + core.IfElse(disableRedirect, "/declaration", "/source")
+ t.Run(name, func(t *testing.T) {
+ t.Parallel()
+ defer testutil.RecoverAndFail(t, "Panic on fourslash test")
+ // The format mapper returns the source unchanged with identity mappings,
+ // using .cts for "cjs" and .mts otherwise. The differing literal types
+ // distinguish source redirects from loading the built declaration.
+ content := `// @Filename: /node_modules/mapper/package.json
+` + contentmappertest.PackageJSON(contentmappertest.FormatVerbatimMapper) + `
+// @Filename: /lib/package.json
+{"type": "$packageType"}
+// @Filename: /lib/tsconfig.json
+{
+ "compilerOptions": {
+ "composite": true, "module": "nodenext", "rootDir": ".", "outDir": "/dist/lib",
+ "rewriteRelativeImportExtensions": true
+ },
+ "contentMappers": [{
+ "package": "mapper", "extensions": [".vue"], "outputExtensions": {".vue": ".$output"}
+ }]
+}
+// @Filename: /lib/Component.vue
+// $mode
+export const component = "source";
+$declarationFile
+// @Filename: /app/tsconfig.json
+{
+ "compilerOptions": {
+ "module": "nodenext", "disableSourceOfProjectReferenceRedirect": $disableRedirect,
+ "rootDir": ".", "outDir": "/dist/app",
+ "rewriteRelativeImportExtensions": true
+ },
+ "references": [{"path": "../lib"}],
+ "contentMappers": [{
+ "package": "mapper", "extensions": [".vue"], "outputExtensions": {".vue": ".$output"}
+ }]
+}
+// @Filename: /app/main.ts
+import { component } from "../dist/lib/Component.$output";
+const expected: "$expected" = component;
+`
+ content = strings.NewReplacer(
+ "$declarationFile", core.IfElse(disableRedirect,
+ "// @Filename: /dist/lib/Component.d."+core.IfElse(mode == "cjs", "cts", "mts")+"\nexport declare const component: \"declaration\";", ""),
+ "$packageType", core.IfElse(mode == "cjs", "module", "commonjs"),
+ "$mode", mode,
+ "$output", core.IfElse(mode == "cjs", "cjs", "mjs"),
+ "$disableRedirect", core.IfElse(disableRedirect, "true", "false"),
+ "$expected", core.IfElse(disableRedirect, "declaration", "source"),
+ ).Replace(content)
+ f, done := fourslash.NewFourslashWithOptions(t, content, &fourslash.FourslashOptions{
+ ContentMapperSpawner: contentmappertest.NewSpawner(), RunExternalCode: true,
+ })
+ defer done()
+ f.VerifyNoErrors(t)
+ })
+ }
+ }
+}
diff --git a/tsc/internal/project/contentmapper_test.go b/tsc/internal/project/contentmapper_test.go
index 3386573079048..a524edfe723f9 100644
--- a/tsc/internal/project/contentmapper_test.go
+++ b/tsc/internal/project/contentmapper_test.go
@@ -655,7 +655,7 @@ func TestContentMapperSupplementalFileClonedOnEdit(t *testing.T) {
func TestContentMapperModuleExtensionClonedOnUnrelatedEdit(t *testing.T) {
t.Parallel()
files := map[string]any{
- "/home/project/tsconfig.json": `{ "contentMappers": [{ "package": "mapper", "extensions": [".box"] }] }`,
+ "/home/project/tsconfig.json": `{ "compilerOptions": { "rewriteRelativeImportExtensions": true }, "contentMappers": [{ "package": "mapper", "extensions": [".box"], "outputExtensions": { ".box": ".mjs" } }] }`,
"/home/project/node_modules/mapper/package.json": contentmappertest.PackageJSON(contentmappertest.ModuleVerbatimMapper),
"/home/project/app.box": "export const value = 1;\n",
"/home/project/main.ts": `import { value } from "./app.box"; value;`,
@@ -694,7 +694,7 @@ func TestContentMapperModuleExtensionClonedOnUnrelatedEdit(t *testing.T) {
func TestContentMapperModuleFormatChangeRebuilds(t *testing.T) {
t.Parallel()
files := map[string]any{
- "/home/project/tsconfig.json": `{ "compilerOptions": { "module": "nodenext", "importHelpers": true, "noEmit": true }, "contentMappers": [{ "package": "mapper", "extensions": [".box"] }] }`,
+ "/home/project/tsconfig.json": `{ "compilerOptions": { "module": "nodenext", "importHelpers": true, "noEmit": true, "rewriteRelativeImportExtensions": true }, "contentMappers": [{ "package": "mapper", "extensions": [".box"], "outputExtensions": { ".box": ".cjs" } }] }`,
"/home/project/package.json": `{ "name": "project" }`,
"/home/project/node_modules/mapper/package.json": contentmappertest.PackageJSON(contentmappertest.FormatVerbatimMapper),
"/home/project/node_modules/tslib/package.json": `{ "name": "tslib", "version": "1.0.0", "exports": { ".": { "import": "./tslib.d.mts", "require": "./tslib.d.ts" } } }`,
@@ -730,12 +730,90 @@ func TestContentMapperModuleFormatChangeRebuilds(t *testing.T) {
assert.Assert(t, session.Snapshot().GetDefaultProject(mainURI).ProgramUpdateKind != project.ProgramUpdateKindCloned)
program := languageService.GetProgram()
mappedFile := program.GetSourceFile("/home/project/app.box")
+ assert.Equal(t, mappedFile.Text(), "// esm\nexport const value = 1;\n")
+ fileDiagnostics := program.GetSyntacticDiagnostics(ctx, mappedFile)
+ assert.Equal(t, len(fileDiagnostics), 1)
+ assert.Equal(t, fileDiagnostics[0].Code(), diagnostics.The_content_mapper_0_returned_virtual_extension_1_whose_module_format_does_not_match_declaration_output_2.Code())
+
+ assert.NilError(t, utils.FS().WriteFile("/home/project/tsconfig.json", strings.ReplaceAll(files["/home/project/tsconfig.json"].(string), ".cjs", ".mjs")))
+ session.DidChangeWatchedFiles(ctx, []*lsproto.FileEvent{{
+ Uri: "file:///home/project/tsconfig.json",
+ Type: lsproto.FileChangeTypeChanged,
+ }})
+ languageService, err = session.GetLanguageService(ctx, mainURI)
+ assert.NilError(t, err)
+ program = languageService.GetProgram()
+ mappedFile = program.GetSourceFile("/home/project/app.box")
assert.Equal(t, mappedFile.VirtualFileName().AsString(), "/home/project/app.box.mts")
assert.Equal(t, program.GetSourceFileMetaData(mappedFile.PathKey()).ImpliedNodeFormat, core.ModuleKindESNext)
tslib := program.GetResolvedModuleFromModuleSpecifier(mappedFile, program.GetImportHelpersImportSpecifier(mappedFile.PathKey()))
assert.Equal(t, tslib.ResolvedFileName.AsString(), "/home/project/node_modules/tslib/tslib.d.mts")
}
+func TestContentMapperModuleFormatDiagnosticsSurviveEdits(t *testing.T) {
+ t.Parallel()
+ for _, mapper := range []string{contentmappertest.VerbatimMapper, contentmappertest.SupplementalMapper} {
+ t.Run(mapper, func(t *testing.T) {
+ t.Parallel()
+ files := map[string]any{
+ "/home/project/tsconfig.json": `{ "compilerOptions": { "module": "nodenext", "moduleDetection": "force", "rewriteRelativeImportExtensions": true }, "contentMappers": [{ "package": "mapper", "extensions": [".box"], "outputExtensions": { ".box": ".mjs" } }] }`,
+ "/home/project/package.json": `{"type":"commonjs"}`,
+ "/home/project/node_modules/mapper/package.json": contentmappertest.PackageJSON(mapper),
+ "/home/project/app.box": "export const value = 1;",
+ "/home/project/main.ts": "export {};",
+ }
+ init, utils := projecttestutil.GetSessionInitOptions(files, &project.SessionOptions{
+ CurrentDirectory: "/home/project",
+ DefaultLibraryPath: bundled.LibPath(),
+ PositionEncoding: lsproto.PositionEncodingKindUTF8,
+ RunExternalCode: true,
+ }, nil)
+ init.Spawner = contentmappertest.NewSpawner()
+ cache := project.NewContentMappedParseCache(project.RefCountCacheOptions{})
+ init.ContentMappedParseCache = cache
+ session := project.NewSession(init)
+ var keys []project.ContentMappedParseCacheKey
+ defer func() {
+ session.Close()
+ for _, key := range keys {
+ assert.Assert(t, !cache.Has(key), "transform bundle remains cached after session disposal")
+ }
+ }()
+
+ ctx := t.Context()
+ mainURI := lsproto.DocumentUri("file:///home/project/main.ts")
+ session.DidOpenFile(ctx, mainURI, 1, files["/home/project/main.ts"].(string), lsproto.LanguageKindTypeScript)
+ for i := range 3 {
+ if i != 0 {
+ assert.NilError(t, utils.FS().WriteFile("/home/project/app.box", fmt.Sprintf("export const value = %d;", i+1)))
+ session.DidChangeWatchedFiles(ctx, []*lsproto.FileEvent{{
+ Uri: "file:///home/project/app.box",
+ Type: lsproto.FileChangeTypeChanged,
+ }})
+ }
+ languageService, err := session.GetLanguageService(ctx, mainURI)
+ assert.NilError(t, err)
+ program := languageService.GetProgram()
+ file := program.GetSourceFile("/home/project/app.box")
+ assert.Assert(t, file != nil)
+ fileDiagnostics := program.GetSyntacticDiagnostics(ctx, file)
+ assert.Equal(t, len(fileDiagnostics), 1)
+ assert.Equal(t, fileDiagnostics[0].Code(), diagnostics.The_content_mapper_0_returned_virtual_extension_1_whose_module_format_does_not_match_declaration_output_2.Code())
+ if i != 0 {
+ assert.Equal(t, session.Snapshot().GetDefaultProject(mainURI).ProgramUpdateKind, project.ProgramUpdateKindCloned)
+ }
+ keys = append(keys, project.ContentMappedParseCacheKey{SourceFileParseOptions: file.ContentMapperParseOptions(), Hash: file.Hash})
+ }
+ assert.Assert(t, cache.Has(keys[len(keys)-1]), "the program must retain its acquired transform bundle")
+ if mapper == contentmappertest.SupplementalMapper {
+ languageService, err := session.GetLanguageService(ctx, mainURI)
+ assert.NilError(t, err)
+ assert.Equal(t, len(languageService.GetProgram().GetSourceFile("/home/project/app.box").SupplementalSourceFiles()), 1)
+ }
+ })
+ }
+}
+
func TestContentMapperLocaleChange(t *testing.T) {
t.Parallel()
files := map[string]any{
diff --git a/tsc/internal/testrunner/compiler_runner.go b/tsc/internal/testrunner/compiler_runner.go
index 6f2712632b5b8..75c8329bafba8 100644
--- a/tsc/internal/testrunner/compiler_runner.go
+++ b/tsc/internal/testrunner/compiler_runner.go
@@ -316,11 +316,16 @@ func newCompilerTest(
// Content-mapped files are transformed during program construction; the transformed text is what the
// compiler actually parses and reports positions against. Baseline that text (rather than the original
// foreign source) so the type, symbol, and error baselines line up with the compiler's positions.
- for _, file := range core.Concatenate(toBeCompiled, otherFiles) {
+ withContentMappedText := func(file *harnessutil.TestFile) *harnessutil.TestFile {
if sf := result.Program.GetSourceFile(tspath.ToRootedFilePath(file.UnitName, currentDirectory)); sf != nil && sf.ContentMapper() != "" {
- file.Content = sf.Text()
+ baselineFile := *file
+ baselineFile.Content = sf.Text()
+ return &baselineFile
}
+ return file
}
+ toBeCompiled = core.Map(toBeCompiled, withContentMappedText)
+ otherFiles = core.Map(otherFiles, withContentMappedText)
return &compilerTest{
testName: testName,
diff --git a/tsc/testdata/baselines/reference/compiler/contentMapperModuleFormat.contentmapper b/tsc/testdata/baselines/reference/compiler/contentMapperModuleFormat.contentmapper
new file mode 100644
index 0000000000000..03f5512ed0bfb
--- /dev/null
+++ b/tsc/testdata/baselines/reference/compiler/contentMapperModuleFormat.contentmapper
@@ -0,0 +1,46 @@
+//// [/src/expected-esm.esm] (ScriptKind: ScriptKindTS, ContentMapper: [.esm .cbox .box])
+--- Original ---
+// @box-extension: .cts
+export const value = 1;
+--- Transformed ---
+const __VERSION = "1.0.0";
+// @box-extension: .cts
+export const value = 1;
+
+//// [/src/expected-cjs.cbox] (ScriptKind: ScriptKindTS, ContentMapper: [.esm .cbox .box])
+--- Original ---
+// @box-extension: .mts
+export const value = 1;
+--- Transformed ---
+const __VERSION = "1.0.0";
+// @box-extension: .mts
+export const value = 1;
+
+//// [/src/package-inferred.box] (ScriptKind: ScriptKindTS, ContentMapper: [.esm .cbox .box])
+--- Original ---
+// @box-extension: .cts
+export const value = 1;
+--- Transformed ---
+const __VERSION = "1.0.0";
+// @box-extension: .cts
+export const value = 1;
+
+=== Diagnostics ===
+
+/src/expected-cjs.cbox:1:1 - error TS18125: The content mapper 'mapper' returned virtual extension '.mts', whose module format does not match declaration output 'expected-cjs.d.cts'.
+ This location is in virtual code produced by the content mapper 'mapper@1.0.0' and has no corresponding location in the original file.
+
+1 const __VERSION = "1.0.0";
+ ~
+
+/src/expected-esm.esm:1:1 - error TS18125: The content mapper 'mapper' returned virtual extension '.cts', whose module format does not match declaration output 'expected-esm.d.mts'.
+ This location is in virtual code produced by the content mapper 'mapper@1.0.0' and has no corresponding location in the original file.
+
+1 const __VERSION = "1.0.0";
+ ~
+
+/src/package-inferred.box:1:1 - error TS18125: The content mapper 'mapper' returned virtual extension '.cts', whose module format does not match declaration output 'package-inferred.d.box.ts'.
+ This location is in virtual code produced by the content mapper 'mapper@1.0.0' and has no corresponding location in the original file.
+
+1 const __VERSION = "1.0.0";
+ ~
diff --git a/tsc/testdata/baselines/reference/compiler/contentMapperModuleFormat.js b/tsc/testdata/baselines/reference/compiler/contentMapperModuleFormat.js
new file mode 100644
index 0000000000000..284cdc39d6173
--- /dev/null
+++ b/tsc/testdata/baselines/reference/compiler/contentMapperModuleFormat.js
@@ -0,0 +1,36 @@
+//// [tests/cases/compiler/contentMapperModuleFormat.ts] ////
+
+//// [package.json]
+{ "type": "module" }
+
+//// [package.json]
+{
+ "name": "mapper",
+ "version": "1.0.0",
+ "typescript": { "contentMapper": { "exec": ["compiler-test-mapper"] } }
+}
+
+//// [expected-esm.esm]
+const __VERSION = "1.0.0";
+// @box-extension: .cts
+export const value = 1;
+
+//// [expected-cjs.cbox]
+const __VERSION = "1.0.0";
+// @box-extension: .mts
+export const value = 1;
+
+//// [package-inferred.box]
+const __VERSION = "1.0.0";
+// @box-extension: .cts
+export const value = 1;
+
+
+
+
+//// [expected-esm.d.mts]
+export declare const value = 1;
+//// [expected-cjs.d.cts]
+export declare const value = 1;
+//// [package-inferred.d.box.ts]
+export declare const value = 1;
diff --git a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.contentmapper b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.contentmapper
index 0b70a1a5b418d..413fcc9a131cf 100644
--- a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.contentmapper
+++ b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.contentmapper
@@ -9,9 +9,11 @@ export declare const Card: (props: CardProps) => string;
//// [/Widget.y.z] (ScriptKind: ScriptKindTS, ContentMapper: [.astro .y.z])
--- Original ---
+// @box-extension: .mts
export declare const Widget: () => string;
--- Transformed ---
const __VERSION = "1.0.0";
+// @box-extension: .mts
export declare const Widget: () => string;
=== Diagnostics ===
diff --git a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.js b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.js
index 081a200e3a1e1..fb6bc1b8696e1 100644
--- a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.js
+++ b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.js
@@ -19,6 +19,7 @@ export declare const Card: (props: CardProps) => string;
//// [Widget.y.z]
const __VERSION = "1.0.0";
+// @box-extension: .mts
export declare const Widget: () => string;
//// [typed.ts]
diff --git a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.js.map b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.js.map
index a53aa97c5e4db..b9b4a659c40dc 100644
--- a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.js.map
+++ b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.js.map
@@ -1,7 +1,7 @@
//// [Card.d.ts.map]
{"version":3,"file":"Card.d.ts","sources":["../Card.astro"],"names":[],"mappings":"AAAA,MAAM,WAAW,SAAS;IAAG,KAAK,EAAE,MAAM,CAAA;CAAE;AAC5C,MAAM,CAAC,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC,KAAK,EAAE,SAAS,KAAK,MAAM,CAAC"}
//// [Widget.d.mts.map]
-{"version":3,"file":"Widget.d.mts","sources":["../Widget.y.z"],"names":[],"mappings":"AAAA,MAAM,CAAC,OAAO,CAAC,MAAM,MAAM,EAAE,MAAM,MAAM,CAAC"}
+{"version":3,"file":"Widget.d.mts","sources":["../Widget.y.z"],"names":[],"mappings":"AACA,MAAM,CAAC,OAAO,CAAC,MAAM,MAAM,EAAE,MAAM,MAAM,CAAC"}
//// [main.d.ts.map]
{"version":3,"file":"main.d.ts","sources":["../main.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAc,CAAC;AACpC,YAAY,EAAE,SAAS,EAAE,MAAM,WAAc,CAAC;AAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAKtC,wBAAsB,IAAI,wCAAqC;AAC/D,eAAO,MAAM,QAAQ,wCAAyB,CAAC;AAC/C,eAAO,MAAM,MAAM;IAAK,IAAI;CAAgC,CAAC;AAC7D,eAAO,MAAM,MAAM,iCAAc,CAAC"}
//// [typed.d.ts.map]
diff --git a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.sourcemap.txt b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.sourcemap.txt
index 8872ed9edb086..bb500374a13d9 100644
--- a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.sourcemap.txt
+++ b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.sourcemap.txt
@@ -115,7 +115,8 @@ sourceFile:../Widget.y.z
9 > ^^^^^^
10> ^^^^^^
11> ^
-1 >
+1 >// @box-extension: .mts
+ >
2 >export
3 >
4 > declare
@@ -126,17 +127,17 @@ sourceFile:../Widget.y.z
9 > () =>
10> string
11> ;
-1 >Emitted(1, 1) Source(1, 1) + SourceIndex(0)
-2 >Emitted(1, 7) Source(1, 7) + SourceIndex(0)
-3 >Emitted(1, 8) Source(1, 8) + SourceIndex(0)
-4 >Emitted(1, 15) Source(1, 15) + SourceIndex(0)
-5 >Emitted(1, 16) Source(1, 16) + SourceIndex(0)
-6 >Emitted(1, 22) Source(1, 22) + SourceIndex(0)
-7 >Emitted(1, 28) Source(1, 28) + SourceIndex(0)
-8 >Emitted(1, 30) Source(1, 30) + SourceIndex(0)
-9 >Emitted(1, 36) Source(1, 36) + SourceIndex(0)
-10>Emitted(1, 42) Source(1, 42) + SourceIndex(0)
-11>Emitted(1, 43) Source(1, 43) + SourceIndex(0)
+1 >Emitted(1, 1) Source(2, 1) + SourceIndex(0)
+2 >Emitted(1, 7) Source(2, 7) + SourceIndex(0)
+3 >Emitted(1, 8) Source(2, 8) + SourceIndex(0)
+4 >Emitted(1, 15) Source(2, 15) + SourceIndex(0)
+5 >Emitted(1, 16) Source(2, 16) + SourceIndex(0)
+6 >Emitted(1, 22) Source(2, 22) + SourceIndex(0)
+7 >Emitted(1, 28) Source(2, 28) + SourceIndex(0)
+8 >Emitted(1, 30) Source(2, 30) + SourceIndex(0)
+9 >Emitted(1, 36) Source(2, 36) + SourceIndex(0)
+10>Emitted(1, 42) Source(2, 42) + SourceIndex(0)
+11>Emitted(1, 43) Source(2, 43) + SourceIndex(0)
---
>>>//# sourceMappingURL=Widget.d.mts.map===================================================================
JsFile: typed.d.ts
diff --git a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.symbols b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.symbols
index fa2590bec3d3e..d47157bbf1813 100644
--- a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.symbols
+++ b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.symbols
@@ -17,8 +17,9 @@ export declare const Card: (props: CardProps) => string;
const __VERSION = "1.0.0";
>__VERSION : Symbol(__VERSION, Decl(Widget.y.z, 0, 5))
+// @box-extension: .mts
export declare const Widget: () => string;
->Widget : Symbol(Widget, Decl(Widget.y.z, 1, 20))
+>Widget : Symbol(Widget, Decl(Widget.y.z, 2, 20))
=== /typed.ts ===
export const annotated: import("./Card.astro").CardProps = { title: "" };
diff --git a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.types b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.types
index 802cb9c2a5077..9d7eab7a70a3d 100644
--- a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.types
+++ b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensions.types
@@ -17,6 +17,7 @@ const __VERSION = "1.0.0";
>__VERSION : "1.0.0"
>"1.0.0" : "1.0.0"
+// @box-extension: .mts
export declare const Widget: () => string;
>Widget : () => string
diff --git a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensionsOverlap.contentmapper b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensionsOverlap.contentmapper
index 4bbc986eb4c37..7c9ecacd6e951 100644
--- a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensionsOverlap.contentmapper
+++ b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensionsOverlap.contentmapper
@@ -7,9 +7,11 @@ export const short = 1;
//// [/Widget.y.z] (ScriptKind: ScriptKindTS, ContentMapper: [.z .y.z .identity.y.z .unmapped.y.z])
--- Original ---
+// @box-extension: .mts
export const long = 1;
--- Transformed ---
const __VERSION = "1.0.0";
+// @box-extension: .mts
export const long = 1;
//// [/Widget.identity.y.z] (ScriptKind: ScriptKindTS, ContentMapper: [.z .y.z .identity.y.z .unmapped.y.z])
diff --git a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensionsOverlap.js b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensionsOverlap.js
index 0d24af0fb0dc3..6f765d76778d0 100644
--- a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensionsOverlap.js
+++ b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensionsOverlap.js
@@ -13,6 +13,7 @@ export const short = 1;
//// [Widget.y.z]
const __VERSION = "1.0.0";
+// @box-extension: .mts
export const long = 1;
//// [Widget.identity.y.z]
diff --git a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensionsOverlap.symbols b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensionsOverlap.symbols
index b187b5a7659e2..5e13cd8395283 100644
--- a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensionsOverlap.symbols
+++ b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensionsOverlap.symbols
@@ -11,8 +11,9 @@ export const short = 1;
const __VERSION = "1.0.0";
>__VERSION : Symbol(__VERSION, Decl(Widget.y.z, 0, 5))
+// @box-extension: .mts
export const long = 1;
->long : Symbol(long, Decl(Widget.y.z, 1, 12))
+>long : Symbol(long, Decl(Widget.y.z, 2, 12))
=== /Widget.identity.y.z ===
const __VERSION = "1.0.0";
diff --git a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensionsOverlap.types b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensionsOverlap.types
index f758afb5c4380..559c6a1c891a9 100644
--- a/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensionsOverlap.types
+++ b/tsc/testdata/baselines/reference/compiler/contentMapperOutputExtensionsOverlap.types
@@ -14,6 +14,7 @@ const __VERSION = "1.0.0";
>__VERSION : "1.0.0"
>"1.0.0" : "1.0.0"
+// @box-extension: .mts
export const long = 1;
>long : 1
>1 : 1
diff --git a/tsc/testdata/tests/cases/compiler/contentMapperModuleFormat.ts b/tsc/testdata/tests/cases/compiler/contentMapperModuleFormat.ts
new file mode 100644
index 0000000000000..50d495a8b93e3
--- /dev/null
+++ b/tsc/testdata/tests/cases/compiler/contentMapperModuleFormat.ts
@@ -0,0 +1,40 @@
+// @runExternalCode: true
+// @noTypesAndSymbols: true
+// @declaration: true
+
+// @Filename: /tsconfig.json
+{
+ "compilerOptions": {
+ "module": "nodenext",
+ "rewriteRelativeImportExtensions": true,
+ "rootDir": "/src",
+ "outDir": "/dist"
+ },
+ "contentMappers": [{
+ "package": "mapper",
+ "extensions": [".esm", ".cbox", ".box"],
+ "outputExtensions": { ".esm": ".mjs", ".cbox": ".cjs" }
+ }]
+}
+
+// @Filename: /package.json
+{ "type": "module" }
+
+// @Filename: /node_modules/mapper/package.json
+{
+ "name": "mapper",
+ "version": "1.0.0",
+ "typescript": { "contentMapper": { "exec": ["compiler-test-mapper"] } }
+}
+
+// @Filename: /src/expected-esm.esm
+// @box-extension: .cts
+export const value = 1;
+
+// @Filename: /src/expected-cjs.cbox
+// @box-extension: .mts
+export const value = 1;
+
+// @Filename: /src/package-inferred.box
+// @box-extension: .cts
+export const value = 1;
diff --git a/tsc/testdata/tests/cases/compiler/contentMapperOutputExtensions.ts b/tsc/testdata/tests/cases/compiler/contentMapperOutputExtensions.ts
index 5227946832da6..5992c53dcc5e6 100644
--- a/tsc/testdata/tests/cases/compiler/contentMapperOutputExtensions.ts
+++ b/tsc/testdata/tests/cases/compiler/contentMapperOutputExtensions.ts
@@ -34,6 +34,7 @@ export interface CardProps { title: string }
export declare const Card: (props: CardProps) => string;
// @Filename: /Widget.y.z
+// @box-extension: .mts
export declare const Widget: () => string;
// @Filename: /typed.ts
diff --git a/tsc/testdata/tests/cases/compiler/contentMapperOutputExtensionsOverlap.ts b/tsc/testdata/tests/cases/compiler/contentMapperOutputExtensionsOverlap.ts
index 8b5f08bc2c68d..11b751d3ccff5 100644
--- a/tsc/testdata/tests/cases/compiler/contentMapperOutputExtensionsOverlap.ts
+++ b/tsc/testdata/tests/cases/compiler/contentMapperOutputExtensionsOverlap.ts
@@ -32,6 +32,7 @@
export const short = 1;
// @Filename: /Widget.y.z
+// @box-extension: .mts
export const long = 1;
// @Filename: /Widget.identity.y.z