Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changepacks/changepack_log_next_turbo_setup.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"changes": {
"packages/next-plugin/package.json": "Patch"
},
"note": "Turbopack honors the `debug` option (readable class names) like the webpack path, and keeps it apart in the production setup cache. A dev restart restores the previous session's sheet, class map and file map all together or not at all, so a missing or corrupt file no longer leaves a mix that gives new styles clashing names. When the import graph or file numbering cannot be built, Turbopack now prints a warning naming the cause and what the build loses instead of continuing silently. No new build errors",
"date": "2026-11-15T00:00:00.000Z"
}
77 changes: 75 additions & 2 deletions packages/next-plugin/src/__tests__/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
DevupUI,
reloadTurboSetupModuleForTesting,
resetTurboSetupCacheForTesting,
restoreSessionState,
} from '../plugin'
import {
loadWasm,
Expand Down Expand Up @@ -1059,16 +1060,34 @@ export const box = style({ color: 'red' })`
throw new Error('unreadable')
})
const profileSpy = spyOn(console, 'info').mockImplementation(() => {})
const warnSpy = spyOn(console, 'warn').mockImplementation(() => {})
try {
expect(DevupUI({}).turbopack?.rules).toBeDefined()
expect(profileSpy).toHaveBeenCalledWith(
expect.stringContaining('"failed":true'),
)
expect(warnSpy).toHaveBeenCalledWith(
'[devup-ui] Turbopack import graph failed: unreadable. Classes are not merged across files only one module imports, and the production stylesheet waits for extraction to go quiet instead of for every compiled file.',
)
} finally {
profileSpy.mockRestore()
warnSpy.mockRestore()
graphSpy.mockRestore()
}
})
it.each([
[{}, false],
[{ debug: true }, true],
])('sets debug class names from %j', (options, debug) => {
process.env.TURBOPACK = '1'
const setDebugSpy = spyOn(wasm, 'setDebug').mockReturnValue(undefined)
try {
DevupUI({}, options)
expect(setDebugSpy).toHaveBeenCalledWith(debug)
} finally {
setDebugSpy.mockRestore()
}
})
it('should create theme.d.ts file', async () => {
process.env.TURBOPACK = '1'
existsSyncSpy.mockReturnValue(true)
Expand Down Expand Up @@ -1174,14 +1193,68 @@ export const box = style({ color: 'red' })`
include: ['@acme/ui'],
})
collectSpy.mockImplementation(() => {
throw new Error('scan boom')
throw 'scan boom'
})
DevupUI({}, {})
const warnSpy = spyOn(console, 'warn').mockImplementation(() => {})
try {
DevupUI({}, {})
expect(warnSpy).toHaveBeenCalledWith(
'[devup-ui] Turbopack file numbering failed: scan boom. Stylesheet file numbers follow the order Turbopack compiles files in, so they can differ between builds of the same source.',
)
} finally {
warnSpy.mockRestore()
}
} finally {
collectSpy.mockRestore()
seedSpy.mockRestore()
}
})
describe('restoreSessionState', () => {
const files = ['sheet.json', 'classMap.json', 'fileMap.json'] as const
const engine = () => ({
importSheet: mock(),
importClassMap: mock(),
importFileMap: mock(),
resetBuildState: mock(),
})

it('imports nothing unless every file reads', () => {
readFileSyncSpy.mockImplementation((path: string) => {
if (path === 'fileMap.json') throw new Error('ENOENT')
return '{}'
})
const restored = engine()
restoreSessionState(restored, files)
expect(restored.importSheet).not.toHaveBeenCalled()
expect(restored.importClassMap).not.toHaveBeenCalled()
expect(restored.importFileMap).not.toHaveBeenCalled()
})

it('imports nothing when one file is corrupt', () => {
readFileSyncSpy.mockImplementation((path: string) =>
path === 'classMap.json' ? '{"a":' : '{}',
)
const restored = engine()
restoreSessionState(restored, files)
expect(restored.importSheet).not.toHaveBeenCalled()
})

it('drops a state that does not import', () => {
readFileSyncSpy.mockImplementation((path: string) =>
JSON.stringify({ path }),
)
const restored = engine()
restored.importClassMap.mockImplementation(() => {
throw new Error('older release')
})
restoreSessionState(restored, files)
expect(restored.importSheet).toHaveBeenCalledWith({
path: 'sheet.json',
})
expect(restored.importFileMap).not.toHaveBeenCalled()
expect(restored.resetBuildState).toHaveBeenCalledTimes(1)
})
})
it('should import previous session state on restart', () => {
process.env.TURBOPACK = '1'
existsSyncSpy
Expand Down
79 changes: 63 additions & 16 deletions packages/next-plugin/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import {
} from './coordinator-port'
import { collectProductionPrewarmFiles } from './prewarm'
import { elapsedMs, profileStart, reportProfile } from './profile'
import { loadWasm, loadWebpackPlugin } from './wasm'
import { type DevupWasm, loadWasm, loadWebpackPlugin } from './wasm'

/** Options accepted by the Next.js integration. */
export type DevupUINextPluginOptions = Partial<DevupUIBasePluginOptions> & {
Expand Down Expand Up @@ -135,6 +135,43 @@ function sourceDir(cwd: string): string {
: resolve(cwd, 'src')
}

/** A setup step that failed but leaves a working, less exact build. */
function setupWarning(step: string, error: unknown, impact: string): string {
const cause = error instanceof Error ? error.message : String(error)
return `[devup-ui] Turbopack ${step} failed: ${cause}. ${impact}`
}

/**
* Restore the sheet, class map and file map an earlier dev session left in
* `distDir`, all together or none: a mix of one session's sheet with another
* session's (or no) class names would give new styles names that clash with
* restored ones. A missing or unreadable file starts fresh (first run); state
* that does not import (another release wrote it) is dropped and starts fresh.
*/
export function restoreSessionState(
wasm: Pick<
DevupWasm,
'importSheet' | 'importClassMap' | 'importFileMap' | 'resetBuildState'
>,
[sheetFile, classMapFile, fileMapFile]: readonly [string, string, string],
): void {
let state: unknown[]
try {
state = [sheetFile, classMapFile, fileMapFile].map((file) =>
JSON.parse(readFileSync(file, 'utf-8')),
)
} catch {
return
}
try {
wasm.importSheet(state[0])
wasm.importClassMap(state[1])
wasm.importFileMap(state[2])
} catch {
wasm.resetBuildState()
}
}

/**
* Devup UI Next Plugin
* @param config
Expand Down Expand Up @@ -163,6 +200,7 @@ export function DevupUI(
devupFile = 'devup.json',
include = [],
prefix,
debug = false,
atomHoist,
importAliases: userImportAliases,
} = options
Expand Down Expand Up @@ -194,6 +232,7 @@ export function DevupUI(
atomHoist: requestedAtomHoist ? atomHoist : 0,
cwd: process.cwd(),
cssDir,
debug,
devupFile,
distDir,
engine,
Expand Down Expand Up @@ -254,18 +293,14 @@ export function DevupUI(
getDefaultTheme,
getThemeInterface,
importCanonicalMap,
importClassMap,
importFileMap,
importSheet,
registerShorthands,
registerTheme,
setDebug,
setPrefix,
} = wasm

registerShorthands(normalizedShorthands)

setPrefix(prefix ?? null)

writeFileSync(
join(distDir, 'compat.d.ts'),
createCompatTypes(importAliases),
Expand All @@ -274,13 +309,10 @@ export function DevupUI(
// When the dev server restarts, Turbopack may skip re-running loaders for
// unchanged files. Without importing previous state, the coordinator's WASM
// starts empty and CSS for cached files would be missing.
try {
importSheet(JSON.parse(readFileSync(sheetFile, 'utf-8')))
importClassMap(JSON.parse(readFileSync(classMapFile, 'utf-8')))
importFileMap(JSON.parse(readFileSync(fileMapFile, 'utf-8')))
} catch {
// No previous session state (first run) or corrupt files, start fresh
}
restoreSessionState(wasm, [sheetFile, classMapFile, fileMapFile])
// After the restore: dropping a state that does not import resets these.
setPrefix(prefix ?? null)
setDebug(debug)

const devupConfig = loadDevupConfigSync(devupFile)

Expand Down Expand Up @@ -348,9 +380,17 @@ export function DevupUI(
files: staticGraph.files.length,
expectedBaseFiles: expectedBaseFiles.length,
})
} catch {
} catch (error) {
// Pre-pass is best-effort; on failure canonical() is the identity (no
// merge) and atom hoisting stays off.
// merge) and atom hoisting stays off. Say so: the build still works,
// but its output differs from what the graph would have given.
console.warn(
setupWarning(
'import graph',
error,
'Classes are not merged across files only one module imports, and the production stylesheet waits for extraction to go quiet instead of for every compiled file.',
),
)
reportProfile('next.graph', {
durationMs: elapsedMs(graphStartedAt),
failed: true,
Expand All @@ -373,8 +413,15 @@ export function DevupUI(
toId: (path) => relative(cwd, path).replaceAll('\\', '/'),
}),
)
} catch {
} catch (error) {
// Best-effort; numbering falls back to arrival order.
console.warn(
setupWarning(
'file numbering',
error,
'Stylesheet file numbers follow the order Turbopack compiles files in, so they can differ between builds of the same source.',
),
)
}
// Turbopack can request a CSS module before it has scheduled every source
// loader. Waiting for a quiet window is not a compilation-complete signal:
Expand Down
Loading