Offer auto-imports from wildcard exports with AutoImportProvider (#54831)

This commit is contained in:
Andrew Branch
2023-07-07 12:50:38 -05:00
committed by GitHub
parent e374eba37c
commit 22a9ae9eed
5 changed files with 172 additions and 36 deletions

View File

@@ -9,6 +9,7 @@ import {
CommandLineOption,
comparePaths,
Comparison,
CompilerHost,
CompilerOptions,
concatenate,
contains,
@@ -36,10 +37,12 @@ import {
forEachAncestorDirectory,
formatMessage,
getAllowJSCompilerOption,
getAnyExtensionFromPath,
getBaseFileName,
GetCanonicalFileName,
getCommonSourceDirectory,
getCompilerOptionValue,
getDeclarationEmitExtensionForPath,
getDirectoryPath,
GetEffectiveTypeRootsHost,
getEmitModuleKind,
@@ -99,6 +102,7 @@ import {
startsWith,
stringContains,
supportedDeclarationExtensions,
supportedJSExtensionsFlat,
supportedTSImplementationExtensions,
toPath,
tryExtractTSExtension,
@@ -194,6 +198,15 @@ function formatExtensions(extensions: Extensions) {
return result.join(", ");
}
function extensionsToExtensionsArray(extensions: Extensions) {
const result: Extension[] = [];
if (extensions & Extensions.TypeScript) result.push(...supportedTSImplementationExtensions);
if (extensions & Extensions.JavaScript) result.push(...supportedJSExtensionsFlat);
if (extensions & Extensions.Declaration) result.push(...supportedDeclarationExtensions);
if (extensions & Extensions.Json) result.push(Extension.Json);
return result;
}
interface PathAndPackageId {
readonly fileName: string;
readonly packageId: PackageId | undefined;
@@ -2085,11 +2098,16 @@ function loadNodeModuleFromDirectory(extensions: Extensions, candidate: string,
return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
}
/** @internal */
export interface GetPackageJsonEntrypointsHost extends ModuleResolutionHost {
readDirectory: CompilerHost["readDirectory"];
}
/** @internal */
export function getEntrypointsFromPackageJsonInfo(
packageJsonInfo: PackageJsonInfo,
options: CompilerOptions,
host: ModuleResolutionHost,
host: GetPackageJsonEntrypointsHost,
cache: ModuleResolutionCache | undefined,
resolveJs?: boolean,
): string[] | false {
@@ -2120,7 +2138,7 @@ export function getEntrypointsFromPackageJsonInfo(
arrayIsEqualTo
);
for (const conditions of conditionSets) {
const loadPackageJsonExportsState = { ...loadPackageJsonMainState, failedLookupLocations: [], conditions };
const loadPackageJsonExportsState = { ...loadPackageJsonMainState, failedLookupLocations: [], conditions, host };
const exportResolutions = loadEntrypointsFromExportMap(
packageJsonInfo,
packageJsonInfo.contents.packageJsonContent.exports,
@@ -2140,7 +2158,7 @@ export function getEntrypointsFromPackageJsonInfo(
function loadEntrypointsFromExportMap(
scope: PackageJsonInfo,
exports: object,
state: ModuleResolutionState,
state: ModuleResolutionState & { host: GetPackageJsonEntrypointsHost },
extensions: Extensions,
): PathAndExtension[] | undefined {
let entrypoints: PathAndExtension[] | undefined;
@@ -2161,17 +2179,37 @@ function loadEntrypointsFromExportMap(
return entrypoints;
function loadEntrypointsFromTargetExports(target: unknown): boolean | undefined {
if (typeof target === "string" && startsWith(target, "./") && target.indexOf("*") === -1) {
const partsAfterFirst = getPathComponents(target).slice(2);
if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) {
return false;
if (typeof target === "string" && startsWith(target, "./")) {
if (target.indexOf("*") >= 0 && state.host.readDirectory) {
if (target.indexOf("*") !== target.lastIndexOf("*")) {
return false;
}
state.host.readDirectory(
scope.packageDirectory,
extensionsToExtensionsArray(extensions),
/*excludes*/ undefined,
[changeAnyExtension(target.replace("*", "**/*"), getDeclarationEmitExtensionForPath(target))]
).forEach(entry => {
entrypoints = appendIfUnique(entrypoints, {
path: entry,
ext: getAnyExtensionFromPath(entry),
resolvedUsingTsExtension: undefined
});
});
}
const resolvedTarget = combinePaths(scope.packageDirectory, target);
const finalPath = getNormalizedAbsolutePath(resolvedTarget, state.host.getCurrentDirectory?.());
const result = loadFileNameFromPackageJsonField(extensions, finalPath, /*onlyRecordFailures*/ false, state);
if (result) {
entrypoints = appendIfUnique(entrypoints, result, (a, b) => a.path === b.path);
return true;
else {
const partsAfterFirst = getPathComponents(target).slice(2);
if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) {
return false;
}
const resolvedTarget = combinePaths(scope.packageDirectory, target);
const finalPath = getNormalizedAbsolutePath(resolvedTarget, state.host.getCurrentDirectory?.());
const result = loadFileNameFromPackageJsonField(extensions, finalPath, /*onlyRecordFailures*/ false, state);
if (result) {
entrypoints = appendIfUnique(entrypoints, result, (a, b) => a.path === b.path);
return true;
}
}
}
else if (Array.isArray(target)) {
@@ -2685,12 +2723,6 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo
return ensureTrailingDirectorySeparator(combinePaths(root, dir));
}
function useCaseSensitiveFileNames() {
return !state.host.useCaseSensitiveFileNames ? true :
typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames :
state.host.useCaseSensitiveFileNames();
}
function tryLoadInputFileForPath(finalPath: string, entry: string, packagePath: string, isImports: boolean) {
// Replace any references to outputs for files in the program with the input files to support package self-names used with outDir
// PROBLEM: We don't know how to calculate the output paths yet, because the "common source directory" we use as the base of the file structure
@@ -2700,13 +2732,13 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo
if (!state.isConfigLookup
&& (state.compilerOptions.declarationDir || state.compilerOptions.outDir)
&& finalPath.indexOf("/node_modules/") === -1
&& (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames()) : true)
&& (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames(state)) : true)
) {
// So that all means we'll only try these guesses for files outside `node_modules` in a directory where the `package.json` and `tsconfig.json` are siblings.
// Even with all that, we still don't know if the root of the output file structure will be (relative to the package file)
// `.`, `./src` or any other deeper directory structure. (If project references are used, it's definitely `.` by fiat, so that should be pretty common.)
const getCanonicalFileName = hostGetCanonicalFileName({ useCaseSensitiveFileNames });
const getCanonicalFileName = hostGetCanonicalFileName({ useCaseSensitiveFileNames: () => useCaseSensitiveFileNames(state) });
const commonSourceDirGuesses: string[] = [];
// A `rootDir` compiler option strongly indicates the root location
// A `composite` project is using project references and has it's common src dir set to `.`, so it shouldn't need to check any other locations
@@ -2761,7 +2793,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo
for (const commonSourceDirGuess of commonSourceDirGuesses) {
const candidateDirectories = getOutputDirectoriesForBaseDirectory(commonSourceDirGuess);
for (const candidateDir of candidateDirectories) {
if (containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames())) {
if (containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames(state))) {
// The matched export is looking up something in either the out declaration or js dir, now map the written path back into the source dir and source extension
const pathFragment = finalPath.slice(candidateDir.length + 1); // +1 to also remove directory seperator
const possibleInputBase = combinePaths(commonSourceDirGuess, pathFragment);
@@ -2771,7 +2803,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo
const inputExts = getPossibleOriginalInputExtensionForExtension(possibleInputBase);
for (const possibleExt of inputExts) {
if (!extensionIsOk(extensions, possibleExt)) continue;
const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames());
const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames(state));
if (state.host.fileExists(possibleInputWithInputExtension)) {
return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField(extensions, possibleInputWithInputExtension, /*onlyRecordFailures*/ false, state)));
}
@@ -3203,3 +3235,9 @@ function traceIfEnabled(state: ModuleResolutionState, diagnostic: DiagnosticMess
trace(state.host, diagnostic, ...args);
}
}
function useCaseSensitiveFileNames(state: ModuleResolutionState) {
return !state.host.useCaseSensitiveFileNames ? true :
typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames :
state.host.useCaseSensitiveFileNames();
}