1import { URL } from 'url'; 2import path from 'path'; 3import process from 'process'; 4import { builtinModules } from 'module'; 5 6const JS_EXTENSIONS = new Set(['.js', '.mjs']); 7 8const baseURL = new URL('file://'); 9baseURL.pathname = process.cwd() + '/'; 10 11export function resolve(specifier, { parentURL = baseURL }, next) { 12 if (builtinModules.includes(specifier)) { 13 return { 14 shortCircuit: true, 15 url: 'node:' + specifier 16 }; 17 } 18 if (/^\.{1,2}[/]/.test(specifier) !== true && !specifier.startsWith('file:')) { 19 // For node_modules support: 20 // return next(specifier); 21 throw new Error( 22 `imports must be URLs or begin with './', or '../'; '${specifier}' does not`); 23 } 24 const resolved = new URL(specifier, parentURL); 25 return { 26 shortCircuit: true, 27 url: resolved.href 28 }; 29} 30 31export function getFormat(url, context, defaultGetFormat) { 32 if (url.startsWith('node:') && builtinModules.includes(url.slice(5))) { 33 return { 34 format: 'builtin' 35 }; 36 } 37 const { pathname } = new URL(url); 38 const ext = path.extname(pathname); 39 if (!JS_EXTENSIONS.has(ext)) { 40 throw new Error( 41 `Cannot load file with non-JavaScript file extension ${ext}.`); 42 } 43 return { 44 format: 'module' 45 }; 46} 47