44 ObjectPrototypeHasOwnProperty,
55 PromisePrototypeThen,
66 PromiseResolve,
7+ StringPrototypeCharCodeAt,
78 StringPrototypeSlice,
89} = primordials ;
9- const { basename, extname , relative } = require ( 'path' ) ;
10+ const { basename, relative } = require ( 'path' ) ;
1011const { getOptionValue } = require ( 'internal/options' ) ;
1112const {
1213 extensionFormatMap,
@@ -41,15 +42,38 @@ function getDataProtocolModuleFormat(parsed) {
4142 return mimeToFormat ( mime ) ;
4243}
4344
45+ const DOT_CODE = 46 ;
46+ const SLASH_CODE = 47 ;
47+
48+ /**
49+ * Returns the file extension from a URL. Should give similar result to
50+ * `require('node:path').extname(require('node:url').fileURLToPath(url))`
51+ * when used with a `file:` URL.
52+ * @param {URL } url
53+ * @returns {string }
54+ */
55+ function extname ( url ) {
56+ const { pathname } = url ;
57+ for ( let i = pathname . length - 1 ; i > 0 ; i -- ) {
58+ switch ( StringPrototypeCharCodeAt ( pathname , i ) ) {
59+ case SLASH_CODE :
60+ return '' ;
61+
62+ case DOT_CODE :
63+ return StringPrototypeCharCodeAt ( pathname , i - 1 ) === SLASH_CODE ? '' : StringPrototypeSlice ( pathname , i ) ;
64+ }
65+ }
66+ return '' ;
67+ }
68+
4469/**
4570 * @param {URL } url
4671 * @param {{parentURL: string} } context
4772 * @param {boolean } ignoreErrors
4873 * @returns {string }
4974 */
5075function getFileProtocolModuleFormat ( url , context , ignoreErrors ) {
51- const filepath = fileURLToPath ( url ) ;
52- const ext = extname ( filepath ) ;
76+ const ext = extname ( url ) ;
5377 if ( ext === '.js' ) {
5478 return getPackageType ( url ) === 'module' ? 'module' : 'commonjs' ;
5579 }
@@ -59,6 +83,7 @@ function getFileProtocolModuleFormat(url, context, ignoreErrors) {
5983
6084 // Explicit undefined return indicates load hook should rerun format check
6185 if ( ignoreErrors ) { return undefined ; }
86+ const filepath = fileURLToPath ( url ) ;
6287 let suggestion = '' ;
6388 if ( getPackageType ( url ) === 'module' && ext === '' ) {
6489 const config = getPackageScopeConfig ( url ) ;
@@ -119,4 +144,5 @@ module.exports = {
119144 defaultGetFormat,
120145 defaultGetFormatWithoutErrors,
121146 extensionFormatMap,
147+ extname,
122148} ;
0 commit comments