@@ -30,7 +30,7 @@ const {
30
30
Stats,
31
31
} = require ( 'fs' ) ;
32
32
const { getOptionValue } = require ( 'internal/options' ) ;
33
- const { sep, relative } = require ( 'path' ) ;
33
+ const { sep, relative, resolve } = require ( 'path' ) ;
34
34
const preserveSymlinks = getOptionValue ( '--preserve-symlinks' ) ;
35
35
const preserveSymlinksMain = getOptionValue ( '--preserve-symlinks-main' ) ;
36
36
const typeFlag = getOptionValue ( '--input-type' ) ;
@@ -160,16 +160,18 @@ function getPackageScopeConfig(resolved) {
160
160
return packageConfig ;
161
161
}
162
162
163
- /*
163
+ /**
164
164
* Legacy CommonJS main resolution:
165
165
* 1. let M = pkg_url + (json main field)
166
166
* 2. TRY(M, M.js, M.json, M.node)
167
167
* 3. TRY(M/index.js, M/index.json, M/index.node)
168
168
* 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
169
169
* 5. NOT_FOUND
170
+ * @param {string | URL } url
171
+ * @returns {boolean }
170
172
*/
171
173
function fileExists ( url ) {
172
- return tryStatSync ( fileURLToPath ( url ) ) . isFile ( ) ;
174
+ return tryStatSync ( url ) . isFile ( ) ;
173
175
}
174
176
175
177
function legacyMainResolve ( packageJSONUrl , packageConfig , base ) {
@@ -236,7 +238,19 @@ function resolveExtensions(search) {
236
238
return undefined ;
237
239
}
238
240
239
- function resolveIndex ( search ) {
241
+ function resolveDirectoryEntry ( search ) {
242
+ const dirPath = fileURLToPath ( search ) ;
243
+ const pkgJsonPath = resolve ( dirPath , 'package.json' ) ;
244
+ if ( fileExists ( pkgJsonPath ) ) {
245
+ const pkgJson = packageJsonReader . read ( pkgJsonPath ) ;
246
+ if ( pkgJson . containsKeys ) {
247
+ const { main } = JSONParse ( pkgJson . string ) ;
248
+ if ( main != null ) {
249
+ const mainUrl = pathToFileURL ( resolve ( dirPath , main ) ) ;
250
+ return resolveExtensionsWithTryExactName ( mainUrl ) ;
251
+ }
252
+ }
253
+ }
240
254
return resolveExtensions ( new URL ( 'index' , search ) ) ;
241
255
}
242
256
@@ -252,10 +266,10 @@ function finalizeResolution(resolved, base) {
252
266
let file = resolveExtensionsWithTryExactName ( resolved ) ;
253
267
if ( file !== undefined ) return file ;
254
268
if ( ! StringPrototypeEndsWith ( path , '/' ) ) {
255
- file = resolveIndex ( new URL ( `${ resolved } /` ) ) ;
269
+ file = resolveDirectoryEntry ( new URL ( `${ resolved } /` ) ) ;
256
270
if ( file !== undefined ) return file ;
257
271
} else {
258
- return resolveIndex ( resolved ) || resolved ;
272
+ return resolveDirectoryEntry ( resolved ) || resolved ;
259
273
}
260
274
throw new ERR_MODULE_NOT_FOUND (
261
275
resolved . pathname , fileURLToPath ( base ) , 'module' ) ;
0 commit comments