Unverified Commit 59da6f30 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Rebase server HMR entry map refactor and address review

Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent e2de3c0b
This diff is collapsed.
...@@ -72,6 +72,7 @@ use turbopack_ecmascript::single_file_ecmascript_output::SingleFileEcmascriptOut ...@@ -72,6 +72,7 @@ use turbopack_ecmascript::single_file_ecmascript_output::SingleFileEcmascriptOut
use turbopack_resolve::{ecmascript::cjs_resolve, resolve_options_context::ResolveOptionsContext}; use turbopack_resolve::{ecmascript::cjs_resolve, resolve_options_context::ResolveOptionsContext};
use crate::{ use crate::{
aggregate_hmr::{ServerHmrChunkList, ServerHmrChunkLists},
dynamic_imports::{NextDynamicChunkAvailability, collect_next_dynamic_chunks}, dynamic_imports::{NextDynamicChunkAvailability, collect_next_dynamic_chunks},
font::FontManifest, font::FontManifest,
loadable_manifest::create_react_loadable_manifest, loadable_manifest::create_react_loadable_manifest,
...@@ -1389,8 +1390,9 @@ impl AppEndpoint { ...@@ -1389,8 +1390,9 @@ impl AppEndpoint {
// TODO: This anchor can go away once edges to chunk references are represented explicitly // TODO: This anchor can go away once edges to chunk references are represented explicitly
// in the chunk graph (rsc chunk -> ssr chunk), which would make the SSR chunks reachable // in the chunk graph (rsc chunk -> ssr chunk), which would make the SSR chunks reachable
// from the RSC chunk lists directly. // from the RSC chunk lists directly.
if is_app_page let ssr_hmr_chunk_list = if is_app_page
&& runtime == NextRuntime::NodeJs && runtime == NextRuntime::NodeJs
&& project.next_mode().await?.is_development()
&& project && project
.client_compile_time_info() .client_compile_time_info()
.await? .await?
...@@ -1409,7 +1411,10 @@ impl AppEndpoint { ...@@ -1409,7 +1411,10 @@ impl AppEndpoint {
.to_resolved() .to_resolved()
.await?; .await?;
server_assets.insert(ssr_hmr_chunks); server_assets.insert(ssr_hmr_chunks);
} Some(ssr_hmr_chunks)
} else {
None
};
// In development, register a page-specific HMR chunk list that owns all client // In development, register a page-specific HMR chunk list that owns all client
// reference chunks for this page. These chunks are computed via separate // reference chunks for this page. These chunks are computed via separate
...@@ -1826,6 +1831,17 @@ impl AppEndpoint { ...@@ -1826,6 +1831,17 @@ impl AppEndpoint {
NextRuntime::NodeJs => { NextRuntime::NodeJs => {
// For node, there will be exactly one asset in this // For node, there will be exactly one asset in this
let rsc_chunk = *app_entry_chunks_ref.first().unwrap(); let rsc_chunk = *app_entry_chunks_ref.first().unwrap();
let server_hmr_chunks = if project.next_mode().await?.is_development() {
let mut server_hmr_chunks =
vec![ServerHmrChunkList::from_chunk_list(rsc_chunk).await?];
if let Some(ssr_hmr_chunk_list) = ssr_hmr_chunk_list {
server_hmr_chunks
.push(ServerHmrChunkList::from_chunk_list(ssr_hmr_chunk_list).await?);
}
Some(ServerHmrChunkLists::new(server_hmr_chunks).resolved_cell())
} else {
None
};
if emit_manifests != EmitManifests::None { if emit_manifests != EmitManifests::None {
// create app paths manifest // create app paths manifest
...@@ -1903,6 +1919,7 @@ impl AppEndpoint { ...@@ -1903,6 +1919,7 @@ impl AppEndpoint {
rsc_chunk, rsc_chunk,
server_assets, server_assets,
client_assets, client_assets,
server_hmr_chunks,
} }
} }
} }
...@@ -2225,37 +2242,22 @@ impl Endpoint for AppEndpoint { ...@@ -2225,37 +2242,22 @@ impl Endpoint for AppEndpoint {
(vec![], vec![]) (vec![], vec![])
}; };
let server_hmr_chunks = match *output.await? {
AppEndpointOutput::NodeJs {
server_hmr_chunks, ..
} => server_hmr_chunks,
AppEndpointOutput::Edge { .. } => None,
};
let written_endpoint = match *output.await? { let written_endpoint = match *output.await? {
AppEndpointOutput::NodeJs { rsc_chunk, .. } => { AppEndpointOutput::NodeJs { rsc_chunk, .. } => EndpointOutputPaths::NodeJs {
let server_entry_path: RcStr = node_root server_entry_path: node_root
.get_path_to(&*rsc_chunk.path().await?) .get_path_to(&*rsc_chunk.path().await?)
.context("Node.js chunk entry path must be inside the node root")? .context("Node.js chunk entry path must be inside the node root")?
.into(); .into(),
let hmr_entry_path = server_entry_path server_paths,
.strip_prefix("server/app/") client_paths,
.unwrap_or(&server_entry_path) },
.strip_suffix(".js")
.unwrap_or(&server_entry_path);
let mut server_hmr_entry_paths = vec![
format!("{hmr_entry_path}.js").into(),
format!("{hmr_entry_path}/client-components-ssr.js").into(),
];
if matches!(this.ty, AppEndpointType::Page { .. })
&& *project
.next_config()
.turbopack_lazy_dynamic_imports_ssr(*project.next_mode().await?)
.await?
{
server_hmr_entry_paths
.push(format!("{hmr_entry_path}/rsc-dynamic-imports.js").into());
}
EndpointOutputPaths::NodeJs {
server_hmr_entry_paths,
server_entry_path,
server_paths,
client_paths,
}
}
AppEndpointOutput::Edge { .. } => EndpointOutputPaths::Edge { AppEndpointOutput::Edge { .. } => EndpointOutputPaths::Edge {
server_paths, server_paths,
client_paths, client_paths,
...@@ -2267,6 +2269,7 @@ impl Endpoint for AppEndpoint { ...@@ -2267,6 +2269,7 @@ impl Endpoint for AppEndpoint {
output_assets: output_assets.to_resolved().await?, output_assets: output_assets.to_resolved().await?,
output_paths: written_endpoint.resolved_cell(), output_paths: written_endpoint.resolved_cell(),
project: project.to_resolved().await?, project: project.to_resolved().await?,
server_hmr_chunks,
} }
.cell(), .cell(),
) )
...@@ -2403,6 +2406,7 @@ enum AppEndpointOutput { ...@@ -2403,6 +2406,7 @@ enum AppEndpointOutput {
rsc_chunk: ResolvedVc<Box<dyn OutputAsset>>, rsc_chunk: ResolvedVc<Box<dyn OutputAsset>>,
server_assets: ResolvedVc<OutputAssets>, server_assets: ResolvedVc<OutputAssets>,
client_assets: ResolvedVc<OutputAssets>, client_assets: ResolvedVc<OutputAssets>,
server_hmr_chunks: Option<ResolvedVc<ServerHmrChunkLists>>,
}, },
Edge { Edge {
files: ResolvedVc<OutputAssets>, files: ResolvedVc<OutputAssets>,
......
...@@ -237,6 +237,7 @@ impl Endpoint for InstrumentationEndpoint { ...@@ -237,6 +237,7 @@ impl Endpoint for InstrumentationEndpoint {
} }
.resolved_cell(), .resolved_cell(),
project: this.project, project: this.project,
server_hmr_chunks: None,
} }
.cell()) .cell())
} }
......
...@@ -387,6 +387,7 @@ impl Endpoint for MiddlewareEndpoint { ...@@ -387,6 +387,7 @@ impl Endpoint for MiddlewareEndpoint {
.resolved_cell(), .resolved_cell(),
output_assets: output_assets.to_resolved().await?, output_assets: output_assets.to_resolved().await?,
project: this.project, project: this.project,
server_hmr_chunks: None,
} }
.cell()) .cell())
} }
......
...@@ -1715,7 +1715,6 @@ impl Endpoint for PageEndpoint { ...@@ -1715,7 +1715,6 @@ impl Endpoint for PageEndpoint {
EndpointOutputPaths::NodeJs { EndpointOutputPaths::NodeJs {
server_entry_path, server_entry_path,
server_hmr_entry_paths: vec![],
server_paths, server_paths,
client_paths, client_paths,
} }
...@@ -1731,6 +1730,7 @@ impl Endpoint for PageEndpoint { ...@@ -1731,6 +1730,7 @@ impl Endpoint for PageEndpoint {
output_assets: output_assets.to_resolved().await?, output_assets: output_assets.to_resolved().await?,
output_paths: written_endpoint.resolved_cell(), output_paths: written_endpoint.resolved_cell(),
project: project.to_resolved().await?, project: project.to_resolved().await?,
server_hmr_chunks: None,
} }
.cell(), .cell(),
) )
......
...@@ -106,7 +106,7 @@ use turbopack_nodejs::{NodeJsChunkingContext, fs::NodeModulesPathMatcher}; ...@@ -106,7 +106,7 @@ use turbopack_nodejs::{NodeJsChunkingContext, fs::NodeModulesPathMatcher};
pub use crate::additional_roots::AdditionalRootConfig; pub use crate::additional_roots::AdditionalRootConfig;
use crate::{ use crate::{
additional_roots::{AdditionalDiskFileSystem, create_additional_root_file_systems}, additional_roots::{AdditionalDiskFileSystem, create_additional_root_file_systems},
aggregate_hmr::ServerHmrChunkLists, aggregate_hmr::{ServerHmrChunkLists, ServerHmrEntryKey, ServerHmrEntryMap},
app::{AppProject, OptionAppProject}, app::{AppProject, OptionAppProject},
empty::EmptyEndpoint, empty::EmptyEndpoint,
entrypoints::Entrypoints, entrypoints::Entrypoints,
...@@ -116,8 +116,8 @@ use crate::{ ...@@ -116,8 +116,8 @@ use crate::{
pages::PagesProject, pages::PagesProject,
path_utils::convention_file_base_name, path_utils::convention_file_base_name,
route::{ route::{
Endpoint, EndpointGroup, EndpointGroupEntry, EndpointGroupKey, EndpointGroups, Endpoints, Endpoint, EndpointGroup, EndpointGroupEntry, EndpointGroupKey, EndpointGroups,
Route, EndpointOutput, Endpoints, Route,
}, },
versioned_content_map::VersionedContentMap, versioned_content_map::VersionedContentMap,
}; };
...@@ -971,6 +971,7 @@ impl ProjectContainer { ...@@ -971,6 +971,7 @@ impl ProjectContainer {
NextMode::Build.resolved_cell() NextMode::Build.resolved_cell()
}, },
versioned_content_map: self.versioned_content_map, versioned_content_map: self.versioned_content_map,
server_hmr_entry_map: dev.then(|| Arc::new(ServerHmrEntryMap::default())),
build_id, build_id,
encryption_key, encryption_key,
preview_props, preview_props,
...@@ -1017,7 +1018,10 @@ impl ProjectContainer { ...@@ -1017,7 +1018,10 @@ impl ProjectContainer {
} }
#[derive(Clone)] #[derive(Clone)]
#[turbo_tasks::value] // The HMR entry map holds session-local pinned operations. Persisting just the other fields and
// defaulting this map after restore would leave clean endpoint tasks with no registrations, so
// recreate the entire Project each session and keep the registry alive for that session.
#[turbo_tasks::value(serialization = "skip", evict = "never")]
pub struct Project { pub struct Project {
/// An absolute root path (Windows or Unix path) from which all files must be nested under. /// An absolute root path (Windows or Unix path) from which all files must be nested under.
/// Trying to access a file outside this root will fail, so think of this as a chroot. /// Trying to access a file outside this root will fail, so think of this as a chroot.
...@@ -1029,6 +1033,11 @@ pub struct Project { ...@@ -1029,6 +1033,11 @@ pub struct Project {
/// E.g. `apps/my-app` /// E.g. `apps/my-app`
project_path: RcStr, project_path: RcStr,
// This map holds pinned operations for the lifetime of the current dev session. It is
// intentionally excluded from Turbo Tasks tracing; Project is never evicted.
#[turbo_tasks(unsafe_ignore, debug_ignore)]
server_hmr_entry_map: Option<Arc<ServerHmrEntryMap>>,
/// A path where to emit the build outputs, relative to [`Project::project_path`], always a /// A path where to emit the build outputs, relative to [`Project::project_path`], always a
/// Unix path. Corresponds to next.config.js's `distDir`. /// Unix path. Corresponds to next.config.js's `distDir`.
/// E.g. `.next` /// E.g. `.next`
...@@ -1090,10 +1099,37 @@ pub struct Project { ...@@ -1090,10 +1099,37 @@ pub struct Project {
project_file_system: OperationVc<DiskFileSystem>, project_file_system: OperationVc<DiskFileSystem>,
output_file_system: OperationVc<DiskFileSystem>, output_file_system: OperationVc<DiskFileSystem>,
#[bincode(with = "turbo_bincode::indexmap")]
pub(crate) additional_roots: FxIndexMap<RcStr, AdditionalDiskFileSystem>, pub(crate) additional_roots: FxIndexMap<RcStr, AdditionalDiskFileSystem>,
} }
impl Project {
pub fn register_server_hmr_entry(
&self,
entry_key: ServerHmrEntryKey,
output: OperationVc<EndpointOutput>,
) {
if let Some(server_hmr_entry_map) = &self.server_hmr_entry_map {
server_hmr_entry_map.set(entry_key, output);
}
}
pub async fn server_hmr_chunk_lists(
&self,
entry_key: &ServerHmrEntryKey,
) -> Result<ReadRef<ServerHmrChunkLists>> {
let output = self
.server_hmr_entry_map
.as_ref()
.and_then(|server_hmr_entry_map| server_hmr_entry_map.get(entry_key));
if let Some(output) = output
&& let Some(chunk_lists) = output.connect().await?.server_hmr_chunks
{
return chunk_lists.await;
}
Ok(ReadRef::new_owned(ServerHmrChunkLists::new(vec![])))
}
}
#[turbo_tasks::value] #[turbo_tasks::value]
pub struct ProjectDefineEnv { pub struct ProjectDefineEnv {
client: ResolvedVc<OptionEnvMap>, client: ResolvedVc<OptionEnvMap>,
...@@ -2593,11 +2629,6 @@ impl Project { ...@@ -2593,11 +2629,6 @@ impl Project {
.await .await
} }
#[turbo_tasks::function]
async fn server_hmr_root_path(self: Vc<Self>) -> Result<Vc<FileSystemPath>> {
Ok(self.node_root().await?.join("server/app")?.cell())
}
/// Get client HMR content by chunk_name. /// Get client HMR content by chunk_name.
#[turbo_tasks::function] #[turbo_tasks::function]
async fn hmr_content(self: Vc<Self>, chunk_name: RcStr) -> Result<Vc<OptionVersionedContent>> { async fn hmr_content(self: Vc<Self>, chunk_name: RcStr) -> Result<Vc<OptionVersionedContent>> {
...@@ -2672,27 +2703,6 @@ impl Project { ...@@ -2672,27 +2703,6 @@ impl Project {
} }
} }
/// Server entry chunks shared by all pull baselines.
#[turbo_tasks::function]
pub async fn server_hmr_chunks(self: Vc<Self>) -> Result<Vc<ServerHmrChunkLists>> {
let Some(map) = self.await?.versioned_content_map else {
bail!("must be in dev mode to hmr")
};
let root = self.server_hmr_root_path().owned().await?;
Ok(map.server_hmr_chunks_in_path(root))
}
#[turbo_tasks::function]
pub async fn server_hmr_chunks_for_entries(
self: Vc<Self>,
entry_paths: Vec<RcStr>,
) -> Result<Vc<ServerHmrChunkLists>> {
let mut chunk_lists =
ServerHmrChunkLists::new(self.server_hmr_chunks().await?.as_slice().to_vec());
chunk_lists.retain_entry_paths(&entry_paths.into_iter().collect());
Ok(chunk_lists.cell())
}
/// Gets a list of all client HMR chunk names that can be subscribed to. /// Gets a list of all client HMR chunk names that can be subscribed to.
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn hmr_chunk_names(self: Vc<Self>) -> Result<Vc<Vec<RcStr>>> { pub async fn hmr_chunk_names(self: Vc<Self>) -> Result<Vc<Vec<RcStr>>> {
......
...@@ -6,15 +6,20 @@ use itertools::Itertools; ...@@ -6,15 +6,20 @@ use itertools::Itertools;
use next_core::app_structure::FileSystemPathVec; use next_core::app_structure::FileSystemPathVec;
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ use turbo_tasks::{
Completion, FxIndexMap, FxIndexSet, JoinIterExt, NonLocalValue, OperationVc, ResolvedVc, Completion, FxIndexMap, FxIndexSet, JoinIterExt, NonLocalValue, OperationVc, ReadRef,
TryJoinIterExt, Vc, debug::ValueDebugFormat, ResolvedVc, TryJoinIterExt, Vc, debug::ValueDebugFormat,
}; };
use turbopack_core::{ use turbopack_core::{
module_graph::{GraphEntries, ModuleGraph}, module_graph::{GraphEntries, ModuleGraph},
output::OutputAssets, output::OutputAssets,
}; };
use crate::{operation::OptionEndpoint, paths::AssetPath, project::Project}; use crate::{
aggregate_hmr::{ServerHmrChunkLists, ServerHmrEntryKey},
operation::OptionEndpoint,
paths::AssetPath,
project::Project,
};
#[derive(PartialEq, Eq, ValueDebugFormat, Clone, Debug, NonLocalValue, Encode, Decode)] #[derive(PartialEq, Eq, ValueDebugFormat, Clone, Debug, NonLocalValue, Encode, Decode)]
pub struct AppPageRoute { pub struct AppPageRoute {
...@@ -211,10 +216,32 @@ pub struct EndpointGroups(Vec<(EndpointGroupKey, EndpointGroup)>); ...@@ -211,10 +216,32 @@ pub struct EndpointGroups(Vec<(EndpointGroupKey, EndpointGroup)>);
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct Endpoints(Vec<ResolvedVc<Box<dyn Endpoint>>>); pub struct Endpoints(Vec<ResolvedVc<Box<dyn Endpoint>>>);
#[turbo_tasks::value(serialization = "skip")]
pub struct EndpointWriteResult {
pub output_paths: ReadRef<EndpointOutputPaths>,
registration: Option<ServerHmrRegistration>,
}
#[derive(NonLocalValue, PartialEq, Eq, ValueDebugFormat)]
struct ServerHmrRegistration {
project: ReadRef<Project>,
output: OperationVc<EndpointOutput>,
}
impl EndpointWriteResult {
pub fn register_server_hmr_entry(&self, entry_key: ServerHmrEntryKey) {
if let Some(registration) = &self.registration {
registration
.project
.register_server_hmr_entry(entry_key, registration.output);
}
}
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn endpoint_write_to_disk( pub async fn endpoint_write_to_disk(
endpoint: ResolvedVc<Box<dyn Endpoint>>, endpoint: ResolvedVc<Box<dyn Endpoint>>,
) -> Result<Vc<EndpointOutputPaths>> { ) -> Result<Vc<EndpointWriteResult>> {
let output_op = output_assets_operation(endpoint); let output_op = output_assets_operation(endpoint);
let EndpointOutput { let EndpointOutput {
project, project,
...@@ -227,7 +254,14 @@ pub async fn endpoint_write_to_disk( ...@@ -227,7 +254,14 @@ pub async fn endpoint_write_to_disk(
.as_side_effect() .as_side_effect()
.await?; .await?;
Ok(*output_paths) Ok(EndpointWriteResult {
output_paths: output_paths.await?,
registration: Some(ServerHmrRegistration {
project: project.await?,
output: output_op,
}),
}
.cell())
} }
#[turbo_tasks::function(operation)] #[turbo_tasks::function(operation)]
...@@ -245,11 +279,15 @@ async fn endpoint_output_assets_operation( ...@@ -245,11 +279,15 @@ async fn endpoint_output_assets_operation(
#[turbo_tasks::function(operation, root)] #[turbo_tasks::function(operation, root)]
pub async fn endpoint_write_to_disk_operation( pub async fn endpoint_write_to_disk_operation(
endpoint: OperationVc<OptionEndpoint>, endpoint: OperationVc<OptionEndpoint>,
) -> Result<Vc<EndpointOutputPaths>> { ) -> Result<Vc<EndpointWriteResult>> {
Ok(if let Some(endpoint) = *endpoint.connect().await? { Ok(if let Some(endpoint) = *endpoint.connect().await? {
endpoint_write_to_disk(*endpoint) endpoint_write_to_disk(*endpoint)
} else { } else {
EndpointOutputPaths::NotFound.cell() EndpointWriteResult {
output_paths: ReadRef::new_owned(EndpointOutputPaths::NotFound),
registration: None,
}
.cell()
}) })
} }
...@@ -281,6 +319,7 @@ pub struct EndpointOutput { ...@@ -281,6 +319,7 @@ pub struct EndpointOutput {
pub output_assets: ResolvedVc<OutputAssets>, pub output_assets: ResolvedVc<OutputAssets>,
pub output_paths: ResolvedVc<EndpointOutputPaths>, pub output_paths: ResolvedVc<EndpointOutputPaths>,
pub project: ResolvedVc<Project>, pub project: ResolvedVc<Project>,
pub server_hmr_chunks: Option<ResolvedVc<ServerHmrChunkLists>>,
} }
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
...@@ -289,7 +328,6 @@ pub enum EndpointOutputPaths { ...@@ -289,7 +328,6 @@ pub enum EndpointOutputPaths {
NodeJs { NodeJs {
/// Relative to the root_path /// Relative to the root_path
server_entry_path: RcStr, server_entry_path: RcStr,
server_hmr_entry_paths: Vec<RcStr>,
server_paths: Vec<AssetPath>, server_paths: Vec<AssetPath>,
client_paths: Vec<RcStr>, client_paths: Vec<RcStr>,
}, },
......
...@@ -5,19 +5,15 @@ use rustc_hash::{FxHashMap, FxHashSet}; ...@@ -5,19 +5,15 @@ use rustc_hash::{FxHashMap, FxHashSet};
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ use turbo_tasks::{
FxIndexSet, GcRoot, NonLocalValue, OperationValue, OperationVc, ResolvedVc, State, FxIndexSet, GcRoot, NonLocalValue, OperationValue, OperationVc, ResolvedVc, State,
TryFlatJoinIterExt, TryJoinIterExt, Vc, debug::ValueDebugFormat, turbo_tasks, turbobail, TryJoinIterExt, Vc, debug::ValueDebugFormat, turbo_tasks, turbobail,
}; };
use turbo_tasks_fs::{FileContent, FileSystemPath}; use turbo_tasks_fs::{FileContent, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
asset::{Asset, AssetContent}, asset::Asset,
output::{ExpandedOutputAssets, OptionOutputAsset, OutputAsset}, output::{ExpandedOutputAssets, OptionOutputAsset, OutputAsset},
source_map::GenerateSourceMap, source_map::GenerateSourceMap,
version::OptionVersionedContent, version::OptionVersionedContent,
}; };
use turbopack_nodejs::ecmascript::node::entry::chunk_list_content::EcmascriptBuildNodeChunkListContent;
use crate::aggregate_hmr::{ServerHmrChunkList, ServerHmrChunkLists};
#[derive(Clone, PartialEq, Eq, ValueDebugFormat, Debug, NonLocalValue, Encode, Decode)] #[derive(Clone, PartialEq, Eq, ValueDebugFormat, Debug, NonLocalValue, Encode, Decode)]
struct MapEntry { struct MapEntry {
assets_operation: OperationVc<ExpandedOutputAssets>, assets_operation: OperationVc<ExpandedOutputAssets>,
...@@ -97,68 +93,6 @@ impl VersionedContentMap { ...@@ -97,68 +93,6 @@ impl VersionedContentMap {
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl VersionedContentMap { impl VersionedContentMap {
/// Lists the aggregate-HMR *entry* chunks under `root` with their
/// [`VersionedContent`], sorted by path. Only Node.js chunk-list content is
/// returned. Callers scope which
/// entries are included by narrowing `root` (e.g. the aggregate server-HMR
/// subscription passes `server/app` to include App Router entries only).
///
/// `map_path_to_op` is an `FxHashMap`, whose iteration order depends on
/// bucket layout rather than insertion order, so the same set of paths can
/// come out in a different order across calls. Since this map contains
/// entries that span server and client contexts, changes for one context
/// can shift the internals of the map, making iteration order different
/// for the same set of paths.
#[turbo_tasks::function(session_dependent)]
pub async fn server_hmr_chunks_in_path(
self: Vc<Self>,
root: FileSystemPath,
) -> Result<Vc<ServerHmrChunkLists>> {
let this = self.await?;
// `State::get` returns a lock guard, which can't be held across the
// awaits below, so snapshot the keys and release it.
let paths: Vec<FileSystemPath> = {
let map = &this.map_path_to_op.get().0;
map.keys().cloned().collect()
};
let mut chunks = paths
.into_iter()
.filter_map(|path| {
let rel = root.get_path_to(&path)?;
Some((RcStr::from(rel), path))
})
.map(async |(name, path)| {
// Skip Redirect assets: they're symlinks with no file content,
// so versioning them would bail with "not a file".
let Some(asset) = *self.get_asset(path).await? else {
return Ok::<_, anyhow::Error>(None);
};
if !matches!(*asset.content().await?, AssetContent::File(_)) {
return Ok(None);
}
let content = asset.versioned_content().to_resolved().await?;
// *Important*: only chunk lists are subscribed to. Individual chunks are already
// covered by the chunk list that owns them, so including them here
// would produce duplicate updates for the same change.
let Some(versioned_content) =
ResolvedVc::try_downcast_type::<EcmascriptBuildNodeChunkListContent>(content)
else {
return Ok(None);
};
Ok(Some(ServerHmrChunkList {
relative_path: name,
versioned_content,
}))
})
.try_flat_join()
.await?;
chunks.sort_by(|a, b| a.relative_path.cmp(&b.relative_path));
Ok(Vc::cell(chunks))
}
/// Inserts output assets into the map and returns a completion that when /// Inserts output assets into the map and returns a completion that when
/// awaited will emit the assets that were inserted. /// awaited will emit the assets that were inserted.
#[turbo_tasks::function(session_dependent)] #[turbo_tasks::function(session_dependent)]
......
...@@ -253,9 +253,13 @@ async fn endpoint_write_to_disk_with_apply( ...@@ -253,9 +253,13 @@ async fn endpoint_write_to_disk_with_apply(
endpoint: ResolvedVc<Box<dyn Endpoint>>, endpoint: ResolvedVc<Box<dyn Endpoint>>,
) -> Result<ReadRef<EndpointOutputPaths>> { ) -> Result<ReadRef<EndpointOutputPaths>> {
#[turbo_tasks::function(operation, root)] #[turbo_tasks::function(operation, root)]
fn inner_operation(endpoint: ResolvedVc<Box<dyn Endpoint>>) -> Vc<EndpointOutputPaths> { async fn inner_operation(
endpoint: ResolvedVc<Box<dyn Endpoint>>,
) -> Result<Vc<EndpointOutputPaths>> {
// we must wrap this in an operation so we can get the Effects collectibles // we must wrap this in an operation so we can get the Effects collectibles
endpoint_write_to_disk(*endpoint) Ok((*endpoint_write_to_disk(*endpoint).await?.output_paths)
.clone()
.cell())
} }
#[turbo_tasks::value(serialization = "skip")] #[turbo_tasks::value(serialization = "skip")]
......
...@@ -11,7 +11,7 @@ use next_api::{ ...@@ -11,7 +11,7 @@ use next_api::{
operation::OptionEndpoint, operation::OptionEndpoint,
paths::AssetPath, paths::AssetPath,
route::{ route::{
Endpoint, EndpointOutputPaths, endpoint_client_changed_operation, Endpoint, EndpointOutputPaths, EndpointWriteResult, endpoint_client_changed_operation,
endpoint_server_changed_operation, endpoint_write_to_disk_operation, endpoint_server_changed_operation, endpoint_write_to_disk_operation,
}, },
}; };
...@@ -52,7 +52,6 @@ impl From<AssetPath> for NapiAssetPath { ...@@ -52,7 +52,6 @@ impl From<AssetPath> for NapiAssetPath {
pub struct NapiWrittenEndpoint { pub struct NapiWrittenEndpoint {
pub r#type: String, pub r#type: String,
pub entry_path: Option<String>, pub entry_path: Option<String>,
pub server_hmr_entry_paths: Vec<String>,
pub client_paths: Vec<String>, pub client_paths: Vec<String>,
pub server_paths: Vec<NapiAssetPath>, pub server_paths: Vec<NapiAssetPath>,
pub config: NapiEndpointConfig, pub config: NapiEndpointConfig,
...@@ -63,16 +62,11 @@ impl From<Option<EndpointOutputPaths>> for NapiWrittenEndpoint { ...@@ -63,16 +62,11 @@ impl From<Option<EndpointOutputPaths>> for NapiWrittenEndpoint {
match written_endpoint { match written_endpoint {
Some(EndpointOutputPaths::NodeJs { Some(EndpointOutputPaths::NodeJs {
server_entry_path, server_entry_path,
server_hmr_entry_paths,
server_paths, server_paths,
client_paths, client_paths,
}) => Self { }) => Self {
r#type: "nodejs".to_string(), r#type: "nodejs".to_string(),
entry_path: Some(server_entry_path.into_owned()), entry_path: Some(server_entry_path.into_owned()),
server_hmr_entry_paths: server_hmr_entry_paths
.into_iter()
.map(String::from)
.collect(),
client_paths: client_paths.into_iter().map(From::from).collect(), client_paths: client_paths.into_iter().map(From::from).collect(),
server_paths: server_paths.into_iter().map(From::from).collect(), server_paths: server_paths.into_iter().map(From::from).collect(),
..Default::default() ..Default::default()
...@@ -133,7 +127,7 @@ async fn issue_filter_from_endpoint( ...@@ -133,7 +127,7 @@ async fn issue_filter_from_endpoint(
#[turbo_tasks::value(serialization = "skip")] #[turbo_tasks::value(serialization = "skip")]
struct WrittenEndpointWithIssues { struct WrittenEndpointWithIssues {
written: Option<ReadRef<EndpointOutputPaths>>, written: Option<ReadRef<EndpointWriteResult>>,
issues: Arc<Vec<ReadRef<PlainIssue>>>, issues: Arc<Vec<ReadRef<PlainIssue>>>,
effects: Arc<Effects>, effects: Arc<Effects>,
} }
...@@ -158,6 +152,7 @@ async fn get_written_endpoint_with_issues_operation( ...@@ -158,6 +152,7 @@ async fn get_written_endpoint_with_issues_operation(
#[napi] #[napi]
pub async fn endpoint_write_to_disk( pub async fn endpoint_write_to_disk(
#[napi(ts_arg_type = "{ __napiType: \"Endpoint\" }")] endpoint: &External<ExternalEndpoint>, #[napi(ts_arg_type = "{ __napiType: \"Endpoint\" }")] endpoint: &External<ExternalEndpoint>,
entry_key: Option<RcStr>,
) -> napi::Result<TurbopackResult<NapiWrittenEndpoint>> { ) -> napi::Result<TurbopackResult<NapiWrittenEndpoint>> {
let ctx = endpoint.turbopack_ctx(); let ctx = endpoint.turbopack_ctx();
let endpoint_op = ****endpoint; let endpoint_op = ****endpoint;
...@@ -174,8 +169,17 @@ pub async fn endpoint_write_to_disk( ...@@ -174,8 +169,17 @@ pub async fn endpoint_write_to_disk(
let WrittenEndpointWithIssues { let WrittenEndpointWithIssues {
written, issues, .. written, issues, ..
} = &*read; } = &*read;
let written = written.as_ref().map(|written| {
if let Some(entry_key) = entry_key {
written.register_server_hmr_entry(
next_api::aggregate_hmr::ServerHmrEntryKey::new(entry_key),
);
}
written.output_paths.clone()
});
let issues = issues.clone();
Ok((written.clone(), issues.clone())) Ok((written, issues))
}) })
.or_else(|e| ctx.throw_turbopack_internal_result(&e.into())) .or_else(|e| ctx.throw_turbopack_internal_result(&e.into()))
.await?; .await?;
......
...@@ -1915,7 +1915,9 @@ async fn hmr_update_with_issues_operation( ...@@ -1915,7 +1915,9 @@ async fn hmr_update_with_issues_operation(
.cell()) .cell())
} }
#[turbo_tasks::value(serialization = "skip")] // These snapshots contain ReadRefs: keep them alive for the duration of a pull instead of
// evicting their cells while the JS caller still holds a version.
#[turbo_tasks::value(serialization = "skip", evict = "never")]
struct ServerHmrSnapshotWithEffects { struct ServerHmrSnapshotWithEffects {
chunk_lists: ReadRef<ServerHmrChunkLists>, chunk_lists: ReadRef<ServerHmrChunkLists>,
version: ReadRef<ServerHmrChunkListVersion>, version: ReadRef<ServerHmrChunkListVersion>,
...@@ -1923,7 +1925,8 @@ struct ServerHmrSnapshotWithEffects { ...@@ -1923,7 +1925,8 @@ struct ServerHmrSnapshotWithEffects {
effects: Arc<Effects>, effects: Arc<Effects>,
} }
#[turbo_tasks::value(serialization = "skip")] // The ReadRefs in this snapshot must remain valid until the pull has finished.
#[turbo_tasks::value(serialization = "skip", evict = "never")]
struct ServerHmrSnapshot { struct ServerHmrSnapshot {
chunk_lists: ReadRef<ServerHmrChunkLists>, chunk_lists: ReadRef<ServerHmrChunkLists>,
version: ReadRef<ServerHmrChunkListVersion>, version: ReadRef<ServerHmrChunkListVersion>,
...@@ -1932,9 +1935,9 @@ struct ServerHmrSnapshot { ...@@ -1932,9 +1935,9 @@ struct ServerHmrSnapshot {
#[turbo_tasks::function(operation, root)] #[turbo_tasks::function(operation, root)]
async fn project_server_hmr_snapshot_operation( async fn project_server_hmr_snapshot_operation(
project: ResolvedVc<Project>, project: ResolvedVc<Project>,
entry_paths: Vec<RcStr>, entry_key: next_api::aggregate_hmr::ServerHmrEntryKey,
) -> Result<Vc<ServerHmrSnapshot>> { ) -> Result<Vc<ServerHmrSnapshot>> {
let chunk_lists = project.server_hmr_chunks_for_entries(entry_paths).await?; let chunk_lists = project.await?.server_hmr_chunk_lists(&entry_key).await?;
let version = ServerHmrChunkListVersion::from_chunk_lists(chunk_lists.as_slice()) let version = ServerHmrChunkListVersion::from_chunk_lists(chunk_lists.as_slice())
.await? .await?
.cell() .cell()
...@@ -1951,10 +1954,10 @@ async fn project_server_hmr_snapshot_operation( ...@@ -1951,10 +1954,10 @@ async fn project_server_hmr_snapshot_operation(
#[turbo_tasks::function(operation, root)] #[turbo_tasks::function(operation, root)]
async fn server_hmr_snapshot_with_effects_operation( async fn server_hmr_snapshot_with_effects_operation(
project: ResolvedVc<Project>, project: ResolvedVc<Project>,
entry_paths: Vec<RcStr>, entry_key: next_api::aggregate_hmr::ServerHmrEntryKey,
) -> Result<Vc<ServerHmrSnapshotWithEffects>> { ) -> Result<Vc<ServerHmrSnapshotWithEffects>> {
tracing::info!("server hmr snapshot"); tracing::info!("server hmr snapshot");
let snapshot_op = project_server_hmr_snapshot_operation(project, entry_paths); let snapshot_op = project_server_hmr_snapshot_operation(project, entry_key);
// Build-graph failures must reach the JS recovery path. // Build-graph failures must reach the JS recovery path.
let snapshot = snapshot_op let snapshot = snapshot_op
.read_strongly_consistent() .read_strongly_consistent()
...@@ -2007,8 +2010,8 @@ impl NapiServerHmrUpdate { ...@@ -2007,8 +2010,8 @@ impl NapiServerHmrUpdate {
#[napi] #[napi]
pub async fn project_get_server_hmr_update( pub async fn project_get_server_hmr_update(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>, #[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>,
entry_key: RcStr,
from: Option<&External<ServerHmrVersion>>, from: Option<&External<ServerHmrVersion>>,
entry_paths: Vec<RcStr>,
) -> napi::Result<TurbopackResult<NapiServerHmrUpdate>> { ) -> napi::Result<TurbopackResult<NapiServerHmrUpdate>> {
let container = project.container; let container = project.container;
let turbo_tasks = project.turbopack_ctx.turbo_tasks(); let turbo_tasks = project.turbopack_ctx.turbo_tasks();
...@@ -2021,7 +2024,10 @@ pub async fn project_get_server_hmr_update( ...@@ -2021,7 +2024,10 @@ pub async fn project_get_server_hmr_update(
let project = container.project().to_resolved().await?; let project = container.project().to_resolved().await?;
// HACK(bgw): Remove this mark call // HACK(bgw): Remove this mark call
mark_top_level_task(); mark_top_level_task();
let snapshot_op = server_hmr_snapshot_with_effects_operation(project, entry_paths); let snapshot_op = server_hmr_snapshot_with_effects_operation(
project,
next_api::aggregate_hmr::ServerHmrEntryKey::new(entry_key),
);
let read = let read =
read_strongly_consistent_and_apply_effects(snapshot_op, |v| &v.effects).await?; read_strongly_consistent_and_apply_effects(snapshot_op, |v| &v.effects).await?;
Ok((project, read)) Ok((project, read))
......
...@@ -88,9 +88,10 @@ export declare function endpointServerChangedSubscribe( ...@@ -88,9 +88,10 @@ export declare function endpointServerChangedSubscribe(
func: (err: Error, value: TurbopackResult<undefined>) => void func: (err: Error, value: TurbopackResult<undefined>) => void
): { __napiType: 'RootTask' } ): { __napiType: 'RootTask' }
export declare function endpointWriteToDisk(endpoint: { export declare function endpointWriteToDisk(
__napiType: 'Endpoint' endpoint: { __napiType: 'Endpoint' },
}): Promise<TurbopackResult<NapiWrittenEndpoint>> entryKey?: RcStr | undefined | null
): Promise<TurbopackResult<NapiWrittenEndpoint>>
export declare function expandNextJsTemplate( export declare function expandNextJsTemplate(
content: Buffer, content: Buffer,
...@@ -554,7 +555,6 @@ export interface NapiWatchOptions { ...@@ -554,7 +555,6 @@ export interface NapiWatchOptions {
export interface NapiWrittenEndpoint { export interface NapiWrittenEndpoint {
type: string type: string
entryPath?: string entryPath?: string
serverHmrEntryPaths: Array<string>
clientPaths: Array<string> clientPaths: Array<string>
serverPaths: Array<NapiAssetPath> serverPaths: Array<NapiAssetPath>
config: NapiEndpointConfig config: NapiEndpointConfig
...@@ -638,8 +638,8 @@ export declare function projectGetAllCompilationIssues(project: { ...@@ -638,8 +638,8 @@ export declare function projectGetAllCompilationIssues(project: {
export declare function projectGetServerHmrUpdate( export declare function projectGetServerHmrUpdate(
project: { __napiType: 'Project' }, project: { __napiType: 'Project' },
from: ExternalObject<ServerHmrVersion> | undefined | null, entryKey: RcStr,
entryPaths: Array<RcStr> from?: ExternalObject<ServerHmrVersion> | undefined | null
): Promise<TurbopackResult<NapiServerHmrUpdate>> ): Promise<TurbopackResult<NapiServerHmrUpdate>>
export declare function projectGetSourceForAsset( export declare function projectGetSourceForAsset(
......
...@@ -13,6 +13,7 @@ import type { ...@@ -13,6 +13,7 @@ import type {
TurbopackRuleConfigItem, TurbopackRuleConfigItem,
} from '../../server/config-shared' } from '../../server/config-shared'
import { type DefineEnvOptions, getDefineEnv } from '../define-env' import { type DefineEnvOptions, getDefineEnv } from '../define-env'
import type { EntryKey } from '../../shared/lib/turbopack/entry-key'
import type { import type {
NapiPartialProjectOptions, NapiPartialProjectOptions,
NapiProjectOptions, NapiProjectOptions,
...@@ -771,14 +772,14 @@ function bindingToApi( ...@@ -771,14 +772,14 @@ function bindingToApi(
} }
async getServerHmrUpdate( async getServerHmrUpdate(
from: ServerHmrVersion | undefined, entryKey: EntryKey,
entryPaths: string[] from: ServerHmrVersion | undefined
): Promise<TurbopackResult<ServerHmrUpdate>> { ): Promise<TurbopackResult<ServerHmrUpdate>> {
// napi cannot express the field correlation. // napi cannot express the field correlation.
return binding.projectGetServerHmrUpdate( return binding.projectGetServerHmrUpdate(
this._nativeProject, this._nativeProject,
from, entryKey,
entryPaths from
) as Promise<TurbopackResult<ServerHmrUpdate>> ) as Promise<TurbopackResult<ServerHmrUpdate>>
} }
...@@ -865,9 +866,12 @@ function bindingToApi( ...@@ -865,9 +866,12 @@ function bindingToApi(
this._nativeEndpoint = nativeEndpoint this._nativeEndpoint = nativeEndpoint
} }
async writeToDisk(): Promise<TurbopackResult<WrittenEndpoint>> { async writeToDisk(
entryKey?: EntryKey
): Promise<TurbopackResult<WrittenEndpoint>> {
return (await binding.endpointWriteToDisk( return (await binding.endpointWriteToDisk(
this._nativeEndpoint this._nativeEndpoint,
entryKey
)) as TurbopackResult<WrittenEndpoint> )) as TurbopackResult<WrittenEndpoint>
} }
......
import type { NextConfigComplete } from '../../server/config-shared' import type { NextConfigComplete } from '../../server/config-shared'
import type { EntryKey } from '../../shared/lib/turbopack/entry-key'
import type { __ApiPreviewProps } from '../../server/api-utils' import type { __ApiPreviewProps } from '../../server/api-utils'
import type { import type {
ExternalObject, ExternalObject,
...@@ -355,8 +356,8 @@ export interface Project { ...@@ -355,8 +356,8 @@ export interface Project {
> >
getServerHmrUpdate( getServerHmrUpdate(
from: ServerHmrVersion | undefined, entryKey: EntryKey,
entryPaths: string[] from: ServerHmrVersion | undefined
): Promise<TurbopackResult<ServerHmrUpdate>> ): Promise<TurbopackResult<ServerHmrUpdate>>
clientHmrEvents( clientHmrEvents(
...@@ -428,7 +429,7 @@ export type Route = ...@@ -428,7 +429,7 @@ export type Route =
export interface Endpoint { export interface Endpoint {
/** Write files for the endpoint to disk. */ /** Write files for the endpoint to disk. */
writeToDisk(): Promise<TurbopackResult<WrittenEndpoint>> writeToDisk(entryKey?: EntryKey): Promise<TurbopackResult<WrittenEndpoint>>
/** /**
* Listen to client-side changes to the endpoint. * Listen to client-side changes to the endpoint.
...@@ -473,8 +474,6 @@ export type WrittenEndpoint = ...@@ -473,8 +474,6 @@ export type WrittenEndpoint =
type: 'nodejs' type: 'nodejs'
/** The entry path for the endpoint. */ /** The entry path for the endpoint. */
entryPath: string entryPath: string
/** Server HMR entry chunk lists owned by this endpoint. */
serverHmrEntryPaths: string[]
/** All client paths that have been written for the endpoint. */ /** All client paths that have been written for the endpoint. */
clientPaths: string[] clientPaths: string[]
/** All server paths that have been written for the endpoint. */ /** All server paths that have been written for the endpoint. */
...@@ -483,7 +482,6 @@ export type WrittenEndpoint = ...@@ -483,7 +482,6 @@ export type WrittenEndpoint =
} }
| { | {
type: 'edge' type: 'edge'
serverHmrEntryPaths: []
/** All client paths that have been written for the endpoint. */ /** All client paths that have been written for the endpoint. */
clientPaths: string[] clientPaths: string[]
/** All server paths that have been written for the endpoint. */ /** All server paths that have been written for the endpoint. */
...@@ -492,7 +490,6 @@ export type WrittenEndpoint = ...@@ -492,7 +490,6 @@ export type WrittenEndpoint =
} }
| { | {
type: 'none' type: 'none'
serverHmrEntryPaths: []
clientPaths: [] clientPaths: []
serverPaths: [] serverPaths: []
config: EndpointConfig config: EndpointConfig
......
...@@ -253,9 +253,7 @@ function setupServerHmr( ...@@ -253,9 +253,7 @@ function setupServerHmr(
} }
) { ) {
let pending = Promise.resolve() let pending = Promise.resolve()
// Each pull snapshots only the requested endpoint's entries. Keep independent const versions = new Map<EntryKey, ServerHmrVersion>()
// baselines so building one route does not discard another route's version.
const versions = new Map<string, ServerHmrVersion>()
let needsReEvaluation = false let needsReEvaluation = false
async function recover() { async function recover() {
...@@ -268,7 +266,7 @@ function setupServerHmr( ...@@ -268,7 +266,7 @@ function setupServerHmr(
} }
} }
function apply(entryPaths: string[]): Promise<void> { function apply(entryKey: EntryKey): Promise<void> {
const applyPromise = pending.then(async () => { const applyPromise = pending.then(async () => {
if (needsReEvaluation) { if (needsReEvaluation) {
await recover() await recover()
...@@ -276,16 +274,14 @@ function setupServerHmr( ...@@ -276,16 +274,14 @@ function setupServerHmr(
} }
try { try {
const versionKey = [...entryPaths].sort().join('\0') // `issues` is intentionally dropped: the endpoint write for this route
// `issues` is intentionally dropped: this pull scans project-wide chunk // already reported them.
// lists, so its issues may belong to an unrelated or removed route, and
// endpoint writes already report route-scoped issues.
const { value: update } = await project.getServerHmrUpdate( const { value: update } = await project.getServerHmrUpdate(
versions.get(versionKey), entryKey,
entryPaths versions.get(entryKey)
) )
if (update.version) { if (update.version) {
versions.set(versionKey, update.version) versions.set(entryKey, update.version)
} }
switch (update.kind) { switch (update.kind) {
case 'none': case 'none':
...@@ -2136,8 +2132,7 @@ export async function createHotReloaderTurbopack( ...@@ -2136,8 +2132,7 @@ export async function createHotReloaderTurbopack(
// Set by `handleWrittenEndpoint` below, so the pull is gated on the // Set by `handleWrittenEndpoint` below, so the pull is gated on the
// same predicate as the require-cache handling rather than a second, // same predicate as the require-cache handling rather than a second,
// coarser reading of `route.type`. // coarser reading of `route.type`.
let shouldPullServerHmr = false let serverHmrEntryKey: EntryKey | undefined
let serverHmrEntryPaths: string[] = []
try { try {
await handleRouteType({ await handleRouteType({
dev, dev,
...@@ -2166,12 +2161,8 @@ export async function createHotReloaderTurbopack( ...@@ -2166,12 +2161,8 @@ export async function createHotReloaderTurbopack(
id, id,
result.value.serverPaths.map(({ path }) => path) result.value.serverPaths.map(({ path }) => path)
) )
shouldPullServerHmr ||= participatesInServerHmr( if (participatesInServerHmr(id, result.value)) {
id, serverHmrEntryKey = id
result.value
)
if (result.value.serverHmrEntryPaths.length > 0) {
serverHmrEntryPaths = result.value.serverHmrEntryPaths
} }
return clearRequireCache(id, result.value, { return clearRequireCache(id, result.value, {
force: forceDeleteCache, force: forceDeleteCache,
...@@ -2182,8 +2173,8 @@ export async function createHotReloaderTurbopack( ...@@ -2182,8 +2173,8 @@ export async function createHotReloaderTurbopack(
// The only server HMR pull, driven by the request being built — which // The only server HMR pull, driven by the request being built — which
// is what makes evaluating a changed module lazy. // is what makes evaluating a changed module lazy.
if (shouldPullServerHmr && serverHmrEntryPaths.length > 0) { if (serverHmrEntryKey) {
await serverHmr?.apply(serverHmrEntryPaths) await serverHmr?.apply(serverHmrEntryKey)
} }
} finally { } finally {
finishBuilding() finishBuilding()
......
...@@ -347,7 +347,9 @@ export async function handleRouteType({ ...@@ -347,7 +347,9 @@ export async function handleRouteType({
case 'app-page': { case 'app-page': {
const key = getEntryKey('app', 'server', page) const key = getEntryKey('app', 'server', page)
const writtenEndpoint = await route.htmlEndpoint.writeToDisk() const writtenEndpoint = await route.htmlEndpoint.writeToDisk(
dev ? key : undefined
)
hooks?.handleWrittenEndpoint(key, writtenEndpoint, false) hooks?.handleWrittenEndpoint(key, writtenEndpoint, false)
if (dev) { if (dev) {
...@@ -403,7 +405,9 @@ export async function handleRouteType({ ...@@ -403,7 +405,9 @@ export async function handleRouteType({
case 'app-route': { case 'app-route': {
const key = getEntryKey('app', 'server', page) const key = getEntryKey('app', 'server', page)
const writtenEndpoint = await route.endpoint.writeToDisk() const writtenEndpoint = await route.endpoint.writeToDisk(
dev ? key : undefined
)
hooks?.handleWrittenEndpoint(key, writtenEndpoint, false) hooks?.handleWrittenEndpoint(key, writtenEndpoint, false)
if (dev) { if (dev) {
......
...@@ -91,7 +91,7 @@ describe('server-hmr', () => { ...@@ -91,7 +91,7 @@ describe('server-hmr', () => {
expect(new Set(evaluatedPages)).toEqual(new Set([2])) expect(new Set(evaluatedPages)).toEqual(new Set([2]))
const diffedPages = Array.from( const diffedPages = Array.from(
outputAfterPatch.matchAll( outputAfterPatch.matchAll(
/Diffing server HMR entry lazy-pages\/(\d+)\/page/g /Diffing server HMR entry \.next\/dev\/server\/app\/lazy-pages\/(\d+)\/page/g
), ),
(match) => Number(match[1]) (match) => Number(match[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