Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
287 changes: 285 additions & 2 deletions tsc/internal/compiler/contentmapper_test.go

Large diffs are not rendered by default.

13 changes: 11 additions & 2 deletions tsc/internal/compiler/fileloader.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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)
Expand Down
49 changes: 44 additions & 5 deletions tsc/internal/compiler/program.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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())
Comment thread
Copilot marked this conversation as resolved.
Resolved
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
Expand Down Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions tsc/internal/contentmapper/contentmapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}
Expand Down
3 changes: 2 additions & 1 deletion tsc/internal/contentmapper/host.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions tsc/internal/diagnostics/diagnosticMessages.generated.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
4 changes: 4 additions & 0 deletions tsc/internal/diagnostics/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
3 changes: 3 additions & 0 deletions tsc/internal/diagnostics/diagnostics_generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

64 changes: 64 additions & 0 deletions tsc/internal/fourslash/tests/contentMapperOutputExtensions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
}
}
}
Loading
Loading