Skip to content

[For testing only]: Redirect node to bundler #51973

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 7 commits into from
Closed
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
43 changes: 26 additions & 17 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -814,6 +814,7 @@ import {
nodeIsPresent,
nodeIsSynthesized,
NodeLinks,
nodeModulesPathPart,
nodeStartsNewLexicalEnvironment,
NodeWithTypeArguments,
NonNullChain,
Expand Down Expand Up @@ -4765,7 +4766,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {

if (sourceFile.symbol) {
if (resolvedModule.isExternalLibraryImport && !resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
errorOnImplicitAnyModule(/*isError*/ false, errorNode, currentSourceFile, mode, resolvedModule, moduleReference);
}
if (moduleResolutionKind === ModuleResolutionKind.Node16 || moduleResolutionKind === ModuleResolutionKind.NodeNext) {
const isSyncImport = (currentSourceFile.impliedNodeFormat === ModuleKind.CommonJS && !findAncestor(location, isImportCall)) || !!findAncestor(location, isImportEqualsDeclaration);
Expand Down Expand Up @@ -4853,7 +4854,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
error(errorNode, diag, moduleReference, resolvedModule!.resolvedFileName);
}
else {
errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule!, moduleReference);
errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, currentSourceFile, mode, resolvedModule!, moduleReference);
}
// Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
return undefined;
Expand Down Expand Up @@ -4923,25 +4924,33 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
}

function errorOnImplicitAnyModule(isError: boolean, errorNode: Node, { packageId, resolvedFileName }: ResolvedModuleFull, moduleReference: string): void {
const errorInfo = !isExternalModuleNameRelative(moduleReference) && packageId
? typesPackageExists(packageId.name)
function errorOnImplicitAnyModule(isError: boolean, errorNode: Node, sourceFile: SourceFile, mode: ResolutionMode, { packageId, resolvedFileName }: ResolvedModuleFull, moduleReference: string): void {
let errorInfo;
if (!isExternalModuleNameRelative(moduleReference) && packageId) {
const legacyResult = sourceFile.resolvedModules?.get(moduleReference, mode)?.legacyResult;
errorInfo = legacyResult
? chainDiagnosticMessages(
/*details*/ undefined,
Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1,
packageId.name, mangleScopedPackageName(packageId.name))
: packageBundlesTypes(packageId.name)
Diagnostics.There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The_1_library_may_need_to_update_its_package_json,
legacyResult,
legacyResult.indexOf(nodeModulesPathPart + "@types/") > -1 ? `@types/${mangleScopedPackageName(packageId.name)}` : packageId.name)
: typesPackageExists(packageId.name)
? chainDiagnosticMessages(
/*details*/ undefined,
Diagnostics.If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1,
packageId.name,
moduleReference)
: chainDiagnosticMessages(
/*details*/ undefined,
Diagnostics.Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0,
moduleReference,
mangleScopedPackageName(packageId.name))
: undefined;
Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1,
packageId.name, mangleScopedPackageName(packageId.name))
: packageBundlesTypes(packageId.name)
? chainDiagnosticMessages(
/*details*/ undefined,
Diagnostics.If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1,
packageId.name,
moduleReference)
: chainDiagnosticMessages(
/*details*/ undefined,
Diagnostics.Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0,
moduleReference,
mangleScopedPackageName(packageId.name));
}
errorOrSuggestion(isError, errorNode, chainDiagnosticMessages(
errorInfo,
Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type,
Expand Down
2 changes: 1 addition & 1 deletion src/compiler/commandLineParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -964,7 +964,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [
type: new Map(Object.entries({
// N.B. The first entry specifies the value shown in `tsc --init`
node10: ModuleResolutionKind.Node10,
node: ModuleResolutionKind.Node10,
node: ModuleResolutionKind.Bundler,
classic: ModuleResolutionKind.Classic,
node16: ModuleResolutionKind.Node16,
nodenext: ModuleResolutionKind.NodeNext,
Expand Down
8 changes: 8 additions & 0 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -5219,6 +5219,14 @@
"category": "Message",
"code": 6276
},
"Resolution of non-relative name failed; trying with modern Node resolution features disabled to see if npm library needs configuration update.": {
"category": "Message",
"code": 6277
},
"There are types at '{0}', but this result could not be resolved when respecting package.json \"exports\". The '{1}' library may need to update its package.json.": {
"category": "Message",
"code": 6278
},

"Enable project compilation": {
"category": "Message",
Expand Down
80 changes: 55 additions & 25 deletions src/compiler/moduleNameResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,8 @@ function createResolvedModuleWithFailedLookupLocations(
failedLookupLocations: string[],
affectingLocations: string[],
diagnostics: Diagnostic[],
resultFromCache: ResolvedModuleWithFailedLookupLocations | undefined
resultFromCache: ResolvedModuleWithFailedLookupLocations | undefined,
legacyResult?: string,
): ResolvedModuleWithFailedLookupLocations {
if (resultFromCache) {
resultFromCache.failedLookupLocations = updateResolutionField(resultFromCache.failedLookupLocations, failedLookupLocations);
Expand All @@ -234,6 +235,7 @@ function createResolvedModuleWithFailedLookupLocations(
failedLookupLocations: initializeResolutionField(failedLookupLocations),
affectingLocations: initializeResolutionField(affectingLocations),
resolutionDiagnostics: initializeResolutionField(diagnostics),
legacyResult,
};
}
function initializeResolutionField<T>(value: T[]): T[] | undefined {
Expand Down Expand Up @@ -1665,12 +1667,37 @@ function nodeModuleNameResolverWorker(features: NodeResolutionFeatures, moduleNa
const priorityExtensions = extensions & (Extensions.TypeScript | Extensions.Declaration);
const secondaryExtensions = extensions & ~(Extensions.TypeScript | Extensions.Declaration);
result =
priorityExtensions && tryResolve(priorityExtensions) ||
secondaryExtensions && tryResolve(secondaryExtensions) ||
priorityExtensions && tryResolve(priorityExtensions, state) ||
secondaryExtensions && tryResolve(secondaryExtensions, state) ||
undefined;
}
else {
result = tryResolve(extensions);
result = tryResolve(extensions, state);
}

// For non-relative names that resolved to JS but no types in modes that look up an "import" condition in package.json "exports",
// try again with "exports" disabled to try to detect if this is likely a configuration error in a dependency's package.json.
let legacyResult;
if (result?.value?.isExternalLibraryImport
&& !isConfigLookup
&& extensions & (Extensions.TypeScript | Extensions.Declaration)
&& features & NodeResolutionFeatures.Exports
&& !isExternalModuleNameRelative(moduleName)
&& !extensionIsOk(Extensions.TypeScript | Extensions.Declaration, result.value.resolved.extension)
&& conditions.indexOf("import") > -1
) {
traceIfEnabled(state, Diagnostics.Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_if_npm_library_needs_configuration_update);
const diagnosticState = {
...state,
features: state.features & ~NodeResolutionFeatures.Exports,
failedLookupLocations: [],
affectingLocations: [],
reportDiagnostic: noop,
};
const diagnosticResult = tryResolve(extensions & (Extensions.TypeScript | Extensions.Declaration), diagnosticState);
if (diagnosticResult?.value?.isExternalLibraryImport) {
legacyResult = diagnosticResult.value.resolved.path;
}
}

return createResolvedModuleWithFailedLookupLocations(
Expand All @@ -1679,10 +1706,11 @@ function nodeModuleNameResolverWorker(features: NodeResolutionFeatures, moduleNa
failedLookupLocations,
affectingLocations,
diagnostics,
state.resultFromCache
state.resultFromCache,
legacyResult,
);

function tryResolve(extensions: Extensions): SearchResult<{ resolved: Resolved, isExternalLibraryImport: boolean }> {
function tryResolve(extensions: Extensions, state: ModuleResolutionState): SearchResult<{ resolved: Resolved, isExternalLibraryImport: boolean }> {
const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true);
const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
if (resolved) {
Expand Down Expand Up @@ -2756,27 +2784,31 @@ function loadModuleFromImmediateNodeModulesDirectory(extensions: Extensions, mod

function loadModuleFromSpecificNodeModulesDirectory(extensions: Extensions, moduleName: string, nodeModulesDirectory: string, nodeModulesDirectoryExists: boolean, state: ModuleResolutionState, cache: ModuleResolutionCache | undefined, redirectedReference: ResolvedProjectReference | undefined): Resolved | undefined {
const candidate = normalizePath(combinePaths(nodeModulesDirectory, moduleName));
const { packageName, rest } = parsePackageName(moduleName);
const packageDirectory = combinePaths(nodeModulesDirectory, packageName);

let rootPackageInfo: PackageJsonInfo | undefined;
// First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
let packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
// But only if we're not respecting export maps (if we are, we might redirect around this location)
if (!(state.features & NodeResolutionFeatures.Exports)) {
if (packageInfo) {
const fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
if (fromFile) {
return noPackageId(fromFile);
}

const fromDirectory = loadNodeModuleFromDirectoryWorker(
extensions,
candidate,
!nodeModulesDirectoryExists,
state,
packageInfo.contents.packageJsonContent,
getVersionPathsOfPackageJsonInfo(packageInfo, state),
);
return withPackageId(packageInfo, fromDirectory);
if (rest !== "" && packageInfo && (
!(state.features & NodeResolutionFeatures.Exports) ||
!hasProperty((rootPackageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state))?.contents.packageJsonContent ?? emptyArray, "exports")
)) {
const fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
if (fromFile) {
return noPackageId(fromFile);
}

const fromDirectory = loadNodeModuleFromDirectoryWorker(
extensions,
candidate,
!nodeModulesDirectoryExists,
state,
packageInfo.contents.packageJsonContent,
getVersionPathsOfPackageJsonInfo(packageInfo, state),
);
return withPackageId(packageInfo, fromDirectory);
}

const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => {
Expand All @@ -2803,11 +2835,9 @@ function loadModuleFromSpecificNodeModulesDirectory(extensions: Extensions, modu
return withPackageId(packageInfo, pathAndExtension);
};

const { packageName, rest } = parsePackageName(moduleName);
const packageDirectory = combinePaths(nodeModulesDirectory, packageName);
if (rest !== "") {
// Previous `packageInfo` may have been from a nested package.json; ensure we have the one from the package root now.
packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
packageInfo = rootPackageInfo ?? getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
}
// package exports are higher priority than file/directory/typesVersions lookups and (and, if there's exports present, blocks them)
if (packageInfo && packageInfo.contents.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) {
Expand Down
2 changes: 2 additions & 0 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7605,6 +7605,8 @@ export interface ResolvedModuleWithFailedLookupLocations {
affectingLocations?: string[];
/** @internal */
resolutionDiagnostics?: Diagnostic[]
/** @internal */
legacyResult?: string;
}

export interface ResolvedTypeReferenceDirective {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[
"======== Resolving module '@restart/hooks/useMergedRefs' from '/main.ts'. ========",
"Explicitly specified module resolution kind: 'Bundler'.",
"File '/package.json' does not exist.",
"Loading module '@restart/hooks/useMergedRefs' from 'node_modules' folder, target file types: TypeScript, JavaScript, Declaration, JSON.",
"Found 'package.json' at '/node_modules/@restart/hooks/useMergedRefs/package.json'.",
"Found 'package.json' at '/node_modules/@restart/hooks/package.json'.",
"File '/node_modules/@restart/hooks/useMergedRefs.ts' does not exist.",
"File '/node_modules/@restart/hooks/useMergedRefs.tsx' does not exist.",
"File '/node_modules/@restart/hooks/useMergedRefs.d.ts' does not exist.",
"'package.json' does not have a 'typesVersions' field.",
"'package.json' does not have a 'typings' field.",
"'package.json' has 'types' field '../esm/useMergedRefs.d.ts' that references '/node_modules/@restart/hooks/esm/useMergedRefs.d.ts'.",
"File '/node_modules/@restart/hooks/esm/useMergedRefs.d.ts' exist - use it as a name resolution result.",
"Resolving real path for '/node_modules/@restart/hooks/esm/useMergedRefs.d.ts', result '/node_modules/@restart/hooks/esm/useMergedRefs.d.ts'.",
"======== Module name '@restart/hooks/useMergedRefs' was successfully resolved to '/node_modules/@restart/hooks/esm/useMergedRefs.d.ts'. ========"
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
[
"File '/node_modules/@restart/hooks/esm/package.json' does not exist.",
"Found 'package.json' at '/node_modules/@restart/hooks/package.json'.",
"File '/package.json' does not exist.",
"======== Resolving module '@restart/hooks/useMergedRefs' from '/main.ts'. ========",
"Explicitly specified module resolution kind: 'Node16'.",
"Resolving in CJS mode with conditions 'node', 'require', 'types'.",
"File '/package.json' does not exist according to earlier cached lookups.",
"Loading module '@restart/hooks/useMergedRefs' from 'node_modules' folder, target file types: TypeScript, JavaScript, Declaration.",
"Found 'package.json' at '/node_modules/@restart/hooks/useMergedRefs/package.json'.",
"File '/node_modules/@restart/hooks/package.json' exists according to earlier cached lookups.",
"File '/node_modules/@restart/hooks/useMergedRefs.ts' does not exist.",
"File '/node_modules/@restart/hooks/useMergedRefs.tsx' does not exist.",
"File '/node_modules/@restart/hooks/useMergedRefs.d.ts' does not exist.",
"'package.json' does not have a 'typesVersions' field.",
"'package.json' does not have a 'typings' field.",
"'package.json' has 'types' field '../esm/useMergedRefs.d.ts' that references '/node_modules/@restart/hooks/esm/useMergedRefs.d.ts'.",
"File '/node_modules/@restart/hooks/esm/useMergedRefs.d.ts' exist - use it as a name resolution result.",
"Resolving real path for '/node_modules/@restart/hooks/esm/useMergedRefs.d.ts', result '/node_modules/@restart/hooks/esm/useMergedRefs.d.ts'.",
"======== Module name '@restart/hooks/useMergedRefs' was successfully resolved to '/node_modules/@restart/hooks/esm/useMergedRefs.d.ts'. ========",
"File 'package.json' does not exist.",
"File '/package.json' does not exist according to earlier cached lookups.",
"File 'package.json' does not exist according to earlier cached lookups.",
"File '/package.json' does not exist according to earlier cached lookups.",
"File 'package.json' does not exist according to earlier cached lookups.",
"File '/package.json' does not exist according to earlier cached lookups.",
"File 'package.json' does not exist according to earlier cached lookups.",
"File '/package.json' does not exist according to earlier cached lookups.",
"File 'package.json' does not exist according to earlier cached lookups.",
"File '/package.json' does not exist according to earlier cached lookups."
]
Loading