diff --git a/packages/typescript/schemas/jsconfig.schema.json b/packages/typescript/schemas/jsconfig.schema.json index cbbdba3ef0a21..4e4909419d58a 100644 --- a/packages/typescript/schemas/jsconfig.schema.json +++ b/packages/typescript/schemas/jsconfig.schema.json @@ -85,15 +85,36 @@ "type": "array", "items": { "type": "string" - } + }, + "description": "File extensions handled by this mapper. Defaults to the value of 'typescript.contentMapper.extensions' in the package manifest." + }, + "include": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Patterns relative to this config file that narrow which files the mapper handles." + }, + "outputExtensions": { + "anyOf": [ + { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + { + "type": "null" + } + ], + "description": "Maps source file extensions to output extensions for declaration filenames and rewritten imports." }, "options": { "type": "object" } }, "required": [ - "package", - "extensions" + "package" ], "additionalProperties": false } diff --git a/packages/typescript/schemas/tsconfig.schema.json b/packages/typescript/schemas/tsconfig.schema.json index 4600b6483f244..bb3f04e9c6a4b 100644 --- a/packages/typescript/schemas/tsconfig.schema.json +++ b/packages/typescript/schemas/tsconfig.schema.json @@ -85,15 +85,36 @@ "type": "array", "items": { "type": "string" - } + }, + "description": "File extensions handled by this mapper. Defaults to the value of 'typescript.contentMapper.extensions' in the package manifest." + }, + "include": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Patterns relative to this config file that narrow which files the mapper handles." + }, + "outputExtensions": { + "anyOf": [ + { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + { + "type": "null" + } + ], + "description": "Maps source file extensions to output extensions for declaration filenames and rewritten imports." }, "options": { "type": "object" } }, "required": [ - "package", - "extensions" + "package" ], "additionalProperties": false } diff --git a/packages/typescript/src/vscode/extensionApi.ts b/packages/typescript/src/vscode/extensionApi.ts index 5fe13b13f94f1..05c729a7d70a2 100644 --- a/packages/typescript/src/vscode/extensionApi.ts +++ b/packages/typescript/src/vscode/extensionApi.ts @@ -25,10 +25,11 @@ export interface ContentMapperManifest { readonly compilerOptions?: readonly string[] | undefined; readonly dynamicConfig?: boolean | undefined; readonly outputExtensions?: Readonly> | undefined; + readonly extensions?: readonly string[] | undefined; } export interface ContentMapperContribution { - readonly extensions: readonly string[]; + readonly extensions?: readonly string[] | undefined; readonly inferredProjectContribution?: { readonly options?: Readonly> | undefined; readonly manifest: ContentMapperManifest; diff --git a/packages/vscode-typescript/src/contentMapperContributions.ts b/packages/vscode-typescript/src/contentMapperContributions.ts index 8be5dc01a8acd..8cdf12ea9b287 100644 --- a/packages/vscode-typescript/src/contentMapperContributions.ts +++ b/packages/vscode-typescript/src/contentMapperContributions.ts @@ -3,7 +3,7 @@ export type { ContentMapperContribution, ContentMapperManifest } from "@typescri export interface SerializedContentMapperContribution { readonly contributorId: string; - readonly extensions: readonly string[]; + readonly extensions?: readonly string[]; readonly inferredProjectContribution?: { readonly options?: Readonly>; readonly manifest: { @@ -14,6 +14,7 @@ export interface SerializedContentMapperContribution { readonly compilerOptions?: readonly string[]; readonly dynamicConfig?: boolean; readonly outputExtensions?: Readonly>; + readonly extensions?: readonly string[]; }; }; } @@ -26,7 +27,7 @@ export function serializeContentMapperContributions( contributions.forEach(contribution => { result.push({ contributorId, - extensions: [...contribution.extensions], + ...(contribution.extensions && { extensions: [...contribution.extensions] }), inferredProjectContribution: contribution.inferredProjectContribution && { options: contribution.inferredProjectContribution.options, manifest: { @@ -37,6 +38,9 @@ export function serializeContentMapperContributions( ...(contribution.inferredProjectContribution.manifest.outputExtensions && { outputExtensions: { ...contribution.inferredProjectContribution.manifest.outputExtensions }, }), + ...(contribution.inferredProjectContribution.manifest.extensions && { + extensions: [...contribution.inferredProjectContribution.manifest.extensions], + }), }, }, }); @@ -50,10 +54,11 @@ export function validateContentMapperRegistration(contributorId: string, contrib throw new TypeError("Content mapper contributor ID must not be empty."); } for (const contribution of contributions) { - if (contribution.extensions.length === 0 || contribution.extensions.some(extension => !isExtension(extension))) { + const extensions = contribution.extensions ?? contribution.inferredProjectContribution?.manifest.extensions; + if (!extensions || extensions.length === 0 || extensions.some(extension => !isExtension(extension))) { throw new TypeError("Content mapper contributions require non-empty extensions beginning with '.' and containing no path separators."); } - if (contribution.extensions.some(extension => /\.(?:[cm]?[jt]s|[jt]sx|json)$/i.test(extension))) { + if (extensions.some(extension => /\.(?:[cm]?[jt]s|[jt]sx|json)$/i.test(extension))) { throw new TypeError("Content mapper extensions must not end in a built-in extension."); } const inferredProjectContribution = contribution.inferredProjectContribution; @@ -69,6 +74,9 @@ export function validateContentMapperRegistration(contributorId: string, contrib if (inferredProjectContribution?.manifest.outputExtensions && Object.entries(inferredProjectContribution.manifest.outputExtensions).some(([source, output]) => !isExtension(source) || !isExtension(output))) { throw new TypeError("Content mapper output extensions must be non-empty, begin with '.', and contain no path separators."); } + if (inferredProjectContribution?.manifest.extensions?.some(extension => !isExtension(extension))) { + throw new TypeError("Content mapper manifest extensions must be non-empty, begin with '.', and contain no path separators."); + } } } @@ -83,7 +91,8 @@ export function documentMatchesContentMapperContributions( const documentPath = document.uri.path.toLowerCase(); for (const contributions of registrations.values()) { for (const contribution of contributions) { - if (contribution.extensions.some(extension => documentPath.endsWith(extension.toLowerCase()))) { + const extensions = contribution.extensions ?? contribution.inferredProjectContribution?.manifest.extensions ?? []; + if (extensions.some(extension => documentPath.endsWith(extension.toLowerCase()))) { return true; } } diff --git a/packages/vscode-typescript/test/contentMapperContributions.test.ts b/packages/vscode-typescript/test/contentMapperContributions.test.ts index e0aa50f96242c..ebd5b9d1c60d2 100644 --- a/packages/vscode-typescript/test/contentMapperContributions.test.ts +++ b/packages/vscode-typescript/test/contentMapperContributions.test.ts @@ -90,4 +90,30 @@ describe("content mapper contributions", { concurrency: true }, () => { }, }]); }); + + test("uses manifest extensions when the contribution omits extensions", () => { + const contribution = { + inferredProjectContribution: { + manifest: { + name: "mapper", + exec: ["mapper"], + extensions: [".toml"], + }, + }, + } satisfies ContentMapperContribution; + assert.doesNotThrow(() => validateContentMapperRegistration("mapper", [contribution])); + assert.deepEqual(serializeContentMapperContributions(new Map([["mapper", [contribution]]])), [{ + contributorId: "mapper", + inferredProjectContribution: { + options: undefined, + manifest: { + name: "mapper", + exec: ["mapper"], + extensions: [".toml"], + cwd: undefined, + compilerOptions: undefined, + }, + }, + }]); + }); }); diff --git a/tools/scripts/lsp/generate.mts b/tools/scripts/lsp/generate.mts index 4fe3bfaed3045..28ae9c1439ef3 100644 --- a/tools/scripts/lsp/generate.mts +++ b/tools/scripts/lsp/generate.mts @@ -460,6 +460,7 @@ const customStructures: Structure[] = [ { name: "compilerOptions", type: { kind: "array", element: { kind: "base", name: "string" } }, optional: true, documentation: "Compiler option names forwarded to the mapper." }, { name: "dynamicConfig", type: { kind: "base", name: "boolean" }, optional: true, documentation: "Whether the mapper uses project-scoped dynamic configuration." }, { name: "outputExtensions", type: { kind: "map", key: { kind: "base", name: "string" }, value: { kind: "base", name: "string" } }, optional: true, documentation: "Default source-to-runtime output extension mappings." }, + { name: "extensions", type: { kind: "array", element: { kind: "base", name: "string" } }, optional: true, documentation: "Default source extensions handled by the mapper." }, ], documentation: "Inline content mapper manifest supplied by a contributing extension.", }, @@ -475,7 +476,7 @@ const customStructures: Structure[] = [ name: "ContentMapperContribution", properties: [ { name: "contributorId", type: { kind: "base", name: "string" }, documentation: "Unique identifier of the contributor extension." }, - { name: "extensions", type: { kind: "array", element: { kind: "base", name: "string" } }, documentation: "File extensions handled by this content mapper." }, + { name: "extensions", type: { kind: "array", element: { kind: "base", name: "string" } }, optional: true, documentation: "File extensions handled by this content mapper." }, { name: "inferredProjectContribution", type: { kind: "reference", name: "InferredProjectContentMapperContribution" }, optional: true, documentation: "When present, contributes this mapper to inferred projects." }, ], documentation: "One extension-provided content mapper contribution.", diff --git a/tools/scripts/tsc/options-schema.ts b/tools/scripts/tsc/options-schema.ts index e3d972501cd6b..d19cf66d6e45f 100644 --- a/tools/scripts/tsc/options-schema.ts +++ b/tools/scripts/tsc/options-schema.ts @@ -110,10 +110,23 @@ function valueSchema(declaration: Declaration): JSONSchema { type: "object", properties: { package: { type: "string", minLength: 1 }, - extensions: { type: "array", items: { type: "string" } }, + extensions: { + type: "array", + items: { type: "string" }, + description: "File extensions handled by this mapper. Defaults to the value of 'typescript.contentMapper.extensions' in the package manifest.", + }, + include: { + type: "array", + items: { type: "string" }, + description: "Patterns relative to this config file that narrow which files the mapper handles.", + }, + outputExtensions: { + ...nullable({ type: "object", additionalProperties: { type: "string" } }), + description: "Maps source file extensions to output extensions for declaration filenames and rewritten imports.", + }, options: { type: "object" }, }, - required: ["package", "extensions"], + required: ["package"], additionalProperties: false, }; } diff --git a/tools/scripts/tsc/options.test.ts b/tools/scripts/tsc/options.test.ts index 6ebdd8be29d13..37f9f34227589 100644 --- a/tools/scripts/tsc/options.test.ts +++ b/tools/scripts/tsc/options.test.ts @@ -374,6 +374,10 @@ test("schemas accept representative valid configs and reject malformed configs", { compilerOptions: { paths: { "@/*": ["src/*"] }, plugins: [{ name: "some-plugin", customSetting: true }], moduleSuffixes: ["", ".native"] } }, { typeAcquisition: { enable: true, include: ["node"], exclude: [] } }, { contentMappers: [{ package: "mapper", extensions: [".vue"], options: { customSetting: true } }] }, + { contentMappers: [{ package: "mapper" }] }, + { contentMappers: [{ package: "mapper", include: ["src", "**/blob.toml"] }] }, + { contentMappers: [{ package: "mapper", include: [], outputExtensions: { ".vue": ".js" } }] }, + { contentMappers: [{ package: "mapper", outputExtensions: null }] }, { "$schema": "./tsconfig.schema.json", "tool-specific": { anything: true } }, ]; const invalid = [ @@ -400,8 +404,10 @@ test("schemas accept representative valid configs and reject malformed configs", { references: [{ path: "" }] }, { references: [{ path: null }] }, { contentMappers: [{ package: "", extensions: [] }] }, - { contentMappers: [{ package: "mapper" }] }, { contentMappers: [{ package: "mapper", extensions: [1] }] }, + { contentMappers: [{ package: "mapper", include: "src" }] }, + { contentMappers: [{ package: "mapper", include: [1] }] }, + { contentMappers: [{ package: "mapper", outputExtensions: { ".vue": 1 } }] }, { contentMappers: [{ package: "mapper", extensions: [], options: null }] }, ]; for (const kind of ["tsconfig", "jsconfig"] as const) { diff --git a/tsc/internal/api/module_resolution.go b/tsc/internal/api/module_resolution.go index d7640b28892c1..3b90a482758f9 100644 --- a/tsc/internal/api/module_resolution.go +++ b/tsc/internal/api/module_resolution.go @@ -356,11 +356,17 @@ func (s *Session) handleResolveModuleName(ctx context.Context, params *ResolveMo if err != nil { return nil, err } - resolver = module.NewResolver(module.ResolverOptions{ + options := module.ResolverOptions{ Host: sd.snapshot, CompilerOptions: data.compilerOptions, ExtraExtensions: sd.snapshot.ContentMapperExtensions(), - }) + } + if configPath := data.compilerOptions.ConfigFilePath; configPath != "" { + if config := sd.snapshot.ConfigFileRegistry.GetConfig(s.caseSensitivity().PathKey(configPath.AsPath())); config != nil { + options.ExtraExtensions = config.ContentMapperExtensions() + } + } + resolver = module.NewResolver(options) } else { resolver = module.NewResolver(module.ResolverOptions{ Host: s, diff --git a/tsc/internal/api/session_module_resolution_test.go b/tsc/internal/api/session_module_resolution_test.go index ccffe90b69709..731145f291ff1 100644 --- a/tsc/internal/api/session_module_resolution_test.go +++ b/tsc/internal/api/session_module_resolution_test.go @@ -66,6 +66,56 @@ func TestModuleResolverUsesSnapshotFileSystem(t *testing.T) { assert.Assert(t, len(result.Trace) > 0) } +func TestContentMapperModuleResolverProjectContext(t *testing.T) { + t.Parallel() + init, _ := projecttestutil.GetSessionInitOptions(map[string]any{ + "/a/tsconfig.json": `{ + "files": ["a.ts"], "compilerOptions": {"noLib": true}, + "contentMappers": [{"package": "mapper", "extensions": [".blob.toml"], "include": ["../b"]}] + }`, + "/b/tsconfig.json": `{ + "files": ["b.ts"], "compilerOptions": {"noLib": true}, + "contentMappers": [{"package": "mapper", "extensions": [".toml"]}] + }`, + "/a/a.ts": "export {};", + "/b/b.ts": "export {};", + "/b/x.blob.toml": "", + "/c/x.blob.toml": "", + "/node_modules/mapper/package.json": `{ + "name": "mapper", "typescript": {"contentMapper": {"exec": ["run"]}} + }`, + }, nil, nil) + init.Options.RunExternalCode = true + session := NewStandaloneSession(init, nil) + defer session.Close() + snapshot, err := session.handleCreateSnapshot(t.Context(), &CreateSnapshotParams{ + OpenProjects: []DocumentIdentifier{{FileName: "/a/tsconfig.json"}, {FileName: "/b/tsconfig.json"}}, + }) + assert.NilError(t, err) + for _, test := range []struct { + configPath tspath.RootedFilePath + extension string + directory string + }{ + {configPath: "/b/tsconfig.json", directory: "/b", extension: ".toml"}, + {directory: "/c", extension: ".blob.toml"}, + } { + resolver, err := session.handleCreateModuleResolver(&CreateModuleResolverParams{ + CompilerOptions: core.CompilerOptions{ + ConfigFilePath: test.configPath, Module: core.ModuleKindPreserve, ModuleResolution: core.ModuleResolutionKindBundler, + }, + }) + assert.NilError(t, err) + result, err := session.handleResolveModuleName(t.Context(), &ResolveModuleNameParams{ + Snapshot: snapshot.Snapshot, Resolver: resolver, ModuleName: "./x.blob.toml", + ContainingDirectory: DocumentIdentifier{FileName: test.directory}, + }) + assert.NilError(t, err) + assert.Assert(t, result.ResolvedModule != nil) + assert.Equal(t, result.ResolvedModule.Extension, test.extension) + } +} + func TestStaticModuleResolutionSpecificityAndLifetime(t *testing.T) { t.Parallel() diff --git a/tsc/internal/checker/checker.go b/tsc/internal/checker/checker.go index 950b9a8e30fb8..b3b4da9db293f 100644 --- a/tsc/internal/checker/checker.go +++ b/tsc/internal/checker/checker.go @@ -16,6 +16,7 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/binder" "github.com/microsoft/TypeScript/tsc/internal/collections" + "github.com/microsoft/TypeScript/tsc/internal/contentmapper" "github.com/microsoft/TypeScript/tsc/internal/core" "github.com/microsoft/TypeScript/tsc/internal/debug" "github.com/microsoft/TypeScript/tsc/internal/diagnostics" @@ -8489,7 +8490,7 @@ func (c *Checker) checkImportCallExpression(node *ast.Node) *Type { if c.compilerOptions.RewriteRelativeImportExtensions.IsTrue() && !c.compilerOptions.DisableDynamicImportExtensionRewriting.IsTrue() && !ast.IsStringLiteralLike(specifier) { - c.checkExternalEmitHelpers(node, ExternalEmitHelpersRewriteRelativeImportExtension) + c.checkDynamicImportExtensionRewriting(node) } specifierType := c.checkExpressionCached(specifier) var optionsType *Type @@ -8537,6 +8538,16 @@ func (c *Checker) checkImportCallExpression(node *ast.Node) *Type { return c.createPromiseReturnType(node, c.anyType) } +func (c *Checker) checkDynamicImportExtensionRewriting(node *ast.Node) { + for _, rewrite := range c.program.ContentMapperExtensionRewrites() { + if !rewrite.Runtime && rewrite.Source != rewrite.Target { + c.error(node, diagnostics.Non_literal_import_paths_cannot_be_rewritten_when_a_content_mapper_uses_both_include_and_an_outputExtensions_mapping_Set_disableDynamicImportExtensionRewriting_to_disable_rewriting_of_non_literal_import_paths) + return + } + } + c.checkExternalEmitHelpers(node, ExternalEmitHelpersRewriteRelativeImportExtension) +} + /** * Syntactically and semantically checks a call or new expression. * @param node The call/new expression to be checked. @@ -8547,7 +8558,7 @@ func (c *Checker) checkCallExpression(node *ast.Node, checkMode CheckMode) *Type !c.compilerOptions.DisableDynamicImportExtensionRewriting.IsTrue() && ast.IsInJSFile(node) && ast.IsRequireCall(node, false /*requireStringLiteralLikeArgument*/) && !ast.IsStringLiteralLike(node.Arguments()[0]) { - c.checkExternalEmitHelpers(node, ExternalEmitHelpersRewriteRelativeImportExtension) + c.checkDynamicImportExtensionRewriting(node) } c.checkGrammarTypeArguments(node, node.TypeArgumentList()) signature := c.getResolvedSignature(node, nil /*candidatesOutArray*/, checkMode) @@ -15572,11 +15583,17 @@ func (c *Checker) resolveExternalModule( } if errorNode != nil && !resolvedModule.IsCustomResolution { - rewrites := c.program.ContentMapperExtensionRewrites() + allRewrites := c.program.ContentMapperExtensionRewrites() caseSensitivity := c.program.CaseSensitivity() specifier := tspath.ToModuleSpecifier(moduleReference) + rewrites := contentmapper.RewritesForImport(allRewrites, importingSourceFile.FileName(), specifier, c.program.ContentMapperExtensionForFileName, caseSensitivity) _, mappedSpecifier := specifier.RewriteExtension(rewrites, caseSensitivity) - checkDeclarationRewrite := c.compilerOptions.GetEmitDeclarations() && mappedSpecifier && + resolvedRewrites := contentmapper.FilterExtensionRewrites(allRewrites, c.program.ContentMapperExtensionForFileName(sourceFile.FileName()), caseSensitivity) + mappedSource := false + if sourceFile.ContentMapper() != "" { + _, mappedSource = sourceFile.FileName().RewriteExtension(resolvedRewrites, caseSensitivity) + } + checkDeclarationRewrite := c.compilerOptions.GetEmitDeclarations() && (mappedSpecifier || mappedSource) && tspath.PathIsRelative(moduleReference) && !importingSourceFile.IsDeclarationFile if resolvedModule.ResolvedUsingTsExtension && tspath.IsDeclarationFileName(moduleReference) { if ast.FindAncestor(location, ast.IsEmittableImport) != nil { @@ -15619,13 +15636,41 @@ func (c *Checker) resolveExternalModule( (!ast.IsLiteralImportTypeNode(location) && !ast.IsPartOfTypeOnlyImportOrExportDeclaration(location) || checkDeclarationRewrite) { shouldRewrite := specifier.ShouldRewriteExtension(rewrites, caseSensitivity) - mappedSource := false - if sourceFile.ContentMapper() != "" { - _, mappedSource = sourceFile.FileName().RewriteExtension(rewrites, caseSensitivity) - } + predictedSpecifier, _ := specifier.RewriteExtension(rewrites, caseSensitivity) + resolvedSpecifier, resolvedSpecifierRewritten := specifier.RewriteExtension(resolvedRewrites, caseSensitivity) resolvedUsingRewritableExtension := resolvedModule.ResolvedUsingTsExtension || resolvedModule.ResolvedUsingExtraExtensions && sourceFile.ContentMapper() != "" && mappedSource - if !resolvedUsingRewritableExtension && shouldRewrite { + if specifier.IsRelative() && sourceFile.ContentMapper() != "" && + (caseSensitivity.Canonicalize(predictedSpecifier.AsString()) != caseSensitivity.Canonicalize(resolvedSpecifier.AsString()) || + mappedSource && !resolvedSpecifierRewritten && resolvedModule.ResolvedUsingExtraExtensions) { + hasRootDirs := len(c.compilerOptions.RootDirs) > 0 + hasModuleSuffixes := len(c.compilerOptions.ModuleSuffixes) > 0 + if (hasRootDirs || hasModuleSuffixes) && mappedSpecifier != mappedSource { + var message *diagnostics.Message + if hasRootDirs && hasModuleSuffixes { + message = diagnostics.This_relative_import_path_is_unsafe_to_rewrite_because_it_appears_not_to_match_the_content_mapper_s_include_but_does_after_resolution_with_rootDirs_and_moduleSuffixes + if mappedSpecifier { + message = diagnostics.This_relative_import_path_is_unsafe_to_rewrite_because_it_appears_to_match_the_content_mapper_s_include_but_does_not_after_resolution_with_rootDirs_and_moduleSuffixes + } + } else if hasRootDirs { + message = diagnostics.This_relative_import_path_is_unsafe_to_rewrite_because_it_appears_not_to_match_the_content_mapper_s_include_but_does_after_resolution_with_rootDirs + if mappedSpecifier { + message = diagnostics.This_relative_import_path_is_unsafe_to_rewrite_because_it_appears_to_match_the_content_mapper_s_include_but_does_not_after_resolution_with_rootDirs + } + } else { + message = diagnostics.This_relative_import_path_is_unsafe_to_rewrite_because_it_appears_not_to_match_the_content_mapper_s_include_but_does_after_resolution_with_moduleSuffixes + if mappedSpecifier { + message = diagnostics.This_relative_import_path_is_unsafe_to_rewrite_because_it_appears_to_match_the_content_mapper_s_include_but_does_not_after_resolution_with_moduleSuffixes + } + } + c.error(errorNode, message) + } else { + c.error( + errorNode, + diagnostics.This_relative_import_path_is_unsafe_to_rewrite_because_the_content_mapper_s_outputExtensions_mapping_depends_on_module_resolution, + ) + } + } else if !resolvedUsingRewritableExtension && shouldRewrite { relativeToSourceFile := resolvedModule.ResolvedFileName.AsString() if relativePath, ok := c.program.CaseSensitivity().RelativePathFromFile( importingSourceFile.FileName(), @@ -15642,7 +15687,7 @@ func (c *Checker) resolveExternalModule( } else if resolvedUsingRewritableExtension && !shouldRewrite && (mappedSource || c.program.SourceFileMayBeEmitted(sourceFile, false)) { extension := tspath.GetAnyExtensionFromPath(moduleReference, nil, tspath.CaseSensitive) if mappedSource { - rewrite, _ := sourceFile.FileName().GetExtensionRewrite(rewrites, caseSensitivity) + rewrite, _ := sourceFile.FileName().GetExtensionRewrite(resolvedRewrites, caseSensitivity) extension = rewrite.Source } c.error( @@ -29399,7 +29444,7 @@ func (c *Checker) checkExternalEmitHelpers(location *ast.Node, helpers ExternalE if !c.hasSignatureWithArityGreaterThan(symbol, 4) { c.error(location, diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 5) } - } else if helper&ExternalEmitHelpersRewriteRelativeImportExtension != 0 && len(c.program.ContentMapperExtensionRewrites()) > 0 { + } else if helper&ExternalEmitHelpersRewriteRelativeImportExtension != 0 && tspath.HasRuntimeExtensionRewrites(c.program.ContentMapperExtensionRewrites()) { if !c.hasSignatureWithArityGreaterThan(symbol, 3) { c.error(location, diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 4) } diff --git a/tsc/internal/checker/nodebuilderimpl.go b/tsc/internal/checker/nodebuilderimpl.go index 6acae42dc15e1..2d2d01e83affa 100644 --- a/tsc/internal/checker/nodebuilderimpl.go +++ b/tsc/internal/checker/nodebuilderimpl.go @@ -8,6 +8,7 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/collections" + "github.com/microsoft/TypeScript/tsc/internal/contentmapper" "github.com/microsoft/TypeScript/tsc/internal/core" "github.com/microsoft/TypeScript/tsc/internal/debug" "github.com/microsoft/TypeScript/tsc/internal/jsnum" @@ -1380,6 +1381,9 @@ func (b *NodeBuilderImpl) rewriteContentMappedModuleSpecifier(specifier tspath.M if b.ctx.internalFlags&nodebuilder.InternalFlagsRewriteModuleSpecifiers != 0 && b.ch.compilerOptions.RewriteRelativeImportExtensions.IsTrue() { rewrites := b.ctx.host.ContentMapperExtensionRewrites() caseSensitivity := b.ctx.host.CaseSensitivity() + if b.ctx.enclosingFile != nil { + rewrites = contentmapper.RewritesForImport(rewrites, b.ctx.enclosingFile.FileName(), specifier, b.ctx.host.ContentMapperExtensionForFileName, caseSensitivity) + } if specifier.ShouldRewriteExtension(rewrites, caseSensitivity) { rewritten, _ := specifier.RewriteExtension(rewrites, caseSensitivity) return rewritten diff --git a/tsc/internal/compiler/contentmapper_test.go b/tsc/internal/compiler/contentmapper_test.go index d477022346274..b7f6493880fab 100644 --- a/tsc/internal/compiler/contentmapper_test.go +++ b/tsc/internal/compiler/contentmapper_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "slices" + "strings" "testing" "github.com/microsoft/TypeScript/tsc/internal/ast" @@ -72,6 +73,431 @@ func newContentMapperProgramWithOutputExtensions(t *testing.T, contentMapperProj }) } +func TestContentMapperSymlinkedPackage(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + include []string + wantFiltered bool + preserveSymlinks bool + }{ + {name: "logical include", include: []string{"node_modules/@scope/lib"}}, + {name: "unchanged association"}, + {name: "realpath mapper", include: []string{"packages/lib"}, wantFiltered: true}, + {name: "logical then real include", include: []string{"node_modules/@scope/lib", "packages/lib"}, wantFiltered: true}, + {name: "real then logical include", include: []string{"packages/lib", "node_modules/@scope/lib"}, wantFiltered: true}, + {name: "preserved logical include", include: []string{"node_modules/@scope/lib"}, wantFiltered: true, preserveSymlinks: true}, + {name: "preserved real include", include: []string{"packages/lib"}, preserveSymlinks: true}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + // A root and both package and relative imports must share the same loaded path. + dataPath := tspath.RootedFilePath("/project/packages/lib/data.vue") + directImport := "./packages/lib/data.vue" + if test.preserveSymlinks { + dataPath = "/project/node_modules/@scope/lib/data.vue" + directImport = "./node_modules/@scope/lib/data.vue" + } + fs := vfstest.FromMap(map[string]any{ + "/project/main.ts": `import { value } from "@scope/lib/data.vue"; import { value as direct } from "` + directImport + `"; export { value, direct };`, + "/project/node_modules/@scope/lib": vfstest.Symlink("/project/packages/lib"), + "/project/packages/lib/package.json": `{"name": "@scope/lib", "version": "1.0.0"}`, + "/project/packages/lib/data.vue": "