|
|
|
|
|
|
|
|
|
import {fileURLToPath} from 'node:url' |
|
import {getPackageType} from './package-json-reader.js' |
|
import {codes} from './errors.js' |
|
|
|
const {ERR_UNKNOWN_FILE_EXTENSION} = codes |
|
|
|
const hasOwnProperty = {}.hasOwnProperty |
|
|
|
|
|
const extensionFormatMap = { |
|
|
|
__proto__: null, |
|
'.cjs': 'commonjs', |
|
'.js': 'module', |
|
'.json': 'json', |
|
'.mjs': 'module' |
|
} |
|
|
|
|
|
|
|
|
|
|
|
function mimeToFormat(mime) { |
|
if ( |
|
mime && |
|
/\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime) |
|
) |
|
return 'module' |
|
if (mime === 'application/json') return 'json' |
|
return null |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const protocolHandlers = { |
|
|
|
__proto__: null, |
|
'data:': getDataProtocolModuleFormat, |
|
'file:': getFileProtocolModuleFormat, |
|
'http:': getHttpProtocolModuleFormat, |
|
'https:': getHttpProtocolModuleFormat, |
|
'node:'() { |
|
return 'builtin' |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
function getDataProtocolModuleFormat(parsed) { |
|
const {1: mime} = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec( |
|
parsed.pathname |
|
) || [null, null, null] |
|
return mimeToFormat(mime) |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function extname(url) { |
|
const pathname = url.pathname |
|
let index = pathname.length |
|
|
|
while (index--) { |
|
const code = pathname.codePointAt(index) |
|
|
|
if (code === 47 ) { |
|
return '' |
|
} |
|
|
|
if (code === 46 ) { |
|
return pathname.codePointAt(index - 1) === 47 |
|
? '' |
|
: pathname.slice(index) |
|
} |
|
} |
|
|
|
return '' |
|
} |
|
|
|
|
|
|
|
|
|
function getFileProtocolModuleFormat(url, _context, ignoreErrors) { |
|
const value = extname(url) |
|
|
|
if (value === '.js') { |
|
const packageType = getPackageType(url) |
|
|
|
if (packageType !== 'none') { |
|
return packageType |
|
} |
|
|
|
return 'commonjs' |
|
} |
|
|
|
if (value === '') { |
|
const packageType = getPackageType(url) |
|
|
|
|
|
if (packageType === 'none' || packageType === 'commonjs') { |
|
return 'commonjs' |
|
} |
|
|
|
|
|
|
|
return 'module' |
|
} |
|
|
|
const format = extensionFormatMap[value] |
|
if (format) return format |
|
|
|
|
|
if (ignoreErrors) { |
|
return undefined |
|
} |
|
|
|
const filepath = fileURLToPath(url) |
|
throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath) |
|
} |
|
|
|
function getHttpProtocolModuleFormat() { |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
export function defaultGetFormatWithoutErrors(url, context) { |
|
const protocol = url.protocol |
|
|
|
if (!hasOwnProperty.call(protocolHandlers, protocol)) { |
|
return null |
|
} |
|
|
|
return protocolHandlers[protocol](url, context, true) || null |
|
} |
|
|