Unverified Commit a3d7ab97 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Fork navigation-testing-lock module (#95611)

Ensures the module graph is not bundled. Right now this has no effect
since all the modules imported by `navigation-test-lock` have legit uses
in prod builds.

Also nice to not have to fork every single implementation inline.
parent c3d1e893
...@@ -160,8 +160,16 @@ pub async fn get_client_resolve_options_context( ...@@ -160,8 +160,16 @@ pub async fn get_client_resolve_options_context(
let next_client_fallback_import_map = get_next_client_fallback_import_map(ty.clone()) let next_client_fallback_import_map = get_next_client_fallback_import_map(ty.clone())
.to_resolved() .to_resolved()
.await?; .await?;
let next_client_resolved_map = let expose_testing_api = mode.await?.is_development()
get_next_client_resolved_map(project_path.clone(), project_path.clone(), *mode.await?) || *next_config
.enable_expose_testing_api_in_production_build()
.await?;
let next_client_resolved_map = get_next_client_resolved_map(
project_path.clone(),
project_path.clone(),
*mode.await?,
expose_testing_api,
)
.await? .await?
.to_resolved() .to_resolved()
.await?; .await?;
......
...@@ -1292,6 +1292,7 @@ pub struct ExperimentalConfig { ...@@ -1292,6 +1292,7 @@ pub struct ExperimentalConfig {
durable_use_cache_entries: Option<bool>, durable_use_cache_entries: Option<bool>,
runtime_server_deployment_id: Option<bool>, runtime_server_deployment_id: Option<bool>,
supports_immutable_assets: Option<bool>, supports_immutable_assets: Option<bool>,
expose_testing_api_in_production_build: Option<bool>,
/// A salt to mix into chunk and asset content hashes. Empty string means /// A salt to mix into chunk and asset content hashes. Empty string means
/// no salt. /// no salt.
...@@ -2332,6 +2333,15 @@ impl NextConfig { ...@@ -2332,6 +2333,15 @@ impl NextConfig {
Vc::cell(self.experimental.blocking_ssr.unwrap_or(false)) Vc::cell(self.experimental.blocking_ssr.unwrap_or(false))
} }
#[turbo_tasks::function]
pub fn enable_expose_testing_api_in_production_build(&self) -> Vc<bool> {
Vc::cell(
self.experimental
.expose_testing_api_in_production_build
.unwrap_or(false),
)
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn enable_cache_components(&self) -> Vc<bool> { pub fn enable_cache_components(&self) -> Vc<bool> {
Vc::cell(self.cache_components.unwrap_or(false)) Vc::cell(self.cache_components.unwrap_or(false))
......
...@@ -568,6 +568,7 @@ pub async fn get_next_client_resolved_map( ...@@ -568,6 +568,7 @@ pub async fn get_next_client_resolved_map(
context_path: FileSystemPath, context_path: FileSystemPath,
root: FileSystemPath, root: FileSystemPath,
_mode: NextMode, _mode: NextMode,
expose_testing_api: bool,
) -> Result<Vc<ResolvedMap>> { ) -> Result<Vc<ResolvedMap>> {
// In the browser bundle, swap every module that has a `.browser` sibling (see // In the browser bundle, swap every module that has a `.browser` sibling (see
// BROWSER_VARIANT_MODULES, generated from the filesystem) for that sibling. The default // BROWSER_VARIANT_MODULES, generated from the filesystem) for that sibling. The default
...@@ -579,7 +580,7 @@ pub async fn get_next_client_resolved_map( ...@@ -579,7 +580,7 @@ pub async fn get_next_client_resolved_map(
// filesystem root so it matches wherever `next` resolves from (node_modules, pnpm store, // filesystem root so it matches wherever `next` resolves from (node_modules, pnpm store,
// or monorepo `packages/next`). // or monorepo `packages/next`).
let fs_root = root.root().owned().await?; let fs_root = root.root().owned().await?;
let mut glob_mappings = Vec::with_capacity(BROWSER_VARIANT_MODULES.len()); let mut glob_mappings = Vec::with_capacity(BROWSER_VARIANT_MODULES.len() + 1);
for module in BROWSER_VARIANT_MODULES { for module in BROWSER_VARIANT_MODULES {
glob_mappings.push(( glob_mappings.push((
fs_root.clone(), fs_root.clone(),
...@@ -595,6 +596,30 @@ pub async fn get_next_client_resolved_map( ...@@ -595,6 +596,30 @@ pub async fn get_next_client_resolved_map(
), ),
)); ));
} }
// When the Instant Navigation Testing API is disabled (production build
// without `experimental.exposeTestingApiInProductionBuild`), swap the
// navigation lock implementation for an inert shim so the testing
// machinery does not ship in the browser bundle. This mirrors the webpack
// alias in `create-compiler-aliases.ts`.
if !expose_testing_api {
glob_mappings.push((
fs_root,
Glob::new(
rcstr!("**/next/dist/client/components/segment-cache/navigation-testing-lock.js"),
GlobOptions::default(),
)
.to_resolved()
.await?,
request_to_import_mapping(
context_path.clone(),
rcstr!(
"next/dist/client/components/segment-cache/navigation-testing-lock.disabled"
),
),
));
}
Ok(ResolvedMap { Ok(ResolvedMap {
by_glob: glob_mappings, by_glob: glob_mappings,
} }
......
...@@ -180,6 +180,22 @@ export function createWebpackAliases({ ...@@ -180,6 +180,22 @@ export function createWebpackAliases({
`next/dist/${moduleId}.browser`, `next/dist/${moduleId}.browser`,
]) ])
), ),
// When the Instant Navigation Testing API is disabled (production
// build without `experimental.exposeTestingApiInProductionBuild`),
// swap the navigation lock implementation for an inert shim so the
// testing machinery does not ship in the browser bundle. Same
// resolved-path matching as the browser-variant swap above.
...(!dev &&
config.experimental.exposeTestingApiInProductionBuild !== true
? {
[path.join(
NEXT_PROJECT_ROOT_DIST,
'client/components/segment-cache/navigation-testing-lock.js'
) + '$']:
'next/dist/client/components/segment-cache/navigation-testing-lock.disabled',
}
: {}),
} }
: {}), : {}),
......
/**
* Inert stand-in for `./navigation-testing-lock`.
*
* When the Instant Navigation Testing API is disabled (a production build
* without `experimental.exposeTestingApiInProductionBuild`), the browser
* bundle resolves `./navigation-testing-lock` to this module instead of the
* real implementation, so none of the lock machinery ships. The alias is set
* up in `create-compiler-aliases.ts` (webpack) and
* `crates/next-core/src/next_import_map.rs` (Turbopack).
*
* Every export mirrors the real module's signature and returns the value the
* real implementation produces when no lock is held.
*/
import type { FlightRouterState } from '../../../shared/lib/app-router-types'
import type { PendingSegmentCacheEntry, SegmentCacheEntry } from './cache'
import type { FetchStrategy } from './types'
import type {
NavigationLockPrefetch,
NavigationLockState,
} from './navigation-testing-lock'
export type {
NavigationLockPrefetch,
NavigationLockState,
} from './navigation-testing-lock'
export function getPreLockFetch(): typeof fetch | null {
return null
}
export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {
return null
}
export function recordNavigationLockOwnedEntry(
_entry: SegmentCacheEntry
): void {}
export function trackNavigationLockPrefetchEntry(
_prefetch: NavigationLockPrefetch,
_entry: PendingSegmentCacheEntry
): void {}
export function finishNavigationLockPrefetchSpawning(
_prefetch: NavigationLockPrefetch
): void {}
export function startListeningForInstantNavigationCookie(): void {}
export function updateCapturedSPAToTree(
_fromTree: FlightRouterState,
_toTree: FlightRouterState
): void {}
export function isNavigationLocked(): boolean {
return false
}
export function getCurrentNavigationLock(): NavigationLockState | null {
return null
}
export function shouldRestrictNavigationToShell(
_rootPrefetchHints: number,
_linkFetchStrategy: FetchStrategy
): boolean {
return false
}
export async function waitForNavigationLockIfActive(
_lock: NavigationLockState | null = null
): Promise<void> {}
...@@ -9,6 +9,13 @@ ...@@ -9,6 +9,13 @@
* and delete the cookie to end one. Next.js writes captured values. * and delete the cookie to end one. Next.js writes captured values.
* The CookieStore handler distinguishes them by value: pending = external, * The CookieStore handler distinguishes them by value: pending = external,
* captured = self-write (ignored). * captured = self-write (ignored).
*
* This module assumes the Instant Navigation Testing API is enabled. When it
* is disabled, the bundler resolves this module to
* `./navigation-testing-lock.disabled` instead (see
* `create-compiler-aliases.ts` for webpack and
* `crates/next-core/src/next_import_map.rs` for Turbopack), so none of this
* code ships in the browser bundle.
*/ */
import { import {
...@@ -138,10 +145,7 @@ export type NavigationLockState = { ...@@ -138,10 +145,7 @@ export type NavigationLockState = {
let lockState: NavigationLockState | null = null let lockState: NavigationLockState | null = null
export function getPreLockFetch(): typeof fetch | null { export function getPreLockFetch(): typeof fetch | null {
if (process.env.__NEXT_EXPOSE_TESTING_API && lockState !== null) { return lockState !== null ? lockState.fetch : null
return lockState.fetch
}
return null
} }
/** /**
...@@ -156,7 +160,7 @@ export function getPreLockFetch(): typeof fetch | null { ...@@ -156,7 +160,7 @@ export function getPreLockFetch(): typeof fetch | null {
* count drains to 0 — i.e. spawning finished and every entry fulfilled. * count drains to 0 — i.e. spawning finished and every entry fulfilled.
*/ */
export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null { export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {
if (process.env.__NEXT_EXPOSE_TESTING_API && lockState !== null) { if (lockState !== null) {
let resolve: () => void let resolve: () => void
const promise = new Promise<void>((r) => { const promise = new Promise<void>((r) => {
resolve = r resolve = r
...@@ -183,7 +187,7 @@ export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null { ...@@ -183,7 +187,7 @@ export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {
* lock is held. * lock is held.
*/ */
export function recordNavigationLockOwnedEntry(entry: SegmentCacheEntry): void { export function recordNavigationLockOwnedEntry(entry: SegmentCacheEntry): void {
if (process.env.__NEXT_EXPOSE_TESTING_API && lockState !== null) { if (lockState !== null) {
lockState.ownedEntries.add(entry) lockState.ownedEntries.add(entry)
} }
} }
...@@ -198,7 +202,6 @@ export function trackNavigationLockPrefetchEntry( ...@@ -198,7 +202,6 @@ export function trackNavigationLockPrefetchEntry(
prefetch: NavigationLockPrefetch, prefetch: NavigationLockPrefetch,
entry: PendingSegmentCacheEntry entry: PendingSegmentCacheEntry
): void { ): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (prefetch.trackedEntries.has(entry)) { if (prefetch.trackedEntries.has(entry)) {
return return
} }
...@@ -211,7 +214,6 @@ export function trackNavigationLockPrefetchEntry( ...@@ -211,7 +214,6 @@ export function trackNavigationLockPrefetchEntry(
// Decrement whether the entry fulfills or its request rejects, so a failed // Decrement whether the entry fulfills or its request rejects, so a failed
// segment can't leave the navigation waiting forever. // segment can't leave the navigation waiting forever.
waitForSegmentCacheEntry(entry).then(onSettled, onSettled) waitForSegmentCacheEntry(entry).then(onSettled, onSettled)
}
} }
/** /**
...@@ -222,16 +224,13 @@ export function trackNavigationLockPrefetchEntry( ...@@ -222,16 +224,13 @@ export function trackNavigationLockPrefetchEntry(
export function finishNavigationLockPrefetchSpawning( export function finishNavigationLockPrefetchSpawning(
prefetch: NavigationLockPrefetch prefetch: NavigationLockPrefetch
): void { ): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
prefetch.pendingCount-- prefetch.pendingCount--
settleNavigationLockPrefetchIfDrained(prefetch) settleNavigationLockPrefetchIfDrained(prefetch)
}
} }
function settleNavigationLockPrefetchIfDrained( function settleNavigationLockPrefetchIfDrained(
prefetch: NavigationLockPrefetch prefetch: NavigationLockPrefetch
): void { ): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (prefetch.pendingCount === 0) { if (prefetch.pendingCount === 0) {
// Unregister from the lock (if still held) and resolve. Resolving is // Unregister from the lock (if still held) and resolve. Resolving is
// idempotent, so it's safe even if the lock already force-resolved this on // idempotent, so it's safe even if the lock already force-resolved this on
...@@ -241,7 +240,6 @@ function settleNavigationLockPrefetchIfDrained( ...@@ -241,7 +240,6 @@ function settleNavigationLockPrefetchIfDrained(
} }
prefetch.resolve() prefetch.resolve()
} }
}
} }
function acquireLock(): void { function acquireLock(): void {
...@@ -263,9 +261,7 @@ function acquireLock(): void { ...@@ -263,9 +261,7 @@ function acquireLock(): void {
// Install the fetch blocker. We only intercept `window.fetch` for the // Install the fetch blocker. We only intercept `window.fetch` for the
// duration of the lock so that — outside of a testing scope — user- // duration of the lock so that — outside of a testing scope — user-
// installed overrides of `window.fetch` are untouched. // installed overrides of `window.fetch` are untouched.
if (process.env.__NEXT_EXPOSE_TESTING_API) {
window.fetch = globalFetchOverride window.fetch = globalFetchOverride
}
} }
function releaseLock(): void { function releaseLock(): void {
...@@ -274,9 +270,7 @@ function releaseLock(): void { ...@@ -274,9 +270,7 @@ function releaseLock(): void {
} }
// Restore the pre-lock `window.fetch` before resolving the lock promise // Restore the pre-lock `window.fetch` before resolving the lock promise
// so any fetches queued on the promise see the restored fetch. // so any fetches queued on the promise see the restored fetch.
if (process.env.__NEXT_EXPOSE_TESTING_API) {
window.fetch = lockState.fetch window.fetch = lockState.fetch
}
const { resolveReleased, activePrefetches } = lockState const { resolveReleased, activePrefetches } = lockState
lockState = null lockState = null
// Force-resolve every prefetch that hasn't finished, so a navigation still // Force-resolve every prefetch that hasn't finished, so a navigation still
...@@ -328,7 +322,6 @@ function globalFetchOverride( ...@@ -328,7 +322,6 @@ function globalFetchOverride(
* Called once during page initialization from app-globals.ts. * Called once during page initialization from app-globals.ts.
*/ */
export function startListeningForInstantNavigationCookie(): void { export function startListeningForInstantNavigationCookie(): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
// If the server served a shell, this is an MPA page load // If the server served a shell, this is an MPA page load
// while the lock is held. Transition to captured-MPA and acquire. // while the lock is held. Transition to captured-MPA and acquire.
if (self.__next_instant_test) { if (self.__next_instant_test) {
...@@ -402,7 +395,6 @@ export function startListeningForInstantNavigationCookie(): void { ...@@ -402,7 +395,6 @@ export function startListeningForInstantNavigationCookie(): void {
} }
} }
}) })
}
} }
/** /**
...@@ -413,16 +405,13 @@ export function updateCapturedSPAToTree( ...@@ -413,16 +405,13 @@ export function updateCapturedSPAToTree(
fromTree: FlightRouterState, fromTree: FlightRouterState,
toTree: FlightRouterState toTree: FlightRouterState
): void { ): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
writeCookieValue([1, `c${Math.random()}`, { from: fromTree, to: toTree }]) writeCookieValue([1, `c${Math.random()}`, { from: fromTree, to: toTree }])
}
} }
/** /**
* Returns true if the navigation lock is currently active. * Returns true if the navigation lock is currently active.
*/ */
export function isNavigationLocked(): boolean { export function isNavigationLocked(): boolean {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (lockState !== null) { if (lockState !== null) {
return true return true
} }
...@@ -454,15 +443,11 @@ export function isNavigationLocked(): boolean { ...@@ -454,15 +443,11 @@ export function isNavigationLocked(): boolean {
return true return true
} }
} }
}
return false return false
} }
export function getCurrentNavigationLock(): NavigationLockState | null { export function getCurrentNavigationLock(): NavigationLockState | null {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
return lockState return lockState
}
return null
} }
/** /**
...@@ -478,21 +463,18 @@ export function getCurrentNavigationLock(): NavigationLockState | null { ...@@ -478,21 +463,18 @@ export function getCurrentNavigationLock(): NavigationLockState | null {
* `<Link prefetch={true}>` or an eagerly-prefetched subtree, in which case the * `<Link prefetch={true}>` or an eagerly-prefetched subtree, in which case the
* concrete-param entry is genuinely warm and may be matched. * concrete-param entry is genuinely warm and may be matched.
* *
* Always returns false outside the testing API; the branch below is eliminated * Always returns false outside the testing API, via the aliased
* from production bundles. * `navigation-testing-lock.disabled` module.
*/ */
export function shouldRestrictNavigationToShell( export function shouldRestrictNavigationToShell(
rootPrefetchHints: number, rootPrefetchHints: number,
linkFetchStrategy: FetchStrategy linkFetchStrategy: FetchStrategy
): boolean { ): boolean {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
return ( return (
isNavigationLocked() && isNavigationLocked() &&
(rootPrefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0 && (rootPrefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0 &&
!subtreeHasSpeculativePrefetch(linkFetchStrategy, rootPrefetchHints) !subtreeHasSpeculativePrefetch(linkFetchStrategy, rootPrefetchHints)
) )
}
return false
} }
/** /**
...@@ -502,9 +484,7 @@ export function shouldRestrictNavigationToShell( ...@@ -502,9 +484,7 @@ export function shouldRestrictNavigationToShell(
export async function waitForNavigationLockIfActive( export async function waitForNavigationLockIfActive(
lock: NavigationLockState | null = getCurrentNavigationLock() lock: NavigationLockState | null = getCurrentNavigationLock()
): Promise<void> { ): Promise<void> {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (lock !== null) { if (lock !== null) {
await lock.released await lock.released
} }
}
} }
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