Unverified Commit 9e6d378b authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: Ignore `Unknown module type` for NFT (#71713)

Part of NFT

~~Dynamic requests such as `require("./"+ something)` often match too
many files. If we cannot process a matched file with the Turbopack
rules, then it's really an unreachable case anyway. This removes the
error in that case.~~

This doesn't change the behavior of regular bundling, but makes
`primary_modules_raw_iter` not throw the error.

- [x] Cleanup API: add the boolean into `.process()`? Or should this be
passed differently?
- [ ] ~~Should this be a warning instead for user code?~~
parent 95493060
......@@ -48,14 +48,15 @@ impl Transition for NextDynamicTransition {
module_asset_context,
Value::new(ReferenceType::Undefined),
)
.try_into_module()
.await?
{
ProcessResult::Module(client_module) => ProcessResult::Module(ResolvedVc::upcast(
Some(client_module) => ProcessResult::Module(ResolvedVc::upcast(
NextDynamicEntryModule::new(*client_module)
.to_resolved()
.await?,
)),
ProcessResult::Ignore => ProcessResult::Ignore,
None => ProcessResult::Ignore,
}
.cell())
}
......
......@@ -4,7 +4,8 @@ use turbo_tasks_fs::{glob::Glob, FileSystemPath};
use crate::{
compile_time_info::CompileTimeInfo,
module::Module,
issue::module::emit_unknown_module_type_error,
module::{Module, OptionModule},
reference_type::ReferenceType,
resolve::{options::ResolveOptions, parse::Request, ModuleResolveResult, ResolveResult},
source::Source,
......@@ -15,6 +16,9 @@ pub enum ProcessResult {
/// A module was created.
Module(ResolvedVc<Box<dyn Module>>),
/// A module could not be created (according to the rules, e.g. no module type was assigned)
Unknown(Vc<Box<dyn Source>>),
/// Reference is ignored. This should lead to no module being included by
/// the reference.
Ignore,
......@@ -29,8 +33,24 @@ impl ProcessResult {
ProcessResult::Ignore => {
bail!("Expected process result to be a module, but it was ignored")
}
ProcessResult::Unknown(_) => {
bail!("Expected process result to be a module, but it could not be processed")
}
}
}
/// Unwrap the module, or return None and emit an issue
#[turbo_tasks::function]
pub async fn try_into_module(&self) -> Result<Vc<OptionModule>> {
Ok(Vc::cell(match self {
ProcessResult::Module(module) => Some(*module),
ProcessResult::Unknown(source) => {
emit_unknown_module_type_error(*source).await?;
None
}
ProcessResult::Ignore => None,
}))
}
}
/// A context for building an asset graph. It's passed through the assets while
......
pub mod analyze;
pub mod code_gen;
pub mod module;
pub mod resolve;
use std::{
......
use turbo_tasks::Vc;
use turbo_tasks_fs::FileSystemPath;
use super::{Issue, IssueStage, OptionStyledString, StyledString};
use crate::{ident::AssetIdent, issue::IssueExt, source::Source};
#[turbo_tasks::value(shared)]
pub struct ModuleIssue {
pub ident: Vc<AssetIdent>,
pub title: Vc<StyledString>,
pub description: Vc<StyledString>,
}
#[turbo_tasks::value_impl]
impl Issue for ModuleIssue {
#[turbo_tasks::function]
fn stage(&self) -> Vc<IssueStage> {
IssueStage::ProcessModule.cell()
}
#[turbo_tasks::function]
fn file_path(&self) -> Vc<FileSystemPath> {
self.ident.path()
}
#[turbo_tasks::function]
fn title(&self) -> Vc<StyledString> {
self.title
}
#[turbo_tasks::function]
fn description(&self) -> Vc<OptionStyledString> {
Vc::cell(Some(self.description))
}
}
#[turbo_tasks::function]
pub fn emit_unknown_module_type_error(source: Vc<Box<dyn Source>>) {
ModuleIssue {
ident: source.ident(),
title: StyledString::Text("Unknown module type".into()).cell(),
description: StyledString::Text(
r"This module doesn't have an associated type. Use a known file extension, or register a loader for it.
Read more: https://nextjs.org/docs/app/api-reference/next-config-js/turbo#webpack-loaders".into(),
)
.cell(),
}
.cell()
.emit();
}
......@@ -139,7 +139,7 @@ pub async fn referenced_modules_and_affecting_sources(
.try_join()
.await?;
for resolve_result in resolve_results {
modules.extend(resolve_result.primary_modules_iter());
modules.extend(resolve_result.primary_modules_raw_iter());
modules.extend(
resolve_result
.affecting_sources_iter()
......
......@@ -10,7 +10,7 @@ use anyhow::{bail, Result};
use serde::{Deserialize, Serialize};
use tracing::{Instrument, Level};
use turbo_tasks::{
fxindexmap, fxindexset, trace::TraceRawVcs, FxIndexMap, RcStr, ResolvedVc, TaskInput,
fxindexmap, trace::TraceRawVcs, FxIndexMap, FxIndexSet, RcStr, ResolvedVc, TaskInput,
TryJoinIterExt, Value, ValueToString, Vc,
};
use turbo_tasks_fs::{
......@@ -31,7 +31,9 @@ use self::{
use crate::{
context::AssetContext,
file_source::FileSource,
issue::{resolve::ResolvingIssue, IssueExt, IssueSource},
issue::{
module::emit_unknown_module_type_error, resolve::ResolvingIssue, IssueExt, IssueSource,
},
module::{Module, Modules, OptionModule},
output::{OutputAsset, OutputAssets},
package_json::{read_package_json, PackageJsonIssue},
......@@ -66,12 +68,31 @@ pub enum ModuleResolveResultItem {
Module(ResolvedVc<Box<dyn Module>>),
OutputAsset(ResolvedVc<Box<dyn OutputAsset>>),
External(RcStr, ExternalType),
/// A module could not be created (according to the rules, e.g. no module type as assigned)
Unknown(Vc<Box<dyn Source>>),
Ignore,
Error(ResolvedVc<RcStr>),
Empty,
Custom(u8),
}
impl ModuleResolveResultItem {
pub async fn as_module(&self) -> Result<Option<ResolvedVc<Box<dyn Module>>>> {
Ok(match *self {
ModuleResolveResultItem::Module(module) => Some(module),
ModuleResolveResultItem::Unknown(source) => {
emit_unknown_module_type_error(source).await?;
None
}
ModuleResolveResultItem::Error(_err) => {
// TODO emit error?
None
}
_ => None,
})
}
}
#[turbo_tasks::value(shared)]
#[derive(Clone, Debug)]
pub struct ModuleResolveResult {
......@@ -151,9 +172,12 @@ impl ModuleResolveResult {
}
}
pub fn primary_modules_iter(&self) -> impl Iterator<Item = ResolvedVc<Box<dyn Module>>> + '_ {
self.primary.iter().filter_map(|(_, item)| match item {
&ModuleResolveResultItem::Module(a) => Some(a),
/// Returns all module results (but ignoring any errors).
pub fn primary_modules_raw_iter(
&self,
) -> impl Iterator<Item = ResolvedVc<Box<dyn Module>>> + '_ {
self.primary.iter().filter_map(|(_, item)| match *item {
ModuleResolveResultItem::Module(a) => Some(a),
_ => None,
})
}
......@@ -303,35 +327,23 @@ impl ModuleResolveResult {
#[turbo_tasks::function]
pub async fn first_module(&self) -> Result<Vc<OptionModule>> {
let first = self.primary.iter().find_map(|(_, item)| match item {
&ModuleResolveResultItem::Module(a) => Some(a),
_ => None,
});
let first_resolved = if let Some(first) = first {
Some(first.to_resolved().await?)
} else {
None
};
Ok(Vc::cell(first_resolved))
for (_, item) in self.primary.iter() {
if let Some(module) = item.as_module().await? {
return Ok(Vc::cell(Some(module)));
}
}
Ok(Vc::cell(None))
}
/// Returns a set (no duplicates) of primary modules in the result. All
/// modules are already resolved Vc.
#[turbo_tasks::function]
pub async fn primary_modules(&self) -> Result<Vc<Modules>> {
let mut iter = self.primary_modules_iter();
let Some(first) = iter.next() else {
return Ok(Vc::cell(vec![]));
};
let Some(second) = iter.next() else {
return Ok(Vc::cell(vec![first]));
};
// We have at least two items, so we need to deduplicate them
let mut set = fxindexset![first, second];
for module in self.primary_modules_iter() {
set.insert(module);
let mut set = FxIndexSet::default();
for (_, item) in self.primary.iter() {
if let Some(module) = item.as_module().await? {
set.insert(module);
}
}
Ok(Vc::cell(set.into_iter().collect()))
}
......
......@@ -127,6 +127,16 @@ impl Pattern {
}
}
pub fn has_dynamic_parts(&self) -> bool {
match self {
Pattern::Constant(_) => false,
Pattern::Dynamic => true,
Pattern::Alternatives(list) | Pattern::Concatenation(list) => {
list.iter().any(|p| p.has_dynamic_parts())
}
}
}
pub fn constant_prefix(&self) -> &str {
// The normalized pattern is an Alternative of maximally merged
// Concatenations, so extracting the first/only Concatenation child
......
......@@ -81,12 +81,12 @@ impl Module for ModuleCssAsset {
.await?
.iter()
.copied()
.chain(match *self.inner().await? {
ProcessResult::Module(inner) => {
Some(Vc::upcast(InternalCssAssetReference::new(*inner)))
}
ProcessResult::Ignore => None,
})
.chain(
self.inner()
.try_into_module()
.await?
.map(|inner| Vc::upcast(InternalCssAssetReference::new(*inner))),
)
.collect();
Ok(Vc::cell(references))
......
......@@ -74,10 +74,10 @@ impl ReferencedAsset {
pub async fn from_resolve_result(resolve_result: Vc<ModuleResolveResult>) -> Result<Vc<Self>> {
// TODO handle multiple keyed results
let result = resolve_result.await?;
if result.primary.is_empty() {
if result.is_unresolvable_ref() {
return Ok(ReferencedAsset::Unresolvable.cell());
}
for (_key, result) in result.primary.iter() {
for (_, result) in result.primary.iter() {
match result {
ModuleResolveResultItem::External(request, ty) => {
return Ok(ReferencedAsset::External(request.clone(), *ty).cell());
......
......@@ -16,7 +16,10 @@ use turbo_tasks::{
};
use turbopack_core::{
chunk::{ChunkItemExt, ChunkableModule, ChunkingContext, ModuleId},
issue::{code_gen::CodeGenerationIssue, IssueExt, IssueSeverity, StyledString},
issue::{
code_gen::CodeGenerationIssue, module::emit_unknown_module_type_error, IssueExt,
IssueSeverity, StyledString,
},
resolve::{
origin::ResolveOrigin, parse::Request, ExternalType, ModuleResolveResult,
ModuleResolveResultItem,
......@@ -317,7 +320,18 @@ async fn to_single_pattern_mapping(
return Ok(SinglePatternMapping::External(s.clone(), *ty));
}
ModuleResolveResultItem::Ignore => return Ok(SinglePatternMapping::Ignored),
_ => {
ModuleResolveResultItem::Unknown(source) => {
emit_unknown_module_type_error(*source).await?;
return Ok(SinglePatternMapping::Unresolvable(
"unknown module type".to_string(),
));
}
ModuleResolveResultItem::Error(str) => {
return Ok(SinglePatternMapping::Unresolvable(str.await?.to_string()))
}
ModuleResolveResultItem::OutputAsset(_)
| ModuleResolveResultItem::Empty
| ModuleResolveResultItem::Custom(_) => {
// TODO implement mapping
CodeGenerationIssue {
severity: IssueSeverity::Bug.into(),
......
......@@ -203,18 +203,16 @@ async fn extra_configs_changed(
.map(|path| async move {
Ok(
if matches!(&*path.get_type().await?, FileSystemEntryType::File) {
match *asset_context
asset_context
.process(
Vc::upcast(FileSource::new(path)),
Value::new(ReferenceType::Internal(InnerAssets::empty())),
)
.try_into_module()
.await?
{
ProcessResult::Module(module) => {
Some(any_content_changed_of_module(*module))
}
ProcessResult::Ignore => None,
}
.as_deref()
.copied()
.map(any_content_changed_of_module)
} else {
None
},
......
function requireSub(s) {
return require(`./sub/${s}`);
}
it("should ignore unrelated files for dynamic requests", () => {
expect(requireSub("index").default).toBe("sub")
});
error - [process module] [project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/dynamic-unrelated/input/sub/helper.txt Unknown module type
This module doesn't have an associated type. Use a known file extension, or register a loader for it.
Read more: https://nextjs.org/docs/app/api-reference/next-config-js/turbo#webpack-loaders
\ No newline at end of file
error - [process module] [project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/dynamic-unrelated/input/sub/README.md Unknown module type
This module doesn't have an associated type. Use a known file extension, or register a loader for it.
Read more: https://nextjs.org/docs/app/api-reference/next-config-js/turbo#webpack-loaders
\ No newline at end of file
......@@ -37,8 +37,7 @@ use turbopack_core::{
asset::Asset,
compile_time_info::CompileTimeInfo,
context::{AssetContext, ProcessResult},
ident::AssetIdent,
issue::{Issue, IssueExt, IssueStage, OptionStyledString, StyledString},
issue::{module::ModuleIssue, IssueExt, StyledString},
module::Module,
output::OutputAsset,
raw_module::RawModule,
......@@ -69,36 +68,6 @@ use self::{
transition::{Transition, TransitionOptions},
};
#[turbo_tasks::value]
struct ModuleIssue {
ident: Vc<AssetIdent>,
title: Vc<StyledString>,
description: Vc<StyledString>,
}
#[turbo_tasks::value_impl]
impl Issue for ModuleIssue {
#[turbo_tasks::function]
fn stage(&self) -> Vc<IssueStage> {
IssueStage::ProcessModule.cell()
}
#[turbo_tasks::function]
fn file_path(&self) -> Vc<FileSystemPath> {
self.ident.path()
}
#[turbo_tasks::function]
fn title(&self) -> Vc<StyledString> {
self.title
}
#[turbo_tasks::function]
fn description(&self) -> Vc<OptionStyledString> {
Vc::cell(Some(self.description))
}
}
#[turbo_tasks::function]
async fn apply_module_type(
source: Vc<Box<dyn Source>>,
......@@ -622,30 +591,14 @@ async fn process_default_internal(
}
}
let module_type = match current_module_type {
Some(module_type) => module_type,
None => {
ModuleIssue {
ident,
title: StyledString::Text("Unknown module type".into()).cell(),
description: StyledString::Text(
r"This module doesn't have an associated type. Use a known file extension, or register a loader for it.
Read more: https://nextjs.org/docs/app/api-reference/next-config-js/turbo#webpack-loaders".into(),
)
.cell(),
}
.cell()
.emit();
return Ok(ProcessResult::Ignore.cell());
}
}.cell();
let Some(module_type) = current_module_type else {
return Ok(ProcessResult::Unknown(current_source).cell());
};
Ok(apply_module_type(
current_source,
module_asset_context,
module_type,
module_type.cell(),
Value::new(reference_type.clone()),
part,
inner_assets,
......@@ -700,6 +653,7 @@ impl AssetContext for ModuleAssetContext {
request,
resolve_options,
);
let mut result = self.process_resolve_result(result.resolve().await?, reference_type);
if *self.is_types_resolving_enabled().await? {
......@@ -721,22 +675,18 @@ impl AssetContext for ModuleAssetContext {
reference_type: Value<ReferenceType>,
) -> Result<Vc<ModuleResolveResult>> {
let this = self.await?;
let transition = this.transition;
let result = result
.await?
.map_module(|source| {
let reference_type = reference_type.clone();
async move {
let process_result = if let Some(transition) = transition {
transition.process(*source, self, reference_type)
} else {
self.process_with_transition_rules(*source, reference_type)
};
let process_result = self.process(*source, reference_type);
Ok(match *process_result.await? {
ProcessResult::Module(m) => {
ModuleResolveResultItem::Module(ResolvedVc::upcast(m))
}
ProcessResult::Unknown(source) => ModuleResolveResultItem::Unknown(source),
ProcessResult::Ignore => ModuleResolveResultItem::Ignore,
})
}
......
......@@ -91,13 +91,17 @@ pub trait Transition {
) -> Result<Vc<ProcessResult>> {
let asset = self.process_source(asset);
let module_asset_context = self.process_context(module_asset_context);
let m = module_asset_context.process_default(asset, reference_type);
Ok(match *m.await? {
Ok(match &*module_asset_context
.process_default(asset, reference_type)
.await?
{
ProcessResult::Module(m) => ProcessResult::Module(
self.process_module(*m, module_asset_context)
self.process_module(**m, module_asset_context)
.to_resolved()
.await?,
),
ProcessResult::Unknown(source) => ProcessResult::Unknown(*source),
ProcessResult::Ignore => ProcessResult::Ignore,
}
.cell())
......
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