Unverified Commit 9f72146d authored by Leah's avatar Leah Committed by GitHub

fix(turbopack): don't emit issues for deleted pages (#62012)

### What?

We now keep track of all client assets emitted for each route in
`ClientAssetMapper` and remove all issues associated with them when a
route get deleted.

Fixes #61384  
Closes PACK-2487
parent 603b3771
......@@ -3,8 +3,8 @@ use std::{ops::Deref, sync::Arc};
use anyhow::Result;
use napi::{bindgen_prelude::External, JsFunction};
use next_api::{
paths::ServerPath,
route::{Endpoint, WrittenEndpoint},
server_paths::ServerPath,
};
use tracing::Instrument;
use turbo_tasks::{ReadRef, Vc};
......@@ -28,10 +28,10 @@ pub struct NapiServerPath {
pub content_hash: String,
}
impl From<&ServerPath> for NapiServerPath {
fn from(server_path: &ServerPath) -> Self {
impl From<ServerPath> for NapiServerPath {
fn from(server_path: ServerPath) -> Self {
Self {
path: server_path.path.clone(),
path: server_path.path,
content_hash: format!("{:x}", server_path.content_hash),
}
}
......@@ -42,25 +42,32 @@ impl From<&ServerPath> for NapiServerPath {
pub struct NapiWrittenEndpoint {
pub r#type: String,
pub entry_path: Option<String>,
pub server_paths: Option<Vec<NapiServerPath>>,
pub client_paths: Vec<String>,
pub server_paths: Vec<NapiServerPath>,
pub config: NapiEndpointConfig,
}
impl From<&WrittenEndpoint> for NapiWrittenEndpoint {
fn from(written_endpoint: &WrittenEndpoint) -> Self {
impl From<WrittenEndpoint> for NapiWrittenEndpoint {
fn from(written_endpoint: WrittenEndpoint) -> Self {
match written_endpoint {
WrittenEndpoint::NodeJs {
server_entry_path,
server_paths,
client_paths,
} => Self {
r#type: "nodejs".to_string(),
entry_path: Some(server_entry_path.clone()),
server_paths: Some(server_paths.iter().map(From::from).collect()),
entry_path: Some(server_entry_path),
client_paths,
server_paths: server_paths.into_iter().map(From::from).collect(),
..Default::default()
},
WrittenEndpoint::Edge { server_paths } => Self {
WrittenEndpoint::Edge {
server_paths,
client_paths,
} => Self {
r#type: "edge".to_string(),
server_paths: Some(server_paths.iter().map(From::from).collect()),
client_paths,
server_paths: server_paths.into_iter().map(From::from).collect(),
..Default::default()
},
}
......@@ -127,7 +134,7 @@ pub async fn endpoint_write_to_disk(
.await
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))?;
Ok(TurbopackResult {
result: NapiWrittenEndpoint::from(&*written),
result: NapiWrittenEndpoint::from(written.clone_value()),
issues: issues.iter().map(|i| NapiIssue::from(&**i)).collect(),
diagnostics: diags.iter().map(|d| NapiDiagnostic::from(d)).collect(),
})
......
......@@ -63,11 +63,13 @@ use crate::{
DynamicImportedChunks,
},
font::create_font_manifest,
middleware::{get_js_paths_from_root, get_wasm_paths_from_root, wasm_paths_to_bindings},
paths::{
all_paths_in_root, all_server_paths, get_js_paths_from_root, get_wasm_paths_from_root,
wasm_paths_to_bindings,
},
project::Project,
route::{AppPageRoute, Endpoint, Route, Routes, WrittenEndpoint},
server_actions::create_server_actions_manifest,
server_paths::all_server_paths,
};
#[turbo_tasks::value]
......@@ -1110,16 +1112,21 @@ impl Endpoint for AppEndpoint {
let node_root_ref = &node_root.await?;
let node_root = this.app_project.project().node_root();
this.app_project
.project()
.emit_all_output_assets(Vc::cell(output_assets))
.await?;
let node_root = this.app_project.project().node_root();
let server_paths = all_server_paths(output_assets, node_root)
.await?
.clone_value();
let client_relative_root = this.app_project.project().client_relative_path();
let client_paths = all_paths_in_root(output_assets, client_relative_root)
.await?
.clone_value();
let written_endpoint = match *output.await? {
AppEndpointOutput::NodeJs { rsc_chunk, .. } => WrittenEndpoint::NodeJs {
server_entry_path: node_root_ref
......@@ -1127,8 +1134,12 @@ impl Endpoint for AppEndpoint {
.context("Node.js chunk entry path must be inside the node root")?
.to_string(),
server_paths,
client_paths,
},
AppEndpointOutput::Edge { .. } => WrittenEndpoint::Edge {
server_paths,
client_paths,
},
AppEndpointOutput::Edge { .. } => WrittenEndpoint::Edge { server_paths },
};
Ok(written_endpoint.cell())
}
......
......@@ -10,7 +10,7 @@ use turbopack_binding::{
},
};
use crate::middleware::get_font_paths_from_root;
use crate::paths::get_font_paths_from_root;
pub(crate) async fn create_font_manifest(
client_root: Vc<FileSystemPath>,
......
......@@ -26,10 +26,11 @@ use turbopack_binding::{
};
use crate::{
middleware::{get_js_paths_from_root, get_wasm_paths_from_root, wasm_paths_to_bindings},
paths::{
all_server_paths, get_js_paths_from_root, get_wasm_paths_from_root, wasm_paths_to_bindings,
},
project::Project,
route::{Endpoint, WrittenEndpoint},
server_paths::all_server_paths,
};
#[turbo_tasks::value]
......@@ -202,7 +203,11 @@ impl Endpoint for InstrumentationEndpoint {
.await?
.clone_value();
Ok(WrittenEndpoint::Edge { server_paths }.cell())
Ok(WrittenEndpoint::Edge {
server_paths,
client_paths: vec![],
}
.cell())
}
.instrument(span)
.await
......
......@@ -8,10 +8,10 @@ mod font;
mod instrumentation;
mod middleware;
mod pages;
pub mod paths;
pub mod project;
pub mod route;
mod server_actions;
pub mod server_paths;
mod versioned_content_map;
// Declare build-time information variables generated in build.rs
......
......@@ -3,23 +3,21 @@ use next_core::{
all_assets_from_entries,
middleware::get_middleware_module,
next_edge::entry::wrap_edge_entry,
next_manifests::{
AssetBinding, EdgeFunctionDefinition, MiddlewareMatcher, MiddlewaresManifestV2,
},
next_manifests::{EdgeFunctionDefinition, MiddlewareMatcher, MiddlewaresManifestV2},
next_server::{get_server_runtime_entries, ServerContextType},
util::parse_config_from_source,
};
use tracing::Instrument;
use turbo_tasks::{Completion, TryFlatJoinIterExt, Value, Vc};
use turbo_tasks::{Completion, Value, Vc};
use turbopack_binding::{
turbo::tasks_fs::{File, FileContent, FileSystemPath},
turbo::tasks_fs::{File, FileContent},
turbopack::{
core::{
asset::AssetContent,
chunk::{availability_info::AvailabilityInfo, ChunkingContextExt},
context::AssetContext,
module::Module,
output::{OutputAsset, OutputAssets},
output::OutputAssets,
reference_type::{EntryReferenceSubType, ReferenceType},
source::Source,
virtual_output::VirtualOutputAsset,
......@@ -29,9 +27,12 @@ use turbopack_binding::{
};
use crate::{
paths::{
all_paths_in_root, all_server_paths, get_js_paths_from_root, get_wasm_paths_from_root,
wasm_paths_to_bindings,
},
project::Project,
route::{Endpoint, WrittenEndpoint},
server_paths::all_server_paths,
};
#[turbo_tasks::value]
......@@ -197,7 +198,17 @@ impl Endpoint for MiddlewareEndpoint {
.await?
.clone_value();
Ok(WrittenEndpoint::Edge { server_paths }.cell())
// Middleware could in theory have a client path (e.g. `new URL`).
let client_relative_root = this.project.client_relative_path();
let client_paths = all_paths_in_root(output_assets, client_relative_root)
.await?
.clone_value();
Ok(WrittenEndpoint::Edge {
server_paths,
client_paths,
}
.cell())
}
.instrument(span)
.await
......@@ -213,94 +224,3 @@ impl Endpoint for MiddlewareEndpoint {
Completion::immutable()
}
}
pub(crate) async fn get_paths_from_root(
root: &FileSystemPath,
output_assets: &[Vc<Box<dyn OutputAsset>>],
filter: impl FnOnce(&str) -> bool + Copy,
) -> Result<Vec<String>> {
output_assets
.iter()
.map({
move |&file| async move {
let path = &*file.ident().path().await?;
let Some(relative) = root.get_path_to(path) else {
return Ok(None);
};
Ok(if filter(relative) {
Some(relative.to_string())
} else {
None
})
}
})
.try_flat_join()
.await
}
pub(crate) async fn get_js_paths_from_root(
root: &FileSystemPath,
output_assets: &[Vc<Box<dyn OutputAsset>>],
) -> Result<Vec<String>> {
get_paths_from_root(root, output_assets, |path| path.ends_with(".js")).await
}
pub(crate) async fn get_wasm_paths_from_root(
root: &FileSystemPath,
output_assets: &[Vc<Box<dyn OutputAsset>>],
) -> Result<Vec<String>> {
get_paths_from_root(root, output_assets, |path| path.ends_with(".wasm")).await
}
pub(crate) async fn get_font_paths_from_root(
root: &FileSystemPath,
output_assets: &[Vc<Box<dyn OutputAsset>>],
) -> Result<Vec<String>> {
get_paths_from_root(root, output_assets, |path| {
path.ends_with(".woff")
|| path.ends_with(".woff2")
|| path.ends_with(".eot")
|| path.ends_with(".ttf")
|| path.ends_with(".otf")
})
.await
}
fn get_file_stem(path: &str) -> &str {
let file_name = if let Some((_, file_name)) = path.rsplit_once('/') {
file_name
} else {
path
};
if let Some((stem, _)) = file_name.split_once('.') {
if stem.is_empty() {
file_name
} else {
stem
}
} else {
file_name
}
}
pub(crate) fn wasm_paths_to_bindings(paths: Vec<String>) -> Vec<AssetBinding> {
paths
.into_iter()
.map(|path| {
let stem = get_file_stem(&path);
// very simple escaping just replacing unsupported characters with `_`
let escaped = stem.replace(
|c: char| !c.is_ascii_alphanumeric() && c != '$' && c != '_',
"_",
);
AssetBinding {
name: format!("wasm_{}", escaped),
file_path: path,
}
})
.collect()
}
......@@ -72,10 +72,12 @@ use crate::{
DynamicImportedChunks,
},
font::create_font_manifest,
middleware::{get_js_paths_from_root, get_wasm_paths_from_root, wasm_paths_to_bindings},
paths::{
all_paths_in_root, all_server_paths, get_js_paths_from_root, get_wasm_paths_from_root,
wasm_paths_to_bindings,
},
project::Project,
route::{Endpoint, Route, Routes, WrittenEndpoint},
server_paths::all_server_paths,
};
#[turbo_tasks::value]
......@@ -1171,6 +1173,11 @@ impl Endpoint for PageEndpoint {
.await?
.clone_value();
let client_relative_root = this.pages_project.project().client_relative_path();
let client_paths = all_paths_in_root(output_assets, client_relative_root)
.await?
.clone_value();
let node_root = &node_root.await?;
let written_endpoint = match *output.await? {
PageEndpointOutput::NodeJs { entry_chunk, .. } => WrittenEndpoint::NodeJs {
......@@ -1179,8 +1186,12 @@ impl Endpoint for PageEndpoint {
.context("ssr chunk entry path must be inside the node root")?
.to_string(),
server_paths,
client_paths,
},
PageEndpointOutput::Edge { .. } => WrittenEndpoint::Edge {
server_paths,
client_paths,
},
PageEndpointOutput::Edge { .. } => WrittenEndpoint::Edge { server_paths },
};
Ok(written_endpoint.cell())
......
use anyhow::Result;
use next_core::all_assets_from_entries;
use next_core::{all_assets_from_entries, next_manifests::AssetBinding};
use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, TryFlatJoinIterExt, Vc};
use turbopack_binding::{
......@@ -24,7 +24,7 @@ pub struct ServerPaths(Vec<ServerPath>);
/// Return a list of all server paths with filename and hash for all output
/// assets references from the `assets` list. Server paths are identified by
/// being inside of `node_root`.
/// being inside `node_root`.
#[turbo_tasks::function]
pub async fn all_server_paths(
assets: Vc<OutputAssets>,
......@@ -55,3 +55,109 @@ pub async fn all_server_paths(
.await?,
))
}
/// Return a list of relative paths to `root` for all output assets references
/// from the `assets` list which are located inside the root path.
#[turbo_tasks::function]
pub async fn all_paths_in_root(
assets: Vc<OutputAssets>,
root: Vc<FileSystemPath>,
) -> Result<Vc<Vec<String>>> {
let all_assets = &*all_assets_from_entries(assets).await?;
let root = &*root.await?;
Ok(Vc::cell(
get_paths_from_root(root, all_assets, |_| true).await?,
))
}
pub(crate) async fn get_paths_from_root(
root: &FileSystemPath,
output_assets: &[Vc<Box<dyn OutputAsset>>],
filter: impl FnOnce(&str) -> bool + Copy,
) -> Result<Vec<String>> {
output_assets
.iter()
.map({
move |&file| async move {
let path = &*file.ident().path().await?;
let Some(relative) = root.get_path_to(path) else {
return Ok(None);
};
Ok(if filter(relative) {
Some(relative.to_string())
} else {
None
})
}
})
.try_flat_join()
.await
}
pub(crate) async fn get_js_paths_from_root(
root: &FileSystemPath,
output_assets: &[Vc<Box<dyn OutputAsset>>],
) -> Result<Vec<String>> {
get_paths_from_root(root, output_assets, |path| path.ends_with(".js")).await
}
pub(crate) async fn get_wasm_paths_from_root(
root: &FileSystemPath,
output_assets: &[Vc<Box<dyn OutputAsset>>],
) -> Result<Vec<String>> {
get_paths_from_root(root, output_assets, |path| path.ends_with(".wasm")).await
}
pub(crate) async fn get_font_paths_from_root(
root: &FileSystemPath,
output_assets: &[Vc<Box<dyn OutputAsset>>],
) -> Result<Vec<String>> {
get_paths_from_root(root, output_assets, |path| {
path.ends_with(".woff")
|| path.ends_with(".woff2")
|| path.ends_with(".eot")
|| path.ends_with(".ttf")
|| path.ends_with(".otf")
})
.await
}
fn get_file_stem(path: &str) -> &str {
let file_name = if let Some((_, file_name)) = path.rsplit_once('/') {
file_name
} else {
path
};
if let Some((stem, _)) = file_name.split_once('.') {
if stem.is_empty() {
file_name
} else {
stem
}
} else {
file_name
}
}
pub(crate) fn wasm_paths_to_bindings(paths: Vec<String>) -> Vec<AssetBinding> {
paths
.into_iter()
.map(|path| {
let stem = get_file_stem(&path);
// very simple escaping just replacing unsupported characters with `_`
let escaped = stem.replace(
|c: char| !c.is_ascii_alphanumeric() && c != '$' && c != '_',
"_",
);
AssetBinding {
name: format!("wasm_{}", escaped),
file_path: path,
}
})
.collect()
}
......@@ -3,7 +3,7 @@ use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, Completion, Vc};
use crate::server_paths::ServerPath;
use crate::paths::ServerPath;
#[derive(TraceRawVcs, Serialize, Deserialize, PartialEq, Eq, ValueDebugFormat, Clone, Debug)]
pub struct AppPageRoute {
......@@ -78,15 +78,17 @@ pub trait Endpoint {
}
#[turbo_tasks::value(shared)]
#[derive(Debug)]
#[derive(Debug, Clone)]
pub enum WrittenEndpoint {
NodeJs {
/// Relative to the root_path
server_entry_path: String,
server_paths: Vec<ServerPath>,
client_paths: Vec<String>,
},
Edge {
server_paths: Vec<ServerPath>,
client_paths: Vec<String>,
},
}
......
/* eslint-disable @typescript-eslint/no-use-before-define */
import path from 'path'
import { pathToFileURL } from 'url'
import { platform, arch } from 'os'
import { arch, platform } from 'os'
import { platformArchTriples } from 'next/dist/compiled/@napi-rs/triples'
import * as Log from '../output/log'
import { getParserOptions } from './options'
import { eventSwcLoadFailure } from '../../telemetry/events/swc-load-failure'
import { patchIncorrectLockfile } from '../../lib/patch-incorrect-lockfile'
import { downloadWasmSwc, downloadNativeNextSwc } from '../../lib/download-swc'
import { downloadNativeNextSwc, downloadWasmSwc } from '../../lib/download-swc'
import type { NextConfigComplete, TurboRule } from '../../server/config-shared'
import { isDeepStrictEqual } from 'util'
import { getDefineEnv } from '../webpack/plugins/define-env-plugin'
import type { DefineEnvPluginOptions } from '../webpack/plugins/define-env-plugin'
import { getDefineEnv } from '../webpack/plugins/define-env-plugin'
import type { PageExtensions } from '../page-extensions-type'
const nextVersion = process.env.__NEXT_VERSION as string
......@@ -718,13 +718,17 @@ export type WrittenEndpoint =
type: 'nodejs'
/** The entry path for the endpoint. */
entryPath: string
/** All server paths that has been written for the endpoint. */
/** All client paths that have been written for the endpoint. */
clientPaths: string[]
/** All server paths that have been written for the endpoint. */
serverPaths: ServerPath[]
config: EndpointConfig
}
| {
type: 'edge'
/** All server paths that has been written for the endpoint. */
/** All client paths that have been written for the endpoint. */
clientPaths: string[]
/** All server paths that have been written for the endpoint. */
serverPaths: ServerPath[]
config: EndpointConfig
}
......@@ -1011,21 +1015,17 @@ function bindingToApi(binding: any, _wasm: boolean) {
}
hmrEvents(identifier: string) {
const subscription = subscribe<TurbopackResult<Update>>(
true,
async (callback) =>
binding.projectHmrEvents(this._nativeProject, identifier, callback)
return subscribe<TurbopackResult<Update>>(true, async (callback) =>
binding.projectHmrEvents(this._nativeProject, identifier, callback)
)
return subscription
}
hmrIdentifiersSubscribe() {
const subscription = subscribe<TurbopackResult<HmrIdentifiers>>(
return subscribe<TurbopackResult<HmrIdentifiers>>(
false,
async (callback) =>
binding.projectHmrIdentifiersSubscribe(this._nativeProject, callback)
)
return subscription
}
traceSource(
......@@ -1226,8 +1226,7 @@ async function loadWasm(importPath = '') {
: Promise.resolve(bindings.parseSync(src.toString(), options))
},
parseSync(src: string, options: any) {
const astStr = bindings.parseSync(src.toString(), options)
return astStr
return bindings.parseSync(src.toString(), options)
},
getTargetTriple() {
return undefined
......@@ -1404,11 +1403,10 @@ function loadNative(importPath?: string) {
turbo: {
startTrace: (options = {}, turboTasks: unknown) => {
initHeapProfiler()
const ret = (customBindings ?? bindings).runTurboTracing(
return (customBindings ?? bindings).runTurboTracing(
toBuffer({ exact: true, ...options }),
turboTasks
)
return ret
},
createTurboTasks: (memoryLimit?: number): unknown =>
bindings.createTurboTasks(memoryLimit),
......@@ -1468,7 +1466,7 @@ function loadNative(importPath?: string) {
/// Build a mdx options object contains default values that
/// can be parsed with serde_wasm_bindgen.
function getMdxOptions(options: any = {}) {
const ret = {
return {
...options,
development: options.development ?? false,
jsx: options.jsx ?? false,
......@@ -1477,8 +1475,6 @@ function getMdxOptions(options: any = {}) {
mathTextSingleDollar: true,
},
}
return ret
}
function toBuffer(t: any) {
......
......@@ -15,7 +15,7 @@ import type {
TurbopackConnectedAction,
} from './hot-reloader-types'
import { HMR_ACTIONS_SENT_TO_BROWSER } from './hot-reloader-types'
import type { Issue, Update as TurbopackUpdate } from '../../build/swc'
import type { Update as TurbopackUpdate } from '../../build/swc'
import {
createDefineEnv,
type Endpoint,
......@@ -43,13 +43,16 @@ import { denormalizePagePath } from '../../shared/lib/page-path/denormalize-page
import { trace } from '../../trace'
import type { VersionInfo } from './parse-version-info'
import {
AssetMapper,
type ChangeSubscriptions,
type ClientState,
type EntryIssuesMap,
formatIssue,
getTurbopackJsConfig,
handleEntrypoints,
handlePagesErrorRoute,
handleRouteType,
hasEntrypointForKey,
msToNs,
processIssues,
type ReadyIds,
......@@ -164,6 +167,8 @@ export async function createHotReloaderTurbopack(
(resolve) => (currentEntriesHandlingResolve = resolve)
)
const assetMapper = new AssetMapper()
function clearRequireCache(
key: EntryKey,
writtenEndpoint: WrittenEndpoint
......@@ -216,6 +221,7 @@ export async function createHotReloaderTurbopack(
return
}
const buildingIds = new Set()
const startBuilding: StartBuilding = (id, requestUrl, forceRebuild) => {
......@@ -252,31 +258,42 @@ export async function createHotReloaderTurbopack(
let hmrEventHappened = false
let hmrHash = 0
const sendEnqueuedMessages = () => {
const clients = new Set<ws>()
const clientStates = new WeakMap<ws, ClientState>()
function sendToClient(client: ws, payload: HMR_ACTION_TYPES) {
client.send(JSON.stringify(payload))
}
function sendEnqueuedMessages() {
for (const [, issueMap] of currentEntryIssues) {
if (issueMap.size > 0) {
// During compilation errors we want to delay the HMR events until errors are fixed
return
}
}
for (const client of clients) {
const state = clientStates.get(client)
if (!state) continue
if (!state) {
continue
}
for (const [, issueMap] of state.clientIssues) {
if (issueMap.size > 0) {
// During compilation errors we want to delay the HMR events until errors are fixed
return
}
}
const sendToClient = (payload: any) => {
client.send(JSON.stringify(payload))
}
for (const payload of state.hmrPayloads.values()) {
sendToClient(payload)
sendToClient(client, payload)
}
state.hmrPayloads.clear()
if (state.turbopackUpdates.length > 0) {
sendToClient({
sendToClient(client, {
action: HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE,
data: state.turbopackUpdates,
})
......@@ -288,45 +305,35 @@ export async function createHotReloaderTurbopack(
const sendHmr: SendHmr = (id: string, payload: HMR_ACTION_TYPES) => {
for (const client of clients) {
const state = clientStates.get(client)
if (!state) continue
state.hmrPayloads.set(`${id}`, payload)
clientStates.get(client)?.hmrPayloads.set(id, payload)
}
hmrEventHappened = true
sendEnqueuedMessagesDebounce()
}
function sendTurbopackMessage(payload: TurbopackUpdate) {
for (const client of clients) {
const state = clientStates.get(client)
if (!state) continue
state.turbopackUpdates.push(payload)
clientStates.get(client)?.turbopackUpdates.push(payload)
}
hmrEventHappened = true
sendEnqueuedMessagesDebounce()
}
type ClientState = {
clientIssues: EntryIssuesMap
hmrPayloads: Map<string, HMR_ACTION_TYPES>
turbopackUpdates: TurbopackUpdate[]
subscriptions: Map<string, AsyncIterator<any>>
}
const clients = new Set<ws>()
const clientStates = new WeakMap<ws, ClientState>()
async function subscribeToChanges(
key: EntryKey,
includeIssues: boolean,
endpoint: Endpoint | undefined,
endpoint: Endpoint,
makePayload: (
change: TurbopackResult
) => Promise<HMR_ACTION_TYPES> | HMR_ACTION_TYPES | void
) {
const { side } = splitEntryKey(key)
if (changeSubscriptions.has(key)) {
return
}
if (!endpoint || changeSubscriptions.has(key)) return
const { side } = splitEntryKey(key)
const changedPromise = endpoint[`${side}Changed`](includeIssues)
changeSubscriptions.set(key, changedPromise)
......@@ -351,15 +358,20 @@ export async function createHotReloaderTurbopack(
}
async function subscribeToHmrEvents(client: ws, id: string) {
const key = getEntryKey('assets', 'client', id)
if (!hasEntrypointForKey(currentEntrypoints, key, assetMapper)) {
// maybe throw an error / force the client to reload?
return
}
const state = clientStates.get(client)
if (!state) return
if (state.subscriptions.has(id)) return
if (!state || state.subscriptions.has(id)) {
return
}
const subscription = project!.hmrEvents(id)
state.subscriptions.set(id, subscription)
const key = getEntryKey('assets', 'client', id)
// The subscription will always emit once, which is the initial
// computation. This is not a change, so swallow it.
try {
......@@ -379,7 +391,7 @@ export async function createHotReloaderTurbopack(
const reloadAction: ReloadPageAction = {
action: HMR_ACTIONS_SENT_TO_BROWSER.RELOAD_PAGE,
}
client.send(JSON.stringify(reloadAction))
sendToClient(client, reloadAction)
client.close()
return
}
......@@ -387,9 +399,13 @@ export async function createHotReloaderTurbopack(
function unsubscribeFromHmrEvents(client: ws, id: string) {
const state = clientStates.get(client)
if (!state) return
if (!state) {
return
}
const subscription = state.subscriptions.get(id)
subscription?.return!()
const key = getEntryKey('assets', 'client', id)
state.clientIssues.delete(key)
}
......@@ -408,22 +424,29 @@ export async function createHotReloaderTurbopack(
currentEntrypoints,
changeSubscriptions,
currentEntryIssues: currentEntryIssues,
manifestLoader,
nextConfig: opts.nextConfig,
rewrites: opts.fsChecker.rewrites,
serverFields,
hooks: {
handleWrittenEndpoint: (id, result) => {
clearRequireCache(id, result)
dev: {
assetMapper,
changeSubscriptions,
clients,
clientStates,
serverFields,
hooks: {
handleWrittenEndpoint: (id, result) => {
clearRequireCache(id, result)
},
propagateServerField: propagateServerField.bind(null, opts),
sendHmr,
startBuilding,
subscribeToChanges,
unsubscribeFromChanges,
unsubscribeFromHmrEvents,
},
propagateServerField: propagateServerField.bind(null, opts),
sendHmr,
startBuilding,
subscribeToChanges,
unsubscribeFromChanges,
},
})
......@@ -496,6 +519,7 @@ export async function createHotReloaderTurbopack(
turbopackUpdates: [],
subscriptions,
})
client.on('close', () => {
// Remove active subscriptions
for (const subscription of subscriptions.values()) {
......@@ -579,18 +603,17 @@ export async function createHotReloaderTurbopack(
const turbopackConnected: TurbopackConnectedAction = {
action: HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_CONNECTED,
}
client.send(JSON.stringify(turbopackConnected))
sendToClient(client, turbopackConnected)
const errors: CompilationError[] = []
const addIssues = (entryIssues: Map<string, Issue>) => {
for (const entryIssues of currentEntryIssues.values()) {
for (const issue of entryIssues.values()) {
errors.push({
message: formatIssue(issue),
})
}
}
clientIssues.forEach(addIssues)
currentEntryIssues.forEach(addIssues)
const sync: SyncAction = {
action: HMR_ACTIONS_SENT_TO_BROWSER.SYNC,
......@@ -600,7 +623,7 @@ export async function createHotReloaderTurbopack(
versionInfo,
}
this.send(sync)
sendToClient(client, sync)
})
},
......@@ -697,6 +720,7 @@ export async function createHotReloaderTurbopack(
subscribeToChanges,
handleWrittenEndpoint: (id, result) => {
clearRequireCache(id, result)
assetMapper.setPathsForKey(id, result.clientPaths)
},
},
})
......@@ -748,6 +772,7 @@ export async function createHotReloaderTurbopack(
subscribeToChanges,
handleWrittenEndpoint: (id, result) => {
clearRequireCache(id, result)
assetMapper.setPathsForKey(id, result.clientPaths)
},
},
})
......@@ -779,11 +804,10 @@ export async function createHotReloaderTurbopack(
case 'end': {
sendEnqueuedMessages()
const errors = new Map<string, CompilationError>()
const addErrors = (
function addErrors(
errorsMap: Map<string, CompilationError>,
issues: EntryIssuesMap
) => {
) {
for (const issueMap of issues.values()) {
for (const [key, issue] of issueMap) {
if (errorsMap.has(key)) continue
......@@ -799,22 +823,25 @@ export async function createHotReloaderTurbopack(
}
}
}
const errors = new Map<string, CompilationError>()
addErrors(errors, currentEntryIssues)
for (const client of clients) {
const state = clientStates.get(client)
if (!state) continue
if (!state) {
continue
}
const clientErrors = new Map(errors)
addErrors(clientErrors, state.clientIssues)
client.send(
JSON.stringify({
action: HMR_ACTIONS_SENT_TO_BROWSER.BUILT,
hash: String(++hmrHash),
errors: [...clientErrors.values()],
warnings: [],
})
)
sendToClient(client, {
action: HMR_ACTIONS_SENT_TO_BROWSER.BUILT,
hash: String(++hmrHash),
errors: [...clientErrors.values()],
warnings: [],
})
}
if (hmrEventHappened) {
......
......@@ -10,6 +10,7 @@ import type {
Issue,
StyledString,
TurbopackResult,
Update as TurbopackUpdate,
WrittenEndpoint,
} from '../../build/swc'
import {
......@@ -30,6 +31,7 @@ import {
getEntryKey,
splitEntryKey,
} from './turbopack/entry-key'
import type ws from 'next/dist/compiled/ws'
export async function getTurbopackJsConfig(
dir: string,
......@@ -199,7 +201,7 @@ export type HandleWrittenEndpoint = (
export type StartChangeSubscription = (
key: EntryKey,
includeIssues: boolean,
endpoint: Endpoint | undefined,
endpoint: Endpoint,
makePayload: (
change: TurbopackResult
) => Promise<HMR_ACTION_TYPES> | HMR_ACTION_TYPES | void
......@@ -217,6 +219,15 @@ export type StartBuilding = (
export type ReadyIds = Set<string>
export type ClientState = {
clientIssues: EntryIssuesMap
hmrPayloads: Map<string, HMR_ACTION_TYPES>
turbopackUpdates: TurbopackUpdate[]
subscriptions: Map<string, AsyncIterator<any>>
}
export type ClientStateMap = WeakMap<ws, ClientState>
// hooks only used by the dev server.
type HandleRouteTypeHooks = {
handleWrittenEndpoint: HandleWrittenEndpoint
......@@ -423,6 +434,117 @@ export async function handleRouteType({
}
}
/**
* Maintains a mapping between entrypoins and the corresponding client asset paths.
*/
export class AssetMapper {
private entryMap: Map<EntryKey, Set<string>> = new Map()
private assetMap: Map<string, Set<EntryKey>> = new Map()
/**
* Overrides asset paths for a key and updates the mapping from path to key.
*
* @param key
* @param assetPaths asset paths relative to the .next directory
*/
setPathsForKey(key: EntryKey, assetPaths: string[]): void {
this.delete(key)
const newAssetPaths = new Set(assetPaths)
this.entryMap.set(key, newAssetPaths)
for (const assetPath of newAssetPaths) {
let assetPathKeys = this.assetMap.get(assetPath)
if (!assetPathKeys) {
assetPathKeys = new Set()
this.assetMap.set(assetPath, assetPathKeys)
}
assetPathKeys!.add(key)
}
}
/**
* Deletes the key and any asset only referenced by this key.
*
* @param key
*/
delete(key: EntryKey) {
for (const assetPath of this.getAssetPathsByKey(key)) {
const assetPathKeys = this.assetMap.get(assetPath)
assetPathKeys?.delete(key)
if (!assetPathKeys?.size) {
this.assetMap.delete(assetPath)
}
}
this.entryMap.delete(key)
}
getAssetPathsByKey(key: EntryKey): string[] {
return Array.from(this.entryMap.get(key) ?? [])
}
getKeysByAsset(path: string): EntryKey[] {
return Array.from(this.assetMap.get(path) ?? [])
}
keys(): IterableIterator<EntryKey> {
return this.entryMap.keys()
}
}
export function hasEntrypointForKey(
entrypoints: Entrypoints,
key: EntryKey,
assetMapper: AssetMapper | undefined
): boolean {
const { type, page } = splitEntryKey(key)
switch (type) {
case 'app':
return entrypoints.app.has(page)
case 'pages':
switch (page) {
case '_app':
return entrypoints.global.app != null
case '_document':
return entrypoints.global.document != null
case '_error':
return entrypoints.global.error != null
default:
return entrypoints.page.has(page)
}
case 'root':
switch (page) {
case 'middleware':
return entrypoints.global.middleware != null
case 'instrumentation':
return entrypoints.global.instrumentation != null
default:
return false
}
case 'assets':
if (!assetMapper) {
return false
}
return assetMapper
.getKeysByAsset(page)
.some((pageKey) =>
hasEntrypointForKey(entrypoints, pageKey, assetMapper)
)
default: {
// validation that we covered all cases, this should never run.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _: never = type
return false
}
}
}
// hooks only used by the dev server.
type HandleEntrypointsHooks = {
handleWrittenEndpoint: HandleWrittenEndpoint
......@@ -434,6 +556,17 @@ type HandleEntrypointsHooks = {
startBuilding: StartBuilding
subscribeToChanges: StartChangeSubscription
unsubscribeFromChanges: StopChangeSubscription
unsubscribeFromHmrEvents: (client: ws, id: string) => void
}
type HandleEntrypointsDevOpts = {
assetMapper: AssetMapper
changeSubscriptions: ChangeSubscriptions
clients: Set<ws>
clientStates: ClientStateMap
serverFields: ServerFields
hooks: HandleEntrypointsHooks
}
export async function handleEntrypoints({
......@@ -446,10 +579,7 @@ export async function handleEntrypoints({
nextConfig,
rewrites,
changeSubscriptions,
serverFields,
hooks,
dev,
}: {
entrypoints: TurbopackResult<RawEntrypoints>
......@@ -460,10 +590,7 @@ export async function handleEntrypoints({
nextConfig: NextConfigComplete
rewrites: SetupOpts['fsChecker']['rewrites']
changeSubscriptions?: ChangeSubscriptions // dev
serverFields?: ServerFields // dev
hooks?: HandleEntrypointsHooks //dev
dev?: HandleEntrypointsDevOpts
}) {
currentEntrypoints.global.app = entrypoints.pagesAppEndpoint
currentEntrypoints.global.document = entrypoints.pagesDocumentEndpoint
......@@ -499,31 +626,13 @@ export async function handleEntrypoints({
}
}
if (changeSubscriptions) {
for (const [key, subscriptionPromise] of changeSubscriptions) {
const { type, page } = splitEntryKey(key)
// middleware is handled below
if (
(type === 'app' && !currentEntrypoints.page.has(page)) ||
(type === 'pages' && !currentEntrypoints.app.has(page))
) {
const subscription = await subscriptionPromise
await subscription.return?.()
changeSubscriptions.delete(key)
}
}
}
if (dev) {
await handleEntrypointsDevCleanup({
currentEntryIssues,
currentEntrypoints,
for (const [key] of currentEntryIssues) {
const { type, page } = splitEntryKey(key)
if (
(type === 'app' && !currentEntrypoints.page.has(page)) ||
(type === 'pages' && !currentEntrypoints.app.has(page))
) {
currentEntryIssues.delete(key)
}
...dev,
})
}
const { middleware, instrumentation } = entrypoints
......@@ -534,19 +643,19 @@ export async function handleEntrypoints({
if (currentEntrypoints.global.middleware && !middleware) {
const key = getEntryKey('root', 'server', 'middleware')
// Went from middleware to no middleware
await hooks?.unsubscribeFromChanges(key)
await dev?.hooks.unsubscribeFromChanges(key)
currentEntryIssues.delete(key)
hooks?.sendHmr('middleware', {
dev?.hooks.sendHmr('middleware', {
event: HMR_ACTIONS_SENT_TO_BROWSER.MIDDLEWARE_CHANGES,
})
} else if (!currentEntrypoints.global.middleware && middleware) {
// Went from no middleware to middleware
hooks?.sendHmr('middleware', {
dev?.hooks.sendHmr('middleware', {
event: HMR_ACTIONS_SENT_TO_BROWSER.MIDDLEWARE_CHANGES,
})
}
currentEntrypoints.global.middleware = entrypoints.middleware
currentEntrypoints.global.middleware = middleware
if (nextConfig.experimental.instrumentationHook && instrumentation) {
const processInstrumentation = async (
......@@ -556,7 +665,7 @@ export async function handleEntrypoints({
const key = getEntryKey('root', 'server', name)
const writtenEndpoint = await instrumentation[prop].writeToDisk()
hooks?.handleWrittenEndpoint(key, writtenEndpoint)
dev?.hooks.handleWrittenEndpoint(key, writtenEndpoint)
processIssues(currentEntryIssues, key, writtenEndpoint)
}
await processInstrumentation('instrumentation.nodeJs', 'nodeJs')
......@@ -570,19 +679,19 @@ export async function handleEntrypoints({
pageEntrypoints: currentEntrypoints.page,
})
if (serverFields && hooks?.propagateServerField) {
serverFields.actualInstrumentationHookFile = '/instrumentation'
await hooks.propagateServerField(
if (dev) {
dev.serverFields.actualInstrumentationHookFile = '/instrumentation'
await dev.hooks.propagateServerField(
'actualInstrumentationHookFile',
serverFields.actualInstrumentationHookFile
dev.serverFields.actualInstrumentationHookFile
)
}
} else {
if (serverFields && hooks?.propagateServerField) {
serverFields.actualInstrumentationHookFile = undefined
await hooks.propagateServerField(
if (dev) {
dev.serverFields.actualInstrumentationHookFile = undefined
await dev.hooks.propagateServerField(
'actualInstrumentationHookFile',
serverFields.actualInstrumentationHookFile
dev.serverFields.actualInstrumentationHookFile
)
}
}
......@@ -590,13 +699,15 @@ export async function handleEntrypoints({
if (middleware) {
const key = getEntryKey('root', 'server', 'middleware')
const processMiddleware = async () => {
const writtenEndpoint = await middleware.endpoint.writeToDisk()
hooks?.handleWrittenEndpoint(key, writtenEndpoint)
const endpoint = middleware.endpoint
async function processMiddleware() {
const writtenEndpoint = await endpoint.writeToDisk()
dev?.hooks.handleWrittenEndpoint(key, writtenEndpoint)
processIssues(currentEntryIssues, key, writtenEndpoint)
await manifestLoader.loadMiddlewareManifest('middleware', 'middleware')
if (serverFields) {
serverFields.middleware = {
if (dev) {
dev.serverFields.middleware = {
match: null as any,
page: '/',
matchers:
......@@ -606,16 +717,21 @@ export async function handleEntrypoints({
}
await processMiddleware()
hooks?.subscribeToChanges(key, false, middleware.endpoint, async () => {
const finishBuilding = hooks.startBuilding('middleware', undefined, true)
dev?.hooks.subscribeToChanges(key, false, endpoint, async () => {
const finishBuilding = dev.hooks.startBuilding(
'middleware',
undefined,
true
)
await processMiddleware()
if (serverFields && hooks.propagateServerField) {
await hooks.propagateServerField(
'actualMiddlewareFile',
serverFields.actualMiddlewareFile
)
await hooks.propagateServerField('middleware', serverFields.middleware)
}
await dev.hooks.propagateServerField(
'actualMiddlewareFile',
dev.serverFields.actualMiddlewareFile
)
await dev.hooks.propagateServerField(
'middleware',
dev.serverFields.middleware
)
await manifestLoader.writeManifests({
rewrites: rewrites,
pageEntrypoints: currentEntrypoints.page,
......@@ -628,17 +744,81 @@ export async function handleEntrypoints({
manifestLoader.deleteMiddlewareManifest(
getEntryKey('root', 'server', 'middleware')
)
if (serverFields) {
serverFields.actualMiddlewareFile = undefined
serverFields.middleware = undefined
if (dev) {
dev.serverFields.actualMiddlewareFile = undefined
dev.serverFields.middleware = undefined
}
}
if (serverFields && hooks?.propagateServerField) {
await hooks.propagateServerField(
if (dev) {
await dev.hooks.propagateServerField(
'actualMiddlewareFile',
serverFields.actualMiddlewareFile
dev.serverFields.actualMiddlewareFile
)
await dev.hooks.propagateServerField(
'middleware',
dev.serverFields.middleware
)
await hooks.propagateServerField('middleware', serverFields.middleware)
}
}
async function handleEntrypointsDevCleanup({
currentEntryIssues,
currentEntrypoints,
assetMapper,
changeSubscriptions,
clients,
clientStates,
hooks,
}: {
currentEntrypoints: Entrypoints
currentEntryIssues: EntryIssuesMap
} & HandleEntrypointsDevOpts) {
// this needs to be first as `hasEntrypointForKey` uses the `assetMapper`
for (const key of assetMapper.keys()) {
if (!hasEntrypointForKey(currentEntrypoints, key, assetMapper)) {
assetMapper.delete(key)
}
}
for (const key of changeSubscriptions.keys()) {
// middleware is handled separately
if (!hasEntrypointForKey(currentEntrypoints, key, assetMapper)) {
await hooks.unsubscribeFromChanges(key)
}
}
for (const [key] of currentEntryIssues) {
if (!hasEntrypointForKey(currentEntrypoints, key, assetMapper)) {
currentEntryIssues.delete(key)
}
}
for (const client of clients) {
const state = clientStates.get(client)
if (!state) {
continue
}
for (const key of state.clientIssues.keys()) {
if (!hasEntrypointForKey(currentEntrypoints, key, assetMapper)) {
state.clientIssues.delete(key)
}
}
for (const id of state.subscriptions.keys()) {
if (
!hasEntrypointForKey(
currentEntrypoints,
getEntryKey('assets', 'client', id),
assetMapper
)
) {
hooks.unsubscribeFromHmrEvents(client, id)
}
}
}
}
......
......@@ -22,6 +22,9 @@ export function getEntryKey(
return JSON.stringify({ type, side, page }) as EntryKey
}
/**
* Split an `EntryKey` up into its components.
*/
export function splitEntryKey(key: EntryKey): {
type: EntryKeyType
side: EntryKeySide
......
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
import './style.css'
import { Test } from './test'
export default function Page() {
return (
<>
<p>nested hello world</p>
<Test />
</>
)
}
/** dummy file necessary to cause the issue with turbopack */
/** dummy file necessary to cause the issue with turbopack */
export function Test() {
return <>e</>
}
import { join } from 'path'
import { nextTestSetup, FileRef } from 'e2e-utils'
import { hasRedbox } from 'next-test-utils'
import { waitForHydration } from 'development-sandbox'
describe('hmr-deleted-page', () => {
const { next } = nextTestSetup({
files: {
app: new FileRef(join(__dirname, 'app')),
},
})
it('should not show errors for a deleted page', async () => {
const browser = await next.browser('/page')
expect(await browser.elementByCss('p').text()).toBe('nested hello world')
await next.deleteFile('app/page/test.tsx')
await next.deleteFile('app/page/style.css')
await waitForHydration(browser)
expect(await hasRedbox(browser)).toBe(true)
await next.deleteFile('app/page')
await waitForHydration(browser)
expect(await hasRedbox(browser)).toBe(false)
expect(await browser.elementByCss('h1').text()).toBe('404')
})
})
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