Unverified Commit a7107a3d authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

[turbopack] Fix css FOUC in dynamic component (#64021)

Follow up for #64294 to make turbopack side work as well

---------
Co-authored-by: 's avatarTobias Koppers <tobias.koppers@googlemail.com>
parent c976ca6e
use std::collections::HashMap;
use anyhow::{bail, Result};
use futures::Future;
use indexmap::IndexMap;
use tracing::Level;
use turbo_tasks::{
graph::{GraphTraversal, NonDeterministic},
Value, Vc,
......@@ -14,9 +16,10 @@ use turbopack_binding::{
turbopack::{
core::{
chunk::{
availability_info::AvailabilityInfo, ChunkableModule, ChunkingContextExt,
EvaluatableAssets,
availability_info::AvailabilityInfo, ChunkableModule, ChunkingContext,
ChunkingContextExt, EvaluatableAsset,
},
context::AssetContext,
issue::IssueSeverity,
module::Module,
output::OutputAssets,
......@@ -25,21 +28,19 @@ use turbopack_binding::{
resolve::{origin::PlainResolveOrigin, parse::Request, pattern::Pattern},
},
ecmascript::{
chunk::{EcmascriptChunkPlaceable, EcmascriptChunkingContext},
parse::ParseResult,
resolve::esm_resolve,
chunk::EcmascriptChunkingContext, parse::ParseResult, resolve::esm_resolve,
EcmascriptModuleAsset,
},
nodejs::NodeJsChunkingContext,
},
};
async fn collect_chunk_group_inner<F>(
async fn collect_chunk_group_inner<F, Fu>(
dynamic_import_entries: IndexMap<Vc<Box<dyn Module>>, DynamicImportedModules>,
build_chunk: F,
mut build_chunk: F,
) -> Result<Vc<DynamicImportedChunks>>
where
F: Fn(Vc<Box<dyn ChunkableModule>>) -> Vc<OutputAssets>,
F: FnMut(Vc<Box<dyn ChunkableModule>>) -> Fu,
Fu: Future<Output = Result<Vc<OutputAssets>>> + Send,
{
let mut chunks_hash: HashMap<String, Vc<OutputAssets>> = HashMap::new();
let mut dynamic_import_chunks = IndexMap::new();
......@@ -51,7 +52,7 @@ where
let chunk = if let Some(chunk) = chunks_hash.get(&imported_raw_str) {
*chunk
} else {
let Some(chunk_item) =
let Some(module) =
Vc::try_resolve_sidecast::<Box<dyn ChunkableModule>>(imported_module).await?
else {
bail!("module must be evaluatable");
......@@ -63,7 +64,7 @@ where
// naive hash to have additonal
// chunks in case if there are same modules being imported in differnt
// origins.
let chunk_group = build_chunk(chunk_item);
let chunk_group = build_chunk(module).await?;
chunks_hash.insert(imported_raw_str.to_string(), chunk_group);
chunk_group
};
......@@ -79,12 +80,12 @@ where
}
pub(crate) async fn collect_chunk_group(
chunking_context: Vc<NodeJsChunkingContext>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
dynamic_import_entries: IndexMap<Vc<Box<dyn Module>>, DynamicImportedModules>,
availability_info: Value<AvailabilityInfo>,
) -> Result<Vc<DynamicImportedChunks>> {
collect_chunk_group_inner(dynamic_import_entries, |chunk_item| {
chunking_context.chunk_group_assets(chunk_item, availability_info)
collect_chunk_group_inner(dynamic_import_entries, |module| async move {
Ok(chunking_context.chunk_group_assets(module, availability_info))
})
.await
}
......@@ -92,14 +93,17 @@ pub(crate) async fn collect_chunk_group(
pub(crate) async fn collect_evaluated_chunk_group(
chunking_context: Vc<Box<dyn EcmascriptChunkingContext>>,
dynamic_import_entries: IndexMap<Vc<Box<dyn Module>>, DynamicImportedModules>,
evaluatable_assets: Vc<EvaluatableAssets>,
) -> Result<Vc<DynamicImportedChunks>> {
collect_chunk_group_inner(dynamic_import_entries, |chunk_item| {
chunking_context.evaluated_chunk_group_assets(
chunk_item.ident(),
evaluatable_assets,
Value::new(AvailabilityInfo::Root),
)
collect_chunk_group_inner(dynamic_import_entries, |module| async move {
if let Some(module) = Vc::try_resolve_downcast::<Box<dyn EvaluatableAsset>>(module).await? {
Ok(chunking_context.evaluated_chunk_group_assets(
module.ident(),
Vc::cell(vec![Vc::upcast(module)]),
Value::new(AvailabilityInfo::Root),
))
} else {
Ok(chunking_context.chunk_group_assets(module, Value::new(AvailabilityInfo::Root)))
}
})
.await
}
......@@ -127,8 +131,10 @@ pub(crate) async fn collect_evaluated_chunk_group(
/// - Loadable runtime [injects preload fn](https://github.com/vercel/next.js/blob/ad42b610c25b72561ad367b82b1c7383fd2a5dd2/packages/next/src/shared/lib/loadable.shared-runtime.tsx#L281)
/// to wait until all the dynamic components are being loaded, this ensures
/// hydration mismatch won't occur
#[tracing::instrument(level = Level::TRACE, skip_all)]
pub(crate) async fn collect_next_dynamic_imports(
entry: Vc<Box<dyn EcmascriptChunkPlaceable>>,
server_entries: impl IntoIterator<Item = Vc<Box<dyn Module>>>,
client_asset_context: Vc<Box<dyn AssetContext>>,
) -> Result<IndexMap<Vc<Box<dyn Module>>, DynamicImportedModules>> {
// Traverse referenced modules graph, collect all of the dynamic imports:
// - Read the Program AST of the Module, this is the origin (A)
......@@ -139,12 +145,14 @@ pub(crate) async fn collect_next_dynamic_imports(
// and Module<B> is the actual resolved Module)
let imported_modules_mapping = NonDeterministic::new()
.skip_duplicates()
.visit([Vc::upcast(entry)], get_referenced_modules)
.visit(server_entries.into_iter(), get_referenced_modules)
.await
.completed()?
.into_inner()
.into_iter()
.map(build_dynamic_imports_map_for_module);
.map(|server_module| {
build_dynamic_imports_map_for_module(client_asset_context, server_module)
});
// Consolidate import mappings into a single indexmap
let mut import_mappings: IndexMap<Vc<Box<dyn Module>>, DynamicImportedModules> =
......@@ -173,18 +181,19 @@ async fn get_referenced_modules(
#[turbo_tasks::function]
async fn build_dynamic_imports_map_for_module(
module: Vc<Box<dyn Module>>,
client_asset_context: Vc<Box<dyn AssetContext>>,
server_module: Vc<Box<dyn Module>>,
) -> Result<Vc<OptionDynamicImportsMap>> {
let Some(ecmascript_asset) =
Vc::try_resolve_downcast_type::<EcmascriptModuleAsset>(module).await?
Vc::try_resolve_downcast_type::<EcmascriptModuleAsset>(server_module).await?
else {
return Ok(OptionDynamicImportsMap::none());
return Ok(Vc::cell(None));
};
// https://github.com/vercel/next.js/pull/56389#discussion_r1349336374
// don't emit specific error as we expect there's a parse error already reported
let ParseResult::Ok { program, .. } = &*ecmascript_asset.parse().await? else {
return Ok(OptionDynamicImportsMap::none());
return Ok(Vc::cell(None));
};
// Reading the Program AST, collect raw imported module str if it's wrapped in
......@@ -193,7 +202,7 @@ async fn build_dynamic_imports_map_for_module(
program.visit_with(&mut visitor);
if visitor.import_sources.is_empty() {
return Ok(OptionDynamicImportsMap::none());
return Ok(Vc::cell(None));
}
let mut import_sources = vec![];
......@@ -202,11 +211,11 @@ async fn build_dynamic_imports_map_for_module(
// resolve the module that is being imported.
let dynamic_imported_resolved_module = *esm_resolve(
Vc::upcast(PlainResolveOrigin::new(
ecmascript_asset.await?.asset_context,
module.ident().path(),
client_asset_context,
server_module.ident().path(),
)),
Request::parse(Value::new(Pattern::Constant(import.to_string()))),
Value::new(EcmaScriptModulesReferenceSubType::Undefined),
Value::new(EcmaScriptModulesReferenceSubType::DynamicImport),
IssueSeverity::Error.cell(),
None,
)
......@@ -218,7 +227,7 @@ async fn build_dynamic_imports_map_for_module(
}
}
Ok(Vc::cell(Some(Vc::cell((module, import_sources)))))
Ok(Vc::cell(Some(Vc::cell((server_module, import_sources)))))
}
/// A visitor to check if there's import to `next/dynamic`, then collecting the
......@@ -312,13 +321,5 @@ pub struct DynamicImportsMap(pub (Vc<Box<dyn Module>>, DynamicImportedModules));
#[turbo_tasks::value(transparent)]
pub struct OptionDynamicImportsMap(Option<Vc<DynamicImportsMap>>);
#[turbo_tasks::value_impl]
impl OptionDynamicImportsMap {
#[turbo_tasks::function]
pub fn none() -> Vc<Self> {
Vc::cell(None)
}
}
#[turbo_tasks::value(transparent)]
pub struct DynamicImportedChunks(pub IndexMap<Vc<Box<dyn Module>>, DynamicImportedOutputAssets>);
......@@ -6,6 +6,7 @@ mod dynamic_imports;
pub mod entrypoints;
mod font;
mod instrumentation;
mod loadable_manifest;
mod middleware;
mod pages;
pub mod paths;
......
use std::collections::HashMap;
use anyhow::Result;
use next_core::next_manifests::LoadableManifest;
use turbo_tasks::{TryFlatJoinIterExt, Vc};
use turbopack_binding::{
turbo::tasks_fs::{File, FileContent, FileSystemPath},
turbopack::core::{
asset::AssetContent,
module::Module,
output::{OutputAsset, OutputAssets},
virtual_output::VirtualOutputAsset,
},
};
use crate::dynamic_imports::DynamicImportedChunks;
#[turbo_tasks::function]
pub async fn create_react_loadable_manifest(
dynamic_import_entries: Vc<DynamicImportedChunks>,
client_relative_path: Vc<FileSystemPath>,
output_path: Vc<FileSystemPath>,
) -> Result<Vc<OutputAssets>> {
let dynamic_import_entries = &*dynamic_import_entries.await?;
let mut output = vec![];
let mut loadable_manifest: HashMap<String, LoadableManifest> = Default::default();
for (origin, dynamic_imports) in dynamic_import_entries.into_iter() {
let origin_path = &*origin.ident().path().await?;
for (import, chunk_output) in dynamic_imports {
let chunk_output = chunk_output.await?;
output.extend(chunk_output.iter().copied());
let id = format!("{} -> {}", origin_path, import);
let client_relative_path_value = client_relative_path.await?;
let files = chunk_output
.iter()
.map(move |&file| {
let client_relative_path_value = client_relative_path_value.clone();
async move {
Ok(client_relative_path_value
.get_path_to(&*file.ident().path().await?)
.map(|path| path.to_string()))
}
})
.try_flat_join()
.await?;
let manifest_item = LoadableManifest {
id: id.clone(),
files,
};
loadable_manifest.insert(id, manifest_item);
}
}
let loadable_manifest = Vc::upcast(VirtualOutputAsset::new(
output_path,
AssetContent::file(
FileContent::Content(File::from(serde_json::to_string_pretty(
&loadable_manifest,
)?))
.cell(),
),
));
output.push(loadable_manifest);
Ok(Vc::cell(output))
}
use std::collections::HashMap;
use anyhow::{bail, Context, Result};
use indexmap::IndexMap;
use next_core::{
......@@ -12,8 +10,8 @@ use next_core::{
next_dynamic::NextDynamicTransition,
next_edge::route_regex::get_named_middleware_regex,
next_manifests::{
BuildManifest, EdgeFunctionDefinition, LoadableManifest, MiddlewareMatcher,
MiddlewaresManifestV2, PagesManifest,
BuildManifest, EdgeFunctionDefinition, MiddlewareMatcher, MiddlewaresManifestV2,
PagesManifest,
},
next_pages::create_page_ssr_entry_module,
next_server::{
......@@ -28,9 +26,7 @@ use next_core::{
};
use serde::{Deserialize, Serialize};
use tracing::Instrument;
use turbo_tasks::{
trace::TraceRawVcs, Completion, TaskInput, TryFlatJoinIterExt, TryJoinIterExt, Value, Vc,
};
use turbo_tasks::{trace::TraceRawVcs, Completion, TaskInput, TryJoinIterExt, Value, Vc};
use turbopack_binding::{
turbo::tasks_fs::{
File, FileContent, FileSystem, FileSystemPath, FileSystemPathOption, VirtualFileSystem,
......@@ -72,6 +68,7 @@ use crate::{
DynamicImportedChunks,
},
font::create_font_manifest,
loadable_manifest::create_react_loadable_manifest,
paths::{
all_paths_in_root, all_server_paths, get_js_paths_from_root, get_wasm_paths_from_root,
wasm_paths_to_bindings,
......@@ -743,15 +740,20 @@ impl PageEndpoint {
let edge_files = edge_chunking_context.evaluated_chunk_group_assets(
ssr_module.ident(),
Vc::cell(evaluatable_assets.clone()),
Vc::cell(evaluatable_assets),
Value::new(AvailabilityInfo::Root),
);
let dynamic_import_modules = collect_next_dynamic_imports(ssr_module).await?;
let dynamic_import_modules = collect_next_dynamic_imports(
[Vc::upcast(ssr_module)],
this.pages_project.client_module_context(),
)
.await?;
let client_chunking_context =
this.pages_project.project().client_chunking_context();
let dynamic_import_entries = collect_evaluated_chunk_group(
edge_chunking_context,
Vc::upcast(client_chunking_context),
dynamic_import_modules,
Vc::cell(evaluatable_assets.clone()),
)
.await?;
......@@ -805,9 +807,15 @@ impl PageEndpoint {
.await?;
let availability_info = Value::new(AvailabilityInfo::Root);
let dynamic_import_modules = collect_next_dynamic_imports(ssr_module).await?;
let dynamic_import_modules = collect_next_dynamic_imports(
[Vc::upcast(ssr_module)],
this.pages_project.client_module_context(),
)
.await?;
let client_chunking_context =
this.pages_project.project().client_chunking_context();
let dynamic_import_entries = collect_chunk_group(
chunking_context,
Vc::upcast(client_chunking_context),
dynamic_import_modules,
availability_info,
)
......@@ -919,74 +927,19 @@ impl PageEndpoint {
#[turbo_tasks::function]
async fn react_loadable_manifest(
self: Vc<Self>,
&self,
dynamic_import_entries: Vc<DynamicImportedChunks>,
) -> Result<Vc<OutputAssets>> {
let this = self.await?;
let node_root = this.pages_project.project().node_root();
let project_src_dir = this.pages_project.pages_dir().parent().await?;
let dynamic_import_entries = &*dynamic_import_entries.await?;
let mut output = vec![];
let mut loadable_manifest: HashMap<String, LoadableManifest> = Default::default();
for (origin, dynamic_imports) in dynamic_import_entries.into_iter() {
let origin_path = &*origin.ident().path().await?;
for (import, chunk_output) in dynamic_imports {
let chunk_output = chunk_output.await?;
output.extend(chunk_output.iter().copied());
// https://github.com/vercel/next.js/blob/canary/packages/next/src/build/webpack/plugins/react-loadable-plugin.ts
// next_dynamic transform puts relative paths to the project dir
// dir for the origin import.
let id = format!(
"{} -> {}",
project_src_dir
.get_path_to(origin_path)
.map_or_else(|| origin_path.to_string(), |path| path.to_string()),
import
);
let server_path = node_root.join("server".to_string());
let server_path_value = server_path.await?;
let files = chunk_output
.iter()
.map(move |file| {
let server_path_value = server_path_value.clone();
async move {
Ok(server_path_value
.get_path_to(&*file.ident().path().await?)
.map(|path| path.to_string()))
}
})
.try_flat_join()
.await?;
let manifest_item = LoadableManifest {
id: id.clone(),
files,
};
loadable_manifest.insert(id, manifest_item);
}
}
let loadable_path_prefix = get_asset_prefix_from_pathname(&this.pathname.await?);
let loadable_manifest = Vc::upcast(VirtualOutputAsset::new(
let node_root = self.pages_project.project().node_root();
let client_relative_path = self.pages_project.project().client_relative_path();
let loadable_path_prefix = get_asset_prefix_from_pathname(&self.pathname.await?);
Ok(create_react_loadable_manifest(
dynamic_import_entries,
client_relative_path,
node_root.join(format!(
"server/pages{loadable_path_prefix}/react-loadable-manifest.json"
)),
AssetContent::file(
FileContent::Content(File::from(serde_json::to_string_pretty(
&loadable_manifest,
)?))
.cell(),
),
));
output.push(loadable_manifest);
Ok(Vc::cell(output))
))
}
#[turbo_tasks::function]
......
......@@ -40,7 +40,7 @@ pub async fn get_next_client_transforms_rules(
let mdx_rs = *next_config.mdx_rs().await?;
rules.push(get_next_font_transform_rule(mdx_rs));
let pages_or_app_dir = match context_ty {
match context_ty {
ClientContextType::Pages { pages_dir } => {
if !foreign_code {
rules.push(
......@@ -57,16 +57,14 @@ pub async fn get_next_client_transforms_rules(
));
rules.push(get_next_page_config_rule(mdx_rs, pages_dir.await?));
}
Some(pages_dir)
}
ClientContextType::App { app_dir } => {
ClientContextType::App { .. } => {
rules.push(get_server_actions_transform_rule(
ActionsTransform::Client,
mdx_rs,
));
Some(app_dir)
}
ClientContextType::Fallback | ClientContextType::Other => None,
ClientContextType::Fallback | ClientContextType::Other => {}
};
if !foreign_code {
......@@ -74,9 +72,7 @@ pub async fn get_next_client_transforms_rules(
rules.push(get_next_cjs_optimizer_rule(mdx_rs));
rules.push(get_next_pure_rule(mdx_rs));
rules.push(
get_next_dynamic_transform_rule(false, false, pages_or_app_dir, mode, mdx_rs).await?,
);
rules.push(get_next_dynamic_transform_rule(false, false, mode, mdx_rs).await?);
rules.push(get_next_image_rule());
rules.push(get_next_page_static_info_assert_rule(
......
......@@ -50,7 +50,7 @@ pub async fn get_next_server_transforms_rules(
));
}
let (is_server_components, pages_or_app_dir) = match context_ty {
let is_server_components = match context_ty {
ServerContextType::Pages { pages_dir } | ServerContextType::PagesApi { pages_dir } => {
if !foreign_code {
rules.push(get_next_disallow_export_all_in_page_rule(
......@@ -58,7 +58,7 @@ pub async fn get_next_server_transforms_rules(
pages_dir.await?,
));
}
(false, Some(pages_dir))
false
}
ServerContextType::PagesData { pages_dir } => {
if !foreign_code {
......@@ -75,9 +75,9 @@ pub async fn get_next_server_transforms_rules(
pages_dir.await?,
));
}
(false, Some(pages_dir))
false
}
ServerContextType::AppSSR { app_dir } => {
ServerContextType::AppSSR { .. } => {
// Yah, this is SSR, but this is still treated as a Client transform layer.
// need to apply to foreign code too
rules.push(get_server_actions_transform_rule(
......@@ -85,12 +85,10 @@ pub async fn get_next_server_transforms_rules(
mdx_rs,
));
(false, Some(app_dir))
false
}
ServerContextType::AppRSC {
app_dir,
client_transition,
..
client_transition, ..
} => {
rules.push(get_server_actions_transform_rule(
ActionsTransform::Server,
......@@ -102,25 +100,15 @@ pub async fn get_next_server_transforms_rules(
client_transition,
));
}
(true, Some(app_dir))
}
ServerContextType::AppRoute { .. } => (false, None),
ServerContextType::Middleware { .. } | ServerContextType::Instrumentation { .. } => {
(false, None)
true
}
ServerContextType::AppRoute { .. } => false,
ServerContextType::Middleware { .. } | ServerContextType::Instrumentation { .. } => false,
};
if !foreign_code {
rules.push(
get_next_dynamic_transform_rule(
true,
is_server_components,
pages_or_app_dir,
mode,
mdx_rs,
)
.await?,
);
rules
.push(get_next_dynamic_transform_rule(true, is_server_components, mode, mdx_rs).await?);
rules.push(get_next_amp_attr_rule(mdx_rs));
rules.push(get_next_cjs_optimizer_rule(mdx_rs));
......
use std::path::PathBuf;
use anyhow::Result;
use async_trait::async_trait;
use next_custom_transforms::transforms::dynamic::{next_dynamic, NextDynamicMode};
......@@ -12,7 +10,6 @@ use turbopack_binding::{
visit::FoldWith,
},
},
turbo::tasks_fs::FileSystemPath,
turbopack::{
ecmascript::{CustomTransformer, EcmascriptInputTransform, TransformContext},
turbopack::module_options::{ModuleRule, ModuleRuleEffect},
......@@ -26,17 +23,12 @@ use crate::mode::NextMode;
pub async fn get_next_dynamic_transform_rule(
is_server_compiler: bool,
is_react_server_layer: bool,
pages_or_app_dir: Option<Vc<FileSystemPath>>,
mode: Vc<NextMode>,
enable_mdx_rs: bool,
) -> Result<ModuleRule> {
let dynamic_transform = EcmascriptInputTransform::Plugin(Vc::cell(Box::new(NextJsDynamic {
is_server_compiler,
is_react_server_layer,
pages_or_app_dir: match pages_or_app_dir {
None => None,
Some(path) => Some(path.await?.path.clone().into()),
},
mode: *mode.await?,
}) as _));
Ok(ModuleRule::new(
......@@ -52,7 +44,6 @@ pub async fn get_next_dynamic_transform_rule(
struct NextJsDynamic {
is_server_compiler: bool,
is_react_server_layer: bool,
pages_or_app_dir: Option<PathBuf>,
mode: NextMode,
}
......@@ -67,7 +58,7 @@ impl CustomTransformer for NextJsDynamic {
false,
NextDynamicMode::Webpack,
FileName::Real(ctx.file_path_str.into()),
self.pages_or_app_dir.clone(),
None,
));
Ok(())
......
......@@ -40,7 +40,11 @@ export default (context, env) => {
const { dynamicIds } = JSON.parse($('#__NEXT_DATA__').html())
if (env === 'dev') {
expect(dynamicIds).toContain(`pages/${page}.js -> ../components/foo`)
expect(
dynamicIds.find((id) =>
id.includes(`pages/${page}.js -> ../components/foo`)
)
).toBeTruthy()
} else {
expect(dynamicIds.length).toBe(1)
}
......
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