From f7726648f45fa0ed96add4162c6d1df1ecc0eef9 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sun, 15 Nov 2026 10:11:40 +0900 Subject: [PATCH] fix(next-plugin): honor debug, restore session state whole and warn on setup fallbacks Three gaps in the Turbopack setup: - The `debug` option was ignored: the Turbopack branch never read it or called `setDebug`, unlike the webpack path. It is now set on the engine and is part of the production setup cache key. - A dev restart imported the sheet, class map and file map one after another in a single `try`. When a later file was missing or corrupt, the earlier ones stayed imported, and new styles could get names that clash with the restored ones. Every file is now read and parsed first, then all are imported; state that does not import is dropped with `resetBuildState`. The prefix and debug flag are set after the restore so a drop keeps them. - A failing import graph or file-numbering scan was swallowed, leaving a successful build without class merging, with idle-based CSS completion or with arrival-order file numbers. Both now print a warning with the cause and what the build loses. Refs #686 (NXT-10, NXT-14, NXT-18) Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_next_turbo_setup.json | 7 ++ .../next-plugin/src/__tests__/plugin.test.ts | 77 +++++++++++++++++- packages/next-plugin/src/plugin.ts | 79 +++++++++++++++---- 3 files changed, 145 insertions(+), 18 deletions(-) create mode 100644 .changepacks/changepack_log_next_turbo_setup.json diff --git a/.changepacks/changepack_log_next_turbo_setup.json b/.changepacks/changepack_log_next_turbo_setup.json new file mode 100644 index 000000000..ea198ca08 --- /dev/null +++ b/.changepacks/changepack_log_next_turbo_setup.json @@ -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" +} diff --git a/packages/next-plugin/src/__tests__/plugin.test.ts b/packages/next-plugin/src/__tests__/plugin.test.ts index 639d7cfe3..59be08a55 100644 --- a/packages/next-plugin/src/__tests__/plugin.test.ts +++ b/packages/next-plugin/src/__tests__/plugin.test.ts @@ -22,6 +22,7 @@ import { DevupUI, reloadTurboSetupModuleForTesting, resetTurboSetupCacheForTesting, + restoreSessionState, } from '../plugin' import { loadWasm, @@ -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) @@ -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 diff --git a/packages/next-plugin/src/plugin.ts b/packages/next-plugin/src/plugin.ts index aa92f663e..e52b59752 100644 --- a/packages/next-plugin/src/plugin.ts +++ b/packages/next-plugin/src/plugin.ts @@ -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 & { @@ -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 @@ -163,6 +200,7 @@ export function DevupUI( devupFile = 'devup.json', include = [], prefix, + debug = false, atomHoist, importAliases: userImportAliases, } = options @@ -194,6 +232,7 @@ export function DevupUI( atomHoist: requestedAtomHoist ? atomHoist : 0, cwd: process.cwd(), cssDir, + debug, devupFile, distDir, engine, @@ -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), @@ -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) @@ -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, @@ -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: