Unverified Commit 2ec51132 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Merge branch 'canary' into 03-09-use_for.in_in_createcomponenttree

parents 5c0efcd7 c4457849
......@@ -25,3 +25,7 @@
- [Adding a new feature](./contributing/core/adding-features.md)
- [Developing Using Local App](./contributing/core/developing-using-local-app.md)
<!-- - [Using the VS Code Debugger](./contributing/core/vscode-debugger.md) -->
## Turbopack
- [Tracing](./contributing/turbopack/tracing.md)
......@@ -6,43 +6,107 @@
## Dependencies
- Install Rust and Cargo via [rustup](https://rustup.rs).
- Install the [GitHub CLI](https://github.com/cli/cli#installation).
- Enable pnpm:
### JavaScript Dependencies
_You'll need a working node.js environment with pnpm._
- Install or enable [pnpm](https://pnpm.io/installation):
```
corepack enable pnpm
# or
npm install -g pnpm@latest
```
- (Linux) Install LLD (the LLVM linker) and Clang (used by `rust-rocksdb`):
`pnpm` [respects the `packageManager` field in `package.json` by
default](https://pnpm.io/settings#managepackagemanagerversions), even when
installed without Corepack. This ensures that pnpm behaves the same locally as
it does in CI.
- _(Optional)_ Install [fnm](https://github.com/Schniz/fnm) or
[nvm](https://github.com/nvm-sh/nvm). This will ensure you use the same
version of node as our CI does, via our `.node-version` configuration file.
- _(Optional)_ Install the [GitHub CLI](https://github.com/cli/cli#installation).
### Rust Dependencies
_You can skip these steps if you don't intend to modify any Rust code._
- Install Rust and Cargo via [rustup](https://rustup.rs).
- _(Linux)_ Install a C compiler:
```
sudo apt install lld clang
sudo apt install build-essential
```
- _(macOS)_ Install the Command Line Tools for Xcode package:
```
xcode-select --install
```
## Local Development
1. Clone the Next.js repository (download only recent commits for faster clone):
1. Clone the Next.js repository (using a [blobless clone] for speed):
```
gh repo clone vercel/next.js -- --filter=blob:none --branch canary --single-branch
gh repo clone vercel/next.js -- --filter=blob:none --single-branch
# or, alternatively (via https)
git clone https://github.com/vercel/next.js.git --filter=blob:none --single-branch
# or, alternatively (via ssh)
git clone git@github.com:vercel/next.js.git --filter=blob:none --single-branch
```
1. Create a new branch:
[blobless clone]: https://github.blog/open-source/git/get-up-to-speed-with-partial-clone-and-shallow-clone/#user-content-blobless-clones
1. The default branch is `canary`. Create a new branch off of `canary` with:
```
git checkout -b MY_BRANCH_NAME origin/canary
git switch --create MY_BRANCH_NAME
```
1. Install the dependencies with:
1. Install the Node.js dependencies with:
```
pnpm install
```
1. Start developing and watch for code changes:
1. Start developing and watch for JavaScript code changes using
[Turborepo](https://turborepo.dev/):
```
pnpm dev
pnpm dev # or use `next build` to build on-demand
```
1. If you make Rust changes (e.g. Turbopack), you can build a new napi binding
with:
```
pnpm swc-build-native
# or, if you'd like to build in release mode (e.g. for benchmarking)
pnpm swc-build-native --release
# or, if you'd like to build both JS and Rust changes at once with Turborepo
pnpm build-all
```
1. In a new terminal, run `pnpm types` to compile declaration files from
TypeScript.
_Note: You may need to repeat this step if your types get outdated._
1. When your changes are finished, commit them to the branch:
```
git add .
git commit -m "DESCRIBE_YOUR_CHANGES_HERE"
```
1. To open a pull request you can use the GitHub CLI which automatically forks and sets up a remote branch. Follow the prompts when running:
```
gh pr create
......
# Tracing Turbopack
`turbo-tasks` comes with a tracing feature that allows to keep track of executions and their runtime and memory consumption. This is useful to debug and optimize the performance of Turbopack.
## Logging
Inside of Next.js one can enable tracing with the `NEXT_TURBOPACK_TRACING` environment variable.
It supports [the following special preset values][presets]:
- **`1` or `overview`:** Basic user level tracing is enabled. (This is the only preset available in a published Next.js release)
- **`next`:** Same as `overview`, but with lower-level `debug` and `trace` logs for Next.js's own crates
- **`turbopack`:** Same as `next`, but with lower-level `debug` and `trace` logs for Turbopack's own crates
- **`turbo-tasks`:** Same as `turbopack`, but also with verbose tracing of every Turbo-Engine function execution.
Alternatively, any directives syntax supported by [`tracing_subscriber::filter::EnvFilter`][directives] can be used.
> [!WARNING]
> A normal Next.js canary/stable release only includes the info level tracing. This is the tracing level intended for user-facing tracing.
>
> For the more detailed tracing a custom Next.js build is required. See [Developing] for more information how to create one.
With this environment variable, Next.js will write a `.next/trace-turbopack` file with the tracing information in a binary format.
[presets]: https://github.com/vercel/next.js/blob/c506c0de1d6f17ad400ad5aa85edaae23b6b44d2/packages/next-swc/crates/napi/src/next_api/project.rs#L218
[directives]: https://tracing.rs/tracing_subscriber/filter/struct.envfilter#directives
[Developing]: ../core/developing.md
## Viewer
To visualize the content of `.next/trace-turbopack`, use the [turbo-trace-viewer].
A video showing how to use the tool [is available here][youtube-tutorial].
This tool connects a WebSocket on port 57475 on localhost to connect to the trace-server. You can start the trace-server with the following command:
```sh
cargo run --bin turbo-trace-server --release -- /path/to/your/trace-turbopack
# or
pnpm next internal trace .next/trace-turbopack
```
Once the server is started, open <https://trace.nextjs.org/> in your browser.
> [!TIP]
> Make sure you're using a `--release` build when running the trace server. The trace server is very slow and this can make a very significant (10x) difference in performance.
The trace viewer allows to switch between multiple different visualization modes:
- **Aggregated spans:** Spans with the same name in the same parent are grouped together.
- **Individual spans:** Every span is shown individually.
- **... in order:** Spans are shown in the order they occur.
- **... by value:** Spans are sorted and spans with the largest value are shown first.
- **Bottom-up view:** Instead of showing the total value, the self value is shown.
And there different value modes:
- **Duration:** The CPU time of each span is shown.
- **Allocated Memory:** How much memory was allocated during the span.
- **Allocations:** How many allocations were made during the span.
- **Deallocated Memory:** How much memory was deallocated during the span.
- **Persistently allocated Memory:** How much memory was allocated but not deallocated during the span. It survives the span.
[turbo-trace-viewer]: https://turbo-trace-viewer.vercel.app/
[youtube-tutorial]: https://www.youtube.com/watch?v=PGO2szAye7A
......@@ -63,7 +63,7 @@ use turbopack_core::{
},
output::{OutputAsset, OutputAssets, OutputAssetsWithReferenced},
reference::all_assets_from_entries,
reference_type::{CommonJsReferenceSubType, CssReferenceSubType, ReferenceType},
reference_type::{CommonJsReferenceSubType, CssReferenceSubType, ReferenceTypeCondition},
resolve::{ResolveErrorMode, origin::PlainResolveOrigin, parse::Request, pattern::Pattern},
source::Source,
source_map::SourceMapAsset,
......@@ -388,9 +388,9 @@ impl AppProject {
// CSS Module to the actual CSS
TransitionRule::new(
RuleCondition::all(vec![
RuleCondition::ReferenceType(ReferenceType::Css(
RuleCondition::ReferenceType(ReferenceTypeCondition::Css(Some(
CssReferenceSubType::Inner,
)),
))),
module_styles_rule_condition(),
]),
self.css_client_reference_transition().to_resolved().await?,
......@@ -399,9 +399,9 @@ impl AppProject {
// the list of CSS module classes.
TransitionRule::new(
RuleCondition::all(vec![
RuleCondition::ReferenceType(ReferenceType::Css(
RuleCondition::ReferenceType(ReferenceTypeCondition::Css(Some(
CssReferenceSubType::Analyze,
)),
))),
module_styles_rule_condition(),
]),
ResolvedVc::upcast(self.client_transition().to_resolved().await?),
......@@ -664,9 +664,9 @@ impl AppProject {
// Change context, this is used to determine the list of CSS module classes.
TransitionRule::new(
RuleCondition::all(vec![
RuleCondition::ReferenceType(ReferenceType::Css(
RuleCondition::ReferenceType(ReferenceTypeCondition::Css(Some(
CssReferenceSubType::Analyze,
)),
))),
module_styles_rule_condition(),
]),
ResolvedVc::upcast(self.client_transition().to_resolved().await?),
......@@ -736,9 +736,9 @@ impl AppProject {
// Change context, this is used to determine the list of CSS module classes.
TransitionRule::new(
RuleCondition::all(vec![
RuleCondition::ReferenceType(ReferenceType::Css(
RuleCondition::ReferenceType(ReferenceTypeCondition::Css(Some(
CssReferenceSubType::Analyze,
)),
))),
module_styles_rule_condition(),
]),
ResolvedVc::upcast(self.client_transition().to_resolved().await?),
......
......@@ -367,6 +367,9 @@ pub struct ProjectOptions {
/// The version of Next.js that is running.
pub next_version: RcStr,
/// Whether server-side HMR is enabled (--experimental-server-fast-refresh).
pub server_hmr: bool,
}
#[derive(Default)]
......@@ -797,6 +800,7 @@ impl ProjectContainer {
let debug_build_paths;
let deferred_entries;
let is_persistent_caching_enabled;
let server_hmr;
{
let options = self.options_state.get();
let options = options
......@@ -824,6 +828,7 @@ impl ProjectContainer {
debug_build_paths = options.debug_build_paths.clone();
deferred_entries = options.deferred_entries.clone().unwrap_or_default();
is_persistent_caching_enabled = options.is_persistent_caching_enabled;
server_hmr = options.server_hmr;
}
let dist_dir = next_config.dist_dir().owned().await?;
......@@ -853,6 +858,7 @@ impl ProjectContainer {
debug_build_paths,
deferred_entries,
is_persistent_caching_enabled,
server_hmr,
}
.cell())
}
......@@ -953,6 +959,9 @@ pub struct Project {
/// Whether to enable persistent caching
is_persistent_caching_enabled: bool,
/// Whether server-side HMR is enabled (--experimental-server-fast-refresh).
server_hmr: bool,
}
#[turbo_tasks::value]
......@@ -1258,12 +1267,14 @@ impl Project {
}
#[turbo_tasks::function]
pub(super) fn client_compile_time_info(&self) -> Vc<CompileTimeInfo> {
get_client_compile_time_info(
pub(super) async fn client_compile_time_info(&self) -> Result<Vc<CompileTimeInfo>> {
let next_mode = self.mode.await?;
Ok(get_client_compile_time_info(
self.browserslist_query.clone(),
self.define_env.client(),
self.next_config.report_system_env_inlining(),
)
next_mode.is_development(),
))
}
#[turbo_tasks::function]
......@@ -1515,6 +1526,7 @@ impl Project {
this.define_env.nodejs(),
self.current_node_js_version(),
this.next_config.report_system_env_inlining(),
this.server_hmr,
))
}
......
......@@ -188,6 +188,7 @@ fn main() {
deferred_entries: None,
is_persistent_caching_enabled: false,
next_version: rcstr!("0.0.0"),
server_hmr: false,
};
let json = serde_json::to_string_pretty(&options).unwrap();
......
......@@ -106,6 +106,7 @@ pub async fn get_client_compile_time_info(
browserslist_query: RcStr,
define_env: Vc<OptionEnvMap>,
report_system_env_inlining: Vc<IssueSeverity>,
hot_module_replacement_enabled: bool,
) -> Result<Vc<CompileTimeInfo>> {
CompileTimeInfo::builder(
Environment::new(ExecutionEnvironment::Browser(
......@@ -126,6 +127,7 @@ pub async fn get_client_compile_time_info(
.to_resolved()
.await?,
)
.hot_module_replacement_enabled(hot_module_replacement_enabled)
.cell()
.await
}
......
......@@ -339,6 +339,7 @@ pub async fn get_server_compile_time_info(
define_env: Vc<OptionEnvMap>,
node_version: ResolvedVc<NodeJsVersion>,
report_system_env_inlining: Vc<IssueSeverity>,
hot_module_replacement_enabled: bool,
) -> Result<Vc<CompileTimeInfo>> {
CompileTimeInfo::builder(
Environment::new(ExecutionEnvironment::NodeJsLambda(
......@@ -358,6 +359,7 @@ pub async fn get_server_compile_time_info(
.to_resolved()
.await?,
)
.hot_module_replacement_enabled(hot_module_replacement_enabled)
.cell()
.await
}
......
......@@ -9,7 +9,7 @@ use turbo_tasks_fs::{
};
use turbopack_core::{
issue::{Issue, IssueExt, IssueSeverity, IssueStage, OptionStyledString, StyledString},
reference_type::{EcmaScriptModulesReferenceSubType, ReferenceType},
reference_type::{ReferenceType, ReferenceTypeCondition},
resolve::{
ExternalTraced, ExternalType, FindContextFileResult, ResolveResult, ResolveResultItem,
ResolveResultOption, find_context_file,
......@@ -155,8 +155,7 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
};
let is_esm = self.import_externals
&& ReferenceType::EcmaScriptModules(EcmaScriptModulesReferenceSubType::Undefined)
.includes(&reference_type);
&& ReferenceTypeCondition::EcmaScriptModules(None).includes(&reference_type);
#[derive(Debug, Copy, Clone)]
enum FileType {
......
......@@ -4,7 +4,7 @@ use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc};
use turbopack::module_options::{ModuleRule, ModuleRuleEffect, RuleCondition};
use turbopack_core::reference_type::{
CssReferenceSubType, EntryReferenceSubType, ReferenceType, UrlReferenceSubType,
CssReferenceSubType, EntryReferenceSubType, ReferenceTypeCondition,
};
use crate::{
......@@ -65,7 +65,9 @@ pub async fn get_next_server_transforms_rules(
// the class names object.
ModuleRule::new(
RuleCondition::all(vec![
RuleCondition::ReferenceType(ReferenceType::Css(CssReferenceSubType::Inner)),
RuleCondition::ReferenceType(ReferenceTypeCondition::Css(Some(
CssReferenceSubType::Inner,
))),
module_styles_rule_condition(),
]),
vec![ModuleRuleEffect::Ignore],
......@@ -90,8 +92,8 @@ pub async fn get_next_server_transforms_rules(
pages_dir.clone(),
ExportFilter::StripDefaultExport,
mdx_rs,
vec![RuleCondition::ReferenceType(ReferenceType::Entry(
EntryReferenceSubType::PageData,
vec![RuleCondition::ReferenceType(ReferenceTypeCondition::Entry(
Some(EntryReferenceSubType::PageData),
))],
&page_extensions,
)?);
......@@ -209,8 +211,8 @@ pub async fn get_next_server_transforms_rules(
// (i.e. for pages), while still allowing `new URL(..., import.meta.url)`
rules.push(ModuleRule::new(
RuleCondition::all(vec![
RuleCondition::not(RuleCondition::ReferenceType(ReferenceType::Url(
UrlReferenceSubType::Undefined,
RuleCondition::not(RuleCondition::ReferenceType(ReferenceTypeCondition::Url(
None,
))),
RuleCondition::any(vec![
RuleCondition::ResourcePathEndsWith(".apng".to_string()),
......
......@@ -34,7 +34,7 @@ pub use server_actions::get_server_actions_transform_rule;
use turbo_tasks::ResolvedVc;
use turbo_tasks_fs::FileSystemPath;
use turbopack::module_options::{ModuleRule, ModuleRuleEffect, ModuleType, RuleCondition};
use turbopack_core::reference_type::{ReferenceType, UrlReferenceSubType};
use turbopack_core::reference_type::ReferenceTypeCondition;
use turbopack_ecmascript::{CustomTransformer, EcmascriptInputTransform};
use crate::next_image::{StructuredImageModuleType, module::BlurPlaceholderMode};
......@@ -44,8 +44,8 @@ pub async fn get_next_image_rule() -> Result<ModuleRule> {
RuleCondition::All(vec![
// avoid urlAssetReference to be affected by this rule, since urlAssetReference
// requires raw module to have its paths in the export
RuleCondition::not(RuleCondition::ReferenceType(ReferenceType::Url(
UrlReferenceSubType::Undefined,
RuleCondition::not(RuleCondition::ReferenceType(ReferenceTypeCondition::Url(
None,
))),
RuleCondition::any(vec![
RuleCondition::ResourcePathEndsWith(".jpg".to_string()),
......@@ -108,8 +108,8 @@ fn match_js_extension(enable_mdx_rs: bool) -> RuleCondition {
/// condition for custom ecma specific transforms.
pub(crate) fn module_rule_match_js_no_url(enable_mdx_rs: bool) -> RuleCondition {
RuleCondition::all(vec![
RuleCondition::not(RuleCondition::ReferenceType(ReferenceType::Url(
UrlReferenceSubType::Undefined,
RuleCondition::not(RuleCondition::ReferenceType(ReferenceTypeCondition::Url(
None,
))),
match_js_extension(enable_mdx_rs),
])
......
......@@ -211,6 +211,9 @@ pub struct NapiProjectOptions {
/// The version of Next.js that is running.
pub next_version: RcStr,
/// Whether server-side HMR is enabled (--experimental-server-fast-refresh).
pub server_hmr: Option<bool>,
}
/// [NapiProjectOptions] with all fields optional.
......@@ -318,6 +321,7 @@ impl From<NapiProjectOptions> for ProjectOptions {
deferred_entries,
is_persistent_caching_enabled,
next_version,
server_hmr,
} = val;
ProjectOptions {
root_path,
......@@ -341,6 +345,7 @@ impl From<NapiProjectOptions> for ProjectOptions {
deferred_entries,
is_persistent_caching_enabled,
next_version,
server_hmr: server_hmr.unwrap_or(false),
}
}
}
......
......@@ -305,7 +305,7 @@ export default function MyApp({ Component, pageProps }) {
<AppOnly>
To use a local font, import your font from `next/font/local` and specify the [`src`](/docs/app/api-reference/components/font#src) of your local font file. Fonts can be stored in the [`public`](/docs/app/api-reference/file-conventions/public-folder) folder or co-located inside the `app` folder. For example:
To use a local font, import the `localFont` function from `next/font/local` and specify the [`src`](/docs/app/api-reference/components/font#src) of your local font file. The path is resolved relative to the file where `localFont` is called. Fonts can be stored anywhere in the project, including the [`public`](/docs/app/api-reference/file-conventions/public-folder) folder or co-located inside the `app` folder. For example, to use a font stored in `app/fonts/`:
```tsx filename="app/layout.tsx" switcher
import localFont from 'next/font/local'
......
......@@ -75,13 +75,6 @@ docs/
.circleci/
Jenkinsfile
# Cache directories and temporary data
.cache/
.parcel-cache/
.eslintcache
.stylelintcache
.turbo/
.tmp/
# Cache directories and temporary data
.cache/
.parcel-cache/
......
......@@ -15,5 +15,5 @@
"registry": "https://registry.npmjs.org/"
}
},
"version": "16.2.0-canary.85"
"version": "16.2.0-canary.87"
}
\ No newline at end of file
{
"name": "create-next-app",
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"keywords": [
"react",
"next",
......
{
"name": "eslint-config-next",
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"description": "ESLint configuration used by Next.js.",
"license": "MIT",
"repository": {
......@@ -12,7 +12,7 @@
"dist"
],
"dependencies": {
"@next/eslint-plugin-next": "16.2.0-canary.85",
"@next/eslint-plugin-next": "16.2.0-canary.87",
"eslint-import-resolver-node": "^0.3.6",
"eslint-import-resolver-typescript": "^3.5.2",
"eslint-plugin-import": "^2.32.0",
......
{
"name": "@next/eslint-plugin-internal",
"private": true,
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"description": "ESLint plugin for working on Next.js.",
"exports": {
".": "./src/eslint-plugin-internal.js"
......
{
"name": "@next/eslint-plugin-next",
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"description": "ESLint plugin for Next.js.",
"main": "dist/index.js",
"types": "dist/index.d.ts",
......
{
"name": "@next/font",
"private": true,
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"repository": {
"url": "vercel/next.js",
"directory": "packages/font"
......
{
"name": "@next/bundle-analyzer",
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"main": "index.js",
"types": "index.d.ts",
"license": "MIT",
......
{
"name": "@next/codemod",
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"license": "MIT",
"repository": {
"type": "git",
......
{
"name": "@next/env",
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"keywords": [
"react",
"next",
......
{
"name": "@next/mdx",
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"main": "index.js",
"license": "MIT",
"repository": {
......
{
"name": "@next/playwright",
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"repository": {
"url": "vercel/next.js",
"directory": "packages/next-playwright"
......
{
"name": "@next/plugin-storybook",
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"repository": {
"url": "vercel/next.js",
"directory": "packages/next-plugin-storybook"
......
{
"name": "@next/polyfill-module",
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"description": "A standard library polyfill for ES Modules supporting browsers (Edge 16+, Firefox 60+, Chrome 61+, Safari 10.1+)",
"main": "dist/polyfill-module.js",
"license": "MIT",
......
{
"name": "@next/polyfill-nomodule",
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"description": "A polyfill for non-dead, nomodule browsers.",
"main": "dist/polyfill-nomodule.js",
"license": "MIT",
......
{
"name": "@next/routing",
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"keywords": [
"react",
"next",
......
{
"name": "next-rspack",
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"repository": {
"url": "vercel/next.js",
"directory": "packages/next-rspack"
......
{
"name": "@next/swc",
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"private": true,
"files": [
"native/"
......
{
"name": "next",
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"description": "The React Framework",
"main": "./dist/server/next.js",
"license": "MIT",
......@@ -97,7 +97,7 @@
]
},
"dependencies": {
"@next/env": "16.2.0-canary.85",
"@next/env": "16.2.0-canary.87",
"@swc/helpers": "0.5.15",
"baseline-browser-mapping": "^2.9.19",
"caniuse-lite": "^1.0.30001579",
......@@ -161,11 +161,11 @@
"@modelcontextprotocol/sdk": "1.18.1",
"@mswjs/interceptors": "0.23.0",
"@napi-rs/triples": "1.2.0",
"@next/font": "16.2.0-canary.85",
"@next/polyfill-module": "16.2.0-canary.85",
"@next/polyfill-nomodule": "16.2.0-canary.85",
"@next/react-refresh-utils": "16.2.0-canary.85",
"@next/swc": "16.2.0-canary.85",
"@next/font": "16.2.0-canary.87",
"@next/polyfill-module": "16.2.0-canary.87",
"@next/polyfill-nomodule": "16.2.0-canary.87",
"@next/react-refresh-utils": "16.2.0-canary.87",
"@next/swc": "16.2.0-canary.87",
"@opentelemetry/api": "1.6.0",
"@playwright/test": "1.51.1",
"@rspack/core": "1.6.7",
......
......@@ -1589,7 +1589,10 @@ export async function handleBuildComplete({
(item) => item.page === dynamicRoute
)?.routeKeys || {}
)
const partialFallbacksEnabled =
config.experimental.partialFallbacks === true
const partialFallback =
partialFallbacksEnabled &&
isAppPage &&
renderingMode === RenderingMode.PARTIALLY_STATIC &&
typeof fallback === 'string' &&
......@@ -1611,8 +1614,9 @@ export async function handleBuildComplete({
// RSC shell.
else if (meta.postponed) {
// If there's postponed fallback content, we usually collapse to a shared shell (`[]`).
// For partial fallbacks in cache components, keep route allowQuery so
// fallback shells can be upgraded per-param instead of sharing one cache key.
// For opt-in partial fallbacks in cache components, keep route
// allowQuery so fallback shells can be upgraded per-param instead
// of sharing one cache key.
htmlAllowQuery =
partialFallback && routesManifest.rsc.clientParamParsing
? allowQuery
......
......@@ -247,6 +247,8 @@ export interface NapiProjectOptions {
isPersistentCachingEnabled: boolean
/** The version of Next.js that is running. */
nextVersion: RcStr
/** Whether server-side HMR is enabled (requires --experimental-server-fast-refresh). */
serverHmr?: boolean
}
/** [NapiProjectOptions] with all fields optional. */
export interface NapiPartialProjectOptions {
......@@ -291,6 +293,8 @@ export interface NapiPartialProjectOptions {
* debugging/profiling purposes.
*/
noMangling?: boolean
/** Whether server-side HMR is enabled (requires --experimental-server-fast-refresh). */
serverHmr?: boolean
}
export interface NapiDefineEnv {
client: Array<NapiOptionEnvVar>
......
......@@ -979,6 +979,7 @@ export async function handler(
if (
!isMinimalMode &&
isRoutePPREnabled &&
nextConfig.experimental.partialFallbacks === true &&
ssgCacheKey &&
incrementalCache &&
!isOnDemandRevalidate &&
......
......@@ -219,6 +219,7 @@ export const experimentalSchema = {
caseSensitiveRoutes: z.boolean().optional(),
clientParamParsingOrigins: z.array(z.string()).optional(),
cachedNavigations: z.boolean().optional(),
partialFallbacks: z.boolean().optional(),
dynamicOnHover: z.boolean().optional(),
optimisticRouting: z.boolean().optional(),
varyParams: z.boolean().optional(),
......
......@@ -353,6 +353,11 @@ export interface ExperimentalConfig {
*/
clientParamParsingOrigins?: string[]
cachedNavigations?: boolean
/**
* Enables partial fallback shells for cache-components routes while the
* feature stabilizes.
*/
partialFallbacks?: boolean
dynamicOnHover?: boolean
optimisticRouting?: boolean
varyParams?: boolean
......@@ -1648,6 +1653,7 @@ export const defaultConfig = Object.freeze({
caseSensitiveRoutes: false,
clientParamParsingOrigins: undefined,
cachedNavigations: false,
partialFallbacks: false,
dynamicOnHover: false,
varyParams: false,
prefetchInlining: false,
......@@ -1828,6 +1834,7 @@ export interface NextConfigRuntime {
| 'maxPostponedStateSize'
| 'devCacheControlNoCache'
| 'cachedNavigations'
| 'partialFallbacks'
| 'exposeTestingApiInProductionBuild'
| 'immutableAssetToken'
> & {
......@@ -1898,6 +1905,7 @@ export function getNextConfigRuntime(
maxPostponedStateSize: ex.maxPostponedStateSize,
devCacheControlNoCache: ex.devCacheControlNoCache,
cachedNavigations: ex.cachedNavigations,
partialFallbacks: ex.partialFallbacks,
exposeTestingApiInProductionBuild: ex.exposeTestingApiInProductionBuild,
immutableAssetToken: ex.immutableAssetToken,
......
......@@ -413,6 +413,7 @@ export async function createHotReloaderTurbopack(
opts.nextConfig
),
nextVersion: process.env.__NEXT_VERSION as string,
serverHmr: experimentalServerFastRefresh,
},
{
memoryLimit: opts.nextConfig.experimental?.turbopackMemoryLimit,
......
......@@ -32,6 +32,7 @@ import { RSCPathnameNormalizer } from '../../normalizers/request/rsc'
import { SegmentPrefixRSCPathnameNormalizer } from '../../normalizers/request/segment-prefix-rsc'
import type { UrlWithParsedQuery } from 'url'
import type { IncomingMessage } from 'http'
import { normalizeAppPageRequestUrl } from './normalize-request-url'
let vendoredReactRSC
let vendoredReactSSR
......@@ -142,6 +143,8 @@ export class AppPageRouteModule extends RouteModule<
} else {
super.normalizeUrl(req, parsedUrl)
}
normalizeAppPageRequestUrl(req, parsedUrl.pathname || '/')
}
public render(
......
import {
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
RSC_HEADER,
} from '../../../client/components/app-router-headers'
import { parseReqUrl } from '../../../lib/url'
import { RSCPathnameNormalizer } from '../../normalizers/request/rsc'
import { SegmentPrefixRSCPathnameNormalizer } from '../../normalizers/request/segment-prefix-rsc'
import { normalizeAppPageRequestUrl } from './normalize-request-url'
type TestRequest = {
headers: Record<string, string>
url: string
}
describe('normalizeAppPageRequestUrl', () => {
it('rewrites req.url for regular RSC requests', () => {
const req: TestRequest = {
headers: {},
url: '/docs/frameworks/frontend.rsc?foo=bar',
}
const parsedUrl = parseReqUrl(req.url)!
parsedUrl.pathname = new RSCPathnameNormalizer().normalize(
parsedUrl.pathname!
)
req.headers[RSC_HEADER] = '1'
normalizeAppPageRequestUrl(req, parsedUrl.pathname!)
expect(parsedUrl.pathname).toBe('/docs/frameworks/frontend')
expect(req.url).toBe('/docs/frameworks/frontend?foo=bar')
expect(req.headers[RSC_HEADER]).toBe('1')
})
it('rewrites req.url for segment prefetch RSC requests', () => {
const req: TestRequest = {
headers: {},
url: '/docs/frameworks/frontend.segments/_tree.segment.rsc?foo=bar',
}
const parsedUrl = parseReqUrl(req.url)!
const result = new SegmentPrefixRSCPathnameNormalizer().extract(
parsedUrl.pathname!
)!
parsedUrl.pathname = result.originalPathname
req.headers[RSC_HEADER] = '1'
req.headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'
req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] = result.segmentPath
normalizeAppPageRequestUrl(req, parsedUrl.pathname)
expect(parsedUrl.pathname).toBe('/docs/frameworks/frontend')
expect(req.url).toBe('/docs/frameworks/frontend?foo=bar')
expect(req.headers[RSC_HEADER]).toBe('1')
expect(req.headers[NEXT_ROUTER_PREFETCH_HEADER]).toBe('1')
expect(req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]).toBe('/_tree')
})
it('rewrites req.url for leaf page segment prefetch requests', () => {
const req: TestRequest = {
headers: {},
url: '/docs/frameworks/frontend.segments/docs/frameworks/frontend/__PAGE__.segment.rsc?foo=bar',
}
const parsedUrl = parseReqUrl(req.url)!
const result = new SegmentPrefixRSCPathnameNormalizer().extract(
parsedUrl.pathname!
)!
parsedUrl.pathname = result.originalPathname
req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] = result.segmentPath
normalizeAppPageRequestUrl(req, parsedUrl.pathname)
expect(parsedUrl.pathname).toBe('/docs/frameworks/frontend')
expect(req.url).toBe('/docs/frameworks/frontend?foo=bar')
expect(req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]).toBe(
'/docs/frameworks/frontend/__PAGE__'
)
})
})
import type { IncomingMessage } from 'http'
import type { BaseNextRequest } from '../../base-http'
import { parseReqUrl } from '../../../lib/url'
import { formatUrl } from '../../../shared/lib/router/utils/format-url'
export function normalizeAppPageRequestUrl(
req: Pick<IncomingMessage | BaseNextRequest, 'url'>,
pathname: string
) {
if (!req.url) {
return
}
const normalizedUrl = parseReqUrl(req.url)
if (!normalizedUrl) {
return
}
normalizedUrl.pathname = pathname
req.url = formatUrl(normalizedUrl)
}
......@@ -70,6 +70,26 @@ declare module 'client-only' {
*/
}
interface TurbopackHotApi {
accept(): void
accept(cb: () => void): void
accept(dep: string | string[], cb?: () => void): void
decline(): void
decline(dep: string | string[]): void
dispose(cb: (data: Record<string, unknown>) => void): void
invalidate(): void
readonly data: Record<string, unknown>
}
interface ImportMeta {
/**
* The HMR API for ESM modules when using Turbopack.
* Equivalent to `module.hot` in CommonJS modules.
* Only available in development mode.
*/
turbopackHot?: TurbopackHotApi
}
interface Window {
MSInputMethodContext?: unknown
/** @internal */
......
{
"name": "@next/react-refresh-utils",
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"description": "An experimental package providing utilities for React Refresh.",
"repository": {
"url": "vercel/next.js",
......
{
"name": "@next/third-parties",
"version": "16.2.0-canary.85",
"version": "16.2.0-canary.87",
"repository": {
"url": "vercel/next.js",
"directory": "packages/third-parties"
......@@ -26,7 +26,7 @@
"third-party-capital": "1.0.20"
},
"devDependencies": {
"next": "16.2.0-canary.85",
"next": "16.2.0-canary.87",
"outdent": "0.8.0",
"prettier": "2.5.1",
"typescript": "5.9.2"
......
......@@ -1014,7 +1014,7 @@ importers:
packages/eslint-config-next:
dependencies:
'@next/eslint-plugin-next':
specifier: 16.2.0-canary.85
specifier: 16.2.0-canary.87
version: link:../eslint-plugin-next
eslint:
specifier: '>=9.0.0'
......@@ -1091,7 +1091,7 @@ importers:
packages/next:
dependencies:
'@next/env':
specifier: 16.2.0-canary.85
specifier: 16.2.0-canary.87
version: link:../next-env
'@swc/helpers':
specifier: 0.5.15
......@@ -1216,19 +1216,19 @@ importers:
specifier: 1.2.0
version: 1.2.0
'@next/font':
specifier: 16.2.0-canary.85
specifier: 16.2.0-canary.87
version: link:../font
'@next/polyfill-module':
specifier: 16.2.0-canary.85
specifier: 16.2.0-canary.87
version: link:../next-polyfill-module
'@next/polyfill-nomodule':
specifier: 16.2.0-canary.85
specifier: 16.2.0-canary.87
version: link:../next-polyfill-nomodule
'@next/react-refresh-utils':
specifier: 16.2.0-canary.85
specifier: 16.2.0-canary.87
version: link:../react-refresh-utils
'@next/swc':
specifier: 16.2.0-canary.85
specifier: 16.2.0-canary.87
version: link:../next-swc
'@opentelemetry/api':
specifier: 1.6.0
......@@ -1953,7 +1953,7 @@ importers:
version: 1.0.20
devDependencies:
next:
specifier: 16.2.0-canary.85
specifier: 16.2.0-canary.87
version: link:../next
outdent:
specifier: 0.8.0
......@@ -10,6 +10,7 @@ const PACKAGES_TO_PATCH = [
'@next/mdx',
'@next/env',
'@next/bundle-analyzer',
'@next/swc-linux-x64-gnu',
]
// --- Argument parsing ---
......@@ -186,6 +187,12 @@ async function patchPackageJson(projectPath, tarballUrls) {
pkg.resolutions[name] = url
}
// Add @next/swc-linux-x64-gnu to dependencies
pkg.dependencies = pkg.dependencies || {}
pkg.dependencies['@next/swc-linux-x64-gnu'] = tarballUrls.get(
'@next/swc-linux-x64-gnu'
)
await fs.writeFile(packageJsonPath, JSON.stringify(pkg, null, 2) + '\n')
console.log(`Patched ${packageJsonPath}`)
......
......@@ -31,6 +31,12 @@ async function main() {
// 15.0.0 -> 15.0.0
const [semverStableVersion] = lernaConfig.version.split('-')
const version = `${semverStableVersion}-preview-${shortSha}-${dateString}`
//
// Lerna version requires a non-detached HEAD
await execa('git', ['checkout', '-B', `preview/${shortSha}`, githubSha], {
cwd: repoRoot,
stdio: 'inherit',
})
await execa(
'pnpm',
......
'use client'
import { useEffect, useState, useRef } from 'react'
import { valueA } from './dep-a'
import { valueB } from './dep-b'
const evaluatedAt = Date.now()
export default function DepAcceptArrayPage() {
const [depAValue, setDepAValue] = useState(valueA)
const [depBValue, setDepBValue] = useState(valueB)
const [acceptCallCount, setAcceptCallCount] = useState(0)
const [evalTime, setEvalTime] = useState<number | null>(null)
const mountedRef = useRef(false)
useEffect(() => {
mountedRef.current = true
setEvalTime(evaluatedAt)
return () => {
mountedRef.current = false
}
}, [])
useEffect(() => {
if (import.meta.turbopackHot) {
import.meta.turbopackHot.accept(['./dep-a', './dep-b'], () => {
// ESM bindings are automatically re-imported before this callback runs,
// so `valueA` and `valueB` already reflect the updated modules.
if (mountedRef.current) {
setDepAValue(valueA)
setDepBValue(valueB)
setAcceptCallCount((c) => c + 1)
}
})
}
}, [])
return (
<div>
<p id="dep-a-value">{depAValue}</p>
<p id="dep-b-value">{depBValue}</p>
{evalTime !== null && (
<p id="parent-eval-time">Parent Evaluated At: {evalTime}</p>
)}
<p id="accept-call-count">Accept Calls: {acceptCallCount}</p>
</div>
)
}
let dep = require('./dep.cjs')
let currentValue = dep.value
let acceptCallCount = 0
const listeners = new Set()
if (module.hot) {
module.hot.accept('./dep.cjs', () => {
dep = require('./dep.cjs')
currentValue = dep.value
acceptCallCount++
listeners.forEach((fn) => fn(currentValue, acceptCallCount))
})
}
module.exports = {
getValue() {
return currentValue
},
getAcceptCallCount() {
return acceptCallCount
},
subscribe(fn) {
listeners.add(fn)
return () => listeners.delete(fn)
},
}
'use client'
import { useEffect, useState } from 'react'
import { getValue, getAcceptCallCount, subscribe } from './dep-observer.cjs'
// Track when this module was evaluated (should NOT change on dep update)
const evaluatedAt = Date.now()
export default function DepAcceptCjsPage() {
const [depValue, setDepValue] = useState(getValue())
const [acceptCallCount, setAcceptCallCount] = useState(getAcceptCallCount())
const [evalTime, setEvalTime] = useState<number | null>(null)
useEffect(() => {
setEvalTime(evaluatedAt)
// dep-observer.cjs registers module.hot.accept('./dep', cb) in CJS context.
// When dep.ts changes, the CJS module handles it and notifies subscribers.
return subscribe((newValue: string, newCount: number) => {
setDepValue(newValue)
setAcceptCallCount(newCount)
})
}, [])
return (
<div>
<p id="dep-value">{depValue}</p>
{evalTime !== null && (
<p id="parent-eval-time">Parent Evaluated At: {evalTime}</p>
)}
<p id="accept-call-count">Accept Calls: {acceptCallCount}</p>
</div>
)
}
// This module exports a value and does NOT self-accept.
// The parent page will accept updates for this module.
export const value = 'initial'
'use client'
import { useEffect, useState, useRef } from 'react'
import { value } from './dep'
// Track when this module was evaluated (should NOT change on dep update)
const evaluatedAt = Date.now()
export default function DepAcceptPage() {
const [depValue, setDepValue] = useState(value)
const [acceptCallCount, setAcceptCallCount] = useState(0)
const [evalTime, setEvalTime] = useState<number | null>(null)
const mountedRef = useRef(false)
useEffect(() => {
mountedRef.current = true
// Set eval time on client only to avoid hydration mismatch
setEvalTime(evaluatedAt)
return () => {
mountedRef.current = false
}
}, [])
useEffect(() => {
// import.meta.turbopackHot is the ESM equivalent of module.hot
if (import.meta.turbopackHot) {
import.meta.turbopackHot.accept('./dep', () => {
// ESM bindings are automatically re-imported before this callback runs,
// so `value` already reflects the updated module.
if (mountedRef.current) {
setDepValue(value)
setAcceptCallCount((c) => c + 1)
}
})
}
}, [])
return (
<div>
<p id="dep-value">{depValue}</p>
{evalTime !== null && (
<p id="parent-eval-time">Parent Evaluated At: {evalTime}</p>
)}
<p id="accept-call-count">Accept Calls: {acceptCallCount}</p>
</div>
)
}
'use client'
import { useEffect, useState } from 'react'
import { valueA } from './dep-a'
import { valueB } from './dep-b'
// Track when this module was evaluated
const evaluatedAt = Date.now()
export default function DepDeclineArrayPage() {
const [evalTime, setEvalTime] = useState<number | null>(null)
useEffect(() => {
setEvalTime(evaluatedAt)
}, [])
useEffect(() => {
if (import.meta.turbopackHot) {
// Decline updates for both dependencies — should trigger full reload
import.meta.turbopackHot.decline(['./dep-a', './dep-b'])
}
}, [])
return (
<div>
<p id="dep-a-value">{valueA}</p>
<p id="dep-b-value">{valueB}</p>
{evalTime !== null && (
<p id="parent-eval-time">Parent Evaluated At: {evalTime}</p>
)}
</div>
)
}
// This module exports a value and does NOT self-accept.
// The parent page will decline updates for this module.
export const value = 'initial'
'use client'
import { useEffect, useState } from 'react'
import { value } from './dep'
// Track when this module was evaluated
const evaluatedAt = Date.now()
export default function DepDeclinePage() {
const [evalTime, setEvalTime] = useState<number | null>(null)
useEffect(() => {
setEvalTime(evaluatedAt)
}, [])
useEffect(() => {
if (import.meta.turbopackHot) {
// Decline updates for this dependency — should trigger full reload
import.meta.turbopackHot.decline('./dep')
}
}, [])
return (
<div>
<p id="dep-value">{value}</p>
{evalTime !== null && (
<p id="parent-eval-time">Parent Evaluated At: {evalTime}</p>
)}
</div>
)
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('hmr-dep-accept', () => {
const { next, isTurbopack, isNextDev } = nextTestSetup({
files: __dirname,
})
// Dependency accept/decline requires Turbopack dev mode
const itTurbopackDev = isTurbopack && isNextDev ? it : it.skip
describe('dependency accept', () => {
itTurbopackDev(
'parent accepts child dependency update without re-evaluating',
async () => {
const browser = await next.browser('/dep-accept')
// Wait for initial render and hydration (eval time only appears after useEffect)
await retry(async () => {
const text = await browser.elementByCss('#dep-value').text()
expect(text).toBe('initial')
})
await retry(async () => {
const text = await browser.elementByCss('#parent-eval-time').text()
expect(text).toMatch(/Parent Evaluated At: \d+/)
})
// Capture the parent evaluation timestamp
const parentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
// Verify initial accept call count
const initialCallCount = await browser
.elementByCss('#accept-call-count')
.text()
expect(initialCallCount).toBe('Accept Calls: 0')
// Patch the dependency to change its exported value
await next.patchFile('app/dep-accept/dep.ts', (content) =>
content.replace("'initial'", "'updated'")
)
// Wait for the accept callback to fire and update the UI
await retry(async () => {
const text = await browser.elementByCss('#dep-value').text()
expect(text).toBe('updated')
})
// The accept callback should have been called
await retry(async () => {
const callCount = await browser
.elementByCss('#accept-call-count')
.text()
expect(callCount).toBe('Accept Calls: 1')
})
// The parent module should NOT have been re-evaluated
const newParentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
expect(newParentEvalTime).toBe(parentEvalTime)
}
)
})
describe('dependency accept with array', () => {
itTurbopackDev(
'parent accepts multiple child dependencies via array',
async () => {
const browser = await next.browser('/dep-accept-array')
// Wait for initial render
await retry(async () => {
const text = await browser.elementByCss('#dep-a-value').text()
expect(text).toBe('initial-a')
})
await retry(async () => {
const text = await browser.elementByCss('#dep-b-value').text()
expect(text).toBe('initial-b')
})
await retry(async () => {
const text = await browser.elementByCss('#parent-eval-time').text()
expect(text).toMatch(/Parent Evaluated At: \d+/)
})
const parentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
// Patch dep-a
await next.patchFile('app/dep-accept-array/dep-a.ts', (content) =>
content.replace("'initial-a'", "'updated-a'")
)
await retry(async () => {
const text = await browser.elementByCss('#dep-a-value').text()
expect(text).toBe('updated-a')
})
await retry(async () => {
const callCount = await browser
.elementByCss('#accept-call-count')
.text()
expect(callCount).toBe('Accept Calls: 1')
})
// Parent should NOT have been re-evaluated
const evalTimeAfterA = await browser
.elementByCss('#parent-eval-time')
.text()
expect(evalTimeAfterA).toBe(parentEvalTime)
// Patch dep-b
await next.patchFile('app/dep-accept-array/dep-b.ts', (content) =>
content.replace("'initial-b'", "'updated-b'")
)
await retry(async () => {
const text = await browser.elementByCss('#dep-b-value').text()
expect(text).toBe('updated-b')
})
await retry(async () => {
const callCount = await browser
.elementByCss('#accept-call-count')
.text()
expect(callCount).toBe('Accept Calls: 2')
})
// Parent should still NOT have been re-evaluated
const evalTimeAfterB = await browser
.elementByCss('#parent-eval-time')
.text()
expect(evalTimeAfterB).toBe(parentEvalTime)
}
)
})
describe('dependency accept via module.hot (CJS)', () => {
itTurbopackDev(
'CJS module registers module.hot.accept and receives dep updates',
async () => {
const browser = await next.browser('/dep-accept-cjs')
// Wait for initial render
await retry(async () => {
const text = await browser.elementByCss('#dep-value').text()
expect(text).toBe('initial')
})
await retry(async () => {
const text = await browser.elementByCss('#parent-eval-time').text()
expect(text).toMatch(/Parent Evaluated At: \d+/)
})
const parentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
expect(await browser.elementByCss('#accept-call-count').text()).toBe(
'Accept Calls: 0'
)
// Patch the dependency
await next.patchFile('app/dep-accept-cjs/dep.cjs', (content) =>
content.replace("'initial'", "'updated'")
)
// dep-observer.cjs handles the update via module.hot.accept
await retry(async () => {
const text = await browser.elementByCss('#dep-value').text()
expect(text).toBe('updated')
})
await retry(async () => {
const callCount = await browser
.elementByCss('#accept-call-count')
.text()
expect(callCount).toBe('Accept Calls: 1')
})
// page.tsx should NOT have been re-evaluated (no full reload)
const newParentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
expect(newParentEvalTime).toBe(parentEvalTime)
}
)
})
describe('dependency decline', () => {
itTurbopackDev(
'declining a dependency triggers full reload on update',
async () => {
const browser = await next.browser('/dep-decline')
// Wait for initial render
await retry(async () => {
const text = await browser.elementByCss('#dep-value').text()
expect(text).toBe('initial')
})
await retry(async () => {
const text = await browser.elementByCss('#parent-eval-time').text()
expect(text).toMatch(/Parent Evaluated At: \d+/)
})
const parentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
// Patch the declined dependency
await next.patchFile('app/dep-decline/dep.ts', (content) =>
content.replace("'initial'", "'updated'")
)
// Since the dep is declined, the update should cause a full page reload.
// After reload, the page re-evaluates with the new dep value.
await retry(async () => {
const text = await browser.elementByCss('#dep-value').text()
expect(text).toBe('updated')
})
// The parent module SHOULD have been re-evaluated (full reload)
await retry(async () => {
const newParentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
expect(newParentEvalTime).not.toBe(parentEvalTime)
})
}
)
})
describe('dependency decline with array', () => {
itTurbopackDev(
'declining multiple dependencies via array triggers full reload',
async () => {
const browser = await next.browser('/dep-decline-array')
// Wait for initial render
await retry(async () => {
const text = await browser.elementByCss('#dep-a-value').text()
expect(text).toBe('initial-a')
})
await retry(async () => {
const text = await browser.elementByCss('#dep-b-value').text()
expect(text).toBe('initial-b')
})
await retry(async () => {
const text = await browser.elementByCss('#parent-eval-time').text()
expect(text).toMatch(/Parent Evaluated At: \d+/)
})
const parentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
// Patch dep-a (declined) — should trigger full reload
await next.patchFile('app/dep-decline-array/dep-a.ts', (content) =>
content.replace("'initial-a'", "'updated-a'")
)
await retry(async () => {
const text = await browser.elementByCss('#dep-a-value').text()
expect(text).toBe('updated-a')
})
// The parent module SHOULD have been re-evaluated (full reload)
await retry(async () => {
const newParentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
expect(newParentEvalTime).not.toBe(parentEvalTime)
})
}
)
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
......@@ -3,6 +3,9 @@
*/
const nextConfig = {
cacheComponents: true,
experimental: {
partialFallbacks: true,
},
}
module.exports = nextConfig
......@@ -4,6 +4,7 @@
const nextConfig = {
experimental: {
useCache: true,
partialFallbacks: true,
},
rewrites: async () => {
return {
......
......@@ -3,6 +3,9 @@
*/
const nextConfig = {
cacheComponents: true,
experimental: {
partialFallbacks: true,
},
}
module.exports = nextConfig
......@@ -258,7 +258,6 @@ describe('adapter-config', () => {
const indexPrerender = prerenderOutputs.find(
(item) => item.pathname === '/docs'
)
expect(indexPrerender?.fallback?.initialHeaders).toEqual({
'content-type': 'text/html; charset=utf-8',
vary: 'rsc, next-router-state-tree, next-router-prefetch, next-router-segment-prefetch',
......
......@@ -144,7 +144,11 @@ where
}
let tx = self.backend.backing_storage.start_read_transaction();
let tx = tx.map(|tx| {
// Safety: self is actually valid for 'a, so it's safe to transmute 'l to 'a
// Safety: `self.backend.backing_storage` lives for at least `'e`. The
// transaction returned by `start_read_transaction()` borrows it for `'e`.
// Since `'tx: 'e`, transmuting to `'tx` is sound because the transaction
// is stored in `self.transaction` (as `Owned`) and dropped with `self`,
// while `self.backend` remains alive for `'e`.
unsafe { transmute::<B::ReadTransaction<'_>, B::ReadTransaction<'tx>>(tx) }
});
self.transaction = TransactionState::Owned(tx);
......
......@@ -165,10 +165,12 @@ where
match self {
Either::Left(this) => {
let tx = tx.map(|tx| read_transaction_left_or_panic(tx.as_ref()));
// Safety: `tx` is unwrapped from `Either::Left`, so it originated from `this`.
unsafe { this.lookup_task_candidates(tx, key) }
}
Either::Right(this) => {
let tx = tx.map(|tx| read_transaction_right_or_panic(tx.as_ref()));
// Safety: `tx` is unwrapped from `Either::Right`, so it originated from `this`.
unsafe { this.lookup_task_candidates(tx, key) }
}
}
......@@ -184,10 +186,12 @@ where
match self {
Either::Left(this) => {
let tx = tx.map(|tx| read_transaction_left_or_panic(tx.as_ref()));
// Safety: `tx` is unwrapped from `Either::Left`, so it originated from `this`.
unsafe { this.lookup_data(tx, task_id, category, storage) }
}
Either::Right(this) => {
let tx = tx.map(|tx| read_transaction_right_or_panic(tx.as_ref()));
// Safety: `tx` is unwrapped from `Either::Right`, so it originated from `this`.
unsafe { this.lookup_data(tx, task_id, category, storage) }
}
}
......@@ -202,10 +206,12 @@ where
match self {
Either::Left(this) => {
let tx = tx.map(|tx| read_transaction_left_or_panic(tx.as_ref()));
// Safety: `tx` is unwrapped from `Either::Left`, so it originated from `this`.
unsafe { this.batch_lookup_data(tx, task_ids, category) }
}
Either::Right(this) => {
let tx = tx.map(|tx| read_transaction_right_or_panic(tx.as_ref()));
// Safety: `tx` is unwrapped from `Either::Right`, so it originated from `this`.
unsafe { this.batch_lookup_data(tx, task_ids, category) }
}
}
......
......@@ -31,9 +31,17 @@ impl<T: KeyValueDatabase> ThreadLocalReadTransactionsContainer<T> {
// Safety: It's safe to send RoTransaction between threads, but the types don't allow that.
unsafe impl<T: KeyValueDatabase> Send for ThreadLocalReadTransactionsContainer<T> {}
/// Caches read transactions in thread-local storage to avoid creating new ones for every operation.
///
/// # Safety invariant (field ordering)
///
/// `read_transactions_cache` must be declared before `database` so that Rust's field drop order
/// (declaration order) drops the cached transactions before the database. The cached transactions
/// store `T::ReadTransaction<'static>` where the `'static` is a transmuted lie — the true
/// lifetime is tied to `database`. Dropping the cache first ensures all transactions are released
/// before the database they borrow from.
pub struct ReadTransactionCache<T: KeyValueDatabase + 'static> {
// Safety: `read_transactions_cache` need to be dropped before `database` since it will end the
// transactions.
// Safety: Must be declared before `database` — see struct-level safety invariant above.
read_transactions_cache: ArcSwap<ThreadLocal<ThreadLocalReadTransactionsContainer<T>>>,
database: T,
}
......@@ -120,10 +128,11 @@ impl<T: KeyValueDatabase> Drop for CachedReadTransaction<'_, T> {
let container = self
.thread_locals
.get_or(|| ThreadLocalReadTransactionsContainer(UnsafeCell::new(Default::default())));
// Safety: We cast it to 'static lifetime, but it will be casted back to 'env when
// taken. It's safe since this will not outlive the environment. We need to
// be careful with Drop, but `read_transactions_cache` is before `env` in the
// LmdbBackingStorage struct, so it's fine.
// Safety: We cast to 'static because the thread-local cache stores transactions
// with an erased lifetime. The transaction will be cast back to the database's
// actual lifetime when popped in `begin_read_transaction`. This is sound because
// `ReadTransactionCache` declares `read_transactions_cache` before `database`,
// so Rust drops the cache (releasing all stored transactions) before the database.
let tx = unsafe {
transmute::<T::ReadTransaction<'_>, T::ReadTransaction<'static>>(
self.tx.take().unwrap(),
......
......@@ -42,6 +42,14 @@ impl<T: KeyValueDatabase> Borrow<[u8]> for ValueBuffer<'_, T> {
type Cache = ByKeySpace<FxDashMap<Vec<u8>, Option<Vec<u8>>>>;
/// A caching layer that stores recently-read key-value pairs for fast startup.
///
/// # Safety invariant (self-referential struct, field ordering)
///
/// `restored_map` contains `&'static [u8]` slices that actually point into the `_restored`
/// `Vec<u8>` buffer. The `'static` lifetime is a transmuted lie. This is sound because
/// `restored_map` is declared before `_restored`, so Rust drops the map (releasing the dangling
/// references) before dropping the backing buffer. **Do not reorder these fields.**
pub struct StartupCacheLayer<T: KeyValueDatabase> {
database: T,
path: PathBuf,
......@@ -49,7 +57,8 @@ pub struct StartupCacheLayer<T: KeyValueDatabase> {
cache_size: AtomicUsize,
cache: Cache,
restored_map: ByKeySpace<FxHashMap<&'static [u8], &'static [u8]>>,
// Need to be kept around to keep the restored_map reference alive
// Safety: Must be declared AFTER `restored_map` — `restored_map` contains references into this
// buffer. See struct-level safety invariant above.
_restored: Vec<u8>,
}
......@@ -65,8 +74,9 @@ impl<T: KeyValueDatabase> StartupCacheLayer<T> {
let (key_space, key, value) = read_key_value_pair(&restored, &mut pos)?;
let map = restored_map.get_mut(key_space);
unsafe {
// Safety: This is a self reference, it's valid as long the `restored`
// buffer is alive
// Safety: Self-referential pattern — these slices point into `restored`
// (which becomes `_restored`). See struct-level safety invariant on
// `StartupCacheLayer` for why the field ordering makes this sound.
map.insert(
transmute::<&'_ [u8], &'static [u8]>(key),
transmute::<&'_ [u8], &'static [u8]>(value),
......
......@@ -280,8 +280,10 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
&[KeySpace::TaskMeta, KeySpace::TaskData],
|&key_space| {
let _span = span.clone().entered();
// Safety: We already finished all processing of the task data and task
// meta
// Safety: `process_task_data` has returned, so no concurrent `put` or
// `delete` on `TaskMeta`/`TaskData` key spaces are in-flight. The
// `parallel::try_for_each` below flushes disjoint key spaces, so
// concurrent flushes on different key spaces are safe.
unsafe { batch.flush(key_space) }
},
)?;
......
......@@ -21,6 +21,14 @@ pub enum RefMut<'a, K, V> {
},
}
// SAFETY: `RefMut` contains a raw `Bucket` pointer into a `DashMap` shard's `RawTable`.
// Sending/sharing is safe because:
// - `Simple` variant: The `Bucket` is accessed under an exclusive `RwLockWriteGuard` on a single
// shard. The guard provides exclusive access to all data in that shard.
// - `Shared` variant: The `Bucket` is accessed under an `Arc<RwLockWriteGuard>`. The
// `get_multiple_mut` function asserts that bucket pointers do not alias, so each `RefMut` has
// exclusive access to its bucket even when sharing a guard.
// - `K: Sync + V: Sync` bounds ensure the key and value types are safe to share across threads.
unsafe impl<K: Eq + Hash + Sync, V: Sync> Send for RefMut<'_, K, V> {}
unsafe impl<K: Eq + Hash + Sync, V: Sync> Sync for RefMut<'_, K, V> {}
......
......@@ -224,7 +224,8 @@ async fn build_internal(
NodeEnv::Production => RuntimeType::Production,
};
let compile_time_info = get_client_compile_time_info(browserslist_query.clone(), node_env);
let compile_time_info =
get_client_compile_time_info(browserslist_query.clone(), node_env, false);
let node_backend = child_process_backend();
let execution_context = ExecutionContext::new(
root_path.clone(),
......
......@@ -197,6 +197,7 @@ fn client_defines(node_env: &NodeEnv) -> CompileTimeDefines {
pub async fn get_client_compile_time_info(
browserslist_query: RcStr,
node_env: Vc<NodeEnv>,
hot_module_replacement_enabled: bool,
) -> Result<Vc<CompileTimeInfo>> {
let node_env = node_env.await?;
CompileTimeInfo::builder(
......@@ -216,6 +217,7 @@ pub async fn get_client_compile_time_info(
.free_var_references(
free_var_references!(..client_defines(&node_env).into_iter()).resolved_cell(),
)
.hot_module_replacement_enabled(hot_module_replacement_enabled)
.cell()
.await
}
......@@ -113,7 +113,7 @@ pub async fn create_web_entry_source(
source_maps_type: SourceMapsType,
browserslist_query: RcStr,
) -> Result<Vc<Box<dyn ContentSource>>> {
let compile_time_info = get_client_compile_time_info(browserslist_query, node_env);
let compile_time_info = get_client_compile_time_info(browserslist_query, node_env, true);
let asset_context = get_client_asset_context(
root_path.clone(),
execution_context,
......
......@@ -455,6 +455,7 @@ pub struct CompileTimeInfo {
pub environment: ResolvedVc<Environment>,
pub defines: ResolvedVc<CompileTimeDefines>,
pub free_var_references: ResolvedVc<FreeVarReferences>,
pub hot_module_replacement_enabled: bool,
}
impl CompileTimeInfo {
......@@ -463,6 +464,7 @@ impl CompileTimeInfo {
environment,
defines: None,
free_var_references: None,
hot_module_replacement_enabled: false,
}
}
}
......@@ -475,6 +477,7 @@ impl CompileTimeInfo {
environment,
defines: CompileTimeDefines::empty().to_resolved().await?,
free_var_references: FreeVarReferences::empty().to_resolved().await?,
hot_module_replacement_enabled: false,
}
.cell())
}
......@@ -489,6 +492,7 @@ pub struct CompileTimeInfoBuilder {
environment: ResolvedVc<Environment>,
defines: Option<ResolvedVc<CompileTimeDefines>>,
free_var_references: Option<ResolvedVc<FreeVarReferences>>,
hot_module_replacement_enabled: bool,
}
impl CompileTimeInfoBuilder {
......@@ -505,6 +509,11 @@ impl CompileTimeInfoBuilder {
self
}
pub fn hot_module_replacement_enabled(mut self, enabled: bool) -> Self {
self.hot_module_replacement_enabled = enabled;
self
}
pub async fn build(self) -> Result<CompileTimeInfo> {
Ok(CompileTimeInfo {
environment: self.environment,
......@@ -516,6 +525,7 @@ impl CompileTimeInfoBuilder {
Some(free_var_references) => free_var_references,
None => FreeVarReferences::empty().to_resolved().await?,
},
hot_module_replacement_enabled: self.hot_module_replacement_enabled,
})
}
......
......@@ -351,53 +351,6 @@ impl Display for ReferenceType {
}
impl ReferenceType {
pub fn includes(&self, other: &Self) -> bool {
if self == other {
return true;
}
match self {
ReferenceType::CommonJs(sub_type) => {
matches!(other, ReferenceType::CommonJs(_))
&& matches!(sub_type, CommonJsReferenceSubType::Undefined)
}
ReferenceType::EcmaScriptModules(sub_type) => {
matches!(other, ReferenceType::EcmaScriptModules(_))
&& matches!(sub_type, EcmaScriptModulesReferenceSubType::Undefined)
}
ReferenceType::Css(CssReferenceSubType::AtImport(_)) => {
// For condition matching, treat any AtImport pair as identical.
matches!(other, ReferenceType::Css(CssReferenceSubType::AtImport(_)))
}
ReferenceType::Css(sub_type) => {
matches!(other, ReferenceType::Css(_))
&& matches!(sub_type, CssReferenceSubType::Undefined)
}
ReferenceType::Url(sub_type) => {
matches!(other, ReferenceType::Url(_))
&& matches!(sub_type, UrlReferenceSubType::Undefined)
}
ReferenceType::TypeScript(sub_type) => {
matches!(other, ReferenceType::TypeScript(_))
&& matches!(sub_type, TypeScriptReferenceSubType::Undefined)
}
ReferenceType::Worker(sub_type) => {
matches!(other, ReferenceType::Worker(_))
&& matches!(sub_type, WorkerReferenceSubType::Undefined)
}
ReferenceType::Entry(sub_type) => {
matches!(other, ReferenceType::Entry(_))
&& matches!(sub_type, EntryReferenceSubType::Undefined)
}
ReferenceType::Runtime => matches!(other, ReferenceType::Runtime),
ReferenceType::Internal(_) => matches!(other, ReferenceType::Internal(_)),
ReferenceType::Loader => matches!(other, ReferenceType::Loader),
ReferenceType::Custom(_) => {
todo!()
}
ReferenceType::Undefined => true,
}
}
/// Returns true if this reference type is internal. This will be used in
/// combination with [`ModuleRuleCondition::Internal`] to determine if a
/// rule should be applied to an internal asset/reference.
......@@ -408,3 +361,84 @@ impl ReferenceType {
)
}
}
/// A type to match [`ReferenceType`] against. This is used in conditions to determine if a rule
/// should be applied to a reference of a given type. It allows
/// - to match against a ReferenceType, e.g. with `ReferenceTypeCondition::Url(None)` matching any
/// `ReferenceType::Url(_)`, or
/// - to match against a specific subtype, e.g. with
/// `ReferenceTypeCondition::Url(Some(UrlReferenceSubType::EcmaScriptNewUrl))` matching
/// `ReferenceType::Url(UrlReferenceSubType::EcmaScriptNewUrl)`
#[derive(
PartialEq, Eq, TraceRawVcs, NonLocalValue, Debug, Clone, Hash, TaskInput, Encode, Decode,
)]
pub enum ReferenceTypeCondition {
CommonJs(Option<CommonJsReferenceSubType>),
EcmaScriptModules(Option<EcmaScriptModulesReferenceSubType>),
Css(Option<CssReferenceSubType>),
Url(Option<UrlReferenceSubType>),
TypeScript(Option<TypeScriptReferenceSubType>),
Worker(Option<WorkerReferenceSubType>),
Entry(Option<EntryReferenceSubType>),
Runtime,
Internal,
Loader,
Custom(u8),
}
impl ReferenceTypeCondition {
pub fn includes(&self, other: &ReferenceType) -> bool {
if matches!(
self,
ReferenceTypeCondition::Css(Some(CssReferenceSubType::AtImport(_)))
) && matches!(other, ReferenceType::Css(CssReferenceSubType::AtImport(_)))
{
// For condition matching, treat any AtImport pair as identical.
return true;
}
if matches!(self, ReferenceTypeCondition::Custom(_)) {
todo!()
}
macro_rules! match_condition_includes {
(
$self:expr, $other:expr,
optional: [$($opt:ident),* $(,)?],
unit: [$($unit:ident),* $(,)?],
value: [$($val:ident),* $(,)?]
$(,)?
) => {
match $self {
$(
ReferenceTypeCondition::$opt(sub_type) => {
if let ReferenceType::$opt(other_sub_type) = $other {
return sub_type.as_ref().is_none_or(|s| s == other_sub_type);
}
}
)*
$(
ReferenceTypeCondition::$unit => {
return matches!($other, ReferenceType::$unit { .. });
}
)*
$(
ReferenceTypeCondition::$val(v) => {
if let ReferenceType::$val(ov) = $other {
return v == ov;
}
}
)*
}
};
}
match_condition_includes!(
self, other,
optional: [CommonJs, EcmaScriptModules, Css, Url, TypeScript, Worker, Entry],
unit: [Runtime, Loader, Internal],
value: [Custom],
);
false
}
}
......@@ -22,13 +22,16 @@ interface HotState {
selfDeclined: boolean
selfInvalidated: boolean
disposeHandlers: ((data: object) => void)[]
acceptedDependencies: Record<ModuleId, AcceptCallback | (() => void)>
acceptedErrorHandlers: Record<ModuleId, AcceptErrorHandler | undefined>
declinedDependencies: Record<ModuleId, true>
}
type AcceptErrorHandler = (
err: Error,
context: { moduleId: ModuleId; dependencyId: string | number }
context: { moduleId: ModuleId; dependencyId: ModuleId }
) => void
type AcceptCallback = (outdatedDependencies: string[]) => void
type AcceptCallback = (outdatedDependencies: ModuleId[]) => void
interface AcceptFunction {
// accept updates for self
......
......@@ -1741,6 +1741,10 @@ impl JsValue {
"import.meta",
"The import.meta object"
),
WellKnownObjectKind::ModuleHot => (
"module.hot",
"The module.hot HMR API"
),
};
if depth > 0 {
let i = hints.len();
......@@ -1879,6 +1883,14 @@ impl JsValue {
"URL".to_string(),
"The standard URL constructor: https://developer.mozilla.org/en-US/docs/Web/API/URL/URL"
),
WellKnownFunctionKind::ModuleHotAccept => (
"module.hot.accept".to_string(),
"The module.hot.accept HMR API: https://webpack.js.org/api/hot-module-replacement/#accept"
),
WellKnownFunctionKind::ModuleHotDecline => (
"module.hot.decline".to_string(),
"The module.hot.decline HMR API: https://webpack.js.org/api/hot-module-replacement/#decline"
),
};
if depth > 0 {
let i = hints.len();
......@@ -3328,6 +3340,8 @@ pub enum WellKnownObjectKind {
ImportMeta,
/// An iterator object, used to model generator return values.
Generator,
/// The `module.hot` object providing HMR API.
ModuleHot,
}
impl WellKnownObjectKind {
......@@ -3473,6 +3487,10 @@ pub enum WellKnownFunctionKind {
// The worker_threads Worker class
NodeWorkerConstructor,
URLConstructor,
/// `module.hot.accept(deps, callback, errorHandler)` — accept HMR updates for dependencies.
ModuleHotAccept,
/// `module.hot.decline(deps)` — decline HMR updates for dependencies.
ModuleHotDecline,
}
impl WellKnownFunctionKind {
......
......@@ -60,6 +60,17 @@ pub async fn replace_well_known(
),
_ => (value, false),
},
// module.hot → WellKnownObject(ModuleHot) (only when HMR is enabled)
JsValue::Member(_, box JsValue::FreeVar(ref name), box ref prop)
if &**name == "module"
&& prop.as_str() == Some("hot")
&& compile_time_info.await?.hot_module_replacement_enabled =>
{
(
JsValue::WellKnownObject(WellKnownObjectKind::ModuleHot),
true,
)
}
_ => (value, false),
})
}
......@@ -624,6 +635,32 @@ async fn well_known_object_member(
WellKnownObjectKind::NodePreGyp => node_pre_gyp(prop),
WellKnownObjectKind::NodeExpressApp => express(prop),
WellKnownObjectKind::NodeProtobufLoader => protobuf_loader(prop),
WellKnownObjectKind::ImportMeta => match prop.as_str() {
// import.meta.turbopackHot is the ESM equivalent of module.hot for HMR
Some("turbopackHot") if compile_time_info.await?.hot_module_replacement_enabled => {
JsValue::WellKnownObject(WellKnownObjectKind::ModuleHot)
}
_ => {
return Ok((
JsValue::member(Box::new(JsValue::WellKnownObject(kind)), Box::new(prop)),
false,
));
}
},
WellKnownObjectKind::ModuleHot => match prop.as_str() {
Some("accept") => JsValue::WellKnownFunction(WellKnownFunctionKind::ModuleHotAccept),
Some("decline") => JsValue::WellKnownFunction(WellKnownFunctionKind::ModuleHotDecline),
_ => {
return Ok((
JsValue::unknown(
JsValue::member(Box::new(JsValue::WellKnownObject(kind)), Box::new(prop)),
true,
"unsupported property on module.hot",
),
true,
));
}
},
#[allow(unreachable_patterns)]
_ => {
return Ok((
......
......@@ -33,6 +33,7 @@ use crate::{
url::UrlAssetReferenceCodeGen,
},
exports_info::{ExportsInfoBinding, ExportsInfoRef},
hot_module::ModuleHotReferenceCodeGen,
ident::IdentReplacement,
member::MemberReplacement,
require_context::RequireContextAssetReferenceCodeGen,
......@@ -199,6 +200,7 @@ pub enum CodeGen {
RequireContextAssetReferenceCodeGen(RequireContextAssetReferenceCodeGen),
UrlAssetReferenceCodeGen(UrlAssetReferenceCodeGen),
WorkerAssetReferenceCodeGen(WorkerAssetReferenceCodeGen),
ModuleHotReferenceCodeGen(ModuleHotReferenceCodeGen),
}
impl CodeGen {
......@@ -231,6 +233,9 @@ impl CodeGen {
Self::RequireContextAssetReferenceCodeGen(v) => v.code_generation(ctx).await,
Self::UrlAssetReferenceCodeGen(v) => v.code_generation(ctx).await,
Self::WorkerAssetReferenceCodeGen(v) => v.code_generation(ctx).await,
Self::ModuleHotReferenceCodeGen(v) => {
v.code_generation(ctx, scope_hoisting_context).await
}
}
}
}
......
......@@ -17,5 +17,7 @@ pub mod failed_to_analyze {
pub const NEW_URL_IMPORT_META: &str = "TP1201";
pub const FREE_VAR_REFERENCE: &str = "TP1202";
pub const NEW_WORKER: &str = "TP1203";
pub const MODULE_HOT_ACCEPT: &str = "TP1204";
pub const MODULE_HOT_DECLINE: &str = "TP1205";
}
}
......@@ -16,7 +16,7 @@ use crate::{
code_gen::{CodeGen, CodeGeneration},
create_visitor, magic_identifier,
references::AstPath,
runtime_functions::TURBOPACK_RESOLVE_ABSOLUTE_PATH,
runtime_functions::{TURBOPACK_MODULE, TURBOPACK_RESOLVE_ABSOLUTE_PATH},
};
/// Responsible for initializing the `import.meta` object binding, so that it
......@@ -31,11 +31,12 @@ use crate::{
)]
pub struct ImportMetaBinding {
path: FileSystemPath,
hmr_enabled: bool,
}
impl ImportMetaBinding {
pub fn new(path: FileSystemPath) -> Self {
ImportMetaBinding { path }
pub fn new(path: FileSystemPath, hmr_enabled: bool) -> Self {
ImportMetaBinding { path, hmr_enabled }
}
pub async fn code_generation(
......@@ -63,16 +64,28 @@ impl ImportMetaBinding {
},
);
Ok(CodeGeneration::hoisted_stmt(
rcstr!("import.meta"),
// [NOTE] url property is lazy-evaluated, as it should be computed once
// turbopack_runtime injects a function to calculate an absolute path.
let hmr_enabled = self.hmr_enabled;
// [NOTE] url property is lazy-evaluated, as it should be computed once
// turbopack_runtime injects a function to calculate an absolute path.
let stmt = if hmr_enabled {
// turbopackHot exposes the HMR API (equivalent to module.hot in CJS).
let turbopack_module: Expr = TURBOPACK_MODULE.into();
quote!(
"const $name = { get url() { return $path }, get turbopackHot() { return $m.hot } };" as Stmt,
name = meta_ident(),
path: Expr = path,
m: Expr = turbopack_module,
)
} else {
quote!(
"const $name = { get url() { return $path } };" as Stmt,
name = meta_ident(),
path: Expr = path.clone(),
),
))
path: Expr = path,
)
};
Ok(CodeGeneration::hoisted_stmt(rcstr!("import.meta"), stmt))
}
}
......
......@@ -7,6 +7,7 @@ pub mod dynamic_expression;
pub mod esm;
pub mod exports_info;
pub mod external_module;
pub mod hot_module;
pub mod ident;
pub mod member;
pub mod node;
......@@ -107,7 +108,7 @@ use crate::{
graph::{
ConditionalKind, DeclUsage, Effect, EffectArg, EvalContext, VarGraph, create_graph,
},
imports::{ImportAnnotations, ImportAttributes, ImportedSymbol, Reexport},
imports::{ImportAnnotations, ImportAttributes, ImportMap, ImportedSymbol, Reexport},
linker::link,
parse_require_context, side_effects,
top_level_await::has_top_level_await,
......@@ -136,6 +137,7 @@ use crate::{
base::EsmAssetReferences, export::EsmExport, module_id::EsmModuleIdAssetReference,
},
exports_info::{ExportsInfoBinding, ExportsInfoRef},
hot_module::{ModuleHotReferenceAssetReference, ModuleHotReferenceCodeGen},
ident::IdentReplacement,
member::MemberReplacement,
node::PackageJsonReference,
......@@ -482,6 +484,12 @@ struct AnalysisState<'a> {
// Whether we are only tracing dependencies (no code generation). When true, synthetic
// wrapper modules like WorkerLoaderModule should not be created.
tracing_only: bool,
// Whether the module is an ESM module (affects resolution for hot module dependencies).
is_esm: bool,
// ESM import references (indexed to match eval_context.imports.references()).
import_references: &'a [ResolvedVc<EsmAssetReference>],
// The import map from the eval context, used to match dep strings to import references.
imports: &'a ImportMap,
}
impl AnalysisState<'_> {
......@@ -1091,6 +1099,9 @@ async fn analyze_ecmascript_module_internal(
url_rewrite_behavior: options.url_rewrite_behavior,
collect_affecting_sources: options.analyze_mode.is_tracing_assets(),
tracing_only: !options.analyze_mode.is_code_gen(),
is_esm,
import_references: &import_references,
imports: &eval_context.imports,
};
enum Action {
......@@ -1574,6 +1585,9 @@ async fn analyze_ecmascript_module_internal(
analysis_state.first_import_meta = false;
analysis.add_code_gen(ImportMetaBinding::new(
source.ident().path().owned().await?,
analysis_state
.compile_time_info_ref
.hot_module_replacement_enabled,
));
}
......@@ -1717,6 +1731,7 @@ async fn compile_time_info_for_module_options(
environment: compile_time_info.environment,
defines: CompileTimeDefines(defines).resolved_cell(),
free_var_references: FreeVarReferences(free_var_references).resolved_cell(),
hot_module_replacement_enabled: compile_time_info.hot_module_replacement_enabled,
}
.cell())
}
......@@ -2912,10 +2927,89 @@ where
),
)
}
kind @ (WellKnownFunctionKind::ModuleHotAccept
| WellKnownFunctionKind::ModuleHotDecline) => {
let is_accept = matches!(kind, WellKnownFunctionKind::ModuleHotAccept);
let args = linked_args().await?;
if let Some(first_arg) = args.first() {
if let Some(dep_strings) = extract_hot_dep_strings(first_arg) {
let mut references = Vec::new();
let mut esm_references = Vec::new();
for dep_str in &dep_strings {
let request = Request::parse_string(dep_str.clone()).to_resolved().await?;
let reference = ModuleHotReferenceAssetReference::new(
*origin,
*request,
issue_source(source, span),
error_mode,
state.is_esm,
)
.to_resolved()
.await?;
analysis.add_reference(reference);
references.push(reference);
// For accept, find a matching ESM import so we can
// re-assign the namespace binding after the update.
let esm_ref = if is_accept {
state
.imports
.references()
.enumerate()
.find(|(_, r)| r.module_path.to_string_lossy() == dep_str.as_str())
.and_then(|(idx, _)| state.import_references.get(idx).copied())
} else {
None
};
esm_references.push(esm_ref);
}
analysis.add_code_gen(ModuleHotReferenceCodeGen::new(
references,
esm_references,
ast_path.to_vec().into(),
));
} else if first_arg.is_unknown() {
let (args_str, hints) = explain_args(args);
let method = if is_accept { "accept" } else { "decline" };
let error_code = if is_accept {
errors::failed_to_analyze::ecmascript::MODULE_HOT_ACCEPT
} else {
errors::failed_to_analyze::ecmascript::MODULE_HOT_DECLINE
};
handler.span_warn_with_code(
span,
&format!(
"module.hot.{method}({args_str}) is not statically analyzable{hints}",
),
DiagnosticId::Error(error_code.to_string()),
)
}
}
}
_ => {}
};
Ok(())
}
/// Extracts dependency strings from the first argument of module.hot.accept/decline.
/// Returns None if the argument is not a string or array of strings (e.g., it's a function
/// for self-accept).
fn extract_hot_dep_strings(arg: &JsValue) -> Option<Vec<RcStr>> {
// Single string: module.hot.accept('./dep', cb)
if let Some(s) = arg.as_str() {
return Some(vec![s.into()]);
}
// Array of strings: module.hot.accept(['./dep-a', './dep-b'], cb)
if let JsValue::Array { items, .. } = arg {
let mut deps = Vec::new();
for item in items {
deps.push(item.as_str()?.into());
}
return Some(deps);
}
None
}
async fn handle_member(
ast_path: &[AstParentKind],
link_obj: impl Future<Output = Result<JsValue>> + Send + Sync,
......
......@@ -50,7 +50,7 @@ use turbopack_core::{
chunk_group_info::{ChunkGroup, ChunkGroupEntry},
},
output::{OutputAsset, OutputAssets, OutputAssetsReference, OutputAssetsWithReferenced},
reference_type::{EntryReferenceSubType, ReferenceType, UrlReferenceSubType},
reference_type::{EntryReferenceSubType, ReferenceType, ReferenceTypeCondition},
};
use turbopack_ecmascript::{
AnalyzeMode, EcmascriptInputTransform, TreeShakingMode, chunk::EcmascriptChunkType,
......@@ -347,8 +347,8 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
.await?;
let conditions = RuleCondition::All(vec![
RuleCondition::not(RuleCondition::ReferenceType(ReferenceType::Url(
UrlReferenceSubType::Undefined,
RuleCondition::not(RuleCondition::ReferenceType(ReferenceTypeCondition::Url(
None,
))),
RuleCondition::any(vec![
RuleCondition::ResourcePathEndsWith(".js".into()),
......
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