Skip to content

Commit bccb2de

Browse files
committed
Request::Module.module is a Pattern now
1 parent 45de419 commit bccb2de

File tree

14 files changed

+159
-102
lines changed

14 files changed

+159
-102
lines changed

crates/next-core/src/next_edge/unsupported.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use anyhow::Result;
22
use indoc::formatdoc;
3-
use turbo_rcstr::RcStr;
43
use turbo_tasks::{ResolvedVc, Vc};
54
use turbo_tasks_fs::{File, FileSystemPath};
65
use turbopack_core::{
@@ -61,7 +60,7 @@ impl ImportMappingReplacement for NextEdgeUnsupportedModuleReplacer {
6160
}
6261

6362
#[turbo_tasks::function]
64-
fn unsupported_module_source(root_path: FileSystemPath, module: RcStr) -> Vc<VirtualSource> {
63+
fn unsupported_module_source(root_path: FileSystemPath, module: Pattern) -> Vc<VirtualSource> {
6564
// packages/next/src/server/web/globals.ts augments global with
6665
// `__import_unsupported` and necessary functions.
6766
let code = formatdoc! {

crates/next-core/src/next_server/resolve.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,9 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
100100
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()
101101
});
102102

103-
let Pattern::Constant(package_subpath) = package_subpath else {
103+
let (Pattern::Constant(package), Pattern::Constant(package_subpath)) =
104+
(package, package_subpath)
105+
else {
104106
return Ok(ResolveResultOption::none());
105107
};
106108
let request_str: RcStr = format!("{package}{package_subpath}").into();

crates/next-core/src/next_shared/resolve.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use turbopack_core::{
1313
resolve::{
1414
ExternalTraced, ExternalType, ResolveResult, ResolveResultItem, ResolveResultOption,
1515
parse::Request,
16+
pattern::Pattern,
1617
plugin::{
1718
AfterResolvePlugin, AfterResolvePluginCondition, BeforeResolvePlugin,
1819
BeforeResolvePluginCondition,
@@ -39,7 +40,7 @@ static FEATURE_MODULES: LazyLock<FxHashMap<&'static str, Vec<&'static str>>> =
3940
"/font/local",
4041
],
4142
),
42-
("@next", vec!["/font/google", "/font/local"]),
43+
("@next/font", vec!["/google", "/local"]),
4344
])
4445
});
4546

@@ -360,7 +361,7 @@ impl BeforeResolvePlugin for ModuleFeatureReportResolvePlugin {
360361
request: Vc<Request>,
361362
) -> Result<Vc<ResolveResultOption>> {
362363
if let Request::Module {
363-
module,
364+
module: Pattern::Constant(module),
364365
path,
365366
query: _,
366367
fragment: _,

turbopack/crates/turbopack-cli/src/build/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ async fn build_internal(
268268
false,
269269
),
270270
EntryRequest::Module(m, p) => Request::module(
271-
m.clone(),
271+
m.clone().into(),
272272
p.clone().into(),
273273
Default::default(),
274274
Default::default(),

turbopack/crates/turbopack-cli/src/dev/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,7 @@ async fn source(
305305
false,
306306
),
307307
EntryRequest::Module(m, p) => Request::module(
308-
m.clone(),
308+
m.clone().into(),
309309
p.clone().into(),
310310
Default::default(),
311311
Default::default(),

turbopack/crates/turbopack-core/src/resolve/alias_map.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -497,12 +497,12 @@ where
497497
}
498498
AliasKey::Wildcard { suffix } => {
499499
let mut remaining = self.request.clone();
500-
remaining.strip_prefix(prefix.len());
500+
remaining.strip_prefix_len(prefix.len());
501501
let remaining_suffix = remaining.constant_suffix();
502502
if !remaining_suffix.ends_with(&**suffix) {
503503
continue;
504504
}
505-
remaining.strip_suffix(suffix.len());
505+
remaining.strip_suffix_len(suffix.len());
506506

507507
let output = template.replace(&remaining);
508508
return Some(AliasMatch::Replaced(output));

turbopack/crates/turbopack-core/src/resolve/mod.rs

Lines changed: 99 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -1154,37 +1154,6 @@ async fn type_exists(
11541154
})
11551155
}
11561156

1157-
async fn any_exists(
1158-
fs_path: FileSystemPath,
1159-
refs: &mut Vec<ResolvedVc<Box<dyn Source>>>,
1160-
) -> Result<Option<(FileSystemEntryType, FileSystemPath)>> {
1161-
let result = fs_path.realpath_with_links().owned().await?;
1162-
refs.extend(
1163-
result
1164-
.symlinks
1165-
.into_iter()
1166-
.map(|path| async move {
1167-
Ok(ResolvedVc::upcast(
1168-
FileSource::new(path).to_resolved().await?,
1169-
))
1170-
})
1171-
.try_join()
1172-
.await?,
1173-
);
1174-
let path = result.path;
1175-
let ty = *path.get_type().await?;
1176-
Ok(
1177-
if matches!(
1178-
ty,
1179-
FileSystemEntryType::NotFound | FileSystemEntryType::Error
1180-
) {
1181-
None
1182-
} else {
1183-
Some((ty, path))
1184-
},
1185-
)
1186-
}
1187-
11881157
#[turbo_tasks::value(shared)]
11891158
enum ExportsFieldResult {
11901159
Some(#[turbo_tasks(debug_ignore, trace_ignore)] ExportsField),
@@ -1362,11 +1331,12 @@ pub async fn find_context_file_or_package_key(
13621331

13631332
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, Debug, NonLocalValue)]
13641333
enum FindPackageItem {
1365-
PackageDirectory(FileSystemPath),
1366-
PackageFile(FileSystemPath),
1334+
PackageDirectory { name: RcStr, dir: FileSystemPath },
1335+
PackageFile { name: RcStr, file: FileSystemPath },
13671336
}
13681337

13691338
#[turbo_tasks::value]
1339+
#[derive(Debug)]
13701340
struct FindPackageResult {
13711341
packages: Vec<FindPackageItem>,
13721342
affecting_sources: Vec<ResolvedVc<Box<dyn Source>>>,
@@ -1375,12 +1345,23 @@ struct FindPackageResult {
13751345
#[turbo_tasks::function]
13761346
async fn find_package(
13771347
lookup_path: FileSystemPath,
1378-
package_name: RcStr,
1348+
package_name: Pattern,
13791349
options: Vc<ResolveModulesOptions>,
13801350
) -> Result<Vc<FindPackageResult>> {
13811351
let mut packages = vec![];
13821352
let mut affecting_sources = vec![];
13831353
let options = options.await?;
1354+
let package_name_cell = Pattern::new(package_name);
1355+
1356+
fn get_package_name(basepath: &FileSystemPath, package_dir: &FileSystemPath) -> Result<RcStr> {
1357+
let name = basepath.get_relative_path_to(package_dir).unwrap();
1358+
if let Some(name) = name.strip_prefix("./") {
1359+
Ok(name.into())
1360+
} else {
1361+
bail!("Package directory {package_dir} is not inside the lookup path {basepath}");
1362+
}
1363+
}
1364+
13841365
for resolve_modules in &options.modules {
13851366
match resolve_modules {
13861367
ResolveModules::Nested(root_vc, names) => {
@@ -1392,11 +1373,18 @@ async fn find_package(
13921373
for name in names.iter() {
13931374
let fs_path = lookup_path.join(name)?;
13941375
if let Some(fs_path) = dir_exists(fs_path, &mut affecting_sources).await? {
1395-
let fs_path = fs_path.join(&package_name.clone())?;
1396-
if let Some(fs_path) =
1397-
dir_exists(fs_path.clone(), &mut affecting_sources).await?
1398-
{
1399-
packages.push(FindPackageItem::PackageDirectory(fs_path));
1376+
// TODO this is wrong, it should only match match 1 or 2 levels deep
1377+
// TODO affecting_sources are not getting added?
1378+
let matches =
1379+
read_matches(fs_path.clone(), rcstr!(""), true, package_name_cell)
1380+
.await?;
1381+
for m in matches {
1382+
if let PatternMatch::Directory(_, package_dir) = m {
1383+
packages.push(FindPackageItem::PackageDirectory {
1384+
name: get_package_name(&fs_path, package_dir)?,
1385+
dir: package_dir.clone(),
1386+
});
1387+
}
14001388
}
14011389
}
14021390
}
@@ -1413,28 +1401,56 @@ async fn find_package(
14131401
excluded_extensions,
14141402
} => {
14151403
let excluded_extensions = excluded_extensions.await?;
1416-
let package_dir = dir.join(&package_name)?;
1417-
if let Some((ty, package_dir)) =
1418-
any_exists(package_dir.clone(), &mut affecting_sources).await?
1419-
{
1420-
match ty {
1421-
FileSystemEntryType::Directory => {
1422-
packages.push(FindPackageItem::PackageDirectory(package_dir.clone()));
1404+
// TODO this is wrong, it should only match match 1 or 2 levels deep
1405+
// TODO affecting_sources are not getting added?
1406+
let matches =
1407+
read_matches(dir.clone(), rcstr!(""), true, package_name_cell).await?;
1408+
for m in matches {
1409+
match m {
1410+
PatternMatch::Directory(_, package_dir) => {
1411+
let name = get_package_name(dir, package_dir)?;
1412+
packages.push(FindPackageItem::PackageDirectory {
1413+
name: name.clone(),
1414+
dir: package_dir.clone(),
1415+
});
1416+
1417+
for extension in &options.extensions {
1418+
if excluded_extensions.contains(extension) {
1419+
continue;
1420+
}
1421+
let package_file = package_dir.append(&extension.clone())?;
1422+
if let Some(package_file) =
1423+
exists(package_file, &mut affecting_sources).await?
1424+
{
1425+
packages.push(FindPackageItem::PackageFile {
1426+
name: name.clone(),
1427+
file: package_file,
1428+
});
1429+
}
1430+
}
14231431
}
1424-
FileSystemEntryType::File => {
1425-
packages.push(FindPackageItem::PackageFile(package_dir.clone()));
1432+
PatternMatch::File(_, package_file) => {
1433+
let name = get_package_name(dir, package_file)?;
1434+
packages.push(FindPackageItem::PackageFile {
1435+
name: name.clone(),
1436+
file: package_file.clone(),
1437+
});
1438+
1439+
for extension in &options.extensions {
1440+
if excluded_extensions.contains(extension) {
1441+
continue;
1442+
}
1443+
let package_file = package_file.append(&extension.clone())?;
1444+
if let Some(package_file) =
1445+
exists(package_file, &mut affecting_sources).await?
1446+
{
1447+
packages.push(FindPackageItem::PackageFile {
1448+
name: name.clone(),
1449+
file: package_file,
1450+
});
1451+
}
1452+
}
14261453
}
1427-
_ => {}
1428-
}
1429-
}
1430-
for extension in &options.extensions {
1431-
if excluded_extensions.contains(extension) {
1432-
continue;
1433-
}
1434-
let package_file = package_dir.append(&extension.clone())?;
1435-
if let Some(package_file) = exists(package_file, &mut affecting_sources).await?
1436-
{
1437-
packages.push(FindPackageItem::PackageFile(package_file));
14381454
}
14391455
}
14401456
}
@@ -2512,7 +2528,7 @@ async fn resolve_module_request(
25122528
request: Vc<Request>,
25132529
options: Vc<ResolveOptions>,
25142530
options_value: &ResolveOptions,
2515-
module: &RcStr,
2531+
module: &Pattern,
25162532
path: &Pattern,
25172533
query: RcStr,
25182534
fragment: RcStr,
@@ -2523,7 +2539,7 @@ async fn resolve_module_request(
25232539
options,
25242540
options_value,
25252541
|_| {
2526-
let full_pattern = Pattern::concat([module.clone().into(), path.clone()]);
2542+
let full_pattern = Pattern::concat([module.clone(), path.clone()]);
25272543
full_pattern.into_string()
25282544
},
25292545
query.clone(),
@@ -2534,12 +2550,14 @@ async fn resolve_module_request(
25342550
return Ok(result);
25352551
}
25362552

2553+
let mut results = vec![];
2554+
25372555
// Self references, if the nearest package.json has the name of the requested
25382556
// module. This should match only using the exports field and no other
25392557
// fields/fallbacks.
25402558
if let FindSelfReferencePackageResult::Found { name, package_path } =
25412559
&*find_self_reference(lookup_path.clone()).await?
2542-
&& module == name
2560+
&& module.is_match(name)
25432561
{
25442562
let result = resolve_into_package(
25452563
path.clone(),
@@ -2566,46 +2584,47 @@ async fn resolve_module_request(
25662584
));
25672585
}
25682586

2569-
let mut results = vec![];
2570-
25712587
// There may be more than one package with the same name. For instance, in a
25722588
// TypeScript project, `compilerOptions.baseUrl` can declare a path where to
25732589
// resolve packages. A request to "foo/bar" might resolve to either
25742590
// "[baseUrl]/foo/bar" or "[baseUrl]/node_modules/foo/bar", and we'll need to
25752591
// try both.
25762592
for item in &result.packages {
25772593
match item {
2578-
FindPackageItem::PackageDirectory(package_path) => {
2579-
results.push(resolve_into_package(
2580-
path.clone(),
2581-
package_path.clone(),
2582-
query.clone(),
2583-
fragment.clone(),
2584-
options,
2585-
));
2594+
FindPackageItem::PackageDirectory { name, dir } => {
2595+
results.push(
2596+
resolve_into_package(
2597+
path.clone(),
2598+
dir.clone(),
2599+
query.clone(),
2600+
fragment.clone(),
2601+
options,
2602+
)
2603+
.with_replaced_request_key(rcstr!("."), RequestKey::new(name.clone())),
2604+
);
25862605
}
2587-
FindPackageItem::PackageFile(package_path) => {
2606+
FindPackageItem::PackageFile { name, file } => {
25882607
if path.is_match("") {
25892608
let resolved = resolved(
25902609
RequestKey::new(rcstr!(".")),
2591-
package_path.clone(),
2610+
file.clone(),
25922611
lookup_path.clone(),
25932612
request,
25942613
options_value,
25952614
options,
25962615
query.clone(),
25972616
fragment.clone(),
25982617
)
2599-
.await?;
2618+
.await?
2619+
.with_replaced_request_key(rcstr!("."), RequestKey::new(name.clone()));
26002620
results.push(resolved)
26012621
}
26022622
}
26032623
}
26042624
}
26052625

26062626
let module_result =
2607-
merge_results_with_affecting_sources(results, result.affecting_sources.clone())
2608-
.with_replaced_request_key(rcstr!("."), RequestKey::new(module.clone()));
2627+
merge_results_with_affecting_sources(results, result.affecting_sources.clone());
26092628

26102629
if options_value.prefer_relative {
26112630
let module_prefix: RcStr = format!("./{module}").into();
@@ -2623,8 +2642,9 @@ async fn resolve_module_request(
26232642
options,
26242643
))
26252644
.await?;
2626-
let relative_result = relative_result
2627-
.with_replaced_request_key(module_prefix, RequestKey::new(module.clone()));
2645+
// TODO request key
2646+
// let relative_result = relative_result
2647+
// .with_replaced_request_key(module_prefix, RequestKey::new(module.clone()));
26282648

26292649
Ok(merge_results(vec![relative_result, module_result]))
26302650
} else {

turbopack/crates/turbopack-core/src/resolve/parse.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,10 @@ static MODULE_PATH: LazyLock<Regex> =
100100
impl Request {
101101
/// Turns the request into a string.
102102
///
103-
/// Note that this is only returns something for the most basic and
104-
/// fully constant patterns.
103+
/// This is not only used for printing the request to the user, but also for matching inner
104+
/// assets.
105+
///
106+
/// Note that this is only returns something for the most basic and fully constant patterns.
105107
pub fn request(&self) -> Option<RcStr> {
106108
Some(match self {
107109
Request::Raw {
@@ -113,7 +115,7 @@ impl Request {
113115
..
114116
} => path.clone(),
115117
Request::Module {
116-
module,
118+
module: Pattern::Constant(module),
117119
path: Pattern::Constant(path),
118120
..
119121
} => format!("{module}{path}").into(),

0 commit comments

Comments
 (0)