Skip to content

Commit

Permalink
feat: throw recursion error when resolving recursed browser fields
Browse files Browse the repository at this point in the history
  • Loading branch information
Boshen committed Dec 8, 2023
1 parent 2baf418 commit f38e398
Show file tree
Hide file tree
Showing 8 changed files with 52 additions and 19 deletions.
Empty file.
Empty file.
Empty file.
Empty file.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 7 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -790,13 +790,16 @@ impl<Fs: FileSystem + Default> ResolverGeneric<Fs> {
package_json: &PackageJson,
ctx: &mut ResolveContext,
) -> ResolveState {
let Some(specifier) = package_json.resolve_browser_field(path, specifier)? else {
let Some(new_specifier) = package_json.resolve_browser_field(path, specifier)? else {
return Ok(None);
};
if ctx.resolving_alias.as_ref().is_some_and(|s| s == specifier) {
if specifier.is_some_and(|s| s == new_specifier) {
return Ok(None);
}
let specifier = Specifier::parse(specifier).map_err(ResolveError::Specifier)?;
if ctx.resolving_alias.as_ref().is_some_and(|s| s == new_specifier) {
return Err(ResolveError::Recursion);
}
let specifier = Specifier::parse(new_specifier).map_err(ResolveError::Specifier)?;
ctx.with_query_fragment(specifier.query, specifier.fragment);
ctx.with_resolving_alias(specifier.path().to_string());
ctx.with_fully_specified(false);
Expand Down Expand Up @@ -845,7 +848,7 @@ impl<Fs: FileSystem + Default> ResolverGeneric<Fs> {
if let Some(path) = self.load_alias_value(
cached_path,
alias_key,
new_specifier.path(), // pass in passed alias value
new_specifier.path(), // pass in parsed alias value
specifier,
ctx,
)? {
Expand Down
29 changes: 14 additions & 15 deletions src/package_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use indexmap::IndexMap;
use rustc_hash::FxHasher;
use serde::{Deserialize, Deserializer};

use crate::{path::PathUtil, ResolveError, ResolveOptions};
use crate::{ResolveError, ResolveOptions};

type FxIndexMap<K, V> = IndexMap<K, V, BuildHasherDefault<FxHasher>>;

Expand Down Expand Up @@ -145,22 +145,15 @@ impl PackageJson {
}

// Dynamically create `browser_fields`.
let dir = path.parent().unwrap();
for object_path in &options.alias_fields {
if let Some(browser_field) = Self::get_value_by_path(&package_json_value, object_path) {
let mut browser_field = BrowserField::deserialize(browser_field)?;
// Normalize all relative paths to make browser_field a constant value lookup
if let BrowserField::Map(map) = &mut browser_field {
let relative_paths = map
.keys()
.filter(|path| path.starts_with("."))
.cloned()
.collect::<Vec<_>>();
for relative_path in relative_paths {
if let Some(value) = map.remove(&relative_path) {
let normalized_path = dir.normalize_with(relative_path);
map.insert(normalized_path, value);
}
// Make browser_field a constant value lookup by normalizing all relative paths.
for key in
map.keys().filter(|key| !key.starts_with(".")).cloned().collect::<Vec<_>>()
{
map.insert(PathBuf::from("./").join(&key), map[&key].clone());
}
}
package_json.browser_fields.push(browser_field);
Expand Down Expand Up @@ -224,12 +217,18 @@ impl PackageJson {
path: &Path,
request: Option<&str>,
) -> Result<Option<&str>, ResolveError> {
let request = request.map_or(path, |r| Path::new(r));
let request = match request {
Some(r) => PathBuf::from(r),
None => match path.strip_prefix(&self.path.parent().unwrap()) {
Ok(r) => Path::new("./").join(r),
Err(_) => return Ok(None),

Check warning on line 224 in src/package_json.rs

View check run for this annotation

Codecov / codecov/patch

src/package_json.rs#L224

Added line #L224 was not covered by tests
},
};
for browser in &self.browser_fields {
// Only object is valid, all other types are invalid
// https://github.com/webpack/enhanced-resolve/blob/3a28f47788de794d9da4d1702a3a583d8422cd48/lib/AliasFieldPlugin.js#L44-L52
if let BrowserField::Map(field_data) = browser {
if let Some(value) = field_data.get(request) {
if let Some(value) = field_data.get(request.as_path()) {
return Self::alias_value(path, value);
}
}
Expand Down
23 changes: 23 additions & 0 deletions src/tests/browser_field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,26 @@ fn crypto_js() {
let resolved_path = resolver.resolve(f.join("crypto-js"), "crypto").map(|r| r.full_path());
assert_eq!(resolved_path, Err(ResolveError::Ignored(f.join("crypto-js"))));
}

// https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/test/cases/resolving/browser-field/index.js#L40-L43
#[test]
fn recursive() {
let f = super::fixture().join("browser-module");

let resolver = Resolver::new(ResolveOptions {
alias_fields: vec![vec!["browser".into()]],
..ResolveOptions::default()
});

let data = [
("should handle recursive file 1", f.clone(), "recursive-file/a"),
("should handle recursive file 2", f.clone(), "recursive-file/b"),
("should handle recursive file 3", f.clone(), "recursive-file/c"),
("should handle recursive file 4", f.clone(), "recursive-file/d"),
];

for (comment, path, request) in data {
let resolved_path = resolver.resolve(&path, request);
assert_eq!(resolved_path, Err(ResolveError::Recursion), "{comment} {path:?} {request}");
}
}

0 comments on commit f38e398

Please sign in to comment.