diff --git a/.changepacks/changepack_log_devup_config_errors.json b/.changepacks/changepack_log_devup_config_errors.json new file mode 100644 index 000000000..ea7247e9a --- /dev/null +++ b/.changepacks/changepack_log_devup_config_errors.json @@ -0,0 +1,12 @@ +{ + "changes": { + "packages/plugin-utils/package.json": "Patch", + "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 broken `devup.json` is reported instead of silently loading an empty theme. New errors: ` is not valid JSON: `, ` must hold a JSON object`, and `devup.json extends form a cycle: a -> b -> a` (previously a cycle recursed until the stack overflowed). Vite, webpack, Rsbuild and Bun log the error and clear the theme as before (Bun used to swallow it); the Next.js Turbopack setup fails with it. `theme.d.ts` is now overwritten even when the theme has no tokens, so removed tokens leave no stale declarations. Rsbuild creates the CSS directory before writing into it, so a cold start no longer fails with ENOENT", + "date": "2026-11-15T00:00:00.000Z" +} diff --git a/packages/bun-plugin/src/__tests__/plugin.test.ts b/packages/bun-plugin/src/__tests__/plugin.test.ts index 6e2ea54a2..ac88f08db 100644 --- a/packages/bun-plugin/src/__tests__/plugin.test.ts +++ b/packages/bun-plugin/src/__tests__/plugin.test.ts @@ -287,9 +287,16 @@ describe('registered Bun hooks', () => { it('registers an empty theme when reading configuration fails', async () => { exists.mockReturnValue(true) - readConfig.mockRejectedValue(new Error('unreadable fixture config')) - await register({ engine: 'wasm' }) - expect(wasm.getDefaultTheme()).toBeUndefined() + const error = new Error('unreadable fixture config') + readConfig.mockRejectedValue(error) + const logged = spyOn(console, 'error').mockReturnValue(undefined) + try { + await register({ engine: 'wasm' }) + expect(wasm.getDefaultTheme()).toBeUndefined() + expect(logged).toHaveBeenCalledWith(error) + } finally { + logged.mockRestore() + } }) it('resolves generated stylesheets and loads their runtime placeholder', async () => { diff --git a/packages/bun-plugin/src/plugin.ts b/packages/bun-plugin/src/plugin.ts index 284772623..40c52bc28 100644 --- a/packages/bun-plugin/src/plugin.ts +++ b/packages/bun-plugin/src/plugin.ts @@ -61,8 +61,10 @@ async function writeDataFiles(compiler: DevupCompiler): Promise { const config = await loadDevupConfig(devupFile) theme = withTailwindCss(config.theme ?? {}, config) tailwindFiles = tailwindCssFiles(config) - } catch { - // Error reading devup.json, use empty theme + } catch (error) { + // A broken devup.json clears the theme, as in the other plugins; the + // error says which file and how to fix it. + console.error(error) } compiler.registerTheme(theme) diff --git a/packages/next-plugin/src/plugin.ts b/packages/next-plugin/src/plugin.ts index aa92f663e..21aa6042a 100644 --- a/packages/next-plugin/src/plugin.ts +++ b/packages/next-plugin/src/plugin.ts @@ -291,9 +291,9 @@ export function DevupUI( const themeInterface = getThemeInterface( ...createThemeInterfaceArgs(libPackage), ) - if (themeInterface) { - writeFileSync(join(distDir, 'theme.d.ts'), themeInterface) - } + // Written even when empty, so tokens removed from the theme leave no + // stale declarations behind. + writeFileSync(join(distDir, 'theme.d.ts'), themeInterface) // disable turbo parallel const excludeRegex = createNodeModulesExcludeRegex(include, '.mdx.[tj]sx?$') diff --git a/packages/plugin-utils/src/__tests__/load-config.test.ts b/packages/plugin-utils/src/__tests__/load-config.test.ts index bc3510ba7..85fa0ffe3 100644 --- a/packages/plugin-utils/src/__tests__/load-config.test.ts +++ b/packages/plugin-utils/src/__tests__/load-config.test.ts @@ -1,5 +1,5 @@ import { mkdirSync, rmSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' +import { join, resolve } from 'node:path' import { afterAll, beforeAll, describe, expect, it } from 'bun:test' @@ -91,12 +91,64 @@ describe('loadDevupConfigSync', () => { }) }) - it('should return empty object for invalid JSON', () => { + it('should report invalid JSON with its path', () => { const configPath = join(testDir, 'invalid.json') writeFileSync(configPath, 'not valid json {{{') - const result = loadDevupConfigSync(configPath) - expect(result).toEqual({}) + expect(() => loadDevupConfigSync(configPath)).toThrow( + `${resolve(configPath)} is not valid JSON: `, + ) + }) + + it.each([ + ['null', 'null'], + ['[]', 'an array'], + ['"theme"', 'a string'], + ])('should report a %s config that is not an object', (content, kind) => { + const configPath = join(testDir, 'not-object.json') + writeFileSync(configPath, content) + + expect(() => loadDevupConfigSync(configPath)).toThrow( + `${resolve(configPath)} must hold a JSON object such as { "theme": {} }, not ${kind}.`, + ) + }) + + it('should report extends that form a cycle', () => { + const baseDir = join(testDir, 'cycle') + mkdirSync(baseDir, { recursive: true }) + const a = join(baseDir, 'a.json') + const b = join(baseDir, 'b.json') + writeFileSync(a, JSON.stringify({ extends: ['./b.json'] })) + writeFileSync(b, JSON.stringify({ extends: ['./a.json'] })) + + expect(() => loadDevupConfigSync(a)).toThrow( + `devup.json \`extends\` form a cycle: ${resolve(a)} -> ${resolve(b)} -> ${resolve(a)}.`, + ) + }) + + it('should load a file that two extended files both extend', () => { + const baseDir = join(testDir, 'diamond') + mkdirSync(baseDir, { recursive: true }) + writeFileSync( + join(baseDir, 'root.json'), + JSON.stringify({ theme: { colors: { default: { text: 'red' } } } }), + ) + writeFileSync( + join(baseDir, 'left.json'), + JSON.stringify({ extends: ['./root.json'] }), + ) + writeFileSync( + join(baseDir, 'right.json'), + JSON.stringify({ extends: ['./root.json'] }), + ) + writeFileSync( + join(baseDir, 'top.json'), + JSON.stringify({ extends: ['./left.json', './right.json'] }), + ) + + expect(loadDevupConfigSync(join(baseDir, 'top.json'))).toEqual({ + theme: { colors: { default: { text: 'red' } } }, + }) }) it('should resolve extends', () => { @@ -214,6 +266,28 @@ describe('loadDevupConfig', () => { expect(result).toEqual({}) }) + it('should report invalid JSON with its path', async () => { + const configPath = join(testDir, 'async-invalid.json') + writeFileSync(configPath, '{ "theme": ') + + await expect(loadDevupConfig(configPath)).rejects.toThrow( + `${resolve(configPath)} is not valid JSON: `, + ) + }) + + it('should report extends that form a cycle', async () => { + const baseDir = join(testDir, 'async-cycle') + mkdirSync(baseDir, { recursive: true }) + const self = join(baseDir, 'self.json') + writeFileSync(self, JSON.stringify({ extends: ['./self.json'] })) + const inputs = new Set() + + await expect(loadDevupConfig(self, inputs)).rejects.toThrow( + `devup.json \`extends\` form a cycle: ${resolve(self)} -> ${resolve(self)}.`, + ) + expect([...inputs]).toEqual([resolve(self)]) + }) + it('should load and resolve extends asynchronously', async () => { const baseDir = join(testDir, 'async-extends') mkdirSync(baseDir, { recursive: true }) diff --git a/packages/plugin-utils/src/load-config.ts b/packages/plugin-utils/src/load-config.ts index 03b151be1..53e0c8282 100644 --- a/packages/plugin-utils/src/load-config.ts +++ b/packages/plugin-utils/src/load-config.ts @@ -46,14 +46,40 @@ export function deepMerge(base: T, override: U): T { } /** - * Parse JSON content safely + * Parse a config file's content. A file that is not a JSON object is an + * error naming the file: loading it as an empty config would silently drop + * the whole theme. */ -function parseConfig(content: string): DevupConfig { +function parseConfig(content: string, path: string): DevupConfig { + let config: unknown try { - return JSON.parse(content) as DevupConfig - } catch { - return {} + config = JSON.parse(content) + } catch (cause) { + throw new Error( + `${path} is not valid JSON: ${(cause as Error).message}. Fix its syntax; Devup UI does not load the theme until it parses.`, + { cause }, + ) + } + if (!isPlainObject(config)) { + throw new Error( + `${path} must hold a JSON object such as { "theme": {} }, not ${config === null ? 'null' : Array.isArray(config) ? 'an array' : `a ${typeof config}`}.`, + ) + } + return config as DevupConfig +} + +/** + * The `extends` chain that leads to `configPath`, ending with it. A file + * that is already on the chain extends itself through it, which never ends. + */ +function enterConfig(configPath: string, chain: readonly string[]): string[] { + const path = resolve(configPath) + if (chain.includes(path)) { + throw new Error( + `devup.json \`extends\` form a cycle: ${[...chain, path].join(' -> ')}. Remove the \`extends\` entry that points back to an earlier file.`, + ) } + return [...chain, path] } /** @@ -86,14 +112,23 @@ function mergeExtendedConfigs( export function loadDevupConfigSync( configPath: string, inputs?: Set, +): DevupConfig { + return loadConfigSync(configPath, inputs, []) +} + +function loadConfigSync( + configPath: string, + inputs: Set | undefined, + parents: readonly string[], ): DevupConfig { inputs?.add(resolve(configPath)) + const chain = enterConfig(configPath, parents) if (!existsSync(configPath)) { return {} } const content = readFileSync(configPath, 'utf-8') - const config = parseConfig(content) + const config = parseConfig(content, chain[chain.length - 1]) // If no extends, return the config as-is if (!config.extends || config.extends.length === 0) { @@ -105,7 +140,7 @@ export function loadDevupConfigSync( return mergeExtendedConfigs( config, config.extends.map((extendPath) => - loadDevupConfigSync(resolve(configDir, extendPath), inputs), + loadConfigSync(resolve(configDir, extendPath), inputs, chain), ), ) } @@ -117,17 +152,26 @@ export function loadDevupConfigSync( * @param configPath - Path to the devup.json file * @returns Resolved configuration with all extends merged */ -export async function loadDevupConfig( +export function loadDevupConfig( configPath: string, inputs?: Set, +): Promise { + return loadConfig(configPath, inputs, []) +} + +async function loadConfig( + configPath: string, + inputs: Set | undefined, + parents: readonly string[], ): Promise { inputs?.add(resolve(configPath)) + const chain = enterConfig(configPath, parents) if (!existsSync(configPath)) { return {} } const content = await readFile(configPath, 'utf-8') - const config = parseConfig(content) + const config = parseConfig(content, chain[chain.length - 1]) // If no extends, return the config as-is if (!config.extends || config.extends.length === 0) { @@ -140,7 +184,7 @@ export async function loadDevupConfig( const extendedConfigs: DevupConfig[] = [] for (const extendPath of config.extends) { extendedConfigs.push( - await loadDevupConfig(resolve(configDir, extendPath), inputs), + await loadConfig(resolve(configDir, extendPath), inputs, chain), ) } diff --git a/packages/rsbuild-plugin/src/__tests__/plugin.test.ts b/packages/rsbuild-plugin/src/__tests__/plugin.test.ts index 15afbd3ad..688257336 100644 --- a/packages/rsbuild-plugin/src/__tests__/plugin.test.ts +++ b/packages/rsbuild-plugin/src/__tests__/plugin.test.ts @@ -688,6 +688,35 @@ const App = () => `, } }) + it('overwrites theme.d.ts when the theme has no tokens and creates cssDir before writing into it', async () => { + getThemeInterfaceSpy.mockReturnValue('') + const cssDir = resolve('df', 'devup-ui') + let made = false + mkdirSpy.mockImplementation( + () => + new Promise((done) => + setTimeout(() => { + made = true + done(undefined) + }, 5), + ), + ) + const writtenAfterMkdir = new Map() + writeFileSpy.mockImplementation((path: string) => { + writtenAfterMkdir.set(path, made) + return Promise.resolve() + }) + const plugin = DevupUI({ atomHoist: 0 }) + await plugin.setup(createSetupContext()) + expect(writeFileSpy).toHaveBeenCalledWith( + join('df', 'theme.d.ts'), + '', + 'utf-8', + ) + expect(mkdirSpy).toHaveBeenCalledWith(cssDir, { recursive: true }) + expect(writtenAfterMkdir.get(join(cssDir, 'devup-ui.css'))).toBe(true) + }) + it('should call setPrefix when prefix option is provided', async () => { const plugin = DevupUI({ prefix: 'my-prefix' }) await plugin.setup( diff --git a/packages/rsbuild-plugin/src/plugin.ts b/packages/rsbuild-plugin/src/plugin.ts index 91dae66c8..842e1c91b 100644 --- a/packages/rsbuild-plugin/src/plugin.ts +++ b/packages/rsbuild-plugin/src/plugin.ts @@ -84,32 +84,28 @@ async function writeDataFiles( compiler.registerTheme(withTailwindCss(theme, config)) tailwindFiles = tailwindCssFiles(config) - const interfaceCode = compiler.getThemeInterface( - ...createThemeInterfaceArgs(options.package), + // Written even when empty, so tokens removed from the theme leave no + // stale declarations behind. + await writeFile( + join(options.distDir, 'theme.d.ts'), + compiler.getThemeInterface(...createThemeInterfaceArgs(options.package)), + 'utf-8', ) - - if (interfaceCode) { - await writeFile( - join(options.distDir, 'theme.d.ts'), - interfaceCode, - 'utf-8', - ) - } } catch (error) { console.error(error) compiler.registerTheme({}) } - await Promise.all([ - !existsSync(options.cssDir) - ? mkdir(options.cssDir, { recursive: true }) - : Promise.resolve(), - !options.singleCss - ? writeFile( - join(options.cssDir, 'devup-ui.css'), - compiler.getCss(null, false), - ) - : Promise.resolve(), - ]) + // Sequential: writing into cssDir concurrently with its own mkdir loses the + // race on a cold start (no `df/`) and fails the build with ENOENT. + if (!existsSync(options.cssDir)) { + await mkdir(options.cssDir, { recursive: true }) + } + if (!options.singleCss) { + await writeFile( + join(options.cssDir, 'devup-ui.css'), + compiler.getCss(null, false), + ) + } return tailwindFiles } diff --git a/packages/vite-plugin/src/__tests__/plugin.test.ts b/packages/vite-plugin/src/__tests__/plugin.test.ts index cbc3643da..610e1c418 100644 --- a/packages/vite-plugin/src/__tests__/plugin.test.ts +++ b/packages/vite-plugin/src/__tests__/plugin.test.ts @@ -1939,15 +1939,15 @@ describe('devupUIVitePlugin', () => { ).toEqual(expect.any(String)) }) - it('should not write interface code when no theme', async () => { + it('overwrites the interface code with nothing when the theme has no tokens', async () => { readFileSpy.mockResolvedValueOnce(JSON.stringify({})) getThemeInterfaceSpy.mockReturnValue('') existsSyncSpy.mockReturnValue(true) const plugin = createPlugin({}) await plugin.configResolved() - expect(writeFileSpy).not.toHaveBeenCalledWith( + expect(writeFileSpy).toHaveBeenCalledWith( join('df', 'theme.d.ts'), - expect.any(String), + '', 'utf-8', ) }) diff --git a/packages/vite-plugin/src/plugin.ts b/packages/vite-plugin/src/plugin.ts index f9ce736fc..1b573a0d5 100644 --- a/packages/vite-plugin/src/plugin.ts +++ b/packages/vite-plugin/src/plugin.ts @@ -283,17 +283,13 @@ async function writeDataFiles( compiler.registerTheme(withTailwindCss(theme, config)) publishTailwind(tailwindCssFiles(config)) - const interfaceCode = compiler.getThemeInterface( - ...createThemeInterfaceArgs(options.package), + // Written even when empty, so tokens removed from the theme leave no + // stale declarations behind. + await writeFile( + join(options.distDir, 'theme.d.ts'), + compiler.getThemeInterface(...createThemeInterfaceArgs(options.package)), + 'utf-8', ) - - if (interfaceCode) { - await writeFile( - join(options.distDir, 'theme.d.ts'), - interfaceCode, - 'utf-8', - ) - } } catch (error) { console.error(error) compiler.registerTheme({}) diff --git a/packages/webpack-plugin/src/__tests__/plugin.test.ts b/packages/webpack-plugin/src/__tests__/plugin.test.ts index f22c489e3..b2773541f 100644 --- a/packages/webpack-plugin/src/__tests__/plugin.test.ts +++ b/packages/webpack-plugin/src/__tests__/plugin.test.ts @@ -498,25 +498,21 @@ describe('devupUIWebpackPlugin', () => { 'CustomShadows', 'DevupTheme', ) - if (_options.getThemeInterface) - expect(writeFileSyncSpy).toHaveBeenCalledWith( - join(options.distDir, 'theme.d.ts'), - _options.getThemeInterface, - { - encoding: 'utf-8', - }, - ) - else expect(writeFileSyncSpy).toHaveBeenCalledTimes(options.watch ? 1 : 0) + // Written even when empty, so removed tokens leave no stale declarations. + expect(writeFileSyncSpy).toHaveBeenCalledWith( + join(options.distDir, 'theme.d.ts'), + _options.getThemeInterface, + { + encoding: 'utf-8', + }, + ) if (options.watch) expect(writeFileSyncSpy).toHaveBeenCalledWith( join(options.cssDir, 'devup-ui.css'), _options.getCss, ) - else - expect(writeFileSyncSpy).toHaveBeenCalledTimes( - _options.getThemeInterface ? 1 : 0, - ) + expect(writeFileSyncSpy).toHaveBeenCalledTimes(options.watch ? 2 : 1) }) }) diff --git a/packages/webpack-plugin/src/plugin.ts b/packages/webpack-plugin/src/plugin.ts index 2c5bd2ed0..718e4e68c 100644 --- a/packages/webpack-plugin/src/plugin.ts +++ b/packages/webpack-plugin/src/plugin.ts @@ -148,15 +148,15 @@ export class DevupUIWebpackPlugin { this.compiler.registerTheme(withTailwindCss(theme, config)) this.tailwindFiles = tailwindCssFiles(config) - const interfaceCode = this.compiler.getThemeInterface( - ...createThemeInterfaceArgs(this.options.package), + // Written even when empty, so tokens removed from the theme leave no + // stale declarations behind. + writeFileSync( + join(this.options.distDir, 'theme.d.ts'), + this.compiler.getThemeInterface( + ...createThemeInterfaceArgs(this.options.package), + ), + { encoding: 'utf-8' }, ) - - if (interfaceCode) { - writeFileSync(join(this.options.distDir, 'theme.d.ts'), interfaceCode, { - encoding: 'utf-8', - }) - } } catch (error) { console.error(error) this.compiler.registerTheme({})