Commit 65c6b0d1 authored by Will Binns-Smith's avatar Will Binns-Smith

Apply suggestions from code review

Co-authored-by: 's avatarLuke Sandberg <lukesandberg@users.noreply.github.com>
parent d9b8bdd0
......@@ -313,25 +313,18 @@ export declare function projectEntrypointsSubscribe(
project: { __napiType: 'Project' },
func: (...args: any[]) => any
): { __napiType: 'RootTask' }
export declare function projectClientHmrEvents(
project: { __napiType: 'Project' },
identifier: RcStr,
func: (...args: any[]) => any
): { __napiType: 'RootTask' }
export declare function projectServerHmrEvents(
export declare function projectHmrEvents(
project: { __napiType: 'Project' },
identifier: RcStr,
target: string,
func: (...args: any[]) => any
): { __napiType: 'RootTask' }
export interface HmrIdentifiers {
identifiers: Array<RcStr>
}
export declare function projectClientHmrIdentifiersSubscribe(
project: { __napiType: 'Project' },
func: (...args: any[]) => any
): { __napiType: 'RootTask' }
export declare function projectServerHmrIdentifiersSubscribe(
export declare function projectHmrIdentifiersSubscribe(
project: { __napiType: 'Project' },
target: string,
func: (...args: any[]) => any
): { __napiType: 'RootTask' }
export interface NapiUpdateMessage {
......
......@@ -44,6 +44,11 @@ import type {
} from './types'
import { throwTurbopackInternalError } from '../../shared/lib/turbopack/internal-error'
export enum HmrTarget {
Client = 'client',
Server = 'server',
}
type RawBindings = typeof import('./generated-native')
type RawWasmBindings = typeof import('./generated-wasm') & {
default?(): Promise<typeof import('./generated-wasm')>
......@@ -736,45 +741,37 @@ function bindingToApi(
})()
}
clientHmrEvents(identifier: string) {
return subscribe<TurbopackResult<Update>>(true, async (callback) =>
binding.projectClientHmrEvents(
hmrEvents(
identifier: string,
target: HmrTarget.Client
): AsyncIterableIterator<TurbopackResult<Update>>
hmrEvents(
identifier: string,
target: HmrTarget.Server
): AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>
hmrEvents(identifier: string, target: HmrTarget.Client | HmrTarget.Server) {
return subscribe(true, async (callback) =>
binding.projectHmrEvents(
this._nativeProject,
identifier,
target,
callback
)
)
}
clientHmrIdentifiersSubscribe() {
return subscribe<TurbopackResult<HmrIdentifiers>>(
false,
async (callback) =>
binding.projectClientHmrIdentifiersSubscribe(
this._nativeProject,
callback
)
)
}
serverHmrEvents(identifier: string) {
return subscribe<TurbopackResult<NodeJsHmrUpdate>>(
true,
async (callback) =>
binding.projectServerHmrEvents(
this._nativeProject,
identifier,
callback
)
)
}
serverHmrIdentifiersSubscribe() {
/**
* Subscribe to the list of output chunk paths that can receive HMR updates.
* Chunk paths are output file paths like "server/chunks/ssr/..._.js" for server
* or "_next/static/chunks/app/page.js" for client.
*/
hmrIdentifiersSubscribe(target: HmrTarget) {
return subscribe<TurbopackResult<HmrIdentifiers>>(
false,
async (callback) =>
binding.projectServerHmrIdentifiersSubscribe(
binding.projectHmrIdentifiersSubscribe(
this._nativeProject,
target,
callback
)
)
......
......@@ -210,7 +210,8 @@ export interface NodeJsPartialHmrUpdate extends BaseUpdate {
export type NodeJsHmrUpdate = IssuesUpdate | NodeJsPartialHmrUpdate
export interface HmrIdentifiers {
identifiers: string[]
/** Paths to output chunks that can receive HMR updates (e.g., "server/chunks/ssr/..._.js") */
chunkPaths: string[]
}
/** @see https://github.com/vercel/next.js/blob/415cd74b9a220b6f50da64da68c13043e9b02995/crates/next-napi-bindings/src/next_api/project.rs#L824-L833 */
......@@ -260,21 +261,18 @@ export interface Project {
TurbopackResult<RawEntrypoints | {}>
>
clientHmrEvents(
identifier: string
hmrEvents(
identifier: string,
target: import('./index').HmrTarget.Client
): AsyncIterableIterator<TurbopackResult<Update>>
clientHmrIdentifiersSubscribe(): AsyncIterableIterator<
TurbopackResult<HmrIdentifiers>
>
serverHmrEvents(
identifier: string
hmrEvents(
identifier: string,
target: import('./index').HmrTarget.Server
): AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>
serverHmrIdentifiersSubscribe(): AsyncIterableIterator<
TurbopackResult<HmrIdentifiers>
>
hmrIdentifiersSubscribe(
target: import('./index').HmrTarget
): AsyncIterableIterator<TurbopackResult<HmrIdentifiers>>
getSourceForAsset(filePath: string): Promise<string | null>
......
......@@ -27,7 +27,7 @@ import type {
NodeJsHmrUpdate,
NodeJsPartialHmrUpdate,
} from '../../build/swc/types'
import { createDefineEnv, getBindingsSync } from '../../build/swc'
import { createDefineEnv, getBindingsSync, HmrTarget } from '../../build/swc'
import * as Log from '../../build/output/log'
import { BLOCKED_PAGES } from '../../shared/lib/constants'
import {
......@@ -156,13 +156,17 @@ function setupServerHmr(project: Project) {
AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>
>()
function subscribeToServerHmr(identifier: string) {
if (serverHmrSubscriptions.has(identifier)) {
/**
* Subscribe to HMR updates for a server chunk.
* @param chunkPath - Server chunk output path (e.g., "server/chunks/ssr/..._.js")
*/
function subscribeToServerHmr(chunkPath: string) {
if (serverHmrSubscriptions.has(chunkPath)) {
return
}
const subscription = project.serverHmrEvents(identifier)
serverHmrSubscriptions.set(identifier, subscription)
const subscription = project.hmrEvents(chunkPath, HmrTarget.Server)
serverHmrSubscriptions.set(chunkPath, subscription)
// Start listening for changes in background
;(async () => {
......@@ -184,7 +188,9 @@ function setupServerHmr(project: Project) {
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
}
......@@ -192,42 +198,46 @@ function setupServerHmr(project: Project) {
}
})().catch((err) => {
console.error('[Server HMR] Subscription error:', err)
serverHmrSubscriptions.delete(identifier)
serverHmrSubscriptions.delete(chunkPath)
})
}
// Listen to the Rust bindings update us on changing server HMR identifiers
// Listen to the Rust bindings update us on changing server HMR chunk paths
;(async () => {
const serverHmrIdentifiers = project.serverHmrIdentifiersSubscribe()
const serverHmrChunkPaths = project.hmrIdentifiersSubscribe(
HmrTarget.Server
)
// Process identifiers (both initial and subsequent updates)
for await (const data of serverHmrIdentifiers) {
const currentIdentifiers = new Set(
data.identifiers.filter((id) => id.endsWith('.js'))
// Process chunk paths (both initial and subsequent updates)
for await (const data of serverHmrChunkPaths) {
const currentChunkPaths = new Set(
data.chunk_paths.filter((path) => path.endsWith('.js'))
)
// Clean up subscriptions for removed identifiers (like when pages are deleted)
const identifiersToRemove = []
for (const identifier of serverHmrSubscriptions.keys()) {
if (!currentIdentifiers.has(identifier)) {
identifiersToRemove.push(identifier)
// 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)
}
}
for (const identifier of identifiersToRemove) {
const subscription = serverHmrSubscriptions.get(identifier)
for (const chunkPath of chunkPathsToRemove) {
const subscription = serverHmrSubscriptions.get(chunkPath)
subscription?.return?.()
serverHmrSubscriptions.delete(identifier)
serverHmrSubscriptions.delete(chunkPath)
}
// Subscribe to HMR events for new server modules
for (const identifier of currentIdentifiers) {
if (!serverHmrSubscriptions.has(identifier)) {
subscribeToServerHmr(identifier)
// 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] error:', err)
})
}
/**
......@@ -755,7 +765,7 @@ export async function createHotReloaderTurbopack(
return
}
const subscription = project!.clientHmrEvents(id)
const subscription = project!.hmrEvents(id, HmrTarget.Client)
state.subscriptions.set(id, subscription)
// The subscription will always emit once, which is the initial
......@@ -766,7 +776,7 @@ export async function createHotReloaderTurbopack(
for await (const data of subscription) {
processIssues(state.clientIssues, key, data, false, true)
if (data.type !== 'issues') {
sendTurbopackMessage(data)
sendTurbopackMessage(data as TurbopackUpdate)
}
}
} catch (e) {
......
import { NextInstance, createNext } from 'e2e-utils'
import { trace } from 'next/dist/trace'
import { PHASE_DEVELOPMENT_SERVER } from 'next/constants'
import { createDefineEnv, loadBindings } from 'next/dist/build/swc'
import { createDefineEnv, loadBindings, HmrTarget } from 'next/dist/build/swc'
import type {
Diagnostics,
Issue,
......@@ -665,12 +665,15 @@ describe('next.rs api', () => {
}
}
const result = await project.clientHmrIdentifiersSubscribe().next()
const result = await project
.hmrIdentifiersSubscribe(HmrTarget.Client)
.next()
expect(result.done).toBe(false)
const identifiers = result.value.identifiers
expect(identifiers).toHaveProperty('length', expect.toBePositive())
const subscriptions = identifiers.map((identifier) =>
project.clientHmrEvents(identifier)
const chunkPaths = result.value.chunk_paths
expect(chunkPaths).toHaveProperty('length', expect.toBePositive())
const subscriptions = chunkPaths.map((chunkPath) =>
project.hmrEvents(chunkPath, HmrTarget.Client)
)
await Promise.all(
subscriptions.map(async (subscription) => {
......@@ -792,12 +795,14 @@ describe('next.rs api', () => {
if (route.type !== 'page') throw new Error('unknown route type')
await route.htmlEndpoint.writeToDisk()
const result = await project.clientHmrIdentifiersSubscribe().next()
const result = await project
.hmrIdentifiersSubscribe(HmrTarget.Client)
.next()
expect(result.done).toBe(false)
const identifiers = result.value.identifiers
const subscriptions = identifiers.map((identifier) =>
project.clientHmrEvents(identifier)
project.hmrEvents(identifier, HmrTarget.Client)
)
await Promise.all(
subscriptions.map(async (subscription) => {
......
......@@ -23,7 +23,9 @@ function _eval(_: EcmascriptModuleEntry) {
}
function __turbopack_server_hmr_apply__(_update: any): boolean {
throw new Error('Server-side HMR is not implemented for edge runtime')
// Server-side HMR is not supported in edge runtime, but this is expected.
// Return false to indicate the update was not applied.
return false
}
globalThis.__turbopack_server_hmr_apply__ = __turbopack_server_hmr_apply__
......@@ -5,6 +5,8 @@
/// <reference path="../shared-node/node-externals-utils.ts" />
/// <reference path="../shared-node/node-wasm-utils.ts" />
import type { NodeJsPartialHmrUpdate } from '../../../../../../packages/next/src/build/swc/types'
enum SourceType {
/**
* The module was instantiated because it was included in an evaluated chunk's
......@@ -313,7 +315,9 @@ function isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {
return regexJsUrl.test(chunkUrlOrPath)
}
function __turbopack_server_hmr_apply__(_update: any): boolean {
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
......
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