1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-04 05:18:59 -05:00

fix(node): correct resolution of dynamic import of esm from cjs (#27071)

Ensures a dynamic import in a CJS file will consider the referrer as an import for node resolution.

Also adds fixes (adds) support for `"resolution-mode"` in TypeScript.
This commit is contained in:
David Sherret 2024-11-26 14:38:24 -05:00 committed by GitHub
parent c443ac5d14
commit 115a306656
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
92 changed files with 868 additions and 1673 deletions

153
Cargo.lock generated
View file

@ -128,19 +128,6 @@ version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f"
[[package]]
name = "ammonia"
version = "4.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ab99eae5ee58501ab236beb6f20f6ca39be615267b014899c89b2f0bc18a459"
dependencies = [
"html5ever",
"maplit",
"once_cell",
"tendril",
"url",
]
[[package]] [[package]]
name = "android_system_properties" name = "android_system_properties"
version = "0.1.5" version = "0.1.5"
@ -1557,18 +1544,16 @@ dependencies = [
[[package]] [[package]]
name = "deno_doc" name = "deno_doc"
version = "0.160.0" version = "0.161.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db2baa33e5d1ed235209c2990f5fe9644bac6b9e7bcb789dd92894f907b09ad7" checksum = "32d994915f85e873865fc341e592080a487b0a987d06177016b2d93fd62162f8"
dependencies = [ dependencies = [
"ammonia",
"anyhow", "anyhow",
"cfg-if", "cfg-if",
"comrak", "comrak",
"deno_ast", "deno_ast",
"deno_graph", "deno_graph",
"deno_path_util", "deno_path_util",
"futures",
"handlebars", "handlebars",
"html-escape", "html-escape",
"import_map", "import_map",
@ -1665,9 +1650,9 @@ dependencies = [
[[package]] [[package]]
name = "deno_graph" name = "deno_graph"
version = "0.85.1" version = "0.86.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c11027d9b4e9ff4f8bcb8316a1a5dd5241dc267380507e177457bc491696189" checksum = "4c3f4be49dad28e794ff4eeb2daaf7956c97f8557097ef6f9c3ff1292e0a5c28"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-trait", "async-trait",
@ -3265,16 +3250,6 @@ version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
[[package]]
name = "futf"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843"
dependencies = [
"mac",
"new_debug_unreachable",
]
[[package]] [[package]]
name = "futures" name = "futures"
version = "0.3.30" version = "0.3.30"
@ -3802,20 +3777,6 @@ dependencies = [
"utf8-width", "utf8-width",
] ]
[[package]]
name = "html5ever"
version = "0.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c13771afe0e6e846f1e67d038d4cb29998a6779f93c809212e4e9c32efd244d4"
dependencies = [
"log",
"mac",
"markup5ever",
"proc-macro2",
"quote",
"syn 2.0.87",
]
[[package]] [[package]]
name = "http" name = "http"
version = "0.2.12" version = "0.2.12"
@ -4663,12 +4624,6 @@ dependencies = [
"serde_repr", "serde_repr",
] ]
[[package]]
name = "mac"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"
[[package]] [[package]]
name = "malloc_buf" name = "malloc_buf"
version = "0.0.6" version = "0.0.6"
@ -4691,26 +4646,6 @@ dependencies = [
"tiny_pretty", "tiny_pretty",
] ]
[[package]]
name = "maplit"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d"
[[package]]
name = "markup5ever"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16ce3abbeba692c8b8441d036ef91aea6df8da2c6b6e21c7e14d3c18e526be45"
dependencies = [
"log",
"phf",
"phf_codegen",
"string_cache",
"string_cache_codegen",
"tendril",
]
[[package]] [[package]]
name = "markup_fmt" name = "markup_fmt"
version = "0.16.0" version = "0.16.0"
@ -5468,27 +5403,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc" checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc"
dependencies = [ dependencies = [
"phf_macros", "phf_macros",
"phf_shared 0.11.2", "phf_shared",
]
[[package]]
name = "phf_codegen"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8d39688d359e6b34654d328e262234662d16cc0f60ec8dcbe5e718709342a5a"
dependencies = [
"phf_generator 0.11.2",
"phf_shared 0.11.2",
]
[[package]]
name = "phf_generator"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6"
dependencies = [
"phf_shared 0.10.0",
"rand",
] ]
[[package]] [[package]]
@ -5497,7 +5412,7 @@ version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0" checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0"
dependencies = [ dependencies = [
"phf_shared 0.11.2", "phf_shared",
"rand", "rand",
] ]
@ -5507,22 +5422,13 @@ version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3444646e286606587e49f3bcf1679b8cef1dc2c5ecc29ddacaffc305180d464b" checksum = "3444646e286606587e49f3bcf1679b8cef1dc2c5ecc29ddacaffc305180d464b"
dependencies = [ dependencies = [
"phf_generator 0.11.2", "phf_generator",
"phf_shared 0.11.2", "phf_shared",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.87",
] ]
[[package]]
name = "phf_shared"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096"
dependencies = [
"siphasher",
]
[[package]] [[package]]
name = "phf_shared" name = "phf_shared"
version = "0.11.2" version = "0.11.2"
@ -5645,12 +5551,6 @@ version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
[[package]]
name = "precomputed-hash"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
[[package]] [[package]]
name = "pretty_assertions" name = "pretty_assertions"
version = "1.4.0" version = "1.4.0"
@ -6985,32 +6885,6 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "string_cache"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f91138e76242f575eb1d3b38b4f1362f10d3a43f47d182a5b359af488a02293b"
dependencies = [
"new_debug_unreachable",
"once_cell",
"parking_lot",
"phf_shared 0.10.0",
"precomputed-hash",
"serde",
]
[[package]]
name = "string_cache_codegen"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bb30289b722be4ff74a408c3cc27edeaad656e06cb1fe8fa9231fa59c728988"
dependencies = [
"phf_generator 0.10.0",
"phf_shared 0.10.0",
"proc-macro2",
"quote",
]
[[package]] [[package]]
name = "string_enum" name = "string_enum"
version = "0.4.4" version = "0.4.4"
@ -7598,17 +7472,6 @@ dependencies = [
"windows-sys 0.52.0", "windows-sys 0.52.0",
] ]
[[package]]
name = "tendril"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0"
dependencies = [
"futf",
"mac",
"utf-8",
]
[[package]] [[package]]
name = "termcolor" name = "termcolor"
version = "1.4.1" version = "1.4.1"

View file

@ -72,8 +72,8 @@ deno_ast = { workspace = true, features = ["bundler", "cjs", "codegen", "proposa
deno_cache_dir.workspace = true deno_cache_dir.workspace = true
deno_config.workspace = true deno_config.workspace = true
deno_core = { workspace = true, features = ["include_js_files_for_snapshotting"] } deno_core = { workspace = true, features = ["include_js_files_for_snapshotting"] }
deno_doc = { version = "0.160.0", features = ["rust", "comrak"] } deno_doc = { version = "=0.161.1", features = ["rust", "comrak"] }
deno_graph = { version = "=0.85.1" } deno_graph = { version = "=0.86.2" }
deno_lint = { version = "=0.68.0", features = ["docs"] } deno_lint = { version = "=0.68.0", features = ["docs"] }
deno_lockfile.workspace = true deno_lockfile.workspace = true
deno_npm.workspace = true deno_npm.workspace = true

View file

@ -284,6 +284,7 @@ fn serialize_media_type(media_type: MediaType) -> i64 {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use deno_graph::JsDocImportInfo;
use deno_graph::PositionRange; use deno_graph::PositionRange;
use deno_graph::SpecifierWithRange; use deno_graph::SpecifierWithRange;
@ -308,18 +309,21 @@ mod test {
); );
let mut module_info = ModuleInfo::default(); let mut module_info = ModuleInfo::default();
module_info.jsdoc_imports.push(SpecifierWithRange { module_info.jsdoc_imports.push(JsDocImportInfo {
range: PositionRange { specifier: SpecifierWithRange {
start: deno_graph::Position { range: PositionRange {
line: 0, start: deno_graph::Position {
character: 3, line: 0,
}, character: 3,
end: deno_graph::Position { },
line: 1, end: deno_graph::Position {
character: 2, line: 1,
character: 2,
},
}, },
text: "test".to_string(),
}, },
text: "test".to_string(), resolution_mode: None,
}); });
cache cache
.set_module_info( .set_module_info(

View file

@ -25,7 +25,7 @@ use deno_config::deno_json::JsxImportSourceConfig;
use deno_config::workspace::JsrPackageConfig; use deno_config::workspace::JsrPackageConfig;
use deno_core::anyhow::bail; use deno_core::anyhow::bail;
use deno_graph::source::LoaderChecksum; use deno_graph::source::LoaderChecksum;
use deno_graph::source::ResolutionMode; use deno_graph::source::ResolutionKind;
use deno_graph::FillFromLockfileOptions; use deno_graph::FillFromLockfileOptions;
use deno_graph::JsrLoadError; use deno_graph::JsrLoadError;
use deno_graph::ModuleLoadError; use deno_graph::ModuleLoadError;
@ -44,7 +44,7 @@ use deno_graph::ModuleGraphError;
use deno_graph::ResolutionError; use deno_graph::ResolutionError;
use deno_graph::SpecifierError; use deno_graph::SpecifierError;
use deno_path_util::url_to_file_path; use deno_path_util::url_to_file_path;
use deno_resolver::sloppy_imports::SloppyImportsResolutionMode; use deno_resolver::sloppy_imports::SloppyImportsResolutionKind;
use deno_runtime::deno_fs::FileSystem; use deno_runtime::deno_fs::FileSystem;
use deno_runtime::deno_node; use deno_runtime::deno_node;
use deno_runtime::deno_permissions::PermissionsContainer; use deno_runtime::deno_permissions::PermissionsContainer;
@ -795,7 +795,7 @@ fn enhanced_sloppy_imports_error_message(
ModuleError::LoadingErr(specifier, _, ModuleLoadError::Loader(_)) // ex. "Is a directory" error ModuleError::LoadingErr(specifier, _, ModuleLoadError::Loader(_)) // ex. "Is a directory" error
| ModuleError::Missing(specifier, _) => { | ModuleError::Missing(specifier, _) => {
let additional_message = CliSloppyImportsResolver::new(SloppyImportsCachedFs::new(fs.clone())) let additional_message = CliSloppyImportsResolver::new(SloppyImportsCachedFs::new(fs.clone()))
.resolve(specifier, SloppyImportsResolutionMode::Execution)? .resolve(specifier, SloppyImportsResolutionKind::Execution)?
.as_suggestion_message(); .as_suggestion_message();
Some(format!( Some(format!(
"{} {} or run with --unstable-sloppy-imports", "{} {} or run with --unstable-sloppy-imports",
@ -1100,12 +1100,12 @@ impl<'a> deno_graph::source::FileSystem for DenoGraphFsAdapter<'a> {
} }
} }
pub fn format_range_with_colors(range: &deno_graph::Range) -> String { pub fn format_range_with_colors(referrer: &deno_graph::Range) -> String {
format!( format!(
"{}:{}:{}", "{}:{}:{}",
colors::cyan(range.specifier.as_str()), colors::cyan(referrer.specifier.as_str()),
colors::yellow(&(range.start.line + 1).to_string()), colors::yellow(&(referrer.range.start.line + 1).to_string()),
colors::yellow(&(range.start.character + 1).to_string()) colors::yellow(&(referrer.range.start.character + 1).to_string())
) )
} }
@ -1195,26 +1195,54 @@ impl<'a> deno_graph::source::Resolver for CliGraphResolver<'a> {
&self, &self,
raw_specifier: &str, raw_specifier: &str,
referrer_range: &deno_graph::Range, referrer_range: &deno_graph::Range,
mode: ResolutionMode, resolution_kind: ResolutionKind,
) -> Result<ModuleSpecifier, ResolveError> { ) -> Result<ModuleSpecifier, ResolveError> {
self.resolver.resolve( self.resolver.resolve(
raw_specifier, raw_specifier,
referrer_range, &referrer_range.specifier,
self referrer_range.range.start,
.cjs_tracker referrer_range
.get_referrer_kind(&referrer_range.specifier), .resolution_mode
mode, .map(to_node_resolution_mode)
.unwrap_or_else(|| {
self
.cjs_tracker
.get_referrer_kind(&referrer_range.specifier)
}),
to_node_resolution_kind(resolution_kind),
) )
} }
} }
pub fn to_node_resolution_kind(
kind: ResolutionKind,
) -> node_resolver::NodeResolutionKind {
match kind {
ResolutionKind::Execution => node_resolver::NodeResolutionKind::Execution,
ResolutionKind::Types => node_resolver::NodeResolutionKind::Types,
}
}
pub fn to_node_resolution_mode(
mode: deno_graph::source::ResolutionMode,
) -> node_resolver::ResolutionMode {
match mode {
deno_graph::source::ResolutionMode::Import => {
node_resolver::ResolutionMode::Import
}
deno_graph::source::ResolutionMode::Require => {
node_resolver::ResolutionMode::Require
}
}
}
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use std::sync::Arc; use std::sync::Arc;
use deno_ast::ModuleSpecifier; use deno_ast::ModuleSpecifier;
use deno_graph::source::ResolveError; use deno_graph::source::ResolveError;
use deno_graph::Position; use deno_graph::PositionRange;
use deno_graph::Range; use deno_graph::Range;
use deno_graph::ResolutionError; use deno_graph::ResolutionError;
use deno_graph::SpecifierError; use deno_graph::SpecifierError;
@ -1235,8 +1263,8 @@ mod test {
specifier: input.to_string(), specifier: input.to_string(),
range: Range { range: Range {
specifier, specifier,
start: Position::zeroed(), resolution_mode: None,
end: Position::zeroed(), range: PositionRange::zeroed(),
}, },
}; };
assert_eq!(get_resolution_error_bare_node_specifier(&err), output); assert_eq!(get_resolution_error_bare_node_specifier(&err), output);
@ -1251,8 +1279,8 @@ mod test {
let err = ResolutionError::InvalidSpecifier { let err = ResolutionError::InvalidSpecifier {
range: Range { range: Range {
specifier, specifier,
start: Position::zeroed(), resolution_mode: None,
end: Position::zeroed(), range: PositionRange::zeroed(),
}, },
error: SpecifierError::ImportPrefixMissing { error: SpecifierError::ImportPrefixMissing {
specifier: input.to_string(), specifier: input.to_string(),

View file

@ -15,7 +15,6 @@ use crate::lsp::search::PackageSearchApi;
use crate::tools::lint::CliLinter; use crate::tools::lint::CliLinter;
use crate::util::path::relative_specifier; use crate::util::path::relative_specifier;
use deno_config::workspace::MappedResolution; use deno_config::workspace::MappedResolution;
use deno_graph::source::ResolutionMode;
use deno_lint::diagnostic::LintDiagnosticRange; use deno_lint::diagnostic::LintDiagnosticRange;
use deno_ast::SourceRange; use deno_ast::SourceRange;
@ -39,7 +38,8 @@ use deno_semver::package::PackageReq;
use deno_semver::package::PackageReqReference; use deno_semver::package::PackageReqReference;
use deno_semver::Version; use deno_semver::Version;
use import_map::ImportMap; use import_map::ImportMap;
use node_resolver::NodeModuleKind; use node_resolver::NodeResolutionKind;
use node_resolver::ResolutionMode;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use std::borrow::Cow; use std::borrow::Cow;
@ -467,7 +467,7 @@ impl<'a> TsResponseImportMapper<'a> {
&self, &self,
specifier: &str, specifier: &str,
referrer: &ModuleSpecifier, referrer: &ModuleSpecifier,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
) -> Option<String> { ) -> Option<String> {
let specifier_stem = specifier.strip_suffix(".js").unwrap_or(specifier); let specifier_stem = specifier.strip_suffix(".js").unwrap_or(specifier);
let specifiers = std::iter::once(Cow::Borrowed(specifier)).chain( let specifiers = std::iter::once(Cow::Borrowed(specifier)).chain(
@ -481,13 +481,10 @@ impl<'a> TsResponseImportMapper<'a> {
.as_cli_resolver(Some(&self.file_referrer)) .as_cli_resolver(Some(&self.file_referrer))
.resolve( .resolve(
&specifier, &specifier,
&deno_graph::Range { referrer,
specifier: referrer.clone(), deno_graph::Position::zeroed(),
start: deno_graph::Position::zeroed(), resolution_mode,
end: deno_graph::Position::zeroed(), NodeResolutionKind::Types,
},
referrer_kind,
ResolutionMode::Types,
) )
.ok() .ok()
.and_then(|s| self.tsc_specifier_map.normalize(s.as_str()).ok()) .and_then(|s| self.tsc_specifier_map.normalize(s.as_str()).ok())
@ -509,20 +506,17 @@ impl<'a> TsResponseImportMapper<'a> {
&self, &self,
specifier_text: &str, specifier_text: &str,
referrer: &ModuleSpecifier, referrer: &ModuleSpecifier,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
) -> bool { ) -> bool {
self self
.resolver .resolver
.as_cli_resolver(Some(&self.file_referrer)) .as_cli_resolver(Some(&self.file_referrer))
.resolve( .resolve(
specifier_text, specifier_text,
&deno_graph::Range { referrer,
specifier: referrer.clone(), deno_graph::Position::zeroed(),
start: deno_graph::Position::zeroed(), resolution_mode,
end: deno_graph::Position::zeroed(), NodeResolutionKind::Types,
},
referrer_kind,
deno_graph::source::ResolutionMode::Types,
) )
.is_ok() .is_ok()
} }
@ -590,7 +584,7 @@ fn try_reverse_map_package_json_exports(
/// like an import and rewrite the import specifier to include the extension /// like an import and rewrite the import specifier to include the extension
pub fn fix_ts_import_changes( pub fn fix_ts_import_changes(
referrer: &ModuleSpecifier, referrer: &ModuleSpecifier,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
changes: &[tsc::FileTextChanges], changes: &[tsc::FileTextChanges],
language_server: &language_server::Inner, language_server: &language_server::Inner,
) -> Result<Vec<tsc::FileTextChanges>, AnyError> { ) -> Result<Vec<tsc::FileTextChanges>, AnyError> {
@ -608,7 +602,7 @@ pub fn fix_ts_import_changes(
let specifier = let specifier =
captures.iter().skip(1).find_map(|s| s).unwrap().as_str(); captures.iter().skip(1).find_map(|s| s).unwrap().as_str();
if let Some(new_specifier) = import_mapper if let Some(new_specifier) = import_mapper
.check_unresolved_specifier(specifier, referrer, referrer_kind) .check_unresolved_specifier(specifier, referrer, resolution_mode)
{ {
line.replace(specifier, &new_specifier) line.replace(specifier, &new_specifier)
} else { } else {
@ -638,7 +632,7 @@ pub fn fix_ts_import_changes(
/// resolution by Deno (includes the extension). /// resolution by Deno (includes the extension).
fn fix_ts_import_action<'a>( fn fix_ts_import_action<'a>(
referrer: &ModuleSpecifier, referrer: &ModuleSpecifier,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
action: &'a tsc::CodeFixAction, action: &'a tsc::CodeFixAction,
language_server: &language_server::Inner, language_server: &language_server::Inner,
) -> Option<Cow<'a, tsc::CodeFixAction>> { ) -> Option<Cow<'a, tsc::CodeFixAction>> {
@ -657,9 +651,11 @@ fn fix_ts_import_action<'a>(
return Some(Cow::Borrowed(action)); return Some(Cow::Borrowed(action));
}; };
let import_mapper = language_server.get_ts_response_import_mapper(referrer); let import_mapper = language_server.get_ts_response_import_mapper(referrer);
if let Some(new_specifier) = if let Some(new_specifier) = import_mapper.check_unresolved_specifier(
import_mapper.check_unresolved_specifier(specifier, referrer, referrer_kind) specifier,
{ referrer,
resolution_mode,
) {
let description = action.description.replace(specifier, &new_specifier); let description = action.description.replace(specifier, &new_specifier);
let changes = action let changes = action
.changes .changes
@ -689,7 +685,8 @@ fn fix_ts_import_action<'a>(
fix_id: None, fix_id: None,
fix_all_description: None, fix_all_description: None,
})) }))
} else if !import_mapper.is_valid_import(specifier, referrer, referrer_kind) { } else if !import_mapper.is_valid_import(specifier, referrer, resolution_mode)
{
None None
} else { } else {
Some(Cow::Borrowed(action)) Some(Cow::Borrowed(action))
@ -1023,7 +1020,7 @@ impl CodeActionCollection {
pub fn add_ts_fix_action( pub fn add_ts_fix_action(
&mut self, &mut self,
specifier: &ModuleSpecifier, specifier: &ModuleSpecifier,
specifier_kind: NodeModuleKind, resolution_mode: ResolutionMode,
action: &tsc::CodeFixAction, action: &tsc::CodeFixAction,
diagnostic: &lsp::Diagnostic, diagnostic: &lsp::Diagnostic,
language_server: &language_server::Inner, language_server: &language_server::Inner,
@ -1042,7 +1039,7 @@ impl CodeActionCollection {
)); ));
} }
let Some(action) = let Some(action) =
fix_ts_import_action(specifier, specifier_kind, action, language_server) fix_ts_import_action(specifier, resolution_mode, action, language_server)
else { else {
return Ok(()); return Ok(());
}; };
@ -1237,12 +1234,12 @@ impl CodeActionCollection {
let text_info = parsed_source.text_info_lazy(); let text_info = parsed_source.text_info_lazy();
let specifier_range = SourceRange::new( let specifier_range = SourceRange::new(
text_info.loc_to_source_pos(LineAndColumnIndex { text_info.loc_to_source_pos(LineAndColumnIndex {
line_index: import.specifier_range.start.line, line_index: import.specifier_range.range.start.line,
column_index: import.specifier_range.start.character, column_index: import.specifier_range.range.start.character,
}), }),
text_info.loc_to_source_pos(LineAndColumnIndex { text_info.loc_to_source_pos(LineAndColumnIndex {
line_index: import.specifier_range.end.line, line_index: import.specifier_range.range.end.line,
column_index: import.specifier_range.end.character, column_index: import.specifier_range.range.end.character,
}), }),
); );
@ -1277,7 +1274,7 @@ impl CodeActionCollection {
if json!(i.kind) != json!("es") && json!(i.kind) != json!("tsType") { if json!(i.kind) != json!("es") && json!(i.kind) != json!("tsType") {
return None; return None;
} }
if !i.specifier_range.includes(&position) { if !i.specifier_range.includes(position) {
return None; return None;
} }
@ -1286,7 +1283,7 @@ impl CodeActionCollection {
let referrer = document.specifier(); let referrer = document.specifier();
let referrer_kind = language_server let referrer_kind = language_server
.is_cjs_resolver .is_cjs_resolver
.get_doc_module_kind(document); .get_doc_resolution_mode(document);
let file_referrer = document.file_referrer(); let file_referrer = document.file_referrer();
let config_data = language_server let config_data = language_server
.config .config

View file

@ -14,11 +14,10 @@ use super::resolver::LspResolver;
use super::search::PackageSearchApi; use super::search::PackageSearchApi;
use super::tsc; use super::tsc;
use crate::graph_util::to_node_resolution_mode;
use crate::jsr::JsrFetchResolver; use crate::jsr::JsrFetchResolver;
use crate::util::path::is_importable_ext; use crate::util::path::is_importable_ext;
use crate::util::path::relative_specifier; use crate::util::path::relative_specifier;
use deno_graph::source::ResolutionMode;
use deno_graph::Range;
use deno_runtime::deno_node::SUPPORTED_BUILTIN_NODE_MODULES; use deno_runtime::deno_node::SUPPORTED_BUILTIN_NODE_MODULES;
use deno_ast::LineAndColumnIndex; use deno_ast::LineAndColumnIndex;
@ -36,7 +35,8 @@ use deno_semver::package::PackageNv;
use import_map::ImportMap; use import_map::ImportMap;
use indexmap::IndexSet; use indexmap::IndexSet;
use lsp_types::CompletionList; use lsp_types::CompletionList;
use node_resolver::NodeModuleKind; use node_resolver::NodeResolutionKind;
use node_resolver::ResolutionMode;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use tower_lsp::lsp_types as lsp; use tower_lsp::lsp_types as lsp;
@ -113,7 +113,7 @@ async fn check_auto_config_registry(
/// which we want to ignore when replacing text. /// which we want to ignore when replacing text.
fn to_narrow_lsp_range( fn to_narrow_lsp_range(
text_info: &SourceTextInfo, text_info: &SourceTextInfo,
range: &deno_graph::Range, range: deno_graph::PositionRange,
) -> lsp::Range { ) -> lsp::Range {
let end_byte_index = text_info let end_byte_index = text_info
.loc_to_source_pos(LineAndColumnIndex { .loc_to_source_pos(LineAndColumnIndex {
@ -166,21 +166,21 @@ pub async fn get_import_completions(
maybe_import_map: Option<&ImportMap>, maybe_import_map: Option<&ImportMap>,
) -> Option<lsp::CompletionResponse> { ) -> Option<lsp::CompletionResponse> {
let document = documents.get(specifier)?; let document = documents.get(specifier)?;
let specifier_kind = is_cjs_resolver.get_doc_module_kind(&document);
let file_referrer = document.file_referrer(); let file_referrer = document.file_referrer();
let (text, _, range) = document.get_maybe_dependency(position)?; let (text, _, graph_range) = document.get_maybe_dependency(position)?;
let range = to_narrow_lsp_range(document.text_info(), &range); let resolution_mode = graph_range
.resolution_mode
.map(to_node_resolution_mode)
.unwrap_or_else(|| is_cjs_resolver.get_doc_resolution_mode(&document));
let range = to_narrow_lsp_range(document.text_info(), graph_range.range);
let resolved = resolver let resolved = resolver
.as_cli_resolver(file_referrer) .as_cli_resolver(file_referrer)
.resolve( .resolve(
&text, &text,
&Range { specifier,
specifier: specifier.clone(), deno_graph::Position::zeroed(),
start: deno_graph::Position::zeroed(), resolution_mode,
end: deno_graph::Position::zeroed(), NodeResolutionKind::Execution,
},
specifier_kind,
ResolutionMode::Execution,
) )
.ok(); .ok();
if let Some(completion_list) = get_jsr_completions( if let Some(completion_list) = get_jsr_completions(
@ -206,7 +206,7 @@ pub async fn get_import_completions(
// completions for import map specifiers // completions for import map specifiers
Some(lsp::CompletionResponse::List(completion_list)) Some(lsp::CompletionResponse::List(completion_list))
} else if let Some(completion_list) = } else if let Some(completion_list) =
get_local_completions(specifier, specifier_kind, &text, &range, resolver) get_local_completions(specifier, resolution_mode, &text, &range, resolver)
{ {
// completions for local relative modules // completions for local relative modules
Some(lsp::CompletionResponse::List(completion_list)) Some(lsp::CompletionResponse::List(completion_list))
@ -361,7 +361,7 @@ fn get_import_map_completions(
/// Return local completions that are relative to the base specifier. /// Return local completions that are relative to the base specifier.
fn get_local_completions( fn get_local_completions(
referrer: &ModuleSpecifier, referrer: &ModuleSpecifier,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
text: &str, text: &str,
range: &lsp::Range, range: &lsp::Range,
resolver: &LspResolver, resolver: &LspResolver,
@ -374,13 +374,10 @@ fn get_local_completions(
.as_cli_resolver(Some(referrer)) .as_cli_resolver(Some(referrer))
.resolve( .resolve(
parent, parent,
&Range { referrer,
specifier: referrer.clone(), deno_graph::Position::zeroed(),
start: deno_graph::Position::zeroed(), resolution_mode,
end: deno_graph::Position::zeroed(), NodeResolutionKind::Execution,
},
referrer_kind,
ResolutionMode::Execution,
) )
.ok()?; .ok()?;
let resolved_parent_path = url_to_file_path(&resolved_parent).ok()?; let resolved_parent_path = url_to_file_path(&resolved_parent).ok()?;
@ -831,7 +828,6 @@ mod tests {
use crate::lsp::documents::LanguageId; use crate::lsp::documents::LanguageId;
use crate::lsp::search::tests::TestPackageSearchApi; use crate::lsp::search::tests::TestPackageSearchApi;
use deno_core::resolve_url; use deno_core::resolve_url;
use deno_graph::Range;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use std::collections::HashMap; use std::collections::HashMap;
use test_util::TempDir; use test_util::TempDir;
@ -912,7 +908,7 @@ mod tests {
ModuleSpecifier::from_file_path(file_c).expect("could not create"); ModuleSpecifier::from_file_path(file_c).expect("could not create");
let actual = get_local_completions( let actual = get_local_completions(
&specifier, &specifier,
NodeModuleKind::Esm, ResolutionMode::Import,
"./", "./",
&lsp::Range { &lsp::Range {
start: lsp::Position { start: lsp::Position {
@ -1608,8 +1604,7 @@ mod tests {
let text_info = SourceTextInfo::from_string(r#""te""#.to_string()); let text_info = SourceTextInfo::from_string(r#""te""#.to_string());
let range = to_narrow_lsp_range( let range = to_narrow_lsp_range(
&text_info, &text_info,
&Range { deno_graph::PositionRange {
specifier: ModuleSpecifier::parse("https://deno.land").unwrap(),
start: deno_graph::Position { start: deno_graph::Position {
line: 0, line: 0,
character: 0, character: 0,
@ -1632,8 +1627,7 @@ mod tests {
let text_info = SourceTextInfo::from_string(r#""te"#.to_string()); let text_info = SourceTextInfo::from_string(r#""te"#.to_string());
let range = to_narrow_lsp_range( let range = to_narrow_lsp_range(
&text_info, &text_info,
&Range { deno_graph::PositionRange {
specifier: ModuleSpecifier::parse("https://deno.land").unwrap(),
start: deno_graph::Position { start: deno_graph::Position {
line: 0, line: 0,
character: 0, character: 0,

View file

@ -45,7 +45,7 @@ use deno_graph::Resolution;
use deno_graph::ResolutionError; use deno_graph::ResolutionError;
use deno_graph::SpecifierError; use deno_graph::SpecifierError;
use deno_resolver::sloppy_imports::SloppyImportsResolution; use deno_resolver::sloppy_imports::SloppyImportsResolution;
use deno_resolver::sloppy_imports::SloppyImportsResolutionMode; use deno_resolver::sloppy_imports::SloppyImportsResolutionKind;
use deno_runtime::deno_fs; use deno_runtime::deno_fs;
use deno_runtime::deno_node; use deno_runtime::deno_node;
use deno_runtime::tokio_util::create_basic_runtime; use deno_runtime::tokio_util::create_basic_runtime;
@ -1266,7 +1266,7 @@ impl DenoDiagnostic {
Self::NoLocal(specifier) => { Self::NoLocal(specifier) => {
let maybe_sloppy_resolution = CliSloppyImportsResolver::new( let maybe_sloppy_resolution = CliSloppyImportsResolver::new(
SloppyImportsCachedFs::new(Arc::new(deno_fs::RealFs)) SloppyImportsCachedFs::new(Arc::new(deno_fs::RealFs))
).resolve(specifier, SloppyImportsResolutionMode::Execution); ).resolve(specifier, SloppyImportsResolutionKind::Execution);
let data = maybe_sloppy_resolution.as_ref().map(|res| { let data = maybe_sloppy_resolution.as_ref().map(|res| {
json!({ json!({
"specifier": specifier, "specifier": specifier,
@ -1531,7 +1531,7 @@ fn diagnose_dependency(
&& !dependency.imports.iter().any(|i| { && !dependency.imports.iter().any(|i| {
dependency dependency
.maybe_type .maybe_type
.includes(&i.specifier_range.start) .includes(i.specifier_range.range.start)
.is_some() .is_some()
}); });

View file

@ -27,7 +27,6 @@ use deno_core::futures::future::Shared;
use deno_core::futures::FutureExt; use deno_core::futures::FutureExt;
use deno_core::parking_lot::Mutex; use deno_core::parking_lot::Mutex;
use deno_core::ModuleSpecifier; use deno_core::ModuleSpecifier;
use deno_graph::source::ResolutionMode;
use deno_graph::Resolution; use deno_graph::Resolution;
use deno_path_util::url_to_file_path; use deno_path_util::url_to_file_path;
use deno_runtime::deno_node; use deno_runtime::deno_node;
@ -36,7 +35,8 @@ use deno_semver::npm::NpmPackageReqReference;
use deno_semver::package::PackageReq; use deno_semver::package::PackageReq;
use indexmap::IndexMap; use indexmap::IndexMap;
use indexmap::IndexSet; use indexmap::IndexSet;
use node_resolver::NodeModuleKind; use node_resolver::NodeResolutionKind;
use node_resolver::ResolutionMode;
use std::borrow::Cow; use std::borrow::Cow;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::collections::HashMap; use std::collections::HashMap;
@ -442,8 +442,8 @@ impl Document {
config_data.and_then(|d| d.maybe_jsx_import_source_config()); config_data.and_then(|d| d.maybe_jsx_import_source_config());
let resolver = SingleReferrerGraphResolver { let resolver = SingleReferrerGraphResolver {
valid_referrer: &self.specifier, valid_referrer: &self.specifier,
referrer_kind: is_cjs_resolver module_resolution_mode: is_cjs_resolver
.get_lsp_referrer_kind(&self.specifier, self.is_script), .get_lsp_resolution_mode(&self.specifier, self.is_script),
cli_resolver, cli_resolver,
jsx_import_source_config: jsx_import_source_config.as_ref(), jsx_import_source_config: jsx_import_source_config.as_ref(),
}; };
@ -768,7 +768,7 @@ impl Document {
}; };
self.dependencies().iter().find_map(|(s, dep)| { self.dependencies().iter().find_map(|(s, dep)| {
dep dep
.includes(&position) .includes(position)
.map(|r| (s.clone(), dep.clone(), r.clone())) .map(|r| (s.clone(), dep.clone(), r.clone()))
}) })
} }
@ -809,15 +809,15 @@ fn resolve_media_type(
MediaType::from_specifier(specifier) MediaType::from_specifier(specifier)
} }
pub fn to_lsp_range(range: &deno_graph::Range) -> lsp::Range { pub fn to_lsp_range(referrer: &deno_graph::Range) -> lsp::Range {
lsp::Range { lsp::Range {
start: lsp::Position { start: lsp::Position {
line: range.start.line as u32, line: referrer.range.start.line as u32,
character: range.start.character as u32, character: referrer.range.start.character as u32,
}, },
end: lsp::Position { end: lsp::Position {
line: range.end.line as u32, line: referrer.range.end.line as u32,
character: range.end.character as u32, character: referrer.range.end.character as u32,
}, },
} }
} }
@ -1271,7 +1271,8 @@ impl Documents {
/// tsc when type checking. /// tsc when type checking.
pub fn resolve( pub fn resolve(
&self, &self,
raw_specifiers: &[String], // (is_cjs: bool, raw_specifier: String)
raw_specifiers: &[(bool, String)],
referrer: &ModuleSpecifier, referrer: &ModuleSpecifier,
file_referrer: Option<&ModuleSpecifier>, file_referrer: Option<&ModuleSpecifier>,
) -> Vec<Option<(ModuleSpecifier, MediaType)>> { ) -> Vec<Option<(ModuleSpecifier, MediaType)>> {
@ -1281,11 +1282,12 @@ impl Documents {
.and_then(|d| d.file_referrer()) .and_then(|d| d.file_referrer())
.or(file_referrer); .or(file_referrer);
let dependencies = referrer_doc.as_ref().map(|d| d.dependencies()); let dependencies = referrer_doc.as_ref().map(|d| d.dependencies());
let referrer_kind = self
.is_cjs_resolver
.get_maybe_doc_module_kind(referrer, referrer_doc.as_deref());
let mut results = Vec::new(); let mut results = Vec::new();
for raw_specifier in raw_specifiers { for (is_cjs, raw_specifier) in raw_specifiers {
let resolution_mode = match is_cjs {
true => ResolutionMode::Require,
false => ResolutionMode::Import,
};
if raw_specifier.starts_with("asset:") { if raw_specifier.starts_with("asset:") {
if let Ok(specifier) = ModuleSpecifier::parse(raw_specifier) { if let Ok(specifier) = ModuleSpecifier::parse(raw_specifier) {
let media_type = MediaType::from_specifier(&specifier); let media_type = MediaType::from_specifier(&specifier);
@ -1300,14 +1302,14 @@ impl Documents {
results.push(self.resolve_dependency( results.push(self.resolve_dependency(
specifier, specifier,
referrer, referrer,
referrer_kind, resolution_mode,
file_referrer, file_referrer,
)); ));
} else if let Some(specifier) = dep.maybe_code.maybe_specifier() { } else if let Some(specifier) = dep.maybe_code.maybe_specifier() {
results.push(self.resolve_dependency( results.push(self.resolve_dependency(
specifier, specifier,
referrer, referrer,
referrer_kind, resolution_mode,
file_referrer, file_referrer,
)); ));
} else { } else {
@ -1316,19 +1318,16 @@ impl Documents {
} else if let Ok(specifier) = } else if let Ok(specifier) =
self.resolver.as_cli_resolver(file_referrer).resolve( self.resolver.as_cli_resolver(file_referrer).resolve(
raw_specifier, raw_specifier,
&deno_graph::Range { referrer,
specifier: referrer.clone(), deno_graph::Position::zeroed(),
start: deno_graph::Position::zeroed(), resolution_mode,
end: deno_graph::Position::zeroed(), NodeResolutionKind::Types,
},
referrer_kind,
ResolutionMode::Types,
) )
{ {
results.push(self.resolve_dependency( results.push(self.resolve_dependency(
&specifier, &specifier,
referrer, referrer,
referrer_kind, resolution_mode,
file_referrer, file_referrer,
)); ));
} else { } else {
@ -1477,27 +1476,24 @@ impl Documents {
let type_specifier = jsx_config.default_types_specifier.as_ref()?; let type_specifier = jsx_config.default_types_specifier.as_ref()?;
let code_specifier = jsx_config.default_specifier.as_ref()?; let code_specifier = jsx_config.default_specifier.as_ref()?;
let cli_resolver = self.resolver.as_cli_resolver(Some(scope)); let cli_resolver = self.resolver.as_cli_resolver(Some(scope));
let range = deno_graph::Range {
specifier: jsx_config.base_url.clone(),
start: deno_graph::Position::zeroed(),
end: deno_graph::Position::zeroed(),
};
let type_specifier = cli_resolver let type_specifier = cli_resolver
.resolve( .resolve(
type_specifier, type_specifier,
&range, &jsx_config.base_url,
deno_graph::Position::zeroed(),
// todo(dsherret): this is wrong because it doesn't consider CJS referrers // todo(dsherret): this is wrong because it doesn't consider CJS referrers
deno_package_json::NodeModuleKind::Esm, ResolutionMode::Import,
ResolutionMode::Types, NodeResolutionKind::Types,
) )
.ok()?; .ok()?;
let code_specifier = cli_resolver let code_specifier = cli_resolver
.resolve( .resolve(
code_specifier, code_specifier,
&range, &jsx_config.base_url,
deno_graph::Position::zeroed(),
// todo(dsherret): this is wrong because it doesn't consider CJS referrers // todo(dsherret): this is wrong because it doesn't consider CJS referrers
deno_package_json::NodeModuleKind::Esm, ResolutionMode::Import,
ResolutionMode::Execution, NodeResolutionKind::Execution,
) )
.ok()?; .ok()?;
dep_info dep_info
@ -1542,7 +1538,7 @@ impl Documents {
&self, &self,
specifier: &ModuleSpecifier, specifier: &ModuleSpecifier,
referrer: &ModuleSpecifier, referrer: &ModuleSpecifier,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
file_referrer: Option<&ModuleSpecifier>, file_referrer: Option<&ModuleSpecifier>,
) -> Option<(ModuleSpecifier, MediaType)> { ) -> Option<(ModuleSpecifier, MediaType)> {
if let Some(module_name) = specifier.as_str().strip_prefix("node:") { if let Some(module_name) = specifier.as_str().strip_prefix("node:") {
@ -1559,7 +1555,7 @@ impl Documents {
let (s, mt) = self.resolver.npm_to_file_url( let (s, mt) = self.resolver.npm_to_file_url(
&npm_ref, &npm_ref,
referrer, referrer,
referrer_kind, resolution_mode,
file_referrer, file_referrer,
)?; )?;
specifier = s; specifier = s;
@ -1571,7 +1567,7 @@ impl Documents {
return Some((specifier, media_type)); return Some((specifier, media_type));
}; };
if let Some(types) = doc.maybe_types_dependency().maybe_specifier() { if let Some(types) = doc.maybe_types_dependency().maybe_specifier() {
let specifier_kind = self.is_cjs_resolver.get_doc_module_kind(&doc); let specifier_kind = self.is_cjs_resolver.get_doc_resolution_mode(&doc);
self.resolve_dependency(types, &specifier, specifier_kind, file_referrer) self.resolve_dependency(types, &specifier, specifier_kind, file_referrer)
} else { } else {
Some((doc.specifier().clone(), doc.media_type())) Some((doc.specifier().clone(), doc.media_type()))
@ -1688,7 +1684,7 @@ fn analyze_module(
config_data.and_then(|d| d.maybe_jsx_import_source_config()); config_data.and_then(|d| d.maybe_jsx_import_source_config());
let resolver = SingleReferrerGraphResolver { let resolver = SingleReferrerGraphResolver {
valid_referrer: &valid_referrer, valid_referrer: &valid_referrer,
referrer_kind: is_cjs_resolver.get_lsp_referrer_kind( module_resolution_mode: is_cjs_resolver.get_lsp_resolution_mode(
&specifier, &specifier,
Some(parsed_source.compute_is_script()), Some(parsed_source.compute_is_script()),
), ),

View file

@ -22,7 +22,8 @@ use deno_semver::jsr::JsrPackageReqReference;
use indexmap::Equivalent; use indexmap::Equivalent;
use indexmap::IndexSet; use indexmap::IndexSet;
use log::error; use log::error;
use node_resolver::NodeModuleKind; use node_resolver::NodeResolutionKind;
use node_resolver::ResolutionMode;
use serde::Deserialize; use serde::Deserialize;
use serde_json::from_value; use serde_json::from_value;
use std::collections::BTreeMap; use std::collections::BTreeMap;
@ -993,13 +994,10 @@ impl Inner {
let resolver = inner.resolver.as_cli_resolver(Some(&referrer)); let resolver = inner.resolver.as_cli_resolver(Some(&referrer));
let Ok(specifier) = resolver.resolve( let Ok(specifier) = resolver.resolve(
&specifier, &specifier,
&deno_graph::Range { &referrer,
specifier: referrer.clone(), deno_graph::Position::zeroed(),
start: deno_graph::Position::zeroed(), ResolutionMode::Import,
end: deno_graph::Position::zeroed(), NodeResolutionKind::Types,
},
NodeModuleKind::Esm,
deno_graph::source::ResolutionMode::Types,
) else { ) else {
return; return;
}; };
@ -1640,8 +1638,8 @@ impl Inner {
.get_ts_diagnostics(&specifier, asset_or_doc.document_lsp_version()); .get_ts_diagnostics(&specifier, asset_or_doc.document_lsp_version());
let specifier_kind = asset_or_doc let specifier_kind = asset_or_doc
.document() .document()
.map(|d| self.is_cjs_resolver.get_doc_module_kind(d)) .map(|d| self.is_cjs_resolver.get_doc_resolution_mode(d))
.unwrap_or(NodeModuleKind::Esm); .unwrap_or(ResolutionMode::Import);
let mut includes_no_cache = false; let mut includes_no_cache = false;
for diagnostic in &fixable_diagnostics { for diagnostic in &fixable_diagnostics {
match diagnostic.source.as_deref() { match diagnostic.source.as_deref() {
@ -1864,8 +1862,8 @@ impl Inner {
maybe_asset_or_doc maybe_asset_or_doc
.as_ref() .as_ref()
.and_then(|d| d.document()) .and_then(|d| d.document())
.map(|d| self.is_cjs_resolver.get_doc_module_kind(d)) .map(|d| self.is_cjs_resolver.get_doc_resolution_mode(d))
.unwrap_or(NodeModuleKind::Esm), .unwrap_or(ResolutionMode::Import),
&combined_code_actions.changes, &combined_code_actions.changes,
self, self,
) )
@ -1921,8 +1919,8 @@ impl Inner {
&action_data.specifier, &action_data.specifier,
asset_or_doc asset_or_doc
.document() .document()
.map(|d| self.is_cjs_resolver.get_doc_module_kind(d)) .map(|d| self.is_cjs_resolver.get_doc_resolution_mode(d))
.unwrap_or(NodeModuleKind::Esm), .unwrap_or(ResolutionMode::Import),
&refactor_edit_info.edits, &refactor_edit_info.edits,
self, self,
) )

View file

@ -9,7 +9,6 @@ use deno_config::workspace::PackageJsonDepResolution;
use deno_config::workspace::WorkspaceResolver; use deno_config::workspace::WorkspaceResolver;
use deno_core::parking_lot::Mutex; use deno_core::parking_lot::Mutex;
use deno_core::url::Url; use deno_core::url::Url;
use deno_graph::source::ResolutionMode;
use deno_graph::GraphImport; use deno_graph::GraphImport;
use deno_graph::ModuleSpecifier; use deno_graph::ModuleSpecifier;
use deno_graph::Range; use deno_graph::Range;
@ -30,8 +29,8 @@ use deno_semver::package::PackageReq;
use indexmap::IndexMap; use indexmap::IndexMap;
use node_resolver::errors::ClosestPkgJsonError; use node_resolver::errors::ClosestPkgJsonError;
use node_resolver::InNpmPackageChecker; use node_resolver::InNpmPackageChecker;
use node_resolver::NodeModuleKind; use node_resolver::NodeResolutionKind;
use node_resolver::NodeResolutionMode; use node_resolver::ResolutionMode;
use std::borrow::Cow; use std::borrow::Cow;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::collections::BTreeSet; use std::collections::BTreeSet;
@ -48,6 +47,8 @@ use crate::args::CliLockfile;
use crate::args::NpmInstallDepsProvider; use crate::args::NpmInstallDepsProvider;
use crate::cache::DenoCacheEnvFsAdapter; use crate::cache::DenoCacheEnvFsAdapter;
use crate::factory::Deferred; use crate::factory::Deferred;
use crate::graph_util::to_node_resolution_kind;
use crate::graph_util::to_node_resolution_mode;
use crate::graph_util::CliJsrUrlProvider; use crate::graph_util::CliJsrUrlProvider;
use crate::http_util::HttpClientProvider; use crate::http_util::HttpClientProvider;
use crate::lsp::config::Config; use crate::lsp::config::Config;
@ -146,7 +147,7 @@ impl LspScopeResolver {
.map(|(referrer, imports)| { .map(|(referrer, imports)| {
let resolver = SingleReferrerGraphResolver { let resolver = SingleReferrerGraphResolver {
valid_referrer: &referrer, valid_referrer: &referrer,
referrer_kind: NodeModuleKind::Esm, module_resolution_mode: ResolutionMode::Import,
cli_resolver: &cli_resolver, cli_resolver: &cli_resolver,
jsx_import_source_config: maybe_jsx_import_source_config jsx_import_source_config: maybe_jsx_import_source_config
.as_ref(), .as_ref(),
@ -180,16 +181,16 @@ impl LspScopeResolver {
&req_ref, &req_ref,
&referrer, &referrer,
// todo(dsherret): this is wrong because it doesn't consider CJS referrers // todo(dsherret): this is wrong because it doesn't consider CJS referrers
NodeModuleKind::Esm, ResolutionMode::Import,
NodeResolutionMode::Types, NodeResolutionKind::Types,
) )
.or_else(|_| { .or_else(|_| {
npm_pkg_req_resolver.resolve_req_reference( npm_pkg_req_resolver.resolve_req_reference(
&req_ref, &req_ref,
&referrer, &referrer,
// todo(dsherret): this is wrong because it doesn't consider CJS referrers // todo(dsherret): this is wrong because it doesn't consider CJS referrers
NodeModuleKind::Esm, ResolutionMode::Import,
NodeResolutionMode::Execution, NodeResolutionKind::Execution,
) )
}) })
.ok()?, .ok()?,
@ -424,7 +425,7 @@ impl LspResolver {
&self, &self,
req_ref: &NpmPackageReqReference, req_ref: &NpmPackageReqReference,
referrer: &ModuleSpecifier, referrer: &ModuleSpecifier,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
file_referrer: Option<&ModuleSpecifier>, file_referrer: Option<&ModuleSpecifier>,
) -> Option<(ModuleSpecifier, MediaType)> { ) -> Option<(ModuleSpecifier, MediaType)> {
let resolver = self.get_scope_resolver(file_referrer); let resolver = self.get_scope_resolver(file_referrer);
@ -434,8 +435,8 @@ impl LspResolver {
.resolve_req_reference( .resolve_req_reference(
req_ref, req_ref,
referrer, referrer,
referrer_kind, resolution_mode,
NodeResolutionMode::Types, NodeResolutionKind::Types,
) )
.ok()?, .ok()?,
))) )))
@ -492,7 +493,7 @@ impl LspResolver {
&self, &self,
specifier_text: &str, specifier_text: &str,
referrer: &ModuleSpecifier, referrer: &ModuleSpecifier,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
) -> bool { ) -> bool {
let resolver = self.get_scope_resolver(Some(referrer)); let resolver = self.get_scope_resolver(Some(referrer));
let Some(npm_pkg_req_resolver) = resolver.npm_pkg_req_resolver.as_ref() let Some(npm_pkg_req_resolver) = resolver.npm_pkg_req_resolver.as_ref()
@ -503,8 +504,8 @@ impl LspResolver {
.resolve_if_for_npm_pkg( .resolve_if_for_npm_pkg(
specifier_text, specifier_text,
referrer, referrer,
referrer_kind, resolution_mode,
NodeResolutionMode::Types, NodeResolutionKind::Types,
) )
.ok() .ok()
.flatten() .flatten()
@ -868,34 +869,23 @@ impl LspIsCjsResolver {
} }
} }
pub fn get_maybe_doc_module_kind( pub fn get_doc_resolution_mode(&self, document: &Document) -> ResolutionMode {
&self, self.get_lsp_resolution_mode(document.specifier(), document.is_script())
specifier: &ModuleSpecifier,
maybe_document: Option<&Document>,
) -> NodeModuleKind {
self.get_lsp_referrer_kind(
specifier,
maybe_document.and_then(|d| d.is_script()),
)
} }
pub fn get_doc_module_kind(&self, document: &Document) -> NodeModuleKind { pub fn get_lsp_resolution_mode(
self.get_lsp_referrer_kind(document.specifier(), document.is_script())
}
pub fn get_lsp_referrer_kind(
&self, &self,
specifier: &ModuleSpecifier, specifier: &ModuleSpecifier,
is_script: Option<bool>, is_script: Option<bool>,
) -> NodeModuleKind { ) -> ResolutionMode {
self.inner.get_lsp_referrer_kind(specifier, is_script) self.inner.get_lsp_resolution_mode(specifier, is_script)
} }
} }
#[derive(Debug)] #[derive(Debug)]
pub struct SingleReferrerGraphResolver<'a> { pub struct SingleReferrerGraphResolver<'a> {
pub valid_referrer: &'a ModuleSpecifier, pub valid_referrer: &'a ModuleSpecifier,
pub referrer_kind: NodeModuleKind, pub module_resolution_mode: ResolutionMode,
pub cli_resolver: &'a CliResolver, pub cli_resolver: &'a CliResolver,
pub jsx_import_source_config: Option<&'a JsxImportSourceConfig>, pub jsx_import_source_config: Option<&'a JsxImportSourceConfig>,
} }
@ -924,16 +914,20 @@ impl<'a> deno_graph::source::Resolver for SingleReferrerGraphResolver<'a> {
&self, &self,
specifier_text: &str, specifier_text: &str,
referrer_range: &Range, referrer_range: &Range,
mode: ResolutionMode, resolution_kind: deno_graph::source::ResolutionKind,
) -> Result<ModuleSpecifier, deno_graph::source::ResolveError> { ) -> Result<ModuleSpecifier, deno_graph::source::ResolveError> {
// this resolver assumes it will only be used with a single referrer // this resolver assumes it will only be used with a single referrer
// with the provided referrer kind // with the provided referrer kind
debug_assert_eq!(referrer_range.specifier, *self.valid_referrer); debug_assert_eq!(referrer_range.specifier, *self.valid_referrer);
self.cli_resolver.resolve( self.cli_resolver.resolve(
specifier_text, specifier_text,
referrer_range, &referrer_range.specifier,
self.referrer_kind, referrer_range.range.start,
mode, referrer_range
.resolution_mode
.map(to_node_resolution_mode)
.unwrap_or(self.module_resolution_mode),
to_node_resolution_kind(resolution_kind),
) )
} }
} }

View file

@ -70,7 +70,7 @@ use indexmap::IndexMap;
use indexmap::IndexSet; use indexmap::IndexSet;
use lazy_regex::lazy_regex; use lazy_regex::lazy_regex;
use log::error; use log::error;
use node_resolver::NodeModuleKind; use node_resolver::ResolutionMode;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Captures; use regex::Captures;
use regex::Regex; use regex::Regex;
@ -4449,9 +4449,14 @@ fn op_load<'s>(
version: state.script_version(&specifier), version: state.script_version(&specifier),
is_cjs: doc is_cjs: doc
.document() .document()
.map(|d| state.state_snapshot.is_cjs_resolver.get_doc_module_kind(d)) .map(|d| {
.unwrap_or(NodeModuleKind::Esm) state
== NodeModuleKind::Cjs, .state_snapshot
.is_cjs_resolver
.get_doc_resolution_mode(d)
})
.unwrap_or(ResolutionMode::Import)
== ResolutionMode::Require,
}) })
}; };
let serialized = serde_v8::to_v8(scope, maybe_load_response)?; let serialized = serde_v8::to_v8(scope, maybe_load_response)?;
@ -4479,17 +4484,9 @@ fn op_release(
fn op_resolve( fn op_resolve(
state: &mut OpState, state: &mut OpState,
#[string] base: String, #[string] base: String,
is_base_cjs: bool, #[serde] specifiers: Vec<(bool, String)>,
#[serde] specifiers: Vec<String>,
) -> Result<Vec<Option<(String, String)>>, AnyError> { ) -> Result<Vec<Option<(String, String)>>, AnyError> {
op_resolve_inner( op_resolve_inner(state, ResolveArgs { base, specifiers })
state,
ResolveArgs {
base,
is_base_cjs,
specifiers,
},
)
} }
struct TscRequestArray { struct TscRequestArray {
@ -4695,7 +4692,7 @@ fn op_script_names(state: &mut OpState) -> ScriptNames {
state state
.state_snapshot .state_snapshot
.is_cjs_resolver .is_cjs_resolver
.get_doc_module_kind(doc), .get_doc_resolution_mode(doc),
doc.file_referrer(), doc.file_referrer(),
)?; )?;
let types_doc = documents.get_or_load(&types, doc.file_referrer())?; let types_doc = documents.get_or_load(&types, doc.file_referrer())?;
@ -6430,8 +6427,7 @@ mod tests {
&mut state, &mut state,
ResolveArgs { ResolveArgs {
base: temp_dir.url().join("a.ts").unwrap().to_string(), base: temp_dir.url().join("a.ts").unwrap().to_string(),
is_base_cjs: false, specifiers: vec![(false, "./b.ts".to_string())],
specifiers: vec!["./b.ts".to_string()],
}, },
) )
.unwrap(); .unwrap();

View file

@ -57,9 +57,7 @@ use deno_core::ModuleSourceCode;
use deno_core::ModuleSpecifier; use deno_core::ModuleSpecifier;
use deno_core::ModuleType; use deno_core::ModuleType;
use deno_core::RequestedModuleType; use deno_core::RequestedModuleType;
use deno_core::ResolutionKind;
use deno_core::SourceCodeCacheInfo; use deno_core::SourceCodeCacheInfo;
use deno_graph::source::ResolutionMode;
use deno_graph::GraphKind; use deno_graph::GraphKind;
use deno_graph::JsModule; use deno_graph::JsModule;
use deno_graph::JsonModule; use deno_graph::JsonModule;
@ -76,7 +74,8 @@ use deno_runtime::deno_permissions::PermissionsContainer;
use deno_semver::npm::NpmPackageReqReference; use deno_semver::npm::NpmPackageReqReference;
use node_resolver::errors::ClosestPkgJsonError; use node_resolver::errors::ClosestPkgJsonError;
use node_resolver::InNpmPackageChecker; use node_resolver::InNpmPackageChecker;
use node_resolver::NodeResolutionMode; use node_resolver::NodeResolutionKind;
use node_resolver::ResolutionMode;
pub struct ModuleLoadPreparer { pub struct ModuleLoadPreparer {
options: Arc<CliOptions>, options: Arc<CliOptions>,
@ -498,13 +497,11 @@ impl<TGraphContainer: ModuleGraphContainer>
} }
Resolution::None => Cow::Owned(self.shared.resolver.resolve( Resolution::None => Cow::Owned(self.shared.resolver.resolve(
raw_specifier, raw_specifier,
&deno_graph::Range { referrer,
specifier: referrer.clone(), deno_graph::Position::zeroed(),
start: deno_graph::Position::zeroed(), // if we're here, that means it's resolving a dynamic import
end: deno_graph::Position::zeroed(), ResolutionMode::Import,
}, NodeResolutionKind::Execution,
self.shared.cjs_tracker.get_referrer_kind(referrer),
ResolutionMode::Execution,
)?), )?),
}; };
@ -517,8 +514,8 @@ impl<TGraphContainer: ModuleGraphContainer>
.resolve_req_reference( .resolve_req_reference(
&reference, &reference,
referrer, referrer,
self.shared.cjs_tracker.get_referrer_kind(referrer), ResolutionMode::Import,
NodeResolutionMode::Execution, NodeResolutionKind::Execution,
) )
.map_err(AnyError::from); .map_err(AnyError::from);
} }
@ -539,8 +536,8 @@ impl<TGraphContainer: ModuleGraphContainer>
&package_folder, &package_folder,
module.nv_reference.sub_path(), module.nv_reference.sub_path(),
Some(referrer), Some(referrer),
self.shared.cjs_tracker.get_referrer_kind(referrer), ResolutionMode::Import,
NodeResolutionMode::Execution, NodeResolutionKind::Execution,
) )
.with_context(|| { .with_context(|| {
format!("Could not resolve '{}'.", module.nv_reference) format!("Could not resolve '{}'.", module.nv_reference)
@ -806,7 +803,7 @@ impl<TGraphContainer: ModuleGraphContainer> ModuleLoader
&self, &self,
specifier: &str, specifier: &str,
referrer: &str, referrer: &str,
_kind: ResolutionKind, _kind: deno_core::ResolutionKind,
) -> Result<ModuleSpecifier, AnyError> { ) -> Result<ModuleSpecifier, AnyError> {
fn ensure_not_jsr_non_jsr_remote_import( fn ensure_not_jsr_non_jsr_remote_import(
specifier: &ModuleSpecifier, specifier: &ModuleSpecifier,

View file

@ -12,7 +12,6 @@ use deno_core::error::AnyError;
use deno_core::url::Url; use deno_core::url::Url;
use deno_core::ModuleSourceCode; use deno_core::ModuleSourceCode;
use deno_core::ModuleSpecifier; use deno_core::ModuleSpecifier;
use deno_graph::source::ResolutionMode;
use deno_graph::source::ResolveError; use deno_graph::source::ResolveError;
use deno_graph::source::UnknownBuiltInNodeModuleError; use deno_graph::source::UnknownBuiltInNodeModuleError;
use deno_graph::NpmLoadError; use deno_graph::NpmLoadError;
@ -25,8 +24,8 @@ use deno_runtime::deno_fs::FileSystem;
use deno_runtime::deno_node::is_builtin_node_module; use deno_runtime::deno_node::is_builtin_node_module;
use deno_runtime::deno_node::DenoFsNodeResolverEnv; use deno_runtime::deno_node::DenoFsNodeResolverEnv;
use deno_semver::package::PackageReq; use deno_semver::package::PackageReq;
use node_resolver::NodeModuleKind; use node_resolver::NodeResolutionKind;
use node_resolver::NodeResolutionMode; use node_resolver::ResolutionMode;
use std::borrow::Cow; use std::borrow::Cow;
use std::path::Path; use std::path::Path;
use std::path::PathBuf; use std::path::PathBuf;
@ -247,25 +246,14 @@ impl CliResolver {
pub fn resolve( pub fn resolve(
&self, &self,
raw_specifier: &str, raw_specifier: &str,
referrer_range: &deno_graph::Range, referrer: &ModuleSpecifier,
referrer_kind: NodeModuleKind, referrer_range_start: deno_graph::Position,
mode: ResolutionMode, resolution_mode: ResolutionMode,
resolution_kind: NodeResolutionKind,
) -> Result<ModuleSpecifier, ResolveError> { ) -> Result<ModuleSpecifier, ResolveError> {
fn to_node_mode(mode: ResolutionMode) -> NodeResolutionMode {
match mode {
ResolutionMode::Execution => NodeResolutionMode::Execution,
ResolutionMode::Types => NodeResolutionMode::Types,
}
}
let resolution = self let resolution = self
.deno_resolver .deno_resolver
.resolve( .resolve(raw_specifier, referrer, resolution_mode, resolution_kind)
raw_specifier,
&referrer_range.specifier,
referrer_kind,
to_node_mode(mode),
)
.map_err(|err| match err.into_kind() { .map_err(|err| match err.into_kind() {
deno_resolver::DenoResolveErrorKind::MappedResolution( deno_resolver::DenoResolveErrorKind::MappedResolution(
mapped_resolution_error, mapped_resolution_error,
@ -291,10 +279,11 @@ impl CliResolver {
} => { } => {
if self.warned_pkgs.insert(reference.req().clone()) { if self.warned_pkgs.insert(reference.req().clone()) {
log::warn!( log::warn!(
"{} {}\n at {}", "{} {}\n at {}:{}",
colors::yellow("Warning"), colors::yellow("Warning"),
diagnostic, diagnostic,
referrer_range referrer,
referrer_range_start,
); );
} }
} }
@ -335,13 +324,10 @@ impl<'a> deno_graph::source::NpmResolver for WorkerCliNpmGraphResolver<'a> {
module_name: &str, module_name: &str,
range: &deno_graph::Range, range: &deno_graph::Range,
) { ) {
let deno_graph::Range { let start = range.range.start;
start, specifier, .. let specifier = &range.specifier;
} = range;
let line = start.line + 1;
let column = start.character + 1;
if !*DENO_DISABLE_PEDANTIC_NODE_WARNINGS { if !*DENO_DISABLE_PEDANTIC_NODE_WARNINGS {
log::warn!("{} 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.", colors::yellow("Warning")) log::warn!("{} Resolving \"{module_name}\" as \"node:{module_name}\" at {specifier}:{start}. If you want to use a built-in Node module, add a \"node:\" prefix.", colors::yellow("Warning"))
} }
} }

View file

@ -50,8 +50,8 @@ use deno_semver::npm::NpmPackageReqReference;
use import_map::parse_from_json; use import_map::parse_from_json;
use node_resolver::analyze::NodeCodeTranslator; use node_resolver::analyze::NodeCodeTranslator;
use node_resolver::errors::ClosestPkgJsonError; use node_resolver::errors::ClosestPkgJsonError;
use node_resolver::NodeModuleKind; use node_resolver::NodeResolutionKind;
use node_resolver::NodeResolutionMode; use node_resolver::ResolutionMode;
use serialization::DenoCompileModuleSource; use serialization::DenoCompileModuleSource;
use std::borrow::Cow; use std::borrow::Cow;
use std::rc::Rc; use std::rc::Rc;
@ -193,9 +193,9 @@ impl ModuleLoader for EmbeddedModuleLoader {
.cjs_tracker .cjs_tracker
.is_maybe_cjs(&referrer, MediaType::from_specifier(&referrer))? .is_maybe_cjs(&referrer, MediaType::from_specifier(&referrer))?
{ {
NodeModuleKind::Cjs ResolutionMode::Require
} else { } else {
NodeModuleKind::Esm ResolutionMode::Import
}; };
if self.shared.node_resolver.in_npm_package(&referrer) { if self.shared.node_resolver.in_npm_package(&referrer) {
@ -207,7 +207,7 @@ impl ModuleLoader for EmbeddedModuleLoader {
raw_specifier, raw_specifier,
&referrer, &referrer,
referrer_kind, referrer_kind,
NodeResolutionMode::Execution, NodeResolutionKind::Execution,
)? )?
.into_url(), .into_url(),
); );
@ -235,7 +235,7 @@ impl ModuleLoader for EmbeddedModuleLoader {
sub_path.as_deref(), sub_path.as_deref(),
Some(&referrer), Some(&referrer),
referrer_kind, referrer_kind,
NodeResolutionMode::Execution, NodeResolutionKind::Execution,
)?, )?,
), ),
Ok(MappedResolution::PackageJson { Ok(MappedResolution::PackageJson {
@ -252,7 +252,7 @@ impl ModuleLoader for EmbeddedModuleLoader {
sub_path.as_deref(), sub_path.as_deref(),
&referrer, &referrer,
referrer_kind, referrer_kind,
NodeResolutionMode::Execution, NodeResolutionKind::Execution,
) )
.map_err(AnyError::from), .map_err(AnyError::from),
PackageJsonDepValue::Workspace(version_req) => { PackageJsonDepValue::Workspace(version_req) => {
@ -272,7 +272,7 @@ impl ModuleLoader for EmbeddedModuleLoader {
sub_path.as_deref(), sub_path.as_deref(),
Some(&referrer), Some(&referrer),
referrer_kind, referrer_kind,
NodeResolutionMode::Execution, NodeResolutionKind::Execution,
)?, )?,
) )
} }
@ -286,7 +286,7 @@ impl ModuleLoader for EmbeddedModuleLoader {
&reference, &reference,
&referrer, &referrer,
referrer_kind, referrer_kind,
NodeResolutionMode::Execution, NodeResolutionKind::Execution,
)?); )?);
} }
@ -313,7 +313,7 @@ impl ModuleLoader for EmbeddedModuleLoader {
raw_specifier, raw_specifier,
&referrer, &referrer,
referrer_kind, referrer_kind,
NodeResolutionMode::Execution, NodeResolutionKind::Execution,
)?; )?;
if let Some(res) = maybe_res { if let Some(res) = maybe_res {
return Ok(res.into_url()); return Ok(res.into_url());

View file

@ -427,33 +427,7 @@ fn generate_docs_directory(
symbol_redirect_map, symbol_redirect_map,
default_symbol_map, default_symbol_map,
markdown_renderer: deno_doc::html::comrak::create_renderer( markdown_renderer: deno_doc::html::comrak::create_renderer(
None, None, None, None,
Some(Box::new(|ammonia| {
ammonia.add_allowed_classes(
"code",
&[
"language-ts",
"language-tsx",
"language-typescript",
"language-js",
"language-jsx",
"language-javascript",
"language-bash",
"language-shell",
"language-md",
"language-markdown",
"language-rs",
"language-rust",
"language-html",
"language-xml",
"language-css",
"language-json",
"language-regex",
"language-svg",
],
);
})),
None,
), ),
markdown_stripper: Rc::new(deno_doc::html::comrak::strip), markdown_stripper: Rc::new(deno_doc::html::comrak::strip),
head_inject: Some(Rc::new(|root| { head_inject: Some(Rc::new(|root| {

View file

@ -235,22 +235,31 @@ fn add_npm_packages_to_json(
.get_mut("dependencies") .get_mut("dependencies")
.and_then(|d| d.as_array_mut()); .and_then(|d| d.as_array_mut());
if let Some(dependencies) = dependencies { if let Some(dependencies) = dependencies {
for dep in dependencies.iter_mut() { for dep in dependencies.iter_mut().flat_map(|d| d.as_object_mut()) {
if let serde_json::Value::Object(dep) = dep { if let Some(specifier) = dep.get("specifier").and_then(|s| s.as_str())
let specifier = dep.get("specifier").and_then(|s| s.as_str()); {
if let Some(specifier) = specifier { if let Ok(npm_ref) = NpmPackageReqReference::from_str(specifier) {
if let Ok(npm_ref) = NpmPackageReqReference::from_str(specifier) { if let Ok(pkg) = snapshot.resolve_pkg_from_pkg_req(npm_ref.req())
if let Ok(pkg) = {
snapshot.resolve_pkg_from_pkg_req(npm_ref.req()) dep.insert(
{ "npmPackage".to_string(),
dep.insert( pkg.id.as_serialized().into(),
"npmPackage".to_string(), );
pkg.id.as_serialized().into(),
);
}
} }
} }
} }
// don't show this in the output unless someone needs it
if let Some(code) =
dep.get_mut("code").and_then(|c| c.as_object_mut())
{
code.remove("resolutionMode");
}
if let Some(types) =
dep.get_mut("types").and_then(|c| c.as_object_mut())
{
types.remove("resolutionMode");
}
} }
} }
} }

View file

@ -8,7 +8,7 @@ use std::sync::Arc;
use deno_ast::SourceRange; use deno_ast::SourceRange;
use deno_config::workspace::WorkspaceResolver; use deno_config::workspace::WorkspaceResolver;
use deno_core::anyhow::anyhow; use deno_core::anyhow::anyhow;
use deno_graph::source::ResolutionMode; use deno_graph::source::ResolutionKind;
use deno_graph::source::ResolveError; use deno_graph::source::ResolveError;
use deno_graph::Range; use deno_graph::Range;
use deno_lint::diagnostic::LintDiagnosticDetails; use deno_lint::diagnostic::LintDiagnosticDetails;
@ -17,7 +17,7 @@ use deno_lint::diagnostic::LintFix;
use deno_lint::diagnostic::LintFixChange; use deno_lint::diagnostic::LintFixChange;
use deno_lint::rules::LintRule; use deno_lint::rules::LintRule;
use deno_resolver::sloppy_imports::SloppyImportsResolution; use deno_resolver::sloppy_imports::SloppyImportsResolution;
use deno_resolver::sloppy_imports::SloppyImportsResolutionMode; use deno_resolver::sloppy_imports::SloppyImportsResolutionKind;
use text_lines::LineAndColumnIndex; use text_lines::LineAndColumnIndex;
use crate::graph_util::CliJsrUrlProvider; use crate::graph_util::CliJsrUrlProvider;
@ -101,16 +101,16 @@ impl LintRule for NoSloppyImportsRule {
maybe_npm_resolver: None, maybe_npm_resolver: None,
}); });
for (range, sloppy_import) in resolver.captures.borrow_mut().drain() { for (referrer, sloppy_import) in resolver.captures.borrow_mut().drain() {
let start_range = let start_range =
context.text_info().loc_to_source_pos(LineAndColumnIndex { context.text_info().loc_to_source_pos(LineAndColumnIndex {
line_index: range.start.line, line_index: referrer.range.start.line,
column_index: range.start.character, column_index: referrer.range.start.character,
}); });
let end_range = let end_range =
context.text_info().loc_to_source_pos(LineAndColumnIndex { context.text_info().loc_to_source_pos(LineAndColumnIndex {
line_index: range.end.line, line_index: referrer.range.end.line,
column_index: range.end.character, column_index: referrer.range.end.character,
}); });
let source_range = SourceRange::new(start_range, end_range); let source_range = SourceRange::new(start_range, end_range);
context.add_diagnostic_details( context.add_diagnostic_details(
@ -183,7 +183,7 @@ impl<'a> deno_graph::source::Resolver for SloppyImportCaptureResolver<'a> {
&self, &self,
specifier_text: &str, specifier_text: &str,
referrer_range: &Range, referrer_range: &Range,
mode: ResolutionMode, resolution_kind: ResolutionKind,
) -> Result<deno_ast::ModuleSpecifier, deno_graph::source::ResolveError> { ) -> Result<deno_ast::ModuleSpecifier, deno_graph::source::ResolveError> {
let resolution = self let resolution = self
.workspace_resolver .workspace_resolver
@ -198,9 +198,9 @@ impl<'a> deno_graph::source::Resolver for SloppyImportCaptureResolver<'a> {
specifier, .. specifier, ..
} => match self.sloppy_imports_resolver.resolve( } => match self.sloppy_imports_resolver.resolve(
&specifier, &specifier,
match mode { match resolution_kind {
ResolutionMode::Execution => SloppyImportsResolutionMode::Execution, ResolutionKind::Execution => SloppyImportsResolutionKind::Execution,
ResolutionMode::Types => SloppyImportsResolutionMode::Types, ResolutionKind::Types => SloppyImportsResolutionKind::Types,
}, },
) { ) {
Some(res) => { Some(res) => {

View file

@ -234,8 +234,8 @@ impl Diagnostic for PublishDiagnostic {
specifier: Cow::Borrowed(&referrer.specifier), specifier: Cow::Borrowed(&referrer.specifier),
text_info: Cow::Borrowed(text_info), text_info: Cow::Borrowed(text_info),
source_pos: DiagnosticSourcePos::LineAndCol { source_pos: DiagnosticSourcePos::LineAndCol {
line: referrer.start.line, line: referrer.range.start.line,
column: referrer.start.character, column: referrer.range.start.character,
}, },
} }
} }
@ -300,7 +300,7 @@ impl Diagnostic for PublishDiagnostic {
text_info: &'a SourceTextInfo, text_info: &'a SourceTextInfo,
referrer: &'a deno_graph::Range, referrer: &'a deno_graph::Range,
) -> Option<DiagnosticSnippet<'a>> { ) -> Option<DiagnosticSnippet<'a>> {
if referrer.start.line == 0 && referrer.start.character == 0 { if referrer.range.start.line == 0 && referrer.range.start.character == 0 {
return None; // no range, probably a jsxImportSource import return None; // no range, probably a jsxImportSource import
} }
@ -310,12 +310,12 @@ impl Diagnostic for PublishDiagnostic {
style: DiagnosticSnippetHighlightStyle::Error, style: DiagnosticSnippetHighlightStyle::Error,
range: DiagnosticSourceRange { range: DiagnosticSourceRange {
start: DiagnosticSourcePos::LineAndCol { start: DiagnosticSourcePos::LineAndCol {
line: referrer.start.line, line: referrer.range.start.line,
column: referrer.start.character, column: referrer.range.start.character,
}, },
end: DiagnosticSourcePos::LineAndCol { end: DiagnosticSourcePos::LineAndCol {
line: referrer.end.line, line: referrer.range.end.line,
column: referrer.end.character, column: referrer.range.end.character,
}, },
}, },
description: Some("the specifier".into()), description: Some("the specifier".into()),

View file

@ -12,7 +12,7 @@ use deno_graph::DynamicTemplatePart;
use deno_graph::ParserModuleAnalyzer; use deno_graph::ParserModuleAnalyzer;
use deno_graph::TypeScriptReference; use deno_graph::TypeScriptReference;
use deno_package_json::PackageJsonDepValue; use deno_package_json::PackageJsonDepValue;
use deno_resolver::sloppy_imports::SloppyImportsResolutionMode; use deno_resolver::sloppy_imports::SloppyImportsResolutionKind;
use deno_runtime::deno_node::is_builtin_node_module; use deno_runtime::deno_node::is_builtin_node_module;
use crate::resolver::CliSloppyImportsResolver; use crate::resolver::CliSloppyImportsResolver;
@ -180,7 +180,7 @@ impl SpecifierUnfurler {
let resolved = let resolved =
if let Some(sloppy_imports_resolver) = &self.sloppy_imports_resolver { if let Some(sloppy_imports_resolver) = &self.sloppy_imports_resolver {
sloppy_imports_resolver sloppy_imports_resolver
.resolve(&resolved, SloppyImportsResolutionMode::Execution) .resolve(&resolved, SloppyImportsResolutionKind::Execution)
.map(|res| res.into_specifier()) .map(|res| res.into_specifier())
.unwrap_or(resolved) .unwrap_or(resolved)
} else { } else {
@ -319,8 +319,8 @@ impl SpecifierUnfurler {
} }
for ts_ref in &module_info.ts_references { for ts_ref in &module_info.ts_references {
let specifier_with_range = match ts_ref { let specifier_with_range = match ts_ref {
TypeScriptReference::Path(range) => range, TypeScriptReference::Path(s) => s,
TypeScriptReference::Types(range) => range, TypeScriptReference::Types { specifier, .. } => specifier,
}; };
analyze_specifier( analyze_specifier(
&specifier_with_range.text, &specifier_with_range.text,
@ -328,10 +328,10 @@ impl SpecifierUnfurler {
&mut text_changes, &mut text_changes,
); );
} }
for specifier_with_range in &module_info.jsdoc_imports { for jsdoc in &module_info.jsdoc_imports {
analyze_specifier( analyze_specifier(
&specifier_with_range.text, &jsdoc.specifier.text,
&specifier_with_range.range, &jsdoc.specifier.range,
&mut text_changes, &mut text_changes,
); );
} }

View file

@ -43,13 +43,13 @@ use deno_core::unsync::spawn;
use deno_core::url::Url; use deno_core::url::Url;
use deno_core::LocalInspectorSession; use deno_core::LocalInspectorSession;
use deno_core::PollEventLoopOptions; use deno_core::PollEventLoopOptions;
use deno_graph::source::ResolutionMode;
use deno_graph::Position; use deno_graph::Position;
use deno_graph::PositionRange; use deno_graph::PositionRange;
use deno_graph::SpecifierWithRange; use deno_graph::SpecifierWithRange;
use deno_runtime::worker::MainWorker; use deno_runtime::worker::MainWorker;
use deno_semver::npm::NpmPackageReqReference; use deno_semver::npm::NpmPackageReqReference;
use node_resolver::NodeModuleKind; use node_resolver::NodeResolutionKind;
use node_resolver::ResolutionMode;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Match; use regex::Match;
use regex::Regex; use regex::Regex;
@ -701,11 +701,6 @@ impl ReplSession {
let mut collector = ImportCollector::new(); let mut collector = ImportCollector::new();
program.visit_with(&mut collector); program.visit_with(&mut collector);
let referrer_range = deno_graph::Range {
specifier: self.referrer.clone(),
start: deno_graph::Position::zeroed(),
end: deno_graph::Position::zeroed(),
};
let resolved_imports = collector let resolved_imports = collector
.imports .imports
.iter() .iter()
@ -714,9 +709,10 @@ impl ReplSession {
.resolver .resolver
.resolve( .resolve(
i, i,
&referrer_range, &self.referrer,
NodeModuleKind::Esm, deno_graph::Position::zeroed(),
ResolutionMode::Execution, ResolutionMode::Import,
NodeResolutionKind::Execution,
) )
.ok() .ok()
.or_else(|| ModuleSpecifier::parse(i).ok()) .or_else(|| ModuleSpecifier::parse(i).ok())

View file

@ -681,14 +681,18 @@ delete Object.prototype.__proto__;
getNewLine() { getNewLine() {
return "\n"; return "\n";
}, },
resolveTypeReferenceDirectives( resolveTypeReferenceDirectiveReferences(
typeDirectiveNames, typeDirectiveReferences,
containingFilePath, containingFilePath,
redirectedReference, redirectedReference,
options, options,
containingFileMode, containingSourceFile,
_reusedNames,
) { ) {
return typeDirectiveNames.map((arg) => { const isCjs =
containingSourceFile?.impliedNodeFormat === ts.ModuleKind.CommonJS;
/** @type {Array<ts.ResolvedTypeReferenceDirectiveWithFailedLookupLocations>} */
const result = typeDirectiveReferences.map((arg) => {
/** @type {ts.FileReference} */ /** @type {ts.FileReference} */
const fileReference = typeof arg === "string" const fileReference = typeof arg === "string"
? { ? {
@ -701,16 +705,28 @@ delete Object.prototype.__proto__;
/** @type {[string, ts.Extension] | undefined} */ /** @type {[string, ts.Extension] | undefined} */
const resolved = ops.op_resolve( const resolved = ops.op_resolve(
containingFilePath, containingFilePath,
containingFileMode === ts.ModuleKind.CommonJS, [
[fileReference.fileName], [
fileReference.resolutionMode == null
? isCjs
: fileReference.resolutionMode === ts.ModuleKind.CommonJS,
fileReference.fileName,
],
],
)?.[0]; )?.[0];
if (resolved) { if (resolved) {
return { return {
primary: true, resolvedTypeReferenceDirective: {
resolvedFileName: resolved[0], primary: true,
resolvedFileName: resolved[0],
// todo(dsherret): we should probably be setting this
isExternalLibraryImport: undefined,
},
}; };
} else { } else {
return undefined; return {
resolvedTypeReferenceDirective: undefined,
};
} }
} else { } else {
return ts.resolveTypeReferenceDirective( return ts.resolveTypeReferenceDirective(
@ -720,41 +736,56 @@ delete Object.prototype.__proto__;
host, host,
redirectedReference, redirectedReference,
undefined, undefined,
containingFileMode ?? fileReference.resolutionMode, containingSourceFile?.impliedNodeFormat ??
).resolvedTypeReferenceDirective; fileReference.resolutionMode,
);
} }
}); });
return result;
}, },
resolveModuleNames( resolveModuleNameLiterals(
specifiers, moduleLiterals,
base, base,
_reusedNames,
_redirectedReference, _redirectedReference,
_options, compilerOptions,
containingSourceFile, containingSourceFile,
_reusedNames,
) { ) {
const specifiers = moduleLiterals.map((literal) => [
ts.getModeForUsageLocation(
containingSourceFile,
literal,
compilerOptions,
) === ts.ModuleKind.CommonJS,
literal.text,
]);
if (logDebug) { if (logDebug) {
debug(`host.resolveModuleNames()`); debug(`host.resolveModuleNames()`);
debug(` base: ${base}`); debug(` base: ${base}`);
debug(` specifiers: ${specifiers.join(", ")}`); debug(` specifiers: ${specifiers.map((s) => s[1]).join(", ")}`);
} }
/** @type {Array<[string, ts.Extension] | undefined>} */ /** @type {Array<[string, ts.Extension] | undefined>} */
const resolved = ops.op_resolve( const resolved = ops.op_resolve(
base, base,
containingSourceFile?.impliedNodeFormat === ts.ModuleKind.CommonJS,
specifiers, specifiers,
); );
if (resolved) { if (resolved) {
/** @type {Array<ts.ResolvedModuleWithFailedLookupLocations>} */
const result = resolved.map((item) => { const result = resolved.map((item) => {
if (item) { if (item) {
const [resolvedFileName, extension] = item; const [resolvedFileName, extension] = item;
return { return {
resolvedFileName, resolvedModule: {
extension, resolvedFileName,
isExternalLibraryImport: false, extension,
// todo(dsherret): we should probably be setting this
isExternalLibraryImport: false,
},
}; };
} }
return undefined; return {
resolvedModule: undefined,
};
}); });
result.length = specifiers.length; result.length = specifiers.length;
return result; return result;

View file

@ -41,8 +41,8 @@ use deno_semver::npm::NpmPackageReqReference;
use node_resolver::errors::NodeJsErrorCode; use node_resolver::errors::NodeJsErrorCode;
use node_resolver::errors::NodeJsErrorCoded; use node_resolver::errors::NodeJsErrorCoded;
use node_resolver::errors::PackageSubpathResolveError; use node_resolver::errors::PackageSubpathResolveError;
use node_resolver::NodeModuleKind; use node_resolver::NodeResolutionKind;
use node_resolver::NodeResolutionMode; use node_resolver::ResolutionMode;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use std::borrow::Cow; use std::borrow::Cow;
use std::collections::HashMap; use std::collections::HashMap;
@ -703,10 +703,9 @@ pub struct ResolveArgs {
/// The base specifier that the supplied specifier strings should be resolved /// The base specifier that the supplied specifier strings should be resolved
/// relative to. /// relative to.
pub base: String, pub base: String,
/// If the base is cjs.
pub is_base_cjs: bool,
/// A list of specifiers that should be resolved. /// A list of specifiers that should be resolved.
pub specifiers: Vec<String>, /// (is_cjs: bool, raw_specifier: String)
pub specifiers: Vec<(bool, String)>,
} }
#[op2] #[op2]
@ -714,17 +713,9 @@ pub struct ResolveArgs {
fn op_resolve( fn op_resolve(
state: &mut OpState, state: &mut OpState,
#[string] base: String, #[string] base: String,
is_base_cjs: bool, #[serde] specifiers: Vec<(bool, String)>,
#[serde] specifiers: Vec<String>,
) -> Result<Vec<(String, &'static str)>, AnyError> { ) -> Result<Vec<(String, &'static str)>, AnyError> {
op_resolve_inner( op_resolve_inner(state, ResolveArgs { base, specifiers })
state,
ResolveArgs {
base,
is_base_cjs,
specifiers,
},
)
} }
#[inline] #[inline]
@ -735,11 +726,6 @@ fn op_resolve_inner(
let state = state.borrow_mut::<State>(); let state = state.borrow_mut::<State>();
let mut resolved: Vec<(String, &'static str)> = let mut resolved: Vec<(String, &'static str)> =
Vec::with_capacity(args.specifiers.len()); Vec::with_capacity(args.specifiers.len());
let referrer_kind = if args.is_base_cjs {
NodeModuleKind::Cjs
} else {
NodeModuleKind::Esm
};
let referrer = if let Some(remapped_specifier) = let referrer = if let Some(remapped_specifier) =
state.remapped_specifiers.get(&args.base) state.remapped_specifiers.get(&args.base)
{ {
@ -752,7 +738,7 @@ fn op_resolve_inner(
)? )?
}; };
let referrer_module = state.graph.get(&referrer); let referrer_module = state.graph.get(&referrer);
for specifier in args.specifiers { for (is_cjs, specifier) in args.specifiers {
if specifier.starts_with("node:") { if specifier.starts_with("node:") {
resolved.push(( resolved.push((
MISSING_DEPENDENCY_SPECIFIER.to_string(), MISSING_DEPENDENCY_SPECIFIER.to_string(),
@ -771,13 +757,20 @@ fn op_resolve_inner(
.and_then(|m| m.js()) .and_then(|m| m.js())
.and_then(|m| m.dependencies_prefer_fast_check().get(&specifier)) .and_then(|m| m.dependencies_prefer_fast_check().get(&specifier))
.and_then(|d| d.maybe_type.ok().or_else(|| d.maybe_code.ok())); .and_then(|d| d.maybe_type.ok().or_else(|| d.maybe_code.ok()));
let resolution_mode = if is_cjs {
ResolutionMode::Require
} else {
ResolutionMode::Import
};
let maybe_result = match resolved_dep { let maybe_result = match resolved_dep {
Some(ResolutionResolved { specifier, .. }) => { Some(ResolutionResolved { specifier, .. }) => {
resolve_graph_specifier_types( resolve_graph_specifier_types(
specifier, specifier,
&referrer, &referrer,
referrer_kind, // we could get this from the resolved dep, but for now assume
// the value resolved in TypeScript is better
resolution_mode,
state, state,
)? )?
} }
@ -785,7 +778,7 @@ fn op_resolve_inner(
match resolve_non_graph_specifier_types( match resolve_non_graph_specifier_types(
&specifier, &specifier,
&referrer, &referrer,
referrer_kind, resolution_mode,
state, state,
) { ) {
Ok(maybe_result) => maybe_result, Ok(maybe_result) => maybe_result,
@ -852,7 +845,7 @@ fn op_resolve_inner(
fn resolve_graph_specifier_types( fn resolve_graph_specifier_types(
specifier: &ModuleSpecifier, specifier: &ModuleSpecifier,
referrer: &ModuleSpecifier, referrer: &ModuleSpecifier,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
state: &State, state: &State,
) -> Result<Option<(ModuleSpecifier, MediaType)>, AnyError> { ) -> Result<Option<(ModuleSpecifier, MediaType)>, AnyError> {
let graph = &state.graph; let graph = &state.graph;
@ -908,8 +901,8 @@ fn resolve_graph_specifier_types(
&package_folder, &package_folder,
module.nv_reference.sub_path(), module.nv_reference.sub_path(),
Some(referrer), Some(referrer),
referrer_kind, resolution_mode,
NodeResolutionMode::Types, NodeResolutionKind::Types,
); );
let maybe_url = match res_result { let maybe_url = match res_result {
Ok(url) => Some(url), Ok(url) => Some(url),
@ -949,7 +942,7 @@ enum ResolveNonGraphSpecifierTypesError {
fn resolve_non_graph_specifier_types( fn resolve_non_graph_specifier_types(
raw_specifier: &str, raw_specifier: &str,
referrer: &ModuleSpecifier, referrer: &ModuleSpecifier,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
state: &State, state: &State,
) -> Result< ) -> Result<
Option<(ModuleSpecifier, MediaType)>, Option<(ModuleSpecifier, MediaType)>,
@ -967,8 +960,8 @@ fn resolve_non_graph_specifier_types(
.resolve( .resolve(
raw_specifier, raw_specifier,
referrer, referrer,
referrer_kind, resolution_mode,
NodeResolutionMode::Types, NodeResolutionKind::Types,
) )
.ok() .ok()
.map(|res| res.into_url()), .map(|res| res.into_url()),
@ -976,7 +969,7 @@ fn resolve_non_graph_specifier_types(
} else if let Ok(npm_req_ref) = } else if let Ok(npm_req_ref) =
NpmPackageReqReference::from_str(raw_specifier) NpmPackageReqReference::from_str(raw_specifier)
{ {
debug_assert_eq!(referrer_kind, NodeModuleKind::Esm); debug_assert_eq!(resolution_mode, ResolutionMode::Import);
// todo(dsherret): add support for injecting this in the graph so // todo(dsherret): add support for injecting this in the graph so
// we don't need this special code here. // we don't need this special code here.
// This could occur when resolving npm:@types/node when it is // This could occur when resolving npm:@types/node when it is
@ -988,8 +981,8 @@ fn resolve_non_graph_specifier_types(
&package_folder, &package_folder,
npm_req_ref.sub_path(), npm_req_ref.sub_path(),
Some(referrer), Some(referrer),
referrer_kind, resolution_mode,
NodeResolutionMode::Types, NodeResolutionKind::Types,
); );
let maybe_url = match res_result { let maybe_url = match res_result {
Ok(url) => Some(url), Ok(url) => Some(url),
@ -1388,8 +1381,7 @@ mod tests {
&mut state, &mut state,
ResolveArgs { ResolveArgs {
base: "https://deno.land/x/a.ts".to_string(), base: "https://deno.land/x/a.ts".to_string(),
is_base_cjs: false, specifiers: vec![(false, "./b.ts".to_string())],
specifiers: vec!["./b.ts".to_string()],
}, },
) )
.expect("should have invoked op"); .expect("should have invoked op");
@ -1408,8 +1400,7 @@ mod tests {
&mut state, &mut state,
ResolveArgs { ResolveArgs {
base: "https://deno.land/x/a.ts".to_string(), base: "https://deno.land/x/a.ts".to_string(),
is_base_cjs: false, specifiers: vec![(false, "./bad.ts".to_string())],
specifiers: vec!["./bad.ts".to_string()],
}, },
) )
.expect("should have not errored"); .expect("should have not errored");

View file

@ -44,8 +44,8 @@ use deno_runtime::WorkerLogLevel;
use deno_semver::npm::NpmPackageReqReference; use deno_semver::npm::NpmPackageReqReference;
use deno_telemetry::OtelConfig; use deno_telemetry::OtelConfig;
use deno_terminal::colors; use deno_terminal::colors;
use node_resolver::NodeModuleKind; use node_resolver::NodeResolutionKind;
use node_resolver::NodeResolutionMode; use node_resolver::ResolutionMode;
use tokio::select; use tokio::select;
use crate::args::CliLockfile; use crate::args::CliLockfile;
@ -698,8 +698,8 @@ impl CliMainWorkerFactory {
package_folder, package_folder,
sub_path, sub_path,
/* referrer */ None, /* referrer */ None,
NodeModuleKind::Esm, ResolutionMode::Import,
NodeResolutionMode::Execution, NodeResolutionKind::Execution,
)?; )?;
if specifier if specifier
.to_file_path() .to_file_path()

View file

@ -8,13 +8,13 @@ use deno_core::v8;
use deno_core::JsRuntimeInspector; use deno_core::JsRuntimeInspector;
use deno_core::OpState; use deno_core::OpState;
use deno_fs::FileSystemRc; use deno_fs::FileSystemRc;
use deno_package_json::NodeModuleKind;
use deno_package_json::PackageJsonRc; use deno_package_json::PackageJsonRc;
use deno_path_util::normalize_path; use deno_path_util::normalize_path;
use deno_path_util::url_from_file_path; use deno_path_util::url_from_file_path;
use deno_path_util::url_to_file_path; use deno_path_util::url_to_file_path;
use node_resolver::errors::ClosestPkgJsonError; use node_resolver::errors::ClosestPkgJsonError;
use node_resolver::NodeResolutionMode; use node_resolver::NodeResolutionKind;
use node_resolver::ResolutionMode;
use node_resolver::REQUIRE_CONDITIONS; use node_resolver::REQUIRE_CONDITIONS;
use std::borrow::Cow; use std::borrow::Cow;
use std::cell::RefCell; use std::cell::RefCell;
@ -462,9 +462,9 @@ where
&expansion, &expansion,
exports, exports,
Some(&referrer), Some(&referrer),
NodeModuleKind::Cjs, ResolutionMode::Require,
REQUIRE_CONDITIONS, REQUIRE_CONDITIONS,
NodeResolutionMode::Execution, NodeResolutionKind::Execution,
)?; )?;
Ok(Some(if r.scheme() == "file" { Ok(Some(if r.scheme() == "file" {
url_to_file_path_string(&r)? url_to_file_path_string(&r)?
@ -559,9 +559,9 @@ where
&format!(".{expansion}"), &format!(".{expansion}"),
exports, exports,
referrer.as_ref(), referrer.as_ref(),
NodeModuleKind::Cjs, ResolutionMode::Require,
REQUIRE_CONDITIONS, REQUIRE_CONDITIONS,
NodeResolutionMode::Execution, NodeResolutionKind::Execution,
)?; )?;
Ok(Some(if r.scheme() == "file" { Ok(Some(if r.scheme() == "file" {
url_to_file_path_string(&r)? url_to_file_path_string(&r)?
@ -630,10 +630,10 @@ where
let url = node_resolver.package_imports_resolve( let url = node_resolver.package_imports_resolve(
&request, &request,
Some(&referrer_url), Some(&referrer_url),
NodeModuleKind::Cjs, ResolutionMode::Require,
Some(&pkg), Some(&pkg),
REQUIRE_CONDITIONS, REQUIRE_CONDITIONS,
NodeResolutionMode::Execution, NodeResolutionKind::Execution,
)?; )?;
Ok(Some(url_to_file_path_string(&url)?)) Ok(Some(url_to_file_path_string(&url)?))
} else { } else {

View file

@ -7,8 +7,8 @@ use deno_media_type::MediaType;
use node_resolver::env::NodeResolverEnv; use node_resolver::env::NodeResolverEnv;
use node_resolver::errors::ClosestPkgJsonError; use node_resolver::errors::ClosestPkgJsonError;
use node_resolver::InNpmPackageChecker; use node_resolver::InNpmPackageChecker;
use node_resolver::NodeModuleKind;
use node_resolver::PackageJsonResolver; use node_resolver::PackageJsonResolver;
use node_resolver::ResolutionMode;
use url::Url; use url::Url;
/// Keeps track of what module specifiers were resolved as CJS. /// Keeps track of what module specifiers were resolved as CJS.
@ -19,7 +19,7 @@ use url::Url;
#[derive(Debug)] #[derive(Debug)]
pub struct CjsTracker<TEnv: NodeResolverEnv> { pub struct CjsTracker<TEnv: NodeResolverEnv> {
is_cjs_resolver: IsCjsResolver<TEnv>, is_cjs_resolver: IsCjsResolver<TEnv>,
known: DashMap<Url, NodeModuleKind>, known: DashMap<Url, ResolutionMode>,
} }
impl<TEnv: NodeResolverEnv> CjsTracker<TEnv> { impl<TEnv: NodeResolverEnv> CjsTracker<TEnv> {
@ -70,42 +70,42 @@ impl<TEnv: NodeResolverEnv> CjsTracker<TEnv> {
is_script: Option<bool>, is_script: Option<bool>,
) -> Result<bool, ClosestPkgJsonError> { ) -> Result<bool, ClosestPkgJsonError> {
let kind = match self let kind = match self
.get_known_kind_with_is_script(specifier, media_type, is_script) .get_known_mode_with_is_script(specifier, media_type, is_script)
{ {
Some(kind) => kind, Some(kind) => kind,
None => self.is_cjs_resolver.check_based_on_pkg_json(specifier)?, None => self.is_cjs_resolver.check_based_on_pkg_json(specifier)?,
}; };
Ok(kind == NodeModuleKind::Cjs) Ok(kind == ResolutionMode::Require)
} }
/// Gets the referrer for the specified module specifier. /// Gets the referrer for the specified module specifier.
/// ///
/// Generally the referrer should already be tracked by calling /// Generally the referrer should already be tracked by calling
/// `is_cjs_with_known_is_script` before calling this method. /// `is_cjs_with_known_is_script` before calling this method.
pub fn get_referrer_kind(&self, specifier: &Url) -> NodeModuleKind { pub fn get_referrer_kind(&self, specifier: &Url) -> ResolutionMode {
if specifier.scheme() != "file" { if specifier.scheme() != "file" {
return NodeModuleKind::Esm; return ResolutionMode::Import;
} }
self self
.get_known_kind(specifier, MediaType::from_specifier(specifier)) .get_known_mode(specifier, MediaType::from_specifier(specifier))
.unwrap_or(NodeModuleKind::Esm) .unwrap_or(ResolutionMode::Import)
} }
fn get_known_kind( fn get_known_mode(
&self, &self,
specifier: &Url, specifier: &Url,
media_type: MediaType, media_type: MediaType,
) -> Option<NodeModuleKind> { ) -> Option<ResolutionMode> {
self.get_known_kind_with_is_script(specifier, media_type, None) self.get_known_mode_with_is_script(specifier, media_type, None)
} }
fn get_known_kind_with_is_script( fn get_known_mode_with_is_script(
&self, &self,
specifier: &Url, specifier: &Url,
media_type: MediaType, media_type: MediaType,
is_script: Option<bool>, is_script: Option<bool>,
) -> Option<NodeModuleKind> { ) -> Option<ResolutionMode> {
self.is_cjs_resolver.get_known_kind_with_is_script( self.is_cjs_resolver.get_known_mode_with_is_script(
specifier, specifier,
media_type, media_type,
is_script, is_script,
@ -141,25 +141,25 @@ impl<TEnv: NodeResolverEnv> IsCjsResolver<TEnv> {
} }
} }
/// Gets the referrer kind for a script in the LSP. /// Gets the resolution mode for a module in the LSP.
pub fn get_lsp_referrer_kind( pub fn get_lsp_resolution_mode(
&self, &self,
specifier: &Url, specifier: &Url,
is_script: Option<bool>, is_script: Option<bool>,
) -> NodeModuleKind { ) -> ResolutionMode {
if specifier.scheme() != "file" { if specifier.scheme() != "file" {
return NodeModuleKind::Esm; return ResolutionMode::Import;
} }
match MediaType::from_specifier(specifier) { match MediaType::from_specifier(specifier) {
MediaType::Mts | MediaType::Mjs | MediaType::Dmts => NodeModuleKind::Esm, MediaType::Mts | MediaType::Mjs | MediaType::Dmts => ResolutionMode::Import,
MediaType::Cjs | MediaType::Cts | MediaType::Dcts => NodeModuleKind::Cjs, MediaType::Cjs | MediaType::Cts | MediaType::Dcts => ResolutionMode::Require,
MediaType::Dts => { MediaType::Dts => {
// dts files are always determined based on the package.json because // dts files are always determined based on the package.json because
// they contain imports/exports even when considered CJS // they contain imports/exports even when considered CJS
self.check_based_on_pkg_json(specifier).unwrap_or(NodeModuleKind::Esm) self.check_based_on_pkg_json(specifier).unwrap_or(ResolutionMode::Import)
} }
MediaType::Wasm | MediaType::Wasm |
MediaType::Json => NodeModuleKind::Esm, MediaType::Json => ResolutionMode::Import,
MediaType::JavaScript MediaType::JavaScript
| MediaType::Jsx | MediaType::Jsx
| MediaType::TypeScript | MediaType::TypeScript
@ -169,27 +169,27 @@ impl<TEnv: NodeResolverEnv> IsCjsResolver<TEnv> {
| MediaType::SourceMap | MediaType::SourceMap
| MediaType::Unknown => { | MediaType::Unknown => {
match is_script { match is_script {
Some(true) => self.check_based_on_pkg_json(specifier).unwrap_or(NodeModuleKind::Esm), Some(true) => self.check_based_on_pkg_json(specifier).unwrap_or(ResolutionMode::Import),
Some(false) | None => NodeModuleKind::Esm, Some(false) | None => ResolutionMode::Import,
} }
} }
} }
} }
fn get_known_kind_with_is_script( fn get_known_mode_with_is_script(
&self, &self,
specifier: &Url, specifier: &Url,
media_type: MediaType, media_type: MediaType,
is_script: Option<bool>, is_script: Option<bool>,
known_cache: &DashMap<Url, NodeModuleKind>, known_cache: &DashMap<Url, ResolutionMode>,
) -> Option<NodeModuleKind> { ) -> Option<ResolutionMode> {
if specifier.scheme() != "file" { if specifier.scheme() != "file" {
return Some(NodeModuleKind::Esm); return Some(ResolutionMode::Import);
} }
match media_type { match media_type {
MediaType::Mts | MediaType::Mjs | MediaType::Dmts => Some(NodeModuleKind::Esm), MediaType::Mts | MediaType::Mjs | MediaType::Dmts => Some(ResolutionMode::Import),
MediaType::Cjs | MediaType::Cts | MediaType::Dcts => Some(NodeModuleKind::Cjs), MediaType::Cjs | MediaType::Cts | MediaType::Dcts => Some(ResolutionMode::Require),
MediaType::Dts => { MediaType::Dts => {
// dts files are always determined based on the package.json because // dts files are always determined based on the package.json because
// they contain imports/exports even when considered CJS // they contain imports/exports even when considered CJS
@ -200,11 +200,11 @@ impl<TEnv: NodeResolverEnv> IsCjsResolver<TEnv> {
if let Some(value) = value { if let Some(value) = value {
known_cache.insert(specifier.clone(), value); known_cache.insert(specifier.clone(), value);
} }
Some(value.unwrap_or(NodeModuleKind::Esm)) Some(value.unwrap_or(ResolutionMode::Import))
} }
} }
MediaType::Wasm | MediaType::Wasm |
MediaType::Json => Some(NodeModuleKind::Esm), MediaType::Json => Some(ResolutionMode::Import),
MediaType::JavaScript MediaType::JavaScript
| MediaType::Jsx | MediaType::Jsx
| MediaType::TypeScript | MediaType::TypeScript
@ -214,17 +214,17 @@ impl<TEnv: NodeResolverEnv> IsCjsResolver<TEnv> {
| MediaType::SourceMap | MediaType::SourceMap
| MediaType::Unknown => { | MediaType::Unknown => {
if let Some(value) = known_cache.get(specifier).map(|v| *v) { if let Some(value) = known_cache.get(specifier).map(|v| *v) {
if value == NodeModuleKind::Cjs && is_script == Some(false) { if value == ResolutionMode::Require && is_script == Some(false) {
// we now know this is actually esm // we now know this is actually esm
known_cache.insert(specifier.clone(), NodeModuleKind::Esm); known_cache.insert(specifier.clone(), ResolutionMode::Import);
Some(NodeModuleKind::Esm) Some(ResolutionMode::Import)
} else { } else {
Some(value) Some(value)
} }
} else if is_script == Some(false) { } else if is_script == Some(false) {
// we know this is esm // we know this is esm
known_cache.insert(specifier.clone(), NodeModuleKind::Esm); known_cache.insert(specifier.clone(), ResolutionMode::Import);
Some(NodeModuleKind::Esm) Some(ResolutionMode::Import)
} else { } else {
None None
} }
@ -235,19 +235,19 @@ impl<TEnv: NodeResolverEnv> IsCjsResolver<TEnv> {
fn check_based_on_pkg_json( fn check_based_on_pkg_json(
&self, &self,
specifier: &Url, specifier: &Url,
) -> Result<NodeModuleKind, ClosestPkgJsonError> { ) -> Result<ResolutionMode, ClosestPkgJsonError> {
if self.in_npm_pkg_checker.in_npm_package(specifier) { if self.in_npm_pkg_checker.in_npm_package(specifier) {
if let Some(pkg_json) = if let Some(pkg_json) =
self.pkg_json_resolver.get_closest_package_json(specifier)? self.pkg_json_resolver.get_closest_package_json(specifier)?
{ {
let is_file_location_cjs = pkg_json.typ != "module"; let is_file_location_cjs = pkg_json.typ != "module";
Ok(if is_file_location_cjs { Ok(if is_file_location_cjs {
NodeModuleKind::Cjs ResolutionMode::Require
} else { } else {
NodeModuleKind::Esm ResolutionMode::Import
}) })
} else { } else {
Ok(NodeModuleKind::Cjs) Ok(ResolutionMode::Require)
} }
} else if self.options.detect_cjs || self.options.is_node_main { } else if self.options.detect_cjs || self.options.is_node_main {
if let Some(pkg_json) = if let Some(pkg_json) =
@ -256,17 +256,17 @@ impl<TEnv: NodeResolverEnv> IsCjsResolver<TEnv> {
let is_cjs_type = pkg_json.typ == "commonjs" let is_cjs_type = pkg_json.typ == "commonjs"
|| self.options.is_node_main && pkg_json.typ == "none"; || self.options.is_node_main && pkg_json.typ == "none";
Ok(if is_cjs_type { Ok(if is_cjs_type {
NodeModuleKind::Cjs ResolutionMode::Require
} else { } else {
NodeModuleKind::Esm ResolutionMode::Import
}) })
} else if self.options.is_node_main { } else if self.options.is_node_main {
Ok(NodeModuleKind::Cjs) Ok(ResolutionMode::Require)
} else { } else {
Ok(NodeModuleKind::Esm) Ok(ResolutionMode::Import)
} }
} else { } else {
Ok(NodeModuleKind::Esm) Ok(ResolutionMode::Import)
} }
} }
} }

View file

@ -20,10 +20,10 @@ use node_resolver::env::NodeResolverEnv;
use node_resolver::errors::NodeResolveError; use node_resolver::errors::NodeResolveError;
use node_resolver::errors::PackageSubpathResolveError; use node_resolver::errors::PackageSubpathResolveError;
use node_resolver::InNpmPackageChecker; use node_resolver::InNpmPackageChecker;
use node_resolver::NodeModuleKind;
use node_resolver::NodeResolution; use node_resolver::NodeResolution;
use node_resolver::NodeResolutionMode; use node_resolver::NodeResolutionKind;
use node_resolver::NodeResolver; use node_resolver::NodeResolver;
use node_resolver::ResolutionMode;
use npm::MissingPackageNodeModulesFolderError; use npm::MissingPackageNodeModulesFolderError;
use npm::NodeModulesOutOfDateError; use npm::NodeModulesOutOfDateError;
use npm::NpmReqResolver; use npm::NpmReqResolver;
@ -31,7 +31,7 @@ use npm::ResolveIfForNpmPackageErrorKind;
use npm::ResolvePkgFolderFromDenoReqError; use npm::ResolvePkgFolderFromDenoReqError;
use npm::ResolveReqWithSubPathErrorKind; use npm::ResolveReqWithSubPathErrorKind;
use sloppy_imports::SloppyImportResolverFs; use sloppy_imports::SloppyImportResolverFs;
use sloppy_imports::SloppyImportsResolutionMode; use sloppy_imports::SloppyImportsResolutionKind;
use sloppy_imports::SloppyImportsResolver; use sloppy_imports::SloppyImportsResolver;
use thiserror::Error; use thiserror::Error;
use url::Url; use url::Url;
@ -145,8 +145,8 @@ impl<
&self, &self,
raw_specifier: &str, raw_specifier: &str,
referrer: &Url, referrer: &Url,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<DenoResolution, DenoResolveError> { ) -> Result<DenoResolution, DenoResolveError> {
let mut found_package_json_dep = false; let mut found_package_json_dep = false;
let mut maybe_diagnostic = None; let mut maybe_diagnostic = None;
@ -157,7 +157,7 @@ impl<
&& self.in_npm_pkg_checker.in_npm_package(referrer) && self.in_npm_pkg_checker.in_npm_package(referrer)
{ {
return node_resolver return node_resolver
.resolve(raw_specifier, referrer, referrer_kind, mode) .resolve(raw_specifier, referrer, resolution_mode, resolution_kind)
.map(|res| DenoResolution { .map(|res| DenoResolution {
url: res.into_url(), url: res.into_url(),
found_package_json_dep, found_package_json_dep,
@ -189,12 +189,12 @@ impl<
sloppy_imports_resolver sloppy_imports_resolver
.resolve( .resolve(
&specifier, &specifier,
match mode { match resolution_kind {
NodeResolutionMode::Execution => { NodeResolutionKind::Execution => {
SloppyImportsResolutionMode::Execution SloppyImportsResolutionKind::Execution
} }
NodeResolutionMode::Types => { NodeResolutionKind::Types => {
SloppyImportsResolutionMode::Types SloppyImportsResolutionKind::Types
} }
}, },
) )
@ -221,8 +221,8 @@ impl<
pkg_json.dir_path(), pkg_json.dir_path(),
sub_path.as_deref(), sub_path.as_deref(),
Some(referrer), Some(referrer),
referrer_kind, resolution_mode,
mode, resolution_kind,
) )
.map_err(|e| e.into()), .map_err(|e| e.into()),
MappedResolution::PackageJson { MappedResolution::PackageJson {
@ -272,8 +272,8 @@ impl<
pkg_folder, pkg_folder,
sub_path.as_deref(), sub_path.as_deref(),
Some(referrer), Some(referrer),
referrer_kind, resolution_mode,
mode, resolution_kind,
) )
.map_err(|e| { .map_err(|e| {
DenoResolveErrorKind::PackageSubpathResolve(e).into_box() DenoResolveErrorKind::PackageSubpathResolve(e).into_box()
@ -328,8 +328,8 @@ impl<
pkg_folder, pkg_folder,
npm_req_ref.sub_path(), npm_req_ref.sub_path(),
Some(referrer), Some(referrer),
referrer_kind, resolution_mode,
mode, resolution_kind,
) )
.map(|url| DenoResolution { .map(|url| DenoResolution {
url, url,
@ -345,8 +345,8 @@ impl<
.resolve_req_reference( .resolve_req_reference(
&npm_req_ref, &npm_req_ref,
referrer, referrer,
referrer_kind, resolution_mode,
mode, resolution_kind,
) )
.map(|url| DenoResolution { .map(|url| DenoResolution {
url, url,
@ -384,8 +384,8 @@ impl<
.resolve_if_for_npm_pkg( .resolve_if_for_npm_pkg(
raw_specifier, raw_specifier,
referrer, referrer,
referrer_kind, resolution_mode,
mode, resolution_kind,
) )
.map_err(|e| match e.into_kind() { .map_err(|e| match e.into_kind() {
ResolveIfForNpmPackageErrorKind::NodeResolve(e) => { ResolveIfForNpmPackageErrorKind::NodeResolve(e) => {

View file

@ -16,10 +16,10 @@ use node_resolver::errors::PackageNotFoundError;
use node_resolver::errors::PackageResolveErrorKind; use node_resolver::errors::PackageResolveErrorKind;
use node_resolver::errors::PackageSubpathResolveError; use node_resolver::errors::PackageSubpathResolveError;
use node_resolver::InNpmPackageChecker; use node_resolver::InNpmPackageChecker;
use node_resolver::NodeModuleKind;
use node_resolver::NodeResolution; use node_resolver::NodeResolution;
use node_resolver::NodeResolutionMode; use node_resolver::NodeResolutionKind;
use node_resolver::NodeResolver; use node_resolver::NodeResolver;
use node_resolver::ResolutionMode;
use thiserror::Error; use thiserror::Error;
use url::Url; use url::Url;
@ -132,15 +132,15 @@ impl<Fs: DenoResolverFs, TNodeResolverEnv: NodeResolverEnv>
&self, &self,
req_ref: &NpmPackageReqReference, req_ref: &NpmPackageReqReference,
referrer: &Url, referrer: &Url,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Url, ResolveReqWithSubPathError> { ) -> Result<Url, ResolveReqWithSubPathError> {
self.resolve_req_with_sub_path( self.resolve_req_with_sub_path(
req_ref.req(), req_ref.req(),
req_ref.sub_path(), req_ref.sub_path(),
referrer, referrer,
referrer_kind, resolution_mode,
mode, resolution_kind,
) )
} }
@ -149,8 +149,8 @@ impl<Fs: DenoResolverFs, TNodeResolverEnv: NodeResolverEnv>
req: &PackageReq, req: &PackageReq,
sub_path: Option<&str>, sub_path: Option<&str>,
referrer: &Url, referrer: &Url,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Url, ResolveReqWithSubPathError> { ) -> Result<Url, ResolveReqWithSubPathError> {
let package_folder = self let package_folder = self
.npm_resolver .npm_resolver
@ -160,8 +160,8 @@ impl<Fs: DenoResolverFs, TNodeResolverEnv: NodeResolverEnv>
&package_folder, &package_folder,
sub_path, sub_path,
Some(referrer), Some(referrer),
referrer_kind, resolution_mode,
mode, resolution_kind,
); );
match resolution_result { match resolution_result {
Ok(url) => Ok(url), Ok(url) => Ok(url),
@ -183,13 +183,15 @@ impl<Fs: DenoResolverFs, TNodeResolverEnv: NodeResolverEnv>
&self, &self,
specifier: &str, specifier: &str,
referrer: &Url, referrer: &Url,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Option<NodeResolution>, ResolveIfForNpmPackageError> { ) -> Result<Option<NodeResolution>, ResolveIfForNpmPackageError> {
let resolution_result = let resolution_result = self.node_resolver.resolve(
self specifier,
.node_resolver referrer,
.resolve(specifier, referrer, referrer_kind, mode); resolution_mode,
resolution_kind,
);
match resolution_result { match resolution_result {
Ok(res) => Ok(Some(res)), Ok(res) => Ok(Some(res)),
Err(err) => { Err(err) => {

View file

@ -80,16 +80,16 @@ impl SloppyImportsResolution {
/// The kind of resolution currently being done. /// The kind of resolution currently being done.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SloppyImportsResolutionMode { pub enum SloppyImportsResolutionKind {
/// Resolving for code that will be executed. /// Resolving for code that will be executed.
Execution, Execution,
/// Resolving for code that will be used for type information. /// Resolving for code that will be used for type information.
Types, Types,
} }
impl SloppyImportsResolutionMode { impl SloppyImportsResolutionKind {
pub fn is_types(&self) -> bool { pub fn is_types(&self) -> bool {
*self == SloppyImportsResolutionMode::Types *self == SloppyImportsResolutionKind::Types
} }
} }
@ -114,7 +114,7 @@ impl<Fs: SloppyImportResolverFs> SloppyImportsResolver<Fs> {
pub fn resolve( pub fn resolve(
&self, &self,
specifier: &Url, specifier: &Url,
mode: SloppyImportsResolutionMode, resolution_kind: SloppyImportsResolutionKind,
) -> Option<SloppyImportsResolution> { ) -> Option<SloppyImportsResolution> {
fn path_without_ext( fn path_without_ext(
path: &Path, path: &Path,
@ -167,7 +167,7 @@ impl<Fs: SloppyImportResolverFs> SloppyImportsResolver<Fs> {
let probe_paths: Vec<(PathBuf, SloppyImportsResolutionReason)> = let probe_paths: Vec<(PathBuf, SloppyImportsResolutionReason)> =
match self.fs.stat_sync(&path) { match self.fs.stat_sync(&path) {
Some(SloppyImportsFsEntry::File) => { Some(SloppyImportsFsEntry::File) => {
if mode.is_types() { if resolution_kind.is_types() {
let media_type = MediaType::from_specifier(specifier); let media_type = MediaType::from_specifier(specifier);
// attempt to resolve the .d.ts file before the .js file // attempt to resolve the .d.ts file before the .js file
let probe_media_type_types = match media_type { let probe_media_type_types = match media_type {
@ -197,7 +197,7 @@ impl<Fs: SloppyImportResolverFs> SloppyImportsResolver<Fs> {
let media_type = MediaType::from_specifier(specifier); let media_type = MediaType::from_specifier(specifier);
let probe_media_type_types = match media_type { let probe_media_type_types = match media_type {
MediaType::JavaScript => ( MediaType::JavaScript => (
if mode.is_types() { if resolution_kind.is_types() {
vec![MediaType::TypeScript, MediaType::Tsx, MediaType::Dts] vec![MediaType::TypeScript, MediaType::Tsx, MediaType::Dts]
} else { } else {
vec![MediaType::TypeScript, MediaType::Tsx] vec![MediaType::TypeScript, MediaType::Tsx]
@ -208,7 +208,7 @@ impl<Fs: SloppyImportResolverFs> SloppyImportsResolver<Fs> {
(vec![MediaType::Tsx], SloppyImportsResolutionReason::JsToTs) (vec![MediaType::Tsx], SloppyImportsResolutionReason::JsToTs)
} }
MediaType::Mjs => ( MediaType::Mjs => (
if mode.is_types() { if resolution_kind.is_types() {
vec![MediaType::Mts, MediaType::Dmts, MediaType::Dts] vec![MediaType::Mts, MediaType::Dmts, MediaType::Dts]
} else { } else {
vec![MediaType::Mts] vec![MediaType::Mts]
@ -216,7 +216,7 @@ impl<Fs: SloppyImportResolverFs> SloppyImportsResolver<Fs> {
SloppyImportsResolutionReason::JsToTs, SloppyImportsResolutionReason::JsToTs,
), ),
MediaType::Cjs => ( MediaType::Cjs => (
if mode.is_types() { if resolution_kind.is_types() {
vec![MediaType::Cts, MediaType::Dcts, MediaType::Dts] vec![MediaType::Cts, MediaType::Dcts, MediaType::Dts]
} else { } else {
vec![MediaType::Cts] vec![MediaType::Cts]
@ -237,7 +237,7 @@ impl<Fs: SloppyImportResolverFs> SloppyImportsResolver<Fs> {
return None; return None;
} }
MediaType::Unknown => ( MediaType::Unknown => (
if mode.is_types() { if resolution_kind.is_types() {
vec![ vec![
MediaType::TypeScript, MediaType::TypeScript,
MediaType::Tsx, MediaType::Tsx,
@ -274,7 +274,7 @@ impl<Fs: SloppyImportResolverFs> SloppyImportsResolver<Fs> {
if matches!(entry, Some(SloppyImportsFsEntry::Dir)) { if matches!(entry, Some(SloppyImportsFsEntry::Dir)) {
// try to resolve at the index file // try to resolve at the index file
if mode.is_types() { if resolution_kind.is_types() {
probe_paths.push(( probe_paths.push((
path.join("index.ts"), path.join("index.ts"),
SloppyImportsResolutionReason::Directory, SloppyImportsResolutionReason::Directory,
@ -373,16 +373,22 @@ mod test {
#[test] #[test]
fn test_unstable_sloppy_imports() { fn test_unstable_sloppy_imports() {
fn resolve(specifier: &Url) -> Option<SloppyImportsResolution> { fn resolve(specifier: &Url) -> Option<SloppyImportsResolution> {
resolve_with_mode(specifier, SloppyImportsResolutionMode::Execution) resolve_with_resolution_kind(
specifier,
SloppyImportsResolutionKind::Execution,
)
} }
fn resolve_types(specifier: &Url) -> Option<SloppyImportsResolution> { fn resolve_types(specifier: &Url) -> Option<SloppyImportsResolution> {
resolve_with_mode(specifier, SloppyImportsResolutionMode::Types) resolve_with_resolution_kind(
specifier,
SloppyImportsResolutionKind::Types,
)
} }
fn resolve_with_mode( fn resolve_with_resolution_kind(
specifier: &Url, specifier: &Url,
mode: SloppyImportsResolutionMode, resolution_kind: SloppyImportsResolutionKind,
) -> Option<SloppyImportsResolution> { ) -> Option<SloppyImportsResolution> {
struct RealSloppyImportsResolverFs; struct RealSloppyImportsResolverFs;
impl SloppyImportResolverFs for RealSloppyImportsResolverFs { impl SloppyImportResolverFs for RealSloppyImportsResolverFs {
@ -400,7 +406,7 @@ mod test {
} }
SloppyImportsResolver::new(RealSloppyImportsResolverFs) SloppyImportsResolver::new(RealSloppyImportsResolverFs)
.resolve(specifier, mode) .resolve(specifier, resolution_kind)
} }
let context = TestContext::default(); let context = TestContext::default();

View file

@ -21,11 +21,11 @@ use url::Url;
use crate::env::NodeResolverEnv; use crate::env::NodeResolverEnv;
use crate::npm::InNpmPackageCheckerRc; use crate::npm::InNpmPackageCheckerRc;
use crate::resolution::NodeResolverRc; use crate::resolution::NodeResolverRc;
use crate::NodeModuleKind; use crate::NodeResolutionKind;
use crate::NodeResolutionMode;
use crate::NpmPackageFolderResolverRc; use crate::NpmPackageFolderResolverRc;
use crate::PackageJsonResolverRc; use crate::PackageJsonResolverRc;
use crate::PathClean; use crate::PathClean;
use crate::ResolutionMode;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum CjsAnalysis<'a> { pub enum CjsAnalysis<'a> {
@ -209,7 +209,7 @@ impl<TCjsCodeAnalyzer: CjsCodeAnalyzer, TNodeResolverEnv: NodeResolverEnv>
// FIXME(bartlomieju): check if these conditions are okay, probably // FIXME(bartlomieju): check if these conditions are okay, probably
// should be `deno-require`, because `deno` is already used in `esm_resolver.rs` // should be `deno-require`, because `deno` is already used in `esm_resolver.rs`
&["deno", "node", "require", "default"], &["deno", "node", "require", "default"],
NodeResolutionMode::Execution, NodeResolutionKind::Execution,
); );
let reexport_specifier = match result { let reexport_specifier = match result {
Ok(Some(specifier)) => specifier, Ok(Some(specifier)) => specifier,
@ -303,7 +303,7 @@ impl<TCjsCodeAnalyzer: CjsCodeAnalyzer, TNodeResolverEnv: NodeResolverEnv>
specifier: &str, specifier: &str,
referrer: &Url, referrer: &Url,
conditions: &[&str], conditions: &[&str],
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Option<Url>, AnyError> { ) -> Result<Option<Url>, AnyError> {
if specifier.starts_with('/') { if specifier.starts_with('/') {
todo!(); todo!();
@ -354,9 +354,9 @@ impl<TCjsCodeAnalyzer: CjsCodeAnalyzer, TNodeResolverEnv: NodeResolverEnv>
&package_subpath, &package_subpath,
exports, exports,
Some(referrer), Some(referrer),
NodeModuleKind::Esm, ResolutionMode::Import,
conditions, conditions,
mode, resolution_kind,
) )
.map_err(AnyError::from), .map_err(AnyError::from),
) )
@ -373,7 +373,9 @@ impl<TCjsCodeAnalyzer: CjsCodeAnalyzer, TNodeResolverEnv: NodeResolverEnv>
.pkg_json_resolver .pkg_json_resolver
.load_package_json(&package_json_path)?; .load_package_json(&package_json_path)?;
if let Some(package_json) = maybe_package_json { if let Some(package_json) = maybe_package_json {
if let Some(main) = package_json.main(NodeModuleKind::Cjs) { if let Some(main) =
package_json.main(deno_package_json::NodeModuleKind::Cjs)
{
return Ok(Some(url_from_file_path(&d.join(main).clean())?)); return Ok(Some(url_from_file_path(&d.join(main).clean())?));
} }
} }
@ -384,7 +386,9 @@ impl<TCjsCodeAnalyzer: CjsCodeAnalyzer, TNodeResolverEnv: NodeResolverEnv>
.file_extension_probe(d, &referrer_path) .file_extension_probe(d, &referrer_path)
.and_then(|p| url_from_file_path(&p).map_err(AnyError::from)) .and_then(|p| url_from_file_path(&p).map_err(AnyError::from))
.map(Some); .map(Some);
} else if let Some(main) = package_json.main(NodeModuleKind::Cjs) { } else if let Some(main) =
package_json.main(deno_package_json::NodeModuleKind::Cjs)
{
return Ok(Some(url_from_file_path(&module_dir.join(main).clean())?)); return Ok(Some(url_from_file_path(&module_dir.join(main).clean())?));
} else { } else {
return Ok(Some(url_from_file_path( return Ok(Some(url_from_file_path(

View file

@ -8,8 +8,8 @@ use boxed_error::Boxed;
use thiserror::Error; use thiserror::Error;
use url::Url; use url::Url;
use crate::NodeModuleKind; use crate::NodeResolutionKind;
use crate::NodeResolutionMode; use crate::ResolutionMode;
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
@ -203,24 +203,24 @@ pub enum PackageSubpathResolveErrorKind {
maybe_referrer.as_ref().map(|r| maybe_referrer.as_ref().map(|r|
format!( format!(
" from{} referrer {}", " from{} referrer {}",
match referrer_kind { match resolution_mode {
NodeModuleKind::Esm => "", ResolutionMode::Import => "",
NodeModuleKind::Cjs => " cjs", ResolutionMode::Require => " cjs",
}, },
r r
) )
).unwrap_or_default(), ).unwrap_or_default(),
match mode { match resolution_kind {
NodeResolutionMode::Execution => "", NodeResolutionKind::Execution => "",
NodeResolutionMode::Types => " for types", NodeResolutionKind::Types => " for types",
} }
)] )]
pub struct PackageTargetNotFoundError { pub struct PackageTargetNotFoundError {
pub pkg_json_path: PathBuf, pub pkg_json_path: PathBuf,
pub target: String, pub target: String,
pub maybe_referrer: Option<Url>, pub maybe_referrer: Option<Url>,
pub referrer_kind: NodeModuleKind, pub resolution_mode: ResolutionMode,
pub mode: NodeResolutionMode, pub resolution_kind: NodeResolutionKind,
} }
impl NodeJsErrorCoded for PackageTargetNotFoundError { impl NodeJsErrorCoded for PackageTargetNotFoundError {
@ -586,7 +586,7 @@ pub struct PackagePathNotExportedError {
pub pkg_json_path: PathBuf, pub pkg_json_path: PathBuf,
pub subpath: String, pub subpath: String,
pub maybe_referrer: Option<Url>, pub maybe_referrer: Option<Url>,
pub mode: NodeResolutionMode, pub resolution_kind: NodeResolutionKind,
} }
impl NodeJsErrorCoded for PackagePathNotExportedError { impl NodeJsErrorCoded for PackagePathNotExportedError {
@ -603,9 +603,9 @@ impl std::fmt::Display for PackagePathNotExportedError {
f.write_str(self.code().as_str())?; f.write_str(self.code().as_str())?;
f.write_char(']')?; f.write_char(']')?;
let types_msg = match self.mode { let types_msg = match self.resolution_kind {
NodeResolutionMode::Execution => String::new(), NodeResolutionKind::Execution => String::new(),
NodeResolutionMode::Types => " for types".to_string(), NodeResolutionKind::Types => " for types".to_string(),
}; };
if self.subpath == "." { if self.subpath == "." {
write!( write!(
@ -678,7 +678,7 @@ mod test {
pkg_json_path: PathBuf::from("test_path").join("package.json"), pkg_json_path: PathBuf::from("test_path").join("package.json"),
subpath: "./jsx-runtime".to_string(), subpath: "./jsx-runtime".to_string(),
maybe_referrer: None, maybe_referrer: None,
mode: NodeResolutionMode::Types resolution_kind: NodeResolutionKind::Types
}.to_string(), }.to_string(),
format!("[ERR_PACKAGE_PATH_NOT_EXPORTED] Package subpath './jsx-runtime' is not defined for types by \"exports\" in 'test_path{separator_char}package.json'") format!("[ERR_PACKAGE_PATH_NOT_EXPORTED] Package subpath './jsx-runtime' is not defined for types by \"exports\" in 'test_path{separator_char}package.json'")
); );
@ -687,7 +687,7 @@ mod test {
pkg_json_path: PathBuf::from("test_path").join("package.json"), pkg_json_path: PathBuf::from("test_path").join("package.json"),
subpath: ".".to_string(), subpath: ".".to_string(),
maybe_referrer: None, maybe_referrer: None,
mode: NodeResolutionMode::Types resolution_kind: NodeResolutionKind::Types
}.to_string(), }.to_string(),
format!("[ERR_PACKAGE_PATH_NOT_EXPORTED] No \"exports\" main defined for types in 'test_path{separator_char}package.json'") format!("[ERR_PACKAGE_PATH_NOT_EXPORTED] No \"exports\" main defined for types in 'test_path{separator_char}package.json'")
); );

View file

@ -23,9 +23,9 @@ pub use package_json::PackageJsonThreadLocalCache;
pub use path::PathClean; pub use path::PathClean;
pub use resolution::parse_npm_pkg_name; pub use resolution::parse_npm_pkg_name;
pub use resolution::resolve_specifier_into_node_modules; pub use resolution::resolve_specifier_into_node_modules;
pub use resolution::NodeModuleKind;
pub use resolution::NodeResolution; pub use resolution::NodeResolution;
pub use resolution::NodeResolutionMode; pub use resolution::NodeResolutionKind;
pub use resolution::NodeResolver; pub use resolution::NodeResolver;
pub use resolution::ResolutionMode;
pub use resolution::DEFAULT_CONDITIONS; pub use resolution::DEFAULT_CONDITIONS;
pub use resolution::REQUIRE_CONDITIONS; pub use resolution::REQUIRE_CONDITIONS;

View file

@ -50,26 +50,30 @@ pub static DEFAULT_CONDITIONS: &[&str] = &["deno", "node", "import"];
pub static REQUIRE_CONDITIONS: &[&str] = &["require", "node"]; pub static REQUIRE_CONDITIONS: &[&str] = &["require", "node"];
static TYPES_ONLY_CONDITIONS: &[&str] = &["types"]; static TYPES_ONLY_CONDITIONS: &[&str] = &["types"];
fn conditions_from_module_kind( fn conditions_from_resolution_mode(
kind: NodeModuleKind, resolution_mode: ResolutionMode,
) -> &'static [&'static str] { ) -> &'static [&'static str] {
match kind { match resolution_mode {
NodeModuleKind::Esm => DEFAULT_CONDITIONS, ResolutionMode::Import => DEFAULT_CONDITIONS,
NodeModuleKind::Cjs => REQUIRE_CONDITIONS, ResolutionMode::Require => REQUIRE_CONDITIONS,
} }
} }
pub type NodeModuleKind = deno_package_json::NodeModuleKind; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ResolutionMode {
Import,
Require,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NodeResolutionMode { pub enum NodeResolutionKind {
Execution, Execution,
Types, Types,
} }
impl NodeResolutionMode { impl NodeResolutionKind {
pub fn is_types(&self) -> bool { pub fn is_types(&self) -> bool {
matches!(self, NodeResolutionMode::Types) matches!(self, NodeResolutionKind::Types)
} }
} }
@ -130,8 +134,8 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
&self, &self,
specifier: &str, specifier: &str,
referrer: &Url, referrer: &Url,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<NodeResolution, NodeResolveError> { ) -> Result<NodeResolution, NodeResolveError> {
// Note: if we are here, then the referrer is an esm module // Note: if we are here, then the referrer is an esm module
// TODO(bartlomieju): skipped "policy" part as we don't plan to support it // TODO(bartlomieju): skipped "policy" part as we don't plan to support it
@ -174,14 +178,18 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
let url = self.module_resolve( let url = self.module_resolve(
specifier, specifier,
referrer, referrer,
referrer_kind, resolution_mode,
conditions_from_module_kind(referrer_kind), conditions_from_resolution_mode(resolution_mode),
mode, resolution_kind,
)?; )?;
let url = if mode.is_types() { let url = if resolution_kind.is_types() {
let file_path = to_file_path(&url); let file_path = to_file_path(&url);
self.path_to_declaration_url(&file_path, Some(referrer), referrer_kind)? self.path_to_declaration_url(
&file_path,
Some(referrer),
resolution_mode,
)?
} else { } else {
url url
}; };
@ -197,9 +205,9 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
&self, &self,
specifier: &str, specifier: &str,
referrer: &Url, referrer: &Url,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
conditions: &[&str], conditions: &[&str],
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Url, NodeResolveError> { ) -> Result<Url, NodeResolveError> {
if should_be_treated_as_relative_or_absolute_path(specifier) { if should_be_treated_as_relative_or_absolute_path(specifier) {
Ok(node_join_url(referrer, specifier).map_err(|err| { Ok(node_join_url(referrer, specifier).map_err(|err| {
@ -218,10 +226,10 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
Ok(self.package_imports_resolve( Ok(self.package_imports_resolve(
specifier, specifier,
Some(referrer), Some(referrer),
referrer_kind, resolution_mode,
pkg_config.as_deref(), pkg_config.as_deref(),
conditions, conditions,
mode, resolution_kind,
)?) )?)
} else if let Ok(resolved) = Url::parse(specifier) { } else if let Ok(resolved) = Url::parse(specifier) {
Ok(resolved) Ok(resolved)
@ -229,9 +237,9 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
Ok(self.package_resolve( Ok(self.package_resolve(
specifier, specifier,
referrer, referrer,
referrer_kind, resolution_mode,
conditions, conditions,
mode, resolution_kind,
)?) )?)
} }
} }
@ -307,8 +315,8 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
package_dir: &Path, package_dir: &Path,
package_subpath: Option<&str>, package_subpath: Option<&str>,
maybe_referrer: Option<&Url>, maybe_referrer: Option<&Url>,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Url, PackageSubpathResolveError> { ) -> Result<Url, PackageSubpathResolveError> {
let package_subpath = package_subpath let package_subpath = package_subpath
.map(|s| format!("./{s}")) .map(|s| format!("./{s}"))
@ -317,9 +325,9 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
package_dir, package_dir,
&package_subpath, &package_subpath,
maybe_referrer, maybe_referrer,
referrer_kind, resolution_mode,
conditions_from_module_kind(referrer_kind), conditions_from_resolution_mode(resolution_mode),
mode, resolution_kind,
)?; )?;
// TODO(bartlomieju): skipped checking errors for commonJS resolution and // TODO(bartlomieju): skipped checking errors for commonJS resolution and
// "preserveSymlinksMain"/"preserveSymlinks" options. // "preserveSymlinksMain"/"preserveSymlinks" options.
@ -385,13 +393,13 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
&self, &self,
path: &Path, path: &Path,
maybe_referrer: Option<&Url>, maybe_referrer: Option<&Url>,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
) -> Result<Url, TypesNotFoundError> { ) -> Result<Url, TypesNotFoundError> {
fn probe_extensions<TEnv: NodeResolverEnv>( fn probe_extensions<TEnv: NodeResolverEnv>(
fs: &TEnv, fs: &TEnv,
path: &Path, path: &Path,
lowercase_path: &str, lowercase_path: &str,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
) -> Option<PathBuf> { ) -> Option<PathBuf> {
let mut searched_for_d_mts = false; let mut searched_for_d_mts = false;
let mut searched_for_d_cts = false; let mut searched_for_d_cts = false;
@ -414,11 +422,11 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
return Some(dts_path); return Some(dts_path);
} }
let specific_dts_path = match referrer_kind { let specific_dts_path = match resolution_mode {
NodeModuleKind::Cjs if !searched_for_d_cts => { ResolutionMode::Require if !searched_for_d_cts => {
Some(with_known_extension(path, "d.cts")) Some(with_known_extension(path, "d.cts"))
} }
NodeModuleKind::Esm if !searched_for_d_mts => { ResolutionMode::Import if !searched_for_d_mts => {
Some(with_known_extension(path, "d.mts")) Some(with_known_extension(path, "d.mts"))
} }
_ => None, // already searched above _ => None, // already searched above
@ -439,7 +447,7 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
return Ok(url_from_file_path(path).unwrap()); return Ok(url_from_file_path(path).unwrap());
} }
if let Some(path) = if let Some(path) =
probe_extensions(&self.env, path, &lowercase_path, referrer_kind) probe_extensions(&self.env, path, &lowercase_path, resolution_mode)
{ {
return Ok(url_from_file_path(&path).unwrap()); return Ok(url_from_file_path(&path).unwrap());
} }
@ -448,9 +456,9 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
path, path,
/* sub path */ ".", /* sub path */ ".",
maybe_referrer, maybe_referrer,
referrer_kind, resolution_mode,
conditions_from_module_kind(referrer_kind), conditions_from_resolution_mode(resolution_mode),
NodeResolutionMode::Types, NodeResolutionKind::Types,
); );
if let Ok(resolution) = resolution_result { if let Ok(resolution) = resolution_result {
return Ok(resolution); return Ok(resolution);
@ -460,7 +468,7 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
&self.env, &self.env,
&index_path, &index_path,
&index_path.to_string_lossy().to_lowercase(), &index_path.to_string_lossy().to_lowercase(),
referrer_kind, resolution_mode,
) { ) {
return Ok(url_from_file_path(&path).unwrap()); return Ok(url_from_file_path(&path).unwrap());
} }
@ -480,10 +488,10 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
&self, &self,
name: &str, name: &str,
maybe_referrer: Option<&Url>, maybe_referrer: Option<&Url>,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
referrer_pkg_json: Option<&PackageJson>, referrer_pkg_json: Option<&PackageJson>,
conditions: &[&str], conditions: &[&str],
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Url, PackageImportsResolveError> { ) -> Result<Url, PackageImportsResolveError> {
if name == "#" || name.starts_with("#/") || name.ends_with('/') { if name == "#" || name.starts_with("#/") || name.ends_with('/') {
let reason = "is not a valid internal imports specifier name"; let reason = "is not a valid internal imports specifier name";
@ -509,11 +517,11 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
"", "",
name, name,
maybe_referrer, maybe_referrer,
referrer_kind, resolution_mode,
false, false,
true, true,
conditions, conditions,
mode, resolution_kind,
)?; )?;
if let Some(resolved) = maybe_resolved { if let Some(resolved) = maybe_resolved {
return Ok(resolved); return Ok(resolved);
@ -549,11 +557,11 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
best_match_subpath.unwrap(), best_match_subpath.unwrap(),
best_match, best_match,
maybe_referrer, maybe_referrer,
referrer_kind, resolution_mode,
true, true,
true, true,
conditions, conditions,
mode, resolution_kind,
)?; )?;
if let Some(resolved) = maybe_resolved { if let Some(resolved) = maybe_resolved {
return Ok(resolved); return Ok(resolved);
@ -581,11 +589,11 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
match_: &str, match_: &str,
package_json_path: &Path, package_json_path: &Path,
maybe_referrer: Option<&Url>, maybe_referrer: Option<&Url>,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
pattern: bool, pattern: bool,
internal: bool, internal: bool,
conditions: &[&str], conditions: &[&str],
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Url, PackageTargetResolveError> { ) -> Result<Url, PackageTargetResolveError> {
if !subpath.is_empty() && !pattern && !target.ends_with('/') { if !subpath.is_empty() && !pattern && !target.ends_with('/') {
return Err( return Err(
@ -626,9 +634,9 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
let result = match self.package_resolve( let result = match self.package_resolve(
&export_target, &export_target,
&package_json_url, &package_json_url,
referrer_kind, resolution_mode,
conditions, conditions,
mode, resolution_kind,
) { ) {
Ok(url) => Ok(url), Ok(url) => Ok(url),
Err(err) => match err.code() { Err(err) => match err.code() {
@ -649,8 +657,8 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
pkg_json_path: package_json_path.to_path_buf(), pkg_json_path: package_json_path.to_path_buf(),
target: export_target.to_string(), target: export_target.to_string(),
maybe_referrer: maybe_referrer.map(ToOwned::to_owned), maybe_referrer: maybe_referrer.map(ToOwned::to_owned),
referrer_kind, resolution_mode,
mode, resolution_kind,
}, },
) )
.into(), .into(),
@ -746,11 +754,11 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
subpath: &str, subpath: &str,
package_subpath: &str, package_subpath: &str,
maybe_referrer: Option<&Url>, maybe_referrer: Option<&Url>,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
pattern: bool, pattern: bool,
internal: bool, internal: bool,
conditions: &[&str], conditions: &[&str],
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Option<Url>, PackageTargetResolveError> { ) -> Result<Option<Url>, PackageTargetResolveError> {
let result = self.resolve_package_target_inner( let result = self.resolve_package_target_inner(
package_json_path, package_json_path,
@ -758,16 +766,16 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
subpath, subpath,
package_subpath, package_subpath,
maybe_referrer, maybe_referrer,
referrer_kind, resolution_mode,
pattern, pattern,
internal, internal,
conditions, conditions,
mode, resolution_kind,
); );
match result { match result {
Ok(maybe_resolved) => Ok(maybe_resolved), Ok(maybe_resolved) => Ok(maybe_resolved),
Err(err) => { Err(err) => {
if mode.is_types() if resolution_kind.is_types()
&& err.code() == NodeJsErrorCode::ERR_TYPES_NOT_FOUND && err.code() == NodeJsErrorCode::ERR_TYPES_NOT_FOUND
&& conditions != TYPES_ONLY_CONDITIONS && conditions != TYPES_ONLY_CONDITIONS
{ {
@ -779,11 +787,11 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
subpath, subpath,
package_subpath, package_subpath,
maybe_referrer, maybe_referrer,
referrer_kind, resolution_mode,
pattern, pattern,
internal, internal,
TYPES_ONLY_CONDITIONS, TYPES_ONLY_CONDITIONS,
mode, resolution_kind,
) { ) {
return Ok(Some(resolved)); return Ok(Some(resolved));
} }
@ -802,11 +810,11 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
subpath: &str, subpath: &str,
package_subpath: &str, package_subpath: &str,
maybe_referrer: Option<&Url>, maybe_referrer: Option<&Url>,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
pattern: bool, pattern: bool,
internal: bool, internal: bool,
conditions: &[&str], conditions: &[&str],
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Option<Url>, PackageTargetResolveError> { ) -> Result<Option<Url>, PackageTargetResolveError> {
if let Some(target) = target.as_str() { if let Some(target) = target.as_str() {
let url = self.resolve_package_target_string( let url = self.resolve_package_target_string(
@ -815,18 +823,18 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
package_subpath, package_subpath,
package_json_path, package_json_path,
maybe_referrer, maybe_referrer,
referrer_kind, resolution_mode,
pattern, pattern,
internal, internal,
conditions, conditions,
mode, resolution_kind,
)?; )?;
if mode.is_types() && url.scheme() == "file" { if resolution_kind.is_types() && url.scheme() == "file" {
let path = deno_path_util::url_to_file_path(&url).unwrap(); let path = deno_path_util::url_to_file_path(&url).unwrap();
return Ok(Some(self.path_to_declaration_url( return Ok(Some(self.path_to_declaration_url(
&path, &path,
maybe_referrer, maybe_referrer,
referrer_kind, resolution_mode,
)?)); )?));
} else { } else {
return Ok(Some(url)); return Ok(Some(url));
@ -844,11 +852,11 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
subpath, subpath,
package_subpath, package_subpath,
maybe_referrer, maybe_referrer,
referrer_kind, resolution_mode,
pattern, pattern,
internal, internal,
conditions, conditions,
mode, resolution_kind,
); );
match resolved_result { match resolved_result {
@ -882,7 +890,7 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
if key == "default" if key == "default"
|| conditions.contains(&key.as_str()) || conditions.contains(&key.as_str())
|| mode.is_types() && key.as_str() == "types" || resolution_kind.is_types() && key.as_str() == "types"
{ {
let condition_target = target_obj.get(key).unwrap(); let condition_target = target_obj.get(key).unwrap();
@ -892,11 +900,11 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
subpath, subpath,
package_subpath, package_subpath,
maybe_referrer, maybe_referrer,
referrer_kind, resolution_mode,
pattern, pattern,
internal, internal,
conditions, conditions,
mode, resolution_kind,
)?; )?;
match resolved { match resolved {
Some(resolved) => return Ok(Some(resolved)), Some(resolved) => return Ok(Some(resolved)),
@ -929,9 +937,9 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
package_subpath: &str, package_subpath: &str,
package_exports: &Map<String, Value>, package_exports: &Map<String, Value>,
maybe_referrer: Option<&Url>, maybe_referrer: Option<&Url>,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
conditions: &[&str], conditions: &[&str],
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Url, PackageExportsResolveError> { ) -> Result<Url, PackageExportsResolveError> {
if package_exports.contains_key(package_subpath) if package_exports.contains_key(package_subpath)
&& package_subpath.find('*').is_none() && package_subpath.find('*').is_none()
@ -944,11 +952,11 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
"", "",
package_subpath, package_subpath,
maybe_referrer, maybe_referrer,
referrer_kind, resolution_mode,
false, false,
false, false,
conditions, conditions,
mode, resolution_kind,
)?; )?;
return match resolved { return match resolved {
Some(resolved) => Ok(resolved), Some(resolved) => Ok(resolved),
@ -957,7 +965,7 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
pkg_json_path: package_json_path.to_path_buf(), pkg_json_path: package_json_path.to_path_buf(),
subpath: package_subpath.to_string(), subpath: package_subpath.to_string(),
maybe_referrer: maybe_referrer.map(ToOwned::to_owned), maybe_referrer: maybe_referrer.map(ToOwned::to_owned),
mode, resolution_kind,
} }
.into(), .into(),
), ),
@ -1006,11 +1014,11 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
&best_match_subpath.unwrap(), &best_match_subpath.unwrap(),
best_match, best_match,
maybe_referrer, maybe_referrer,
referrer_kind, resolution_mode,
true, true,
false, false,
conditions, conditions,
mode, resolution_kind,
)?; )?;
if let Some(resolved) = maybe_resolved { if let Some(resolved) = maybe_resolved {
return Ok(resolved); return Ok(resolved);
@ -1020,7 +1028,7 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
pkg_json_path: package_json_path.to_path_buf(), pkg_json_path: package_json_path.to_path_buf(),
subpath: package_subpath.to_string(), subpath: package_subpath.to_string(),
maybe_referrer: maybe_referrer.map(ToOwned::to_owned), maybe_referrer: maybe_referrer.map(ToOwned::to_owned),
mode, resolution_kind,
} }
.into(), .into(),
); );
@ -1032,7 +1040,7 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
pkg_json_path: package_json_path.to_path_buf(), pkg_json_path: package_json_path.to_path_buf(),
subpath: package_subpath.to_string(), subpath: package_subpath.to_string(),
maybe_referrer: maybe_referrer.map(ToOwned::to_owned), maybe_referrer: maybe_referrer.map(ToOwned::to_owned),
mode, resolution_kind,
} }
.into(), .into(),
) )
@ -1042,9 +1050,9 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
&self, &self,
specifier: &str, specifier: &str,
referrer: &Url, referrer: &Url,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
conditions: &[&str], conditions: &[&str],
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Url, PackageResolveError> { ) -> Result<Url, PackageResolveError> {
let (package_name, package_subpath, _is_scoped) = let (package_name, package_subpath, _is_scoped) =
parse_npm_pkg_name(specifier, referrer)?; parse_npm_pkg_name(specifier, referrer)?;
@ -1061,9 +1069,9 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
&package_subpath, &package_subpath,
exports, exports,
Some(referrer), Some(referrer),
referrer_kind, resolution_mode,
conditions, conditions,
mode, resolution_kind,
) )
.map_err(|err| err.into()); .map_err(|err| err.into());
} }
@ -1074,9 +1082,9 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
&package_name, &package_name,
&package_subpath, &package_subpath,
referrer, referrer,
referrer_kind, resolution_mode,
conditions, conditions,
mode, resolution_kind,
) )
} }
@ -1086,28 +1094,28 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
package_name: &str, package_name: &str,
package_subpath: &str, package_subpath: &str,
referrer: &Url, referrer: &Url,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
conditions: &[&str], conditions: &[&str],
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Url, PackageResolveError> { ) -> Result<Url, PackageResolveError> {
let result = self.resolve_package_subpath_for_package_inner( let result = self.resolve_package_subpath_for_package_inner(
package_name, package_name,
package_subpath, package_subpath,
referrer, referrer,
referrer_kind, resolution_mode,
conditions, conditions,
mode, resolution_kind,
); );
if mode.is_types() && !matches!(result, Ok(Url { .. })) { if resolution_kind.is_types() && !matches!(result, Ok(Url { .. })) {
// try to resolve with the @types package // try to resolve with the @types package
let package_name = types_package_name(package_name); let package_name = types_package_name(package_name);
if let Ok(result) = self.resolve_package_subpath_for_package_inner( if let Ok(result) = self.resolve_package_subpath_for_package_inner(
&package_name, &package_name,
package_subpath, package_subpath,
referrer, referrer,
referrer_kind, resolution_mode,
conditions, conditions,
mode, resolution_kind,
) { ) {
return Ok(result); return Ok(result);
} }
@ -1121,9 +1129,9 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
package_name: &str, package_name: &str,
package_subpath: &str, package_subpath: &str,
referrer: &Url, referrer: &Url,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
conditions: &[&str], conditions: &[&str],
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Url, PackageResolveError> { ) -> Result<Url, PackageResolveError> {
let package_dir_path = self let package_dir_path = self
.npm_pkg_folder_resolver .npm_pkg_folder_resolver
@ -1148,9 +1156,9 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
&package_dir_path, &package_dir_path,
package_subpath, package_subpath,
Some(referrer), Some(referrer),
referrer_kind, resolution_mode,
conditions, conditions,
mode, resolution_kind,
) )
.map_err(|err| err.into()) .map_err(|err| err.into())
} }
@ -1161,9 +1169,9 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
package_dir_path: &Path, package_dir_path: &Path,
package_subpath: &str, package_subpath: &str,
maybe_referrer: Option<&Url>, maybe_referrer: Option<&Url>,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
conditions: &[&str], conditions: &[&str],
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Url, PackageSubpathResolveError> { ) -> Result<Url, PackageSubpathResolveError> {
let package_json_path = package_dir_path.join("package.json"); let package_json_path = package_dir_path.join("package.json");
match self match self
@ -1174,17 +1182,17 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
&pkg_json, &pkg_json,
package_subpath, package_subpath,
maybe_referrer, maybe_referrer,
referrer_kind, resolution_mode,
conditions, conditions,
mode, resolution_kind,
), ),
None => self None => self
.resolve_package_subpath_no_pkg_json( .resolve_package_subpath_no_pkg_json(
package_dir_path, package_dir_path,
package_subpath, package_subpath,
maybe_referrer, maybe_referrer,
referrer_kind, resolution_mode,
mode, resolution_kind,
) )
.map_err(|err| { .map_err(|err| {
PackageSubpathResolveErrorKind::LegacyResolve(err).into() PackageSubpathResolveErrorKind::LegacyResolve(err).into()
@ -1198,9 +1206,9 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
package_json: &PackageJson, package_json: &PackageJson,
package_subpath: &str, package_subpath: &str,
referrer: Option<&Url>, referrer: Option<&Url>,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
conditions: &[&str], conditions: &[&str],
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Url, PackageSubpathResolveError> { ) -> Result<Url, PackageSubpathResolveError> {
if let Some(exports) = &package_json.exports { if let Some(exports) = &package_json.exports {
let result = self.package_exports_resolve( let result = self.package_exports_resolve(
@ -1208,16 +1216,21 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
package_subpath, package_subpath,
exports, exports,
referrer, referrer,
referrer_kind, resolution_mode,
conditions, conditions,
mode, resolution_kind,
); );
match result { match result {
Ok(found) => return Ok(found), Ok(found) => return Ok(found),
Err(exports_err) => { Err(exports_err) => {
if mode.is_types() && package_subpath == "." { if resolution_kind.is_types() && package_subpath == "." {
return self return self
.legacy_main_resolve(package_json, referrer, referrer_kind, mode) .legacy_main_resolve(
package_json,
referrer,
resolution_mode,
resolution_kind,
)
.map_err(|err| { .map_err(|err| {
PackageSubpathResolveErrorKind::LegacyResolve(err).into() PackageSubpathResolveErrorKind::LegacyResolve(err).into()
}); });
@ -1231,7 +1244,12 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
if package_subpath == "." { if package_subpath == "." {
return self return self
.legacy_main_resolve(package_json, referrer, referrer_kind, mode) .legacy_main_resolve(
package_json,
referrer,
resolution_mode,
resolution_kind,
)
.map_err(|err| { .map_err(|err| {
PackageSubpathResolveErrorKind::LegacyResolve(err).into() PackageSubpathResolveErrorKind::LegacyResolve(err).into()
}); });
@ -1242,8 +1260,8 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
package_json.path.parent().unwrap(), package_json.path.parent().unwrap(),
package_subpath, package_subpath,
referrer, referrer,
referrer_kind, resolution_mode,
mode, resolution_kind,
) )
.map_err(|err| { .map_err(|err| {
PackageSubpathResolveErrorKind::LegacyResolve(err.into()).into() PackageSubpathResolveErrorKind::LegacyResolve(err.into()).into()
@ -1255,13 +1273,13 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
directory: &Path, directory: &Path,
package_subpath: &str, package_subpath: &str,
referrer: Option<&Url>, referrer: Option<&Url>,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Url, TypesNotFoundError> { ) -> Result<Url, TypesNotFoundError> {
assert_ne!(package_subpath, "."); assert_ne!(package_subpath, ".");
let file_path = directory.join(package_subpath); let file_path = directory.join(package_subpath);
if mode.is_types() { if resolution_kind.is_types() {
Ok(self.path_to_declaration_url(&file_path, referrer, referrer_kind)?) Ok(self.path_to_declaration_url(&file_path, referrer, resolution_mode)?)
} else { } else {
Ok(url_from_file_path(&file_path).unwrap()) Ok(url_from_file_path(&file_path).unwrap())
} }
@ -1272,19 +1290,24 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
directory: &Path, directory: &Path,
package_subpath: &str, package_subpath: &str,
maybe_referrer: Option<&Url>, maybe_referrer: Option<&Url>,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Url, LegacyResolveError> { ) -> Result<Url, LegacyResolveError> {
if package_subpath == "." { if package_subpath == "." {
self.legacy_index_resolve(directory, maybe_referrer, referrer_kind, mode) self.legacy_index_resolve(
directory,
maybe_referrer,
resolution_mode,
resolution_kind,
)
} else { } else {
self self
.resolve_subpath_exact( .resolve_subpath_exact(
directory, directory,
package_subpath, package_subpath,
maybe_referrer, maybe_referrer,
referrer_kind, resolution_mode,
mode, resolution_kind,
) )
.map_err(|err| err.into()) .map_err(|err| err.into())
} }
@ -1294,21 +1317,25 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
&self, &self,
package_json: &PackageJson, package_json: &PackageJson,
maybe_referrer: Option<&Url>, maybe_referrer: Option<&Url>,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Url, LegacyResolveError> { ) -> Result<Url, LegacyResolveError> {
let maybe_main = if mode.is_types() { let pkg_json_kind = match resolution_mode {
ResolutionMode::Require => deno_package_json::NodeModuleKind::Cjs,
ResolutionMode::Import => deno_package_json::NodeModuleKind::Esm,
};
let maybe_main = if resolution_kind.is_types() {
match package_json.types.as_ref() { match package_json.types.as_ref() {
Some(types) => Some(types.as_str()), Some(types) => Some(types.as_str()),
None => { None => {
// fallback to checking the main entrypoint for // fallback to checking the main entrypoint for
// a corresponding declaration file // a corresponding declaration file
if let Some(main) = package_json.main(referrer_kind) { if let Some(main) = package_json.main(pkg_json_kind) {
let main = package_json.path.parent().unwrap().join(main).clean(); let main = package_json.path.parent().unwrap().join(main).clean();
let decl_url_result = self.path_to_declaration_url( let decl_url_result = self.path_to_declaration_url(
&main, &main,
maybe_referrer, maybe_referrer,
referrer_kind, resolution_mode,
); );
// don't surface errors, fallback to checking the index now // don't surface errors, fallback to checking the index now
if let Ok(url) = decl_url_result { if let Ok(url) = decl_url_result {
@ -1319,7 +1346,7 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
} }
} }
} else { } else {
package_json.main(referrer_kind) package_json.main(pkg_json_kind)
}; };
if let Some(main) = maybe_main { if let Some(main) = maybe_main {
@ -1329,12 +1356,12 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
} }
// todo(dsherret): investigate exactly how node and typescript handles this // todo(dsherret): investigate exactly how node and typescript handles this
let endings = if mode.is_types() { let endings = if resolution_kind.is_types() {
match referrer_kind { match resolution_mode {
NodeModuleKind::Cjs => { ResolutionMode::Require => {
vec![".d.ts", ".d.cts", "/index.d.ts", "/index.d.cts"] vec![".d.ts", ".d.cts", "/index.d.ts", "/index.d.cts"]
} }
NodeModuleKind::Esm => vec![ ResolutionMode::Import => vec![
".d.ts", ".d.ts",
".d.mts", ".d.mts",
"/index.d.ts", "/index.d.ts",
@ -1363,8 +1390,8 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
self.legacy_index_resolve( self.legacy_index_resolve(
package_json.path.parent().unwrap(), package_json.path.parent().unwrap(),
maybe_referrer, maybe_referrer,
referrer_kind, resolution_mode,
mode, resolution_kind,
) )
} }
@ -1372,14 +1399,16 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
&self, &self,
directory: &Path, directory: &Path,
maybe_referrer: Option<&Url>, maybe_referrer: Option<&Url>,
referrer_kind: NodeModuleKind, resolution_mode: ResolutionMode,
mode: NodeResolutionMode, resolution_kind: NodeResolutionKind,
) -> Result<Url, LegacyResolveError> { ) -> Result<Url, LegacyResolveError> {
let index_file_names = if mode.is_types() { let index_file_names = if resolution_kind.is_types() {
// todo(dsherret): investigate exactly how typescript does this // todo(dsherret): investigate exactly how typescript does this
match referrer_kind { match resolution_mode {
NodeModuleKind::Cjs => vec!["index.d.ts", "index.d.cts"], ResolutionMode::Require => vec!["index.d.ts", "index.d.cts"],
NodeModuleKind::Esm => vec!["index.d.ts", "index.d.mts", "index.d.cts"], ResolutionMode::Import => {
vec!["index.d.ts", "index.d.mts", "index.d.cts"]
}
} }
} else { } else {
vec!["index.js"] vec!["index.js"]
@ -1392,7 +1421,7 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
} }
} }
if mode.is_types() { if resolution_kind.is_types() {
Err( Err(
TypesNotFoundError(Box::new(TypesNotFoundErrorData { TypesNotFoundError(Box::new(TypesNotFoundErrorData {
code_specifier: url_from_file_path(&directory.join("index.js")) code_specifier: url_from_file_path(&directory.join("index.js"))

View file

@ -0,0 +1,44 @@
{
"tests": {
"cjs_check": {
"args": "check index.cts",
"output": "check.out",
"exitCode": 1
},
"cjs_run": {
"args": "run index.cts",
"output": "run_cjs.out"
},
"mjs_run": {
"args": "run index.mjs",
"output": "run_mts.out"
},
"jsdoc_import_decl": {
"args": "check jsdoc_import_decl.js",
"output": "jsdoc_import_decl.out",
"exitCode": 1
},
"resolution_mode_import": {
"args": "check resolution_mode_import.mts",
"output": "resolution_mode_import.out",
"exitCode": 1
},
"resolution_mode_require": {
"args": "check resolution_mode_require.mts",
"output": "resolution_mode_require.out",
"exitCode": 1
},
"resolution_mode_require_jsdoc": {
"args": "check resolution_mode_require_jsdoc.js",
"output": "resolution_mode_require_jsdoc.out",
"exitCode": 1
},
"resolution_mode_require_import_type": {
// waiting on https://github.com/swc-project/swc/issues/9377
"ignore": true,
"args": "check resolution_mode_require_import_type.ts",
"output": "resolution_mode_require_import_type.out",
"exitCode": 1
}
}
}

View file

@ -0,0 +1,5 @@
Check file:///[WILDLINE]/index.cts
error: TS2322 [ERROR]: Type '"mjs"' is not assignable to type '"value"'.
const value: "value" = mod.kind;
~~~~~
at file:///[WILDLINE]/index.cts:3:9

View file

@ -0,0 +1,8 @@
async function main() {
const mod = await import("package");
const value: "value" = mod.kind;
console.log(value);
console.log(mod);
}
main();

View file

@ -0,0 +1,11 @@
import { createRequire } from "node:module";
{
const mod = await import("package");
console.log(mod.kind);
console.log(mod);
}
{
const require = createRequire(import.meta.url);
const mod = require("package");
console.log(mod);
}

View file

@ -0,0 +1,12 @@
// @ts-check
/** @import { kind } from "package" */
/**
* @param {typeof kind} myValue
*/
export function log(myValue) {
console.log(myValue);
}
log("value");

View file

@ -0,0 +1,5 @@
Check file:///[WILDLINE]/jsdoc_import_decl.js
error: TS2345 [ERROR]: Argument of type '"value"' is not assignable to parameter of type '"mjs"'.
log("value");
~~~~~~~
at file:///[WILDLINE]/jsdoc_import_decl.js:12:5

View file

@ -0,0 +1 @@
export const kind: "mjs";

View file

@ -0,0 +1 @@
export const kind = "esm";

View file

@ -0,0 +1,11 @@
{
"name": "package",
"version": "1.0.0",
"type": "module",
"exports": {
".": {
"import": "./mod.mjs",
"require": "./require.cjs"
}
}
}

View file

@ -0,0 +1 @@
module.exports.kind = "cjs";

View file

@ -0,0 +1 @@
export const kind: "cjs";

View file

@ -0,0 +1,6 @@
{
"type": "commonjs",
"dependencies": {
"package": "*"
}
}

View file

@ -0,0 +1,6 @@
import type { kind } from "package" with {
"resolution-mode": "import",
};
const test: typeof kind = "other";
console.log(test);

View file

@ -0,0 +1,5 @@
Check file:///[WILDLINE]/resolution_mode_import.mts
error: TS2322 [ERROR]: Type '"other"' is not assignable to type '"mjs"'.
const test: typeof kind = "other";
~~~~
at file:///[WILDLINE]/resolution_mode_import.mts:5:7

View file

@ -0,0 +1,6 @@
import type { kind } from "package" with {
"resolution-mode": "require",
};
const test: typeof kind = "other";
console.log(test);

View file

@ -0,0 +1,5 @@
Check file:///[WILDLINE]/resolution_mode_require.mts
error: TS2322 [ERROR]: Type '"other"' is not assignable to type '"cjs"'.
const test: typeof kind = "other";
~~~~
at file:///[WILDLINE]/resolution_mode_require.mts:5:7

View file

@ -0,0 +1,5 @@
// deno-fmt-ignore-file
type Value = typeof import("package", { with: { 'resolution-mode': 'require' } }).kind;
const value: Value = "value";
console.log(value);

View file

@ -0,0 +1,12 @@
// @ts-check
/** @import { kind } from "package" with { 'resolution-mode': 'require' } */
/**
* @param {typeof kind} myValue
*/
export function log(myValue) {
console.log(myValue);
}
log("value");

View file

@ -0,0 +1,5 @@
Check file:///[WILDLINE]/resolution_mode_require_jsdoc.js
error: TS2345 [ERROR]: Argument of type '"value"' is not assignable to parameter of type '"cjs"'.
log("value");
~~~~~~~
at file:///[WILDLINE]/resolution_mode_require_jsdoc.js:12:5

View file

@ -0,0 +1,2 @@
esm
[Module: null prototype] { kind: "esm" }

View file

@ -0,0 +1,3 @@
esm
[Module: null prototype] { kind: "esm" }
{ kind: "cjs" }

View file

@ -1,5 +1,5 @@
{ {
"args": "info --quiet cjs_with_deps/main.js", "args": "info --quiet main.js",
"output": "cjs_with_deps/main_info.out", "output": "main_info.out",
"exitCode": 0 "exitCode": 0
} }

View file

@ -1,33 +0,0 @@
[UNORDERED_START]
Download http://localhost:4260/chalk
Download http://localhost:4260/chai
Download http://localhost:4260/ansi-styles
Download http://localhost:4260/supports-color
Download http://localhost:4260/assertion-error
Download http://localhost:4260/check-error
Download http://localhost:4260/deep-eql
Download http://localhost:4260/get-func-name
Download http://localhost:4260/loupe
Download http://localhost:4260/pathval
Download http://localhost:4260/type-detect
Download http://localhost:4260/color-convert
Download http://localhost:4260/has-flag
Download http://localhost:4260/color-name
[UNORDERED_END]
[UNORDERED_START]
Download http://localhost:4260/ansi-styles/ansi-styles-4.3.0.tgz
Download http://localhost:4260/assertion-error/assertion-error-1.1.0.tgz
Download http://localhost:4260/chai/chai-4.3.6.tgz
Download http://localhost:4260/chalk/chalk-4.1.2.tgz
Download http://localhost:4260/check-error/check-error-1.0.2.tgz
Download http://localhost:4260/color-convert/color-convert-2.0.1.tgz
Download http://localhost:4260/color-name/color-name-1.1.4.tgz
Download http://localhost:4260/deep-eql/deep-eql-3.0.1.tgz
Download http://localhost:4260/get-func-name/get-func-name-2.0.0.tgz
Download http://localhost:4260/has-flag/has-flag-4.0.0.tgz
Download http://localhost:4260/loupe/loupe-2.3.4.tgz
Download http://localhost:4260/pathval/pathval-1.1.1.tgz
Download http://localhost:4260/supports-color/supports-color-7.2.0.tgz
Download http://localhost:4260/type-detect/type-detect-4.0.8.tgz
[UNORDERED_END]
chalk cjs loads

View file

@ -1,148 +0,0 @@
{
"version": 1,
"roots": [
"file://[WILDCARD]/main.js"
],
"modules": [
{
"kind": "esm",
"dependencies": [
{
"specifier": "npm:chalk@4",
"code": {
"specifier": "npm:chalk@4",
"span": {
"start": {
"line": 0,
"character": 18
},
"end": {
"line": 0,
"character": 31
}
}
},
"npmPackage": "chalk@4.1.2"
},
{
"specifier": "npm:chai@4.3",
"code": {
"specifier": "npm:chai@4.3",
"span": {
"start": {
"line": 1,
"character": 23
},
"end": {
"line": 1,
"character": 37
}
}
},
"npmPackage": "chai@4.3.6"
}
],
"local": "[WILDCARD]main.js",
"size": 325,
"mediaType": "JavaScript",
"specifier": "[WILDCARD]/main.js"
}
],
"redirects": {
"npm:chai@4.3": "npm:/chai@4.3.6",
"npm:chalk@4": "npm:/chalk@4.1.2"
},
"npmPackages": {
"ansi-styles@4.3.0": {
"name": "ansi-styles",
"version": "4.3.0",
"dependencies": [
"color-convert@2.0.1"
]
},
"assertion-error@1.1.0": {
"name": "assertion-error",
"version": "1.1.0",
"dependencies": []
},
"chai@4.3.6": {
"name": "chai",
"version": "4.3.6",
"dependencies": [
"assertion-error@1.1.0",
"check-error@1.0.2",
"deep-eql@3.0.1",
"get-func-name@2.0.0",
"loupe@2.3.4",
"pathval@1.1.1",
"type-detect@4.0.8"
]
},
"chalk@4.1.2": {
"name": "chalk",
"version": "4.1.2",
"dependencies": [
"ansi-styles@4.3.0",
"supports-color@7.2.0"
]
},
"check-error@1.0.2": {
"name": "check-error",
"version": "1.0.2",
"dependencies": []
},
"color-convert@2.0.1": {
"name": "color-convert",
"version": "2.0.1",
"dependencies": [
"color-name@1.1.4"
]
},
"color-name@1.1.4": {
"name": "color-name",
"version": "1.1.4",
"dependencies": []
},
"deep-eql@3.0.1": {
"name": "deep-eql",
"version": "3.0.1",
"dependencies": [
"type-detect@4.0.8"
]
},
"get-func-name@2.0.0": {
"name": "get-func-name",
"version": "2.0.0",
"dependencies": []
},
"has-flag@4.0.0": {
"name": "has-flag",
"version": "4.0.0",
"dependencies": []
},
"loupe@2.3.4": {
"name": "loupe",
"version": "2.3.4",
"dependencies": [
"get-func-name@2.0.0"
]
},
"pathval@1.1.1": {
"name": "pathval",
"version": "1.1.1",
"dependencies": []
},
"supports-color@7.2.0": {
"name": "supports-color",
"version": "7.2.0",
"dependencies": [
"has-flag@4.0.0"
]
},
"type-detect@4.0.8": {
"name": "type-detect",
"version": "4.0.8",
"dependencies": []
}
}
}

View file

@ -1,47 +0,0 @@
[UNORDERED_START]
Download http://localhost:4260/chalk
Download http://localhost:4260/chai
Download http://localhost:4260/ansi-styles
Download http://localhost:4260/supports-color
Download http://localhost:4260/assertion-error
Download http://localhost:4260/check-error
Download http://localhost:4260/deep-eql
Download http://localhost:4260/get-func-name
Download http://localhost:4260/loupe
Download http://localhost:4260/pathval
Download http://localhost:4260/type-detect
Download http://localhost:4260/color-convert
Download http://localhost:4260/has-flag
Download http://localhost:4260/color-name
[UNORDERED_END]
[UNORDERED_START]
Download http://localhost:4260/ansi-styles/ansi-styles-4.3.0.tgz
Initialize ansi-styles@4.3.0
Download http://localhost:4260/assertion-error/assertion-error-1.1.0.tgz
Initialize assertion-error@1.1.0
Download http://localhost:4260/chai/chai-4.3.6.tgz
Initialize chai@4.3.6
Download http://localhost:4260/chalk/chalk-4.1.2.tgz
Initialize chalk@4.1.2
Download http://localhost:4260/check-error/check-error-1.0.2.tgz
Initialize check-error@1.0.2
Download http://localhost:4260/color-convert/color-convert-2.0.1.tgz
Initialize color-convert@2.0.1
Download http://localhost:4260/color-name/color-name-1.1.4.tgz
Initialize color-name@1.1.4
Download http://localhost:4260/deep-eql/deep-eql-3.0.1.tgz
Initialize deep-eql@3.0.1
Download http://localhost:4260/get-func-name/get-func-name-2.0.0.tgz
Initialize get-func-name@2.0.0
Download http://localhost:4260/has-flag/has-flag-4.0.0.tgz
Initialize has-flag@4.0.0
Download http://localhost:4260/loupe/loupe-2.3.4.tgz
Initialize loupe@2.3.4
Download http://localhost:4260/pathval/pathval-1.1.1.tgz
Initialize pathval@1.1.1
Download http://localhost:4260/supports-color/supports-color-7.2.0.tgz
Initialize supports-color@7.2.0
Download http://localhost:4260/type-detect/type-detect-4.0.8.tgz
Initialize type-detect@4.0.8
[UNORDERED_END]
chalk cjs loads

View file

@ -3,7 +3,7 @@ type: JavaScript
dependencies: 14 unique dependencies: 14 unique
size: [WILDCARD] size: [WILDCARD]
file:///[WILDCARD]/cjs_with_deps/main.js ([WILDCARD]) file:///[WILDCARD]/main.js ([WILDCARD])
├─┬ npm:/chalk@4.1.2 ([WILDCARD]) ├─┬ npm:/chalk@4.1.2 ([WILDCARD])
│ ├─┬ npm:/ansi-styles@4.3.0 ([WILDCARD]) │ ├─┬ npm:/ansi-styles@4.3.0 ([WILDCARD])
│ │ └─┬ npm:/color-convert@2.0.1 ([WILDCARD]) │ │ └─┬ npm:/color-convert@2.0.1 ([WILDCARD])

View file

@ -1,6 +1,6 @@
{ {
"tempDir": true, "tempDir": true,
"args": "info --quiet --node-modules-dir cjs_with_deps/main.js", "args": "info --quiet --node-modules-dir main.js",
"output": "cjs_with_deps/main_info.out", "output": "main_info.out",
"exitCode": 0 "exitCode": 0
} }

View file

@ -1,33 +0,0 @@
[UNORDERED_START]
Download http://localhost:4260/chalk
Download http://localhost:4260/chai
Download http://localhost:4260/ansi-styles
Download http://localhost:4260/supports-color
Download http://localhost:4260/assertion-error
Download http://localhost:4260/check-error
Download http://localhost:4260/deep-eql
Download http://localhost:4260/get-func-name
Download http://localhost:4260/loupe
Download http://localhost:4260/pathval
Download http://localhost:4260/type-detect
Download http://localhost:4260/color-convert
Download http://localhost:4260/has-flag
Download http://localhost:4260/color-name
[UNORDERED_END]
[UNORDERED_START]
Download http://localhost:4260/ansi-styles/ansi-styles-4.3.0.tgz
Download http://localhost:4260/assertion-error/assertion-error-1.1.0.tgz
Download http://localhost:4260/chai/chai-4.3.6.tgz
Download http://localhost:4260/chalk/chalk-4.1.2.tgz
Download http://localhost:4260/check-error/check-error-1.0.2.tgz
Download http://localhost:4260/color-convert/color-convert-2.0.1.tgz
Download http://localhost:4260/color-name/color-name-1.1.4.tgz
Download http://localhost:4260/deep-eql/deep-eql-3.0.1.tgz
Download http://localhost:4260/get-func-name/get-func-name-2.0.0.tgz
Download http://localhost:4260/has-flag/has-flag-4.0.0.tgz
Download http://localhost:4260/loupe/loupe-2.3.4.tgz
Download http://localhost:4260/pathval/pathval-1.1.1.tgz
Download http://localhost:4260/supports-color/supports-color-7.2.0.tgz
Download http://localhost:4260/type-detect/type-detect-4.0.8.tgz
[UNORDERED_END]
chalk cjs loads

View file

@ -1,22 +0,0 @@
local: [WILDCARD]main.js
type: JavaScript
dependencies: 14 unique
size: [WILDCARD]
file:///[WILDCARD]/cjs_with_deps/main.js ([WILDCARD])
├─┬ npm:/chalk@4.1.2 ([WILDCARD])
│ ├─┬ npm:/ansi-styles@4.3.0 ([WILDCARD])
│ │ └─┬ npm:/color-convert@2.0.1 ([WILDCARD])
│ │ └── npm:/color-name@1.1.4 ([WILDCARD])
│ └─┬ npm:/supports-color@7.2.0 ([WILDCARD])
│ └── npm:/has-flag@4.0.0 ([WILDCARD])
└─┬ npm:/chai@4.3.6 ([WILDCARD])
├── npm:/assertion-error@1.1.0 ([WILDCARD])
├── npm:/check-error@1.0.2 ([WILDCARD])
├─┬ npm:/deep-eql@3.0.1 ([WILDCARD])
│ └── npm:/type-detect@4.0.8 ([WILDCARD])
├── npm:/get-func-name@2.0.0 ([WILDCARD])
├─┬ npm:/loupe@2.3.4 ([WILDCARD])
│ └── npm:/get-func-name@2.0.0 ([WILDCARD])
├── npm:/pathval@1.1.1 ([WILDCARD])
└── npm:/type-detect@4.0.8 ([WILDCARD])

View file

@ -1,148 +0,0 @@
{
"version": 1,
"roots": [
"file://[WILDCARD]/main.js"
],
"modules": [
{
"kind": "esm",
"dependencies": [
{
"specifier": "npm:chalk@4",
"code": {
"specifier": "npm:chalk@4",
"span": {
"start": {
"line": 0,
"character": 18
},
"end": {
"line": 0,
"character": 31
}
}
},
"npmPackage": "chalk@4.1.2"
},
{
"specifier": "npm:chai@4.3",
"code": {
"specifier": "npm:chai@4.3",
"span": {
"start": {
"line": 1,
"character": 23
},
"end": {
"line": 1,
"character": 37
}
}
},
"npmPackage": "chai@4.3.6"
}
],
"local": "[WILDCARD]main.js",
"size": 325,
"mediaType": "JavaScript",
"specifier": "[WILDCARD]/main.js"
}
],
"redirects": {
"npm:chai@4.3": "npm:/chai@4.3.6",
"npm:chalk@4": "npm:/chalk@4.1.2"
},
"npmPackages": {
"ansi-styles@4.3.0": {
"name": "ansi-styles",
"version": "4.3.0",
"dependencies": [
"color-convert@2.0.1"
]
},
"assertion-error@1.1.0": {
"name": "assertion-error",
"version": "1.1.0",
"dependencies": []
},
"chai@4.3.6": {
"name": "chai",
"version": "4.3.6",
"dependencies": [
"assertion-error@1.1.0",
"check-error@1.0.2",
"deep-eql@3.0.1",
"get-func-name@2.0.0",
"loupe@2.3.4",
"pathval@1.1.1",
"type-detect@4.0.8"
]
},
"chalk@4.1.2": {
"name": "chalk",
"version": "4.1.2",
"dependencies": [
"ansi-styles@4.3.0",
"supports-color@7.2.0"
]
},
"check-error@1.0.2": {
"name": "check-error",
"version": "1.0.2",
"dependencies": []
},
"color-convert@2.0.1": {
"name": "color-convert",
"version": "2.0.1",
"dependencies": [
"color-name@1.1.4"
]
},
"color-name@1.1.4": {
"name": "color-name",
"version": "1.1.4",
"dependencies": []
},
"deep-eql@3.0.1": {
"name": "deep-eql",
"version": "3.0.1",
"dependencies": [
"type-detect@4.0.8"
]
},
"get-func-name@2.0.0": {
"name": "get-func-name",
"version": "2.0.0",
"dependencies": []
},
"has-flag@4.0.0": {
"name": "has-flag",
"version": "4.0.0",
"dependencies": []
},
"loupe@2.3.4": {
"name": "loupe",
"version": "2.3.4",
"dependencies": [
"get-func-name@2.0.0"
]
},
"pathval@1.1.1": {
"name": "pathval",
"version": "1.1.1",
"dependencies": []
},
"supports-color@7.2.0": {
"name": "supports-color",
"version": "7.2.0",
"dependencies": [
"has-flag@4.0.0"
]
},
"type-detect@4.0.8": {
"name": "type-detect",
"version": "4.0.8",
"dependencies": []
}
}
}

View file

@ -1,47 +0,0 @@
[UNORDERED_START]
Download http://localhost:4260/chalk
Download http://localhost:4260/chai
Download http://localhost:4260/ansi-styles
Download http://localhost:4260/supports-color
Download http://localhost:4260/assertion-error
Download http://localhost:4260/check-error
Download http://localhost:4260/deep-eql
Download http://localhost:4260/get-func-name
Download http://localhost:4260/loupe
Download http://localhost:4260/pathval
Download http://localhost:4260/type-detect
Download http://localhost:4260/color-convert
Download http://localhost:4260/has-flag
Download http://localhost:4260/color-name
[UNORDERED_END]
[UNORDERED_START]
Download http://localhost:4260/ansi-styles/ansi-styles-4.3.0.tgz
Initialize ansi-styles@4.3.0
Download http://localhost:4260/assertion-error/assertion-error-1.1.0.tgz
Initialize assertion-error@1.1.0
Download http://localhost:4260/chai/chai-4.3.6.tgz
Initialize chai@4.3.6
Download http://localhost:4260/chalk/chalk-4.1.2.tgz
Initialize chalk@4.1.2
Download http://localhost:4260/check-error/check-error-1.0.2.tgz
Initialize check-error@1.0.2
Download http://localhost:4260/color-convert/color-convert-2.0.1.tgz
Initialize color-convert@2.0.1
Download http://localhost:4260/color-name/color-name-1.1.4.tgz
Initialize color-name@1.1.4
Download http://localhost:4260/deep-eql/deep-eql-3.0.1.tgz
Initialize deep-eql@3.0.1
Download http://localhost:4260/get-func-name/get-func-name-2.0.0.tgz
Initialize get-func-name@2.0.0
Download http://localhost:4260/has-flag/has-flag-4.0.0.tgz
Initialize has-flag@4.0.0
Download http://localhost:4260/loupe/loupe-2.3.4.tgz
Initialize loupe@2.3.4
Download http://localhost:4260/pathval/pathval-1.1.1.tgz
Initialize pathval@1.1.1
Download http://localhost:4260/supports-color/supports-color-7.2.0.tgz
Initialize supports-color@7.2.0
Download http://localhost:4260/type-detect/type-detect-4.0.8.tgz
Initialize type-detect@4.0.8
[UNORDERED_END]
chalk cjs loads

View file

@ -3,7 +3,7 @@ type: JavaScript
dependencies: 14 unique dependencies: 14 unique
size: [WILDCARD] size: [WILDCARD]
file:///[WILDCARD]/cjs_with_deps/main.js ([WILDCARD]) file:///[WILDCARD]/main.js ([WILDCARD])
├─┬ npm:/chalk@4.1.2 ([WILDCARD]) ├─┬ npm:/chalk@4.1.2 ([WILDCARD])
│ ├─┬ npm:/ansi-styles@4.3.0 ([WILDCARD]) │ ├─┬ npm:/ansi-styles@4.3.0 ([WILDCARD])
│ │ └─┬ npm:/color-convert@2.0.1 ([WILDCARD]) │ │ └─┬ npm:/color-convert@2.0.1 ([WILDCARD])

View file

@ -1,5 +1,5 @@
{ {
"args": "info --quiet --json cjs_with_deps/main.js", "args": "info --quiet --json main.js",
"output": "cjs_with_deps/main_info_json.out", "output": "main_info_json.out",
"exitCode": 0 "exitCode": 0
} }

View file

@ -1,33 +0,0 @@
[UNORDERED_START]
Download http://localhost:4260/chalk
Download http://localhost:4260/chai
Download http://localhost:4260/ansi-styles
Download http://localhost:4260/supports-color
Download http://localhost:4260/assertion-error
Download http://localhost:4260/check-error
Download http://localhost:4260/deep-eql
Download http://localhost:4260/get-func-name
Download http://localhost:4260/loupe
Download http://localhost:4260/pathval
Download http://localhost:4260/type-detect
Download http://localhost:4260/color-convert
Download http://localhost:4260/has-flag
Download http://localhost:4260/color-name
[UNORDERED_END]
[UNORDERED_START]
Download http://localhost:4260/ansi-styles/ansi-styles-4.3.0.tgz
Download http://localhost:4260/assertion-error/assertion-error-1.1.0.tgz
Download http://localhost:4260/chai/chai-4.3.6.tgz
Download http://localhost:4260/chalk/chalk-4.1.2.tgz
Download http://localhost:4260/check-error/check-error-1.0.2.tgz
Download http://localhost:4260/color-convert/color-convert-2.0.1.tgz
Download http://localhost:4260/color-name/color-name-1.1.4.tgz
Download http://localhost:4260/deep-eql/deep-eql-3.0.1.tgz
Download http://localhost:4260/get-func-name/get-func-name-2.0.0.tgz
Download http://localhost:4260/has-flag/has-flag-4.0.0.tgz
Download http://localhost:4260/loupe/loupe-2.3.4.tgz
Download http://localhost:4260/pathval/pathval-1.1.1.tgz
Download http://localhost:4260/supports-color/supports-color-7.2.0.tgz
Download http://localhost:4260/type-detect/type-detect-4.0.8.tgz
[UNORDERED_END]
chalk cjs loads

View file

@ -1,47 +0,0 @@
[UNORDERED_START]
Download http://localhost:4260/chalk
Download http://localhost:4260/chai
Download http://localhost:4260/ansi-styles
Download http://localhost:4260/supports-color
Download http://localhost:4260/assertion-error
Download http://localhost:4260/check-error
Download http://localhost:4260/deep-eql
Download http://localhost:4260/get-func-name
Download http://localhost:4260/loupe
Download http://localhost:4260/pathval
Download http://localhost:4260/type-detect
Download http://localhost:4260/color-convert
Download http://localhost:4260/has-flag
Download http://localhost:4260/color-name
[UNORDERED_END]
[UNORDERED_START]
Download http://localhost:4260/ansi-styles/ansi-styles-4.3.0.tgz
Initialize ansi-styles@4.3.0
Download http://localhost:4260/assertion-error/assertion-error-1.1.0.tgz
Initialize assertion-error@1.1.0
Download http://localhost:4260/chai/chai-4.3.6.tgz
Initialize chai@4.3.6
Download http://localhost:4260/chalk/chalk-4.1.2.tgz
Initialize chalk@4.1.2
Download http://localhost:4260/check-error/check-error-1.0.2.tgz
Initialize check-error@1.0.2
Download http://localhost:4260/color-convert/color-convert-2.0.1.tgz
Initialize color-convert@2.0.1
Download http://localhost:4260/color-name/color-name-1.1.4.tgz
Initialize color-name@1.1.4
Download http://localhost:4260/deep-eql/deep-eql-3.0.1.tgz
Initialize deep-eql@3.0.1
Download http://localhost:4260/get-func-name/get-func-name-2.0.0.tgz
Initialize get-func-name@2.0.0
Download http://localhost:4260/has-flag/has-flag-4.0.0.tgz
Initialize has-flag@4.0.0
Download http://localhost:4260/loupe/loupe-2.3.4.tgz
Initialize loupe@2.3.4
Download http://localhost:4260/pathval/pathval-1.1.1.tgz
Initialize pathval@1.1.1
Download http://localhost:4260/supports-color/supports-color-7.2.0.tgz
Initialize supports-color@7.2.0
Download http://localhost:4260/type-detect/type-detect-4.0.8.tgz
Initialize type-detect@4.0.8
[UNORDERED_END]
chalk cjs loads

View file

@ -1,6 +1,6 @@
{ {
"tempDir": true, "tempDir": true,
"args": "info --quiet --node-modules-dir --json cjs_with_deps/main.js", "args": "info --quiet --node-modules-dir --json main.js",
"output": "cjs_with_deps/main_info_json.out", "output": "main_info_json.out",
"exitCode": 0 "exitCode": 0
} }

View file

@ -1,33 +0,0 @@
[UNORDERED_START]
Download http://localhost:4260/chalk
Download http://localhost:4260/chai
Download http://localhost:4260/ansi-styles
Download http://localhost:4260/supports-color
Download http://localhost:4260/assertion-error
Download http://localhost:4260/check-error
Download http://localhost:4260/deep-eql
Download http://localhost:4260/get-func-name
Download http://localhost:4260/loupe
Download http://localhost:4260/pathval
Download http://localhost:4260/type-detect
Download http://localhost:4260/color-convert
Download http://localhost:4260/has-flag
Download http://localhost:4260/color-name
[UNORDERED_END]
[UNORDERED_START]
Download http://localhost:4260/ansi-styles/ansi-styles-4.3.0.tgz
Download http://localhost:4260/assertion-error/assertion-error-1.1.0.tgz
Download http://localhost:4260/chai/chai-4.3.6.tgz
Download http://localhost:4260/chalk/chalk-4.1.2.tgz
Download http://localhost:4260/check-error/check-error-1.0.2.tgz
Download http://localhost:4260/color-convert/color-convert-2.0.1.tgz
Download http://localhost:4260/color-name/color-name-1.1.4.tgz
Download http://localhost:4260/deep-eql/deep-eql-3.0.1.tgz
Download http://localhost:4260/get-func-name/get-func-name-2.0.0.tgz
Download http://localhost:4260/has-flag/has-flag-4.0.0.tgz
Download http://localhost:4260/loupe/loupe-2.3.4.tgz
Download http://localhost:4260/pathval/pathval-1.1.1.tgz
Download http://localhost:4260/supports-color/supports-color-7.2.0.tgz
Download http://localhost:4260/type-detect/type-detect-4.0.8.tgz
[UNORDERED_END]
chalk cjs loads

View file

@ -1,22 +0,0 @@
local: [WILDCARD]main.js
type: JavaScript
dependencies: 14 unique
size: [WILDCARD]
file:///[WILDCARD]/cjs_with_deps/main.js ([WILDCARD])
├─┬ npm:/chalk@4.1.2 ([WILDCARD])
│ ├─┬ npm:/ansi-styles@4.3.0 ([WILDCARD])
│ │ └─┬ npm:/color-convert@2.0.1 ([WILDCARD])
│ │ └── npm:/color-name@1.1.4 ([WILDCARD])
│ └─┬ npm:/supports-color@7.2.0 ([WILDCARD])
│ └── npm:/has-flag@4.0.0 ([WILDCARD])
└─┬ npm:/chai@4.3.6 ([WILDCARD])
├── npm:/assertion-error@1.1.0 ([WILDCARD])
├── npm:/check-error@1.0.2 ([WILDCARD])
├─┬ npm:/deep-eql@3.0.1 ([WILDCARD])
│ └── npm:/type-detect@4.0.8 ([WILDCARD])
├── npm:/get-func-name@2.0.0 ([WILDCARD])
├─┬ npm:/loupe@2.3.4 ([WILDCARD])
│ └── npm:/get-func-name@2.0.0 ([WILDCARD])
├── npm:/pathval@1.1.1 ([WILDCARD])
└── npm:/type-detect@4.0.8 ([WILDCARD])

View file

@ -1,47 +0,0 @@
[UNORDERED_START]
Download http://localhost:4260/chalk
Download http://localhost:4260/chai
Download http://localhost:4260/ansi-styles
Download http://localhost:4260/supports-color
Download http://localhost:4260/assertion-error
Download http://localhost:4260/check-error
Download http://localhost:4260/deep-eql
Download http://localhost:4260/get-func-name
Download http://localhost:4260/loupe
Download http://localhost:4260/pathval
Download http://localhost:4260/type-detect
Download http://localhost:4260/color-convert
Download http://localhost:4260/has-flag
Download http://localhost:4260/color-name
[UNORDERED_END]
[UNORDERED_START]
Download http://localhost:4260/ansi-styles/ansi-styles-4.3.0.tgz
Initialize ansi-styles@4.3.0
Download http://localhost:4260/assertion-error/assertion-error-1.1.0.tgz
Initialize assertion-error@1.1.0
Download http://localhost:4260/chai/chai-4.3.6.tgz
Initialize chai@4.3.6
Download http://localhost:4260/chalk/chalk-4.1.2.tgz
Initialize chalk@4.1.2
Download http://localhost:4260/check-error/check-error-1.0.2.tgz
Initialize check-error@1.0.2
Download http://localhost:4260/color-convert/color-convert-2.0.1.tgz
Initialize color-convert@2.0.1
Download http://localhost:4260/color-name/color-name-1.1.4.tgz
Initialize color-name@1.1.4
Download http://localhost:4260/deep-eql/deep-eql-3.0.1.tgz
Initialize deep-eql@3.0.1
Download http://localhost:4260/get-func-name/get-func-name-2.0.0.tgz
Initialize get-func-name@2.0.0
Download http://localhost:4260/has-flag/has-flag-4.0.0.tgz
Initialize has-flag@4.0.0
Download http://localhost:4260/loupe/loupe-2.3.4.tgz
Initialize loupe@2.3.4
Download http://localhost:4260/pathval/pathval-1.1.1.tgz
Initialize pathval@1.1.1
Download http://localhost:4260/supports-color/supports-color-7.2.0.tgz
Initialize supports-color@7.2.0
Download http://localhost:4260/type-detect/type-detect-4.0.8.tgz
Initialize type-detect@4.0.8
[UNORDERED_END]
chalk cjs loads

View file

@ -1,5 +1,5 @@
{ {
"args": "info --quiet peer_deps_with_copied_folders/main.ts", "args": "info --quiet main.ts",
"output": "peer_deps_with_copied_folders/main_info.out", "output": "main_info.out",
"exitCode": 0 "exitCode": 0
} }

View file

@ -3,7 +3,7 @@ type: TypeScript
dependencies: 6 unique dependencies: 6 unique
size: [WILDCARD] size: [WILDCARD]
file:///[WILDCARD]/peer_deps_with_copied_folders/main.ts (171B) file:///[WILDCARD]/main.ts (171B)
├─┬ npm:/@denotest/peer-dep-test-child@1.0.0 ([WILDCARD]) ├─┬ npm:/@denotest/peer-dep-test-child@1.0.0 ([WILDCARD])
│ ├─┬ npm:/@denotest/peer-dep-test-grandchild@1.0.0_@denotest+peer-dep-test-peer@1.0.0 ([WILDCARD]) │ ├─┬ npm:/@denotest/peer-dep-test-grandchild@1.0.0_@denotest+peer-dep-test-peer@1.0.0 ([WILDCARD])
│ │ └── npm:/@denotest/peer-dep-test-peer@1.0.0 ([WILDCARD]) │ │ └── npm:/@denotest/peer-dep-test-peer@1.0.0 ([WILDCARD])

View file

@ -1,14 +0,0 @@
[UNORDERED_START]
Download http://localhost:4260/@denotest%2fpeer-dep-test-child
Download http://localhost:4260/@denotest%2fpeer-dep-test-grandchild
Download http://localhost:4260/@denotest%2fpeer-dep-test-peer
[UNORDERED_END]
[UNORDERED_START]
Download http://localhost:4260/@denotest/peer-dep-test-child/1.0.0.tgz
Download http://localhost:4260/@denotest/peer-dep-test-child/2.0.0.tgz
Download http://localhost:4260/@denotest/peer-dep-test-grandchild/1.0.0.tgz
Download http://localhost:4260/@denotest/peer-dep-test-peer/1.0.0.tgz
Download http://localhost:4260/@denotest/peer-dep-test-peer/2.0.0.tgz
[UNORDERED_END]
1
2

View file

@ -1,97 +0,0 @@
{
"version": 1,
"roots": [
"[WILDCARD]/peer_deps_with_copied_folders/main.ts"
],
"modules": [
{
"kind": "esm",
"dependencies": [
{
"specifier": "npm:@denotest/peer-dep-test-child@1",
"code": {
"specifier": "npm:@denotest/peer-dep-test-child@1",
"span": {
"start": {
"line": 0,
"character": 21
},
"end": {
"line": 0,
"character": 58
}
}
},
"npmPackage": "@denotest/peer-dep-test-child@1.0.0_@denotest+peer-dep-test-peer@1.0.0"
},
{
"specifier": "npm:@denotest/peer-dep-test-child@2",
"code": {
"specifier": "npm:@denotest/peer-dep-test-child@2",
"span": {
"start": {
"line": 1,
"character": 21
},
"end": {
"line": 1,
"character": 58
}
}
},
"npmPackage": "@denotest/peer-dep-test-child@2.0.0_@denotest+peer-dep-test-peer@2.0.0"
}
],
"local": "[WILDCARD]main.ts",
"size": 171,
"mediaType": "TypeScript",
"specifier": "file://[WILDCARD]/main.ts"
}
],
"redirects": {
"npm:@denotest/peer-dep-test-child@1": "npm:/@denotest/peer-dep-test-child@1.0.0",
"npm:@denotest/peer-dep-test-child@2": "npm:/@denotest/peer-dep-test-child@2.0.0"
},
"npmPackages": {
"@denotest/peer-dep-test-child@1.0.0_@denotest+peer-dep-test-peer@1.0.0": {
"name": "@denotest/peer-dep-test-child",
"version": "1.0.0",
"dependencies": [
"@denotest/peer-dep-test-grandchild@1.0.0_@denotest+peer-dep-test-peer@1.0.0",
"@denotest/peer-dep-test-peer@1.0.0"
]
},
"@denotest/peer-dep-test-child@2.0.0_@denotest+peer-dep-test-peer@2.0.0": {
"name": "@denotest/peer-dep-test-child",
"version": "2.0.0",
"dependencies": [
"@denotest/peer-dep-test-grandchild@1.0.0_@denotest+peer-dep-test-peer@2.0.0",
"@denotest/peer-dep-test-peer@2.0.0"
]
},
"@denotest/peer-dep-test-grandchild@1.0.0_@denotest+peer-dep-test-peer@1.0.0": {
"name": "@denotest/peer-dep-test-grandchild",
"version": "1.0.0",
"dependencies": [
"@denotest/peer-dep-test-peer@1.0.0"
]
},
"@denotest/peer-dep-test-grandchild@1.0.0_@denotest+peer-dep-test-peer@2.0.0": {
"name": "@denotest/peer-dep-test-grandchild",
"version": "1.0.0",
"dependencies": [
"@denotest/peer-dep-test-peer@2.0.0"
]
},
"@denotest/peer-dep-test-peer@1.0.0": {
"name": "@denotest/peer-dep-test-peer",
"version": "1.0.0",
"dependencies": []
},
"@denotest/peer-dep-test-peer@2.0.0": {
"name": "@denotest/peer-dep-test-peer",
"version": "2.0.0",
"dependencies": []
}
}
}

View file

@ -1,9 +0,0 @@
[UNORDERED_START]
Initialize @denotest/peer-dep-test-child@1.0.0
Initialize @denotest/peer-dep-test-child@2.0.0
Initialize @denotest/peer-dep-test-grandchild@1.0.0
Initialize @denotest/peer-dep-test-peer@1.0.0
Initialize @denotest/peer-dep-test-peer@2.0.0
[UNORDERED_END]
1
2

View file

@ -1,19 +0,0 @@
[UNORDERED_START]
Download http://localhost:4260/@denotest%2fpeer-dep-test-child
Download http://localhost:4260/@denotest%2fpeer-dep-test-grandchild
Download http://localhost:4260/@denotest%2fpeer-dep-test-peer
[UNORDERED_END]
[UNORDERED_START]
Download http://localhost:4260/@denotest/peer-dep-test-child/1.0.0.tgz
Initialize @denotest/peer-dep-test-child@1.0.0
Download http://localhost:4260/@denotest/peer-dep-test-child/2.0.0.tgz
Initialize @denotest/peer-dep-test-child@2.0.0
Download http://localhost:4260/@denotest/peer-dep-test-grandchild/1.0.0.tgz
Initialize @denotest/peer-dep-test-grandchild@1.0.0
Download http://localhost:4260/@denotest/peer-dep-test-peer/1.0.0.tgz
Initialize @denotest/peer-dep-test-peer@1.0.0
Download http://localhost:4260/@denotest/peer-dep-test-peer/2.0.0.tgz
Initialize @denotest/peer-dep-test-peer@2.0.0
[UNORDERED_END]
1
2

View file

@ -1,5 +1,5 @@
{ {
"args": "info --quiet --json peer_deps_with_copied_folders/main.ts", "args": "info --quiet --json main.ts",
"output": "peer_deps_with_copied_folders/main_info_json.out", "output": "main_info_json.out",
"exitCode": 0 "exitCode": 0
} }

View file

@ -1,14 +0,0 @@
[UNORDERED_START]
Download http://localhost:4260/@denotest%2fpeer-dep-test-child
Download http://localhost:4260/@denotest%2fpeer-dep-test-grandchild
Download http://localhost:4260/@denotest%2fpeer-dep-test-peer
[UNORDERED_END]
[UNORDERED_START]
Download http://localhost:4260/@denotest/peer-dep-test-child/1.0.0.tgz
Download http://localhost:4260/@denotest/peer-dep-test-child/2.0.0.tgz
Download http://localhost:4260/@denotest/peer-dep-test-grandchild/1.0.0.tgz
Download http://localhost:4260/@denotest/peer-dep-test-peer/1.0.0.tgz
Download http://localhost:4260/@denotest/peer-dep-test-peer/2.0.0.tgz
[UNORDERED_END]
1
2

View file

@ -1,14 +0,0 @@
local: [WILDCARD]main.ts
type: TypeScript
dependencies: 6 unique
size: [WILDCARD]
file:///[WILDCARD]/peer_deps_with_copied_folders/main.ts (171B)
├─┬ npm:/@denotest/peer-dep-test-child@1.0.0 ([WILDCARD])
│ ├─┬ npm:/@denotest/peer-dep-test-grandchild@1.0.0_@denotest+peer-dep-test-peer@1.0.0 ([WILDCARD])
│ │ └── npm:/@denotest/peer-dep-test-peer@1.0.0 ([WILDCARD])
│ └── npm:/@denotest/peer-dep-test-peer@1.0.0 ([WILDCARD])
└─┬ npm:/@denotest/peer-dep-test-child@2.0.0 ([WILDCARD])
├─┬ npm:/@denotest/peer-dep-test-grandchild@1.0.0_@denotest+peer-dep-test-peer@2.0.0 ([WILDCARD])
│ └── npm:/@denotest/peer-dep-test-peer@2.0.0 ([WILDCARD])
└── npm:/@denotest/peer-dep-test-peer@2.0.0 ([WILDCARD])

View file

@ -1,9 +0,0 @@
[UNORDERED_START]
Initialize @denotest/peer-dep-test-child@1.0.0
Initialize @denotest/peer-dep-test-child@2.0.0
Initialize @denotest/peer-dep-test-grandchild@1.0.0
Initialize @denotest/peer-dep-test-peer@1.0.0
Initialize @denotest/peer-dep-test-peer@2.0.0
[UNORDERED_END]
1
2

View file

@ -1,19 +0,0 @@
[UNORDERED_START]
Download http://localhost:4260/@denotest%2fpeer-dep-test-child
Download http://localhost:4260/@denotest%2fpeer-dep-test-grandchild
Download http://localhost:4260/@denotest%2fpeer-dep-test-peer
[UNORDERED_END]
[UNORDERED_START]
Download http://localhost:4260/@denotest/peer-dep-test-child/1.0.0.tgz
Initialize @denotest/peer-dep-test-child@1.0.0
Download http://localhost:4260/@denotest/peer-dep-test-child/2.0.0.tgz
Initialize @denotest/peer-dep-test-child@2.0.0
Download http://localhost:4260/@denotest/peer-dep-test-grandchild/1.0.0.tgz
Initialize @denotest/peer-dep-test-grandchild@1.0.0
Download http://localhost:4260/@denotest/peer-dep-test-peer/1.0.0.tgz
Initialize @denotest/peer-dep-test-peer@1.0.0
Download http://localhost:4260/@denotest/peer-dep-test-peer/2.0.0.tgz
Initialize @denotest/peer-dep-test-peer@2.0.0
[UNORDERED_END]
1
2