summaryrefslogtreecommitdiff
path: root/ext/node
diff options
context:
space:
mode:
Diffstat (limited to 'ext/node')
-rw-r--r--ext/node/Cargo.toml2
-rw-r--r--ext/node/analyze.rs22
-rw-r--r--ext/node/lib.rs4
-rw-r--r--ext/node/ops/require.rs68
-rw-r--r--ext/node/package_json.rs288
-rw-r--r--ext/node/polyfills/01_require.js2
-rw-r--r--ext/node/resolution.rs380
7 files changed, 292 insertions, 474 deletions
diff --git a/ext/node/Cargo.toml b/ext/node/Cargo.toml
index 8b5895bc7..425364792 100644
--- a/ext/node/Cargo.toml
+++ b/ext/node/Cargo.toml
@@ -23,9 +23,11 @@ bytes.workspace = true
cbc.workspace = true
const-oid = "0.9.5"
data-encoding.workspace = true
+deno_config = { workspace = true, default-features = false, features = ["package_json"] }
deno_core.workspace = true
deno_fetch.workspace = true
deno_fs.workspace = true
+deno_io.workspace = true
deno_media_type.workspace = true
deno_net.workspace = true
deno_permissions.workspace = true
diff --git a/ext/node/analyze.rs b/ext/node/analyze.rs
index d80108733..0a4ff8dac 100644
--- a/ext/node/analyze.rs
+++ b/ext/node/analyze.rs
@@ -16,13 +16,12 @@ use once_cell::sync::Lazy;
use deno_core::error::AnyError;
+use crate::package_json::load_pkg_json;
use crate::path::to_file_specifier;
use crate::resolution::NodeResolverRc;
-use crate::AllowAllNodePermissions;
use crate::NodeModuleKind;
use crate::NodeResolutionMode;
use crate::NpmResolverRc;
-use crate::PackageJson;
use crate::PathClean;
#[derive(Debug, Clone)]
@@ -312,13 +311,8 @@ impl<TCjsCodeAnalyzer: CjsCodeAnalyzer> NodeCodeTranslator<TCjsCodeAnalyzer> {
)?;
let package_json_path = module_dir.join("package.json");
- let package_json = PackageJson::load(
- &*self.fs,
- &*self.npm_resolver,
- &mut AllowAllNodePermissions,
- package_json_path.clone(),
- )?;
- if package_json.exists {
+ let maybe_package_json = load_pkg_json(&*self.fs, &package_json_path)?;
+ if let Some(package_json) = maybe_package_json {
if let Some(exports) = &package_json.exports {
return self.node_resolver.package_exports_resolve(
&package_json_path,
@@ -337,13 +331,9 @@ impl<TCjsCodeAnalyzer: CjsCodeAnalyzer> NodeCodeTranslator<TCjsCodeAnalyzer> {
if self.fs.is_dir_sync(&d) {
// subdir might have a package.json that specifies the entrypoint
let package_json_path = d.join("package.json");
- let package_json = PackageJson::load(
- &*self.fs,
- &*self.npm_resolver,
- &mut AllowAllNodePermissions,
- package_json_path,
- )?;
- if package_json.exists {
+ let maybe_package_json =
+ load_pkg_json(&*self.fs, &package_json_path)?;
+ if let Some(package_json) = maybe_package_json {
if let Some(main) = package_json.main(NodeModuleKind::Cjs) {
return Ok(to_file_specifier(&d.join(main).clean()));
}
diff --git a/ext/node/lib.rs b/ext/node/lib.rs
index d0a8e24d5..ff979a8ba 100644
--- a/ext/node/lib.rs
+++ b/ext/node/lib.rs
@@ -32,6 +32,7 @@ mod path;
mod polyfill;
mod resolution;
+pub use deno_config::package_json::PackageJson;
pub use ops::ipc::ChildPipeFd;
pub use ops::ipc::IpcJsonStreamResource;
use ops::vm;
@@ -39,7 +40,8 @@ pub use ops::vm::create_v8_context;
pub use ops::vm::init_global_template;
pub use ops::vm::ContextInitMode;
pub use ops::vm::VM_CONTEXT_INDEX;
-pub use package_json::PackageJson;
+pub use package_json::load_pkg_json;
+pub use package_json::PackageJsonThreadLocalCache;
pub use path::PathClean;
pub use polyfill::is_builtin_node_module;
pub use polyfill::SUPPORTED_BUILTIN_NODE_MODULES;
diff --git a/ext/node/ops/require.rs b/ext/node/ops/require.rs
index 3fde6c31a..3702a9047 100644
--- a/ext/node/ops/require.rs
+++ b/ext/node/ops/require.rs
@@ -17,7 +17,6 @@ use std::rc::Rc;
use crate::resolution;
use crate::resolution::NodeResolverRc;
-use crate::AllowAllNodePermissions;
use crate::NodeModuleKind;
use crate::NodePermissions;
use crate::NodeResolutionMode;
@@ -390,7 +389,6 @@ where
let pkg = node_resolver
.get_closest_package_json(
&Url::from_file_path(parent_path.unwrap()).unwrap(),
- &mut AllowAllNodePermissions,
)
.ok()
.flatten();
@@ -497,30 +495,30 @@ where
original
}
};
- let pkg = node_resolver.load_package_json(
- &mut AllowAllNodePermissions,
- PathBuf::from(&pkg_path).join("package.json"),
- )?;
+ let Some(pkg) = node_resolver
+ .load_package_json(&PathBuf::from(&pkg_path).join("package.json"))?
+ else {
+ return Ok(None);
+ };
+ let Some(exports) = &pkg.exports else {
+ return Ok(None);
+ };
- if let Some(exports) = &pkg.exports {
- let referrer = Url::from_file_path(parent_path).unwrap();
- let r = node_resolver.package_exports_resolve(
- &pkg.path,
- &format!(".{expansion}"),
- exports,
- &referrer,
- NodeModuleKind::Cjs,
- resolution::REQUIRE_CONDITIONS,
- NodeResolutionMode::Execution,
- )?;
- Ok(Some(if r.scheme() == "file" {
- url_to_file_path_string(&r)?
- } else {
- r.to_string()
- }))
+ let referrer = Url::from_file_path(parent_path).unwrap();
+ let r = node_resolver.package_exports_resolve(
+ &pkg.path,
+ &format!(".{expansion}"),
+ exports,
+ &referrer,
+ NodeModuleKind::Cjs,
+ resolution::REQUIRE_CONDITIONS,
+ NodeResolutionMode::Execution,
+ )?;
+ Ok(Some(if r.scheme() == "file" {
+ url_to_file_path_string(&r)?
} else {
- Ok(None)
- }
+ r.to_string()
+ }))
}
#[op2]
@@ -537,12 +535,8 @@ where
PathBuf::from(&filename).parent().unwrap(),
)?;
let node_resolver = state.borrow::<NodeResolverRc>().clone();
- let permissions = state.borrow_mut::<P>();
node_resolver
- .get_closest_package_json(
- &Url::from_file_path(filename).unwrap(),
- permissions,
- )
+ .get_closest_package_json(&Url::from_file_path(filename).unwrap())
.map(|maybe_pkg| maybe_pkg.map(|pkg| (*pkg).clone()))
}
@@ -556,12 +550,16 @@ where
P: NodePermissions + 'static,
{
let node_resolver = state.borrow::<NodeResolverRc>().clone();
- let permissions = state.borrow_mut::<P>();
let package_json_path = PathBuf::from(package_json_path);
+ if package_json_path.file_name() != Some("package.json".as_ref()) {
+ // permissions: do not allow reading a non-package.json file
+ return None;
+ }
node_resolver
- .load_package_json(permissions, package_json_path)
- .map(|pkg| (*pkg).clone())
+ .load_package_json(&package_json_path)
.ok()
+ .flatten()
+ .map(|pkg| (*pkg).clone())
}
#[op2]
@@ -577,10 +575,8 @@ where
let referrer_path = PathBuf::from(&referrer_filename);
ensure_read_permission::<P>(state, &referrer_path)?;
let node_resolver = state.borrow::<NodeResolverRc>();
- let Some(pkg) = node_resolver.get_closest_package_json_from_path(
- &referrer_path,
- &mut AllowAllNodePermissions,
- )?
+ let Some(pkg) =
+ node_resolver.get_closest_package_json_from_path(&referrer_path)?
else {
return Ok(None);
};
diff --git a/ext/node/package_json.rs b/ext/node/package_json.rs
index a19a2d64d..8a88fe8f1 100644
--- a/ext/node/package_json.rs
+++ b/ext/node/package_json.rs
@@ -1,272 +1,58 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
-use crate::NodeModuleKind;
-use crate::NodePermissions;
-
-use super::NpmResolver;
-
-use deno_core::anyhow;
-use deno_core::anyhow::bail;
-use deno_core::error::AnyError;
-use deno_core::serde_json;
-use deno_core::serde_json::Map;
-use deno_core::serde_json::Value;
-use deno_core::ModuleSpecifier;
-use indexmap::IndexMap;
-use serde::Serialize;
+use deno_config::package_json::PackageJson;
+use deno_config::package_json::PackageJsonLoadError;
+use deno_config::package_json::PackageJsonRc;
+use deno_fs::DenoConfigFsAdapter;
use std::cell::RefCell;
use std::collections::HashMap;
use std::io::ErrorKind;
+use std::path::Path;
use std::path::PathBuf;
-use std::rc::Rc;
+// use a thread local cache so that workers have their own distinct cache
thread_local! {
- static CACHE: RefCell<HashMap<PathBuf, Rc<PackageJson>>> = RefCell::new(HashMap::new());
+ static CACHE: RefCell<HashMap<PathBuf, PackageJsonRc>> = RefCell::new(HashMap::new());
}
-#[derive(Clone, Debug, Serialize)]
-pub struct PackageJson {
- pub exists: bool,
- pub exports: Option<Map<String, Value>>,
- pub imports: Option<Map<String, Value>>,
- pub bin: Option<Value>,
- main: Option<String>, // use .main(...)
- module: Option<String>, // use .main(...)
- pub name: Option<String>,
- pub version: Option<String>,
- pub path: PathBuf,
- pub typ: String,
- pub types: Option<String>,
- pub dependencies: Option<IndexMap<String, String>>,
- pub dev_dependencies: Option<IndexMap<String, String>>,
- pub scripts: Option<IndexMap<String, String>>,
-}
-
-impl PackageJson {
- pub fn empty(path: PathBuf) -> PackageJson {
- PackageJson {
- exists: false,
- exports: None,
- imports: None,
- bin: None,
- main: None,
- module: None,
- name: None,
- version: None,
- path,
- typ: "none".to_string(),
- types: None,
- dependencies: None,
- dev_dependencies: None,
- scripts: None,
- }
- }
-
- pub fn load(
- fs: &dyn deno_fs::FileSystem,
- resolver: &dyn NpmResolver,
- permissions: &mut dyn NodePermissions,
- path: PathBuf,
- ) -> Result<Rc<PackageJson>, AnyError> {
- resolver.ensure_read_permission(permissions, &path)?;
- Self::load_skip_read_permission(fs, path)
- }
-
- pub fn load_skip_read_permission(
- fs: &dyn deno_fs::FileSystem,
- path: PathBuf,
- ) -> Result<Rc<PackageJson>, AnyError> {
- assert!(path.is_absolute());
-
- if CACHE.with(|cache| cache.borrow().contains_key(&path)) {
- return Ok(CACHE.with(|cache| cache.borrow()[&path].clone()));
- }
-
- let source = match fs.read_text_file_lossy_sync(&path, None) {
- Ok(source) => source,
- Err(err) if err.kind() == ErrorKind::NotFound => {
- return Ok(Rc::new(PackageJson::empty(path)));
- }
- Err(err) => bail!(
- "Error loading package.json at {}. {:#}",
- path.display(),
- AnyError::from(err),
- ),
- };
-
- let package_json = Rc::new(Self::load_from_string(path, source)?);
- CACHE.with(|cache| {
- cache
- .borrow_mut()
- .insert(package_json.path.clone(), package_json.clone());
- });
- Ok(package_json)
- }
-
- pub fn load_from_string(
- path: PathBuf,
- source: String,
- ) -> Result<PackageJson, AnyError> {
- if source.trim().is_empty() {
- return Ok(PackageJson::empty(path));
- }
-
- let package_json: Value = serde_json::from_str(&source).map_err(|err| {
- anyhow::anyhow!(
- "malformed package.json: {}\n at {}",
- err,
- path.display()
- )
- })?;
- Self::load_from_value(path, package_json)
- }
-
- pub fn load_from_value(
- path: PathBuf,
- package_json: serde_json::Value,
- ) -> Result<PackageJson, AnyError> {
- let imports_val = package_json.get("imports");
- let main_val = package_json.get("main");
- let module_val = package_json.get("module");
- let name_val = package_json.get("name");
- let version_val = package_json.get("version");
- let type_val = package_json.get("type");
- let bin = package_json.get("bin").map(ToOwned::to_owned);
- let exports = package_json.get("exports").and_then(|exports| {
- Some(if is_conditional_exports_main_sugar(exports) {
- let mut map = Map::new();
- map.insert(".".to_string(), exports.to_owned());
- map
- } else {
- exports.as_object()?.to_owned()
- })
- });
-
- let imports = imports_val
- .and_then(|imp| imp.as_object())
- .map(|imp| imp.to_owned());
- let main = main_val.and_then(|s| s.as_str()).map(|s| s.to_string());
- let name = name_val.and_then(|s| s.as_str()).map(|s| s.to_string());
- let version = version_val.and_then(|s| s.as_str()).map(|s| s.to_string());
- let module = module_val.and_then(|s| s.as_str()).map(|s| s.to_string());
-
- let dependencies = package_json.get("dependencies").and_then(|d| {
- if d.is_object() {
- let deps: IndexMap<String, String> =
- serde_json::from_value(d.to_owned()).unwrap();
- Some(deps)
- } else {
- None
- }
- });
- let dev_dependencies = package_json.get("devDependencies").and_then(|d| {
- if d.is_object() {
- let deps: IndexMap<String, String> =
- serde_json::from_value(d.to_owned()).unwrap();
- Some(deps)
- } else {
- None
- }
- });
-
- let scripts: Option<IndexMap<String, String>> = package_json
- .get("scripts")
- .and_then(|d| serde_json::from_value(d.to_owned()).ok());
-
- // Ignore unknown types for forwards compatibility
- let typ = if let Some(t) = type_val {
- if let Some(t) = t.as_str() {
- if t != "module" && t != "commonjs" {
- "none".to_string()
- } else {
- t.to_string()
- }
- } else {
- "none".to_string()
- }
- } else {
- "none".to_string()
- };
-
- // for typescript, it looks for "typings" first, then "types"
- let types = package_json
- .get("typings")
- .or_else(|| package_json.get("types"))
- .and_then(|t| t.as_str().map(|s| s.to_string()));
-
- let package_json = PackageJson {
- exists: true,
- path,
- main,
- name,
- version,
- module,
- typ,
- types,
- exports,
- imports,
- bin,
- dependencies,
- dev_dependencies,
- scripts,
- };
-
- Ok(package_json)
- }
-
- pub fn main(&self, referrer_kind: NodeModuleKind) -> Option<&str> {
- let main = if referrer_kind == NodeModuleKind::Esm && self.typ == "module" {
- self.module.as_ref().or(self.main.as_ref())
- } else {
- self.main.as_ref()
- };
- main.map(|m| m.trim()).filter(|m| !m.is_empty())
- }
+pub struct PackageJsonThreadLocalCache;
- pub fn specifier(&self) -> ModuleSpecifier {
- ModuleSpecifier::from_file_path(&self.path).unwrap()
+impl PackageJsonThreadLocalCache {
+ pub fn clear() {
+ CACHE.with(|cache| cache.borrow_mut().clear());
}
}
-fn is_conditional_exports_main_sugar(exports: &Value) -> bool {
- if exports.is_string() || exports.is_array() {
- return true;
+impl deno_config::package_json::PackageJsonCache
+ for PackageJsonThreadLocalCache
+{
+ fn get(&self, path: &Path) -> Option<PackageJsonRc> {
+ CACHE.with(|cache| cache.borrow().get(path).cloned())
}
- if exports.is_null() || !exports.is_object() {
- return false;
- }
-
- let exports_obj = exports.as_object().unwrap();
- let mut is_conditional_sugar = false;
- let mut i = 0;
- for key in exports_obj.keys() {
- let cur_is_conditional_sugar = key.is_empty() || !key.starts_with('.');
- if i == 0 {
- is_conditional_sugar = cur_is_conditional_sugar;
- i += 1;
- } else if is_conditional_sugar != cur_is_conditional_sugar {
- panic!("\"exports\" cannot contains some keys starting with \'.\' and some not.
- The exports object must either be an object of package subpath keys
- or an object of main entry condition name keys only.")
- }
+ fn set(&self, path: PathBuf, package_json: PackageJsonRc) {
+ CACHE.with(|cache| cache.borrow_mut().insert(path, package_json));
}
-
- is_conditional_sugar
}
-#[cfg(test)]
-mod test {
- use super::*;
-
- #[test]
- fn null_exports_should_not_crash() {
- let package_json = PackageJson::load_from_string(
- PathBuf::from("/package.json"),
- r#"{ "exports": null }"#.to_string(),
- )
- .unwrap();
-
- assert!(package_json.exports.is_none());
+/// Helper to load a package.json file using the thread local cache
+/// in deno_node.
+pub fn load_pkg_json(
+ fs: &dyn deno_fs::FileSystem,
+ path: &Path,
+) -> Result<Option<PackageJsonRc>, PackageJsonLoadError> {
+ let result = PackageJson::load_from_path(
+ path,
+ &DenoConfigFsAdapter::new(fs),
+ Some(&PackageJsonThreadLocalCache),
+ );
+ match result {
+ Ok(pkg_json) => Ok(Some(pkg_json)),
+ Err(PackageJsonLoadError::Io { source, .. })
+ if source.kind() == ErrorKind::NotFound =>
+ {
+ Ok(None)
+ }
+ Err(err) => Err(err),
}
}
diff --git a/ext/node/polyfills/01_require.js b/ext/node/polyfills/01_require.js
index bdd91e0b4..da598fe29 100644
--- a/ext/node/polyfills/01_require.js
+++ b/ext/node/polyfills/01_require.js
@@ -1055,7 +1055,7 @@ Module._extensions[".js"] = function (module, filename) {
if (StringPrototypeEndsWith(filename, ".js")) {
const pkg = op_require_read_closest_package_json(filename);
- if (pkg && pkg.exists && pkg.typ === "module") {
+ if (pkg && pkg.typ === "module") {
throw createRequireEsmError(
filename,
moduleParentCache.get(module)?.filename,
diff --git a/ext/node/resolution.rs b/ext/node/resolution.rs
index 8047ac4ec..1b9a20012 100644
--- a/ext/node/resolution.rs
+++ b/ext/node/resolution.rs
@@ -4,10 +4,9 @@ use std::borrow::Cow;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
-use std::rc::Rc;
+use deno_config::package_json::PackageJsonRc;
use deno_core::anyhow::bail;
-use deno_core::anyhow::Context;
use deno_core::error::generic_error;
use deno_core::error::AnyError;
use deno_core::serde_json::Map;
@@ -21,8 +20,6 @@ use crate::errors;
use crate::is_builtin_node_module;
use crate::path::to_file_specifier;
use crate::polyfill::get_module_name_from_builtin_node_module_specifier;
-use crate::AllowAllNodePermissions;
-use crate::NodePermissions;
use crate::NpmResolverRc;
use crate::PackageJson;
use crate::PathClean;
@@ -30,11 +27,7 @@ use crate::PathClean;
pub static DEFAULT_CONDITIONS: &[&str] = &["deno", "node", "import"];
pub static REQUIRE_CONDITIONS: &[&str] = &["require", "node"];
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum NodeModuleKind {
- Esm,
- Cjs,
-}
+pub type NodeModuleKind = deno_config::package_json::NodeModuleKind;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NodeResolutionMode {
@@ -236,8 +229,7 @@ impl NodeResolver {
Some(resolved_specifier)
}
} else if specifier.starts_with('#') {
- let pkg_config = self
- .get_closest_package_json(referrer, &mut AllowAllNodePermissions)?;
+ let pkg_config = self.get_closest_package_json(referrer)?;
Some(self.package_imports_resolve(
specifier,
referrer,
@@ -325,31 +317,18 @@ impl NodeResolver {
referrer: &ModuleSpecifier,
mode: NodeResolutionMode,
) -> Result<Option<NodeResolution>, AnyError> {
- let package_json_path = package_dir.join("package.json");
- let package_json = self.load_package_json(
- &mut AllowAllNodePermissions,
- package_json_path.clone(),
- )?;
let node_module_kind = NodeModuleKind::Esm;
let package_subpath = package_subpath
.map(|s| format!("./{s}"))
.unwrap_or_else(|| ".".to_string());
- let maybe_resolved_url = self
- .resolve_package_subpath(
- &package_json,
- &package_subpath,
- referrer,
- node_module_kind,
- DEFAULT_CONDITIONS,
- mode,
- )
- .with_context(|| {
- format!(
- "Failed resolving package subpath '{}' for '{}'",
- package_subpath,
- package_json.path.display()
- )
- })?;
+ let maybe_resolved_url = self.resolve_package_dir_subpath(
+ package_dir,
+ &package_subpath,
+ referrer,
+ node_module_kind,
+ DEFAULT_CONDITIONS,
+ mode,
+ )?;
let resolved_url = match maybe_resolved_url {
Some(resolved_path) => resolved_path,
None => return Ok(None),
@@ -383,10 +362,9 @@ impl NodeResolver {
package_folder: &Path,
) -> Result<Vec<String>, AnyError> {
let package_json_path = package_folder.join("package.json");
- let package_json = self.load_package_json(
- &mut AllowAllNodePermissions,
- package_json_path.clone(),
- )?;
+ let Some(package_json) = self.load_package_json(&package_json_path)? else {
+ return Ok(Vec::new());
+ };
Ok(match &package_json.bin {
Some(Value::String(_)) => {
@@ -408,10 +386,12 @@ impl NodeResolver {
sub_path: Option<&str>,
) -> Result<NodeResolution, AnyError> {
let package_json_path = package_folder.join("package.json");
- let package_json = self.load_package_json(
- &mut AllowAllNodePermissions,
- package_json_path.clone(),
- )?;
+ let Some(package_json) = self.load_package_json(&package_json_path)? else {
+ bail!(
+ "Failed resolving binary export. '{}' did not exist",
+ package_json_path.display(),
+ )
+ };
let bin_entry = resolve_bin_entry_value(&package_json, sub_path)?;
let url = to_file_specifier(&package_folder.join(bin_entry));
@@ -429,8 +409,7 @@ impl NodeResolver {
if url_str.starts_with("http") || url_str.ends_with(".json") {
Ok(NodeResolution::Esm(url))
} else if url_str.ends_with(".js") || url_str.ends_with(".d.ts") {
- let maybe_package_config =
- self.get_closest_package_json(&url, &mut AllowAllNodePermissions)?;
+ let maybe_package_config = self.get_closest_package_json(&url)?;
match maybe_package_config {
Some(c) if c.typ == "module" => Ok(NodeResolution::Esm(url)),
Some(_) => Ok(NodeResolution::CommonJs(url)),
@@ -515,24 +494,19 @@ impl NodeResolver {
return Ok(Some(to_file_specifier(&path)));
}
if self.fs.is_dir_sync(&path) {
- let package_json_path = path.join("package.json");
- if let Ok(pkg_json) =
- self.load_package_json(&mut AllowAllNodePermissions, package_json_path)
- {
- let maybe_resolution = self.resolve_package_subpath(
- &pkg_json,
- /* sub path */ ".",
- referrer,
- referrer_kind,
- match referrer_kind {
- NodeModuleKind::Esm => DEFAULT_CONDITIONS,
- NodeModuleKind::Cjs => REQUIRE_CONDITIONS,
- },
- NodeResolutionMode::Types,
- )?;
- if let Some(resolution) = maybe_resolution {
- return Ok(Some(resolution));
- }
+ let maybe_resolution = self.resolve_package_dir_subpath(
+ &path,
+ /* sub path */ ".",
+ referrer,
+ referrer_kind,
+ match referrer_kind {
+ NodeModuleKind::Esm => DEFAULT_CONDITIONS,
+ NodeModuleKind::Cjs => REQUIRE_CONDITIONS,
+ },
+ NodeResolutionMode::Types,
+ )?;
+ if let Some(resolution) = maybe_resolution {
+ return Ok(Some(resolution));
}
let index_path = path.join("index.js");
if let Some(path) = probe_extensions(
@@ -572,19 +546,59 @@ impl NodeResolver {
let mut package_json_path = None;
if let Some(pkg_json) = &referrer_pkg_json {
- if pkg_json.exists {
- package_json_path = Some(pkg_json.path.clone());
- if let Some(imports) = &pkg_json.imports {
- if imports.contains_key(name) && !name.contains('*') {
- let target = imports.get(name).unwrap();
+ package_json_path = Some(pkg_json.path.clone());
+ if let Some(imports) = &pkg_json.imports {
+ if imports.contains_key(name) && !name.contains('*') {
+ let target = imports.get(name).unwrap();
+ let maybe_resolved = self.resolve_package_target(
+ package_json_path.as_ref().unwrap(),
+ target,
+ "",
+ name,
+ referrer,
+ referrer_kind,
+ false,
+ true,
+ conditions,
+ mode,
+ )?;
+ if let Some(resolved) = maybe_resolved {
+ return Ok(resolved);
+ }
+ } else {
+ let mut best_match = "";
+ let mut best_match_subpath = None;
+ for key in imports.keys() {
+ let pattern_index = key.find('*');
+ if let Some(pattern_index) = pattern_index {
+ let key_sub = &key[0..=pattern_index];
+ if name.starts_with(key_sub) {
+ let pattern_trailer = &key[pattern_index + 1..];
+ if name.len() > key.len()
+ && name.ends_with(&pattern_trailer)
+ && pattern_key_compare(best_match, key) == 1
+ && key.rfind('*') == Some(pattern_index)
+ {
+ best_match = key;
+ best_match_subpath = Some(
+ name[pattern_index..=(name.len() - pattern_trailer.len())]
+ .to_string(),
+ );
+ }
+ }
+ }
+ }
+
+ if !best_match.is_empty() {
+ let target = imports.get(best_match).unwrap();
let maybe_resolved = self.resolve_package_target(
package_json_path.as_ref().unwrap(),
target,
- "",
- name,
+ &best_match_subpath.unwrap(),
+ best_match,
referrer,
referrer_kind,
- false,
+ true,
true,
conditions,
mode,
@@ -592,49 +606,6 @@ impl NodeResolver {
if let Some(resolved) = maybe_resolved {
return Ok(resolved);
}
- } else {
- let mut best_match = "";
- let mut best_match_subpath = None;
- for key in imports.keys() {
- let pattern_index = key.find('*');
- if let Some(pattern_index) = pattern_index {
- let key_sub = &key[0..=pattern_index];
- if name.starts_with(key_sub) {
- let pattern_trailer = &key[pattern_index + 1..];
- if name.len() > key.len()
- && name.ends_with(&pattern_trailer)
- && pattern_key_compare(best_match, key) == 1
- && key.rfind('*') == Some(pattern_index)
- {
- best_match = key;
- best_match_subpath = Some(
- name
- [pattern_index..=(name.len() - pattern_trailer.len())]
- .to_string(),
- );
- }
- }
- }
- }
-
- if !best_match.is_empty() {
- let target = imports.get(best_match).unwrap();
- let maybe_resolved = self.resolve_package_target(
- package_json_path.as_ref().unwrap(),
- target,
- &best_match_subpath.unwrap(),
- best_match,
- referrer,
- referrer_kind,
- true,
- true,
- conditions,
- mode,
- )?;
- if let Some(resolved) = maybe_resolved {
- return Ok(resolved);
- }
- }
}
}
}
@@ -1013,15 +984,11 @@ impl NodeResolver {
let (package_name, package_subpath, _is_scoped) =
parse_npm_pkg_name(specifier, referrer)?;
- let Some(package_config) =
- self.get_closest_package_json(referrer, &mut AllowAllNodePermissions)?
- else {
+ let Some(package_config) = self.get_closest_package_json(referrer)? else {
return Ok(None);
};
// ResolveSelf
- if package_config.exists
- && package_config.name.as_ref() == Some(&package_name)
- {
+ if package_config.name.as_ref() == Some(&package_name) {
if let Some(exports) = &package_config.exports {
return self
.package_exports_resolve(
@@ -1037,20 +1004,40 @@ impl NodeResolver {
}
}
- let result = self.resolve_package_subpath_for_package(
+ self.resolve_package_subpath_for_package(
&package_name,
&package_subpath,
referrer,
referrer_kind,
conditions,
mode,
+ )
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn resolve_package_subpath_for_package(
+ &self,
+ package_name: &str,
+ package_subpath: &str,
+ referrer: &ModuleSpecifier,
+ referrer_kind: NodeModuleKind,
+ conditions: &[&str],
+ mode: NodeResolutionMode,
+ ) -> Result<Option<ModuleSpecifier>, AnyError> {
+ let result = self.resolve_package_subpath_for_package_inner(
+ package_name,
+ package_subpath,
+ referrer,
+ referrer_kind,
+ conditions,
+ mode,
);
if mode.is_types() && !matches!(result, Ok(Some(_))) {
- // try to resolve with the @types/node package
- let package_name = types_package_name(&package_name);
- if let Ok(Some(result)) = self.resolve_package_subpath_for_package(
+ // try to resolve with the @types package
+ let package_name = types_package_name(package_name);
+ if let Ok(Some(result)) = self.resolve_package_subpath_for_package_inner(
&package_name,
- &package_subpath,
+ package_subpath,
referrer,
referrer_kind,
conditions,
@@ -1059,12 +1046,11 @@ impl NodeResolver {
return Ok(Some(result));
}
}
-
result
}
#[allow(clippy::too_many_arguments)]
- fn resolve_package_subpath_for_package(
+ fn resolve_package_subpath_for_package_inner(
&self,
package_name: &str,
package_subpath: &str,
@@ -1076,7 +1062,6 @@ impl NodeResolver {
let package_dir_path = self
.npm_resolver
.resolve_package_folder_from_package(package_name, referrer)?;
- let package_json_path = package_dir_path.join("package.json");
// todo: error with this instead when can't find package
// Err(errors::err_module_not_found(
@@ -1092,10 +1077,8 @@ impl NodeResolver {
// ))
// Package match.
- let package_json = self
- .load_package_json(&mut AllowAllNodePermissions, package_json_path)?;
- self.resolve_package_subpath(
- &package_json,
+ self.resolve_package_dir_subpath(
+ &package_dir_path,
package_subpath,
referrer,
referrer_kind,
@@ -1105,6 +1088,36 @@ impl NodeResolver {
}
#[allow(clippy::too_many_arguments)]
+ fn resolve_package_dir_subpath(
+ &self,
+ package_dir_path: &Path,
+ package_subpath: &str,
+ referrer: &ModuleSpecifier,
+ referrer_kind: NodeModuleKind,
+ conditions: &[&str],
+ mode: NodeResolutionMode,
+ ) -> Result<Option<ModuleSpecifier>, AnyError> {
+ let package_json_path = package_dir_path.join("package.json");
+ match self.load_package_json(&package_json_path)? {
+ Some(pkg_json) => self.resolve_package_subpath(
+ &pkg_json,
+ package_subpath,
+ referrer,
+ referrer_kind,
+ conditions,
+ mode,
+ ),
+ None => self.resolve_package_subpath_no_pkg_json(
+ package_dir_path,
+ package_subpath,
+ referrer,
+ referrer_kind,
+ mode,
+ ),
+ }
+ }
+
+ #[allow(clippy::too_many_arguments)]
fn resolve_package_subpath(
&self,
package_json: &PackageJson,
@@ -1139,6 +1152,7 @@ impl NodeResolver {
}
}
}
+
if package_subpath == "." {
return self.legacy_main_resolve(
package_json,
@@ -1148,7 +1162,25 @@ impl NodeResolver {
);
}
- let file_path = package_json.path.parent().unwrap().join(package_subpath);
+ self.resolve_subpath_exact(
+ package_json.path.parent().unwrap(),
+ package_subpath,
+ referrer,
+ referrer_kind,
+ mode,
+ )
+ }
+
+ fn resolve_subpath_exact(
+ &self,
+ directory: &Path,
+ package_subpath: &str,
+ referrer: &ModuleSpecifier,
+ referrer_kind: NodeModuleKind,
+ mode: NodeResolutionMode,
+ ) -> Result<Option<ModuleSpecifier>, AnyError> {
+ assert_ne!(package_subpath, ".");
+ let file_path = directory.join(package_subpath);
if mode.is_types() {
self.path_to_declaration_url(file_path, referrer, referrer_kind)
} else {
@@ -1156,49 +1188,54 @@ impl NodeResolver {
}
}
+ fn resolve_package_subpath_no_pkg_json(
+ &self,
+ directory: &Path,
+ package_subpath: &str,
+ referrer: &ModuleSpecifier,
+ referrer_kind: NodeModuleKind,
+ mode: NodeResolutionMode,
+ ) -> Result<Option<ModuleSpecifier>, AnyError> {
+ if package_subpath == "." {
+ self.legacy_index_resolve(directory, referrer_kind, mode)
+ } else {
+ self.resolve_subpath_exact(
+ directory,
+ package_subpath,
+ referrer,
+ referrer_kind,
+ mode,
+ )
+ }
+ }
+
pub fn get_closest_package_json(
&self,
url: &ModuleSpecifier,
- permissions: &mut dyn NodePermissions,
- ) -> Result<Option<Rc<PackageJson>>, AnyError> {
+ ) -> Result<Option<PackageJsonRc>, AnyError> {
let Ok(file_path) = url.to_file_path() else {
return Ok(None);
};
- self.get_closest_package_json_from_path(&file_path, permissions)
+ self.get_closest_package_json_from_path(&file_path)
}
pub fn get_closest_package_json_from_path(
&self,
file_path: &Path,
- permissions: &mut dyn NodePermissions,
- ) -> Result<Option<Rc<PackageJson>>, AnyError> {
- let Some(package_json_path) =
- self.get_closest_package_json_path(file_path)?
- else {
- return Ok(None);
- };
- self
- .load_package_json(permissions, package_json_path)
- .map(Some)
- }
-
- fn get_closest_package_json_path(
- &self,
- file_path: &Path,
- ) -> Result<Option<PathBuf>, AnyError> {
+ ) -> Result<Option<PackageJsonRc>, AnyError> {
let current_dir = deno_core::strip_unc_prefix(
self.fs.realpath_sync(file_path.parent().unwrap())?,
);
let mut current_dir = current_dir.as_path();
let package_json_path = current_dir.join("package.json");
- if self.fs.exists_sync(&package_json_path) {
- return Ok(Some(package_json_path));
+ if let Some(pkg_json) = self.load_package_json(&package_json_path)? {
+ return Ok(Some(pkg_json));
}
while let Some(parent) = current_dir.parent() {
current_dir = parent;
let package_json_path = current_dir.join("package.json");
- if self.fs.exists_sync(&package_json_path) {
- return Ok(Some(package_json_path));
+ if let Some(pkg_json) = self.load_package_json(&package_json_path)? {
+ return Ok(Some(pkg_json));
}
}
@@ -1207,15 +1244,12 @@ impl NodeResolver {
pub(super) fn load_package_json(
&self,
- permissions: &mut dyn NodePermissions,
- package_json_path: PathBuf,
- ) -> Result<Rc<PackageJson>, AnyError> {
- PackageJson::load(
- &*self.fs,
- &*self.npm_resolver,
- permissions,
- package_json_path,
- )
+ package_json_path: &Path,
+ ) -> Result<
+ Option<PackageJsonRc>,
+ deno_config::package_json::PackageJsonLoadError,
+ > {
+ crate::package_json::load_pkg_json(&*self.fs, package_json_path)
}
pub(super) fn legacy_main_resolve(
@@ -1284,6 +1318,19 @@ impl NodeResolver {
}
}
+ self.legacy_index_resolve(
+ package_json.path.parent().unwrap(),
+ referrer_kind,
+ mode,
+ )
+ }
+
+ fn legacy_index_resolve(
+ &self,
+ directory: &Path,
+ referrer_kind: NodeModuleKind,
+ mode: NodeResolutionMode,
+ ) -> Result<Option<ModuleSpecifier>, AnyError> {
let index_file_names = if mode.is_types() {
// todo(dsherret): investigate exactly how typescript does this
match referrer_kind {
@@ -1294,12 +1341,7 @@ impl NodeResolver {
vec!["index.js"]
};
for index_file_name in index_file_names {
- let guess = package_json
- .path
- .parent()
- .unwrap()
- .join(index_file_name)
- .clean();
+ let guess = directory.join(index_file_name).clean();
if self.fs.is_file_sync(&guess) {
// TODO(bartlomieju): emitLegacyIndexDeprecation()
return Ok(Some(to_file_specifier(&guess)));
@@ -1651,7 +1693,7 @@ mod tests {
use super::*;
fn build_package_json(json: Value) -> PackageJson {
- PackageJson::load_from_value(PathBuf::from("/package.json"), json).unwrap()
+ PackageJson::load_from_value(PathBuf::from("/package.json"), json)
}
#[test]