Commit e62258be authored by Will Binns-Smith's avatar Will Binns-Smith

Wire up server HMR update application

Connects the server HMR infrastructure to actually apply updates:

entry-base.ts:
- Exposes __next__server_hmr_apply__ global from the Turbopack runtime
- Adds ServerHmrUpdate type definition

hot-reloader-turbopack.ts:
- Adds applyServerHmrUpdate() to apply incremental module updates
- Updates server HMR subscriptions to call the apply function
- Falls back to full reload if update is not accepted

When an update is successfully applied, the Turbopack runtime handles
module disposal and re-instantiation. When not accepted, the existing
clearModuleContext + deleteCache flow handles the full reload.
parent 51f55989
...@@ -61,14 +61,36 @@ if (process.env.NODE_ENV === 'development') { ...@@ -61,14 +61,36 @@ if (process.env.NODE_ENV === 'development') {
declare global { declare global {
var __next__clear_chunk_cache__: (() => void) | null | undefined var __next__clear_chunk_cache__: (() => void) | null | undefined
var __turbopack_clear_chunk_cache__: () => void | null | undefined var __turbopack_clear_chunk_cache__: () => void | null | undefined
// Server-side HMR apply function - applies module updates and returns whether they were accepted
var __next__server_hmr_apply__:
| ((update: ServerHmrUpdate) => boolean)
| null
| undefined
var __turbopack_server_hmr_apply__:
| ((update: ServerHmrUpdate) => boolean)
| null
| undefined
} }
// Type for server HMR updates (matches EcmascriptMergedUpdate from the runtime)
interface ServerHmrUpdate {
type: 'EcmascriptMergedUpdate'
entries: Record<
string,
{ code: string; url: string; map?: string | undefined }
>
chunks?: Record<string, { type: 'partial' }>
}
// hot-reloader modules are not bundled so we need to inject `__next__clear_chunk_cache__` // hot-reloader modules are not bundled so we need to inject `__next__clear_chunk_cache__`
// into globalThis from this file which is bundled. // into globalThis from this file which is bundled.
if (process.env.TURBOPACK) { if (process.env.TURBOPACK) {
globalThis.__next__clear_chunk_cache__ = __turbopack_clear_chunk_cache__ globalThis.__next__clear_chunk_cache__ = __turbopack_clear_chunk_cache__
globalThis.__next__server_hmr_apply__ = __turbopack_server_hmr_apply__
} else { } else {
// Webpack does not have chunks on the server // Webpack does not have chunks on the server
globalThis.__next__clear_chunk_cache__ = null globalThis.__next__clear_chunk_cache__ = null
globalThis.__next__server_hmr_apply__ = null
} }
// patchFetch makes use of APIs such as `React.unstable_postpone` which are only available // patchFetch makes use of APIs such as `React.unstable_postpone` which are only available
......
...@@ -143,6 +143,20 @@ const sessionId = Math.floor(Number.MAX_SAFE_INTEGER * Math.random()) ...@@ -143,6 +143,20 @@ const sessionId = Math.floor(Number.MAX_SAFE_INTEGER * Math.random())
declare const __next__clear_chunk_cache__: (() => void) | null | undefined declare const __next__clear_chunk_cache__: (() => void) | null | undefined
// Type for server HMR updates (matches EcmascriptMergedUpdate from the runtime)
interface ServerHmrUpdate {
type: 'EcmascriptMergedUpdate'
entries: Record<
string,
{ code: string; url: string; map?: string | undefined }
>
chunks?: Record<string, { type: 'partial' }>
}
declare const __next__server_hmr_apply__:
| ((update: ServerHmrUpdate) => boolean)
| null
| undefined
/** /**
* Replaces turbopack:///[project] with the specified project in the `source` field. * Replaces turbopack:///[project] with the specified project in the `source` field.
*/ */
...@@ -1464,42 +1478,105 @@ export async function createHotReloaderTurbopack( ...@@ -1464,42 +1478,105 @@ export async function createHotReloaderTurbopack(
process.exit(1) process.exit(1)
}) })
// DEBUG: Test server HMR identifiers subscription // Server HMR subscriptions - track active subscriptions by identifier
const serverHmrSubscriptions = new Map< const serverHmrSubscriptions = new Map<
string, string,
AsyncIterableIterator<unknown> AsyncIterableIterator<TurbopackResult<TurbopackUpdate>>
>() >()
/**
* Apply a server HMR update. Returns true if the update was successfully applied
* (all affected modules accepted the update), false otherwise.
*/
function applyServerHmrUpdate(update: TurbopackUpdate): boolean {
if (typeof __next__server_hmr_apply__ !== 'function') {
// Server HMR not available (e.g., Pages Router or Edge Runtime)
return false
}
if (update.type !== 'partial') {
// Only partial updates can be applied incrementally
return false
}
const merged = update.instruction?.merged
if (!merged || merged.length === 0) {
// No actual module updates
return false
}
// Try to apply each merged update
for (const mergedUpdate of merged) {
if (mergedUpdate.type !== 'EcmascriptMergedUpdate') {
// Unknown update type, fall back to full reload
return false
}
const applied = __next__server_hmr_apply__(mergedUpdate)
if (!applied) {
// Update was not accepted, need full reload
return false
}
}
return true
}
/**
* Subscribe to server HMR events for a specific identifier.
* When updates arrive, attempts to apply them incrementally.
*/
function subscribeToServerHmr(identifier: string) {
if (serverHmrSubscriptions.has(identifier)) {
return
}
const subscription = project.serverHmrEvents(identifier)
serverHmrSubscriptions.set(identifier, subscription)
// Start listening for changes in background
;(async () => {
// Skip initial state
await subscription.next()
for await (const result of subscription) {
const update = result as TurbopackUpdate
const applied = applyServerHmrUpdate(update)
if (applied) {
console.log('[Server HMR] Applied update for:', identifier)
} else {
// Update not accepted - the existing serverChanged/clearModuleContext
// flow will handle the full reload
console.log(
'[Server HMR] Update not accepted for:',
identifier,
'- falling back to full reload'
)
}
}
})().catch((err) => {
console.error(
'[Server HMR] Event subscription error for',
identifier,
err
)
serverHmrSubscriptions.delete(identifier)
})
}
// Subscribe to server HMR identifiers to track available server modules
;(async () => { ;(async () => {
const serverHmrIdentifiers = project.serverHmrIdentifiersSubscribe() const serverHmrIdentifiers = project.serverHmrIdentifiersSubscribe()
// Skip initial // Skip initial state
await serverHmrIdentifiers.next() await serverHmrIdentifiers.next()
for await (const data of serverHmrIdentifiers) { for await (const data of serverHmrIdentifiers) {
console.log('[Server HMR] Identifiers updated:', data.identifiers.length) // Subscribe to HMR events for all server modules
// For testing, subscribe to page.js files // For now, focus on page.js files as a starting point
for (const identifier of data.identifiers) { for (const identifier of data.identifiers) {
if ( if (identifier.includes('page.js')) {
identifier.includes('page.js') && subscribeToServerHmr(identifier)
!serverHmrSubscriptions.has(identifier)
) {
console.log('[Server HMR] Subscribing to:', identifier)
const subscription = project.serverHmrEvents(identifier)
serverHmrSubscriptions.set(identifier, subscription)
// Start listening for changes in background
;(async () => {
// Skip initial
await subscription.next()
for await (const update of subscription) {
console.log('[Server HMR] Update for', identifier, ':', update)
}
})().catch((err) => {
console.error(
'[Server HMR] Event subscription error for',
identifier,
':',
err
)
})
} }
} }
} }
......
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