Unverified Commit a21f4028 authored by Sam Selikoff's avatar Sam Selikoff Committed by GitHub

Merge branch 'canary' into feat/staletime-segment-config

parents bf73658e 50d61f93
...@@ -39,6 +39,17 @@ The main Next.js framework lives in `packages/next/`. This is what gets publishe ...@@ -39,6 +39,17 @@ The main Next.js framework lives in `packages/next/`. This is what gets publishe
- `packages/font/` - `next/font` implementation - `packages/font/` - `next/font` implementation
- `packages/third-parties/` - Third-party script integrations - `packages/third-parties/` - Third-party script integrations
### README files
Before editing or creating files in any subdirectory (e.g., `packages/*`, `crates/*`), read all `README.md` files in the directory path from the repo root up to and including the target file's directory. This helps identify any local patterns, conventions, and documentation.
**Example:** Before editing `turbopack/crates/turbopack-ecmascript-runtime/js/src/nodejs/runtime/runtime-base.ts`, read:
- `turbopack/README.md` (if exists)
- `turbopack/crates/README.md` (if exists)
- `turbopack/crates/turbopack-ecmascript-runtime/README.md` (if exists)
- `turbopack/crates/turbopack-ecmascript-runtime/js/README.md` (if exists - closest to target file)
## Build Commands ## Build Commands
```bash ```bash
......
...@@ -166,6 +166,51 @@ pub struct DebugBuildPaths { ...@@ -166,6 +166,51 @@ pub struct DebugBuildPaths {
pub pages: Vec<RcStr>, pub pages: Vec<RcStr>,
} }
/// Target for HMR operations - client-side (browser) or server-side (Node.js).
#[derive(
Debug,
Default,
Copy,
Clone,
TaskInput,
PartialEq,
Eq,
Hash,
TraceRawVcs,
NonLocalValue,
Encode,
Decode,
)]
pub enum HmrTarget {
#[default]
Client,
Server,
}
impl std::fmt::Display for HmrTarget {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
HmrTarget::Client => write!(f, "client"),
HmrTarget::Server => write!(f, "server"),
}
}
}
impl std::str::FromStr for HmrTarget {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"client" => Ok(HmrTarget::Client),
"server" => Ok(HmrTarget::Server),
_ => Err(format!(
"Invalid HMR target: '{}'. Expected 'client' or 'server'",
s
)),
}
}
}
/// Pre-converted route keys from debug build paths for O(1) lookups. /// Pre-converted route keys from debug build paths for O(1) lookups.
struct DebugBuildPathsRouteKeys { struct DebugBuildPathsRouteKeys {
app: FxHashSet<RcStr>, app: FxHashSet<RcStr>,
...@@ -745,10 +790,10 @@ impl ProjectContainer { ...@@ -745,10 +790,10 @@ impl ProjectContainer {
self.project().entrypoints() self.project().entrypoints()
} }
/// See [Project::hmr_identifiers]. /// See [Project::hmr_chunk_names].
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn hmr_identifiers(self: Vc<Self>) -> Vc<Vec<RcStr>> { pub fn hmr_chunk_names(self: Vc<Self>, target: HmrTarget) -> Vc<Vec<RcStr>> {
self.project().hmr_identifiers() self.project().hmr_chunk_names(target)
} }
/// Gets a source map for a particular `file_path`. If `dev` mode is disabled, this will always /// Gets a source map for a particular `file_path`. If `dev` mode is disabled, this will always
...@@ -2050,19 +2095,39 @@ impl Project { ...@@ -2050,19 +2095,39 @@ impl Project {
.await .await
} }
/// Returns the root path for HMR content based on the target.
/// Client uses client_relative_path, Server uses node_root.
#[turbo_tasks::function]
async fn hmr_root_path(self: Vc<Self>, target: HmrTarget) -> Result<Vc<FileSystemPath>> {
Ok(match target {
HmrTarget::Client => self.client_relative_path(),
HmrTarget::Server => self.node_root(),
})
}
/// Get HMR content by chunk_name for the specified target.
#[turbo_tasks::function] #[turbo_tasks::function]
async fn hmr_content(self: Vc<Self>, identifier: RcStr) -> Result<Vc<OptionVersionedContent>> { async fn hmr_content(
self: Vc<Self>,
chunk_name: RcStr,
target: HmrTarget,
) -> Result<Vc<OptionVersionedContent>> {
if let Some(map) = self.await?.versioned_content_map { if let Some(map) = self.await?.versioned_content_map {
let content = map.get(self.client_relative_path().await?.join(&identifier)?); let content = map.get(self.hmr_root_path(target).await?.join(&chunk_name)?);
Ok(content) Ok(content)
} else { } else {
bail!("must be in dev mode to hmr") bail!("must be in dev mode to hmr")
} }
} }
/// Get HMR version for the specified target.
#[turbo_tasks::function] #[turbo_tasks::function]
async fn hmr_version(self: Vc<Self>, identifier: RcStr) -> Result<Vc<Box<dyn Version>>> { async fn hmr_version(
let content = self.hmr_content(identifier).await?; self: Vc<Self>,
chunk_name: RcStr,
target: HmrTarget,
) -> Result<Vc<Box<dyn Version>>> {
let content = self.hmr_content(chunk_name, target).await?;
if let Some(content) = &*content { if let Some(content) = &*content {
Ok(content.version()) Ok(content.version())
} else { } else {
...@@ -2070,15 +2135,16 @@ impl Project { ...@@ -2070,15 +2135,16 @@ impl Project {
} }
} }
/// Get the version state for a session. Initialized with the first seen /// Get the version state for an HMR session. Initialized with the first seen
/// version in that session. /// version in that session.
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn hmr_version_state( pub async fn hmr_version_state(
self: Vc<Self>, self: Vc<Self>,
identifier: RcStr, chunk_name: RcStr,
target: HmrTarget,
session: TransientInstance<()>, session: TransientInstance<()>,
) -> Result<Vc<VersionState>> { ) -> Result<Vc<VersionState>> {
let version = self.hmr_version(identifier); let version = self.hmr_version(chunk_name, target);
// The session argument is important to avoid caching this function between // The session argument is important to avoid caching this function between
// sessions. // sessions.
...@@ -2099,15 +2165,16 @@ impl Project { ...@@ -2099,15 +2165,16 @@ impl Project {
} }
/// Emits opaque HMR events whenever a change is detected in the chunk group /// Emits opaque HMR events whenever a change is detected in the chunk group
/// internally known as `identifier`. /// internally known as `chunk_name` for the specified target.
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn hmr_update( pub async fn hmr_update(
self: Vc<Self>, self: Vc<Self>,
identifier: RcStr, chunk_name: RcStr,
target: HmrTarget,
from: Vc<VersionState>, from: Vc<VersionState>,
) -> Result<Vc<Update>> { ) -> Result<Vc<Update>> {
let from = from.get(); let from = from.get();
let content = self.hmr_content(identifier).await?; let content = self.hmr_content(chunk_name, target).await?;
if let Some(content) = *content { if let Some(content) = *content {
Ok(content.update(from)) Ok(content.update(from))
} else { } else {
...@@ -2115,12 +2182,13 @@ impl Project { ...@@ -2115,12 +2182,13 @@ impl Project {
} }
} }
/// Gets a list of all HMR identifiers that can be subscribed to. This is /// Gets a list of all HMR chunk names that can be subscribed to for the
/// only needed for testing purposes and isn't used in real apps. /// specified target. This is only needed for testing purposes and isn't
/// used in real apps.
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn hmr_identifiers(self: Vc<Self>) -> Result<Vc<Vec<RcStr>>> { pub async fn hmr_chunk_names(self: Vc<Self>, target: HmrTarget) -> Result<Vc<Vec<RcStr>>> {
if let Some(map) = self.await?.versioned_content_map { if let Some(map) = self.await?.versioned_content_map {
Ok(map.keys_in_path(self.client_relative_path().owned().await?)) Ok(map.keys_in_path(self.hmr_root_path(target).owned().await?))
} else { } else {
bail!("must be in dev mode to hmr") bail!("must be in dev mode to hmr")
} }
......
...@@ -8,7 +8,7 @@ use std::{str::FromStr, time::Instant}; ...@@ -8,7 +8,7 @@ use std::{str::FromStr, time::Instant};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use futures_util::{StreamExt, TryStreamExt}; use futures_util::{StreamExt, TryStreamExt};
use next_api::{ use next_api::{
project::{ProjectContainer, ProjectOptions}, project::{HmrTarget, ProjectContainer, ProjectOptions},
route::{Endpoint, EndpointOutputPaths, Route, endpoint_write_to_disk}, route::{Endpoint, EndpointOutputPaths, Route, endpoint_write_to_disk},
}; };
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
...@@ -257,7 +257,7 @@ async fn hmr( ...@@ -257,7 +257,7 @@ async fn hmr(
tracing::info!("HMR..."); tracing::info!("HMR...");
let session = TransientInstance::new(()); let session = TransientInstance::new(());
let idents = tt let idents = tt
.run(async move { project.hmr_identifiers().await }) .run(async move { project.hmr_chunk_names(HmrTarget::Client).await })
.await?; .await?;
let start = Instant::now(); let start = Instant::now();
for ident in idents { for ident in idents {
...@@ -270,8 +270,10 @@ async fn hmr( ...@@ -270,8 +270,10 @@ async fn hmr(
let session = session.clone(); let session = session.clone();
async move { async move {
let project = project.project(); let project = project.project();
let state = project.hmr_version_state(ident.clone(), session); let state = project.hmr_version_state(ident.clone(), HmrTarget::Client, session);
project.hmr_update(ident.clone(), state).await?; project
.hmr_update(ident.clone(), HmrTarget::Client, state)
.await?;
Ok(Vc::<()>::cell(())) Ok(Vc::<()>::cell(()))
} }
}); });
......
...@@ -18,7 +18,7 @@ use next_api::{ ...@@ -18,7 +18,7 @@ use next_api::{
RouteOperation, RouteOperation,
}, },
project::{ project::{
DebugBuildPaths, DefineEnv, DraftModeOptions, PartialProjectOptions, Project, DebugBuildPaths, DefineEnv, DraftModeOptions, HmrTarget, PartialProjectOptions, Project,
ProjectContainer, ProjectOptions, WatchOptions, ProjectContainer, ProjectOptions, WatchOptions,
}, },
route::Endpoint, route::Endpoint,
...@@ -82,7 +82,7 @@ use crate::{ ...@@ -82,7 +82,7 @@ use crate::{
/// Used by [`benchmark_file_io`]. This is a noisy benchmark, so set the /// Used by [`benchmark_file_io`]. This is a noisy benchmark, so set the
/// threshold high. /// threshold high.
const SLOW_FILESYSTEM_THRESHOLD: Duration = Duration::from_millis(100); const SLOW_FILESYSTEM_THRESHOLD: Duration = Duration::from_millis(200);
static SOURCE_MAP_PREFIX: Lazy<String> = Lazy::new(|| format!("{SOURCE_URL_PROTOCOL}///")); static SOURCE_MAP_PREFIX: Lazy<String> = Lazy::new(|| format!("{SOURCE_URL_PROTOCOL}///"));
static SOURCE_MAP_PREFIX_PROJECT: Lazy<String> = static SOURCE_MAP_PREFIX_PROJECT: Lazy<String> =
Lazy::new(|| format!("{SOURCE_URL_PROTOCOL}///[{PROJECT_FILESYSTEM_NAME}]/")); Lazy::new(|| format!("{SOURCE_URL_PROTOCOL}///[{PROJECT_FILESYSTEM_NAME}]/"));
...@@ -602,8 +602,8 @@ impl CompilationEvent for SlowFilesystemEvent { ...@@ -602,8 +602,8 @@ impl CompilationEvent for SlowFilesystemEvent {
fn message(&self) -> String { fn message(&self) -> String {
format!( format!(
"Slow filesystem detected. The benchmark took {}ms. If {} is a network drive, \ "Slow filesystem detected. The benchmark took {}ms. If {} is a network drive, \
consider moving it to a local folder. If you have an antivirus enabled, consider \ consider moving it to a local folder.\n\
excluding your project directory.", See more: https://nextjs.org/docs/app/guides/local-development",
self.duration_ms, self.directory self.duration_ms, self.directory
) )
} }
...@@ -1205,13 +1205,24 @@ struct HmrUpdateWithIssues { ...@@ -1205,13 +1205,24 @@ struct HmrUpdateWithIssues {
effects: Arc<Effects>, effects: Arc<Effects>,
} }
#[turbo_tasks::function(operation)]
fn project_hmr_update_operation(
project: ResolvedVc<Project>,
chunk_name: RcStr,
target: HmrTarget,
state: ResolvedVc<VersionState>,
) -> Vc<Update> {
project.hmr_update(chunk_name, target, *state)
}
#[turbo_tasks::function(operation)] #[turbo_tasks::function(operation)]
async fn hmr_update_with_issues_operation( async fn hmr_update_with_issues_operation(
project: ResolvedVc<Project>, project: ResolvedVc<Project>,
identifier: RcStr, chunk_name: RcStr,
state: ResolvedVc<VersionState>, state: ResolvedVc<VersionState>,
target: HmrTarget,
) -> Result<Vc<HmrUpdateWithIssues>> { ) -> Result<Vc<HmrUpdateWithIssues>> {
let update_op = project_hmr_update_operation(project, identifier, state); let update_op = project_hmr_update_operation(project, chunk_name, target, state);
let update = update_op.read_strongly_consistent().await?; let update = update_op.read_strongly_consistent().await?;
let issues = get_issues(update_op, NEXT_ISSUE_FILTER).await?; let issues = get_issues(update_op, NEXT_ISSUE_FILTER).await?;
let diagnostics = get_diagnostics(update_op).await?; let diagnostics = get_diagnostics(update_op).await?;
...@@ -1225,42 +1236,42 @@ async fn hmr_update_with_issues_operation( ...@@ -1225,42 +1236,42 @@ async fn hmr_update_with_issues_operation(
.cell()) .cell())
} }
#[turbo_tasks::function(operation)] #[tracing::instrument(level = "info", name = "get HMR events", skip(project, func), fields(target = %target))]
fn project_hmr_update_operation(
project: ResolvedVc<Project>,
identifier: RcStr,
state: ResolvedVc<VersionState>,
) -> Vc<Update> {
project.hmr_update(identifier, *state)
}
#[tracing::instrument(level = "info", name = "get HMR events", skip(project, func))]
#[napi(ts_return_type = "{ __napiType: \"RootTask\" }")] #[napi(ts_return_type = "{ __napiType: \"RootTask\" }")]
pub fn project_hmr_events( pub fn project_hmr_events(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>, #[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
identifier: RcStr, chunk_name: RcStr,
target: String,
func: JsFunction, func: JsFunction,
) -> napi::Result<External<RootTask>> { ) -> napi::Result<External<RootTask>> {
let hmr_target = target
.parse::<HmrTarget>()
.map_err(napi::Error::from_reason)?;
let container = project.container; let container = project.container;
let session = TransientInstance::new(()); let session = TransientInstance::new(());
subscribe( subscribe(
project.turbopack_ctx.clone(), project.turbopack_ctx.clone(),
func, func,
{ {
let outer_identifier = identifier.clone(); let outer_chunk_name = chunk_name.clone();
let session = session.clone(); let session = session.clone();
move || { move || {
let identifier: RcStr = outer_identifier.clone(); let chunk_name: RcStr = outer_chunk_name.clone();
let session = session.clone(); let session = session.clone();
async move { async move {
let project = container.project().to_resolved().await?; let project = container.project().to_resolved().await?;
let state = project let state = project
.hmr_version_state(identifier.clone(), session) .hmr_version_state(chunk_name.clone(), hmr_target, session)
.to_resolved() .to_resolved()
.await?; .await?;
let update_op = let update_op = hmr_update_with_issues_operation(
hmr_update_with_issues_operation(project, identifier.clone(), state); project,
chunk_name.clone(),
state,
hmr_target,
);
let update = update_op.read_strongly_consistent().await?; let update = update_op.read_strongly_consistent().await?;
let HmrUpdateWithIssues { let HmrUpdateWithIssues {
update, update,
...@@ -1295,7 +1306,7 @@ pub fn project_hmr_events( ...@@ -1295,7 +1306,7 @@ pub fn project_hmr_events(
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let identifier = ResourceIdentifier { let identifier = ResourceIdentifier {
path: identifier.clone(), path: chunk_name.clone(),
headers: None, headers: None,
}; };
let update = match update.as_deref() { let update = match update.as_deref() {
...@@ -1320,29 +1331,38 @@ pub fn project_hmr_events( ...@@ -1320,29 +1331,38 @@ pub fn project_hmr_events(
} }
#[napi(object)] #[napi(object)]
struct HmrIdentifiers { struct HmrChunkNames {
pub identifiers: Vec<RcStr>, pub chunk_names: Vec<RcStr>,
} }
#[turbo_tasks::value(serialization = "none")] #[turbo_tasks::value(serialization = "none")]
struct HmrIdentifiersWithIssues { struct HmrChunkNamesWithIssues {
identifiers: ReadRef<Vec<RcStr>>, chunk_names: ReadRef<Vec<RcStr>>,
issues: Arc<Vec<ReadRef<PlainIssue>>>, issues: Arc<Vec<ReadRef<PlainIssue>>>,
diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>, diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>,
effects: Arc<Effects>, effects: Arc<Effects>,
} }
#[turbo_tasks::function(operation)] #[turbo_tasks::function(operation)]
async fn get_hmr_identifiers_with_issues_operation( fn project_hmr_chunk_names_operation(
container: ResolvedVc<ProjectContainer>,
target: HmrTarget,
) -> Vc<Vec<RcStr>> {
container.hmr_chunk_names(target)
}
#[turbo_tasks::function(operation)]
async fn get_hmr_chunk_names_with_issues_operation(
container: ResolvedVc<ProjectContainer>, container: ResolvedVc<ProjectContainer>,
) -> Result<Vc<HmrIdentifiersWithIssues>> { target: HmrTarget,
let hmr_identifiers_op = project_container_hmr_identifiers_operation(container); ) -> Result<Vc<HmrChunkNamesWithIssues>> {
let hmr_identifiers = hmr_identifiers_op.read_strongly_consistent().await?; let hmr_chunk_names_op = project_hmr_chunk_names_operation(container, target);
let issues = get_issues(hmr_identifiers_op, NEXT_ISSUE_FILTER).await?; let hmr_chunk_names = hmr_chunk_names_op.read_strongly_consistent().await?;
let diagnostics = get_diagnostics(hmr_identifiers_op).await?; let issues = get_issues(hmr_chunk_names_op, NEXT_ISSUE_FILTER).await?;
let effects = Arc::new(get_effects(hmr_identifiers_op).await?); let diagnostics = get_diagnostics(hmr_chunk_names_op).await?;
Ok(HmrIdentifiersWithIssues { let effects = Arc::new(get_effects(hmr_chunk_names_op).await?);
identifiers: hmr_identifiers, Ok(HmrChunkNamesWithIssues {
chunk_names: hmr_chunk_names,
issues, issues,
diagnostics, diagnostics,
effects, effects,
...@@ -1350,44 +1370,42 @@ async fn get_hmr_identifiers_with_issues_operation( ...@@ -1350,44 +1370,42 @@ async fn get_hmr_identifiers_with_issues_operation(
.cell()) .cell())
} }
#[turbo_tasks::function(operation)] #[tracing::instrument(level = "info", name = "get HMR chunk names", skip(project, func), fields(target = %target))]
fn project_container_hmr_identifiers_operation(
container: ResolvedVc<ProjectContainer>,
) -> Vc<Vec<RcStr>> {
container.hmr_identifiers()
}
#[tracing::instrument(level = "info", name = "get HMR identifiers", skip_all)]
#[napi(ts_return_type = "{ __napiType: \"RootTask\" }")] #[napi(ts_return_type = "{ __napiType: \"RootTask\" }")]
pub fn project_hmr_identifiers_subscribe( pub fn project_hmr_chunk_names_subscribe(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>, #[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
target: String,
func: JsFunction, func: JsFunction,
) -> napi::Result<External<RootTask>> { ) -> napi::Result<External<RootTask>> {
let hmr_target = target
.parse::<HmrTarget>()
.map_err(napi::Error::from_reason)?;
let container = project.container; let container = project.container;
subscribe( subscribe(
project.turbopack_ctx.clone(), project.turbopack_ctx.clone(),
func, func,
move || async move { move || async move {
let hmr_identifiers_with_issues_op = let hmr_chunk_names_with_issues_op =
get_hmr_identifiers_with_issues_operation(container); get_hmr_chunk_names_with_issues_operation(container, hmr_target);
let HmrIdentifiersWithIssues { let HmrChunkNamesWithIssues {
identifiers, chunk_names,
issues, issues,
diagnostics, diagnostics,
effects, effects,
} = &*hmr_identifiers_with_issues_op } = &*hmr_chunk_names_with_issues_op
.read_strongly_consistent() .read_strongly_consistent()
.await?; .await?;
effects.apply().await?; effects.apply().await?;
Ok((identifiers.clone(), issues.clone(), diagnostics.clone())) Ok((chunk_names.clone(), issues.clone(), diagnostics.clone()))
}, },
move |ctx| { move |ctx| {
let (identifiers, issues, diagnostics) = ctx.value; let (chunk_names, issues, diagnostics) = ctx.value;
Ok(vec![TurbopackResult { Ok(vec![TurbopackResult {
result: HmrIdentifiers { result: HmrChunkNames {
identifiers: ReadRef::into_owned(identifiers), chunk_names: ReadRef::into_owned(chunk_names),
}, },
issues: issues issues: issues
.iter() .iter()
......
...@@ -15,5 +15,5 @@ ...@@ -15,5 +15,5 @@
"registry": "https://registry.npmjs.org/" "registry": "https://registry.npmjs.org/"
} }
}, },
"version": "16.2.0-canary.33" "version": "16.2.0-canary.35"
} }
\ No newline at end of file
{ {
"name": "create-next-app", "name": "create-next-app",
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"keywords": [ "keywords": [
"react", "react",
"next", "next",
......
{ {
"name": "eslint-config-next", "name": "eslint-config-next",
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"description": "ESLint configuration used by Next.js.", "description": "ESLint configuration used by Next.js.",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
"dist" "dist"
], ],
"dependencies": { "dependencies": {
"@next/eslint-plugin-next": "16.2.0-canary.33", "@next/eslint-plugin-next": "16.2.0-canary.35",
"eslint-import-resolver-node": "^0.3.6", "eslint-import-resolver-node": "^0.3.6",
"eslint-import-resolver-typescript": "^3.5.2", "eslint-import-resolver-typescript": "^3.5.2",
"eslint-plugin-import": "^2.32.0", "eslint-plugin-import": "^2.32.0",
......
{ {
"name": "@next/eslint-plugin-internal", "name": "@next/eslint-plugin-internal",
"private": true, "private": true,
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"description": "ESLint plugin for working on Next.js.", "description": "ESLint plugin for working on Next.js.",
"exports": { "exports": {
".": "./src/eslint-plugin-internal.js" ".": "./src/eslint-plugin-internal.js"
......
{ {
"name": "@next/eslint-plugin-next", "name": "@next/eslint-plugin-next",
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"description": "ESLint plugin for Next.js.", "description": "ESLint plugin for Next.js.",
"main": "dist/index.js", "main": "dist/index.js",
"types": "dist/index.d.ts", "types": "dist/index.d.ts",
......
{ {
"name": "@next/font", "name": "@next/font",
"private": true, "private": true,
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"repository": { "repository": {
"url": "vercel/next.js", "url": "vercel/next.js",
"directory": "packages/font" "directory": "packages/font"
......
{ {
"name": "@next/bundle-analyzer", "name": "@next/bundle-analyzer",
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"main": "index.js", "main": "index.js",
"types": "index.d.ts", "types": "index.d.ts",
"license": "MIT", "license": "MIT",
......
{ {
"name": "@next/codemod", "name": "@next/codemod",
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
"type": "git", "type": "git",
......
{ {
"name": "@next/env", "name": "@next/env",
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"keywords": [ "keywords": [
"react", "react",
"next", "next",
......
{ {
"name": "@next/mdx", "name": "@next/mdx",
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"main": "index.js", "main": "index.js",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
......
{ {
"name": "@next/plugin-storybook", "name": "@next/plugin-storybook",
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"repository": { "repository": {
"url": "vercel/next.js", "url": "vercel/next.js",
"directory": "packages/next-plugin-storybook" "directory": "packages/next-plugin-storybook"
......
{ {
"name": "@next/polyfill-module", "name": "@next/polyfill-module",
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"description": "A standard library polyfill for ES Modules supporting browsers (Edge 16+, Firefox 60+, Chrome 61+, Safari 10.1+)", "description": "A standard library polyfill for ES Modules supporting browsers (Edge 16+, Firefox 60+, Chrome 61+, Safari 10.1+)",
"main": "dist/polyfill-module.js", "main": "dist/polyfill-module.js",
"license": "MIT", "license": "MIT",
......
{ {
"name": "@next/polyfill-nomodule", "name": "@next/polyfill-nomodule",
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"description": "A polyfill for non-dead, nomodule browsers.", "description": "A polyfill for non-dead, nomodule browsers.",
"main": "dist/polyfill-nomodule.js", "main": "dist/polyfill-nomodule.js",
"license": "MIT", "license": "MIT",
......
{ {
"name": "@next/routing", "name": "@next/routing",
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"keywords": [ "keywords": [
"react", "react",
"next", "next",
......
{ {
"name": "next-rspack", "name": "next-rspack",
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"repository": { "repository": {
"url": "vercel/next.js", "url": "vercel/next.js",
"directory": "packages/next-rspack" "directory": "packages/next-rspack"
......
{ {
"name": "@next/swc", "name": "@next/swc",
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"private": true, "private": true,
"files": [ "files": [
"native/" "native/"
......
{ {
"name": "next", "name": "next",
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"description": "The React Framework", "description": "The React Framework",
"main": "./dist/server/next.js", "main": "./dist/server/next.js",
"license": "MIT", "license": "MIT",
...@@ -97,7 +97,7 @@ ...@@ -97,7 +97,7 @@
] ]
}, },
"dependencies": { "dependencies": {
"@next/env": "16.2.0-canary.33", "@next/env": "16.2.0-canary.35",
"@swc/helpers": "0.5.15", "@swc/helpers": "0.5.15",
"baseline-browser-mapping": "^2.9.19", "baseline-browser-mapping": "^2.9.19",
"caniuse-lite": "^1.0.30001579", "caniuse-lite": "^1.0.30001579",
...@@ -162,11 +162,11 @@ ...@@ -162,11 +162,11 @@
"@modelcontextprotocol/sdk": "1.18.1", "@modelcontextprotocol/sdk": "1.18.1",
"@mswjs/interceptors": "0.23.0", "@mswjs/interceptors": "0.23.0",
"@napi-rs/triples": "1.2.0", "@napi-rs/triples": "1.2.0",
"@next/font": "16.2.0-canary.33", "@next/font": "16.2.0-canary.35",
"@next/polyfill-module": "16.2.0-canary.33", "@next/polyfill-module": "16.2.0-canary.35",
"@next/polyfill-nomodule": "16.2.0-canary.33", "@next/polyfill-nomodule": "16.2.0-canary.35",
"@next/react-refresh-utils": "16.2.0-canary.33", "@next/react-refresh-utils": "16.2.0-canary.35",
"@next/swc": "16.2.0-canary.33", "@next/swc": "16.2.0-canary.35",
"@opentelemetry/api": "1.6.0", "@opentelemetry/api": "1.6.0",
"@playwright/test": "1.51.1", "@playwright/test": "1.51.1",
"@rspack/core": "1.6.7", "@rspack/core": "1.6.7",
......
...@@ -314,14 +314,16 @@ export declare function projectEntrypointsSubscribe( ...@@ -314,14 +314,16 @@ export declare function projectEntrypointsSubscribe(
): { __napiType: 'RootTask' } ): { __napiType: 'RootTask' }
export declare function projectHmrEvents( export declare function projectHmrEvents(
project: { __napiType: 'Project' }, project: { __napiType: 'Project' },
identifier: RcStr, chunkName: RcStr,
target: string,
func: (...args: any[]) => any func: (...args: any[]) => any
): { __napiType: 'RootTask' } ): { __napiType: 'RootTask' }
export interface HmrIdentifiers { export interface HmrChunkNames {
identifiers: Array<RcStr> chunkNames: Array<RcStr>
} }
export declare function projectHmrIdentifiersSubscribe( export declare function projectHmrChunkNamesSubscribe(
project: { __napiType: 'Project' }, project: { __napiType: 'Project' },
target: string,
func: (...args: any[]) => any func: (...args: any[]) => any
): { __napiType: 'RootTask' } ): { __napiType: 'RootTask' }
export interface NapiUpdateMessage { export interface NapiUpdateMessage {
......
...@@ -27,8 +27,9 @@ import type { ...@@ -27,8 +27,9 @@ import type {
CompilationEvent, CompilationEvent,
DefineEnv, DefineEnv,
Endpoint, Endpoint,
HmrIdentifiers, HmrChunkNames,
Lockfile, Lockfile,
NodeJsHmrUpdate,
PartialProjectOptions, PartialProjectOptions,
Project, Project,
ProjectOptions, ProjectOptions,
...@@ -43,6 +44,11 @@ import type { ...@@ -43,6 +44,11 @@ import type {
} from './types' } from './types'
import { throwTurbopackInternalError } from '../../shared/lib/turbopack/internal-error' import { throwTurbopackInternalError } from '../../shared/lib/turbopack/internal-error'
export enum HmrTarget {
Client = 'client',
Server = 'server',
}
type RawBindings = typeof import('./generated-native') type RawBindings = typeof import('./generated-native')
type RawWasmBindings = typeof import('./generated-wasm') & { type RawWasmBindings = typeof import('./generated-wasm') & {
default?(): Promise<typeof import('./generated-wasm')> default?(): Promise<typeof import('./generated-wasm')>
...@@ -735,17 +741,39 @@ function bindingToApi( ...@@ -735,17 +741,39 @@ function bindingToApi(
})() })()
} }
hmrEvents(identifier: string) { hmrEvents(
return subscribe<TurbopackResult<Update>>(true, async (callback) => chunkName: string,
binding.projectHmrEvents(this._nativeProject, identifier, callback) target: HmrTarget.Client
): AsyncIterableIterator<TurbopackResult<Update>>
hmrEvents(
chunkName: string,
target: HmrTarget.Server
): AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>
hmrEvents(chunkName: string, target: HmrTarget.Client | HmrTarget.Server) {
return subscribe(true, async (callback) =>
binding.projectHmrEvents(
this._nativeProject,
chunkName,
target,
callback
)
) )
} }
hmrIdentifiersSubscribe() { /**
return subscribe<TurbopackResult<HmrIdentifiers>>( * Subscribe to the list of output chunk paths that can receive HMR updates.
* Chunk paths are output file paths like "server/chunks/ssr/..._.js" for server
* or "_next/static/chunks/app/page.js" for client.
*/
hmrChunkNamesSubscribe(target: HmrTarget) {
return subscribe<TurbopackResult<HmrChunkNames>>(
false, false,
async (callback) => async (callback) =>
binding.projectHmrIdentifiersSubscribe(this._nativeProject, callback) binding.projectHmrChunkNamesSubscribe(
this._nativeProject,
target,
callback
)
) )
} }
......
...@@ -195,8 +195,30 @@ interface PartialUpdate extends BaseUpdate { ...@@ -195,8 +195,30 @@ interface PartialUpdate extends BaseUpdate {
export type Update = IssuesUpdate | PartialUpdate export type Update = IssuesUpdate | PartialUpdate
export interface HmrIdentifiers { /**
identifiers: string[] * IMPORTANT: This type is duplicated in:
* turbopack/crates/turbopack-ecmascript-runtime/js/src/nodejs/hmr-types.d.ts
*
* The runtime file cannot import from this ES module without triggering module semantics,
* so we maintain a copy there. Please keep both definitions in sync.
*/
export interface NodeJsPartialHmrUpdate extends BaseUpdate {
type: 'partial'
instruction: {
type: 'EcmascriptMergedUpdate'
entries: Record<
string,
{ code: string; url: string; map?: string | undefined }
>
chunks?: Record<string, { type: 'partial' }>
}
}
export type NodeJsHmrUpdate = IssuesUpdate | NodeJsPartialHmrUpdate
export interface HmrChunkNames {
/** Relative paths to output chunks that can receive HMR updates (e.g., "server/chunks/ssr/..._.js") */
chunkNames: string[]
} }
/** @see https://github.com/vercel/next.js/blob/415cd74b9a220b6f50da64da68c13043e9b02995/crates/next-napi-bindings/src/next_api/project.rs#L824-L833 */ /** @see https://github.com/vercel/next.js/blob/415cd74b9a220b6f50da64da68c13043e9b02995/crates/next-napi-bindings/src/next_api/project.rs#L824-L833 */
...@@ -246,11 +268,18 @@ export interface Project { ...@@ -246,11 +268,18 @@ export interface Project {
TurbopackResult<RawEntrypoints | {}> TurbopackResult<RawEntrypoints | {}>
> >
hmrEvents(identifier: string): AsyncIterableIterator<TurbopackResult<Update>> hmrEvents(
identifier: string,
hmrIdentifiersSubscribe(): AsyncIterableIterator< target: import('./index').HmrTarget.Client
TurbopackResult<HmrIdentifiers> ): AsyncIterableIterator<TurbopackResult<Update>>
> hmrEvents(
identifier: string,
target: import('./index').HmrTarget.Server
): AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>
hmrChunkNamesSubscribe(
target: import('./index').HmrTarget
): AsyncIterableIterator<TurbopackResult<HmrChunkNames>>
getSourceForAsset(filePath: string): Promise<string | null> getSourceForAsset(filePath: string): Promise<string | null>
......
...@@ -92,7 +92,10 @@ import { createServerInsertedHTML } from './server-inserted-html' ...@@ -92,7 +92,10 @@ import { createServerInsertedHTML } from './server-inserted-html'
import { getRequiredScripts } from './required-scripts' import { getRequiredScripts } from './required-scripts'
import { addPathPrefix } from '../../shared/lib/router/utils/add-path-prefix' import { addPathPrefix } from '../../shared/lib/router/utils/add-path-prefix'
import { makeGetServerInsertedHTML } from './make-get-server-inserted-html' import { makeGetServerInsertedHTML } from './make-get-server-inserted-html'
import { walkTreeWithFlightRouterState } from './walk-tree-with-flight-router-state' import {
walkTreeWithFlightRouterState,
createFullTreeFlightDataForNavigation,
} from './walk-tree-with-flight-router-state'
import { createComponentTree, getRootParams } from './create-component-tree' import { createComponentTree, getRootParams } from './create-component-tree'
import { getAssetQueryString } from './get-asset-query-string' import { getAssetQueryString } from './get-asset-query-string'
import { import {
...@@ -533,6 +536,14 @@ async function generateDynamicRSCPayload( ...@@ -533,6 +536,14 @@ async function generateDynamicRSCPayload(
if (!options?.skipPageRendering) { if (!options?.skipPageRendering) {
const preloadCallbacks: PreloadCallbacks = [] const preloadCallbacks: PreloadCallbacks = []
// If we're performing instant validation, we need to render the whole tree,
// without skipping shared layouts.
const needsFullTree =
process.env.NODE_ENV === 'development' &&
ctx.renderOpts.cacheComponents &&
!options?.actionResult && // Only for navigations
(await anySegmentNeedsInstantValidation(loaderTree))
const { Viewport, Metadata, MetadataOutlet } = createMetadataComponents({ const { Viewport, Metadata, MetadataOutlet } = createMetadataComponents({
tree: loaderTree, tree: loaderTree,
parsedQuery: query, parsedQuery: query,
...@@ -543,38 +554,50 @@ async function generateDynamicRSCPayload( ...@@ -543,38 +554,50 @@ async function generateDynamicRSCPayload(
serveStreamingMetadata, serveStreamingMetadata,
}) })
const rscHead = createElement(
Fragment,
{
key: flightDataPathHeadKey,
},
createElement(NonIndex, {
createElement,
pagePath: ctx.pagePath,
statusCode: ctx.res.statusCode,
isPossibleServerAction: ctx.isPossibleServerAction,
}),
createElement(Viewport, {
key: getFlightViewportKey(requestId),
}),
createElement(Metadata, {
key: getFlightMetadataKey(requestId),
})
)
flightData = ( flightData = (
await walkTreeWithFlightRouterState({ needsFullTree
ctx, ? await createFullTreeFlightDataForNavigation({
loaderTreeToFilter: loaderTree, ctx,
parentParams: {}, loaderTree,
flightRouterState, rscHead,
// For flight, render metadata inside leaf page injectedCSS: new Set(),
rscHead: createElement( injectedJS: new Set(),
Fragment, injectedFontPreloadTags: new Set(),
{ preloadCallbacks,
key: flightDataPathHeadKey, MetadataOutlet,
}, })
createElement(NonIndex, { : await walkTreeWithFlightRouterState({
createElement, ctx,
pagePath: ctx.pagePath, loaderTreeToFilter: loaderTree,
statusCode: ctx.res.statusCode, parentParams: {},
isPossibleServerAction: ctx.isPossibleServerAction, flightRouterState,
}), rscHead,
createElement(Viewport, { injectedCSS: new Set(),
key: getFlightViewportKey(requestId), injectedJS: new Set(),
}), injectedFontPreloadTags: new Set(),
createElement(Metadata, { rootLayoutIncluded: false,
key: getFlightMetadataKey(requestId), preloadCallbacks,
MetadataOutlet,
}) })
),
injectedCSS: new Set(),
injectedJS: new Set(),
injectedFontPreloadTags: new Set(),
rootLayoutIncluded: false,
preloadCallbacks,
MetadataOutlet,
})
).map((path) => path.slice(1)) // remove the '' (root) segment ).map((path) => path.slice(1)) // remove the '' (root) segment
} }
...@@ -829,7 +852,12 @@ async function generateDynamicFlightRenderResultWithStagesInDev( ...@@ -829,7 +852,12 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
renderOpts, renderOpts,
requestId, requestId,
workStore, workStore,
componentMod: { createElement }, componentMod: {
createElement,
routeModule: {
userland: { loaderTree },
},
},
url, url,
} = ctx } = ctx
...@@ -857,11 +885,13 @@ async function generateDynamicFlightRenderResultWithStagesInDev( ...@@ -857,11 +885,13 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
onFlightDataRenderError onFlightDataRenderError
) )
// We only validate RSC requests if it is for HMR refreshes since we know we // We validate RSC requests for HMR refreshes and client navigations when
// will render all the layouts necessary to perform the validation. // instant configs exist, since we render all the layouts necessary to perform
// the validation in those cases.
const shouldValidate = const shouldValidate =
!isBypassingCachesInDev(renderOpts, initialRequestStore) && !isBypassingCachesInDev(renderOpts, initialRequestStore) &&
initialRequestStore.isHmrRefresh === true (initialRequestStore.isHmrRefresh === true ||
(await anySegmentNeedsInstantValidation(loaderTree)))
const getPayload = async (requestStore: RequestStore) => { const getPayload = async (requestStore: RequestStore) => {
const payload: RSCPayload & const payload: RSCPayload &
......
import type { NodeJsPartialHmrUpdate } from '../../build/swc/types'
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
export { export {
createTemporaryReferenceSet, createTemporaryReferenceSet,
...@@ -66,7 +68,11 @@ if (process.env.NODE_ENV === 'development') { ...@@ -66,7 +68,11 @@ if (process.env.NODE_ENV === 'development') {
declare global { declare global {
var __next__clear_chunk_cache__: (() => void) | null | undefined var __next__clear_chunk_cache__: (() => void) | null | undefined
var __turbopack_clear_chunk_cache__: () => void | null | undefined var __turbopack_clear_chunk_cache__: () => void | null | undefined
var __turbopack_server_hmr_apply__:
| ((update: NodeJsPartialHmrUpdate) => boolean)
| undefined
} }
// hot-reloader modules are not bundled so we need to inject `__next__clear_chunk_cache__` // hot-reloader modules are not bundled so we need to inject `__next__clear_chunk_cache__`
// into globalThis from this file which is bundled. // into globalThis from this file which is bundled.
if (process.env.TURBOPACK) { if (process.env.TURBOPACK) {
......
...@@ -2,6 +2,10 @@ import { getLayoutOrPageModule } from '../../lib/app-dir-module' ...@@ -2,6 +2,10 @@ import { getLayoutOrPageModule } from '../../lib/app-dir-module'
import type { LoaderTree } from '../../lib/app-dir-module' import type { LoaderTree } from '../../lib/app-dir-module'
import { parseLoaderTree } from '../../../shared/lib/router/utils/parse-loader-tree' import { parseLoaderTree } from '../../../shared/lib/router/utils/parse-loader-tree'
import type { AppSegmentConfig } from '../../../build/segment-config/app/app-segment-config' import type { AppSegmentConfig } from '../../../build/segment-config/app/app-segment-config'
import {
workAsyncStorage,
type WorkStore,
} from '../work-async-storage.external'
export async function anySegmentHasRuntimePrefetchEnabled( export async function anySegmentHasRuntimePrefetchEnabled(
tree: LoaderTree tree: LoaderTree
...@@ -70,53 +74,90 @@ type FoundSegmentWithConfig = { ...@@ -70,53 +74,90 @@ type FoundSegmentWithConfig = {
config: NonNullable<AppSegmentConfig['unstable_instant']> config: NonNullable<AppSegmentConfig['unstable_instant']>
} }
export async function anySegmentNeedsInstantValidation( /**
rootTree: LoaderTree * Checks if any segments in the loader tree have `instant` configs that need validating.
): Promise<boolean> { * NOTE: Client navigations call this multiple times, so we cache it.
const segments = await findSegmentsWithInstantConfig(rootTree) * */
export const anySegmentNeedsInstantValidation = cacheScopedToWorkStore(
// Check if there's any configs with `prefetch: 'static'` or `mode: 'instant'`. async (rootTree: LoaderTree): Promise<boolean> => {
// (If there's only `false`, there's no need to run validation). const segments = await findSegmentsWithInstantConfig(rootTree)
// If any segment has `unstable_disableValidation`, we skip validation for the whole tree.
let needsValidation = false // Check if there's any configs with `prefetch: 'static'` or `mode: 'instant'`.
for (const { config } of segments) { // (If there's only `false`, there's no need to run validation).
if (typeof config === 'object') { // If any segment has `unstable_disableValidation`, we skip validation for the whole tree.
if (config.unstable_disableValidation) { let needsValidation = false
return false for (const { config } of segments) {
if (typeof config === 'object') {
if (config.unstable_disableValidation) {
return false
}
// do not short-circuit, some other segment might still have `unstable_disableValidation`
needsValidation = true
} }
// do not short-circuit, some other segment might still have `unstable_disableValidation`
needsValidation = true
} }
return needsValidation
} }
return needsValidation )
}
export const findSegmentsWithInstantConfig = cacheScopedToWorkStore(
async (rootTree: LoaderTree): Promise<FoundSegmentWithConfig[]> => {
const results: FoundSegmentWithConfig[] = []
async function visit(tree: LoaderTree, path: string[]): Promise<void> {
const { mod: layoutOrPageMod } = await getLayoutOrPageModule(tree)
// TODO(restart-on-cache-miss): Does this work correctly for client page/layout modules?
const instantConfig = layoutOrPageMod
? (layoutOrPageMod as AppSegmentConfig).unstable_instant
: undefined
if (instantConfig !== undefined) {
results.push({
path,
config: instantConfig,
})
}
export async function findSegmentsWithInstantConfig( const { parallelRoutes } = parseLoaderTree(tree)
rootTree: LoaderTree for (const parallelRouteKey in parallelRoutes) {
): Promise<FoundSegmentWithConfig[]> { const childTree = parallelRoutes[parallelRouteKey]
const results: FoundSegmentWithConfig[] = [] await visit(childTree, [...path, parallelRouteKey])
}
async function visit(tree: LoaderTree, path: string[]): Promise<void> {
const { mod: layoutOrPageMod } = await getLayoutOrPageModule(tree)
// TODO(restart-on-cache-miss): Does this work correctly for client page/layout modules?
const instantConfig = layoutOrPageMod
? (layoutOrPageMod as AppSegmentConfig).unstable_instant
: undefined
if (instantConfig !== undefined) {
results.push({
path,
config: instantConfig,
})
} }
const { parallelRoutes } = parseLoaderTree(tree) await visit(rootTree, [])
for (const parallelRouteKey in parallelRoutes) { return results
const childTree = parallelRoutes[parallelRouteKey]
await visit(childTree, [...path, parallelRouteKey])
}
} }
)
/**
* A simple cache wrapper for 1-argument functions.
* The cache will live as long as the current WorkStore,
* i.e. it's scoped to a single request.
*/
function cacheScopedToWorkStore<TArg extends WeakKey, TRes>(
func: (arg: TArg) => TRes
): (arg: TArg) => TRes {
const resultsPerWorkStore = new WeakMap<WorkStore, WeakMap<TArg, TRes>>()
return (arg: TArg): TRes => {
const workStore = workAsyncStorage.getStore()
if (!workStore) {
// No caching.
return func(arg)
}
await visit(rootTree, []) let results = resultsPerWorkStore.get(workStore)
return results if (results && results.has(arg)) {
return results.get(arg)!
}
const result = func(arg)
if (!results) {
results = new WeakMap()
resultsPerWorkStore.set(workStore, results)
}
results.set(arg, result)
return result
}
} }
...@@ -294,6 +294,70 @@ export async function walkTreeWithFlightRouterState({ ...@@ -294,6 +294,70 @@ export async function walkTreeWithFlightRouterState({
return paths return paths
} }
/**
* A simplified version of `walkTreeWithFlightRouterState` that doesn't skip any layouts
* but returns a result of the same shape.
* Intended to be used for instant validation, where we need the complete tree.
*/
export async function createFullTreeFlightDataForNavigation({
loaderTree,
rscHead,
injectedCSS,
injectedJS,
injectedFontPreloadTags,
ctx,
preloadCallbacks,
MetadataOutlet,
}: {
loaderTree: LoaderTree
flightRouterState?: FlightRouterState
rscHead: HeadData
injectedCSS: Set<string>
injectedJS: Set<string>
injectedFontPreloadTags: Set<string>
ctx: AppRenderContext
preloadCallbacks: PreloadCallbacks
MetadataOutlet: React.ComponentType
}): Promise<[rootSegment: FlightDataPath]> {
const {
renderOpts: { experimental },
query,
getDynamicParamFromSegment,
} = ctx
const routerState = createFlightRouterStateFromLoaderTree(
loaderTree,
getDynamicParamFromSegment,
query
)
const rootSegment = routerState[0]
const seedData = await createComponentTree({
ctx,
loaderTree,
parentParams: {},
injectedCSS,
injectedJS,
injectedFontPreloadTags,
rootLayoutIncluded: false,
preloadCallbacks,
authInterrupts: experimental.authInterrupts,
MetadataOutlet,
})
return [
[
// TODO: app-render slices this Segment off.
// why is that valid, and why are we including it in the first place?
rootSegment,
routerState,
seedData,
rscHead,
false,
] satisfies FlightDataSegment,
]
}
/* /*
* This function is used to determine if an existing segment can be overridden * This function is used to determine if an existing segment can be overridden
* by the incoming segment. * by the incoming segment.
......
...@@ -24,8 +24,10 @@ import type { ...@@ -24,8 +24,10 @@ import type {
TurbopackResult, TurbopackResult,
Project, Project,
Entrypoints, Entrypoints,
NodeJsHmrUpdate,
NodeJsPartialHmrUpdate,
} from '../../build/swc/types' } from '../../build/swc/types'
import { createDefineEnv, getBindingsSync } from '../../build/swc' import { createDefineEnv, getBindingsSync, HmrTarget } from '../../build/swc'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
import { BLOCKED_PAGES } from '../../shared/lib/constants' import { BLOCKED_PAGES } from '../../shared/lib/constants'
import { import {
...@@ -144,6 +146,98 @@ const sessionId = Math.floor(Number.MAX_SAFE_INTEGER * Math.random()) ...@@ -144,6 +146,98 @@ const sessionId = Math.floor(Number.MAX_SAFE_INTEGER * Math.random())
declare const __next__clear_chunk_cache__: (() => void) | null | undefined declare const __next__clear_chunk_cache__: (() => void) | null | undefined
declare const __turbopack_server_hmr_apply__:
| ((update: NodeJsPartialHmrUpdate) => boolean)
| undefined
function setupServerHmr(project: Project) {
const serverHmrSubscriptions = new Map<
string,
AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>
>()
/**
* Subscribe to HMR updates for a server chunk.
* @param chunkPath - Server chunk output path (e.g., "server/chunks/ssr/..._.js")
*/
function subscribeToServerHmr(chunkPath: string) {
if (serverHmrSubscriptions.has(chunkPath)) {
return
}
const subscription = project.hmrEvents(chunkPath, HmrTarget.Server)
serverHmrSubscriptions.set(chunkPath, subscription)
// Start listening for changes in background
;(async () => {
// Skip initial state
await subscription.next()
for await (const result of subscription) {
const update = result as NodeJsHmrUpdate
// Only process partial updates with actual code changes
if (update.type !== 'partial') {
continue
}
const entries = update.instruction?.entries
if (!entries || Object.keys(entries).length === 0) {
continue
}
if (typeof __turbopack_server_hmr_apply__ === 'function') {
const applied = __turbopack_server_hmr_apply__(update as any)
if (applied) {
console.log(`[Server HMR] Applied update for ${chunkPath}`)
// TODO: Notify clients to refresh and get updated server content
// This will trigger the client to re-fetch the page with new server components
}
}
}
})().catch((err) => {
console.error('[Server HMR] Subscription error:', err)
serverHmrSubscriptions.delete(chunkPath)
})
}
// Listen to the Rust bindings update us on changing server HMR chunk paths
;(async () => {
const serverHmrChunkPaths = project.hmrChunkNamesSubscribe(HmrTarget.Server)
// Process chunk paths (both initial and subsequent updates)
for await (const data of serverHmrChunkPaths) {
const currentChunkPaths = new Set(
data.chunkNames.filter((path) => path.endsWith('.js'))
)
// Clean up subscriptions for removed chunk paths (like when pages are deleted)
const chunkPathsToRemove = []
for (const chunkPath of serverHmrSubscriptions.keys()) {
if (!currentChunkPaths.has(chunkPath)) {
chunkPathsToRemove.push(chunkPath)
}
}
for (const chunkPath of chunkPathsToRemove) {
const subscription = serverHmrSubscriptions.get(chunkPath)
subscription?.return?.()
serverHmrSubscriptions.delete(chunkPath)
}
// Subscribe to HMR events for new server chunks
for (const chunkPath of currentChunkPaths) {
if (!serverHmrSubscriptions.has(chunkPath)) {
subscribeToServerHmr(chunkPath)
}
}
}
})().catch((err) => {
console.error('[Server HMR] error:', err)
})
}
/** /**
* Replaces turbopack:///[project] with the specified project in the `source` field. * Replaces turbopack:///[project] with the specified project in the `source` field.
*/ */
...@@ -194,7 +288,8 @@ export async function createHotReloaderTurbopack( ...@@ -194,7 +288,8 @@ export async function createHotReloaderTurbopack(
serverFields: ServerFields, serverFields: ServerFields,
distDir: string, distDir: string,
resetFetch: () => void, resetFetch: () => void,
lockfile: Lockfile | undefined lockfile: Lockfile | undefined,
experimentalServerFastRefresh?: boolean
): Promise<NextJsHotReloaderInterface> { ): Promise<NextJsHotReloaderInterface> {
const dev = true const dev = true
const buildId = 'development' const buildId = 'development'
...@@ -292,7 +387,11 @@ export async function createHotReloaderTurbopack( ...@@ -292,7 +387,11 @@ export async function createHotReloaderTurbopack(
} }
) )
backgroundLogCompilationEvents(project, { backgroundLogCompilationEvents(project, {
eventTypes: ['StartupCacheInvalidationEvent', 'TimingEvent'], eventTypes: [
'StartupCacheInvalidationEvent',
'TimingEvent',
'SlowFilesystemEvent',
],
}) })
setBundlerFindSourceMapImplementation( setBundlerFindSourceMapImplementation(
getSourceMapFromTurbopack.bind(null, project, projectPath) getSourceMapFromTurbopack.bind(null, project, projectPath)
...@@ -513,6 +612,10 @@ export async function createHotReloaderTurbopack( ...@@ -513,6 +612,10 @@ export async function createHotReloaderTurbopack(
} }
} }
if (experimentalServerFastRefresh) {
setupServerHmr(project)
}
let hmrEventHappened = false let hmrEventHappened = false
let hmrHash = 0 let hmrHash = 0
...@@ -606,7 +709,7 @@ export async function createHotReloaderTurbopack( ...@@ -606,7 +709,7 @@ export async function createHotReloaderTurbopack(
sendEnqueuedMessagesDebounce() sendEnqueuedMessagesDebounce()
} }
async function subscribeToChanges( async function subscribeToClientChanges(
key: EntryKey, key: EntryKey,
includeIssues: boolean, includeIssues: boolean,
endpoint: Endpoint, endpoint: Endpoint,
...@@ -648,7 +751,7 @@ export async function createHotReloaderTurbopack( ...@@ -648,7 +751,7 @@ export async function createHotReloaderTurbopack(
changeSubscriptions.delete(key) changeSubscriptions.delete(key)
} }
async function unsubscribeFromChanges(key: EntryKey) { async function unsubscribeFromClientChanges(key: EntryKey) {
const subscription = await changeSubscriptions.get(key) const subscription = await changeSubscriptions.get(key)
if (subscription) { if (subscription) {
await subscription.return?.() await subscription.return?.()
...@@ -657,7 +760,7 @@ export async function createHotReloaderTurbopack( ...@@ -657,7 +760,7 @@ export async function createHotReloaderTurbopack(
currentEntryIssues.delete(key) currentEntryIssues.delete(key)
} }
async function subscribeToHmrEvents(client: ws, id: string) { async function subscribeToClientHmrEvents(client: ws, id: string) {
const key = getEntryKey('assets', 'client', id) const key = getEntryKey('assets', 'client', id)
if (!hasEntrypointForKey(currentEntrypoints, key, assetMapper)) { if (!hasEntrypointForKey(currentEntrypoints, key, assetMapper)) {
// maybe throw an error / force the client to reload? // maybe throw an error / force the client to reload?
...@@ -669,7 +772,7 @@ export async function createHotReloaderTurbopack( ...@@ -669,7 +772,7 @@ export async function createHotReloaderTurbopack(
return return
} }
const subscription = project!.hmrEvents(id) const subscription = project!.hmrEvents(id, HmrTarget.Client)
state.subscriptions.set(id, subscription) state.subscriptions.set(id, subscription)
// The subscription will always emit once, which is the initial // The subscription will always emit once, which is the initial
...@@ -680,7 +783,7 @@ export async function createHotReloaderTurbopack( ...@@ -680,7 +783,7 @@ export async function createHotReloaderTurbopack(
for await (const data of subscription) { for await (const data of subscription) {
processIssues(state.clientIssues, key, data, false, true) processIssues(state.clientIssues, key, data, false, true)
if (data.type !== 'issues') { if (data.type !== 'issues') {
sendTurbopackMessage(data) sendTurbopackMessage(data as TurbopackUpdate)
} }
} }
} catch (e) { } catch (e) {
...@@ -698,7 +801,7 @@ export async function createHotReloaderTurbopack( ...@@ -698,7 +801,7 @@ export async function createHotReloaderTurbopack(
} }
} }
function unsubscribeFromHmrEvents(client: ws, id: string) { function unsubscribeFromClientHmrEvents(client: ws, id: string) {
const state = clientStates.get(client) const state = clientStates.get(client)
if (!state) { if (!state) {
return return
...@@ -775,9 +878,9 @@ export async function createHotReloaderTurbopack( ...@@ -775,9 +878,9 @@ export async function createHotReloaderTurbopack(
propagateServerField: propagateServerField.bind(null, opts), propagateServerField: propagateServerField.bind(null, opts),
sendHmr, sendHmr,
startBuilding, startBuilding,
subscribeToChanges, subscribeToChanges: subscribeToClientChanges,
unsubscribeFromChanges, unsubscribeFromChanges: unsubscribeFromClientChanges,
unsubscribeFromHmrEvents, unsubscribeFromHmrEvents: unsubscribeFromClientHmrEvents,
}, },
}, },
}) })
...@@ -1132,11 +1235,11 @@ export async function createHotReloaderTurbopack( ...@@ -1132,11 +1235,11 @@ export async function createHotReloaderTurbopack(
// Turbopack messages // Turbopack messages
switch (parsedData.type) { switch (parsedData.type) {
case 'turbopack-subscribe': case 'turbopack-subscribe':
subscribeToHmrEvents(client, parsedData.path) subscribeToClientHmrEvents(client, parsedData.path)
break break
case 'turbopack-unsubscribe': case 'turbopack-unsubscribe':
unsubscribeFromHmrEvents(client, parsedData.path) unsubscribeFromClientHmrEvents(client, parsedData.path)
break break
default: default:
...@@ -1446,7 +1549,7 @@ export async function createHotReloaderTurbopack( ...@@ -1446,7 +1549,7 @@ export async function createHotReloaderTurbopack(
productionRewrites: undefined, productionRewrites: undefined,
logErrors: true, logErrors: true,
hooks: { hooks: {
subscribeToChanges, subscribeToChanges: subscribeToClientChanges,
handleWrittenEndpoint: (id, result, forceDeleteCache) => { handleWrittenEndpoint: (id, result, forceDeleteCache) => {
currentWrittenEntrypoints.set(id, result) currentWrittenEntrypoints.set(id, result)
assetMapper.setPathsForKey(id, result.clientPaths) assetMapper.setPathsForKey(id, result.clientPaths)
...@@ -1514,7 +1617,7 @@ export async function createHotReloaderTurbopack( ...@@ -1514,7 +1617,7 @@ export async function createHotReloaderTurbopack(
logErrors: true, logErrors: true,
hooks: { hooks: {
subscribeToChanges, subscribeToChanges: subscribeToClientChanges,
handleWrittenEndpoint: (id, result, forceDeleteCache) => { handleWrittenEndpoint: (id, result, forceDeleteCache) => {
currentWrittenEntrypoints.set(id, result) currentWrittenEntrypoints.set(id, result)
assetMapper.setPathsForKey(id, result.clientPaths) assetMapper.setPathsForKey(id, result.clientPaths)
......
...@@ -8,6 +8,7 @@ import type { UrlWithParsedQuery } from 'url' ...@@ -8,6 +8,7 @@ import type { UrlWithParsedQuery } from 'url'
import type { MiddlewareRoutingItem } from '../base-server' import type { MiddlewareRoutingItem } from '../base-server'
import type { RouteDefinition } from '../route-definitions/route-definition' import type { RouteDefinition } from '../route-definitions/route-definition'
import type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager' import type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager'
import { import {
addRequestMeta, addRequestMeta,
getRequestMeta, getRequestMeta,
...@@ -39,7 +40,12 @@ import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-pat ...@@ -39,7 +40,12 @@ import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-pat
import { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix' import { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'
import { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix' import { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'
import { Telemetry } from '../../telemetry/storage' import { Telemetry } from '../../telemetry/storage'
import { type Span, setGlobal, trace } from '../../trace' import {
type Span,
hrtimeToEpochNanoseconds,
setGlobal,
trace,
} from '../../trace'
import { traceGlobals } from '../../trace/shared' import { traceGlobals } from '../../trace/shared'
import { findPageFile } from '../lib/find-page-file' import { findPageFile } from '../lib/find-page-file'
import { getFormattedNodeOptionsWithoutInspect } from '../lib/utils' import { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'
...@@ -532,6 +538,20 @@ export default class DevServer extends Server { ...@@ -532,6 +538,20 @@ export default class DevServer extends Server {
getRequestMeta(req, 'devRequestTimingInternalsEnd'), getRequestMeta(req, 'devRequestTimingInternalsEnd'),
getRequestMeta(req, 'devGenerateStaticParamsDuration') getRequestMeta(req, 'devGenerateStaticParamsDuration')
) )
// Create trace span for render phase
const devRequestTimingInternalsEnd = getRequestMeta(
req,
'devRequestTimingInternalsEnd'
)
if (devRequestTimingInternalsEnd) {
this.startServerSpan.manualTraceChild(
'render-path',
hrtimeToEpochNanoseconds(devRequestTimingInternalsEnd),
hrtimeToEpochNanoseconds(requestEnd),
{ path: req.url || '' }
)
}
}) })
} }
} }
......
...@@ -90,6 +90,7 @@ export async function initialize(opts: { ...@@ -90,6 +90,7 @@ export async function initialize(opts: {
keepAliveTimeout?: number keepAliveTimeout?: number
customServer?: boolean customServer?: boolean
experimentalHttpsServer?: boolean experimentalHttpsServer?: boolean
experimentalServerFastRefresh?: boolean
startServerSpan?: Span startServerSpan?: Span
quiet?: boolean quiet?: boolean
}): Promise<ServerInitResult> { }): Promise<ServerInitResult> {
...@@ -178,6 +179,7 @@ export async function initialize(opts: { ...@@ -178,6 +179,7 @@ export async function initialize(opts: {
port: opts.port, port: opts.port,
onDevServerCleanup: opts.onDevServerCleanup, onDevServerCleanup: opts.onDevServerCleanup,
resetFetch, resetFetch,
experimentalServerFastRefresh: opts.experimentalServerFastRefresh,
}) })
) )
......
...@@ -115,6 +115,7 @@ export type SetupOpts = { ...@@ -115,6 +115,7 @@ export type SetupOpts = {
port: number port: number
onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined
resetFetch: () => void resetFetch: () => void
experimentalServerFastRefresh?: boolean
} }
export interface DevRoutesManifest { export interface DevRoutesManifest {
...@@ -237,7 +238,8 @@ async function startWatcher( ...@@ -237,7 +238,8 @@ async function startWatcher(
serverFields, serverFields,
distDir, distDir,
resetFetch, resetFetch,
lockfile lockfile,
opts.experimentalServerFastRefresh
) )
})() })()
: await (async () => { : await (async () => {
......
...@@ -136,6 +136,7 @@ export async function getRequestHandlers({ ...@@ -136,6 +136,7 @@ export async function getRequestHandlers({
minimalMode, minimalMode,
keepAliveTimeout, keepAliveTimeout,
experimentalHttpsServer, experimentalHttpsServer,
experimentalServerFastRefresh,
quiet, quiet,
}: { }: {
dir: string dir: string
...@@ -147,6 +148,7 @@ export async function getRequestHandlers({ ...@@ -147,6 +148,7 @@ export async function getRequestHandlers({
minimalMode?: boolean minimalMode?: boolean
keepAliveTimeout?: number keepAliveTimeout?: number
experimentalHttpsServer?: boolean experimentalHttpsServer?: boolean
experimentalServerFastRefresh?: boolean
quiet?: boolean quiet?: boolean
}): ReturnType<typeof initialize> { }): ReturnType<typeof initialize> {
return initialize({ return initialize({
...@@ -159,6 +161,7 @@ export async function getRequestHandlers({ ...@@ -159,6 +161,7 @@ export async function getRequestHandlers({
server, server,
keepAliveTimeout, keepAliveTimeout,
experimentalHttpsServer, experimentalHttpsServer,
experimentalServerFastRefresh,
startServerSpan, startServerSpan,
quiet, quiet,
}) })
...@@ -179,6 +182,7 @@ export async function startServer( ...@@ -179,6 +182,7 @@ export async function startServer(
allowRetry, allowRetry,
keepAliveTimeout, keepAliveTimeout,
selfSignedCertificate, selfSignedCertificate,
experimentalServerFastRefresh,
} = serverOptions } = serverOptions
let { port } = serverOptions let { port } = serverOptions
...@@ -414,6 +418,9 @@ export async function startServer( ...@@ -414,6 +418,9 @@ export async function startServer(
cleanupListeners?.runAll().catch(console.error), cleanupListeners?.runAll().catch(console.error),
]) ])
// Flush any remaining traces to the trace file on shutdown
await flushAllTraces()
// Flush telemetry if this is a dev server // Flush telemetry if this is a dev server
if (isDev) { if (isDev) {
try { try {
...@@ -476,6 +483,7 @@ export async function startServer( ...@@ -476,6 +483,7 @@ export async function startServer(
minimalMode, minimalMode,
keepAliveTimeout, keepAliveTimeout,
experimentalHttpsServer: !!selfSignedCertificate, experimentalHttpsServer: !!selfSignedCertificate,
experimentalServerFastRefresh,
}) })
requestHandler = initResult.requestHandler requestHandler = initResult.requestHandler
upgradeHandler = initResult.upgradeHandler upgradeHandler = initResult.upgradeHandler
......
...@@ -7,6 +7,7 @@ import { ...@@ -7,6 +7,7 @@ import {
recordTraceEvents, recordTraceEvents,
Span, Span,
SpanStatus, SpanStatus,
hrtimeToEpochNanoseconds,
} from './trace' } from './trace'
import { setGlobal } from './shared' import { setGlobal } from './shared'
import type { SpanId, TraceEvent, TraceState } from './types' import type { SpanId, TraceEvent, TraceState } from './types'
...@@ -16,6 +17,7 @@ export { ...@@ -16,6 +17,7 @@ export {
exportTraceState, exportTraceState,
flushAllTraces, flushAllTraces,
getTraceEvents, getTraceEvents,
hrtimeToEpochNanoseconds,
initializeTraceState, initializeTraceState,
recordTraceEvents, recordTraceEvents,
Span, Span,
......
...@@ -15,6 +15,7 @@ const COMMON_ALLOWED_EVENTS = ['memory-usage'] ...@@ -15,6 +15,7 @@ const COMMON_ALLOWED_EVENTS = ['memory-usage']
const DEV_ALLOWED_EVENTS = new Set([ const DEV_ALLOWED_EVENTS = new Set([
...COMMON_ALLOWED_EVENTS, ...COMMON_ALLOWED_EVENTS,
'client-hmr-latency', 'client-hmr-latency',
'render-path',
'hot-reloader', 'hot-reloader',
'webpack-invalid-client', 'webpack-invalid-client',
'webpack-invalidated-server', 'webpack-invalidated-server',
......
...@@ -3,6 +3,7 @@ import type { SpanId, TraceEvent, TraceState } from './types' ...@@ -3,6 +3,7 @@ import type { SpanId, TraceEvent, TraceState } from './types'
const NUM_OF_MICROSEC_IN_NANOSEC = BigInt('1000') const NUM_OF_MICROSEC_IN_NANOSEC = BigInt('1000')
const NUM_OF_MILLISEC_IN_NANOSEC = BigInt('1000000') const NUM_OF_MILLISEC_IN_NANOSEC = BigInt('1000000')
let count = 0 let count = 0
const getId = () => { const getId = () => {
count++ count++
...@@ -188,3 +189,18 @@ export function recordTraceEvents(events: TraceEvent[]) { ...@@ -188,3 +189,18 @@ export function recordTraceEvents(events: TraceEvent[]) {
} }
export const clearTraceEvents = () => (savedTraceEvents = []) export const clearTraceEvents = () => (savedTraceEvents = [])
/**
* Converts hrtime (process.hrtime.bigint()) to epoch-based nanoseconds.
*
* hrtime values are relative to an arbitrary point in the past, while
* epoch-based times are nanoseconds since Unix epoch (Jan 1, 1970).
*
* This is useful when passing hrtime values to APIs that expect epoch-based times,
* such as Span.manualTraceChild().
*/
export function hrtimeToEpochNanoseconds(hrtimeValue: bigint): bigint {
const offset =
BigInt(Date.now()) * NUM_OF_MILLISEC_IN_NANOSEC - process.hrtime.bigint()
return hrtimeValue + offset
}
{ {
"name": "@next/react-refresh-utils", "name": "@next/react-refresh-utils",
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"description": "An experimental package providing utilities for React Refresh.", "description": "An experimental package providing utilities for React Refresh.",
"repository": { "repository": {
"url": "vercel/next.js", "url": "vercel/next.js",
......
{ {
"name": "@next/third-parties", "name": "@next/third-parties",
"version": "16.2.0-canary.33", "version": "16.2.0-canary.35",
"repository": { "repository": {
"url": "vercel/next.js", "url": "vercel/next.js",
"directory": "packages/third-parties" "directory": "packages/third-parties"
...@@ -26,7 +26,7 @@ ...@@ -26,7 +26,7 @@
"third-party-capital": "1.0.20" "third-party-capital": "1.0.20"
}, },
"devDependencies": { "devDependencies": {
"next": "16.2.0-canary.33", "next": "16.2.0-canary.35",
"outdent": "0.8.0", "outdent": "0.8.0",
"prettier": "2.5.1", "prettier": "2.5.1",
"typescript": "5.9.2" "typescript": "5.9.2"
......
...@@ -1011,7 +1011,7 @@ importers: ...@@ -1011,7 +1011,7 @@ importers:
packages/eslint-config-next: packages/eslint-config-next:
dependencies: dependencies:
'@next/eslint-plugin-next': '@next/eslint-plugin-next':
specifier: 16.2.0-canary.33 specifier: 16.2.0-canary.35
version: link:../eslint-plugin-next version: link:../eslint-plugin-next
eslint: eslint:
specifier: '>=9.0.0' specifier: '>=9.0.0'
...@@ -1088,7 +1088,7 @@ importers: ...@@ -1088,7 +1088,7 @@ importers:
packages/next: packages/next:
dependencies: dependencies:
'@next/env': '@next/env':
specifier: 16.2.0-canary.33 specifier: 16.2.0-canary.35
version: link:../next-env version: link:../next-env
'@swc/helpers': '@swc/helpers':
specifier: 0.5.15 specifier: 0.5.15
...@@ -1216,19 +1216,19 @@ importers: ...@@ -1216,19 +1216,19 @@ importers:
specifier: 1.2.0 specifier: 1.2.0
version: 1.2.0 version: 1.2.0
'@next/font': '@next/font':
specifier: 16.2.0-canary.33 specifier: 16.2.0-canary.35
version: link:../font version: link:../font
'@next/polyfill-module': '@next/polyfill-module':
specifier: 16.2.0-canary.33 specifier: 16.2.0-canary.35
version: link:../next-polyfill-module version: link:../next-polyfill-module
'@next/polyfill-nomodule': '@next/polyfill-nomodule':
specifier: 16.2.0-canary.33 specifier: 16.2.0-canary.35
version: link:../next-polyfill-nomodule version: link:../next-polyfill-nomodule
'@next/react-refresh-utils': '@next/react-refresh-utils':
specifier: 16.2.0-canary.33 specifier: 16.2.0-canary.35
version: link:../react-refresh-utils version: link:../react-refresh-utils
'@next/swc': '@next/swc':
specifier: 16.2.0-canary.33 specifier: 16.2.0-canary.35
version: link:../next-swc version: link:../next-swc
'@opentelemetry/api': '@opentelemetry/api':
specifier: 1.6.0 specifier: 1.6.0
...@@ -1943,7 +1943,7 @@ importers: ...@@ -1943,7 +1943,7 @@ importers:
version: 1.0.20 version: 1.0.20
devDependencies: devDependencies:
next: next:
specifier: 16.2.0-canary.33 specifier: 16.2.0-canary.35
version: link:../next version: link:../next
outdent: outdent:
specifier: 0.8.0 specifier: 0.8.0
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
import { nextTestSetup } from 'e2e-utils'
import { join } from 'path'
import { existsSync, readFileSync } from 'fs'
type SpanId = number
type TraceEvent = {
traceId?: string
parentId?: SpanId
name: string
id: SpanId
timestamp: number
duration: number
tags?: Record<string, unknown>
startTime?: number
}
interface TraceStructure {
events: TraceEvent[]
eventsByName: Map<string, TraceEvent[]>
eventsById: Map<string, TraceEvent>
}
function parseTraceFile(tracePath: string): TraceStructure {
const traceContent = readFileSync(tracePath, 'utf8')
const traceLines = traceContent
.trim()
.split('\n')
.filter((line) => line.trim())
const allEvents: TraceEvent[] = []
for (const line of traceLines) {
const events = JSON.parse(line) as TraceEvent[]
allEvents.push(...events)
}
const eventsByName = new Map<string, TraceEvent[]>()
const eventsById = new Map<string, TraceEvent>()
// Index all events
for (const event of allEvents) {
if (!eventsByName.has(event.name)) {
eventsByName.set(event.name, [])
}
eventsByName.get(event.name)!.push(event)
eventsById.set(event.id.toString(), event)
}
return {
events: allEvents,
eventsByName,
eventsById,
}
}
describe('render-path tracing', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (!isNextDev) {
it('should be skipped in production', () => {})
return
}
it('should record render-path events for page requests', async () => {
const tracePath = join(next.testDir, '.next/dev/trace')
// Trigger page request if trace doesn't exist yet
if (!existsSync(tracePath)) {
const browser = await next.browser('/')
expect(await browser.elementByCss('p').text()).toBe('hello world')
await browser.close()
await next.stop('SIGTERM')
await new Promise((resolve) => setTimeout(resolve, 500))
}
const traceStructure = parseTraceFile(tracePath)
// Check for render-path events
const renderPathEvents = traceStructure.eventsByName.get('render-path')
expect(renderPathEvents).toBeDefined()
expect(renderPathEvents!.length).toBeGreaterThan(0)
// Verify the first render-path event has expected attributes
const renderEvent = renderPathEvents![0]
expect(renderEvent.tags).toBeDefined()
const renderTags = renderEvent.tags as any
expect(renderTags.path).toBeDefined()
expect(typeof renderTags.path).toBe('string')
// Verify render event has valid duration
expect(renderEvent.duration).toBeGreaterThan(0)
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { NextInstance, createNext } from 'e2e-utils' import { NextInstance, createNext } from 'e2e-utils'
import { trace } from 'next/dist/trace' import { trace } from 'next/dist/trace'
import { PHASE_DEVELOPMENT_SERVER } from 'next/constants' import { PHASE_DEVELOPMENT_SERVER } from 'next/constants'
import { createDefineEnv, loadBindings } from 'next/dist/build/swc' import { createDefineEnv, loadBindings, HmrTarget } from 'next/dist/build/swc'
import type { import type {
Diagnostics, Diagnostics,
Issue, Issue,
...@@ -667,12 +667,15 @@ describe('next.rs api', () => { ...@@ -667,12 +667,15 @@ describe('next.rs api', () => {
} }
} }
const result = await project.hmrIdentifiersSubscribe().next() const result = await project
.hmrChunkNamesSubscribe(HmrTarget.Client)
.next()
expect(result.done).toBe(false) expect(result.done).toBe(false)
const identifiers = result.value.identifiers const chunkNames = result.value.chunkNames
expect(identifiers).toHaveProperty('length', expect.toBePositive()) expect(chunkNames).toHaveProperty('length', expect.toBePositive())
const subscriptions = identifiers.map((identifier) =>
project.hmrEvents(identifier) const subscriptions = chunkNames.map((chunkName) =>
project.hmrEvents(chunkName, HmrTarget.Client)
) )
await Promise.all( await Promise.all(
subscriptions.map(async (subscription) => { subscriptions.map(async (subscription) => {
...@@ -794,12 +797,12 @@ describe('next.rs api', () => { ...@@ -794,12 +797,12 @@ describe('next.rs api', () => {
if (route.type !== 'page') throw new Error('unknown route type') if (route.type !== 'page') throw new Error('unknown route type')
await route.htmlEndpoint.writeToDisk() await route.htmlEndpoint.writeToDisk()
const result = await project.hmrIdentifiersSubscribe().next() const result = await project.hmrChunkNamesSubscribe(HmrTarget.Client).next()
expect(result.done).toBe(false) expect(result.done).toBe(false)
const identifiers = result.value.identifiers const chunkNames = result.value.chunkNames
const subscriptions = identifiers.map((identifier) => const subscriptions = chunkNames.map((chunkName) =>
project.hmrEvents(identifier) project.hmrEvents(chunkName, HmrTarget.Client)
) )
await Promise.all( await Promise.all(
subscriptions.map(async (subscription) => { subscriptions.map(async (subscription) => {
......
...@@ -3,18 +3,7 @@ import { ReactNode } from 'react' ...@@ -3,18 +3,7 @@ import { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) { export default function RootLayout({ children }: { children: ReactNode }) {
return ( return (
<html> <html>
<body style={{ fontFamily: 'monospace' }}> <body style={{ fontFamily: 'monospace' }}>{children}</body>
<Header />
{children}
</body>
</html> </html>
) )
} }
function Header() {
return (
<header>
<a href="/">Home</a>
</header>
)
}
import Link from 'next/link'
export default function IndexPage() {
return (
<main>
<h1>Instant Validation Test</h1>
<ul>
<li>
<Link href="/default">Default (plain root layout)</Link>
</li>
<li>
<Link href="/suspense-in-root">Suspense in Root</Link>
</li>
</ul>
</main>
)
}
import { ReactNode } from 'react' import { connection } from 'next/server'
import { ReactNode, Suspense } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) { export default function RootLayout({ children }: { children: ReactNode }) {
return ( return (
<html> <html>
<body style={{ fontFamily: 'monospace' }}> <body style={{ fontFamily: 'monospace' }}>
<Header /> <Header />
<hr />
{children} {children}
</body> </body>
</html> </html>
...@@ -14,7 +16,17 @@ export default function RootLayout({ children }: { children: ReactNode }) { ...@@ -14,7 +16,17 @@ export default function RootLayout({ children }: { children: ReactNode }) {
function Header() { function Header() {
return ( return (
<header> <header>
<a href="/">Home</a> <a href="/">Home</a>{' '}
<Suspense fallback="...">
<div id="root-layout-timestamp">
<Now />
</div>
</Suspense>
</header> </header>
) )
} }
async function Now() {
await connection()
return Date.now()
}
import { cacheLife } from 'next/cache'
import { DebugLinks } from '../shared'
export default async function Page() {
'use cache'
cacheLife('minutes')
return (
<main>
<h2>Static</h2>
<ul>
<li>
<DebugLinks href="/default/static/valid-blocked-children" />
</li>
<li>
<DebugLinks href="/default/static/valid-blocking-inside-static" />
</li>
</ul>
</main>
)
}
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
import Link from 'next/link'
import { setTimeout } from 'timers/promises' import { setTimeout } from 'timers/promises'
export function DebugLinks({ href }: { href: string }) {
return (
<span>
<span>{href}</span>{' '}
<Link data-link-type="soft" href={href}>
[SPA]
</Link>{' '}
<a data-link-type="hard" href={href}>
[MPA]
</a>
</span>
)
}
export async function uncachedIO() { export async function uncachedIO() {
await setTimeout(0) await setTimeout(0)
} }
......
import { connection } from 'next/server'
import { ReactNode, Suspense } from 'react' import { ReactNode, Suspense } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) { export default function RootLayout({ children }: { children: ReactNode }) {
...@@ -9,6 +10,7 @@ export default function RootLayout({ children }: { children: ReactNode }) { ...@@ -9,6 +10,7 @@ export default function RootLayout({ children }: { children: ReactNode }) {
<html> <html>
<body style={{ fontFamily: 'monospace' }}> <body style={{ fontFamily: 'monospace' }}>
<Header /> <Header />
<hr />
{children} {children}
</body> </body>
</html> </html>
...@@ -19,7 +21,17 @@ export default function RootLayout({ children }: { children: ReactNode }) { ...@@ -19,7 +21,17 @@ export default function RootLayout({ children }: { children: ReactNode }) {
function Header() { function Header() {
return ( return (
<header> <header>
<a href="/">Home</a> <a href="/">Home</a>{' '}
<Suspense fallback="...">
<div id="root-layout-timestamp">
<Now />
</div>
</Suspense>
</header> </header>
) )
} }
async function Now() {
await connection()
return Date.now()
}
import { DebugLinkMPA } from '../../components/debug-link'
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
import { DebugLinks } from '../shared'
export default async function Page() { export default async function Page() {
'use cache' 'use cache'
...@@ -9,90 +9,84 @@ export default async function Page() { ...@@ -9,90 +9,84 @@ export default async function Page() {
<h2>Runtime</h2> <h2>Runtime</h2>
<ul> <ul>
<li> <li>
<DebugLinkMPA href="/runtime/suspense-around-dynamic" /> <DebugLinks href="/suspense-in-root/runtime/suspense-around-dynamic" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/runtime/no-suspense-around-params/123" /> <DebugLinks href="/suspense-in-root/runtime/no-suspense-around-params/123" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/runtime/missing-suspense-around-dynamic" /> <DebugLinks href="/suspense-in-root/runtime/missing-suspense-around-dynamic" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/runtime/missing-suspense-around-dynamic-layout" /> <DebugLinks href="/suspense-in-root/runtime/missing-suspense-around-dynamic-layout" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/runtime/suspense-too-high" /> <DebugLinks href="/suspense-in-root/runtime/suspense-too-high" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/runtime/invalid-blocking-inside-runtime" /> <DebugLinks href="/suspense-in-root/static/invalid-blocking-inside-static" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/runtime/invalid-sync-io" /> <DebugLinks href="/suspense-in-root/runtime/invalid-blocking-inside-runtime" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/runtime/valid-blocking-inside-runtime" /> <DebugLinks href="/suspense-in-root/runtime/invalid-sync-io" />
</li>
<li>
<DebugLinks href="/suspense-in-root/runtime/valid-blocking-inside-runtime" />
</li> </li>
</ul> </ul>
<h2>Static</h2> <h2>Static</h2>
<ul> <ul>
<li> <li>
<DebugLinkMPA href="/static/suspense-around-dynamic" /> <DebugLinks href="/suspense-in-root/static/suspense-around-dynamic" />
</li>
<li>
<DebugLinkMPA href="/static/missing-suspense-around-dynamic" />
</li>
<li>
<DebugLinkMPA href="/static/missing-suspense-around-params/123" />
</li>
<li>
<DebugLinkMPA href="/static/missing-suspense-around-dynamic-layout" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/static/suspense-too-high" /> <DebugLinks href="/suspense-in-root/static/missing-suspense-around-dynamic" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/static/blocking-layout" /> <DebugLinks href="/suspense-in-root/static/missing-suspense-around-params/123" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/static/blocking-layout/missing-suspense-around-dynamic" /> <DebugLinks href="/suspense-in-root/static/missing-suspense-around-dynamic-layout" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/static/invalid-only-loading-around-dynamic" /> <DebugLinks href="/suspense-in-root/static/suspense-too-high" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/static/missing-suspense-around-runtime" /> <DebugLinks href="/suspense-in-root/static/blocking-layout" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/static/missing-suspense-in-parallel-route" /> <DebugLinks href="/suspense-in-root/static/blocking-layout/missing-suspense-around-dynamic" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/static/missing-suspense-in-parallel-route/foo" /> <DebugLinks href="/suspense-in-root/static/invalid-only-loading-around-dynamic" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/static/missing-suspense-in-parallel-route/bar" /> <DebugLinks href="/suspense-in-root/static/missing-suspense-around-runtime" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/static/invalid-blocking-inside-static" /> <DebugLinks href="/suspense-in-root/static/missing-suspense-in-parallel-route" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/static/valid-blocked-children" /> <DebugLinks href="/suspense-in-root/static/missing-suspense-in-parallel-route/foo" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/static/valid-blocking-inside-static" /> <DebugLinks href="/suspense-in-root/static/missing-suspense-in-parallel-route/bar" />
</li> </li>
</ul> </ul>
<h2>Disable Validation</h2> <h2>Disable Validation</h2>
<ul> <ul>
<li> <li>
<DebugLinkMPA href="/disable-validation/in-layout" /> <DebugLinks href="/suspense-in-root/disable-validation/in-layout" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/disable-validation/in-page" /> <DebugLinks href="/suspense-in-root/disable-validation/in-page" />
</li> </li>
<li> <li>
<DebugLinkMPA href="/disable-validation/in-page-with-outer" /> <DebugLinks href="/suspense-in-root/disable-validation/in-page-with-outer" />
</li> </li>
</ul> </ul>
</main> </main>
......
import Link from 'next/link'
export const unstable_instant = { prefetch: 'static' } export const unstable_instant = { prefetch: 'static' }
export default async function Page() { export default async function Page() {
return ( return (
<main> <main>
<p>This is a static page below a blocking layout</p> <p>This is a static page below a blocking layout</p>
<div>
<Link href="/suspense-in-root/static/blocking-layout/missing-suspense-around-dynamic">
/suspense-in-root/static/blocking-layout/missing-suspense-around-dynamic
</Link>
</div>
</main> </main>
) )
} }
...@@ -6,7 +6,9 @@ export default async function Page() { ...@@ -6,7 +6,9 @@ export default async function Page() {
return ( return (
<main> <main>
<p>This is a static page</p> <p>This is a static page</p>
<Link href="./missing-suspense-in-parallel-route/foo">./foo</Link> <Link href="/suspense-in-root/static/missing-suspense-in-parallel-route/foo">
./foo
</Link>
</main> </main>
) )
} }
'use client' 'use client'
import Link from 'next/link'
import { ComponentProps } from 'react' import { ComponentProps } from 'react'
export function DebugLink({
href,
...props
}: Omit<ComponentProps<typeof Link>, 'children' | 'href'> & { href: string }) {
return (
<Link href={href} {...props}>
{href}
</Link>
)
}
export function DebugLinkMPA({ export function DebugLinkMPA({
href, href,
...props ...props
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
describe('not-found-with-pages', () => { const isAdapterTest = Boolean(process.env.NEXT_ENABLE_ADAPTER)
const { next, isNextStart } = nextTestSetup({
describe('not-found-with-pages-i18n', () => {
const { next, isNextStart, isNextDeploy } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
...@@ -17,15 +19,32 @@ describe('not-found-with-pages', () => { ...@@ -17,15 +19,32 @@ describe('not-found-with-pages', () => {
}) })
} }
it('should prefer the app router 404 over the pages router 404 when both are present', async () => { // When using the builder, pages router is incorrectly preferred. This is already fixed when using the adapter
const browser = await next.browser('/app-dir/foo') const SKIP_TEST_FOR_BUILDER = isNextDeploy ? !isAdapterTest : false
expect(await browser.elementByCss('h1').text()).toBe(
'APP ROUTER - 404 PAGE' if (!SKIP_TEST_FOR_BUILDER) {
) it.each(['/app-dir/foo', '/foo'])(
'should prefer the app router 404 over the pages router 404 when both are present - browser %s',
async (s) => {
const browser = await next.browser(s)
expect(await browser.elementByCss('h1').text()).toBe(
'APP ROUTER - 404 PAGE'
)
await browser.loadPage(next.url) await browser.loadPage(next.url)
expect(await browser.elementByCss('h1').text()).toBe( expect(await browser.elementByCss('h1').text()).toBe(
'APP ROUTER - 404 PAGE' 'APP ROUTER - 404 PAGE'
)
}
) )
}) }
it.each(SKIP_TEST_FOR_BUILDER ? ['/app-dir/foo'] : ['/app-dir/foo', '/foo'])(
'should prefer the app router 404 over the pages router 404 when both are present - SSR %s',
async (s) => {
const ssr = await next.fetch(s)
expect(ssr.status).toEqual(404)
expect(await ssr.text()).toContain('APP ROUTER - 404 PAGE')
}
)
}) })
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { createRouterAct } from 'router-act' import { createRouterAct } from 'router-act'
import { setTimeout } from 'node:timers/promises' import { setTimeout } from 'node:timers/promises'
import { retry } from 'next-test-utils'
describe('parallel-routes-root-param-dynamic-child', () => { describe('parallel-routes-root-param-dynamic-child', () => {
const { next, isNextDev } = nextTestSetup({ const { next, isNextDev } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
async function createBrowserActor(url: string, errorPage: boolean = false) { async function createBrowserActor(
url: string,
{
errorPage = false,
waitForPrefetch = false,
}: {
errorPage?: boolean
waitForPrefetch?: boolean
} = {}
) {
let act: ReturnType<typeof createRouterAct> let act: ReturnType<typeof createRouterAct>
const browser = await next.browser(url, { const browser = await next.browser(url, {
beforePageLoad(page) { beforePageLoad(page) {
...@@ -22,29 +32,39 @@ describe('parallel-routes-root-param-dynamic-child', () => { ...@@ -22,29 +32,39 @@ describe('parallel-routes-root-param-dynamic-child', () => {
return { act, browser } return { act, browser }
} }
// The page has navigation links that will be automatically prefetched. if (waitForPrefetch) {
// Some routes will 404 (like /es which isn't in generateStaticParams), // The page has navigation links that will be automatically prefetched.
// so we allow 404 status codes. Let's reveal the navigation links and let // Some routes will 404 (like /es which isn't in generateStaticParams),
// the prefetching occur. // so we allow 404 status codes. Let's reveal the navigation links and let
await act( // the prefetching occur.
async () => { await act(
await browser.elementByCss('#reveal').click() async () => {
await browser.elementByCss('#reveal').click()
// Ensure the navigation is visible
await browser.elementByCss('#nav') // Ensure the navigation is visible
await browser.elementByCss('#nav')
// Wait for 500ms to ensure all links are visible
await setTimeout(500) // Wait for 500ms to ensure all links are visible
await setTimeout(500)
// Scroll to bottom to ensure all links enter viewport and trigger prefetches
await browser.eval('window.scrollTo(0, document.body.scrollHeight)') // Scroll to bottom to ensure all links enter viewport and trigger prefetches
await browser.eval('window.scrollTo(0, document.body.scrollHeight)')
// Wait for 500ms to ensure all links are visible
await setTimeout(500) // Wait for 500ms to ensure all links are visible
}, await setTimeout(500)
// If we're in development, we don't have any prefetching to wait for. },
isNextDev ? 'no-requests' : undefined // If we're in development, we don't have any prefetching to wait for.
) isNextDev ? 'no-requests' : undefined
)
} else {
// Most assertions only need the nav revealed, and should not block on
// background prefetch request completion.
await browser.elementByCss('#reveal').click()
await browser.elementByCss('#nav')
await setTimeout(500)
await browser.eval('window.scrollTo(0, document.body.scrollHeight)')
await setTimeout(500)
}
return { act, browser } return { act, browser }
} }
...@@ -52,7 +72,7 @@ describe('parallel-routes-root-param-dynamic-child', () => { ...@@ -52,7 +72,7 @@ describe('parallel-routes-root-param-dynamic-child', () => {
if (!isNextDev) { if (!isNextDev) {
describe('Prefetching', () => { describe('Prefetching', () => {
it('prefetches the 404 pages correctly', async () => { it('prefetches the 404 pages correctly', async () => {
await createBrowserActor('/en') await createBrowserActor('/en', { waitForPrefetch: true })
// If we got here without errors, the prefetch responses completed successfully // If we got here without errors, the prefetch responses completed successfully
// without problematic redirects (like 307). Those will throw because // without problematic redirects (like 307). Those will throw because
...@@ -67,14 +87,16 @@ describe('parallel-routes-root-param-dynamic-child', () => { ...@@ -67,14 +87,16 @@ describe('parallel-routes-root-param-dynamic-child', () => {
async (locale) => { async (locale) => {
const { browser } = await createBrowserActor(`/${locale}`) const { browser } = await createBrowserActor(`/${locale}`)
expect(await browser.elementByCss('#locale-page').text()).toBe( await retry(async () => {
`Locale: ${locale}` expect(await browser.elementByCss('#locale-page').text()).toBe(
) `Locale: ${locale}`
)
})
} }
) )
it('should render a 404 for /es (not in generateStaticParams)', async () => { it('should render a 404 for /es (not in generateStaticParams)', async () => {
const { browser } = await createBrowserActor('/es', true) const { browser } = await createBrowserActor('/es', { errorPage: true })
expect(await browser.elementByCss('.next-error-h1').text()).toBe('404') expect(await browser.elementByCss('.next-error-h1').text()).toBe('404')
}) })
...@@ -92,12 +114,14 @@ describe('parallel-routes-root-param-dynamic-child', () => { ...@@ -92,12 +114,14 @@ describe('parallel-routes-root-param-dynamic-child', () => {
.click() .click()
}) })
expect(await browser.elementByCss('#story-locale').text()).toBe( await retry(async () => {
`Locale: ${locale}` expect(await browser.elementByCss('#story-locale').text()).toBe(
) `Locale: ${locale}`
expect(await browser.elementByCss('#story-slug').text()).toBe( )
'Story: dynamic-123' expect(await browser.elementByCss('#story-slug').text()).toBe(
) 'Story: dynamic-123'
)
})
} }
) )
...@@ -130,12 +154,14 @@ describe('parallel-routes-root-param-dynamic-child', () => { ...@@ -130,12 +154,14 @@ describe('parallel-routes-root-param-dynamic-child', () => {
.click() .click()
}) })
expect(await browser.elementByCss('#story-locale').text()).toBe( await retry(async () => {
`Locale: ${locale}` expect(await browser.elementByCss('#story-locale').text()).toBe(
) `Locale: ${locale}`
expect(await browser.elementByCss('#story-slug').text()).toBe( )
'Story: static-123' expect(await browser.elementByCss('#story-slug').text()).toBe(
) 'Story: static-123'
)
})
} }
) )
...@@ -157,9 +183,11 @@ describe('parallel-routes-root-param-dynamic-child', () => { ...@@ -157,9 +183,11 @@ describe('parallel-routes-root-param-dynamic-child', () => {
.click() .click()
}) })
expect(await browser.elementByCss('.next-error-h1').text()).toBe( await retry(async () => {
'404' expect(await browser.elementByCss('.next-error-h1').text()).toBe(
) '404'
)
})
} }
) )
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { createRouterAct } from 'router-act' import { retry } from 'next-test-utils'
describe('navigating without a prefetch', () => { describe('navigating without a prefetch', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -7,23 +7,18 @@ describe('navigating without a prefetch', () => { ...@@ -7,23 +7,18 @@ describe('navigating without a prefetch', () => {
}) })
it('can show a loading boundary from the dynamic response', async () => { it('can show a loading boundary from the dynamic response', async () => {
let act: ReturnType<typeof createRouterAct> const browser = await next.browser('/')
const browser = await next.browser('/', {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
// Navigate to a dynamic page with a `loading.tsx` without a prefetch. // Navigate to a dynamic page with a `loading.tsx` without a prefetch.
await act(async () => { await browser.elementByCss('a[href="/with-loading"]').click()
await browser.elementByCss('a[href="/with-loading"]').click()
})
// The page suspends on the client, so we should display the `loading` that we got from the dynamic response. // The page suspends on the client, so we should display the `loading` that we got from the dynamic response.
expect( await retry(async () => {
await browser expect(
.elementByCss('#loading-component', { state: 'visible' }) await browser
.text() .elementByCss('#loading-component', { state: 'visible' })
).toContain('Loading...') .text()
).toContain('Loading...')
})
}) })
}) })
This diff is collapsed.
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