2024-01-01 19:58:21 +00:00
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
2021-10-10 21:26:22 +00:00
2023-12-07 00:03:18 +00:00
use deno_ast ::MediaType ;
2023-03-03 22:27:05 +00:00
use deno_core ::anyhow ::anyhow ;
2024-01-27 17:10:36 +00:00
use deno_core ::anyhow ::Context ;
2023-01-24 13:23:19 +00:00
use deno_core ::error ::AnyError ;
2023-02-22 19:15:25 +00:00
use deno_core ::futures ::future ;
use deno_core ::futures ::future ::LocalBoxFuture ;
use deno_core ::futures ::FutureExt ;
2023-12-07 00:03:18 +00:00
use deno_core ::parking_lot ::Mutex ;
2024-01-27 17:10:36 +00:00
use deno_core ::ModuleCodeString ;
2021-10-10 21:26:22 +00:00
use deno_core ::ModuleSpecifier ;
2023-09-07 13:09:16 +00:00
use deno_graph ::source ::NpmPackageReqResolution ;
2023-02-22 19:15:25 +00:00
use deno_graph ::source ::NpmResolver ;
2023-10-24 13:37:02 +00:00
use deno_graph ::source ::ResolutionMode ;
2023-10-20 04:02:08 +00:00
use deno_graph ::source ::ResolveError ;
2021-10-10 21:26:22 +00:00
use deno_graph ::source ::Resolver ;
2023-02-22 19:15:25 +00:00
use deno_graph ::source ::UnknownBuiltInNodeModuleError ;
2022-11-02 14:47:02 +00:00
use deno_graph ::source ::DEFAULT_JSX_IMPORT_SOURCE_MODULE ;
2024-01-27 17:10:36 +00:00
use deno_runtime ::deno_fs ;
2023-10-25 18:39:00 +00:00
use deno_runtime ::deno_fs ::FileSystem ;
2023-02-22 19:15:25 +00:00
use deno_runtime ::deno_node ::is_builtin_node_module ;
2023-10-27 01:22:15 +00:00
use deno_runtime ::deno_node ::parse_npm_pkg_name ;
2024-03-06 00:23:51 +00:00
use deno_runtime ::deno_node ::NodePermissions ;
2023-10-25 18:39:00 +00:00
use deno_runtime ::deno_node ::NodeResolution ;
use deno_runtime ::deno_node ::NodeResolutionMode ;
use deno_runtime ::deno_node ::NodeResolver ;
2023-10-27 01:22:15 +00:00
use deno_runtime ::deno_node ::NpmResolver as DenoNodeNpmResolver ;
2024-03-06 00:23:51 +00:00
use deno_runtime ::deno_node ::PackageJson ;
2024-04-17 14:19:55 +00:00
use deno_runtime ::fs_util ::specifier_to_file_path ;
2023-10-25 18:39:00 +00:00
use deno_runtime ::permissions ::PermissionsContainer ;
use deno_semver ::npm ::NpmPackageReqReference ;
2023-08-21 09:53:52 +00:00
use deno_semver ::package ::PackageReq ;
2021-10-10 21:26:22 +00:00
use import_map ::ImportMap ;
2023-12-07 00:03:18 +00:00
use std ::borrow ::Cow ;
use std ::collections ::HashMap ;
2024-01-27 17:10:36 +00:00
use std ::collections ::HashSet ;
2023-12-07 00:03:18 +00:00
use std ::path ::Path ;
2023-08-17 16:14:22 +00:00
use std ::path ::PathBuf ;
2024-04-01 13:10:04 +00:00
use std ::rc ::Rc ;
2021-11-09 01:26:39 +00:00
use std ::sync ::Arc ;
2021-10-10 21:26:22 +00:00
2023-03-03 22:27:05 +00:00
use crate ::args ::package_json ::PackageJsonDeps ;
2022-11-25 22:00:28 +00:00
use crate ::args ::JsxImportSourceConfig ;
2023-05-11 00:06:59 +00:00
use crate ::args ::PackageJsonDepsProvider ;
2024-03-07 13:59:57 +00:00
use crate ::args ::DENO_DISABLE_PEDANTIC_NODE_WARNINGS ;
2024-02-13 16:22:30 +00:00
use crate ::colors ;
2024-01-27 17:10:36 +00:00
use crate ::node ::CliNodeCodeTranslator ;
2023-10-27 01:22:15 +00:00
use crate ::npm ::ByonmCliNpmResolver ;
2023-09-30 16:06:38 +00:00
use crate ::npm ::CliNpmResolver ;
2023-10-03 23:05:06 +00:00
use crate ::npm ::InnerCliNpmResolverRef ;
2023-04-11 22:10:51 +00:00
use crate ::util ::sync ::AtomicFlag ;
2022-08-24 17:36:05 +00:00
2024-02-13 16:22:30 +00:00
pub fn format_range_with_colors ( range : & deno_graph ::Range ) -> String {
format! (
" {}:{}:{} " ,
colors ::cyan ( range . specifier . as_str ( ) ) ,
colors ::yellow ( & ( range . start . line + 1 ) . to_string ( ) ) ,
colors ::yellow ( & ( range . start . character + 1 ) . to_string ( ) )
)
}
2024-01-27 17:10:36 +00:00
pub struct ModuleCodeStringSource {
pub code : ModuleCodeString ,
pub found_url : ModuleSpecifier ,
pub media_type : MediaType ,
}
2024-03-06 00:23:51 +00:00
#[ derive(Debug) ]
2024-01-27 17:10:36 +00:00
pub struct CliNodeResolver {
2024-03-06 00:23:51 +00:00
// not used in the LSP
cjs_resolutions : Option < Arc < CjsResolutionStore > > ,
fs : Arc < dyn deno_fs ::FileSystem > ,
2024-01-27 17:10:36 +00:00
node_resolver : Arc < NodeResolver > ,
2024-03-06 00:23:51 +00:00
// todo(dsherret): remove this pub(crate)
2024-01-27 17:10:36 +00:00
pub ( crate ) npm_resolver : Arc < dyn CliNpmResolver > ,
}
impl CliNodeResolver {
pub fn new (
2024-03-06 00:23:51 +00:00
cjs_resolutions : Option < Arc < CjsResolutionStore > > ,
fs : Arc < dyn deno_fs ::FileSystem > ,
2024-01-27 17:10:36 +00:00
node_resolver : Arc < NodeResolver > ,
npm_resolver : Arc < dyn CliNpmResolver > ,
) -> Self {
Self {
cjs_resolutions ,
2024-03-06 00:23:51 +00:00
fs ,
2024-01-27 17:10:36 +00:00
node_resolver ,
npm_resolver ,
}
}
pub fn in_npm_package ( & self , referrer : & ModuleSpecifier ) -> bool {
self . npm_resolver . in_npm_package ( referrer )
}
2024-03-06 00:23:51 +00:00
pub fn get_closest_package_json (
& self ,
referrer : & ModuleSpecifier ,
permissions : & dyn NodePermissions ,
2024-04-01 13:10:04 +00:00
) -> Result < Option < Rc < PackageJson > > , AnyError > {
2024-03-06 00:23:51 +00:00
self
. node_resolver
. get_closest_package_json ( referrer , permissions )
}
2024-01-27 17:10:36 +00:00
pub fn resolve_if_in_npm_package (
& self ,
specifier : & str ,
referrer : & ModuleSpecifier ,
2024-03-06 00:23:51 +00:00
mode : NodeResolutionMode ,
2024-01-27 17:10:36 +00:00
permissions : & PermissionsContainer ,
2024-03-06 00:23:51 +00:00
) -> Option < Result < Option < NodeResolution > , AnyError > > {
2024-01-27 17:10:36 +00:00
if self . in_npm_package ( referrer ) {
// we're in an npm package, so use node resolution
2024-03-06 00:23:51 +00:00
Some ( self . resolve ( specifier , referrer , mode , permissions ) )
2024-01-27 17:10:36 +00:00
} else {
None
}
}
2024-03-06 00:23:51 +00:00
pub fn resolve (
& self ,
specifier : & str ,
referrer : & ModuleSpecifier ,
mode : NodeResolutionMode ,
permissions : & PermissionsContainer ,
) -> Result < Option < NodeResolution > , AnyError > {
self . handle_node_resolve_result ( self . node_resolver . resolve (
specifier ,
referrer ,
mode ,
permissions ,
) )
}
2024-01-27 17:10:36 +00:00
pub fn resolve_req_reference (
& self ,
req_ref : & NpmPackageReqReference ,
permissions : & PermissionsContainer ,
referrer : & ModuleSpecifier ,
2024-03-06 00:23:51 +00:00
mode : NodeResolutionMode ,
) -> Result < NodeResolution , AnyError > {
2024-01-27 17:10:36 +00:00
let package_folder = self
. npm_resolver
. resolve_pkg_folder_from_deno_module_req ( req_ref . req ( ) , referrer ) ? ;
2024-03-06 00:23:51 +00:00
let maybe_resolution = self . resolve_package_sub_path_from_deno_module (
& package_folder ,
req_ref . sub_path ( ) ,
referrer ,
mode ,
permissions ,
) ? ;
match maybe_resolution {
Some ( resolution ) = > Ok ( resolution ) ,
None = > {
if self . npm_resolver . as_byonm ( ) . is_some ( ) {
let package_json_path = package_folder . join ( " package.json " ) ;
if ! self . fs . exists_sync ( & package_json_path ) {
return Err ( anyhow! (
" Could not find '{}'. Deno expects the node_modules/ directory to be up to date. Did you forget to run `npm install`? " ,
package_json_path . display ( )
) ) ;
}
}
Err ( anyhow! (
" Failed resolving package subpath for '{}' in '{}'. " ,
req_ref ,
package_folder . display ( )
) )
}
}
2024-01-27 17:10:36 +00:00
}
2024-03-06 00:23:51 +00:00
pub fn resolve_package_sub_path_from_deno_module (
2024-01-27 17:10:36 +00:00
& self ,
package_folder : & Path ,
sub_path : Option < & str > ,
referrer : & ModuleSpecifier ,
2024-03-06 00:23:51 +00:00
mode : NodeResolutionMode ,
2024-01-27 17:10:36 +00:00
permissions : & PermissionsContainer ,
2024-03-06 00:23:51 +00:00
) -> Result < Option < NodeResolution > , AnyError > {
2024-01-27 17:10:36 +00:00
self . handle_node_resolve_result (
self . node_resolver . resolve_package_subpath_from_deno_module (
package_folder ,
sub_path ,
referrer ,
2024-03-06 00:23:51 +00:00
mode ,
2024-01-27 17:10:36 +00:00
permissions ,
) ,
)
}
2024-03-06 00:23:51 +00:00
pub fn handle_if_in_node_modules (
& self ,
specifier : ModuleSpecifier ,
) -> Result < ModuleSpecifier , AnyError > {
// skip canonicalizing if we definitely know it's unnecessary
if specifier . scheme ( ) = = " file "
& & specifier . path ( ) . contains ( " /node_modules/ " )
{
// Specifiers in the node_modules directory are canonicalized
// so canoncalize then check if it's in the node_modules directory.
// If so, check if we need to store this specifier as being a CJS
// resolution.
let specifier =
crate ::node ::resolve_specifier_into_node_modules ( & specifier ) ;
if self . in_npm_package ( & specifier ) {
if let Some ( cjs_resolutions ) = & self . cjs_resolutions {
let resolution =
self . node_resolver . url_to_node_resolution ( specifier ) ? ;
if let NodeResolution ::CommonJs ( specifier ) = & resolution {
cjs_resolutions . insert ( specifier . clone ( ) ) ;
}
return Ok ( resolution . into_url ( ) ) ;
} else {
return Ok ( specifier ) ;
}
}
}
Ok ( specifier )
}
2024-04-15 21:50:52 +00:00
pub fn url_to_node_resolution (
& self ,
specifier : ModuleSpecifier ,
) -> Result < NodeResolution , AnyError > {
self . node_resolver . url_to_node_resolution ( specifier )
}
2024-01-27 17:10:36 +00:00
fn handle_node_resolve_result (
& self ,
result : Result < Option < NodeResolution > , AnyError > ,
2024-03-06 00:23:51 +00:00
) -> Result < Option < NodeResolution > , AnyError > {
match result ? {
Some ( response ) = > {
if let NodeResolution ::CommonJs ( specifier ) = & response {
// remember that this was a common js resolution
if let Some ( cjs_resolutions ) = & self . cjs_resolutions {
cjs_resolutions . insert ( specifier . clone ( ) ) ;
}
}
Ok ( Some ( response ) )
}
None = > Ok ( None ) ,
2024-01-27 17:10:36 +00:00
}
}
}
pub struct NpmModuleLoader {
cjs_resolutions : Arc < CjsResolutionStore > ,
node_code_translator : Arc < CliNodeCodeTranslator > ,
fs : Arc < dyn deno_fs ::FileSystem > ,
node_resolver : Arc < CliNodeResolver > ,
}
impl NpmModuleLoader {
pub fn new (
cjs_resolutions : Arc < CjsResolutionStore > ,
node_code_translator : Arc < CliNodeCodeTranslator > ,
fs : Arc < dyn deno_fs ::FileSystem > ,
node_resolver : Arc < CliNodeResolver > ,
) -> Self {
Self {
cjs_resolutions ,
node_code_translator ,
fs ,
node_resolver ,
}
}
pub fn maybe_prepare_load (
& self ,
specifier : & ModuleSpecifier ,
) -> Option < Result < ( ) , AnyError > > {
if self . node_resolver . in_npm_package ( specifier ) {
// nothing to prepare
Some ( Ok ( ( ) ) )
} else {
None
}
}
pub fn load_sync_if_in_npm_package (
& self ,
specifier : & ModuleSpecifier ,
maybe_referrer : Option < & ModuleSpecifier > ,
permissions : & PermissionsContainer ,
) -> Option < Result < ModuleCodeStringSource , AnyError > > {
if self . node_resolver . in_npm_package ( specifier ) {
Some ( self . load_sync ( specifier , maybe_referrer , permissions ) )
} else {
None
}
}
fn load_sync (
& self ,
specifier : & ModuleSpecifier ,
maybe_referrer : Option < & ModuleSpecifier > ,
permissions : & PermissionsContainer ,
) -> Result < ModuleCodeStringSource , AnyError > {
let file_path = specifier . to_file_path ( ) . unwrap ( ) ;
let code = self
. fs
2024-04-20 00:12:03 +00:00
. read_text_file_sync ( & file_path , None )
2024-01-27 17:10:36 +00:00
. map_err ( AnyError ::from )
. with_context ( | | {
if file_path . is_dir ( ) {
// directory imports are not allowed when importing from an
// ES module, so provide the user with a helpful error message
let dir_path = file_path ;
let mut msg = " Directory import " . to_string ( ) ;
msg . push_str ( & dir_path . to_string_lossy ( ) ) ;
if let Some ( referrer ) = & maybe_referrer {
msg . push_str ( " is not supported resolving import from " ) ;
msg . push_str ( referrer . as_str ( ) ) ;
let entrypoint_name = [ " index.mjs " , " index.js " , " index.cjs " ]
. iter ( )
. find ( | e | dir_path . join ( e ) . is_file ( ) ) ;
if let Some ( entrypoint_name ) = entrypoint_name {
msg . push_str ( " \n Did you mean to import " ) ;
msg . push_str ( entrypoint_name ) ;
msg . push_str ( " within the directory? " ) ;
}
}
msg
} else {
let mut msg = " Unable to load " . to_string ( ) ;
msg . push_str ( & file_path . to_string_lossy ( ) ) ;
if let Some ( referrer ) = & maybe_referrer {
msg . push_str ( " imported from " ) ;
msg . push_str ( referrer . as_str ( ) ) ;
}
msg
}
} ) ? ;
let code = if self . cjs_resolutions . contains ( specifier ) {
// translate cjs to esm if it's cjs and inject node globals
self . node_code_translator . translate_cjs_to_esm (
specifier ,
2024-03-21 18:35:51 +00:00
Some ( code ) ,
2024-01-27 17:10:36 +00:00
permissions ,
) ?
} else {
// esm and json code is untouched
code
} ;
Ok ( ModuleCodeStringSource {
code : code . into ( ) ,
found_url : specifier . clone ( ) ,
media_type : MediaType ::from_specifier ( specifier ) ,
} )
}
}
/// Keeps track of what module specifiers were resolved as CJS.
#[ derive(Debug, Default) ]
pub struct CjsResolutionStore ( Mutex < HashSet < ModuleSpecifier > > ) ;
impl CjsResolutionStore {
pub fn contains ( & self , specifier : & ModuleSpecifier ) -> bool {
self . 0. lock ( ) . contains ( specifier )
}
pub fn insert ( & self , specifier : ModuleSpecifier ) {
self . 0. lock ( ) . insert ( specifier ) ;
}
}
2023-05-11 00:06:59 +00:00
/// Result of checking if a specifier is mapped via
/// an import map or package.json.
pub enum MappedResolution {
None ,
PackageJson ( ModuleSpecifier ) ,
ImportMap ( ModuleSpecifier ) ,
}
impl MappedResolution {
pub fn into_specifier ( self ) -> Option < ModuleSpecifier > {
match self {
MappedResolution ::None = > Option ::None ,
MappedResolution ::PackageJson ( specifier ) = > Some ( specifier ) ,
MappedResolution ::ImportMap ( specifier ) = > Some ( specifier ) ,
}
}
}
/// Resolver for specifiers that could be mapped via an
/// import map or package.json.
#[ derive(Debug) ]
pub struct MappedSpecifierResolver {
maybe_import_map : Option < Arc < ImportMap > > ,
package_json_deps_provider : Arc < PackageJsonDepsProvider > ,
}
impl MappedSpecifierResolver {
pub fn new (
maybe_import_map : Option < Arc < ImportMap > > ,
package_json_deps_provider : Arc < PackageJsonDepsProvider > ,
) -> Self {
Self {
maybe_import_map ,
package_json_deps_provider ,
}
}
pub fn resolve (
& self ,
specifier : & str ,
referrer : & ModuleSpecifier ,
) -> Result < MappedResolution , AnyError > {
// attempt to resolve with the import map first
let maybe_import_map_err = match self
. maybe_import_map
. as_ref ( )
. map ( | import_map | import_map . resolve ( specifier , referrer ) )
{
Some ( Ok ( value ) ) = > return Ok ( MappedResolution ::ImportMap ( value ) ) ,
Some ( Err ( err ) ) = > Some ( err ) ,
None = > None ,
} ;
// then with package.json
if let Some ( deps ) = self . package_json_deps_provider . deps ( ) {
if let Some ( specifier ) = resolve_package_json_dep ( specifier , deps ) ? {
return Ok ( MappedResolution ::PackageJson ( specifier ) ) ;
}
}
// otherwise, surface the import map error or try resolving when has no import map
if let Some ( err ) = maybe_import_map_err {
Err ( err . into ( ) )
} else {
Ok ( MappedResolution ::None )
}
}
}
2022-11-02 14:47:02 +00:00
/// A resolver that takes care of resolution, taking into account loaded
/// import map, JSX settings.
2023-04-14 20:22:33 +00:00
#[ derive(Debug) ]
2023-02-15 16:30:54 +00:00
pub struct CliGraphResolver {
2023-12-07 20:59:13 +00:00
sloppy_imports_resolver : Option < SloppyImportsResolver > ,
2023-05-11 00:06:59 +00:00
mapped_specifier_resolver : MappedSpecifierResolver ,
2022-11-02 14:47:02 +00:00
maybe_default_jsx_import_source : Option < String > ,
maybe_jsx_import_source_module : Option < String > ,
2023-08-17 16:14:22 +00:00
maybe_vendor_specifier : Option < ModuleSpecifier > ,
2024-03-06 00:23:51 +00:00
node_resolver : Option < Arc < CliNodeResolver > > ,
2023-09-30 16:06:38 +00:00
npm_resolver : Option < Arc < dyn CliNpmResolver > > ,
2023-04-11 22:10:51 +00:00
found_package_json_dep_flag : Arc < AtomicFlag > ,
2023-10-20 04:02:08 +00:00
bare_node_builtins_enabled : bool ,
2023-02-22 19:15:25 +00:00
}
2023-08-17 16:14:22 +00:00
pub struct CliGraphResolverOptions < ' a > {
2023-12-07 20:59:13 +00:00
pub sloppy_imports_resolver : Option < SloppyImportsResolver > ,
2024-03-06 00:23:51 +00:00
pub node_resolver : Option < Arc < CliNodeResolver > > ,
2023-10-25 18:39:00 +00:00
pub npm_resolver : Option < Arc < dyn CliNpmResolver > > ,
pub package_json_deps_provider : Arc < PackageJsonDepsProvider > ,
2023-08-17 16:14:22 +00:00
pub maybe_jsx_import_source_config : Option < JsxImportSourceConfig > ,
pub maybe_import_map : Option < Arc < ImportMap > > ,
pub maybe_vendor_dir : Option < & ' a PathBuf > ,
2023-10-20 04:02:08 +00:00
pub bare_node_builtins_enabled : bool ,
2023-08-17 16:14:22 +00:00
}
2023-02-15 16:30:54 +00:00
impl CliGraphResolver {
2023-10-25 18:39:00 +00:00
pub fn new ( options : CliGraphResolverOptions ) -> Self {
let is_byonm = options
. npm_resolver
. as_ref ( )
. map ( | n | n . as_byonm ( ) . is_some ( ) )
. unwrap_or ( false ) ;
2023-02-15 16:30:54 +00:00
Self {
2023-12-07 00:03:18 +00:00
sloppy_imports_resolver : options . sloppy_imports_resolver ,
2023-10-03 23:05:06 +00:00
mapped_specifier_resolver : MappedSpecifierResolver ::new (
options . maybe_import_map ,
2023-10-25 18:39:00 +00:00
if is_byonm {
// don't resolve from the root package.json deps for byonm
Arc ::new ( PackageJsonDepsProvider ::new ( None ) )
} else {
options . package_json_deps_provider
} ,
2023-10-03 23:05:06 +00:00
) ,
2023-08-17 16:14:22 +00:00
maybe_default_jsx_import_source : options
. maybe_jsx_import_source_config
2023-02-15 16:30:54 +00:00
. as_ref ( )
. and_then ( | c | c . default_specifier . clone ( ) ) ,
2023-08-17 16:14:22 +00:00
maybe_jsx_import_source_module : options
. maybe_jsx_import_source_config
2023-02-15 16:30:54 +00:00
. map ( | c | c . module ) ,
2023-08-17 16:14:22 +00:00
maybe_vendor_specifier : options
. maybe_vendor_dir
. and_then ( | v | ModuleSpecifier ::from_directory_path ( v ) . ok ( ) ) ,
2023-10-25 18:39:00 +00:00
node_resolver : options . node_resolver ,
npm_resolver : options . npm_resolver ,
2023-04-11 22:10:51 +00:00
found_package_json_dep_flag : Default ::default ( ) ,
2023-10-20 04:02:08 +00:00
bare_node_builtins_enabled : options . bare_node_builtins_enabled ,
2022-01-31 22:33:57 +00:00
}
2021-10-10 21:26:22 +00:00
}
2021-11-09 01:26:39 +00:00
2022-11-02 14:47:02 +00:00
pub fn as_graph_resolver ( & self ) -> & dyn Resolver {
2021-11-09 01:26:39 +00:00
self
}
2023-02-22 19:15:25 +00:00
pub fn as_graph_npm_resolver ( & self ) -> & dyn NpmResolver {
self
}
2023-04-11 22:10:51 +00:00
2023-09-30 16:06:38 +00:00
pub fn found_package_json_dep ( & self ) -> bool {
self . found_package_json_dep_flag . is_raised ( )
2023-04-11 22:10:51 +00:00
}
2023-10-27 01:22:15 +00:00
fn check_surface_byonm_node_error (
& self ,
specifier : & str ,
referrer : & ModuleSpecifier ,
mode : NodeResolutionMode ,
original_err : AnyError ,
resolver : & ByonmCliNpmResolver ,
) -> Result < ( ) , AnyError > {
if let Ok ( ( pkg_name , _ , _ ) ) = parse_npm_pkg_name ( specifier , referrer ) {
match resolver
. resolve_package_folder_from_package ( & pkg_name , referrer , mode )
{
Ok ( _ ) = > {
return Err ( original_err ) ;
}
Err ( _ ) = > {
if resolver
. find_ancestor_package_json_with_dep ( & pkg_name , referrer )
. is_some ( )
{
return Err ( anyhow! (
concat! (
" Could not resolve \" {} \" , but found it in a package.json. " ,
" Deno expects the node_modules/ directory to be up to date. " ,
" Did you forget to run `npm install`? "
) ,
specifier
) ) ;
}
}
}
}
Ok ( ( ) )
}
2021-11-09 01:26:39 +00:00
}
2023-02-15 16:30:54 +00:00
impl Resolver for CliGraphResolver {
2022-08-24 17:36:05 +00:00
fn default_jsx_import_source ( & self ) -> Option < String > {
2022-11-02 14:47:02 +00:00
self . maybe_default_jsx_import_source . clone ( )
2022-08-24 17:36:05 +00:00
}
2021-11-09 01:26:39 +00:00
fn jsx_import_source_module ( & self ) -> & str {
2022-11-02 14:47:02 +00:00
self
. maybe_jsx_import_source_module
. as_deref ( )
. unwrap_or ( DEFAULT_JSX_IMPORT_SOURCE_MODULE )
2021-11-09 01:26:39 +00:00
}
fn resolve (
& self ,
specifier : & str ,
2023-12-07 00:03:18 +00:00
referrer_range : & deno_graph ::Range ,
2023-10-25 18:39:00 +00:00
mode : ResolutionMode ,
2023-10-20 04:02:08 +00:00
) -> Result < ModuleSpecifier , ResolveError > {
2023-10-25 18:39:00 +00:00
fn to_node_mode ( mode : ResolutionMode ) -> NodeResolutionMode {
match mode {
ResolutionMode ::Execution = > NodeResolutionMode ::Execution ,
ResolutionMode ::Types = > NodeResolutionMode ::Types ,
}
}
2023-12-07 00:03:18 +00:00
let referrer = & referrer_range . specifier ;
2024-03-06 00:23:51 +00:00
let result : Result < _ , ResolveError > = self
2023-05-11 00:06:59 +00:00
. mapped_specifier_resolver
2024-01-04 03:50:58 +00:00
. resolve ( specifier , referrer )
. map_err ( | err | err . into ( ) )
. and_then ( | resolution | match resolution {
MappedResolution ::ImportMap ( specifier ) = > Ok ( specifier ) ,
MappedResolution ::PackageJson ( specifier ) = > {
// found a specifier in the package.json, so mark that
// we need to do an "npm install" later
self . found_package_json_dep_flag . raise ( ) ;
Ok ( specifier )
}
MappedResolution ::None = > {
deno_graph ::resolve_import ( specifier , & referrer_range . specifier )
. map_err ( | err | err . into ( ) )
}
} ) ;
2023-08-17 16:14:22 +00:00
2023-12-07 00:03:18 +00:00
// do sloppy imports resolution if enabled
let result =
if let Some ( sloppy_imports_resolver ) = & self . sloppy_imports_resolver {
result . map ( | specifier | {
sloppy_imports_resolve (
sloppy_imports_resolver ,
specifier ,
referrer_range ,
2024-02-27 18:30:21 +00:00
mode ,
2023-12-07 00:03:18 +00:00
)
} )
} else {
result
} ;
2023-08-17 16:14:22 +00:00
// When the user is vendoring, don't allow them to import directly from the vendor/ directory
// as it might cause them confusion or duplicate dependencies. Additionally, this folder has
// special treatment in the language server so it will definitely cause issues/confusion there
// if they do this.
if let Some ( vendor_specifier ) = & self . maybe_vendor_specifier {
if let Ok ( specifier ) = & result {
if specifier . as_str ( ) . starts_with ( vendor_specifier . as_str ( ) ) {
2023-10-20 04:02:08 +00:00
return Err ( ResolveError ::Other ( anyhow! ( " Importing from the vendor directory is not permitted. Use a remote specifier instead or disable vendoring. " ) ) ) ;
2023-08-17 16:14:22 +00:00
}
}
2023-02-23 22:20:23 +00:00
}
2023-08-17 16:14:22 +00:00
2023-10-25 18:39:00 +00:00
if let Some ( resolver ) =
self . npm_resolver . as_ref ( ) . and_then ( | r | r . as_byonm ( ) )
{
match & result {
Ok ( specifier ) = > {
if let Ok ( npm_req_ref ) =
NpmPackageReqReference ::from_specifier ( specifier )
{
let node_resolver = self . node_resolver . as_ref ( ) . unwrap ( ) ;
2024-03-06 00:23:51 +00:00
return node_resolver
. resolve_req_reference (
& npm_req_ref ,
& PermissionsContainer ::allow_all ( ) ,
2023-10-25 18:39:00 +00:00
referrer ,
to_node_mode ( mode ) ,
2024-03-06 00:23:51 +00:00
)
. map ( | res | res . into_url ( ) )
. map_err ( | err | err . into ( ) ) ;
2023-10-25 18:39:00 +00:00
}
}
Err ( _ ) = > {
if referrer . scheme ( ) = = " file " {
if let Some ( node_resolver ) = & self . node_resolver {
let node_result = node_resolver . resolve (
specifier ,
referrer ,
to_node_mode ( mode ) ,
& PermissionsContainer ::allow_all ( ) ,
) ;
2023-10-27 01:22:15 +00:00
match node_result {
2024-03-06 00:23:51 +00:00
Ok ( Some ( res ) ) = > {
return Ok ( res . into_url ( ) ) ;
2023-10-27 01:22:15 +00:00
}
Ok ( None ) = > {
self
. check_surface_byonm_node_error (
specifier ,
referrer ,
to_node_mode ( mode ) ,
anyhow! ( " Cannot find \" {} \" " , specifier ) ,
resolver ,
)
. map_err ( ResolveError ::Other ) ? ;
}
Err ( err ) = > {
self
. check_surface_byonm_node_error (
specifier ,
referrer ,
to_node_mode ( mode ) ,
err ,
resolver ,
)
. map_err ( ResolveError ::Other ) ? ;
2023-10-25 18:39:00 +00:00
}
}
}
}
}
}
}
2024-03-06 00:23:51 +00:00
let specifier = result ? ;
match & self . node_resolver {
Some ( node_resolver ) = > node_resolver
. handle_if_in_node_modules ( specifier )
. map_err ( | e | e . into ( ) ) ,
None = > Ok ( specifier ) ,
}
2021-11-09 01:26:39 +00:00
}
}
2023-02-22 19:15:25 +00:00
2023-12-07 00:03:18 +00:00
fn sloppy_imports_resolve (
2023-12-07 20:59:13 +00:00
resolver : & SloppyImportsResolver ,
2023-12-07 00:03:18 +00:00
specifier : ModuleSpecifier ,
referrer_range : & deno_graph ::Range ,
2024-02-27 18:30:21 +00:00
mode : ResolutionMode ,
2023-12-07 00:03:18 +00:00
) -> ModuleSpecifier {
2024-02-27 18:30:21 +00:00
let resolution = resolver . resolve ( & specifier , mode ) ;
if mode . is_types ( ) {
// don't bother warning for types resolution because
// we already probably warned during execution resolution
match resolution {
SloppyImportsResolution ::None ( _ ) = > return specifier , // avoid a clone
_ = > return resolution . into_specifier ( ) . into_owned ( ) ,
}
}
2023-12-07 00:03:18 +00:00
let hint_message = match & resolution {
2023-12-07 20:59:13 +00:00
SloppyImportsResolution ::JsToTs ( to_specifier ) = > {
2023-12-07 00:03:18 +00:00
let to_media_type = MediaType ::from_specifier ( to_specifier ) ;
2024-02-27 18:30:21 +00:00
let from_media_type = MediaType ::from_specifier ( & specifier ) ;
2023-12-07 00:03:18 +00:00
format! (
" update {} extension to {} " ,
from_media_type . as_ts_extension ( ) ,
to_media_type . as_ts_extension ( )
)
}
2023-12-07 20:59:13 +00:00
SloppyImportsResolution ::NoExtension ( to_specifier ) = > {
2023-12-07 00:03:18 +00:00
let to_media_type = MediaType ::from_specifier ( to_specifier ) ;
format! ( " add {} extension " , to_media_type . as_ts_extension ( ) )
}
2023-12-07 20:59:13 +00:00
SloppyImportsResolution ::Directory ( to_specifier ) = > {
2023-12-07 00:03:18 +00:00
let file_name = to_specifier
. path ( )
. rsplit_once ( '/' )
. map ( | ( _ , file_name ) | file_name )
. unwrap_or ( to_specifier . path ( ) ) ;
format! ( " specify path to {} file in directory instead " , file_name )
}
2023-12-07 20:59:13 +00:00
SloppyImportsResolution ::None ( _ ) = > return specifier ,
2023-12-07 00:03:18 +00:00
} ;
// show a warning when this happens in order to drive
// the user towards correcting these specifiers
2024-03-07 13:59:57 +00:00
if ! * DENO_DISABLE_PEDANTIC_NODE_WARNINGS {
log ::warn! (
" {} Sloppy module resolution {} \n at {} " ,
crate ::colors ::yellow ( " Warning " ) ,
crate ::colors ::gray ( format! ( " (hint: {} ) " , hint_message ) ) . to_string ( ) ,
if referrer_range . end = = deno_graph ::Position ::zeroed ( ) {
// not worth showing the range in this case
crate ::colors ::cyan ( referrer_range . specifier . as_str ( ) ) . to_string ( )
} else {
format_range_with_colors ( referrer_range )
} ,
) ;
}
2023-12-08 14:57:06 +00:00
resolution . into_specifier ( ) . into_owned ( )
2023-12-07 00:03:18 +00:00
}
2023-02-23 17:33:23 +00:00
fn resolve_package_json_dep (
specifier : & str ,
2023-03-03 22:27:05 +00:00
deps : & PackageJsonDeps ,
) -> Result < Option < ModuleSpecifier > , AnyError > {
for ( bare_specifier , req_result ) in deps {
2023-02-23 17:33:23 +00:00
if specifier . starts_with ( bare_specifier ) {
let path = & specifier [ bare_specifier . len ( ) .. ] ;
2023-03-03 22:27:05 +00:00
if path . is_empty ( ) | | path . starts_with ( '/' ) {
let req = req_result . as_ref ( ) . map_err ( | err | {
anyhow! (
" Parsing version constraints in the application-level package.json is more strict at the moment. \n \n {:#} " ,
err . clone ( )
)
} ) ? ;
return Ok ( Some ( ModuleSpecifier ::parse ( & format! ( " npm: {req} {path} " ) ) ? ) ) ;
2023-02-23 17:33:23 +00:00
}
}
}
Ok ( None )
}
2023-02-22 19:15:25 +00:00
impl NpmResolver for CliGraphResolver {
fn resolve_builtin_node_module (
& self ,
specifier : & ModuleSpecifier ,
) -> Result < Option < String > , UnknownBuiltInNodeModuleError > {
if specifier . scheme ( ) ! = " node " {
return Ok ( None ) ;
}
let module_name = specifier . path ( ) . to_string ( ) ;
if is_builtin_node_module ( & module_name ) {
Ok ( Some ( module_name ) )
} else {
Err ( UnknownBuiltInNodeModuleError { module_name } )
}
}
2023-10-20 04:02:08 +00:00
fn on_resolve_bare_builtin_node_module (
& self ,
module_name : & str ,
range : & deno_graph ::Range ,
) {
let deno_graph ::Range {
start , specifier , ..
} = range ;
let line = start . line + 1 ;
let column = start . character + 1 ;
2024-03-07 13:59:57 +00:00
if ! * DENO_DISABLE_PEDANTIC_NODE_WARNINGS {
log ::warn! ( " Warning: Resolving \" {module_name} \" as \" node:{module_name} \" at {specifier}:{line}:{column}. If you want to use a built-in Node module, add a \" node: \" prefix. " )
}
2023-10-20 04:02:08 +00:00
}
2023-02-22 19:15:25 +00:00
fn load_and_cache_npm_package_info (
& self ,
package_name : & str ,
2023-04-12 12:36:11 +00:00
) -> LocalBoxFuture < 'static , Result < ( ) , AnyError > > {
2023-09-30 16:06:38 +00:00
match & self . npm_resolver {
Some ( npm_resolver ) if npm_resolver . as_managed ( ) . is_some ( ) = > {
let package_name = package_name . to_string ( ) ;
let npm_resolver = npm_resolver . clone ( ) ;
async move {
if let Some ( managed ) = npm_resolver . as_managed ( ) {
managed . cache_package_info ( & package_name ) . await ? ;
}
Ok ( ( ) )
}
. boxed ( )
}
_ = > {
// return it succeeded and error at the import site below
Box ::pin ( future ::ready ( Ok ( ( ) ) ) )
}
2023-02-22 19:15:25 +00:00
}
}
2023-09-07 13:09:16 +00:00
fn resolve_npm ( & self , package_req : & PackageReq ) -> NpmPackageReqResolution {
2023-09-30 16:06:38 +00:00
match & self . npm_resolver {
2023-10-03 23:05:06 +00:00
Some ( npm_resolver ) = > match npm_resolver . as_inner ( ) {
InnerCliNpmResolverRef ::Managed ( npm_resolver ) = > {
npm_resolver . resolve_npm_for_deno_graph ( package_req )
}
// if we are using byonm, then this should never be called because
// we don't use deno_graph's npm resolution in this case
InnerCliNpmResolverRef ::Byonm ( _ ) = > unreachable! ( ) ,
} ,
2023-09-30 16:06:38 +00:00
None = > NpmPackageReqResolution ::Err ( anyhow! (
" npm specifiers were requested; but --no-npm is specified "
) ) ,
2023-04-07 01:41:19 +00:00
}
2023-02-22 19:15:25 +00:00
}
2023-10-20 04:02:08 +00:00
fn enables_bare_builtin_node_module ( & self ) -> bool {
self . bare_node_builtins_enabled
}
2023-02-22 19:15:25 +00:00
}
2023-02-23 17:33:23 +00:00
2023-12-07 00:03:18 +00:00
#[ derive(Debug) ]
2023-12-07 20:59:13 +00:00
struct SloppyImportsStatCache {
2023-12-07 00:03:18 +00:00
fs : Arc < dyn FileSystem > ,
2023-12-07 20:59:13 +00:00
cache : Mutex < HashMap < PathBuf , Option < SloppyImportsFsEntry > > > ,
2023-12-07 00:03:18 +00:00
}
2023-12-07 20:59:13 +00:00
impl SloppyImportsStatCache {
2023-12-07 00:03:18 +00:00
pub fn new ( fs : Arc < dyn FileSystem > ) -> Self {
Self {
fs ,
cache : Default ::default ( ) ,
}
}
2023-12-07 20:59:13 +00:00
pub fn stat_sync ( & self , path : & Path ) -> Option < SloppyImportsFsEntry > {
2023-12-07 00:03:18 +00:00
// there will only ever be one thread in here at a
// time, so it's ok to hold the lock for so long
let mut cache = self . cache . lock ( ) ;
if let Some ( entry ) = cache . get ( path ) {
return * entry ;
}
2023-12-08 14:57:06 +00:00
let entry = self
. fs
. stat_sync ( path )
. ok ( )
. and_then ( | stat | SloppyImportsFsEntry ::from_fs_stat ( & stat ) ) ;
2023-12-07 00:03:18 +00:00
cache . insert ( path . to_owned ( ) , entry ) ;
entry
}
}
#[ derive(Debug, Clone, Copy, PartialEq, Eq) ]
2023-12-07 20:59:13 +00:00
pub enum SloppyImportsFsEntry {
2023-12-07 00:03:18 +00:00
File ,
Dir ,
}
2023-12-08 14:57:06 +00:00
impl SloppyImportsFsEntry {
pub fn from_fs_stat (
stat : & deno_runtime ::deno_io ::fs ::FsStat ,
) -> Option < SloppyImportsFsEntry > {
if stat . is_file {
Some ( SloppyImportsFsEntry ::File )
} else if stat . is_directory {
Some ( SloppyImportsFsEntry ::Dir )
} else {
None
}
}
}
2023-12-07 00:03:18 +00:00
#[ derive(Debug, PartialEq, Eq) ]
2023-12-07 20:59:13 +00:00
pub enum SloppyImportsResolution < ' a > {
2023-12-07 00:03:18 +00:00
/// No sloppy resolution was found.
None ( & ' a ModuleSpecifier ) ,
/// Ex. `./file.js` to `./file.ts`
JsToTs ( ModuleSpecifier ) ,
/// Ex. `./file` to `./file.ts`
NoExtension ( ModuleSpecifier ) ,
/// Ex. `./dir` to `./dir/index.ts`
Directory ( ModuleSpecifier ) ,
}
2023-12-07 20:59:13 +00:00
impl < ' a > SloppyImportsResolution < ' a > {
2023-12-08 14:57:06 +00:00
pub fn as_specifier ( & self ) -> & ModuleSpecifier {
match self {
Self ::None ( specifier ) = > specifier ,
Self ::JsToTs ( specifier ) = > specifier ,
Self ::NoExtension ( specifier ) = > specifier ,
Self ::Directory ( specifier ) = > specifier ,
}
}
2023-12-07 00:03:18 +00:00
pub fn into_specifier ( self ) -> Cow < ' a , ModuleSpecifier > {
match self {
Self ::None ( specifier ) = > Cow ::Borrowed ( specifier ) ,
Self ::JsToTs ( specifier ) = > Cow ::Owned ( specifier ) ,
Self ::NoExtension ( specifier ) = > Cow ::Owned ( specifier ) ,
Self ::Directory ( specifier ) = > Cow ::Owned ( specifier ) ,
}
}
2023-12-08 14:57:06 +00:00
pub fn as_suggestion_message ( & self ) -> Option < String > {
Some ( format! ( " Maybe {} " , self . as_base_message ( ) ? ) )
}
pub fn as_lsp_quick_fix_message ( & self ) -> Option < String > {
let message = self . as_base_message ( ) ? ;
let mut chars = message . chars ( ) ;
Some ( format! (
" {}{}. " ,
chars . next ( ) . unwrap ( ) . to_uppercase ( ) ,
chars . as_str ( )
) )
}
fn as_base_message ( & self ) -> Option < String > {
2023-12-07 00:03:18 +00:00
match self {
2023-12-08 14:57:06 +00:00
SloppyImportsResolution ::None ( _ ) = > None ,
SloppyImportsResolution ::JsToTs ( specifier ) = > {
let media_type = MediaType ::from_specifier ( specifier ) ;
Some ( format! (
" change the extension to '{}' " ,
media_type . as_ts_extension ( )
) )
}
SloppyImportsResolution ::NoExtension ( specifier ) = > {
let media_type = MediaType ::from_specifier ( specifier ) ;
Some ( format! (
" add a '{}' extension " ,
media_type . as_ts_extension ( )
) )
}
SloppyImportsResolution ::Directory ( specifier ) = > {
let file_name = specifier
. path ( )
. rsplit_once ( '/' )
. map ( | ( _ , file_name ) | file_name )
. unwrap_or ( specifier . path ( ) ) ;
Some ( format! (
" specify path to '{}' file in directory instead " ,
file_name
) )
}
2023-12-07 00:03:18 +00:00
}
}
}
#[ derive(Debug) ]
2023-12-07 20:59:13 +00:00
pub struct SloppyImportsResolver {
stat_cache : SloppyImportsStatCache ,
2023-12-07 00:03:18 +00:00
}
2023-12-07 20:59:13 +00:00
impl SloppyImportsResolver {
2023-12-07 00:03:18 +00:00
pub fn new ( fs : Arc < dyn FileSystem > ) -> Self {
Self {
2023-12-07 20:59:13 +00:00
stat_cache : SloppyImportsStatCache ::new ( fs ) ,
2023-12-07 00:03:18 +00:00
}
}
2023-12-08 14:57:06 +00:00
pub fn resolve_with_fs < ' a > (
fs : & dyn FileSystem ,
specifier : & ' a ModuleSpecifier ,
2024-02-27 18:30:21 +00:00
mode : ResolutionMode ,
2023-12-08 14:57:06 +00:00
) -> SloppyImportsResolution < ' a > {
2024-02-27 18:30:21 +00:00
Self ::resolve_with_stat_sync ( specifier , mode , | path | {
2023-12-08 14:57:06 +00:00
fs . stat_sync ( path )
. ok ( )
. and_then ( | stat | SloppyImportsFsEntry ::from_fs_stat ( & stat ) )
} )
}
2023-12-07 00:03:18 +00:00
pub fn resolve_with_stat_sync (
specifier : & ModuleSpecifier ,
2024-02-27 18:30:21 +00:00
mode : ResolutionMode ,
2023-12-07 20:59:13 +00:00
stat_sync : impl Fn ( & Path ) -> Option < SloppyImportsFsEntry > ,
) -> SloppyImportsResolution {
2024-02-27 18:30:21 +00:00
fn path_without_ext (
path : & Path ,
media_type : MediaType ,
) -> Option < Cow < str > > {
let old_path_str = path . to_string_lossy ( ) ;
match media_type {
MediaType ::Unknown = > Some ( old_path_str ) ,
_ = > old_path_str
. strip_suffix ( media_type . as_ts_extension ( ) )
. map ( | s | Cow ::Owned ( s . to_string ( ) ) ) ,
}
}
fn media_types_to_paths (
path_no_ext : & str ,
probe_media_type_types : Vec < MediaType > ,
2024-03-08 17:25:55 +00:00
reason : SloppyImportsResolutionReason ,
) -> Vec < ( PathBuf , SloppyImportsResolutionReason ) > {
2024-02-27 18:30:21 +00:00
probe_media_type_types
. into_iter ( )
. map ( | media_type | {
2024-03-08 17:25:55 +00:00
(
PathBuf ::from ( format! (
" {}{} " ,
path_no_ext ,
media_type . as_ts_extension ( )
) ) ,
reason ,
)
2024-02-27 18:30:21 +00:00
} )
. collect ::< Vec < _ > > ( )
}
2023-12-07 00:03:18 +00:00
if specifier . scheme ( ) ! = " file " {
2023-12-07 20:59:13 +00:00
return SloppyImportsResolution ::None ( specifier ) ;
2023-12-07 00:03:18 +00:00
}
let Ok ( path ) = specifier_to_file_path ( specifier ) else {
2023-12-07 20:59:13 +00:00
return SloppyImportsResolution ::None ( specifier ) ;
2023-12-07 00:03:18 +00:00
} ;
2024-03-08 17:25:55 +00:00
#[ derive(Clone, Copy) ]
enum SloppyImportsResolutionReason {
JsToTs ,
NoExtension ,
Directory ,
}
let probe_paths : Vec < ( PathBuf , SloppyImportsResolutionReason ) > =
match ( stat_sync ) ( & path ) {
Some ( SloppyImportsFsEntry ::File ) = > {
if mode . is_types ( ) {
let media_type = MediaType ::from_specifier ( specifier ) ;
// attempt to resolve the .d.ts file before the .js file
let probe_media_type_types = match media_type {
MediaType ::JavaScript = > {
vec! [ ( MediaType ::Dts ) , MediaType ::JavaScript ]
}
MediaType ::Mjs = > {
vec! [ MediaType ::Dmts , MediaType ::Dts , MediaType ::Mjs ]
}
MediaType ::Cjs = > {
vec! [ MediaType ::Dcts , MediaType ::Dts , MediaType ::Cjs ]
}
_ = > return SloppyImportsResolution ::None ( specifier ) ,
} ;
let Some ( path_no_ext ) = path_without_ext ( & path , media_type ) else {
return SloppyImportsResolution ::None ( specifier ) ;
} ;
media_types_to_paths (
& path_no_ext ,
probe_media_type_types ,
SloppyImportsResolutionReason ::JsToTs ,
)
} else {
return SloppyImportsResolution ::None ( specifier ) ;
}
}
entry @ None | entry @ Some ( SloppyImportsFsEntry ::Dir ) = > {
2024-02-27 18:30:21 +00:00
let media_type = MediaType ::from_specifier ( specifier ) ;
let probe_media_type_types = match media_type {
2024-03-08 17:25:55 +00:00
MediaType ::JavaScript = > (
if mode . is_types ( ) {
vec! [ MediaType ::TypeScript , MediaType ::Tsx , MediaType ::Dts ]
} else {
vec! [ MediaType ::TypeScript , MediaType ::Tsx ]
} ,
SloppyImportsResolutionReason ::JsToTs ,
) ,
MediaType ::Jsx = > {
( vec! [ MediaType ::Tsx ] , SloppyImportsResolutionReason ::JsToTs )
2024-02-27 18:30:21 +00:00
}
2024-03-08 17:25:55 +00:00
MediaType ::Mjs = > (
if mode . is_types ( ) {
vec! [ MediaType ::Mts , MediaType ::Dmts , MediaType ::Dts ]
} else {
vec! [ MediaType ::Mts ]
} ,
SloppyImportsResolutionReason ::JsToTs ,
) ,
MediaType ::Cjs = > (
if mode . is_types ( ) {
vec! [ MediaType ::Cts , MediaType ::Dcts , MediaType ::Dts ]
} else {
vec! [ MediaType ::Cts ]
} ,
SloppyImportsResolutionReason ::JsToTs ,
) ,
MediaType ::TypeScript
| MediaType ::Mts
| MediaType ::Cts
| MediaType ::Dts
| MediaType ::Dmts
| MediaType ::Dcts
| MediaType ::Tsx
| MediaType ::Json
| MediaType ::Wasm
| MediaType ::TsBuildInfo
| MediaType ::SourceMap = > {
return SloppyImportsResolution ::None ( specifier )
2024-02-27 18:30:21 +00:00
}
2024-03-08 17:25:55 +00:00
MediaType ::Unknown = > (
if mode . is_types ( ) {
vec! [
MediaType ::TypeScript ,
MediaType ::Tsx ,
MediaType ::Mts ,
MediaType ::Dts ,
MediaType ::Dmts ,
MediaType ::Dcts ,
MediaType ::JavaScript ,
MediaType ::Jsx ,
MediaType ::Mjs ,
]
} else {
vec! [
MediaType ::TypeScript ,
MediaType ::JavaScript ,
MediaType ::Tsx ,
MediaType ::Jsx ,
MediaType ::Mts ,
MediaType ::Mjs ,
]
} ,
SloppyImportsResolutionReason ::NoExtension ,
) ,
2024-02-27 18:30:21 +00:00
} ;
2024-03-08 17:25:55 +00:00
let mut probe_paths = match path_without_ext ( & path , media_type ) {
Some ( path_no_ext ) = > media_types_to_paths (
& path_no_ext ,
probe_media_type_types . 0 ,
probe_media_type_types . 1 ,
) ,
None = > vec! [ ] ,
2024-02-27 18:30:21 +00:00
} ;
2024-03-08 17:25:55 +00:00
if matches! ( entry , Some ( SloppyImportsFsEntry ::Dir ) ) {
// try to resolve at the index file
2024-02-27 18:30:21 +00:00
if mode . is_types ( ) {
2024-03-08 17:25:55 +00:00
probe_paths . push ( (
path . join ( " index.ts " ) ,
SloppyImportsResolutionReason ::Directory ,
) ) ;
probe_paths . push ( (
path . join ( " index.mts " ) ,
SloppyImportsResolutionReason ::Directory ,
) ) ;
probe_paths . push ( (
path . join ( " index.d.ts " ) ,
SloppyImportsResolutionReason ::Directory ,
) ) ;
probe_paths . push ( (
path . join ( " index.d.mts " ) ,
SloppyImportsResolutionReason ::Directory ,
) ) ;
probe_paths . push ( (
path . join ( " index.js " ) ,
SloppyImportsResolutionReason ::Directory ,
) ) ;
probe_paths . push ( (
path . join ( " index.mjs " ) ,
SloppyImportsResolutionReason ::Directory ,
) ) ;
probe_paths . push ( (
path . join ( " index.tsx " ) ,
SloppyImportsResolutionReason ::Directory ,
) ) ;
probe_paths . push ( (
path . join ( " index.jsx " ) ,
SloppyImportsResolutionReason ::Directory ,
) ) ;
2024-02-27 18:30:21 +00:00
} else {
2024-03-08 17:25:55 +00:00
probe_paths . push ( (
path . join ( " index.ts " ) ,
SloppyImportsResolutionReason ::Directory ,
) ) ;
probe_paths . push ( (
path . join ( " index.mts " ) ,
SloppyImportsResolutionReason ::Directory ,
) ) ;
probe_paths . push ( (
path . join ( " index.tsx " ) ,
SloppyImportsResolutionReason ::Directory ,
) ) ;
probe_paths . push ( (
path . join ( " index.js " ) ,
SloppyImportsResolutionReason ::Directory ,
) ) ;
probe_paths . push ( (
path . join ( " index.mjs " ) ,
SloppyImportsResolutionReason ::Directory ,
) ) ;
probe_paths . push ( (
path . join ( " index.jsx " ) ,
SloppyImportsResolutionReason ::Directory ,
) ) ;
2024-02-27 18:30:21 +00:00
}
}
2024-03-08 17:25:55 +00:00
if probe_paths . is_empty ( ) {
return SloppyImportsResolution ::None ( specifier ) ;
2023-12-07 00:03:18 +00:00
}
2024-03-08 17:25:55 +00:00
probe_paths
}
} ;
2023-12-07 00:03:18 +00:00
2024-03-08 17:25:55 +00:00
for ( probe_path , reason ) in probe_paths {
2023-12-07 20:59:13 +00:00
if ( stat_sync ) ( & probe_path ) = = Some ( SloppyImportsFsEntry ::File ) {
2023-12-07 00:03:18 +00:00
if let Ok ( specifier ) = ModuleSpecifier ::from_file_path ( probe_path ) {
2024-03-08 17:25:55 +00:00
match reason {
SloppyImportsResolutionReason ::JsToTs = > {
return SloppyImportsResolution ::JsToTs ( specifier )
}
SloppyImportsResolutionReason ::NoExtension = > {
return SloppyImportsResolution ::NoExtension ( specifier )
}
SloppyImportsResolutionReason ::Directory = > {
return SloppyImportsResolution ::Directory ( specifier )
}
2023-12-07 00:03:18 +00:00
}
}
}
}
2023-12-07 20:59:13 +00:00
SloppyImportsResolution ::None ( specifier )
2023-12-07 00:03:18 +00:00
}
pub fn resolve < ' a > (
& self ,
specifier : & ' a ModuleSpecifier ,
2024-02-27 18:30:21 +00:00
mode : ResolutionMode ,
2023-12-07 20:59:13 +00:00
) -> SloppyImportsResolution < ' a > {
2024-02-27 18:30:21 +00:00
Self ::resolve_with_stat_sync ( specifier , mode , | path | {
2023-12-07 00:03:18 +00:00
self . stat_cache . stat_sync ( path )
} )
}
}
2023-02-23 17:33:23 +00:00
#[ cfg(test) ]
mod test {
2023-03-03 22:27:05 +00:00
use std ::collections ::BTreeMap ;
2023-12-07 00:03:18 +00:00
use deno_runtime ::deno_fs ::RealFs ;
use test_util ::TestContext ;
2023-02-23 17:33:23 +00:00
use super ::* ;
#[ test ]
fn test_resolve_package_json_dep ( ) {
fn resolve (
specifier : & str ,
2023-08-21 09:53:52 +00:00
deps : & BTreeMap < String , PackageReq > ,
2023-02-23 17:33:23 +00:00
) -> Result < Option < String > , String > {
2023-03-03 22:27:05 +00:00
let deps = deps
. iter ( )
. map ( | ( key , value ) | ( key . to_string ( ) , Ok ( value . clone ( ) ) ) )
. collect ( ) ;
resolve_package_json_dep ( specifier , & deps )
2023-02-23 17:33:23 +00:00
. map ( | s | s . map ( | s | s . to_string ( ) ) )
. map_err ( | err | err . to_string ( ) )
}
let deps = BTreeMap ::from ( [
(
" package " . to_string ( ) ,
2023-08-21 09:53:52 +00:00
PackageReq ::from_str ( " package@1.0 " ) . unwrap ( ) ,
2023-02-23 17:33:23 +00:00
) ,
(
" package-alias " . to_string ( ) ,
2023-08-21 09:53:52 +00:00
PackageReq ::from_str ( " package@^1.2 " ) . unwrap ( ) ,
2023-02-23 17:33:23 +00:00
) ,
(
" @deno/test " . to_string ( ) ,
2023-08-21 09:53:52 +00:00
PackageReq ::from_str ( " @deno/test@~0.2 " ) . unwrap ( ) ,
2023-02-23 17:33:23 +00:00
) ,
] ) ;
assert_eq! (
resolve ( " package " , & deps ) . unwrap ( ) ,
Some ( " npm:package@1.0 " . to_string ( ) ) ,
) ;
assert_eq! (
resolve ( " package/some_path.ts " , & deps ) . unwrap ( ) ,
2023-03-03 22:27:05 +00:00
Some ( " npm:package@1.0/some_path.ts " . to_string ( ) ) ,
2023-02-23 17:33:23 +00:00
) ;
assert_eq! (
resolve ( " @deno/test " , & deps ) . unwrap ( ) ,
Some ( " npm:@deno/test@~0.2 " . to_string ( ) ) ,
) ;
assert_eq! (
resolve ( " @deno/test/some_path.ts " , & deps ) . unwrap ( ) ,
2023-03-03 22:27:05 +00:00
Some ( " npm:@deno/test@~0.2/some_path.ts " . to_string ( ) ) ,
2023-02-23 17:33:23 +00:00
) ;
// matches the start, but doesn't have the same length or a path
assert_eq! ( resolve ( " @deno/testing " , & deps ) . unwrap ( ) , None , ) ;
// alias
assert_eq! (
resolve ( " package-alias " , & deps ) . unwrap ( ) ,
Some ( " npm:package@^1.2 " . to_string ( ) ) ,
) ;
// non-existent bare specifier
assert_eq! ( resolve ( " non-existent " , & deps ) . unwrap ( ) , None ) ;
}
2023-12-07 00:03:18 +00:00
#[ test ]
fn test_unstable_sloppy_imports ( ) {
2023-12-07 20:59:13 +00:00
fn resolve ( specifier : & ModuleSpecifier ) -> SloppyImportsResolution {
2024-02-27 18:30:21 +00:00
SloppyImportsResolver ::resolve_with_stat_sync (
specifier ,
ResolutionMode ::Execution ,
| path | {
RealFs . stat_sync ( path ) . ok ( ) . and_then ( | stat | {
if stat . is_file {
Some ( SloppyImportsFsEntry ::File )
} else if stat . is_directory {
Some ( SloppyImportsFsEntry ::Dir )
} else {
None
}
} )
} ,
)
2023-12-07 00:03:18 +00:00
}
let context = TestContext ::default ( ) ;
let temp_dir = context . temp_dir ( ) . path ( ) ;
// scenarios like resolving ./example.js to ./example.ts
for ( ext_from , ext_to ) in [ ( " js " , " ts " ) , ( " js " , " tsx " ) , ( " mjs " , " mts " ) ] {
let ts_file = temp_dir . join ( format! ( " file. {} " , ext_to ) ) ;
ts_file . write ( " " ) ;
let ts_file_uri = ts_file . uri_file ( ) ;
assert_eq! (
resolve ( & ts_file . uri_file ( ) ) ,
2023-12-07 20:59:13 +00:00
SloppyImportsResolution ::None ( & ts_file_uri ) ,
2023-12-07 00:03:18 +00:00
) ;
assert_eq! (
resolve (
& temp_dir
. uri_dir ( )
. join ( & format! ( " file. {} " , ext_from ) )
. unwrap ( )
) ,
2023-12-07 20:59:13 +00:00
SloppyImportsResolution ::JsToTs ( ts_file . uri_file ( ) ) ,
2023-12-07 00:03:18 +00:00
) ;
ts_file . remove_file ( ) ;
}
// no extension scenarios
for ext in [ " js " , " ts " , " js " , " tsx " , " jsx " , " mjs " , " mts " ] {
let file = temp_dir . join ( format! ( " file. {} " , ext ) ) ;
file . write ( " " ) ;
assert_eq! (
resolve (
& temp_dir
. uri_dir ( )
. join ( " file " ) // no ext
. unwrap ( )
) ,
2023-12-07 20:59:13 +00:00
SloppyImportsResolution ::NoExtension ( file . uri_file ( ) ) ,
2023-12-07 00:03:18 +00:00
) ;
file . remove_file ( ) ;
}
// .ts and .js exists, .js specified (goes to specified)
{
let ts_file = temp_dir . join ( " file.ts " ) ;
ts_file . write ( " " ) ;
let js_file = temp_dir . join ( " file.js " ) ;
js_file . write ( " " ) ;
let js_file_uri = js_file . uri_file ( ) ;
assert_eq! (
resolve ( & js_file . uri_file ( ) ) ,
2023-12-07 20:59:13 +00:00
SloppyImportsResolution ::None ( & js_file_uri ) ,
2023-12-07 00:03:18 +00:00
) ;
}
// resolving a directory to an index file
{
let routes_dir = temp_dir . join ( " routes " ) ;
routes_dir . create_dir_all ( ) ;
let index_file = routes_dir . join ( " index.ts " ) ;
index_file . write ( " " ) ;
assert_eq! (
resolve ( & routes_dir . uri_file ( ) ) ,
2023-12-07 20:59:13 +00:00
SloppyImportsResolution ::Directory ( index_file . uri_file ( ) ) ,
2023-12-07 00:03:18 +00:00
) ;
2024-03-08 17:25:55 +00:00
}
// both a directory and a file with specifier is present
{
let api_dir = temp_dir . join ( " api " ) ;
api_dir . create_dir_all ( ) ;
let bar_file = api_dir . join ( " bar.ts " ) ;
bar_file . write ( " " ) ;
let api_file = temp_dir . join ( " api.ts " ) ;
api_file . write ( " " ) ;
assert_eq! (
resolve ( & api_dir . uri_file ( ) ) ,
SloppyImportsResolution ::NoExtension ( api_file . uri_file ( ) ) ,
) ;
2023-12-07 00:03:18 +00:00
}
}
2023-12-08 14:57:06 +00:00
#[ test ]
fn test_sloppy_import_resolution_suggestion_message ( ) {
// none
let url = ModuleSpecifier ::parse ( " file:///dir/index.js " ) . unwrap ( ) ;
assert_eq! (
SloppyImportsResolution ::None ( & url ) . as_suggestion_message ( ) ,
None ,
) ;
// directory
assert_eq! (
SloppyImportsResolution ::Directory (
ModuleSpecifier ::parse ( " file:///dir/index.js " ) . unwrap ( )
)
. as_suggestion_message ( )
. unwrap ( ) ,
" Maybe specify path to 'index.js' file in directory instead "
) ;
// no ext
assert_eq! (
SloppyImportsResolution ::NoExtension (
ModuleSpecifier ::parse ( " file:///dir/index.mjs " ) . unwrap ( )
)
. as_suggestion_message ( )
. unwrap ( ) ,
" Maybe add a '.mjs' extension "
) ;
// js to ts
assert_eq! (
SloppyImportsResolution ::JsToTs (
ModuleSpecifier ::parse ( " file:///dir/index.mts " ) . unwrap ( )
)
. as_suggestion_message ( )
. unwrap ( ) ,
" Maybe change the extension to '.mts' "
) ;
}
2023-02-23 17:33:23 +00:00
}