Unverified Commit db1ff7c6 authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Turbopack: Implement server hmr in nodejs dev runtime (#89130)

This implements the remainder of functionality needed for Server HMR
(Fast Refresh).

How It Works

- Turbopack detects file changes in RSC modules
- Rust sends HMR update payloads to the Node.js runtime via the existing
chunk update system
- A Node-specific HMR client evaluates changed modules using shared HMR
runtime logic (extracted earlier in this stack)
- Only modified modules are re-evaluated. Unmodified modules retain
their state
- Next.js hot-reloader forwards updates to RSC workers, triggering
automatic re-renders in clients

Test Plan: Added an e2e test confirming that unaffected modules don't
get re-evaluated when others change.
parent 098c591f
......@@ -10146,6 +10146,9 @@ dependencies = [
"anyhow",
"bincode 2.0.1",
"indoc",
"serde",
"serde_json",
"serde_qs",
"tracing",
"turbo-bincode",
"turbo-rcstr",
......
......@@ -303,7 +303,12 @@ export default defineConfig([
'jest/no-standalone-expect': [
'error',
{
additionalTestBlockFunctions: ['retry', 'itCI', 'itHeaded'],
additionalTestBlockFunctions: [
'retry',
'itCI',
'itHeaded',
'itTurbopackDev',
],
},
],
},
......
......@@ -150,11 +150,20 @@ declare const __turbopack_server_hmr_apply__:
| ((update: NodeJsPartialHmrUpdate) => boolean)
| undefined
function setupServerHmr(project: Project) {
const serverHmrSubscriptions = new Map<
string,
AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>
>()
type ServerHmrSubscriptions = Map<
string,
AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>
>
function setupServerHmr(
project: Project,
{
onUpdateFailed,
}: {
onUpdateFailed: () => void | Promise<void>
}
) {
const serverHmrSubscriptions: ServerHmrSubscriptions = new Map()
/**
* Subscribe to HMR updates for a server chunk.
......@@ -175,67 +184,69 @@ function setupServerHmr(project: Project) {
for await (const result of subscription) {
const update = result as NodeJsHmrUpdate
// Only process partial updates with actual code changes
if (update.type !== 'partial') {
continue
}
const entries = update.instruction?.entries
if (!entries || Object.keys(entries).length === 0) {
const instruction = update.instruction
if (!instruction || instruction.type !== 'EcmascriptMergedUpdate') {
continue
}
if (typeof __turbopack_server_hmr_apply__ === 'function') {
const applied = __turbopack_server_hmr_apply__(update as any)
if (applied) {
console.log(`[Server HMR] Applied update for ${chunkPath}`)
// TODO: Notify clients to refresh and get updated server content
// This will trigger the client to re-fetch the page with new server components
const applied = __turbopack_server_hmr_apply__(update)
if (!applied) {
await onUpdateFailed()
}
}
}
})().catch((err) => {
})().catch(async (err) => {
console.error('[Server HMR] Subscription error:', err)
serverHmrSubscriptions.delete(chunkPath)
await onUpdateFailed()
})
}
// Listen to the Rust bindings update us on changing server HMR chunk paths
;(async () => {
const serverHmrChunkPaths = project.hmrChunkNamesSubscribe(HmrTarget.Server)
// Process chunk paths (both initial and subsequent updates)
for await (const data of serverHmrChunkPaths) {
const currentChunkPaths = new Set(
data.chunkNames.filter((path) => path.endsWith('.js'))
try {
const serverHmrChunkPaths = project.hmrChunkNamesSubscribe(
HmrTarget.Server
)
// Clean up subscriptions for removed chunk paths (like when pages are deleted)
const chunkPathsToRemove = []
for (const chunkPath of serverHmrSubscriptions.keys()) {
if (!currentChunkPaths.has(chunkPath)) {
chunkPathsToRemove.push(chunkPath)
// Process chunk paths (both initial and subsequent updates)
for await (const data of serverHmrChunkPaths) {
const currentChunkPaths = new Set<string>(
data.chunkNames.filter((path) => path.endsWith('.js'))
)
// Clean up subscriptions for removed chunk paths (like when pages are deleted)
const chunkPathsToRemove: string[] = []
for (const chunkPath of serverHmrSubscriptions.keys()) {
if (!currentChunkPaths.has(chunkPath)) {
chunkPathsToRemove.push(chunkPath)
}
}
}
for (const chunkPath of chunkPathsToRemove) {
const subscription = serverHmrSubscriptions.get(chunkPath)
subscription?.return?.()
serverHmrSubscriptions.delete(chunkPath)
}
for (const chunkPath of chunkPathsToRemove) {
const subscription = serverHmrSubscriptions.get(chunkPath)
subscription?.return?.()
serverHmrSubscriptions.delete(chunkPath)
}
// Subscribe to HMR events for new server chunks
for (const chunkPath of currentChunkPaths) {
if (!serverHmrSubscriptions.has(chunkPath)) {
subscribeToServerHmr(chunkPath)
// Subscribe to HMR events for new server chunks
for (const chunkPath of currentChunkPaths) {
if (!serverHmrSubscriptions.has(chunkPath)) {
subscribeToServerHmr(chunkPath)
}
}
}
} catch (err) {
console.error('[Server HMR Setup] Error in chunk path subscription:', err)
}
})().catch((err) => {
console.error('[Server HMR] error:', err)
})
})()
return serverHmrSubscriptions
}
/**
......@@ -558,22 +569,35 @@ export async function createHotReloaderTurbopack(
resetFetch()
// Not available in:
// - Pages Router (no server-side HMR)
// - Edge Runtime (uses browser runtime which already disposes chunks individually)
if (typeof __next__clear_chunk_cache__ === 'function') {
__next__clear_chunk_cache__()
}
const serverPaths = writtenEndpoint.serverPaths.map(({ path: p }) =>
join(distDir, p)
)
for (const file of serverPaths) {
// Skip clearing cache for server chunks with active HMR subscriptions
// Server HMR already applied granular updates to the turbopack module cache
const relativePath = relative(distDir, file)
if (serverHmrSubscriptions?.has(relativePath)) {
continue
}
clearModuleContext(file)
deleteCache(file)
}
// Clear Turbopack's module cache when server HMR is not active.
// When server HMR IS active, HMR manages the module cache granularly,
// so we must not clear it here.
// Not available in:
// - Pages Router (no server-side HMR)
// - Edge Runtime (uses browser runtime which already disposes chunks individually)
if (
!serverHmrSubscriptions &&
typeof __next__clear_chunk_cache__ === 'function'
) {
__next__clear_chunk_cache__()
}
return true
}
......@@ -612,9 +636,7 @@ export async function createHotReloaderTurbopack(
}
}
if (experimentalServerFastRefresh) {
setupServerHmr(project)
}
let serverHmrSubscriptions: ServerHmrSubscriptions | undefined
let hmrEventHappened = false
let hmrHash = 0
......@@ -1760,5 +1782,24 @@ export async function createHotReloaderTurbopack(
process.exit(1)
})
if (experimentalServerFastRefresh) {
serverHmrSubscriptions = setupServerHmr(project, {
onUpdateFailed: async () => {
if (typeof __next__clear_chunk_cache__ === 'function') {
__next__clear_chunk_cache__()
}
// Clear all module contexts so they're re-evaluated on next request
await clearAllModuleContexts()
// Tell browsers to refetch RSC (soft refresh, not full page reload)
hotReloader.send({
type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES,
hash: String(++hmrHash),
})
},
})
}
return hotReloader
}
import { message, evaluatedAt } from '../child-module'
export default function Page() {
return (
<div>
<p id="message">{message}</p>
<p id="eval-time">Module evaluated at: {evaluatedAt}</p>
</div>
)
}
export const message = 'Initial message'
export const evaluatedAt = Date.now()
declare const module: any
if (typeof module !== 'undefined' && module.hot) {
module.hot.accept()
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { evaluatedAt } from '../unmodified-module'
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>
)
}
export const _hmrTrigger = 0
export const evaluatedAt = Date.now()
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('server-hmr', () => {
const { next, isTurbopack, isNextDev } = nextTestSetup({
files: __dirname,
startArgs: ['--experimental-server-fast-refresh'],
})
// Server HMR is a Turbopack-only feature, only available in dev mode
const itTurbopackDev = isTurbopack && isNextDev ? it : it.skip
describe('module preservation', () => {
itTurbopackDev(
'does not re-evaluate an unmodified module when page module changes',
async () => {
const browser = await next.browser('/module-preservation')
// 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()
// Make a change to the page that doesn't affect the unmodified module
await next.patchFile('app/module-preservation/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)
}
)
itTurbopackDev(
're-evaluates a module when the module itself changes',
async () => {
const browser = await next.browser('/module-preservation')
// 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()
// Make a change to the module itself to trigger re-evaluation
await next.patchFile('app/unmodified-module.ts', (content) =>
content.replace('_hmrTrigger = 0', '_hmrTrigger = 1')
)
// 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)
})
}
)
})
describe('child module accept', () => {
itTurbopackDev(
'allows child modules to accept hot updates using module.hot.accept',
async () => {
const browser = await next.browser('/child-accept')
// Wait for initial render
await retry(async () => {
const text = await browser.elementByCss('#message').text()
expect(text).toBe('Initial message')
})
const initialEvalTime = await browser.elementByCss('#eval-time').text()
expect(initialEvalTime).toMatch(/Module evaluated at: \d+/)
// Make a change to the child module
// The child module calls module.hot.accept(), which allows it to
// accept updates. While pages auto-accept at the top level in server HMR,
// this test verifies that module.hot.accept() is available and functional
// in non-page, user-authored child modules.
await next.patchFile('app/child-module.ts', (content) =>
content.replace('Initial message', 'Updated message')
)
// Wait for HMR to apply - the child module should accept the update
await retry(async () => {
const text = await browser.elementByCss('#message').text()
expect(text).toBe('Updated message')
})
// The module should have been re-evaluated (new timestamp)
const newEvalTime = await browser.elementByCss('#eval-time').text()
expect(newEvalTime).not.toBe(initialEvalTime)
// Apply another update to verify the module continues to accept updates
await next.patchFile('app/child-module.ts', (content) =>
content.replace('Updated message', 'Second update')
)
await retry(async () => {
const text = await browser.elementByCss('#message').text()
expect(text).toBe('Second update')
})
}
)
})
})
// Adapted from https://github.com/vercel/next.js/blob/canary/packages/next/src/client/dev/error-overlay/websocket.ts
import type { WebSocketMessage } from '@vercel/turbopack-ecmascript-runtime/browser/dev/hmr-client/hmr-client'
import type { HmrMessage } from '@vercel/turbopack-ecmascript-runtime/browser/dev/hmr-client/hmr-client'
let source: WebSocket
const messageCallbacks: ((message: WebSocketMessage) => void)[] = []
const messageCallbacks: ((message: HmrMessage) => void)[] = []
// TODO: add timeout again
// let lastActivity = Date.now()
......@@ -19,7 +19,7 @@ function getSocketProtocol(assetPrefix: string): string {
return protocol === 'http:' ? 'ws' : 'wss'
}
export function addMessageListener(cb: (message: WebSocketMessage) => void) {
export function addMessageListener(cb: (message: HmrMessage) => void) {
messageCallbacks.push(cb)
}
......
......@@ -21,6 +21,9 @@ devModuleCache = Object.create(null)
devContextPrototype.c = devModuleCache
runtimeModules = new Set()
// Set flag to indicate we use ModuleWithDirection
createModuleWithDirectionFlag = true
// This file must not use `import` and `export` statements. Otherwise, it
// becomes impossible to augment interfaces declared in `<reference>`d files
// (e.g. `Module`). Hence, the need for `import()` here.
......@@ -381,10 +384,11 @@ function applyEcmascriptMergedUpdate(update: EcmascriptMergedUpdate) {
modified,
disposedModules,
evalModuleEntry: _eval, // browser's eval with source maps
instantiateModule,
instantiateModule, // now wraps shared logic
applyModuleFactoryName,
moduleFactories,
devModuleCache,
autoAcceptRootModules: false,
})
}
......
/// <reference path="../../shared/runtime/dev-protocol.d.ts" />
/// <reference path="./hmr-client.ts" />
/**
* Note: hmr-runtime.ts is embedded before this file, so its functions
* (initializeServerHmr, emitMessage) are available in the same scope.
*/
// Initialize server HMR client (connects to shared HMR infrastructure)
let hmrClientInitialized = false
function ensureHmrClientInitialized() {
if (hmrClientInitialized) return
hmrClientInitialized = true
// initializeServerHmr is from hmr-client.ts (embedded before this file)
// moduleFactories is from dev-runtime.ts
// devModuleCache is the HotModule-typed cache from dev-runtime.ts
initializeServerHmr(moduleFactories, devModuleCache)
}
function __turbopack_server_hmr_apply__(update: NodeJsHmrPayload): boolean {
try {
ensureHmrClientInitialized()
// emitMessage returns false if any listener failed to apply the update
return emitMessage({
type: 'turbopack-message',
data: update,
})
} catch (err) {
console.error('[Server HMR] Failed to apply update:', err)
return false
}
}
globalThis.__turbopack_server_hmr_apply__ = __turbopack_server_hmr_apply__
/// <reference path="../../shared/runtime/dev-protocol.d.ts" />
/// <reference path="../../shared/runtime/hmr-runtime.ts" />
/* eslint-disable @typescript-eslint/no-unused-vars */
type NodeJsHmrPayload = {
resource: {
path: string
headers?: Record<string, string>
}
issues: Issue[]
type: 'partial'
instruction: EcmascriptMergedUpdate
}
let serverHmrUpdateHandler: ((msg: NodeJsHmrPayload) => void) | null = null
function initializeServerHmr(
moduleFactories: ModuleFactories,
devModuleCache: ModuleCache<HotModule>
): void {
if (serverHmrUpdateHandler != null) {
throw new Error('[Server HMR] Server HMR client is already initialized')
}
// Register the update handler for the server runtime
serverHmrUpdateHandler = (msg: NodeJsHmrPayload) => {
handleNodejsUpdate(msg, moduleFactories, devModuleCache)
}
}
/**
* Emits an HMR message to the registered update handler.
* Node uses a simpler listener pattern than the browser's websocket connection.
*
* Note: This is only called via __turbopack_server_hmr_apply__ which ensures
* the handler is initialized first via ensureHmrClientInitialized().
*/
function emitMessage(msg: { type: string; data: any }): boolean {
if (serverHmrUpdateHandler == null) {
console.warn(
'[Server HMR] No update handler registered to receive message:',
msg
)
return false
}
try {
serverHmrUpdateHandler(msg.data)
return true
} catch (err) {
console.error('[Server HMR] Listener error:', err)
return false
}
}
/**
* Handles server message updates and applies them to the Node.js runtime.
* Uses shared HMR update logic from hmr-runtime.ts.
*/
function handleNodejsUpdate(
msg: NodeJsHmrPayload,
moduleFactories: ModuleFactories,
devModuleCache: ModuleCache<HotModule>
): void {
if (msg.type !== 'partial') {
return
}
const instruction = msg.instruction
if (instruction.type !== 'EcmascriptMergedUpdate') {
return
}
try {
const { entries = {}, chunks = {} } = instruction
// Node.js eval function (no source maps)
const evalModuleEntry = (entry: EcmascriptModuleEntry) => {
// eslint-disable-next-line no-eval
return (0, eval)(entry.code)
}
const { added, modified } = computeChangedModules(
entries,
chunks,
undefined // no chunkModulesMap for Node.js
)
// Use shared HMR update implementation
applyEcmascriptMergedUpdateShared({
added,
modified,
disposedModules: [], // no disposedModules for Node.js (no chunk management)
evalModuleEntry,
instantiateModule,
applyModuleFactoryName: () => {}, // Node doesn't use this
moduleFactories,
devModuleCache,
autoAcceptRootModules: true,
})
} catch (e) {
console.error('[Server HMR] Update failed, full reload needed:', e)
throw e
}
}
/* eslint-disable @typescript-eslint/no-unused-vars */
/// <reference path="./runtime-base.ts" />
/**
* Production Node.js runtime.
* Uses ModuleWithDirection and simple module instantiation without HMR support.
*/
// moduleCache and moduleFactories are declared in runtime-base.ts
// this is read in runtime-utils.ts so it creates a module with direction for hmr
createModuleWithDirectionFlag = true
interface TurbopackNodeBuildContext
extends TurbopackBaseContext<ModuleWithDirection> {
R: ResolvePathFromModule
x: ExternalRequire
y: ExternalImport
C: typeof clearChunkCache
}
const nodeContextPrototype = Context.prototype as TurbopackNodeBuildContext
nodeContextPrototype.q = exportUrl
nodeContextPrototype.M = moduleFactories
// Cast moduleCache to ModuleWithDirection for production mode
nodeContextPrototype.c = moduleCache as ModuleCache<ModuleWithDirection>
nodeContextPrototype.R = resolvePathFromModule
nodeContextPrototype.b = createWorker
nodeContextPrototype.C = clearChunkCache
function instantiateModule(
id: ModuleId,
sourceType: SourceType,
sourceData: SourceData
): ModuleWithDirection {
const moduleFactory = moduleFactories.get(id)
if (typeof moduleFactory !== 'function') {
// This can happen if modules incorrectly handle HMR disposes/updates,
// e.g. when they keep a `setTimeout` around which still executes old code
// and contains e.g. a `require("something")` call.
let instantiationReason: string
switch (sourceType) {
case SourceType.Runtime:
instantiationReason = `as a runtime entry of chunk ${sourceData}`
break
case SourceType.Parent:
instantiationReason = `because it was required from module ${sourceData}`
break
default:
invariant(
sourceType,
(sourceType) => `Unknown source type: ${sourceType}`
)
}
throw new Error(
`Module ${id} was instantiated ${instantiationReason}, but the module factory is not available.`
)
}
const module: ModuleWithDirection = createModuleWithDirection(id)
const exports = module.exports
moduleCache[id] = module
const context =
new (Context as any as ContextConstructor<ModuleWithDirection>)(
module,
exports
)
// NOTE(alexkirsz) This can fail when the module encounters a runtime error.
try {
moduleFactory(context, module, exports)
} catch (error) {
module.error = error as any
throw error
}
;(module as any).loaded = true
if (module.namespaceObject && module.exports !== module.namespaceObject) {
// in case of a circular dependency: cjs1 -> esm2 -> cjs1
interopEsm(module.exports, module.namespaceObject)
}
return module
}
/**
* Retrieves a module from the cache, or instantiate it if it is not cached.
*/
// @ts-ignore
function getOrInstantiateModuleFromParent(
id: ModuleId,
sourceModule: ModuleWithDirection
): ModuleWithDirection {
const module = moduleCache[id]
if (module) {
if (module.error) {
throw module.error
}
return module
}
return instantiateModule(id, SourceType.Parent, sourceModule.id)
}
/**
* Instantiates a runtime module.
*/
function instantiateRuntimeModule(
chunkPath: ChunkPath,
moduleId: ModuleId
): ModuleWithDirection {
return instantiateModule(moduleId, SourceType.Runtime, chunkPath)
}
/**
* Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached.
*/
// @ts-ignore TypeScript doesn't separate this module space from the browser runtime
function getOrInstantiateRuntimeModule(
chunkPath: ChunkPath,
moduleId: ModuleId
): ModuleWithDirection {
const module = moduleCache[moduleId]
if (module) {
if (module.error) {
throw module.error
}
return module
}
return instantiateRuntimeModule(chunkPath, moduleId)
}
module.exports = (sourcePath: ChunkPath) => ({
m: (id: ModuleId) => getOrInstantiateRuntimeModule(sourcePath, id),
c: (chunkData: ChunkData) => loadRuntimeChunk(sourcePath, chunkData),
})
/* eslint-disable @typescript-eslint/no-unused-vars */
/// <reference path="./runtime-base.ts" />
/// <reference path="../../shared/runtime/dev-extensions.ts" />
/// <reference path="../../shared/runtime/hmr-runtime.ts" />
/**
* Development Node.js runtime.
* Uses HotModule and shared HMR logic for hot module replacement support.
*/
// Cast the module cache to HotModule for development mode
// (hmr-runtime.ts declares devModuleCache as `let` variable expecting assignment)
// This is safe because HotModule extends Module
devModuleCache = moduleCache as ModuleCache<HotModule>
// this is read in runtime-utils.ts so it creates a module with direction for hmr
createModuleWithDirectionFlag = true
if (!globalThis.__turbopack_runtime_modules__) {
globalThis.__turbopack_runtime_modules__ = new Set()
}
runtimeModules = globalThis.__turbopack_runtime_modules__
interface TurbopackNodeDevBuildContext extends TurbopackBaseContext<HotModule> {
R: ResolvePathFromModule
x: ExternalRequire
y: ExternalImport
C: typeof clearChunkCache
}
const nodeDevContextPrototype =
Context.prototype as TurbopackNodeDevBuildContext
nodeDevContextPrototype.q = exportUrl
nodeDevContextPrototype.M = moduleFactories
nodeDevContextPrototype.c = devModuleCache
nodeDevContextPrototype.R = resolvePathFromModule
nodeDevContextPrototype.b = createWorker
nodeDevContextPrototype.C = clearChunkCache
/**
* Instantiates a module in development mode using shared HMR logic.
*/
function instantiateModule(
id: ModuleId,
sourceType: SourceType,
sourceData: SourceData
): HotModule {
// Node.js: creates base module object (hot API added by shared code)
const createModuleObjectFn = (moduleId: ModuleId) => {
return createModuleWithDirection(moduleId) as HotModule
}
// Node.js: creates Context (no refresh parameter)
const createContext = (
module: HotModule,
exports: Exports,
_refresh?: any
) => {
return new (Context as any as ContextConstructor<HotModule>)(
module,
exports
)
}
// Node.js: no hooks wrapper, just execute directly
const runWithHooks = (module: HotModule, exec: (refresh: any) => void) => {
exec(undefined) // no refresh context
}
// Use shared instantiation logic (includes hot API setup)
const newModule = instantiateModuleShared(
id,
sourceType,
sourceData,
moduleFactories,
devModuleCache,
runtimeModules,
createModuleObjectFn,
createContext,
runWithHooks
)
// Node.js-specific: mark module as loaded
;(newModule as any).loaded = true
return newModule
}
/**
* Instantiates a runtime module in development mode.
*/
function instantiateRuntimeModule(
chunkPath: ChunkPath,
moduleId: ModuleId
): HotModule {
return instantiateModule(moduleId, SourceType.Runtime, chunkPath)
}
/**
* Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached.
*/
// @ts-ignore TypeScript doesn't separate this module space from the browser runtime
function getOrInstantiateRuntimeModule(
chunkPath: ChunkPath,
moduleId: ModuleId
): HotModule {
const module = devModuleCache[moduleId]
if (module) {
if (module.error) {
throw module.error
}
return module
}
return instantiateRuntimeModule(chunkPath, moduleId)
}
/**
* Retrieves a module from the cache, or instantiate it if it is not cached.
* Also tracks parent-child relationships for HMR dependency tracking.
*/
// @ts-ignore
function getOrInstantiateModuleFromParent(
id: ModuleId,
sourceModule: HotModule
): HotModule {
// Track parent-child relationship
trackModuleImport(sourceModule, id, devModuleCache[id])
const module = devModuleCache[id]
if (module) {
if (module.error) {
throw module.error
}
return module
}
const newModule = instantiateModule(id, SourceType.Parent, sourceModule.id)
// Track again after instantiation to ensure the relationship is recorded
trackModuleImport(sourceModule, id, newModule)
return newModule
}
module.exports = (sourcePath: ChunkPath) => ({
m: (id: ModuleId) => getOrInstantiateRuntimeModule(sourcePath, id),
c: (chunkData: ChunkData) => loadRuntimeChunk(sourcePath, chunkData),
})
/// <reference path="../../shared/runtime-types.d.ts" />
/**
* Global type definitions for Node.js Turbopack runtime.
* These properties are stored on globalThis to persist across chunk reloads during HMR.
*/
declare global {
var __turbopack_module_factories__: ModuleFactories
var __turbopack_module_cache__: Record<ModuleId, any>
var __turbopack_runtime_modules__: Set<ModuleId>
}
export {}
/* eslint-disable @typescript-eslint/no-unused-vars */
/// <reference path="../hmr-types.d.ts" />
/// <reference path="../../shared/runtime/runtime-utils.ts" />
/// <reference path="../../shared-node/base-externals-utils.ts" />
/// <reference path="../../shared-node/node-externals-utils.ts" />
/// <reference path="../../shared-node/node-wasm-utils.ts" />
/// <reference path="./nodejs-globals.d.ts" />
enum SourceType {
/**
* The module was instantiated because it was included in an evaluated chunk's
* runtime.
* SourceData is a ChunkPath.
*/
Runtime = 0,
/**
* The module was instantiated because a parent module imported it.
* SourceData is a ModuleId.
*/
Parent = 1,
}
type SourceData = ChunkPath | ModuleId
/**
* Base Node.js runtime shared between production and development.
* Contains chunk loading, module caching, and other non-HMR functionality.
*/
process.env.TURBOPACK = '1'
interface TurbopackNodeBuildContext extends TurbopackBaseContext<Module> {
R: ResolvePathFromModule
x: ExternalRequire
y: ExternalImport
q: ExportUrl
}
const nodeContextPrototype = Context.prototype as TurbopackNodeBuildContext
type ModuleFactory = (
this: Module['exports'],
context: TurbopackNodeBuildContext
) => unknown
const url = require('url') as typeof import('url')
const moduleFactories: ModuleFactories = new Map()
nodeContextPrototype.M = moduleFactories
const moduleCache: ModuleCache<Module> = Object.create(null)
nodeContextPrototype.c = moduleCache
/**
* Returns an absolute path to the given module's id.
......@@ -63,7 +36,6 @@ function resolvePathFromModule(
return url.pathToFileURL(resolved).href
}
nodeContextPrototype.R = resolvePathFromModule
/**
* Exports a URL value. No suffix is added in Node.js runtime.
......@@ -75,7 +47,6 @@ function exportUrl(
) {
exportValue.call(this, urlValue, id)
}
nodeContextPrototype.q = exportUrl
function loadRuntimeChunk(sourcePath: ChunkPath, chunkData: ChunkData): void {
if (typeof chunkData === 'string') {
......@@ -92,6 +63,7 @@ const chunkCache = new Map<ChunkPath, Promise<void>>()
function clearChunkCache() {
chunkCache.clear()
loadedChunks.clear()
}
function loadRuntimeChunkPath(
......@@ -126,8 +98,8 @@ function loadRuntimeChunkPath(
}
}
function loadChunkAsync(
this: TurbopackBaseContext<Module>,
function loadChunkAsync<TModule extends Module>(
this: TurbopackBaseContext<TModule>,
chunkData: ChunkData
): Promise<void> {
const chunkPath = typeof chunkData === 'string' ? chunkData : chunkData.path
......@@ -162,8 +134,8 @@ function loadChunkAsync(
}
contextPrototype.l = loadChunkAsync
function loadChunkAsyncByUrl(
this: TurbopackBaseContext<Module>,
function loadChunkAsyncByUrl<TModule extends Module>(
this: TurbopackBaseContext<TModule>,
chunkUrl: string
) {
const path = url.fileURLToPath(new URL(chunkUrl, RUNTIME_ROOT)) as ChunkPath
......@@ -224,112 +196,6 @@ function createWorker(
return new WorkerConstructor(workerPath, options)
}
nodeContextPrototype.b = createWorker
function instantiateModule(
id: ModuleId,
sourceType: SourceType,
sourceData: SourceData
): Module {
const moduleFactory = moduleFactories.get(id)
if (typeof moduleFactory !== 'function') {
// This can happen if modules incorrectly handle HMR disposes/updates,
// e.g. when they keep a `setTimeout` around which still executes old code
// and contains e.g. a `require("something")` call.
let instantiationReason: string
switch (sourceType) {
case SourceType.Runtime:
instantiationReason = `as a runtime entry of chunk ${sourceData}`
break
case SourceType.Parent:
instantiationReason = `because it was required from module ${sourceData}`
break
default:
invariant(
sourceType,
(sourceType) => `Unknown source type: ${sourceType}`
)
}
throw new Error(
`Module ${id} was instantiated ${instantiationReason}, but the module factory is not available.`
)
}
const module: Module = createModuleObject(id)
const exports = module.exports
moduleCache[id] = module
const context = new (Context as any as ContextConstructor<Module>)(
module,
exports
)
// NOTE(alexkirsz) This can fail when the module encounters a runtime error.
try {
moduleFactory(context, module, exports)
} catch (error) {
module.error = error as any
throw error
}
module.loaded = true
if (module.namespaceObject && module.exports !== module.namespaceObject) {
// in case of a circular dependency: cjs1 -> esm2 -> cjs1
interopEsm(module.exports, module.namespaceObject)
}
return module
}
/**
* Retrieves a module from the cache, or instantiate it if it is not cached.
*/
// @ts-ignore
function getOrInstantiateModuleFromParent(
id: ModuleId,
sourceModule: Module
): Module {
const module = moduleCache[id]
if (module) {
if (module.error) {
throw module.error
}
return module
}
return instantiateModule(id, SourceType.Parent, sourceModule.id)
}
/**
* Instantiates a runtime module.
*/
function instantiateRuntimeModule(
chunkPath: ChunkPath,
moduleId: ModuleId
): Module {
return instantiateModule(moduleId, SourceType.Runtime, chunkPath)
}
/**
* Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached.
*/
// @ts-ignore TypeScript doesn't separate this module space from the browser runtime
function getOrInstantiateRuntimeModule(
chunkPath: ChunkPath,
moduleId: ModuleId
): Module {
const module = moduleCache[moduleId]
if (module) {
if (module.error) {
throw module.error
}
return module
}
return instantiateRuntimeModule(chunkPath, moduleId)
}
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/
/**
* Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
......@@ -337,18 +203,3 @@ const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/
function isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {
return regexJsUrl.test(chunkUrlOrPath)
}
function __turbopack_server_hmr_apply__(
_update: NodeJsPartialHmrUpdate
): boolean {
// TODO: Implement actual HMR logic to update module factories
// For now, just return true to indicate we "accepted" the update
return true
}
globalThis.__turbopack_server_hmr_apply__ = __turbopack_server_hmr_apply__
module.exports = (sourcePath: ChunkPath) => ({
m: (id: ModuleId) => getOrInstantiateRuntimeModule(sourcePath, id),
c: (chunkData: ChunkData) => loadRuntimeChunk(sourcePath, chunkData),
})
......@@ -102,11 +102,14 @@ function formatDependencyChain(dependencyChain: ModuleId[]): string {
* Returns information about whether the update can be accepted and which
* modules need to be invalidated.
*
* Copied directly from browser implementation.
*
* @param moduleId - The module to check for effects
* @param moduleId - The module that changed
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept().
* This is used for server-side HMR where pages auto-accept at the top level.
*/
function getAffectedModuleEffects(moduleId: ModuleId): ModuleEffect {
function getAffectedModuleEffects(
moduleId: ModuleId,
autoAcceptRootModules: boolean
): ModuleEffect {
const outdatedModules: Set<ModuleId> = new Set()
type QueueItem = { moduleId?: ModuleId; dependencyChain: ModuleId[] }
......@@ -120,25 +123,34 @@ function getAffectedModuleEffects(moduleId: ModuleId): ModuleEffect {
let nextItem
while ((nextItem = queue.shift())) {
const { moduleId: currentModuleId, dependencyChain } = nextItem
const { moduleId, dependencyChain } = nextItem
if (moduleId != null) {
if (outdatedModules.has(moduleId)) {
// Avoid infinite loops caused by cycles between modules in the dependency chain.
continue
}
outdatedModules.add(moduleId)
}
// We've arrived at the runtime of the chunk, which means that nothing
// else above can accept this update.
if (currentModuleId === undefined) {
if (moduleId === undefined) {
if (autoAcceptRootModules) {
return {
type: 'accepted',
moduleId,
outdatedModules,
}
}
return {
type: 'unaccepted',
dependencyChain,
}
}
if (outdatedModules.has(currentModuleId)) {
// Avoid infinite loops caused by cycles between modules in the dependency chain.
continue
}
outdatedModules.add(currentModuleId)
const module = devModuleCache[currentModuleId]
const module = devModuleCache[moduleId]
const hotState = moduleHotState.get(module)!
if (
......@@ -155,14 +167,17 @@ function getAffectedModuleEffects(moduleId: ModuleId): ModuleEffect {
return {
type: 'self-declined',
dependencyChain,
moduleId: currentModuleId,
moduleId,
}
}
if (runtimeModules.has(currentModuleId)) {
if (runtimeModules.has(moduleId)) {
if (autoAcceptRootModules) {
continue
}
queue.push({
moduleId: undefined,
dependencyChain: [...dependencyChain, currentModuleId],
dependencyChain: [...dependencyChain, moduleId],
})
continue
}
......@@ -180,9 +195,14 @@ function getAffectedModuleEffects(moduleId: ModuleId): ModuleEffect {
queue.push({
moduleId: parentId,
dependencyChain: [...dependencyChain, currentModuleId],
dependencyChain: [...dependencyChain, moduleId],
})
}
// If no parents and we're at a root module, auto-accept if configured
if (module.parents.length === 0 && autoAcceptRootModules) {
continue
}
}
return {
......@@ -195,17 +215,17 @@ function getAffectedModuleEffects(moduleId: ModuleId): ModuleEffect {
/**
* Computes all modules that need to be invalidated based on which modules changed.
*
* Copied directly from browser implementation.
*
* @param invalidated - The modules to check for invalidation
* @param invalidated - The modules that have been invalidated
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/
function computedInvalidatedModules(
invalidated: Iterable<ModuleId>
invalidated: Iterable<ModuleId>,
autoAcceptRootModules: boolean
): Set<ModuleId> {
const outdatedModules = new Set<ModuleId>()
for (const moduleId of invalidated) {
const effect = getAffectedModuleEffects(moduleId)
const effect = getAffectedModuleEffects(moduleId, autoAcceptRootModules)
switch (effect.type) {
case 'unaccepted':
......@@ -325,14 +345,18 @@ function createModuleHot(
* Processes queued invalidated modules and adds them to the outdated modules set.
* Modules that call module.hot.invalidate() are queued and processed here.
*
* @param outdatedModules - The set of already outdated modules
* @param outdatedModules - The current set of outdated modules
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/
function applyInvalidatedModules(
outdatedModules: Set<ModuleId>
outdatedModules: Set<ModuleId>,
autoAcceptRootModules: boolean
): Set<ModuleId> {
if (queuedInvalidatedModules.size > 0) {
computedInvalidatedModules(queuedInvalidatedModules).forEach((moduleId) => {
computedInvalidatedModules(
queuedInvalidatedModules,
autoAcceptRootModules
).forEach((moduleId) => {
outdatedModules.add(moduleId)
})
......@@ -600,7 +624,7 @@ function computeChangedModules(
break
}
default:
throw new Error(`Unknown merged chunk update`)
throw new Error('Unknown merged chunk update type')
}
}
......@@ -634,11 +658,13 @@ function computeChangedModules(
* @param added - Map of added modules
* @param modified - Map of modified modules
* @param evalModuleEntry - Function to compile module code
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/
function computeOutdatedModules(
added: Map<ModuleId, EcmascriptModuleEntry | undefined>,
modified: Map<ModuleId, EcmascriptModuleEntry>,
evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction
evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction,
autoAcceptRootModules: boolean
): {
outdatedModules: Set<ModuleId>
newModuleFactories: Map<ModuleId, HotModuleFactoryFunction>
......@@ -653,8 +679,12 @@ function computeOutdatedModules(
}
// Walk dependency tree to find all modules affected by modifications
const outdatedModules = computedInvalidatedModules(modified.keys())
const outdatedModules = computedInvalidatedModules(
modified.keys(),
autoAcceptRootModules
)
// Compile modified modules
for (const [moduleId, entry] of modified) {
newModuleFactories.set(moduleId, evalModuleEntry(entry))
}
......@@ -719,6 +749,8 @@ function applyPhase(
/**
* Internal implementation that orchestrates the full HMR update flow:
* invalidation, disposal, and application of new modules.
*
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/
function applyInternal(
outdatedModules: Set<ModuleId>,
......@@ -731,9 +763,13 @@ function applyInternal(
sourceType: SourceType,
sourceData: SourceData
) => HotModule,
applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void
applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void,
autoAcceptRootModules: boolean
) {
outdatedModules = applyInvalidatedModules(outdatedModules)
outdatedModules = applyInvalidatedModules(
outdatedModules,
autoAcceptRootModules
)
// Find self-accepted modules to re-instantiate
const outdatedSelfAcceptedModules =
......@@ -775,7 +811,8 @@ function applyInternal(
moduleFactories,
devModuleCache,
instantiateModuleFn,
applyModuleFactoryNameFn
applyModuleFactoryNameFn,
autoAcceptRootModules
)
}
}
......@@ -783,6 +820,10 @@ function applyInternal(
/**
* Main entry point for applying an ECMAScript merged update.
* This is called by both browser and Node.js runtimes with platform-specific callbacks.
*
* @param options.autoAcceptRootModules - If true, root modules auto-accept updates without explicit
* module.hot.accept(). Used for server-side HMR where pages
* auto-accept at the top level.
*/
function applyEcmascriptMergedUpdateShared(options: {
added: Map<ModuleId, EcmascriptModuleEntry | undefined>
......@@ -797,6 +838,7 @@ function applyEcmascriptMergedUpdateShared(options: {
applyModuleFactoryName: (factory: HotModuleFactoryFunction) => void
moduleFactories: ModuleFactories
devModuleCache: ModuleCache<HotModule>
autoAcceptRootModules: boolean
}) {
const {
added,
......@@ -807,12 +849,14 @@ function applyEcmascriptMergedUpdateShared(options: {
applyModuleFactoryName,
moduleFactories,
devModuleCache,
autoAcceptRootModules,
} = options
const { outdatedModules, newModuleFactories } = computeOutdatedModules(
added,
modified,
evalModuleEntry
evalModuleEntry,
autoAcceptRootModules
)
applyInternal(
......@@ -822,6 +866,7 @@ function applyEcmascriptMergedUpdateShared(options: {
moduleFactories,
devModuleCache,
instantiateModule,
applyModuleFactoryName
applyModuleFactoryName,
autoAcceptRootModules
)
}
......@@ -76,14 +76,6 @@ type LoadWebAssemblyModule = (
type ModuleCache<M> = Record<ModuleId, M>
// TODO properly type values here
type ModuleFactories = Map<ModuleId, Function>
/**
* Constraint for module factory functions used in HMR.
* Platform-specific runtimes define their own ModuleFactory types that must satisfy this constraint.
*/
type ModuleFactoryFunction<
TModule extends Module,
TContext extends TurbopackBaseContext<TModule>,
> = (this: TContext, ...args: unknown[]) => unknown
/**
* This is an alternating, non-empty arrow of module factory functions and module ids
* `[id1, id2..., factory1, id3, factory2, id4, id5, factory3]`
......
......@@ -43,6 +43,17 @@ declare function getOrInstantiateModuleFromParent<M>(
sourceModule: M
): M
// @ts-ignore Defined in `hmr-runtime.ts` (dev mode only)
declare let devModuleCache: Record<ModuleId, any> | undefined
/**
* Flag indicating which module object type to create when a module is merged. Set to `true`
* by each runtime that uses ModuleWithDirection (browser dev-base.ts, nodejs dev-base.ts,
* nodejs build-base.ts). Browser production (build-base.ts) leaves it as `false` since it
* uses plain Module objects.
*/
let createModuleWithDirectionFlag = false
const REEXPORTED_OBJECTS = new WeakMap<Module, ReexportedObjects>()
/**
......@@ -111,9 +122,12 @@ function getOverwrittenModule(
): Module {
let module = moduleCache[id]
if (!module) {
// This is invoked when a module is merged into another module, thus it wasn't invoked via
// instantiateModule and the cache entry wasn't created yet.
module = createModuleObject(id)
if (createModuleWithDirectionFlag) {
// set in development modes for hmr support
module = createModuleWithDirection(id)
} else {
module = createModuleObject(id)
}
moduleCache[id] = module
}
return module
......
......@@ -6,12 +6,13 @@ use turbopack_core::{
environment::Environment,
};
use crate::{asset_context::get_runtime_asset_context, embed_js::embed_static_code};
use crate::{RuntimeType, asset_context::get_runtime_asset_context, embed_js::embed_static_code};
/// Returns the code for the Node.js production ECMAScript runtime.
/// Returns the code for the Node.js ECMAScript runtime.
#[turbo_tasks::function]
pub async fn get_nodejs_runtime_code(
environment: ResolvedVc<Environment>,
runtime_type: RuntimeType,
generate_source_map: bool,
) -> Result<Vc<Code>> {
let asset_context = get_runtime_asset_context(*environment).resolve().await?;
......@@ -36,7 +37,9 @@ pub async fn get_nodejs_runtime_code(
rcstr!("shared-node/node-wasm-utils.ts"),
generate_source_map,
);
let runtime_code = embed_static_code(
// Runtime base is shared between production and development
let runtime_base_code = embed_static_code(
asset_context,
rcstr!("nodejs/runtime/runtime-base.ts"),
generate_source_map,
......@@ -47,7 +50,65 @@ pub async fn get_nodejs_runtime_code(
code.push_code(&*shared_base_external_utils_code.await?);
code.push_code(&*shared_node_external_utils_code.await?);
code.push_code(&*shared_node_wasm_utils_code.await?);
code.push_code(&*runtime_code.await?);
code.push_code(&*runtime_base_code.await?);
match runtime_type {
RuntimeType::Production => {
code.push_code(
&*embed_static_code(
asset_context,
rcstr!("nodejs/runtime/build-base.ts"),
generate_source_map,
)
.await?,
);
}
RuntimeType::Development => {
// Include shared HMR runtime (includes instantiateModuleShared, etc.)
code.push_code(
&*embed_static_code(
asset_context,
rcstr!("shared/runtime/hmr-runtime.ts"),
generate_source_map,
)
.await?,
);
// Include Node.js-specific dev runtime
code.push_code(
&*embed_static_code(
asset_context,
rcstr!("nodejs/runtime/dev-base.ts"),
generate_source_map,
)
.await?,
);
// Include Node.js HMR client (standalone, doesn't use shared ESM client)
code.push_code(
&*embed_static_code(
asset_context,
rcstr!("nodejs/dev/hmr-client.ts"),
generate_source_map,
)
.await?,
);
// Include dev-nodejs (HMR initialization and __turbopack_server_hmr_apply__)
code.push_code(
&*embed_static_code(
asset_context,
rcstr!("nodejs/dev/dev-nodejs.ts"),
generate_source_map,
)
.await?,
);
}
#[cfg(feature = "test")]
RuntimeType::Dummy => {
panic!("Dummy runtime is not supported in Node.js runtime")
}
}
Ok(Code::cell(code.build()))
}
......@@ -22,6 +22,9 @@ workspace = true
anyhow = { workspace = true }
bincode = { workspace = true }
indoc = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
serde_qs = { workspace = true }
tracing = { workspace = true }
urlencoding = { workspace = true }
......
......@@ -7,11 +7,14 @@ use turbopack_core::{
code_builder::{Code, CodeBuilder},
output::OutputAsset,
source_map::{GenerateSourceMap, SourceMapAsset},
version::{Version, VersionedContent},
version::{Update, Version, VersionedContent},
};
use turbopack_ecmascript::{chunk::EcmascriptChunkContent, minify::minify, utils::StringifyJs};
use super::{chunk::EcmascriptBuildNodeChunk, version::EcmascriptBuildNodeChunkVersion};
use super::{
chunk::EcmascriptBuildNodeChunk, update::update_node_chunk,
version::EcmascriptBuildNodeChunkVersion,
};
use crate::NodeJsChunkingContext;
#[turbo_tasks::value]
......@@ -114,4 +117,12 @@ impl VersionedContent for EcmascriptBuildNodeChunkContent {
fn version(self: Vc<Self>) -> Vc<Box<dyn Version>> {
Vc::upcast(self.own_version())
}
#[turbo_tasks::function]
async fn update(
self: Vc<Self>,
from_version: ResolvedVc<Box<dyn Version>>,
) -> Result<Vc<Update>> {
Ok(update_node_chunk(self, from_version).await?.cell())
}
}
......@@ -99,6 +99,7 @@ impl EcmascriptBuildNodeRuntimeChunk {
RuntimeType::Development => {
let runtime_code = turbopack_ecmascript_runtime::get_nodejs_runtime_code(
this.chunking_context.environment(),
RuntimeType::Development,
generate_source_map,
);
code.push_code(&*runtime_code.await?);
......@@ -106,6 +107,7 @@ impl EcmascriptBuildNodeRuntimeChunk {
RuntimeType::Production => {
let runtime_code = turbopack_ecmascript_runtime::get_nodejs_runtime_code(
this.chunking_context.environment(),
RuntimeType::Production,
generate_source_map,
);
code.push_code(&*runtime_code.await?);
......
pub(crate) mod chunk;
pub(crate) mod content;
pub(crate) mod entry;
pub(crate) mod update;
pub(crate) mod version;
use std::sync::Arc;
use anyhow::Result;
use serde::Serialize;
use turbo_tasks::{FxIndexMap, FxIndexSet, IntoTraitRef, ReadRef, ResolvedVc, Vc};
use turbo_tasks_fs::rope::Rope;
use turbopack_core::{
chunk::ModuleId,
code_builder::Code,
source_map::GenerateSourceMap,
version::{PartialUpdate, TotalUpdate, Update, Version},
};
use super::{content::EcmascriptBuildNodeChunkContent, version::EcmascriptBuildNodeChunkVersion};
#[derive(Serialize, Default)]
#[serde(
tag = "type",
rename = "EcmascriptMergedUpdate",
rename_all = "camelCase"
)]
struct EcmascriptMergedUpdate<'a> {
/// A map from module id to latest module entry.
#[serde(skip_serializing_if = "FxIndexMap::is_empty")]
entries: FxIndexMap<ModuleId, EcmascriptModuleEntry>,
/// A map from chunk path to the chunk update.
#[serde(skip_serializing_if = "FxIndexMap::is_empty")]
chunks: FxIndexMap<&'a str, EcmascriptMergedChunkUpdate>,
}
impl EcmascriptMergedUpdate<'_> {
fn is_empty(&self) -> bool {
self.entries.is_empty() && self.chunks.is_empty()
}
}
#[derive(Serialize)]
#[serde(tag = "type", rename_all = "camelCase")]
enum EcmascriptMergedChunkUpdate {
Partial(EcmascriptMergedChunkPartial),
}
#[derive(Serialize, Default)]
#[serde(rename_all = "camelCase")]
struct EcmascriptMergedChunkPartial {
#[serde(skip_serializing_if = "FxIndexSet::is_empty")]
added: FxIndexSet<ModuleId>,
#[serde(skip_serializing_if = "FxIndexSet::is_empty")]
deleted: FxIndexSet<ModuleId>,
}
#[derive(Serialize)]
struct EcmascriptModuleEntry {
#[serde(with = "turbo_tasks_fs::rope::ser_as_string")]
code: Rope,
url: String,
#[serde(with = "turbo_tasks_fs::rope::ser_option_as_string")]
map: Option<Rope>,
}
impl EcmascriptModuleEntry {
async fn from_code(id: &ModuleId, code: Vc<Code>, chunk_path: &str) -> Result<Self> {
let map = &*code.generate_source_map().await?;
let map = map.as_content().map(|f| f.content().clone());
/// serde_qs can't serialize a lone enum when it's [serde::untagged].
#[derive(Serialize)]
struct Id<'a> {
id: &'a ModuleId,
}
let id = serde_qs::to_string(&Id { id }).unwrap();
Ok(EcmascriptModuleEntry {
// Cloning a rope is cheap.
code: code.await?.source_code().clone(),
url: format!("{}?{}", chunk_path, &id),
map,
})
}
}
pub(super) async fn update_node_chunk(
content: Vc<EcmascriptBuildNodeChunkContent>,
from_version: ResolvedVc<Box<dyn Version>>,
) -> Result<Update> {
let to_version = content.own_version();
let from_version = if let Some(from) =
ResolvedVc::try_downcast_type::<EcmascriptBuildNodeChunkVersion>(from_version)
{
from
} else {
// It's likely `from_version` is `NotFoundVersion`.
return Ok(Update::Total(TotalUpdate {
to: Vc::upcast::<Box<dyn Version>>(to_version)
.into_trait_ref()
.await?,
}));
};
let to = to_version.await?;
let from = from_version.await?;
// When to and from point to the same value we can skip comparing them
if from.ptr_eq(&to) {
return Ok(Update::None);
}
let chunk_path = &to.chunk_path;
let chunk_update = update_ecmascript_node_chunk_content(&to, &from).await?;
let mut merged_update = EcmascriptMergedUpdate::default();
match chunk_update {
NodeChunkUpdate::None => {
return Ok(Update::None);
}
NodeChunkUpdate::Partial {
added,
modified,
deleted,
} => {
let mut partial = EcmascriptMergedChunkPartial::default();
for (module_id, module_code) in added {
partial.added.insert(module_id.clone());
let entry =
EcmascriptModuleEntry::from_code(&module_id, module_code, chunk_path).await?;
merged_update.entries.insert(module_id, entry);
}
partial.deleted.extend(deleted.into_keys());
for (module_id, module_code) in modified {
let entry =
EcmascriptModuleEntry::from_code(&module_id, module_code, chunk_path).await?;
merged_update.entries.insert(module_id, entry);
}
merged_update
.chunks
.insert(chunk_path, EcmascriptMergedChunkUpdate::Partial(partial));
}
}
let update = if merged_update.is_empty() {
Update::None
} else {
// Serialize EcmascriptMergedUpdate directly
// The hot-reloader will wrap it in ChunkListUpdate format for the runtime
let instruction_value = serde_json::to_value(&merged_update)?;
Update::Partial(PartialUpdate {
to: Vc::upcast::<Box<dyn Version>>(to_version)
.into_trait_ref()
.await?,
instruction: Arc::new(instruction_value),
})
};
Ok(update)
}
enum NodeChunkUpdate {
None,
Partial {
added: FxIndexMap<ModuleId, Vc<Code>>,
modified: FxIndexMap<ModuleId, Vc<Code>>,
deleted: FxIndexMap<ModuleId, u64>,
},
}
async fn update_ecmascript_node_chunk_content(
to: &ReadRef<EcmascriptBuildNodeChunkVersion>,
from: &ReadRef<EcmascriptBuildNodeChunkVersion>,
) -> Result<NodeChunkUpdate> {
let mut added = FxIndexMap::default();
let mut modified = FxIndexMap::default();
let mut deleted = FxIndexMap::default();
// Build a map of module_id -> Vc<Code> for the "to" version
let mut to_entries: FxIndexMap<ModuleId, Vc<Code>> = FxIndexMap::default();
for item in &to.chunk_items {
for (id, code) in item {
// Convert ReadRef<Code> to Vc<Code>
to_entries.insert(id.clone(), ReadRef::cell(code.clone()));
}
}
// Check for deleted and modified modules
for (id, from_hash) in &from.entries_hashes {
if let Some(to_hash) = to.entries_hashes.get(id) {
if *to_hash != *from_hash {
// Module was modified
if let Some(code) = to_entries.get(id) {
modified.insert(id.clone(), *code);
}
}
} else {
// Module was deleted
deleted.insert(id.clone(), *from_hash);
}
}
// Check for added modules
for (id, _hash) in &to.entries_hashes {
if !from.entries_hashes.contains_key(id)
&& let Some(code) = to_entries.get(id)
{
added.insert(id.clone(), *code);
}
}
let update = if added.is_empty() && modified.is_empty() && deleted.is_empty() {
NodeChunkUpdate::None
} else {
NodeChunkUpdate::Partial {
added,
modified,
deleted,
}
};
Ok(update)
}
use anyhow::{Result, bail};
use turbo_rcstr::RcStr;
use turbo_tasks::{ReadRef, Vc};
use turbo_tasks::{FxIndexMap, ReadRef, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbo_tasks_hash::{Xxh3Hash64Hasher, encode_hex};
use turbopack_core::{chunk::MinifyType, version::Version};
use turbopack_core::{
chunk::{MinifyType, ModuleId},
version::Version,
};
use turbopack_ecmascript::chunk::{CodeAndIds, EcmascriptChunkContent};
#[turbo_tasks::value(serialization = "none")]
pub(super) struct EcmascriptBuildNodeChunkVersion {
chunk_path: String,
chunk_items: Vec<ReadRef<CodeAndIds>>,
minify_type: MinifyType,
pub(super) chunk_path: String,
pub(super) chunk_items: Vec<ReadRef<CodeAndIds>>,
pub(super) minify_type: MinifyType,
pub(super) entries_hashes: FxIndexMap<ModuleId, u64>,
}
#[turbo_tasks::value_impl]
......@@ -30,10 +34,25 @@ impl EcmascriptBuildNodeChunkVersion {
bail!("chunk path {chunk_path} is not in client root {output_root}");
};
let chunk_items = content.await?.chunk_item_code_and_ids().await?;
// Compute per-module hashes for fine-grained HMR tracking
let mut entries_hashes = FxIndexMap::default();
for item in &chunk_items {
for (module_id, code) in item {
let mut hasher = Xxh3Hash64Hasher::new();
let source = code.source_code();
hasher.write_ref(source);
let hash = hasher.finish();
entries_hashes.insert(module_id.clone(), hash);
}
}
Ok(EcmascriptBuildNodeChunkVersion {
chunk_path: chunk_path.to_string(),
chunk_items,
minify_type,
entries_hashes,
}
.cell())
}
......@@ -46,11 +65,13 @@ impl Version for EcmascriptBuildNodeChunkVersion {
let mut hasher = Xxh3Hash64Hasher::new();
hasher.write_ref(&self.chunk_path);
hasher.write_ref(&self.minify_type);
hasher.write_value(self.chunk_items.len());
for item in &self.chunk_items {
for (module_id, code) in item {
hasher.write_value((module_id, code.source_code()));
}
let sorted_hashes = {
let mut hashes: Vec<_> = self.entries_hashes.values().copied().collect();
hashes.sort();
hashes
};
for hash in sorted_hashes {
hasher.write_value(hash);
}
let hash = hasher.finish();
let hex_hash = encode_hex(hash);
......
......@@ -28,6 +28,12 @@ const WORKER_FORWARDED_GLOBALS = [];
*/ SourceType[SourceType["Update"] = 2] = "Update";
return SourceType;
}(SourceType || {});
/**
* Flag indicating which module object type to create when a module is merged. Set to `true`
* by each runtime that uses ModuleWithDirection (browser dev-base.ts, nodejs dev-base.ts,
* nodejs build-base.ts). Browser production (build-base.ts) leaves it as `false` since it
* uses plain Module objects.
*/ let createModuleWithDirectionFlag = false;
const REEXPORTED_OBJECTS = new WeakMap();
/**
* Constructs the `__turbopack_context__` object for a module.
......@@ -51,9 +57,12 @@ function defineProp(obj, name, options) {
function getOverwrittenModule(moduleCache, id) {
let module = moduleCache[id];
if (!module) {
// This is invoked when a module is merged into another module, thus it wasn't invoked via
// instantiateModule and the cache entry wasn't created yet.
module = createModuleObject(id);
if (createModuleWithDirectionFlag) {
// set in development modes for hmr support
module = createModuleWithDirection(id);
} else {
module = createModuleObject(id);
}
moduleCache[id] = module;
}
return module;
......@@ -626,30 +635,18 @@ async function instantiateWebAssemblyFromPath(path, importsObj) {
const { instance } = await WebAssembly.instantiateStreaming(response, importsObj);
return instance.exports;
}
/* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../hmr-types.d.ts" />
/// <reference path="../../shared/runtime/runtime-utils.ts" />
/* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../../shared/runtime/runtime-utils.ts" />
/// <reference path="../../shared-node/base-externals-utils.ts" />
/// <reference path="../../shared-node/node-externals-utils.ts" />
/// <reference path="../../shared-node/node-wasm-utils.ts" />
var SourceType = /*#__PURE__*/ function(SourceType) {
/**
* The module was instantiated because it was included in an evaluated chunk's
* runtime.
* SourceData is a ChunkPath.
*/ SourceType[SourceType["Runtime"] = 0] = "Runtime";
/**
* The module was instantiated because a parent module imported it.
* SourceData is a ModuleId.
*/ SourceType[SourceType["Parent"] = 1] = "Parent";
return SourceType;
}(SourceType || {});
process.env.TURBOPACK = '1';
const nodeContextPrototype = Context.prototype;
/// <reference path="./nodejs-globals.d.ts" />
/**
* Base Node.js runtime shared between production and development.
* Contains chunk loading, module caching, and other non-HMR functionality.
*/ process.env.TURBOPACK = '1';
const url = require('url');
const moduleFactories = new Map();
nodeContextPrototype.M = moduleFactories;
const moduleCache = Object.create(null);
nodeContextPrototype.c = moduleCache;
/**
* Returns an absolute path to the given module's id.
*/ function resolvePathFromModule(moduleId) {
......@@ -662,13 +659,11 @@ nodeContextPrototype.c = moduleCache;
const resolved = path.resolve(RUNTIME_ROOT, strippedAssetPrefix);
return url.pathToFileURL(resolved).href;
}
nodeContextPrototype.R = resolvePathFromModule;
/**
* Exports a URL value. No suffix is added in Node.js runtime.
*/ function exportUrl(urlValue, id) {
exportValue.call(this, urlValue, id);
}
nodeContextPrototype.q = exportUrl;
function loadRuntimeChunk(sourcePath, chunkData) {
if (typeof chunkData === 'string') {
loadRuntimeChunkPath(sourcePath, chunkData);
......@@ -682,6 +677,7 @@ const loadedChunk = Promise.resolve(undefined);
const chunkCache = new Map();
function clearChunkCache() {
chunkCache.clear();
loadedChunks.clear();
}
function loadRuntimeChunkPath(sourcePath, chunkPath) {
if (!isJs(chunkPath)) {
......@@ -780,7 +776,27 @@ contextPrototype.u = loadWebAssemblyModule;
};
return new WorkerConstructor(workerPath, options);
}
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/;
/**
* Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
*/ function isJs(chunkUrlOrPath) {
return regexJsUrl.test(chunkUrlOrPath);
}
/* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-base.ts" />
/**
* Production Node.js runtime.
* Uses ModuleWithDirection and simple module instantiation without HMR support.
*/ // moduleCache and moduleFactories are declared in runtime-base.ts
// this is read in runtime-utils.ts so it creates a module with direction for hmr
createModuleWithDirectionFlag = true;
const nodeContextPrototype = Context.prototype;
nodeContextPrototype.q = exportUrl;
nodeContextPrototype.M = moduleFactories;
// Cast moduleCache to ModuleWithDirection for production mode
nodeContextPrototype.c = moduleCache;
nodeContextPrototype.R = resolvePathFromModule;
nodeContextPrototype.b = createWorker;
nodeContextPrototype.C = clearChunkCache;
function instantiateModule(id, sourceType, sourceData) {
const moduleFactory = moduleFactories.get(id);
if (typeof moduleFactory !== 'function') {
......@@ -789,10 +805,10 @@ function instantiateModule(id, sourceType, sourceData) {
// and contains e.g. a `require("something")` call.
let instantiationReason;
switch(sourceType){
case 0:
case SourceType.Runtime:
instantiationReason = `as a runtime entry of chunk ${sourceData}`;
break;
case 1:
case SourceType.Parent:
instantiationReason = `because it was required from module ${sourceData}`;
break;
default:
......@@ -800,7 +816,7 @@ function instantiateModule(id, sourceType, sourceData) {
}
throw new Error(`Module ${id} was instantiated ${instantiationReason}, but the module factory is not available.`);
}
const module1 = createModuleObject(id);
const module1 = createModuleWithDirection(id);
const exports = module1.exports;
moduleCache[id] = module1;
const context = new Context(module1, exports);
......@@ -811,6 +827,7 @@ function instantiateModule(id, sourceType, sourceData) {
module1.error = error;
throw error;
}
;
module1.loaded = true;
if (module1.namespaceObject && module1.exports !== module1.namespaceObject) {
// in case of a circular dependency: cjs1 -> esm2 -> cjs1
......@@ -829,12 +846,12 @@ function getOrInstantiateModuleFromParent(id, sourceModule) {
}
return module1;
}
return instantiateModule(id, 1, sourceModule.id);
return instantiateModule(id, SourceType.Parent, sourceModule.id);
}
/**
* Instantiates a runtime module.
*/ function instantiateRuntimeModule(chunkPath, moduleId) {
return instantiateModule(moduleId, 0, chunkPath);
return instantiateModule(moduleId, SourceType.Runtime, chunkPath);
}
/**
* Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached.
......@@ -849,18 +866,6 @@ function getOrInstantiateRuntimeModule(chunkPath, moduleId) {
}
return instantiateRuntimeModule(chunkPath, moduleId);
}
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/;
/**
* Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
*/ function isJs(chunkUrlOrPath) {
return regexJsUrl.test(chunkUrlOrPath);
}
function __turbopack_server_hmr_apply__(_update) {
// TODO: Implement actual HMR logic to update module factories
// For now, just return true to indicate we "accepted" the update
return true;
}
globalThis.__turbopack_server_hmr_apply__ = __turbopack_server_hmr_apply__;
module.exports = (sourcePath)=>({
m: (id)=>getOrInstantiateRuntimeModule(sourcePath, id),
c: (chunkData)=>loadRuntimeChunk(sourcePath, chunkData)
......
......@@ -183,6 +183,12 @@ function _ts_generator(thisArg, body) {
*/ SourceType[SourceType["Update"] = 2] = "Update";
return SourceType;
}(SourceType || {});
/**
* Flag indicating which module object type to create when a module is merged. Set to `true`
* by each runtime that uses ModuleWithDirection (browser dev-base.ts, nodejs dev-base.ts,
* nodejs build-base.ts). Browser production (build-base.ts) leaves it as `false` since it
* uses plain Module objects.
*/ var createModuleWithDirectionFlag = false;
var REEXPORTED_OBJECTS = new WeakMap();
/**
* Constructs the `__turbopack_context__` object for a module.
......@@ -206,9 +212,12 @@ function defineProp(obj, name, options) {
function getOverwrittenModule(moduleCache, id) {
var module = moduleCache[id];
if (!module) {
// This is invoked when a module is merged into another module, thus it wasn't invoked via
// instantiateModule and the cache entry wasn't created yet.
module = createModuleObject(id);
if (createModuleWithDirectionFlag) {
// set in development modes for hmr support
module = createModuleWithDirection(id);
} else {
module = createModuleObject(id);
}
moduleCache[id] = module;
}
return module;
......
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