Unverified Commit 39fb1ea8 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: support requests with dynamic part in module name (#82401)

Turbopack fails to resolve this
```js
function requireOrgPkg(s) {
  return require(`@org/pkg-${s}`)
}
```
which is needed for the case of
```js
require(`@img/sharp-${currentArch()}/sharp.node`)
```
parent 48ea532b
use anyhow::Result;
use indoc::formatdoc;
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::{File, FileSystemPath};
use turbopack_core::{
......@@ -61,18 +60,20 @@ impl ImportMappingReplacement for NextEdgeUnsupportedModuleReplacer {
}
#[turbo_tasks::function]
fn unsupported_module_source(root_path: FileSystemPath, module: RcStr) -> Vc<VirtualSource> {
fn unsupported_module_source(root_path: FileSystemPath, module: Pattern) -> Vc<VirtualSource> {
// packages/next/src/server/web/globals.ts augments global with
// `__import_unsupported` and necessary functions.
let code = formatdoc! {
r#"
{TURBOPACK_EXPORT_NAMESPACE}(__import_unsupported(`{module}`));
"#
"#,
module = module.as_constant_string().map(ToString::to_string).unwrap_or_else(|| module.describe_as_string()),
};
let content = AssetContent::file(File::from(code).into());
VirtualSource::new_with_ident(
AssetIdent::from_path(root_path)
.with_modifier(format!("unsupported edge import {module}").into()),
AssetIdent::from_path(root_path).with_modifier(
format!("unsupported edge import {}", module.describe_as_string()).into(),
),
content,
)
}
......@@ -100,7 +100,9 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
Regex::new("^(?:private-next-pages\\/|next\\/(?:dist\\/pages\\/|(?:app|cache|document|link|form|head|image|legacy\\/image|constants|dynamic|script|navigation|headers|router|compat\\/router|server)$)|string-hash|private-next-rsc-action-validate|private-next-rsc-action-client-wrapper|private-next-rsc-server-reference|private-next-rsc-cache-wrapper$)").unwrap()
});
let Pattern::Constant(package_subpath) = package_subpath else {
let (Pattern::Constant(package), Pattern::Constant(package_subpath)) =
(package, package_subpath)
else {
return Ok(ResolveResultOption::none());
};
let request_str: RcStr = format!("{package}{package_subpath}").into();
......
......@@ -13,6 +13,7 @@ use turbopack_core::{
resolve::{
ExternalTraced, ExternalType, ResolveResult, ResolveResultItem, ResolveResultOption,
parse::Request,
pattern::Pattern,
plugin::{
AfterResolvePlugin, AfterResolvePluginCondition, BeforeResolvePlugin,
BeforeResolvePluginCondition,
......@@ -39,7 +40,7 @@ static FEATURE_MODULES: LazyLock<FxHashMap<&'static str, Vec<&'static str>>> =
"/font/local",
],
),
("@next", vec!["/font/google", "/font/local"]),
("@next/font", vec!["/google", "/local"]),
])
});
......@@ -360,7 +361,7 @@ impl BeforeResolvePlugin for ModuleFeatureReportResolvePlugin {
request: Vc<Request>,
) -> Result<Vc<ResolveResultOption>> {
if let Request::Module {
module,
module: Pattern::Constant(module),
path,
query: _,
fragment: _,
......
......@@ -268,7 +268,7 @@ async fn build_internal(
false,
),
EntryRequest::Module(m, p) => Request::module(
m.clone(),
m.clone().into(),
p.clone().into(),
Default::default(),
Default::default(),
......
......@@ -305,7 +305,7 @@ async fn source(
false,
),
EntryRequest::Module(m, p) => Request::module(
m.clone(),
m.clone().into(),
p.clone().into(),
Default::default(),
Default::default(),
......
......@@ -497,12 +497,12 @@ where
}
AliasKey::Wildcard { suffix } => {
let mut remaining = self.request.clone();
remaining.strip_prefix(prefix.len());
remaining.strip_prefix_len(prefix.len());
let remaining_suffix = remaining.constant_suffix();
if !remaining_suffix.ends_with(&**suffix) {
continue;
}
remaining.strip_suffix(suffix.len());
remaining.strip_suffix_len(suffix.len());
let output = template.replace(&remaining);
return Some(AliasMatch::Replaced(output));
......
......@@ -1035,6 +1035,32 @@ impl ResolveResult {
.into())
}
/// Returns a new [ResolveResult] where all [RequestKey]s are updated. The prefix is removed
/// from all [RequestKey]s. It's not expected that the [ResolveResult] contains [RequestKey]s
/// without the prefix, but if there are still some, they are discarded.
#[turbo_tasks::function]
fn with_stripped_request_key_prefix(&self, prefix: RcStr) -> Result<Vc<Self>> {
let new_primary = self
.primary
.iter()
.filter_map(|(k, v)| {
let remaining = k.request.as_ref()?.strip_prefix(&*prefix)?;
Some((
RequestKey {
request: Some(remaining.into()),
conditions: k.conditions.clone(),
},
v.clone(),
))
})
.collect();
Ok(ResolveResult {
primary: new_primary,
affecting_sources: self.affecting_sources.clone(),
}
.into())
}
/// Returns a new [ResolveResult] where all [RequestKey]s are updated. All keys matching
/// `old_request_key` are rewritten according to `request_key`. It's not expected that the
/// [ResolveResult] contains [RequestKey]s that do not match the `old_request_key` prefix, but
......@@ -1114,38 +1140,25 @@ impl ResolveResultOption {
}
async fn exists(
fs_path: FileSystemPath,
fs_path: &FileSystemPath,
refs: &mut Vec<ResolvedVc<Box<dyn Source>>>,
) -> Result<Option<FileSystemPath>> {
type_exists(fs_path, FileSystemEntryType::File, refs).await
}
async fn dir_exists(
fs_path: FileSystemPath,
fs_path: &FileSystemPath,
refs: &mut Vec<ResolvedVc<Box<dyn Source>>>,
) -> Result<Option<FileSystemPath>> {
type_exists(fs_path, FileSystemEntryType::Directory, refs).await
}
async fn type_exists(
fs_path: FileSystemPath,
fs_path: &FileSystemPath,
ty: FileSystemEntryType,
refs: &mut Vec<ResolvedVc<Box<dyn Source>>>,
) -> Result<Option<FileSystemPath>> {
let result = fs_path.realpath_with_links().owned().await?;
refs.extend(
result
.symlinks
.into_iter()
.map(|path| async move {
Ok(ResolvedVc::upcast(
FileSource::new(path).to_resolved().await?,
))
})
.try_join()
.await?,
);
let path = result.path;
let path = realpath(fs_path, refs).await?;
Ok(if *path.get_type().await? == ty {
Some(path)
} else {
......@@ -1153,10 +1166,10 @@ async fn type_exists(
})
}
async fn any_exists(
fs_path: FileSystemPath,
async fn realpath(
fs_path: &FileSystemPath,
refs: &mut Vec<ResolvedVc<Box<dyn Source>>>,
) -> Result<Option<(FileSystemEntryType, FileSystemPath)>> {
) -> Result<FileSystemPath> {
let result = fs_path.realpath_with_links().owned().await?;
refs.extend(
result
......@@ -1170,18 +1183,7 @@ async fn any_exists(
.try_join()
.await?,
);
let path = result.path;
let ty = *path.get_type().await?;
Ok(
if matches!(
ty,
FileSystemEntryType::NotFound | FileSystemEntryType::Error
) {
None
} else {
Some((ty, path))
},
)
Ok(result.path)
}
#[turbo_tasks::value(shared)]
......@@ -1284,7 +1286,7 @@ pub async fn find_context_file(
let mut refs = Vec::new();
for name in &*names.await? {
let fs_path = lookup_path.join(name)?;
if let Some(fs_path) = exists(fs_path, &mut refs).await? {
if let Some(fs_path) = exists(&fs_path, &mut refs).await? {
return Ok(FindContextFileResult::Found(fs_path, refs).cell());
}
}
......@@ -1324,7 +1326,7 @@ pub async fn find_context_file_or_package_key(
) -> Result<Vc<FindContextFileResult>> {
let mut refs = Vec::new();
let package_json_path = lookup_path.join("package.json")?;
if let Some(package_json_path) = exists(package_json_path, &mut refs).await?
if let Some(package_json_path) = exists(&package_json_path, &mut refs).await?
&& let Some(json) =
&*read_package_json(Vc::upcast(FileSource::new(package_json_path.clone()))).await?
&& json.get(&*package_key).is_some()
......@@ -1333,7 +1335,7 @@ pub async fn find_context_file_or_package_key(
}
for name in &*names.await? {
let fs_path = lookup_path.join(name)?;
if let Some(fs_path) = exists(fs_path, &mut refs).await? {
if let Some(fs_path) = exists(&fs_path, &mut refs).await? {
return Ok(FindContextFileResult::Found(fs_path, refs).into());
}
}
......@@ -1361,11 +1363,12 @@ pub async fn find_context_file_or_package_key(
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, Debug, NonLocalValue)]
enum FindPackageItem {
PackageDirectory(FileSystemPath),
PackageFile(FileSystemPath),
PackageDirectory { name: RcStr, dir: FileSystemPath },
PackageFile { name: RcStr, file: FileSystemPath },
}
#[turbo_tasks::value]
#[derive(Debug)]
struct FindPackageResult {
packages: Vec<FindPackageItem>,
affecting_sources: Vec<ResolvedVc<Box<dyn Source>>>,
......@@ -1374,28 +1377,41 @@ struct FindPackageResult {
#[turbo_tasks::function]
async fn find_package(
lookup_path: FileSystemPath,
package_name: RcStr,
package_name: Pattern,
options: Vc<ResolveModulesOptions>,
) -> Result<Vc<FindPackageResult>> {
let mut packages = vec![];
let mut affecting_sources = vec![];
let options = options.await?;
let package_name_cell = Pattern::new(package_name.clone());
fn get_package_name(basepath: &FileSystemPath, package_dir: &FileSystemPath) -> Result<RcStr> {
if let Some(name) = basepath.get_path_to(package_dir) {
Ok(name.into())
} else {
bail!("Package directory {package_dir} is not inside the lookup path {basepath}");
}
}
for resolve_modules in &options.modules {
match resolve_modules {
ResolveModules::Nested(root_vc, names) => {
ResolveModules::Nested(root, names) => {
let mut lookup_path = lookup_path.clone();
let mut lookup_path_value = lookup_path.clone();
// For clippy -- This explicit deref is necessary
let root = root_vc.clone();
while lookup_path_value.is_inside_ref(&root) {
while lookup_path_value.is_inside_ref(root) {
for name in names.iter() {
let fs_path = lookup_path.join(name)?;
if let Some(fs_path) = dir_exists(fs_path, &mut affecting_sources).await? {
let fs_path = fs_path.join(&package_name)?;
if let Some(fs_path) =
dir_exists(fs_path.clone(), &mut affecting_sources).await?
{
packages.push(FindPackageItem::PackageDirectory(fs_path));
if let Some(fs_path) = dir_exists(&fs_path, &mut affecting_sources).await? {
let matches =
read_matches(fs_path.clone(), rcstr!(""), true, package_name_cell)
.await?;
for m in &*matches {
if let PatternMatch::Directory(_, package_dir) = m {
packages.push(FindPackageItem::PackageDirectory {
name: get_package_name(&fs_path, package_dir)?,
dir: realpath(package_dir, &mut affecting_sources).await?,
});
}
}
}
}
......@@ -1411,29 +1427,46 @@ async fn find_package(
dir,
excluded_extensions,
} => {
let excluded_extensions = excluded_extensions.await?;
let package_dir = dir.join(&package_name)?;
if let Some((ty, package_dir)) =
any_exists(package_dir.clone(), &mut affecting_sources).await?
{
match ty {
FileSystemEntryType::Directory => {
packages.push(FindPackageItem::PackageDirectory(package_dir.clone()));
let matches =
read_matches(dir.clone(), rcstr!(""), true, package_name_cell).await?;
for m in &*matches {
match m {
PatternMatch::Directory(_, package_dir) => {
packages.push(FindPackageItem::PackageDirectory {
name: get_package_name(dir, package_dir)?,
dir: realpath(package_dir, &mut affecting_sources).await?,
});
}
FileSystemEntryType::File => {
packages.push(FindPackageItem::PackageFile(package_dir.clone()));
PatternMatch::File(_, package_file) => {
packages.push(FindPackageItem::PackageFile {
name: get_package_name(dir, package_file)?,
file: realpath(package_file, &mut affecting_sources).await?,
});
}
_ => {}
}
}
for extension in &options.extensions {
if excluded_extensions.contains(extension) {
continue;
}
let package_file = package_dir.append(extension)?;
if let Some(package_file) = exists(package_file, &mut affecting_sources).await?
{
packages.push(FindPackageItem::PackageFile(package_file));
let excluded_extensions = excluded_extensions.await?;
let mut package_name_with_extensions = package_name.clone();
package_name_with_extensions.push(Pattern::alternatives(
options
.extensions
.iter()
.filter(|ext| !excluded_extensions.contains(*ext))
.cloned()
.map(Pattern::from),
));
let package_name_with_extensions = Pattern::new(package_name_with_extensions);
let matches =
read_matches(dir.clone(), rcstr!(""), true, package_name_with_extensions)
.await?;
for m in matches {
if let PatternMatch::File(_, package_file) = m {
packages.push(FindPackageItem::PackageFile {
name: get_package_name(dir, package_file)?,
file: realpath(package_file, &mut affecting_sources).await?,
});
}
}
}
......@@ -1535,7 +1568,7 @@ pub async fn resolve_raw(
if matches.len() > 10000 {
println!(
"WARN: resolving pattern {} in {} leads to {} results",
pat,
pat.describe_as_string(),
lookup_dir_str,
matches.len()
);
......@@ -2047,7 +2080,7 @@ async fn resolve_internal_inline(
if !has_alias {
ResolvingIssue {
severity: error_severity(options).await?,
request_type: format!("unknown import: `{path}`"),
request_type: format!("unknown import: `{}`", path.describe_as_string()),
request: request.to_resolved().await?,
file_path: lookup_path.clone(),
resolve_options: options.to_resolved().await?,
......@@ -2184,7 +2217,7 @@ async fn resolve_relative_request(
options,
options_value,
|package_path| {
let request = path_pattern.as_string()?;
let request = path_pattern.as_constant_string()?;
let prefix_path = package_path.get_path_to(&lookup_path_ref)?;
let request = normalize_request(&format!("./{prefix_path}/{request}"));
Some(request.into())
......@@ -2511,7 +2544,7 @@ async fn resolve_module_request(
request: Vc<Request>,
options: Vc<ResolveOptions>,
options_value: &ResolveOptions,
module: &RcStr,
module: &Pattern,
path: &Pattern,
query: RcStr,
fragment: RcStr,
......@@ -2522,8 +2555,8 @@ async fn resolve_module_request(
options,
options_value,
|_| {
let full_pattern = Pattern::concat([module.clone().into(), path.clone()]);
full_pattern.into_string()
let full_pattern = Pattern::concat([module.clone(), path.clone()]);
full_pattern.as_constant_string().cloned()
},
query.clone(),
fragment.clone(),
......@@ -2533,12 +2566,14 @@ async fn resolve_module_request(
return Ok(result);
}
let mut results = vec![];
// Self references, if the nearest package.json has the name of the requested
// module. This should match only using the exports field and no other
// fields/fallbacks.
if let FindSelfReferencePackageResult::Found { name, package_path } =
&*find_self_reference(lookup_path.clone()).await?
&& module == name
&& module.is_match(name)
{
let result = resolve_into_package(
path.clone(),
......@@ -2565,8 +2600,6 @@ async fn resolve_module_request(
));
}
let mut results = vec![];
// There may be more than one package with the same name. For instance, in a
// TypeScript project, `compilerOptions.baseUrl` can declare a path where to
// resolve packages. A request to "foo/bar" might resolve to either
......@@ -2574,20 +2607,23 @@ async fn resolve_module_request(
// try both.
for item in &result.packages {
match item {
FindPackageItem::PackageDirectory(package_path) => {
results.push(resolve_into_package(
path.clone(),
package_path.clone(),
query.clone(),
fragment.clone(),
options,
));
FindPackageItem::PackageDirectory { name, dir } => {
results.push(
resolve_into_package(
path.clone(),
dir.clone(),
query.clone(),
fragment.clone(),
options,
)
.with_replaced_request_key(rcstr!("."), RequestKey::new(name.clone())),
);
}
FindPackageItem::PackageFile(package_path) => {
FindPackageItem::PackageFile { name, file } => {
if path.is_match("") {
let resolved = resolved(
RequestKey::new(rcstr!(".")),
package_path.clone(),
file.clone(),
lookup_path.clone(),
request,
options_value,
......@@ -2595,7 +2631,8 @@ async fn resolve_module_request(
query.clone(),
fragment.clone(),
)
.await?;
.await?
.with_replaced_request_key(rcstr!("."), RequestKey::new(name.clone()));
results.push(resolved)
}
}
......@@ -2603,16 +2640,12 @@ async fn resolve_module_request(
}
let module_result =
merge_results_with_affecting_sources(results, result.affecting_sources.clone())
.with_replaced_request_key(rcstr!("."), RequestKey::new(module.clone()));
merge_results_with_affecting_sources(results, result.affecting_sources.clone());
if options_value.prefer_relative {
let module_prefix: RcStr = format!("./{module}").into();
let pattern = Pattern::concat([
module_prefix.clone().into(),
rcstr!("/").into(),
path.clone(),
]);
let mut module_prefixed = module.clone();
module_prefixed.push_front(rcstr!("./").into());
let pattern = Pattern::concat([module_prefixed.clone(), rcstr!("/").into(), path.clone()]);
let relative = Request::relative(pattern, query, fragment, true)
.to_resolved()
.await?;
......@@ -2622,8 +2655,7 @@ async fn resolve_module_request(
options,
))
.await?;
let relative_result = relative_result
.with_replaced_request_key(module_prefix, RequestKey::new(module.clone()));
let relative_result = relative_result.with_stripped_request_key_prefix(rcstr!("./"));
Ok(merge_results(vec![relative_result, module_result]))
} else {
......@@ -2660,11 +2692,11 @@ async fn resolve_into_package(
continue;
};
let Some(path) = path.clone().into_string() else {
let Some(path) = path.as_constant_string() else {
todo!("pattern into an exports field is not implemented yet");
};
let path = if &*path == "/" {
let path = if path == "/" {
rcstr!(".")
} else {
format!(".{path}").into()
......
......@@ -234,7 +234,7 @@ impl AliasTemplate for Vc<ImportMapping> {
ImportMapping::External(name, ty, traced) => {
if let Some(name) = name {
ReplacedImportMapping::External(
capture.spread_into_star(name).as_string().map(|s| s.into()),
capture.spread_into_star(name).as_constant_string().cloned(),
*ty,
*traced,
)
......@@ -250,7 +250,7 @@ impl AliasTemplate for Vc<ImportMapping> {
} => {
if let Some(name) = name {
ReplacedImportMapping::PrimaryAlternativeExternal {
name: capture.spread_into_star(name).as_string().map(|s| s.into()),
name: capture.spread_into_star(name).as_constant_string().cloned(),
ty: *ty,
traced: *traced,
lookup_dir: lookup_dir.clone(),
......
......@@ -23,7 +23,7 @@ pub enum Request {
fragment: RcStr,
},
Module {
module: RcStr,
module: Pattern,
path: Pattern,
query: RcStr,
fragment: RcStr,
......@@ -100,8 +100,10 @@ static MODULE_PATH: LazyLock<Regex> =
impl Request {
/// Turns the request into a string.
///
/// Note that this is only returns something for the most basic and
/// fully constant patterns.
/// This is not only used for printing the request to the user, but also for matching inner
/// assets.
///
/// Note that this is only returns something for the most basic and fully constant patterns.
pub fn request(&self) -> Option<RcStr> {
Some(match self {
Request::Raw {
......@@ -113,7 +115,7 @@ impl Request {
..
} => path.clone(),
Request::Module {
module,
module: Pattern::Constant(module),
path: Pattern::Constant(path),
..
} => format!("{module}{path}").into(),
......@@ -146,7 +148,7 @@ impl Request {
/// recursively. Most users should call [Self::parse] instead.
fn parse_ref(request: Pattern) -> Self {
match request {
Pattern::Dynamic => Request::Dynamic,
Pattern::Dynamic | Pattern::DynamicNoSlash => Request::Dynamic,
Pattern::Constant(r) => Request::parse_constant_pattern(r),
Pattern::Concatenation(list) => Request::parse_concatenation_pattern(list),
Pattern::Alternatives(_) => panic!(
......@@ -236,7 +238,7 @@ impl Request {
let (path, query, fragment) = split_off_query_fragment(path.as_str());
return Request::Module {
module: module.as_str().into(),
module: RcStr::from(module.as_str()).into(),
path,
query,
fragment,
......@@ -263,7 +265,17 @@ impl Request {
Request::Relative { path, .. } => {
path.push(item);
}
Request::Module { path, .. } => {
Request::Module { module, path, .. } => {
if path.is_empty() && matches!(item, Pattern::Dynamic) {
// TODO ideally this would be more general (i.e. support also
// `module-part<dynamic>more-module/subpath`) and not just handle
// Pattern::Dynamic, but this covers the common case of
// `require('@img/sharp-' + arch + '/sharp.node')`
// Insert dynamic between module and path (by adding it to both of them,
// because both could happen).
module.push(Pattern::DynamicNoSlash);
}
path.push(item);
}
Request::ServerRelative { path, .. } => {
......@@ -358,7 +370,7 @@ impl Request {
}
#[turbo_tasks::function]
pub fn module(module: RcStr, path: Pattern, query: RcStr, fragment: RcStr) -> Vc<Self> {
pub fn module(module: Pattern, path: Pattern, query: RcStr, fragment: RcStr) -> Vc<Self> {
Self::cell(Request::Module {
module,
path,
......@@ -385,7 +397,8 @@ impl Request {
query: _,
fragment: _,
} => {
let mut pat = Pattern::Constant(format!("./{module}").into());
let mut pat = module.clone();
pat.push_front(rcstr!("./").into());
pat.push(path.clone());
// TODO add query
Self::parse(pat)
......@@ -692,7 +705,7 @@ impl Request {
Request::Relative { path, .. } => path.clone(),
Request::Module { module, path, .. } => {
let mut path = path.clone();
path.push_front(Pattern::Constant(module.clone()));
path.push_front(module.clone());
path.normalize();
path
}
......@@ -740,9 +753,9 @@ impl ValueToString for Request {
..
} => {
if *force_in_lookup_dir {
format!("in-lookup-dir {path}").into()
format!("in-lookup-dir {}", path.describe_as_string()).into()
} else {
format!("{path}").into()
path.describe_as_string().into()
}
}
Request::Relative {
......@@ -751,22 +764,33 @@ impl ValueToString for Request {
..
} => {
if *force_in_lookup_dir {
format!("relative-in-lookup-dir {path}").into()
format!("relative-in-lookup-dir {}", path.describe_as_string()).into()
} else {
format!("relative {path}").into()
format!("relative {}", path.describe_as_string()).into()
}
}
Request::Module { module, path, .. } => {
if path.could_match_others("") {
format!("module \"{module}\" with subpath {path}").into()
format!(
"module {} with subpath {}",
module.describe_as_string(),
path.describe_as_string()
)
.into()
} else {
format!("module \"{module}\"").into()
format!("module \"{}\"", module.describe_as_string()).into()
}
}
Request::ServerRelative { path, .. } => format!("server relative {path}").into(),
Request::Windows { path, .. } => format!("windows {path}").into(),
Request::ServerRelative { path, .. } => {
format!("server relative {}", path.describe_as_string()).into()
}
Request::Windows { path, .. } => {
format!("windows {}", path.describe_as_string()).into()
}
Request::Empty => rcstr!("empty"),
Request::PackageInternal { path } => format!("package internal {path}").into(),
Request::PackageInternal { path } => {
format!("package internal {}", path.describe_as_string()).into()
}
Request::DataUri {
media_type,
encoding,
......@@ -781,7 +805,7 @@ impl ValueToString for Request {
remainder,
..
} => format!("uri \"{protocol}\" \"{remainder}\"").into(),
Request::Unknown { path } => format!("unknown {path}").into(),
Request::Unknown { path } => format!("unknown {}", path.describe_as_string()).into(),
Request::Dynamic => rcstr!("dynamic"),
Request::Alternatives { requests } => {
let vec = requests.iter().map(|i| i.to_string()).try_join().await?;
......@@ -811,6 +835,124 @@ pub async fn stringify_data_uri(
mod tests {
use super::*;
#[test]
fn test_parse_module() {
assert_eq!(
Request::Module {
module: rcstr!("foo").into(),
path: rcstr!("").into(),
query: rcstr!(""),
fragment: rcstr!(""),
},
Request::parse_ref(rcstr!("foo").into())
);
assert_eq!(
Request::Module {
module: rcstr!("@org/foo").into(),
path: rcstr!("").into(),
query: rcstr!(""),
fragment: rcstr!(""),
},
Request::parse_ref(rcstr!("@org/foo").into())
);
assert_eq!(
Request::Module {
module: Pattern::Concatenation(vec![
Pattern::Constant(rcstr!("foo-")),
Pattern::DynamicNoSlash,
]),
path: Pattern::Dynamic,
query: rcstr!(""),
fragment: rcstr!(""),
},
Request::parse_ref(Pattern::Concatenation(vec![
Pattern::Constant(rcstr!("foo-")),
Pattern::Dynamic,
]))
);
assert_eq!(
Request::Module {
module: Pattern::Concatenation(vec![
Pattern::Constant(rcstr!("foo-")),
Pattern::DynamicNoSlash,
]),
path: Pattern::Concatenation(vec![
Pattern::Dynamic,
Pattern::Constant(rcstr!("/file")),
]),
query: rcstr!(""),
fragment: rcstr!(""),
},
Request::parse_ref(Pattern::Concatenation(vec![
Pattern::Constant(rcstr!("foo-")),
Pattern::Dynamic,
Pattern::Constant(rcstr!("/file")),
]))
);
assert_eq!(
Request::Module {
module: Pattern::Concatenation(vec![
Pattern::Constant(rcstr!("foo-")),
Pattern::DynamicNoSlash,
]),
path: Pattern::Concatenation(vec![
Pattern::Dynamic,
Pattern::Constant(rcstr!("/file")),
Pattern::Dynamic,
Pattern::Constant(rcstr!("sub")),
]),
query: rcstr!(""),
fragment: rcstr!(""),
},
Request::parse_ref(Pattern::Concatenation(vec![
Pattern::Constant(rcstr!("foo-")),
Pattern::Dynamic,
Pattern::Constant(rcstr!("/file")),
Pattern::Dynamic,
Pattern::Constant(rcstr!("sub")),
]))
);
// TODO see parse_concatenation_pattern
// assert_eq!(
// Request::Alternatives {
// requests: vec![
// Request::Module {
// module: Pattern::Concatenation(vec![
// Pattern::Constant(rcstr!("prefix")),
// Pattern::Dynamic,
// Pattern::Constant(rcstr!("suffix")),
// ]),
// path: rcstr!("subpath").into(),
// query: rcstr!(""),
// fragment: rcstr!(""),
// }
// .resolved_cell(),
// Request::Module {
// module: Pattern::Concatenation(vec![
// Pattern::Constant(rcstr!("prefix")),
// Pattern::Dynamic,
// ]),
// path: Pattern::Concatenation(vec![
// Pattern::Dynamic,
// Pattern::Constant(rcstr!("suffix/subpath")),
// ]),
// query: rcstr!(""),
// fragment: rcstr!(""),
// }
// .resolved_cell()
// ]
// },
// Request::parse_ref(Pattern::Concatenation(vec![
// Pattern::Constant(rcstr!("prefix")),
// Pattern::Dynamic,
// Pattern::Constant(rcstr!("suffix/subpath")),
// ]))
// );
}
#[test]
fn test_split_query_fragment() {
assert_eq!(
......
use std::{
collections::{VecDeque, hash_map::Entry},
fmt::Display,
mem::take,
sync::LazyLock,
};
......@@ -25,6 +24,7 @@ pub enum Pattern {
Constant(RcStr),
#[default]
Dynamic,
DynamicNoSlash,
Alternatives(Vec<Pattern>),
Concatenation(Vec<Pattern>),
}
......@@ -117,26 +117,19 @@ fn longest_common_suffix<'a>(strings: &[&'a str]) -> &'a str {
impl Pattern {
// TODO this should be removed in favor of pattern resolving
pub fn into_string(self) -> Option<RcStr> {
pub fn as_constant_string(&self) -> Option<&RcStr> {
match self {
Pattern::Constant(str) => Some(str),
_ => None,
}
}
pub fn as_string(&self) -> Option<&str> {
match self {
Pattern::Constant(str) => Some(str.as_str()),
_ => None,
}
}
/// Whether the pattern has any significant constant parts (everything except `/`).
/// E.g. `<dynamic>/<dynamic>` doesn't really have constant parts
pub fn has_constant_parts(&self) -> bool {
match self {
Pattern::Constant(str) => str != "/",
Pattern::Dynamic => false,
Pattern::Dynamic | Pattern::DynamicNoSlash => false,
Pattern::Alternatives(list) | Pattern::Concatenation(list) => {
list.iter().any(|p| p.has_constant_parts())
}
......@@ -146,7 +139,7 @@ impl Pattern {
pub fn has_dynamic_parts(&self) -> bool {
match self {
Pattern::Constant(_) => false,
Pattern::Dynamic => true,
Pattern::Dynamic | Pattern::DynamicNoSlash => true,
Pattern::Alternatives(list) | Pattern::Concatenation(list) => {
list.iter().any(|p| p.has_dynamic_parts())
}
......@@ -171,7 +164,7 @@ impl Pattern {
Pattern::Alternatives(_) => {
panic!("for constant_prefix a Pattern must be normalized");
}
Pattern::Dynamic => {}
Pattern::Dynamic | Pattern::DynamicNoSlash => {}
}
}
......@@ -185,7 +178,7 @@ impl Pattern {
collect_constant_prefix(c, &mut strings);
}
}
Pattern::Dynamic => {}
Pattern::Dynamic | Pattern::DynamicNoSlash => {}
}
longest_common_prefix(&strings)
}
......@@ -208,7 +201,7 @@ impl Pattern {
Pattern::Alternatives(_) => {
panic!("for constant_suffix a Pattern must be normalized");
}
Pattern::Dynamic => {}
Pattern::Dynamic | Pattern::DynamicNoSlash => {}
}
}
......@@ -222,12 +215,22 @@ impl Pattern {
collect_constant_suffix(c, &mut strings);
}
}
Pattern::Dynamic => {}
Pattern::Dynamic | Pattern::DynamicNoSlash => {}
}
longest_common_suffix(&strings)
}
pub fn strip_prefix(&mut self, len: usize) {
pub fn strip_prefix(&self, prefix: &str) -> Option<Self> {
if self.must_match(prefix) {
let mut pat = self.clone();
pat.strip_prefix_len(prefix.len());
Some(pat)
} else {
None
}
}
pub fn strip_prefix_len(&mut self, len: usize) {
fn strip_prefix_internal(pattern: &mut Pattern, chars_to_strip: &mut usize) {
match pattern {
Pattern::Constant(c) => {
......@@ -249,7 +252,7 @@ impl Pattern {
Pattern::Alternatives(_) => {
panic!("for strip_prefix a Pattern must be normalized");
}
Pattern::Dynamic => {
Pattern::Dynamic | Pattern::DynamicNoSlash => {
panic!("strip_prefix prefix is too long");
}
}
......@@ -266,7 +269,7 @@ impl Pattern {
strip_prefix_internal(c, &mut len_local);
}
}
Pattern::Dynamic => {
Pattern::Dynamic | Pattern::DynamicNoSlash => {
if len > 0 {
panic!("strip_prefix prefix is too long");
}
......@@ -276,7 +279,7 @@ impl Pattern {
self.normalize()
}
pub fn strip_suffix(&mut self, len: usize) {
pub fn strip_suffix_len(&mut self, len: usize) {
fn strip_suffix_internal(pattern: &mut Pattern, chars_to_strip: &mut usize) {
match pattern {
Pattern::Constant(c) => {
......@@ -298,7 +301,7 @@ impl Pattern {
Pattern::Alternatives(_) => {
panic!("for strip_suffix a Pattern must be normalized");
}
Pattern::Dynamic => {
Pattern::Dynamic | Pattern::DynamicNoSlash => {
panic!("strip_suffix suffix is too long");
}
}
......@@ -315,7 +318,7 @@ impl Pattern {
strip_suffix_internal(c, &mut len_local);
}
}
Pattern::Dynamic => {
Pattern::Dynamic | Pattern::DynamicNoSlash => {
if len > 0 {
panic!("strip_suffix suffix is too long");
}
......@@ -378,6 +381,14 @@ impl Pattern {
/// Appends something to end the pattern.
pub fn push(&mut self, pat: Pattern) {
if let Pattern::Constant(this) = &*self
&& this.is_empty()
{
// Short-circuit to replace empty constants with the appended pattern
*self = pat;
return;
}
match (self, pat) {
(Pattern::Concatenation(list), Pattern::Concatenation(more)) => {
concatenation_extend_or_merge_items(list, more.into_iter());
......@@ -463,7 +474,7 @@ impl Pattern {
*c = RcStr::from(normalize_path(normalized.as_str())?);
Some(())
}
Pattern::Dynamic => Some(()),
Pattern::Dynamic | Pattern::DynamicNoSlash => Some(()),
Pattern::Concatenation(list) => {
let mut segments = Vec::new();
for segment in list.iter() {
......@@ -484,12 +495,12 @@ impl Pattern {
segments.push(vec![]);
}
}
Pattern::Dynamic => {
Pattern::Dynamic | Pattern::DynamicNoSlash => {
if segments.is_empty() {
segments.push(vec![]);
}
let last = segments.last_mut().unwrap();
last.push(Pattern::Dynamic);
last.push(segment.clone());
}
Pattern::Alternatives(_) | Pattern::Concatenation(_) => {
panic!("for with_normalized_path the Pattern must be normalized");
......@@ -521,7 +532,7 @@ impl Pattern {
normalize_path_internal(c)?;
}
}
Pattern::Dynamic => {}
Pattern::Dynamic | Pattern::DynamicNoSlash => {}
}
new.normalize();
......@@ -532,7 +543,7 @@ impl Pattern {
/// Merge when possible
pub fn normalize(&mut self) {
match self {
Pattern::Dynamic | Pattern::Constant(_) => {
Pattern::Dynamic | Pattern::DynamicNoSlash | Pattern::Constant(_) => {
// already normalized
}
Pattern::Alternatives(list) => {
......@@ -641,12 +652,21 @@ impl Pattern {
}
}
Pattern::Dynamic => {
if let Some(Pattern::Dynamic) = new_parts.last() {
if let Some(Pattern::Dynamic | Pattern::DynamicNoSlash) =
new_parts.last()
{
// do nothing
} else {
new_parts.push(Pattern::Dynamic);
}
}
Pattern::DynamicNoSlash => {
if let Some(Pattern::DynamicNoSlash) = new_parts.last() {
// do nothing
} else {
new_parts.push(Pattern::DynamicNoSlash);
}
}
Pattern::Concatenation(parts) => {
for part in parts {
add_part(part, new_parts);
......@@ -668,6 +688,15 @@ impl Pattern {
}
}
pub fn is_empty(&self) -> bool {
match self {
Pattern::Constant(s) => s.is_empty(),
Pattern::Dynamic | Pattern::DynamicNoSlash => false,
Pattern::Concatenation(parts) => parts.iter().all(|p| p.is_empty()),
Pattern::Alternatives(parts) => parts.iter().all(|p| p.is_empty()),
}
}
pub fn filter_could_match(&self, value: &str) -> Option<Pattern> {
if let Pattern::Alternatives(list) = self {
let new_list = list
......@@ -844,7 +873,7 @@ impl Pattern {
MatchResult::None
}
}
Pattern::Dynamic => {
Pattern::Dynamic | Pattern::DynamicNoSlash => {
static FORBIDDEN: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(/|^)(ROOT|\.|/|(node_modules|__tests?__)(/|$))").unwrap()
});
......@@ -860,9 +889,13 @@ impl Pattern {
} else if ignore_dynamic {
MatchResult::None
} else {
let match_length = matches!(self, Pattern::DynamicNoSlash)
.then(|| value.find("/"))
.flatten()
.unwrap_or(value.len());
MatchResult::Consumed {
remaining: value,
any_offset: Some(value.len()),
any_offset: Some(match_length),
}
}
}
......@@ -930,7 +963,7 @@ impl Pattern {
MatchResult::None
}
}
Pattern::Dynamic => {
Pattern::Dynamic | Pattern::DynamicNoSlash => {
static FORBIDDEN: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(/|^)(ROOT|\.|/|(node_modules|__tests?__)(/|$))").unwrap()
});
......@@ -944,9 +977,13 @@ impl Pattern {
} else if FORBIDDEN_MATCH.find(value).is_some() {
MatchResult::Partial
} else {
let match_length = matches!(self, Pattern::DynamicNoSlash)
.then(|| value.find("/"))
.flatten()
.unwrap_or(value.len());
MatchResult::Consumed {
remaining: value,
any_offset: Some(value.len()),
any_offset: Some(match_length),
}
}
}
......@@ -1044,7 +1081,7 @@ impl Pattern {
NextConstantUntilResult::NoMatch
}
}
Pattern::Dynamic => {
Pattern::Dynamic | Pattern::DynamicNoSlash => {
static FORBIDDEN: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(/|^)(\.|(node_modules|__tests?__)(/|$))").unwrap()
});
......@@ -1108,7 +1145,7 @@ impl Pattern {
replaced = true;
}
}
Pattern::Dynamic => {}
Pattern::Dynamic | Pattern::DynamicNoSlash => {}
Pattern::Alternatives(list) => {
for i in list {
replaced = i.replace_final_constants(cb) || replaced;
......@@ -1123,6 +1160,27 @@ impl Pattern {
replaced
}
/// Calls `cb` on all constants and replaces the them with the returned pattern. Returns true if
/// replacements were performed.
pub fn replace_constants(&mut self, cb: &impl Fn(&RcStr) -> Option<Pattern>) -> bool {
let mut replaced = false;
match self {
Pattern::Constant(c) => {
if let Some(replacement) = cb(c) {
*self = replacement;
replaced = true;
}
}
Pattern::Dynamic | Pattern::DynamicNoSlash => {}
Pattern::Concatenation(list) | Pattern::Alternatives(list) => {
for i in list {
replaced = i.replace_constants(cb) || replaced;
}
}
}
replaced
}
/// Matches the given string against self, and applies the match onto the target pattern.
///
/// The two patterns should have a similar structure (same number of alternatives and dynamics)
......@@ -1155,12 +1213,14 @@ impl Pattern {
let mut result = "".to_string();
match target {
Pattern::Constant(c) => result.push_str(c),
Pattern::Dynamic => result.push_str(dynamics.pop_front()?),
Pattern::Dynamic | Pattern::DynamicNoSlash => result.push_str(dynamics.pop_front()?),
Pattern::Concatenation(list) => {
for c in list {
match c {
Pattern::Constant(c) => result.push_str(c),
Pattern::Dynamic => result.push_str(dynamics.pop_front()?),
Pattern::Dynamic | Pattern::DynamicNoSlash => {
result.push_str(dynamics.pop_front()?)
}
Pattern::Alternatives(_) | Pattern::Concatenation(_) => {
panic!("Pattern must be normalized")
}
......@@ -1280,27 +1340,24 @@ impl From<RcStr> for Pattern {
}
}
impl Display for Pattern {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl Pattern {
pub fn describe_as_string(&self) -> String {
match self {
Pattern::Constant(c) => write!(f, "'{c}'"),
Pattern::Dynamic => write!(f, "<dynamic>"),
Pattern::Alternatives(list) => write!(
f,
Pattern::Constant(c) => format!("'{c}'"),
Pattern::Dynamic => "<dynamic>".to_string(),
Pattern::DynamicNoSlash => "<dynamic no slash>".to_string(),
Pattern::Alternatives(list) => format!(
"({})",
list.iter()
.map(|i| i.to_string())
.map(|i| i.describe_as_string())
.collect::<Vec<_>>()
.join(" | ")
),
Pattern::Concatenation(list) => write!(
f,
"{}",
list.iter()
.map(|i| i.to_string())
.collect::<Vec<_>>()
.join(" ")
),
Pattern::Concatenation(list) => list
.iter()
.map(|i| i.describe_as_string())
.collect::<Vec<_>>()
.join(" "),
}
}
}
......@@ -1309,7 +1366,7 @@ impl Display for Pattern {
impl ValueToString for Pattern {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> {
Vc::cell(self.to_string().into())
Vc::cell(self.describe_as_string().into())
}
}
......@@ -1891,6 +1948,8 @@ mod tests {
assert!(!pat.is_match("./"));
assert!(pat.is_match("./index.js"));
assert!(!pat.is_match("./index"));
assert!(pat.is_match("./foo/index.js"));
assert!(pat.is_match("./foo/bar/index.js"));
// forbidden:
assert!(!pat.is_match("./../index.js"));
......@@ -1907,6 +1966,23 @@ mod tests {
assert!(!pat.could_match("./inner/.git/"));
}
#[test]
fn is_match_dynamic_no_slash() {
let pat = Pattern::Concatenation(vec![
Pattern::Constant(rcstr!(".")),
Pattern::Constant(rcstr!("/")),
Pattern::DynamicNoSlash,
Pattern::Constant(rcstr!(".js")),
]);
assert!(pat.could_match(""));
assert!(pat.could_match("./"));
assert!(!pat.is_match("./"));
assert!(pat.is_match("./index.js"));
assert!(!pat.is_match("./index"));
assert!(!pat.is_match("./foo/index.js"));
assert!(!pat.is_match("./foo/bar/index.js"));
}
#[test]
fn constant_prefix() {
assert_eq!(
......@@ -1944,7 +2020,7 @@ mod tests {
#[test]
fn strip_prefix() {
fn strip(mut pat: Pattern, n: usize) -> Pattern {
pat.strip_prefix(n);
pat.strip_prefix_len(n);
pat
}
......@@ -1985,7 +2061,7 @@ mod tests {
#[test]
fn strip_suffix() {
fn strip(mut pat: Pattern, n: usize) -> Pattern {
pat.strip_suffix(n);
pat.strip_suffix_len(n);
pat
}
......
......@@ -71,7 +71,7 @@ impl BeforeResolvePluginCondition {
},
BeforeResolvePluginCondition::Modules(modules) => {
if let Request::Module { module, .. } = &*request.await? {
modules.contains(module)
modules.iter().any(|m| module.is_match(m))
} else {
false
}
......
......@@ -419,7 +419,7 @@ impl ModuleReference for EsmAssetReference {
}
if let Request::Module { module, .. } = &*self.request.await?
&& module == TURBOPACK_PART_IMPORT_SOURCE
&& module.is_match(TURBOPACK_PART_IMPORT_SOURCE)
{
if let Some(part) = &self.export_name {
let module: ResolvedVc<crate::EcmascriptModuleAsset> =
......
......@@ -128,7 +128,7 @@ impl ModuleReference for TsReferenceTypeAssetReference {
type_resolve(
*self.origin,
Request::module(
self.module.clone(),
self.module.clone().into(),
RcStr::default().into(),
RcStr::default(),
RcStr::default(),
......
......@@ -160,7 +160,7 @@ impl Module for TsConfigModuleAsset {
TsConfigTypesReference::new(
*self.origin,
Request::module(
name,
name.into(),
RcStr::default().into(),
RcStr::default(),
RcStr::default(),
......
......@@ -426,13 +426,15 @@ pub async fn type_resolve(
fragment: _,
} = &*request.await?
{
let m = if let Some(stripped) = m.strip_prefix('@') {
stripped.replace('/', "__").into()
let mut m = if let Some(mut stripped) = m.strip_prefix("@") {
stripped.replace_constants(&|c| Some(Pattern::Constant(c.replace("/", "__").into())));
stripped
} else {
m.clone()
};
m.push_front(rcstr!("@types/").into());
Some(Request::module(
format!("@types/{m}").into(),
m,
p.clone(),
RcStr::default(),
RcStr::default(),
......
function requirePkg(s) {
return require(`pkg-${s}`)
}
function requireOrgPkg(s) {
return require(`@org/pkg-${s}`)
}
it('should correctly handle dynamic parts in regular package name', () => {
expect(requirePkg('a').default).toBe('pkg-a')
expect(requirePkg('b').default).toBe('pkg-b')
expect(requirePkg('c').default).toBe('pkg-c')
})
it('should correctly handle dynamic parts in namespaced package name', () => {
expect(requireOrgPkg('a').default).toBe('org/pkg-a')
expect(requireOrgPkg('b').default).toBe('org/pkg-b')
expect(requireOrgPkg('c').default).toBe('org/pkg-c')
})
......@@ -10,7 +10,7 @@ error - [resolve] /turbopack/crates/turbopack-tests/tests/snapshot/imports/resol
| It was not possible to find the requested file.
| Parsed request as written in source code: module "does-not-exist" with subpath '/path'
| Parsed request as written in source code: module 'does-not-exist' with subpath '/path'
| Path where resolving has started: [project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/resolve_error_cjs/input/index.js
| Type of request: commonjs request
|
\ No newline at end of file
......@@ -11,7 +11,7 @@ error - [resolve] /turbopack/crates/turbopack-tests/tests/snapshot/imports/resol
| It was not possible to find the requested file.
| Parsed request as written in source code: module "does-not-exist" with subpath '/path'
| Parsed request as written in source code: module 'does-not-exist' with subpath '/path'
| Path where resolving has started: [project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/resolve_error_esm/input/index.js
| Type of request: EcmaScript Modules (part) request
|
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment