From 22e50592bd415b675010b96dc328e1db15d21503 Mon Sep 17 00:00:00 2001 From: Sebastian Peralta Friedburg Date: Thu, 16 Apr 2026 12:06:42 +0200 Subject: [PATCH] fix: improve handling of node_modules path in package resolution --- src/compiler/moduleNameResolver.ts | 4 +++- src/server/moduleSpecifierCache.ts | 17 ++++++++++------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 5e2f1b6b793db..438068ef5fa6b 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -2444,7 +2444,9 @@ function readPackageJsonPeerDependencies(packageJsonInfo: PackageJsonInfo, state if (peerDependencies === undefined) return undefined; if (state.traceEnabled) trace(state.host, Diagnostics.package_json_has_a_peerDependencies_field); const packageDirectory = realPath(packageJsonInfo.packageDirectory, state.host, state.traceEnabled); - const nodeModules = packageDirectory.substring(0, packageDirectory.lastIndexOf("node_modules") + "node_modules".length) + directorySeparator; + const nodeModulesIndex = packageDirectory.lastIndexOf("node_modules"); + if (nodeModulesIndex === -1) return undefined; + const nodeModules = packageDirectory.substring(0, nodeModulesIndex + "node_modules".length) + directorySeparator; let result = ""; for (const key in peerDependencies) { if (hasProperty(peerDependencies, key)) { diff --git a/src/server/moduleSpecifierCache.ts b/src/server/moduleSpecifierCache.ts index 96d8eb3bf43bc..d75684a7b7457 100644 --- a/src/server/moduleSpecifierCache.ts +++ b/src/server/moduleSpecifierCache.ts @@ -39,13 +39,16 @@ export function createModuleSpecifierCache(host: ModuleSpecifierResolutionCacheH for (const p of modulePaths) { if (p.isInNodeModules) { // No trailing slash - const nodeModulesPath = p.path.substring(0, p.path.indexOf(nodeModulesPathPart) + nodeModulesPathPart.length - 1); - const key = host.toPath(nodeModulesPath); - if (!containedNodeModulesWatchers?.has(key)) { - (containedNodeModulesWatchers ||= new Map()).set( - key, - host.watchNodeModulesForPackageJsonChanges(nodeModulesPath), - ); + const nodeModulesIndex = p.path.indexOf(nodeModulesPathPart); + if (nodeModulesIndex !== -1) { + const nodeModulesPath = p.path.substring(0, nodeModulesIndex + nodeModulesPathPart.length - 1); + const key = host.toPath(nodeModulesPath); + if (!containedNodeModulesWatchers?.has(key)) { + (containedNodeModulesWatchers ||= new Map()).set( + key, + host.watchNodeModulesForPackageJsonChanges(nodeModulesPath), + ); + } } } }