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
11 changes: 11 additions & 0 deletions .changepacks/changepack_log_theme_errors_fail_build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"changes": {
"packages/vite-plugin/package.json": "Patch",
"packages/webpack-plugin/package.json": "Patch",
"packages/rsbuild-plugin/package.json": "Patch",
"packages/next-plugin/package.json": "Patch",
"packages/bun-plugin/package.json": "Patch"
},
"note": "A theme that cannot be loaded or registered (a broken `devup.json`, an invalid token name, or two token kinds that become the same CSS variable) now fails production builds with that error instead of building with an empty theme. Dev servers and watch builds keep running on an empty theme and report the error: Vite shows it in the error overlay in place of the reload, webpack, Next.js (webpack) and Rsbuild add it to every compilation's errors until it is fixed, and a Bun reload logs it",
"date": "2026-11-15T00:00:00.000Z"
}
63 changes: 61 additions & 2 deletions packages/bun-plugin/src/__tests__/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -312,16 +312,75 @@ describe('registered Bun hooks', () => {
expect(mkdir).not.toHaveBeenCalled()
})

it('registers an empty theme when reading configuration fails', async () => {
it('fails registration when reading configuration fails', async () => {
exists.mockReturnValue(true)
const error = new Error('unreadable fixture config')
readConfig.mockRejectedValue(error)
const logged = spyOn(console, 'error').mockReturnValue(undefined)
try {
await expect(register({ engine: 'wasm' })).rejects.toBe(error)
hooks.expectedErrors.add(error)
expect(logged).not.toHaveBeenCalled()
} finally {
logged.mockRestore()
}
})

it('fails registration when the theme cannot be registered', async () => {
exists.mockReturnValue(true)
readConfig.mockResolvedValue(
'{"theme":{"colors":{"default":{"card":"#fff"}},"shadows":{"default":{"card":"0 1px #000"}}}}',
)
const clash = new Error('clash')
const registration = spyOn(wasm, 'registerTheme').mockImplementationOnce(
() => {
throw clash
},
)
try {
await expect(register({ engine: 'wasm' })).rejects.toBe(clash)
hooks.expectedErrors.add(clash)
expect(registration).toHaveBeenCalledTimes(1)
} finally {
registration.mockRestore()
}
})

it('reports a failed reload of a changed Tailwind CSS and clears the theme', async () => {
const tailwind = join(root, 'reload-tailwind.css')
await Bun.write(tailwind, '@theme { --color-brand: #0af; }')
const listeners: (() => void)[] = []
const watching = spyOn(fs, 'watch').mockImplementation(((
_file: string,
_options: object,
listener: () => void,
) => {
listeners.push(listener)
return { on() {}, close() {} }
}) as unknown as typeof fs.watch)
exists.mockReturnValue(true)
readConfig.mockResolvedValueOnce(
JSON.stringify({
tailwind: { css: tailwind },
theme: { colors: { default: { primary: '#123456' } } },
}),
)
const error = new Error('broken devup.json')
readConfig.mockRejectedValueOnce(error)
const logged = spyOn(console, 'error').mockReturnValue(undefined)
try {
await register({ engine: 'wasm' })
expect(wasm.getDefaultTheme()).toBeUndefined()
expect(wasm.getDefaultTheme()).toBe('default')
expect(listeners).toHaveLength(1)

listeners[0]!()
for (let tick = 0; tick < 100 && logged.mock.calls.length === 0; tick++)
await Bun.sleep(1)

expect(logged).toHaveBeenCalledWith(error)
expect(wasm.getDefaultTheme()).toBeUndefined()
} finally {
watching.mockRestore()
logged.mockRestore()
}
})
Expand Down
23 changes: 15 additions & 8 deletions packages/bun-plugin/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,19 +56,26 @@ export interface DevupUIBunPluginOptions {

type SourceLoader = 'tsx' | 'ts' | 'jsx' | 'js'

async function writeDataFiles(compiler: DevupCompiler): Promise<string[]> {
let theme = {}
/**
* Load devup.json into the compiler. The first load fails on a theme that
* cannot be loaded or registered: Bun runs once, and an empty theme would
* leave every token unstyled. A reload for a changed Tailwind CSS runs in a
* process that is already up, so it reports the error and clears the theme.
*/
async function writeDataFiles(
compiler: DevupCompiler,
reloading = false,
): Promise<string[]> {
let tailwindFiles: string[] = []
try {
const config = await loadDevupConfig(devupFile)
theme = withTailwindCss(config.theme ?? {}, config)
tailwindFiles = tailwindCssFiles(config)
compiler.registerTheme(withTailwindCss(config.theme ?? {}, config))
} catch (error) {
// A broken devup.json clears the theme, as in the other plugins; the
// error says which file and how to fix it.
if (!reloading) throw error
console.error(error)
compiler.registerTheme({})
}
compiler.registerTheme(theme)

// Generate theme interface after registration (always write, even if empty)
await writeFile(
Expand Down Expand Up @@ -178,8 +185,8 @@ async function loadSourceFile(
function DevupUI(options: DevupUIBunPluginOptions = {}) {
const shorthands = normalizeShorthands(options.shorthands ?? {})
const compiler = loadCompiler(options.engine)
const watchTailwindCss = createTailwindWatcher(
writeDataFiles.bind(undefined, compiler),
const watchTailwindCss = createTailwindWatcher(() =>
writeDataFiles(compiler, true),
)
return {
name: 'devup-ui',
Expand Down
166 changes: 151 additions & 15 deletions packages/rsbuild-plugin/src/__tests__/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,28 +280,164 @@ describe('DevupUIRsbuildPlugin', () => {
expect(writeFileSyncSpy).not.toHaveBeenCalled()
})

it('should error when write data files', async () => {
it.each([
['rsbuild build', 'build'],
['an rsbuild without an action', undefined],
])('fails %s on a theme error', async (_name, action) => {
const consoleErrorSpy = spyOn(console, 'error').mockReturnValue(undefined)
try {
readFileSpy.mockRejectedValueOnce('error')
existsSyncSpy.mockImplementation((path: string) => {
if (path === 'devup.json') return true
return false
const clash = new Error(
"theme: color token 'card' and shadow token 'card' both become the CSS variable --card",
)
registerThemeSpy.mockImplementationOnce(() => {
throw clash
})
const plugin = DevupUI()
expect(plugin).toBeDefined()
expect(plugin.setup).toBeDefined()
existsSyncSpy.mockImplementation((path: string) => path === 'devup.json')
const transform = mock()
const modifyRsbuildConfig = mock()
await plugin.setup(
createSetupContext({
transform,
modifyRsbuildConfig,
}),

await expect(
DevupUI().setup(
createSetupContext({
transform,
context: { rootPath: process.cwd(), action },
} as Partial<RsbuildSetupContext>),
),
).rejects.toBe(clash)

expect(console.error).not.toHaveBeenCalled()
expect(transform).not.toHaveBeenCalled()
} finally {
consoleErrorSpy.mockRestore()
}
})

it.each([
['an Error', new Error('bad token'), '[devup-ui] bad token'],
['a thrown string', 'error', '[devup-ui] error'],
])(
'reports a theme error that is %s in every dev compilation until it loads again',
async (_name, thrown, message) => {
const consoleErrorSpy = spyOn(console, 'error').mockReturnValue(undefined)
const statSpy = spyOn(fsPromises, 'stat')
const readFileSyncSpy = spyOn(fs, 'readFileSync').mockReturnValue(
'@theme { --color-brand: #0af; }',
)
expect(console.error).toHaveBeenCalledWith('error')
try {
registerThemeSpy.mockImplementationOnce(() => {
throw thrown
})
readFileSpy.mockResolvedValue(
JSON.stringify({ tailwind: { css: 'tailwind.css' } }),
)
existsSyncSpy.mockImplementation(
(path: string) => path === 'devup.json',
)
const modifyRspackConfig = mock()
await DevupUI({ atomHoist: 0 }).setup(
createSetupContext({
modifyRspackConfig,
context: { rootPath: process.cwd(), action: 'dev' },
} as Partial<RsbuildSetupContext>),
)
expect(console.error).toHaveBeenCalledWith(thrown)
expect(registerThemeSpy).toHaveBeenLastCalledWith({})

const taps: Record<string, (...args: unknown[]) => unknown> = {}
const tap =
(hook: string) =>
(_: unknown, fn: (...args: unknown[]) => unknown) => {
taps[hook] = fn
}
const compiler = {
options: {},
rspack: {
WebpackError: Error,
Compilation: { PROCESS_ASSETS_STAGE_REPORT: 5000 },
},
hooks: {
run: { tap: tap('run') },
watchRun: { tap: tap('watchRun') },
invalid: { tap: tap('invalid') },
thisCompilation: { tap: tap('start') },
},
}
const config: { plugins?: { apply(compiler: unknown): void }[] } = {}
modifyRspackConfig.mock.calls[0][0](config)
const tapPromise = mock()
config.plugins![0]!.apply({ hooks: { watchRun: { tapPromise } } })
modifyRspackConfig.mock.calls[1][0](config, {
environment: { name: 'web' },
})
config.plugins![1]!.apply(compiler)
const compile = () => {
const compilation = {
errors: [] as Error[],
assets: {},
hooks: {
finishModules: { tap: mock() },
processAssets: { tap: mock() },
needAdditionalPass: { tap: mock() },
},
}
taps.start!(compilation)
return compilation.errors.map((error) => error.message)
}
expect(compile()).toEqual([message])
expect(compile()).toEqual([message])

// The theme loads again once its files change
const watchRun = tapPromise.mock.calls[0][1] as () => Promise<void>
statSpy.mockResolvedValueOnce({ mtimeMs: 1 } as fs.Stats)
await watchRun()
expect(compile()).toEqual([message])
statSpy.mockResolvedValueOnce({ mtimeMs: 2 } as fs.Stats)
await watchRun()
expect(compile()).toEqual([])
} finally {
consoleErrorSpy.mockRestore()
statSpy.mockRestore()
readFileSyncSpy.mockRestore()
readFileSpy.mockResolvedValue('{}')
}
},
)

it('keeps a dev server running when a reload fails to register the theme', async () => {
const consoleErrorSpy = spyOn(console, 'error').mockReturnValue(undefined)
const statSpy = spyOn(fsPromises, 'stat')
const readFileSyncSpy = spyOn(fs, 'readFileSync').mockReturnValue(
'@theme { --color-brand: #0af; }',
)
try {
readFileSpy.mockResolvedValue(
JSON.stringify({ tailwind: { css: 'tailwind.css' } }),
)
existsSyncSpy.mockImplementation((path: string) => path === 'devup.json')
const modifyRspackConfig = mock()
// A build run: only its first load fails the build
await DevupUI({}).setup(createSetupContext({ modifyRspackConfig }))
const config: { plugins?: { apply: (compiler: unknown) => void }[] } = {}
modifyRspackConfig.mock.calls[0][0](config)
const tapPromise = mock()
config.plugins?.[0].apply({ hooks: { watchRun: { tapPromise } } })
const watchRun = tapPromise.mock.calls[0][1] as () => Promise<void>
const failure = new Error('bad token')
registerThemeSpy.mockImplementationOnce(() => {
throw failure
})

statSpy.mockResolvedValueOnce({ mtimeMs: 1 } as fs.Stats)
await watchRun()
statSpy.mockResolvedValueOnce({ mtimeMs: 2 } as fs.Stats)
await watchRun()

expect(console.error).toHaveBeenCalledWith(failure)
expect(registerThemeSpy).toHaveBeenLastCalledWith({})
} finally {
consoleErrorSpy.mockRestore()
statSpy.mockRestore()
readFileSyncSpy.mockRestore()
readFileSpy.mockResolvedValue('{}')
}
})

Expand Down
Loading
Loading