4
4
ObjectPrototypeHasOwnProperty,
5
5
PromisePrototypeThen,
6
6
PromiseResolve,
7
+ StringPrototypeCharCodeAt,
7
8
StringPrototypeSlice,
8
9
} = primordials ;
9
- const { basename, extname , relative } = require ( 'path' ) ;
10
+ const { basename, relative } = require ( 'path' ) ;
10
11
const { getOptionValue } = require ( 'internal/options' ) ;
11
12
const {
12
13
extensionFormatMap,
@@ -44,15 +45,38 @@ function getDataProtocolModuleFormat(parsed) {
44
45
return mimeToFormat ( mime ) ;
45
46
}
46
47
48
+ const DOT_CODE = 46 ;
49
+ const SLASH_CODE = 47 ;
50
+
51
+ /**
52
+ * Returns the file extension from a URL. Should give similar result to
53
+ * `require('node:path').extname(require('node:url').fileURLToPath(url))`
54
+ * when used with a `file:` URL.
55
+ * @param {URL } url
56
+ * @returns {string }
57
+ */
58
+ function extname ( url ) {
59
+ const { pathname } = url ;
60
+ for ( let i = pathname . length - 1 ; i > 0 ; i -- ) {
61
+ switch ( StringPrototypeCharCodeAt ( pathname , i ) ) {
62
+ case SLASH_CODE :
63
+ return '' ;
64
+
65
+ case DOT_CODE :
66
+ return StringPrototypeCharCodeAt ( pathname , i - 1 ) === SLASH_CODE ? '' : StringPrototypeSlice ( pathname , i ) ;
67
+ }
68
+ }
69
+ return '' ;
70
+ }
71
+
47
72
/**
48
73
* @param {URL } url
49
74
* @param {{parentURL: string} } context
50
75
* @param {boolean } ignoreErrors
51
76
* @returns {string }
52
77
*/
53
78
function getFileProtocolModuleFormat ( url , context , ignoreErrors ) {
54
- const filepath = fileURLToPath ( url ) ;
55
- const ext = extname ( filepath ) ;
79
+ const ext = extname ( url ) ;
56
80
if ( ext === '.js' ) {
57
81
return getPackageType ( url ) === 'module' ? 'module' : 'commonjs' ;
58
82
}
@@ -63,6 +87,7 @@ function getFileProtocolModuleFormat(url, context, ignoreErrors) {
63
87
if ( experimentalSpecifierResolution !== 'node' ) {
64
88
// Explicit undefined return indicates load hook should rerun format check
65
89
if ( ignoreErrors ) return undefined ;
90
+ const filepath = fileURLToPath ( url ) ;
66
91
let suggestion = '' ;
67
92
if ( getPackageType ( url ) === 'module' && ext === '' ) {
68
93
const config = getPackageScopeConfig ( url ) ;
@@ -128,4 +153,5 @@ module.exports = {
128
153
defaultGetFormat,
129
154
defaultGetFormatWithoutErrors,
130
155
extensionFormatMap,
156
+ extname,
131
157
} ;
0 commit comments