11import { resolveAlias } from "pathe/utils" ;
2- import { resolvePathSync } from "mlly" ;
2+ import { fileURLToPath , resolvePathSync } from "mlly" ;
3+ import { join , dirname } from "pathe" ;
34import type { Context , JitiResolveOptions } from "./types" ;
5+ import { isDir } from "./utils" ;
46
57const JS_EXT_RE = / \. ( c | m ) ? j ( s x ? ) $ / ;
68const TS_EXT_RE = / \. ( c | m ) ? t ( s x ? ) $ / ;
@@ -10,7 +12,7 @@ export function jitiResolve(
1012 id : string ,
1113 options : JitiResolveOptions & { async ?: boolean ; paths ?: string [ ] } ,
1214) {
13- let resolved , err ;
15+ let resolved , lastError ;
1416
1517 if ( ctx . isNativeRe . test ( id ) ) {
1618 return id ;
@@ -21,6 +23,12 @@ export function jitiResolve(
2123 id = resolveAlias ( id , ctx . alias ) ;
2224 }
2325
26+ // Resolve parent URL
27+ let parentURL = options ?. parentURL || ctx . url ;
28+ if ( isDir ( parentURL ) ) {
29+ parentURL = join ( parentURL as string , "_index.js" ) ;
30+ }
31+
2432 // Try resolving with ESM compatible Node.js resolution in async context
2533 const conditionSets = (
2634 options ?. async
@@ -30,12 +38,12 @@ export function jitiResolve(
3038 for ( const conditions of conditionSets ) {
3139 try {
3240 resolved = resolvePathSync ( id , {
33- url : options ?. parentURL || ctx . url ,
41+ url : parentURL ,
3442 conditions,
3543 extensions : ctx . opts . extensions ,
3644 } ) ;
3745 } catch ( error ) {
38- err = error ;
46+ lastError = error ;
3947 }
4048 if ( resolved ) {
4149 return resolved ;
@@ -46,12 +54,12 @@ export function jitiResolve(
4654 try {
4755 return ctx . nativeRequire . resolve ( id , options ) ;
4856 } catch ( error ) {
49- err = error ;
57+ lastError = error ;
5058 }
5159 for ( const ext of ctx . additionalExts ) {
5260 resolved =
53- tryNativeRequireResolve ( ctx , id + ext , options ) ||
54- tryNativeRequireResolve ( ctx , id + "/index" + ext , options ) ;
61+ tryNativeRequireResolve ( ctx , id + ext , parentURL , options ) ||
62+ tryNativeRequireResolve ( ctx , id + "/index" + ext , parentURL , options ) ;
5563 if ( resolved ) {
5664 return resolved ;
5765 }
@@ -63,6 +71,7 @@ export function jitiResolve(
6371 resolved = tryNativeRequireResolve (
6472 ctx ,
6573 id . replace ( JS_EXT_RE , ".$1t$2" ) ,
74+ parentURL ,
6675 options ,
6776 ) ;
6877 if ( resolved ) {
@@ -76,16 +85,20 @@ export function jitiResolve(
7685 return undefined as unknown as string ;
7786 }
7887
79- throw err ;
88+ throw lastError ;
8089}
8190
8291export function tryNativeRequireResolve (
8392 ctx : Context ,
8493 id : string ,
94+ parentURL : URL | string ,
8595 options ?: { paths ?: string [ ] } ,
8696) {
8797 try {
88- return ctx . nativeRequire . resolve ( id , options ) ;
98+ return ctx . nativeRequire . resolve ( id , {
99+ ...options ,
100+ paths : [ dirname ( fileURLToPath ( parentURL ) ) , ...( options ?. paths || [ ] ) ] ,
101+ } ) ;
89102 } catch {
90103 // Ignore errors
91104 }
0 commit comments