1- import { dirname , isAbsolute , resolve } from 'path'
1+ import { dirname , isAbsolute , resolve , sep } from 'path'
22import { URL , fileURLToPath , pathToFileURL } from 'url'
33import vm , { Context } from 'vm'
44
@@ -13,16 +13,15 @@ export const isInESModuleScope = (): boolean => {
1313// @ts -expect-error: experimental
1414export const isVMModuleAvailable = ( ) : boolean => vm . Module !== undefined
1515
16- const FILE_URL_SCHEME = 'file:'
16+ const FILE_URL_PROTOCOL = 'file:'
1717
18- const isFileURL = ( value : string ) : boolean => value . startsWith ( FILE_URL_SCHEME )
18+ const isFileURL = ( value : string ) : boolean => value . startsWith ( FILE_URL_PROTOCOL )
1919
20- // correct url using `URL` API,
21- // because `path.join` transforms `file:///home` to `file:/home`
22- export const pathToFileURLString = ( value : string ) : string => {
23- const url = isFileURL ( value ) ? new URL ( value ) : pathToFileURL ( value )
24- return url . toString ( )
25- }
20+ export const ensureFileURL = ( value : string ) : string =>
21+ isFileURL ( value ) ? value : pathToFileURL ( value ) . toString ( )
22+
23+ export const ensurePath = ( value : string ) : string =>
24+ isFileURL ( value ) ? fileURLToPath ( value ) : value
2625
2726const internalFunctionNames : readonly string [ ] = [
2827 'getCallerDirname' ,
@@ -43,7 +42,25 @@ export const getCallerDirname = (): string => {
4342 Error . prepareStackTrace = __prepareStackTrace
4443 const caller = callSites [ 0 ]
4544 const callerFilename = caller . getFileName ( ) ?? process . argv [ 1 ]
46- return dirname ( isFileURL ( callerFilename ) ? fileURLToPath ( callerFilename ) : callerFilename )
45+ return dirname ( ensurePath ( callerFilename ) )
46+ }
47+
48+ const normalizeDirname = ( dirname : string ) : string => {
49+ const separater = isFileURL ( dirname ) ? '/' : sep
50+ return dirname . endsWith ( separater ) ? dirname : `${ dirname } ${ separater } `
51+ }
52+
53+ export const getModuleFilename = ( dirname : string , filename : string ) : string => {
54+ if ( isInESModuleScope ( ) ) {
55+ if ( isFileURL ( filename ) ) {
56+ return filename
57+ } else {
58+ const normalizedDirname = normalizeDirname ( dirname )
59+ return new URL ( filename , ensureFileURL ( normalizedDirname ) ) . toString ( )
60+ }
61+ } else {
62+ return resolve ( ensurePath ( dirname ) , ensurePath ( filename ) )
63+ }
4764}
4865
4966const forEachPropertyKey = (
@@ -106,6 +123,6 @@ export const resolveModuleSpecifier = (specifier: string, dirname: string): stri
106123 return specifier
107124 }
108125 return specifier . startsWith ( '.' ) || isAbsolute ( specifier )
109- ? resolve ( dirname , specifier )
126+ ? resolve ( ensurePath ( dirname ) , specifier )
110127 : specifier
111128}
0 commit comments