Skip to content
Projects
Groups
Snippets
Help
Loading...
Sign in
Toggle navigation
N
next.js
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Alex
next.js
Commits
87457e79
Commit
87457e79
authored
Jan 21, 2026
by
Will Binns-Smith
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
wip
parent
24576ee4
Hide whitespace changes
Inline
Side-by-side
Showing
8 changed files
with
358 additions
and
74 deletions
+358
-74
eslint.config.mjs
eslint.config.mjs
+6
-1
hot-reloader-turbopack.ts
packages/next/src/server/dev/hot-reloader-turbopack.ts
+94
-59
layout.tsx
...e2e/app-dir/server-hmr-module-preservation/app/layout.tsx
+8
-0
page.tsx
test/e2e/app-dir/server-hmr-module-preservation/app/page.tsx
+14
-0
unmodified-module.ts
...r/server-hmr-module-preservation/app/unmodified-module.ts
+9
-0
next.config.js
...e2e/app-dir/server-hmr-module-preservation/next.config.js
+6
-0
server-hmr-module-preservation.test.ts
...odule-preservation/server-hmr-module-preservation.test.ts
+97
-0
dev-runtime.ts
...turbopack-ecmascript-runtime/js/src/nodejs/dev-runtime.ts
+124
-14
No files found.
eslint.config.mjs
View file @
87457e79
...
@@ -303,7 +303,12 @@ export default defineConfig([
...
@@ -303,7 +303,12 @@ export default defineConfig([
'jest/no-standalone-expect'
:
[
'jest/no-standalone-expect'
:
[
'error'
,
'error'
,
{
{
additionalTestBlockFunctions
:
[
'retry'
,
'itCI'
,
'itHeaded'
],
additionalTestBlockFunctions
:
[
'retry'
,
'itCI'
,
'itHeaded'
,
'itIfTurbopackDev'
,
],
},
},
],
],
},
},
...
...
packages/next/src/server/dev/hot-reloader-turbopack.ts
View file @
87457e79
...
@@ -407,8 +407,62 @@ export async function createHotReloaderTurbopack(
...
@@ -407,8 +407,62 @@ export async function createHotReloaderTurbopack(
}
}
}
}
// Check if server HMR is active for this endpoint.
// The HMR identifier format is `server/app/<path>.js` for app routes.
// We derive the expected identifier from the entry key.
let
expectedHmrIdentifier
:
string
|
null
=
null
try
{
const
entryKey
=
splitEntryKey
(
key
)
if
(
entryKey
.
type
===
'app'
&&
entryKey
.
page
)
{
// App Router: page is like "/page" or "/foo/bar"
// HMR identifier is like "server/app/page.js" or "server/app/foo/bar/page.js"
const
pagePath
=
entryKey
.
page
===
'/'
?
'/page'
:
entryKey
.
page
expectedHmrIdentifier
=
`server/app
${
pagePath
}
.js`
}
}
catch
{
// Entry key couldn't be parsed, skip HMR check
}
// Check if server HMR has an active subscription for this endpoint.
// If so, let HMR handle module updates instead of clearing everything.
const
hasActiveHmrSubscription
=
expectedHmrIdentifier
?
serverHmrSubscriptions
.
has
(
expectedHmrIdentifier
)
:
false
resetFetch
()
resetFetch
()
const
serverPaths
=
writtenEndpoint
.
serverPaths
.
map
(({
path
:
p
})
=>
join
(
distDir
,
p
)
)
if
(
hasActiveHmrSubscription
&&
expectedHmrIdentifier
)
{
// Server HMR is active. The HMR runtime has already:
// 1. Received the update with new module factories
// 2. Disposed only the changed modules from devModuleCache
// 3. Updated moduleFactories with the new code
//
// We need to clear the Node.js require cache so the bundle entry is
// re-required on the next request. When re-required:
// - Bundle calls getOrInstantiateRuntimeModule for entry
// - Entry module was disposed → not in cache → instantiate with new factory
// - Entry imports children, checking devModuleCache
// - Changed children (disposed) → instantiate with new factory
// - Unchanged children → return from cache (preserved!)
//
// We do NOT clear the chunk cache because:
// - HMR has already updated moduleFactories with new code
// - Chunk files on disk might be stale
// - Clearing chunk cache would cause chunks to reload from disk,
// overwriting the HMR-applied factories
// Clear Node.js require cache so bundle entry is re-required
for
(
const
file
of
serverPaths
)
{
deleteCache
(
file
)
}
return
true
}
// No active HMR subscription - clear everything (fallback behavior)
// Not available in:
// Not available in:
// - Pages Router (no server-side HMR)
// - Pages Router (no server-side HMR)
// - Edge Runtime (uses browser runtime which already disposes chunks individually)
// - Edge Runtime (uses browser runtime which already disposes chunks individually)
...
@@ -416,10 +470,6 @@ export async function createHotReloaderTurbopack(
...
@@ -416,10 +470,6 @@ export async function createHotReloaderTurbopack(
__next__clear_chunk_cache__
()
__next__clear_chunk_cache__
()
}
}
const
serverPaths
=
writtenEndpoint
.
serverPaths
.
map
(({
path
:
p
})
=>
join
(
distDir
,
p
)
)
for
(
const
file
of
serverPaths
)
{
for
(
const
file
of
serverPaths
)
{
clearModuleContext
(
file
)
clearModuleContext
(
file
)
deleteCache
(
file
)
deleteCache
(
file
)
...
@@ -1491,44 +1541,44 @@ export async function createHotReloaderTurbopack(
...
@@ -1491,44 +1541,44 @@ export async function createHotReloaderTurbopack(
>
()
>
()
/**
/**
* Apply a server HMR update. Returns t
rue if the update was successfully applied
* Apply a server HMR update. Returns t
he set of modified module IDs if successful,
*
(all affected modules accepted the update), false otherwise
.
*
null if the update could not be applied
.
*/
*/
function
applyServerHmrUpdate
(
update
:
TurbopackUpdate
):
boolean
{
function
applyServerHmrUpdate
(
update
:
TurbopackUpdate
):
Set
<
string
>
|
null
{
if
(
typeof
__next__server_hmr_apply__
!==
'function'
)
{
if
(
typeof
__next__server_hmr_apply__
!==
'function'
)
{
// Server HMR not available (e.g., Pages Router or Edge Runtime)
// Server HMR not available (e.g., Pages Router or Edge Runtime)
console
.
log
(
'[Server HMR] __next__server_hmr_apply__ not available'
)
return
null
return
false
}
}
if
(
update
.
type
!==
'partial'
)
{
if
(
update
.
type
!==
'partial'
)
{
// Only partial updates can be applied incrementally
// Only partial updates can be applied incrementally
console
.
log
(
'[Server HMR] Update type is not partial:'
,
update
.
type
)
return
null
return
false
}
}
const
merged
=
update
.
instruction
?.
merged
const
merged
=
update
.
instruction
?.
merged
if
(
!
merged
||
merged
.
length
===
0
)
{
if
(
!
merged
||
merged
.
length
===
0
)
{
// No actual module updates
// No actual module updates
console
.
log
(
'[Server HMR] No merged updates in instruction'
)
return
null
return
false
}
}
console
.
log
(
// Collect all modified module IDs from the update
'[Server HMR] Applying update with'
,
const
modifiedModuleIds
=
new
Set
<
string
>
()
merged
.
length
,
for
(
const
mergedUpdate
of
merged
)
{
'merged updates'
if
(
mergedUpdate
.
entries
)
{
)
for
(
const
moduleId
of
Object
.
keys
(
mergedUpdate
.
entries
))
{
modifiedModuleIds
.
add
(
moduleId
)
}
}
}
// Pass the full update to the runtime - it handles extracting merged updates
// Pass the full update to the runtime - it handles extracting merged updates
const
applied
=
__next__server_hmr_apply__
(
update
as
any
)
const
applied
=
__next__server_hmr_apply__
(
update
as
any
)
if
(
!
applied
)
{
if
(
!
applied
)
{
// Update was not accepted, need full reload
// Update was not accepted, need full reload
console
.
log
(
'[Server HMR] Runtime did not accept update'
)
return
null
return
false
}
}
return
true
return
modifiedModuleIds
}
}
/**
/**
...
@@ -1537,81 +1587,66 @@ export async function createHotReloaderTurbopack(
...
@@ -1537,81 +1587,66 @@ export async function createHotReloaderTurbopack(
*/
*/
function
subscribeToServerHmr
(
identifier
:
string
)
{
function
subscribeToServerHmr
(
identifier
:
string
)
{
if
(
serverHmrSubscriptions
.
has
(
identifier
))
{
if
(
serverHmrSubscriptions
.
has
(
identifier
))
{
console
.
log
(
'[Server HMR] Already subscribed to:'
,
identifier
)
return
return
}
}
console
.
log
(
'[Server HMR] Creating subscription for:'
,
identifier
)
const
subscription
=
project
.
serverHmrEvents
(
identifier
)
const
subscription
=
project
.
serverHmrEvents
(
identifier
)
serverHmrSubscriptions
.
set
(
identifier
,
subscription
)
serverHmrSubscriptions
.
set
(
identifier
,
subscription
)
// Start listening for changes in background
// Start listening for changes in background
;(
async
()
=>
{
;(
async
()
=>
{
// Skip initial state
// Skip initial state
console
.
log
(
'[Server HMR] Waiting for initial state:'
,
identifier
)
await
subscription
.
next
()
await
subscription
.
next
()
console
.
log
(
'[Server HMR] Subscription active, waiting for updates:'
,
identifier
)
for
await
(
const
result
of
subscription
)
{
for
await
(
const
result
of
subscription
)
{
const
update
=
result
as
TurbopackUpdate
const
update
=
result
as
TurbopackUpdate
console
.
log
(
'[Server HMR] Received update for:'
,
identifier
,
'type:'
,
update
.
type
)
// Skip non-partial updates (e.g., 'issues' updates are just diagnostics)
// Skip non-partial updates (e.g., 'issues' updates are just diagnostics)
if
(
update
.
type
!==
'partial'
)
{
if
(
update
.
type
!==
'partial'
)
{
console
.
log
(
'[Server HMR] Skipping non-partial update:'
,
update
.
type
)
continue
continue
}
}
const
applied
=
applyServerHmrUpdate
(
update
)
const
modifiedModules
=
applyServerHmrUpdate
(
update
)
if
(
applied
)
{
if
(
modifiedModules
!==
null
)
{
console
.
log
(
'[Server HMR] Applied update for:'
,
identifier
)
// Notify clients to refresh and get updated server content
}
else
{
// This triggers the client to re-fetch the page with the new server components
// Update not accepted - the existing serverChanged/clearModuleContext
const
serverComponentChangesMessage
:
HmrMessageSentToBrowser
=
{
// flow will handle the full reload
type
:
HMR_MESSAGE_SENT_TO_BROWSER
.
SERVER_COMPONENT_CHANGES
as
const
,
console
.
log
(
hash
:
String
(
++
hmrHash
),
'[Server HMR] Update not accepted for:'
,
}
identifier
,
for
(
const
client
of
[
'- falling back to full reload'
...
clientsWithoutHtmlRequestId
,
)
...
clientsByHtmlRequestId
.
values
(),
])
{
sendToClient
(
client
,
serverComponentChangesMessage
)
}
}
}
// If update not accepted, fall back to existing behavior (full reload via clearRequireCache)
}
}
})().
catch
((
err
)
=>
{
})().
catch
((
err
)
=>
{
console
.
error
(
console
.
error
(
'[Server HMR] Event subscription error:'
,
err
)
'[Server HMR] Event subscription error for'
,
identifier
,
err
)
serverHmrSubscriptions
.
delete
(
identifier
)
serverHmrSubscriptions
.
delete
(
identifier
)
})
})
}
}
// Subscribe to server HMR identifiers to track available server modules
// Subscribe to server HMR identifiers to track available server modules
;(
async
()
=>
{
;(
async
()
=>
{
console
.
log
(
'[Server HMR] Starting identifiers subscription...'
)
let
serverHmrIdentifiers
const
serverHmrIdentifiers
=
project
.
serverHmrIdentifiersSubscribe
()
try
{
serverHmrIdentifiers
=
project
.
serverHmrIdentifiersSubscribe
()
}
catch
(
err
)
{
console
.
error
(
'[Server HMR] Failed to create subscription:'
,
err
)
return
}
// Process identifiers (both initial and subsequent updates)
// Process identifiers (both initial and subsequent updates)
for
await
(
const
data
of
serverHmrIdentifiers
)
{
for
await
(
const
data
of
serverHmrIdentifiers
)
{
console
.
log
(
'[Server HMR] Got identifiers update:'
,
data
.
identifiers
.
length
,
'total'
)
// Subscribe to HMR events for all server modules
// Subscribe to HMR events for all server modules
// For now, focus on page.js files as a starting point
// For now, focus on page.js files as a starting point
for
(
const
identifier
of
data
.
identifiers
)
{
for
(
const
identifier
of
data
.
identifiers
)
{
// Skip source maps and other non-JS files
// Skip source maps and other non-JS files
if
(
identifier
.
endsWith
(
'.js'
)
&&
identifier
.
includes
(
'page.js'
))
{
if
(
identifier
.
endsWith
(
'.js'
)
&&
identifier
.
includes
(
'page.js'
))
{
console
.
log
(
'[Server HMR] Subscribing to:'
,
identifier
)
subscribeToServerHmr
(
identifier
)
subscribeToServerHmr
(
identifier
)
}
}
}
}
...
...
test/e2e/app-dir/server-hmr-module-preservation/app/layout.tsx
0 → 100644
View file @
87457e79
import
{
ReactNode
}
from
'react'
export
default
function
Root
({
children
}:
{
children
:
ReactNode
})
{
return
(
<
html
>
<
body
>
{
children
}
</
body
>
</
html
>
)
}
test/e2e/app-dir/server-hmr-module-preservation/app/page.tsx
0 → 100644
View file @
87457e79
import
{
evaluatedAt
}
from
'./unmodified-module'
// This value changes each time THIS module is re-evaluated
const
pageLoadId
=
Math
.
random
().
toString
(
36
).
slice
(
2
)
export
default
function
Page
()
{
return
(
<
div
>
<
p
id=
"greeting"
>
hello world
</
p
>
<
p
id=
"page-load-id"
>
Page Load ID:
{
pageLoadId
}
</
p
>
<
p
id=
"module-eval-time"
>
Module Evaluated At:
{
evaluatedAt
}
</
p
>
</
div
>
)
}
test/e2e/app-dir/server-hmr-module-preservation/app/unmodified-module.ts
0 → 100644
View file @
87457e79
// This module's evaluation timestamp is used to verify it's not re-evaluated on HMR
// unless the module itself changes
// Log when this module is evaluated - this is what we test
console
.
log
(
'[Module] evaluated'
)
// Timestamp showing when this module was last evaluated
// This value only changes if this module is re-evaluated
export
const
evaluatedAt
=
Date
.
now
()
test/e2e/app-dir/server-hmr-module-preservation/next.config.js
0 → 100644
View file @
87457e79
/**
* @type {import('next').NextConfig}
*/
const
nextConfig
=
{}
module
.
exports
=
nextConfig
test/e2e/app-dir/server-hmr-module-preservation/server-hmr-module-preservation.test.ts
0 → 100644
View file @
87457e79
import
{
nextTestSetup
}
from
'e2e-utils'
import
{
retry
}
from
'next-test-utils'
describe
(
'server-hmr-module-preservation'
,
()
=>
{
const
{
next
,
isTurbopack
,
isNextDev
}
=
nextTestSetup
({
files
:
__dirname
,
})
// Server HMR is a Turbopack-only feature, only available in dev mode
const
itIfTurbopackDev
=
isTurbopack
&&
isNextDev
?
it
:
it
.
skip
itIfTurbopackDev
(
'should preserve unmodified module when page module changes'
,
async
()
=>
{
const
browser
=
await
next
.
browser
(
'/'
)
// Wait for initial render with module timestamp
await
retry
(
async
()
=>
{
const
text
=
await
browser
.
elementByCss
(
'#module-eval-time'
).
text
()
expect
(
text
).
toMatch
(
/Module Evaluated At:
\d
+/
)
})
// Capture the initial module evaluation timestamp
const
initialModuleEvalTime
=
await
browser
.
elementByCss
(
'#module-eval-time'
)
.
text
()
// Mark where we are in CLI output
const
cliOutputBeforePatch
=
next
.
cliOutput
.
length
// Make a change to the page that doesn't affect the unmodified module
await
next
.
patchFile
(
'app/page.tsx'
,
(
content
)
=>
content
.
replace
(
'hello world'
,
'hello universe'
)
)
// Wait for HMR to apply and verify the page updated
await
retry
(
async
()
=>
{
const
text
=
await
browser
.
elementByCss
(
'#greeting'
).
text
()
expect
(
text
).
toBe
(
'hello universe'
)
})
// The unmodified module should NOT have been re-evaluated (same timestamp)
const
newModuleEvalTime
=
await
browser
.
elementByCss
(
'#module-eval-time'
)
.
text
()
expect
(
newModuleEvalTime
).
toBe
(
initialModuleEvalTime
)
// Also verify via CLI output that unmodified module wasn't re-evaluated
const
cliOutputAfterPatch
=
next
.
cliOutput
.
slice
(
cliOutputBeforePatch
)
expect
(
cliOutputAfterPatch
).
not
.
toContain
(
'[Module] evaluated'
)
}
)
itIfTurbopackDev
(
'should re-evaluate module when the module itself changes'
,
async
()
=>
{
const
browser
=
await
next
.
browser
(
'/'
)
// Wait for initial render
await
retry
(
async
()
=>
{
const
text
=
await
browser
.
elementByCss
(
'#module-eval-time'
).
text
()
expect
(
text
).
toMatch
(
/Module Evaluated At:
\d
+/
)
})
// Capture the initial module evaluation timestamp
const
initialModuleEvalTime
=
await
browser
.
elementByCss
(
'#module-eval-time'
)
.
text
()
// Mark CLI output position
const
cliOutputBeforePatch
=
next
.
cliOutput
.
length
// Make a change to the unmodified module itself
await
next
.
patchFile
(
'app/unmodified-module.ts'
,
(
content
)
=>
content
.
replace
(
"console.log('[Module] evaluated')"
,
"console.log('[Module] RE-evaluated')"
)
)
// Wait for HMR to apply - the module should be re-evaluated
// and the timestamp should change
await
retry
(
async
()
=>
{
// Refresh to trigger re-evaluation of changed modules
await
browser
.
refresh
()
const
newModuleEvalTime
=
await
browser
.
elementByCss
(
'#module-eval-time'
)
.
text
()
expect
(
newModuleEvalTime
).
not
.
toBe
(
initialModuleEvalTime
)
})
// Verify via CLI output that module was re-evaluated
const
cliOutputAfterPatch
=
next
.
cliOutput
.
slice
(
cliOutputBeforePatch
)
expect
(
cliOutputAfterPatch
).
toContain
(
'[Module] RE-evaluated'
)
}
)
})
turbopack/crates/turbopack-ecmascript-runtime/js/src/nodejs/dev-runtime.ts
View file @
87457e79
...
@@ -147,35 +147,66 @@ type ModuleFactory = (
...
@@ -147,35 +147,66 @@ type ModuleFactory = (
const
url
=
require
(
'url'
)
as
typeof
import
(
'url'
)
const
url
=
require
(
'url'
)
as
typeof
import
(
'url'
)
const
moduleFactories
:
ModuleFactories
=
new
Map
()
// Declare global storage for module caches that persist across bundle re-requires.
// This is necessary for server HMR to work correctly - when the bundle file's
// Node.js require cache is cleared and the bundle is re-required, we need to
// preserve the Turbopack module cache so unchanged modules (like database
// connections) are not re-evaluated.
declare
global
{
var
__turbopack_module_factories__
:
ModuleFactories
|
undefined
var
__turbopack_dev_module_cache__
:
ModuleCache
<
HotModule
>
|
undefined
}
// Reuse existing caches if available (they persist across bundle re-requires)
const
moduleFactories
:
ModuleFactories
=
globalThis
.
__turbopack_module_factories__
||
(
globalThis
.
__turbopack_module_factories__
=
new
Map
())
nodeDevContextPrototype
.
M
=
moduleFactories
nodeDevContextPrototype
.
M
=
moduleFactories
const
devModuleCache
:
ModuleCache
<
HotModule
>
=
Object
.
create
(
null
)
const
devModuleCache
:
ModuleCache
<
HotModule
>
=
globalThis
.
__turbopack_dev_module_cache__
||
(
globalThis
.
__turbopack_dev_module_cache__
=
Object
.
create
(
null
))
nodeDevContextPrototype
.
c
=
devModuleCache
nodeDevContextPrototype
.
c
=
devModuleCache
// ============================================================================
// ============================================================================
// HMR State
// HMR State
(also persisted globally for bundle re-requires)
// ============================================================================
// ============================================================================
declare
global
{
var
__turbopack_module_hot_data__
:
Map
<
ModuleId
,
HotData
>
|
undefined
var
__turbopack_module_hot_state__
:
Map
<
HotModule
,
HotState
>
|
undefined
var
__turbopack_queued_invalidated_modules__
:
Set
<
ModuleId
>
|
undefined
var
__turbopack_runtime_modules__
:
Set
<
ModuleId
>
|
undefined
}
/**
/**
* Maps module IDs to persisted data between executions of their hot module
* Maps module IDs to persisted data between executions of their hot module
* implementation (`hot.data`).
* implementation (`hot.data`).
*/
*/
const
moduleHotData
:
Map
<
ModuleId
,
HotData
>
=
new
Map
()
const
moduleHotData
:
Map
<
ModuleId
,
HotData
>
=
globalThis
.
__turbopack_module_hot_data__
||
(
globalThis
.
__turbopack_module_hot_data__
=
new
Map
())
/**
/**
* Maps module instances to their hot module state.
* Maps module instances to their hot module state.
*/
*/
const
moduleHotState
:
Map
<
HotModule
,
HotState
>
=
new
Map
()
const
moduleHotState
:
Map
<
HotModule
,
HotState
>
=
globalThis
.
__turbopack_module_hot_state__
||
(
globalThis
.
__turbopack_module_hot_state__
=
new
Map
())
/**
/**
* Modules that call `module.hot.invalidate()` (while being updated).
* Modules that call `module.hot.invalidate()` (while being updated).
*/
*/
const
queuedInvalidatedModules
:
Set
<
ModuleId
>
=
new
Set
()
const
queuedInvalidatedModules
:
Set
<
ModuleId
>
=
globalThis
.
__turbopack_queued_invalidated_modules__
||
(
globalThis
.
__turbopack_queued_invalidated_modules__
=
new
Set
())
/**
/**
* Module IDs that are instantiated as part of the runtime of a chunk.
* Module IDs that are instantiated as part of the runtime of a chunk.
*/
*/
const
runtimeModules
:
Set
<
ModuleId
>
=
new
Set
()
const
runtimeModules
:
Set
<
ModuleId
>
=
globalThis
.
__turbopack_runtime_modules__
||
(
globalThis
.
__turbopack_runtime_modules__
=
new
Set
())
/**
/**
* When true, modules that bubble up to the root without being accepted
* When true, modules that bubble up to the root without being accepted
...
@@ -229,6 +260,7 @@ const chunkCache = new Map<ChunkPath, Promise<void>>()
...
@@ -229,6 +260,7 @@ const chunkCache = new Map<ChunkPath, Promise<void>>()
function
clearChunkCache
()
{
function
clearChunkCache
()
{
chunkCache
.
clear
()
chunkCache
.
clear
()
loadedChunks
.
clear
()
}
}
function
loadRuntimeChunkPath
(
function
loadRuntimeChunkPath
(
...
@@ -491,10 +523,19 @@ function getOrInstantiateModuleFromParent(
...
@@ -491,10 +523,19 @@ function getOrInstantiateModuleFromParent(
id
:
ModuleId
,
id
:
ModuleId
,
sourceModule
:
HotModule
sourceModule
:
HotModule
):
HotModule
{
):
HotModule
{
// Handle race condition: if the source module was disposed by HMR but an
// in-flight request is still using old accessor functions that reference it,
// try to "upgrade" to use the current valid module instead of continuing
// with the disposed module's context.
if
(
!
sourceModule
.
hot
.
active
)
{
if
(
!
sourceModule
.
hot
.
active
)
{
console
.
warn
(
// Check if there's a newer version of the source module in the cache
`Unexpected import of module
${
id
}
from module
${
sourceModule
.
id
}
, which was deleted by an HMR update`
const
currentSourceModule
=
devModuleCache
[
sourceModule
.
id
]
)
if
(
currentSourceModule
&&
currentSourceModule
.
hot
.
active
)
{
// There's a valid newer version - use it instead
sourceModule
=
currentSourceModule
}
// If no valid replacement found, continue with the disposed module
// and let normal error handling take over if needed
}
}
const
module
=
devModuleCache
[
id
]
const
module
=
devModuleCache
[
id
]
...
@@ -531,6 +572,7 @@ function getOrInstantiateRuntimeModule(
...
@@ -531,6 +572,7 @@ function getOrInstantiateRuntimeModule(
moduleId
:
ModuleId
moduleId
:
ModuleId
):
HotModule
{
):
HotModule
{
const
module
=
devModuleCache
[
moduleId
]
const
module
=
devModuleCache
[
moduleId
]
if
(
module
)
{
if
(
module
)
{
if
(
module
.
error
)
{
if
(
module
.
error
)
{
throw
module
.
error
throw
module
.
error
...
@@ -563,8 +605,7 @@ function disposeModule(moduleId: ModuleId, mode: 'clear' | 'replace') {
...
@@ -563,8 +605,7 @@ function disposeModule(moduleId: ModuleId, mode: 'clear' | 'replace') {
disposeHandler
(
data
)
disposeHandler
(
data
)
}
}
// This used to warn in `getOrInstantiateModuleFromParent` when a disposed
// Mark module as inactive so imports from it can be detected
// module is still importing other modules.
module
.
hot
.
active
=
false
module
.
hot
.
active
=
false
moduleHotState
.
delete
(
module
)
moduleHotState
.
delete
(
module
)
...
@@ -778,12 +819,47 @@ function computeOutdatedSelfAcceptedModules(
...
@@ -778,12 +819,47 @@ function computeOutdatedSelfAcceptedModules(
function disposePhase(outdatedModules: Iterable<ModuleId>): {
function disposePhase(outdatedModules: Iterable<ModuleId>): {
outdatedModuleParents: Map<ModuleId, Array<ModuleId>>
outdatedModuleParents: Map<ModuleId, Array<ModuleId>>
} {
} {
// Collect all module IDs to dispose, including related variants
const modulesToDispose = new Set<ModuleId>()
for (const moduleId of outdatedModules) {
for (const moduleId of outdatedModules) {
modulesToDispose.add(moduleId)
const idStr = moduleId as string
// If this is a <locals> variant, also dispose the non-locals version
// Pattern: "...path [app-rsc] (ecmascript) <locals>" -> "...path [app-rsc] (ecmascript)"
if (idStr.endsWith(' <locals>')) {
const nonLocalsId = idStr.slice(0, -9) // Remove " <locals>"
modulesToDispose.add(nonLocalsId as ModuleId)
}
// Also dispose variants of the EXACT SAME module with different context annotations
// e.g., if we're disposing "path/page.tsx [app-rsc] (ecmascript)", also dispose
// "path/page.tsx [app-rsc] (ecmascript, Next.js Server Component)"
// But NOT different modules like "path/db.ts [app-rsc] (ecmascript)"
const contextStart = idStr.indexOf(' [app-')
if (contextStart !== -1) {
const exactBasePath = idStr.substring(0, contextStart)
// Find all cached modules with the EXACT SAME file path (not just prefix)
for (const cachedId of Object.keys(devModuleCache)) {
const cachedContextStart = cachedId.indexOf(' [app-')
if (cachedContextStart !== -1) {
const cachedBasePath = cachedId.substring(0, cachedContextStart)
// Only dispose if the base path matches EXACTLY
if (cachedBasePath === exactBasePath) {
modulesToDispose.add(cachedId as ModuleId)
}
}
}
}
}
for (const moduleId of modulesToDispose) {
disposeModule(moduleId, 'replace')
disposeModule(moduleId, 'replace')
}
}
const outdatedModuleParents = new Map<ModuleId, Array<ModuleId>>()
const outdatedModuleParents = new Map<ModuleId, Array<ModuleId>>()
for (const moduleId of
outdatedModules
) {
for (const moduleId of
modulesToDispose
) {
const oldModule = devModuleCache[moduleId]
const oldModule = devModuleCache[moduleId]
outdatedModuleParents.set(moduleId, oldModule?.parents || [])
outdatedModuleParents.set(moduleId, oldModule?.parents || [])
delete devModuleCache[moduleId]
delete devModuleCache[moduleId]
...
@@ -801,9 +877,16 @@ function applyPhase(
...
@@ -801,9 +877,16 @@ function applyPhase(
outdatedModuleParents: Map<ModuleId, Array<ModuleId>>,
outdatedModuleParents: Map<ModuleId, Array<ModuleId>>,
reportError: (err: any) => void
reportError: (err: any) => void
) {
) {
// Update module factories
// Update module factories
for the primary module IDs
for (const [moduleId, factory] of newModuleFactories.entries()) {
for (const [moduleId, factory] of newModuleFactories.entries()) {
moduleFactories.set(moduleId, factory)
moduleFactories.set(moduleId, factory)
// Also update factories for related module IDs (variants without <locals>)
const idStr = moduleId as string
if (idStr.endsWith(' <locals>')) {
const nonLocalsId = idStr.slice(0, -9) // Remove " <locals>"
moduleFactories.set(nonLocalsId as ModuleId, factory)
}
}
}
// Re-instantiate all outdated self-accepted modules
// Re-instantiate all outdated self-accepted modules
...
@@ -911,7 +994,34 @@ function applyEcmascriptMergedUpdate(update: EcmascriptMergedUpdate): boolean {
...
@@ -911,7 +994,34 @@ function applyEcmascriptMergedUpdate(update: EcmascriptMergedUpdate): boolean {
try {
try {
const { outdatedModules, newModuleFactories } =
const { outdatedModules, newModuleFactories } =
computeOutdatedModules(modified)
computeOutdatedModules(modified)
// We need to clear the chunk cache so that chunk loader accessor functions
// get fresh closures. The chunks contain inline code that creates accessor
// functions which close over module contexts. Without clearing, those
// accessors would still reference disposed modules.
//
// However, clearing the cache means chunks will be reloaded from disk when
// the bundle is re-required. Those disk chunks may have old code and will
// call moduleFactories.set() with their factories, potentially overwriting
// our HMR-applied factories.
//
// To handle this, we store the HMR factories and re-apply them after
// applyInternal completes, ensuring HMR factories take precedence.
clearChunkCache()
// Store the HMR factories so we can restore them if chunks overwrite them
const hmrFactories = new Map<ModuleId, ModuleFactory>()
for (const [moduleId, factory] of newModuleFactories) {
hmrFactories.set(moduleId, factory)
}
applyInternal(outdatedModules, newModuleFactories)
applyInternal(outdatedModules, newModuleFactories)
// After applying, re-set the HMR factories in case chunks overwrote them
// This ensures HMR factories always take precedence over chunk factories
for (const [moduleId, factory] of hmrFactories) {
moduleFactories.set(moduleId, factory)
}
return true
return true
} catch (err) {
} catch (err) {
if (err instanceof UpdateApplyError) {
if (err instanceof UpdateApplyError) {
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment