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