Skip to content
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

Only look up package.json type if module is node16/nodenext or file is in node_modules #58825

Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Revert "Revert "Respect package.json "type" and module-format-speci…
…fic file extensions in more `module` modes (#57896)""

This reverts commit d3c8f08.
  • Loading branch information
andrewbranch committed Jun 17, 2024
commit c4069c58b0aaa0eaa738f4419c03b7d6bba9797a
2 changes: 1 addition & 1 deletion src/compiler/_namespaces/ts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export * from "../transformers/generators.js";
export * from "../transformers/module/module.js";
export * from "../transformers/module/system.js";
export * from "../transformers/module/esnextAnd2015.js";
export * from "../transformers/module/node.js";
export * from "../transformers/module/impliedNodeFormatDependent.js";
export * from "../transformers/declarations/diagnostics.js";
export * from "../transformers/declarations.js";
export * from "../transformer.js";
Expand Down
97 changes: 63 additions & 34 deletions src/compiler/checker.ts

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -967,6 +967,10 @@
"category": "Error",
"code": 1292
},
"ESM syntax is not allowed in a CommonJS module when 'module' is set to 'preserve'.": {
"category": "Error",
"code": 1293
},

"'with' statements are not allowed in an async function block.": {
"category": "Error",
Expand Down
3 changes: 3 additions & 0 deletions src/compiler/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ import {
getEmitFlags,
getEmitHelpers,
getEmitModuleKind,
getEmitModuleResolutionKind,
getEmitScriptTarget,
getExternalModuleName,
getIdentifierTypeArguments,
Expand Down Expand Up @@ -829,6 +830,7 @@ export function emitFiles(
newLine: compilerOptions.newLine,
noEmitHelpers: compilerOptions.noEmitHelpers,
module: getEmitModuleKind(compilerOptions),
moduleResolution: getEmitModuleResolutionKind(compilerOptions),
target: getEmitScriptTarget(compilerOptions),
sourceMap: compilerOptions.sourceMap,
inlineSourceMap: compilerOptions.inlineSourceMap,
Expand Down Expand Up @@ -904,6 +906,7 @@ export function emitFiles(
newLine: compilerOptions.newLine,
noEmitHelpers: true,
module: compilerOptions.module,
moduleResolution: compilerOptions.moduleResolution,
target: compilerOptions.target,
sourceMap: !forceDtsEmit && compilerOptions.declarationMap,
inlineSourceMap: compilerOptions.inlineSourceMap,
Expand Down
8 changes: 4 additions & 4 deletions src/compiler/factory/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,12 @@ import {
getAllAccessorDeclarations,
getEmitFlags,
getEmitHelpers,
getEmitModuleFormatOfFileWorker,
getEmitModuleKind,
getESModuleInterop,
getExternalModuleName,
getExternalModuleNameFromPath,
getImpliedNodeFormatForEmitWorker,
getJSDocType,
getJSDocTypeTag,
getModifiers,
Expand Down Expand Up @@ -712,7 +714,7 @@ export function createExternalHelpersImportDeclarationIfNeeded(nodeFactory: Node
if (compilerOptions.importHelpers && isEffectiveExternalModule(sourceFile, compilerOptions)) {
let namedBindings: NamedImportBindings | undefined;
const moduleKind = getEmitModuleKind(compilerOptions);
if ((moduleKind >= ModuleKind.ES2015 && moduleKind <= ModuleKind.ESNext) || sourceFile.impliedNodeFormat === ModuleKind.ESNext) {
if ((moduleKind >= ModuleKind.ES2015 && moduleKind <= ModuleKind.ESNext) || getImpliedNodeFormatForEmitWorker(sourceFile, compilerOptions) === ModuleKind.ESNext) {
// use named imports
const helpers = getEmitHelpers(sourceFile);
if (helpers) {
Expand Down Expand Up @@ -769,10 +771,8 @@ export function getOrCreateExternalHelpersModuleNameIfNeeded(factory: NodeFactor
return externalHelpersModuleName;
}

const moduleKind = getEmitModuleKind(compilerOptions);
let create = (hasExportStarsToExportValues || (getESModuleInterop(compilerOptions) && hasImportStarOrImportDefault))
&& moduleKind !== ModuleKind.System
&& (moduleKind < ModuleKind.ES2015 || node.impliedNodeFormat === ModuleKind.CommonJS);
&& getEmitModuleFormatOfFileWorker(node, compilerOptions) < ModuleKind.System;
if (!create) {
const helpers = getEmitHelpers(node);
if (helpers) {
Expand Down
37 changes: 24 additions & 13 deletions src/compiler/moduleSpecifiers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ import {
getBaseFileName,
GetCanonicalFileName,
getConditions,
getDefaultResolutionModeForFileWorker,
getDirectoryPath,
getEmitModuleResolutionKind,
getModeForResolutionAtIndex,
getModuleNameStringLiteralAt,
getModuleSpecifierEndingPreference,
getNodeModulePathParts,
Expand Down Expand Up @@ -143,12 +143,13 @@ export interface ModuleSpecifierPreferences {
/**
* @param syntaxImpliedNodeFormat Used when the import syntax implies ESM or CJS irrespective of the mode of the file.
*/
getAllowedEndingsInPreferredOrder(syntaxImpliedNodeFormat?: SourceFile["impliedNodeFormat"]): ModuleSpecifierEnding[];
getAllowedEndingsInPreferredOrder(syntaxImpliedNodeFormat?: ResolutionMode): ModuleSpecifierEnding[];
}

/** @internal */
export function getModuleSpecifierPreferences(
{ importModuleSpecifierPreference, importModuleSpecifierEnding }: UserPreferences,
host: Pick<ModuleSpecifierResolutionHost, "getDefaultResolutionModeForFile">,
compilerOptions: CompilerOptions,
importingSourceFile: Pick<SourceFile, "fileName" | "impliedNodeFormat">,
oldImportSpecifier?: string,
Expand All @@ -163,8 +164,10 @@ export function getModuleSpecifierPreferences(
importModuleSpecifierPreference === "project-relative" ? RelativePreference.ExternalNonRelative :
RelativePreference.Shortest,
getAllowedEndingsInPreferredOrder: syntaxImpliedNodeFormat => {
const preferredEnding = syntaxImpliedNodeFormat !== importingSourceFile.impliedNodeFormat ? getPreferredEnding(syntaxImpliedNodeFormat) : filePreferredEnding;
if ((syntaxImpliedNodeFormat ?? importingSourceFile.impliedNodeFormat) === ModuleKind.ESNext) {
const impliedNodeFormat = getDefaultResolutionModeForFile(importingSourceFile, host, compilerOptions);
const preferredEnding = syntaxImpliedNodeFormat !== impliedNodeFormat ? getPreferredEnding(syntaxImpliedNodeFormat) : filePreferredEnding;
const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
if ((syntaxImpliedNodeFormat ?? impliedNodeFormat) === ModuleKind.ESNext && ModuleResolutionKind.Node16 <= moduleResolution && moduleResolution <= ModuleResolutionKind.NodeNext) {
if (shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName)) {
return [ModuleSpecifierEnding.TsExtension, ModuleSpecifierEnding.JsExtension];
}
Expand Down Expand Up @@ -204,7 +207,7 @@ export function getModuleSpecifierPreferences(
}
return getModuleSpecifierEndingPreference(
importModuleSpecifierEnding,
resolutionMode ?? importingSourceFile.impliedNodeFormat,
resolutionMode ?? getDefaultResolutionModeForFile(importingSourceFile, host, compilerOptions),
compilerOptions,
isFullSourceFile(importingSourceFile) ? importingSourceFile : undefined,
);
Expand All @@ -225,7 +228,7 @@ export function updateModuleSpecifier(
oldImportSpecifier: string,
options: ModuleSpecifierOptions = {},
): string | undefined {
const res = getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, getModuleSpecifierPreferences({}, compilerOptions, importingSourceFile, oldImportSpecifier), {}, options);
const res = getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, getModuleSpecifierPreferences({}, host, compilerOptions, importingSourceFile, oldImportSpecifier), {}, options);
if (res === oldImportSpecifier) return undefined;
return res;
}
Expand All @@ -245,7 +248,7 @@ export function getModuleSpecifier(
host: ModuleSpecifierResolutionHost,
options: ModuleSpecifierOptions = {},
): string {
return getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, getModuleSpecifierPreferences({}, compilerOptions, importingSourceFile), {}, options);
return getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, getModuleSpecifierPreferences({}, host, compilerOptions, importingSourceFile), {}, options);
}

/** @internal */
Expand Down Expand Up @@ -275,7 +278,7 @@ function getModuleSpecifierWorker(
const info = getInfo(importingSourceFileName, host);
const modulePaths = getAllModulePaths(info, toFileName, host, userPreferences, compilerOptions, options);
return firstDefined(modulePaths, modulePath => tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, userPreferences, /*packageNameOnly*/ undefined, options.overrideImportMode)) ||
getLocalModuleSpecifier(toFileName, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences);
getLocalModuleSpecifier(toFileName, info, compilerOptions, host, options.overrideImportMode || getDefaultResolutionModeForFile(importingSourceFile, host, compilerOptions), preferences);
}

/** @internal */
Expand Down Expand Up @@ -403,7 +406,7 @@ export function getLocalModuleSpecifierBetweenFileNames(
compilerOptions,
host,
importMode,
getModuleSpecifierPreferences({}, compilerOptions, importingFile),
getModuleSpecifierPreferences({}, host, compilerOptions, importingFile),
);
}

Expand All @@ -417,15 +420,19 @@ function computeModuleSpecifiers(
forAutoImport: boolean,
): ModuleSpecifierResult {
const info = getInfo(importingSourceFile.fileName, host);
const preferences = getModuleSpecifierPreferences(userPreferences, compilerOptions, importingSourceFile);
const preferences = getModuleSpecifierPreferences(userPreferences, host, compilerOptions, importingSourceFile);
const existingSpecifier = isFullSourceFile(importingSourceFile) && forEach(modulePaths, modulePath =>
forEach(
host.getFileIncludeReasons().get(toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)),
reason => {
if (reason.kind !== FileIncludeKind.Import || reason.file !== importingSourceFile.path) return undefined;
// If the candidate import mode doesn't match the mode we're generating for, don't consider it
// TODO: maybe useful to keep around as an alternative option for certain contexts where the mode is overridable
if (importingSourceFile.impliedNodeFormat && importingSourceFile.impliedNodeFormat !== getModeForResolutionAtIndex(importingSourceFile, reason.index, compilerOptions)) return undefined;
const existingMode = host.getModeForResolutionAtIndex(importingSourceFile, reason.index);
const targetMode = options.overrideImportMode ?? host.getDefaultResolutionModeForFile(importingSourceFile);
if (existingMode !== targetMode && existingMode !== undefined && targetMode !== undefined) {
return undefined;
}
const specifier = getModuleNameStringLiteralAt(importingSourceFile, reason.index).text;
// If the preference is for non relative and the module specifier is relative, ignore it
return preferences.relativePreference !== RelativePreference.NonRelative || !pathIsRelative(specifier) ?
Expand Down Expand Up @@ -1093,7 +1100,7 @@ function tryGetModuleNameAsNodeModule({ path, isRedirect }: ModulePath, { getCan

// Simplify the full file path to something that can be resolved by Node.

const preferences = getModuleSpecifierPreferences(userPreferences, options, importingSourceFile);
const preferences = getModuleSpecifierPreferences(userPreferences, host, options, importingSourceFile);
const allowedEndings = preferences.getAllowedEndingsInPreferredOrder();
let moduleSpecifier = path;
let isPackageRootPath = false;
Expand Down Expand Up @@ -1153,7 +1160,7 @@ function tryGetModuleNameAsNodeModule({ path, isRedirect }: ModulePath, { getCan
const cachedPackageJson = host.getPackageJsonInfoCache?.()?.getPackageJsonInfo(packageJsonPath);
if (isPackageJsonInfo(cachedPackageJson) || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) {
const packageJsonContent: Record<string, any> | undefined = cachedPackageJson?.contents.packageJsonContent || tryParseJson(host.readFile!(packageJsonPath)!);
const importMode = overrideMode || importingSourceFile.impliedNodeFormat;
const importMode = overrideMode || getDefaultResolutionModeForFile(importingSourceFile, host, options);
if (getResolvePackageJsonExports(options)) {
// The package name that we found in node_modules could be different from the package
// name in the package.json content via url/filepath dependency specifiers. We need to
Expand Down Expand Up @@ -1348,3 +1355,7 @@ function getRelativePathIfInSameVolume(path: string, directoryPath: string, getC
function isPathRelativeToParent(path: string): boolean {
return startsWith(path, "..");
}

function getDefaultResolutionModeForFile(file: Pick<SourceFile, "fileName" | "impliedNodeFormat" | "packageJsonScope">, host: Pick<ModuleSpecifierResolutionHost, "getDefaultResolutionModeForFile">, compilerOptions: CompilerOptions) {
return isFullSourceFile(file) ? host.getDefaultResolutionModeForFile(file) : getDefaultResolutionModeForFileWorker(file, compilerOptions);
}
Loading