From bcd1c88f3693f8f6afc1ae86abc0164a6826b48e Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sun, 15 Nov 2026 19:29:02 +0900 Subject: [PATCH 1/2] fix(plugins): resolve relative options against the bundler project root Builds started from a parent directory (turbo, nx, `next build apps/web`) resolved devupFile, distDir, cssDir, the tsconfig and the webpack extraction ids against process.cwd(), so they read the wrong devup.json, wrote df into the wrong directory and changed class names. - plugin-utils: add resolveProjectPath and resolveDevupFile. A relative path resolves against the project root, and is returned unchanged when the root is the cwd. The default devup.json falls back to the cwd one, with a one-time warning, when only the cwd holds one. - webpack: normalize the path options, productionPrewarmFiles and the tsconfig against compiler.options.context at apply time, pass the root to the loader, and key loader ids, dependencies, the canonical map, numbering and reservation on it. - Rsbuild: resolve the options and tsconfig against api.context.rootPath, and build the atom-hoist graph and reservation from it. - Vite: resolve devupFile, distDir, cssDir and the tsconfig against config.root in configResolved. - Next (webpack): place cssDir and the prewarm graph under the project directory Next passes to webpack. Turbopack keeps the cwd. - Bun: use the root of Bun.build when it sets one. Refs #686 Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_plugin_project_root.json | 12 +++ .../(detail)/docs/devup/devup-json/page.mdx | 10 +- packages/bun-plugin/README.md | 6 ++ .../bun-plugin/src/__tests__/plugin.test.ts | 63 ++++++++++- packages/bun-plugin/src/plugin.ts | 97 ++++++++++++----- packages/next-plugin/README.md | 17 +++ .../next-plugin/src/__tests__/plugin.test.ts | 41 +++++++ packages/next-plugin/src/plugin.ts | 6 +- .../src/__tests__/project-root.test.ts | 97 +++++++++++++++++ packages/plugin-utils/src/index.ts | 1 + packages/plugin-utils/src/project-root.ts | 46 ++++++++ packages/rsbuild-plugin/README.md | 14 +++ .../src/__tests__/plugin.test.ts | 72 +++++++++++++ .../src/__tests__/reservation.test.ts | 3 +- packages/rsbuild-plugin/src/plugin.ts | 27 +++-- packages/rsbuild-plugin/src/reservation.ts | 4 +- packages/vite-plugin/README.md | 13 +++ .../vite-plugin/src/__tests__/plugin.test.ts | 58 ++++++++++ packages/vite-plugin/src/plugin.ts | 40 +++++-- packages/webpack-plugin/README.md | 15 +++ .../src/__tests__/loader.test.ts | 43 ++++++++ .../src/__tests__/plugin.test.ts | 100 +++++++++++++++++- .../src/__tests__/reservation-roots.test.ts | 3 +- .../src/__tests__/reservation.test.ts | 5 +- packages/webpack-plugin/src/loader.ts | 29 +++-- packages/webpack-plugin/src/plugin.ts | 87 +++++++++++---- packages/webpack-plugin/src/reservation.ts | 7 +- 27 files changed, 830 insertions(+), 86 deletions(-) create mode 100644 .changepacks/changepack_log_plugin_project_root.json create mode 100644 packages/plugin-utils/src/__tests__/project-root.test.ts create mode 100644 packages/plugin-utils/src/project-root.ts diff --git a/.changepacks/changepack_log_plugin_project_root.json b/.changepacks/changepack_log_plugin_project_root.json new file mode 100644 index 000000000..e21e9303b --- /dev/null +++ b/.changepacks/changepack_log_plugin_project_root.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": "Resolve relative plugin options (devupFile, distDir, cssDir), the tsconfig and the webpack extraction ids against the bundler's project root (Vite root, webpack context, Rsbuild rootPath, Next's project directory for webpack builds, Bun.build root) instead of process.cwd(), so builds started from a parent directory as turbo or nx do read the project's devup.json and write its df. Builds started from the project root are unchanged. When devupFile is not set and only the working directory holds a devup.json, that file is still read and a one-time warning says to move it next to the project or set devupFile. Class names may change once for webpack and Next webpack builds run from a parent directory, because files are now numbered relative to the project root.", + "date": "2026-11-15T00:00:00.000Z" +} diff --git a/apps/landing/src/app/(detail)/docs/devup/devup-json/page.mdx b/apps/landing/src/app/(detail)/docs/devup/devup-json/page.mdx index 462776cec..203ceb4c9 100644 --- a/apps/landing/src/app/(detail)/docs/devup/devup-json/page.mdx +++ b/apps/landing/src/app/(detail)/docs/devup/devup-json/page.mdx @@ -254,7 +254,15 @@ your-project/ ## Plugin Configuration -By default, plugins look for `devup.json` in the project root. You can customize this: +By default, plugins look for `devup.json` in the project root: Vite's `root`, +webpack's `context`, Rsbuild's root, the Next.js project directory (webpack +builds) or the `root` of `Bun.build`. Relative `devupFile`, `distDir` and +`cssDir` paths resolve against it, not against the directory a monorepo tool +(turbo, nx, ...) starts the build from. If `devupFile` is not set and only the +working directory holds a `devup.json`, that file is still used and a one-time +warning asks you to move it into the project root or set `devupFile`. + +You can customize the path: ### Vite diff --git a/packages/bun-plugin/README.md b/packages/bun-plugin/README.md index 03b5d0223..edfbf94fb 100644 --- a/packages/bun-plugin/README.md +++ b/packages/bun-plugin/README.md @@ -140,6 +140,12 @@ Create a `devup.json` file in your project root: ``` The plugin will generate `df/theme.d.ts` with TypeScript types for your theme. + +The project root is the `root` of `Bun.build` when it sets one, and the working +directory otherwise: `devup.json`, `df` and `tsconfig.json` are read and written +there. When the root has no `devup.json` but the working directory does, that +file is still read and a one-time warning is printed; move `devup.json` into the +root to resolve it. ## How It Works diff --git a/packages/bun-plugin/src/__tests__/plugin.test.ts b/packages/bun-plugin/src/__tests__/plugin.test.ts index 6e2ea54a2..394a581ad 100644 --- a/packages/bun-plugin/src/__tests__/plugin.test.ts +++ b/packages/bun-plugin/src/__tests__/plugin.test.ts @@ -201,7 +201,9 @@ describe('registered Bun hooks', () => { ) exists.mockImplementation(realExists) const resolve = spyOn(nodePath, 'resolve').mockImplementation((...paths) => - paths.length === 1 && paths[0] === 'src' ? root : realResolve(...paths), + paths.length === 2 && paths[0] === process.cwd() && paths[1] === 'src' + ? root + : realResolve(...paths), ) try { await register({ engine: 'wasm' }) @@ -370,3 +372,62 @@ describe('registered Bun hooks', () => { await expect(load(path)).rejects.toThrow(/invalid\.ts:\d+:\d+:/) }) }) + +describe('project root', () => { + /** Run setup as `Bun.build` does, with `root` in its config */ + async function setupBuild(buildRoot: string | undefined) { + const ends: (() => void)[] = [] + const builder = { + config: { entrypoints: [], root: buildRoot }, + onStart: () => builder, + onEnd: (end: () => void) => { + ends.push(end) + return builder + }, + onResolve: () => builder, + onLoad: () => builder, + } + try { + await DevupUI({ engine: 'wasm' }).setup( + builder as unknown as Parameters< + ReturnType['setup'] + >[0], + ) + } finally { + // End the build session setup began + for (const end of ends) end() + } + return write.mock.calls.map(([path]) => String(path)) + } + + it('writes df under the root of Bun.build', async () => { + const buildRoot = nodePath.resolve('apps', 'web') + const written = await setupBuild(buildRoot) + expect(written).toContain(join(buildRoot, 'df', '.gitignore')) + expect(written).toContain(join(buildRoot, 'df', 'devup-ui', 'devup-ui.css')) + }) + + it('keeps writing df in the cwd without a root', async () => { + const written = await setupBuild(undefined) + expect(written).toContain(join('df', '.gitignore')) + expect(written).toContain( + nodePath.resolve('df', 'devup-ui', 'devup-ui.css'), + ) + }) + + it('falls back to the devup.json of the cwd with a warning', async () => { + const warn = spyOn(console, 'warn').mockReturnValue(undefined) + const cwdFile = nodePath.resolve('devup.json') + exists.mockImplementation((path) => String(path) === cwdFile) + try { + const buildRoot = nodePath.resolve('apps', 'bun-fallback') + const written = await setupBuild(buildRoot) + expect(readConfig).toHaveBeenCalledWith(cwdFile, 'utf-8') + expect(written).toContain(join(buildRoot, 'df', '.gitignore')) + expect(warn).toHaveBeenCalledTimes(1) + expect(String(warn.mock.calls[0]?.[0])).toContain('devupFile') + } finally { + warn.mockRestore() + } + }) +}) diff --git a/packages/bun-plugin/src/plugin.ts b/packages/bun-plugin/src/plugin.ts index 284772623..8fa49b544 100644 --- a/packages/bun-plugin/src/plugin.ts +++ b/packages/bun-plugin/src/plugin.ts @@ -18,8 +18,11 @@ import { mergeImportAliases, normalizeShorthands, readJsxImportSource, + resolveDevupFile, + resolveProjectPath, seedFileNumbers, tailwindCssFiles, + type WasmImportAliases, withTailwindCss, } from '@devup-ui/plugin-utils' import { type BunPlugin, plugin, type PluginBuilder } from 'bun' @@ -28,18 +31,42 @@ import { cssDirName, cssNamespace, resolveCssId } from './css-id' import { createTailwindWatcher } from './tailwind-watch' const libPackage = '@devup-ui/react' -const devupFile = 'devup.json' -const distDir = 'df' -const cssDir = resolve(distDir, cssDirName) +const distDirName = 'df' const singleCss = true -const importAliases = mergeImportAliases(undefined, readJsxImportSource()) -// The packages whose imports the extractor compiles: Devup UI, the packages it -// takes the place of, and StyleX -const compiledPackages = [ - libPackage, - '@stylexjs/stylex', - ...Object.keys(importAliases), -] + +/** Where a project keeps its files, and what its tsconfig compiles */ +interface BunProject { + readonly root: string + readonly devupFile: string + readonly distDir: string + readonly cssDir: string + readonly importAliases: WasmImportAliases + /** + * The packages whose imports the extractor compiles: Devup UI, the packages + * it takes the place of, and StyleX + */ + readonly compiledPackages: string[] +} + +/** + * The project at `root`: the `root` of `Bun.build`, or the working directory + * of the runtime and of a build without one + */ +function locateProject(root: string): BunProject { + const importAliases = mergeImportAliases(undefined, readJsxImportSource(root)) + return { + root, + devupFile: resolveDevupFile(root, undefined), + distDir: resolveProjectPath(root, distDirName), + cssDir: resolve(root, distDirName, cssDirName), + importAliases, + compiledPackages: [ + libPackage, + '@stylexjs/stylex', + ...Object.keys(importAliases), + ], + } +} export interface DevupUIBunPluginOptions { /** Native by default. Select WASM explicitly without automatic fallback. */ @@ -54,7 +81,10 @@ export interface DevupUIBunPluginOptions { type SourceLoader = 'tsx' | 'ts' | 'jsx' | 'js' -async function writeDataFiles(compiler: DevupCompiler): Promise { +async function writeDataFiles( + compiler: DevupCompiler, + { devupFile, distDir, cssDir }: BunProject, +): Promise { let theme = {} let tailwindFiles: string[] = [] try { @@ -88,7 +118,9 @@ async function initialize( compiler: DevupCompiler, shorthands: Record, watchTailwindCss: ReturnType, + project: BunProject, ) { + const { distDir } = project compiler.registerShorthands(shorthands) compiler.setPrefix(null) compiler.setModuleResolver(createModuleResolver()) @@ -96,16 +128,20 @@ async function initialize( await writeFile(join(distDir, '.gitignore'), '*', 'utf-8') await writeFile( join(distDir, 'compat.d.ts'), - createCompatTypes(importAliases), + createCompatTypes(project.importAliases), 'utf-8', ) - watchTailwindCss(await writeDataFiles(compiler)) + watchTailwindCss(await writeDataFiles(compiler, project)) } const scanners = new Map() /** Whether `contents` imports a package the extractor compiles */ -function importsCompiledPackage(contents: string, loader: SourceLoader) { +function importsCompiledPackage( + contents: string, + loader: SourceLoader, + compiledPackages: readonly string[], +) { let scanner = scanners.get(loader) if (!scanner) { scanner = new Bun.Transpiler({ loader }) @@ -129,6 +165,7 @@ async function loadSourceFile( compiler: DevupCompiler, filePath: string, bundling: boolean, + { cssDir, importAliases, compiledPackages }: BunProject, ) { const loader: SourceLoader = filePath.endsWith('.tsx') ? 'tsx' @@ -141,7 +178,7 @@ async function loadSourceFile( if ( isProjectJsx(filePath, importAliases) || - importsCompiledPackage(contents, loader) || + importsCompiledPackage(contents, loader, compiledPackages) || compiler.hasDevupUI(filePath, contents, libPackage, importAliases) ) { using code = compiler.codeExtract( @@ -175,8 +212,9 @@ async function loadSourceFile( function DevupUI(options: DevupUIBunPluginOptions = {}) { const shorthands = normalizeShorthands(options.shorthands ?? {}) const compiler = loadCompiler(options.engine) - const watchTailwindCss = createTailwindWatcher( - writeDataFiles.bind(undefined, compiler), + let project = locateProject(process.cwd()) + const watchTailwindCss = createTailwindWatcher(() => + writeDataFiles(compiler, project), ) return { name: 'devup-ui', @@ -184,11 +222,17 @@ function DevupUI(options: DevupUIBunPluginOptions = {}) { async setup(build: PluginBuilder) { // `Bun.build` hands its config to plugins; the runtime has none const bundling = build.config !== undefined + // The relative paths belong to the `root` of `Bun.build` when it sets + // one, not to the directory a monorepo tool starts the build from + project = locateProject( + resolve((bundling && build.config.root) || process.cwd()), + ) + const { root, importAliases, cssDir } = project // A build starts from its own options, not from what an earlier build in // this process left in the engine const endBuild = beginBuild(compiler) build.onEnd?.(endBuild) - await initialize(compiler, shorthands, watchTailwindCss) + await initialize(compiler, shorthands, watchTailwindCss, project) const debug = options.debug ?? !bundling compiler.setDebug(debug) const slots = createSharedSlotReservation(compiler) @@ -197,14 +241,14 @@ function DevupUI(options: DevupUIBunPluginOptions = {}) { slots.invalidate() slots.reserve( { - roots: [resolve('src'), resolve('app')], + roots: [resolve(root, 'src'), resolve(root, 'app')], entries: bundling ? build.config.entrypoints.map((entry) => ({ request: resolve(entry), - context: process.cwd(), + context: root, })) : [], - cwd: process.cwd(), + cwd: root, package: libPackage, importAliases, toId: (path) => path, @@ -228,8 +272,9 @@ function DevupUI(options: DevupUIBunPluginOptions = {}) { seedFileNumbers( compiler, collectNumberedFiles({ - roots: [resolve('src')], - needles: compiledPackages, + roots: [resolve(root, 'src')], + cwd: root, + needles: project.compiledPackages, importAliases, toId: (path) => path, }), @@ -244,7 +289,7 @@ function DevupUI(options: DevupUIBunPluginOptions = {}) { // content-keyed transpiler cache. See ./css-id. build.onResolve( { filter: /devup-ui(-\d+)?\.css$/ }, - ({ path, importer }) => resolveCssId(path, importer, distDir), + ({ path, importer }) => resolveCssId(path, importer, distDirName), ) // The bundler takes the stylesheet once every other module is loaded, @@ -270,7 +315,7 @@ function DevupUI(options: DevupUIBunPluginOptions = {}) { reserveFiles() reservationPending = false } - return loadSourceFile(compiler, path, bundling) + return loadSourceFile(compiler, path, bundling, project) }, ) }, diff --git a/packages/next-plugin/README.md b/packages/next-plugin/README.md index 631d06541..a82d06518 100644 --- a/packages/next-plugin/README.md +++ b/packages/next-plugin/README.md @@ -177,6 +177,23 @@ const box = const box = ``` +## Project root + +With webpack (`next build --webpack`), relative `devupFile`, `distDir` and +`cssDir` paths, the `tsconfig.json` the plugin reads and the file ids class names +are derived from resolve against the Next project directory, not against the +directory the build is started from. A build that a monorepo tool (turbo, nx, +...) runs from a parent directory (`next build apps/web`) reads +`apps/web/devup.json` and writes `apps/web/df`. Builds run from the project +directory are unchanged; builds run from a parent directory may get different +class names once. Turbopack does not tell its config the project directory, so +there the paths stay relative to the working directory. + +When `devupFile` is not set and the project directory has no `devup.json` but +the working directory does, that file is still read and a one-time warning is +printed. Move `devup.json` into the project directory, or set `devupFile` to the +file you want, to resolve it. + ## Custom Shorthands Custom shorthands belong to the plugin options rather than `devup.json` because diff --git a/packages/next-plugin/src/__tests__/plugin.test.ts b/packages/next-plugin/src/__tests__/plugin.test.ts index 639d7cfe3..851c735e2 100644 --- a/packages/next-plugin/src/__tests__/plugin.test.ts +++ b/packages/next-plugin/src/__tests__/plugin.test.ts @@ -461,6 +461,47 @@ describe('DevupUINextPlugin', () => { } }) + it('reads routes and places the CSS under the Next project directory', () => { + // Given: `next build apps/web` started from the workspace root. + const dir = resolve('apps', 'web') + existsSyncSpy.mockImplementation( + (path: fs.PathLike) => String(path) === join(dir, 'app'), + ) + const graphSpy = spyOn( + importGraphModule, + 'buildStaticImportGraph', + ).mockReturnValue(createSingleFileGraph(join(dir, 'app', 'page.tsx'))) + try { + // When + DevupUI({}).webpack!( + createWebpackConfig(), + createWebpackContext({ dir }), + ) + // Then + expect(graphSpy).toHaveBeenCalledWith(dir, join(dir, 'tsconfig.json')) + expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith( + expect.objectContaining({ + cssDir: join(dir, '.next', 'cache', 'devup-ui'), + }), + ) + } finally { + graphSpy.mockRestore() + } + }) + + it('places the dev CSS under the Next project directory', () => { + const dir = resolve('apps', 'web') + DevupUI({}).webpack!( + createWebpackConfig(), + createWebpackContext({ dev: true, dir }), + ) + expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith({ + cssDir: join(dir, 'df', 'devup-ui_tmpBuildId'), + engine: 'native', + watch: true, + }) + }) + it('should apply webpack plugin with dev', async () => { const ret = DevupUI({}) diff --git a/packages/next-plugin/src/plugin.ts b/packages/next-plugin/src/plugin.ts index aa92f663e..cae74d178 100644 --- a/packages/next-plugin/src/plugin.ts +++ b/packages/next-plugin/src/plugin.ts @@ -642,12 +642,16 @@ export function DevupUI( let productionPrewarmFiles: readonly string[] | undefined config.webpack = (config, _options) => { const { DevupUIWebpackPlugin } = loadWebpackPlugin() + // Next's project directory, which it also hands webpack as `context`: the + // webpack plugin resolves the relative options against it, not the cwd + const root = _options.dir ?? process.cwd() options.cssDir ??= resolve( + root, _options.dev ? (options.distDir ?? 'df') : '.next/cache', _options.dev ? `devup-ui_${_options.buildId}` : 'devup-ui', ) if (!_options.dev && productionPrewarmFiles === undefined) { - const cwd = process.cwd() + const cwd = root const srcDir = sourceDir(cwd) const tsconfigPath = resolve(cwd, 'tsconfig.json') const graph = buildStaticImportGraph(srcDir, tsconfigPath) diff --git a/packages/plugin-utils/src/__tests__/project-root.test.ts b/packages/plugin-utils/src/__tests__/project-root.test.ts new file mode 100644 index 000000000..40cb63b78 --- /dev/null +++ b/packages/plugin-utils/src/__tests__/project-root.test.ts @@ -0,0 +1,97 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' + +import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test' + +import { resolveDevupFile, resolveProjectPath } from '../project-root' + +let workspace: string +let project: string +let cwd: string +let warn: ReturnType + +beforeEach(() => { + cwd = process.cwd() + workspace = mkdtempSync(join(tmpdir(), 'devup-project-root-')) + project = join(workspace, 'apps', 'web') + mkdirSync(project, { recursive: true }) + process.chdir(workspace) + warn = spyOn(console, 'warn').mockReturnValue(undefined) +}) + +afterEach(() => { + warn.mockRestore() + process.chdir(cwd) + rmSync(workspace, { recursive: true, force: true }) +}) + +describe('resolveProjectPath', () => { + it('keeps a relative path as given when the build runs from the root', () => { + expect(resolveProjectPath(workspace, 'df')).toBe('df') + expect(resolveProjectPath(`${workspace}/`, 'devup.json')).toBe('devup.json') + }) + + it('resolves a relative path against a root other than the cwd', () => { + expect(resolveProjectPath(project, 'df')).toBe(join(project, 'df')) + expect(resolveProjectPath('apps/web', 'devup.json')).toBe( + join(project, 'devup.json'), + ) + }) + + it('keeps an absolute path', () => { + const absolute = resolve(workspace, 'elsewhere', 'df') + expect(resolveProjectPath(project, absolute)).toBe(absolute) + }) +}) + +describe('resolveDevupFile', () => { + it('reads the default devup.json from the cwd when it is the root', () => { + writeFileSync(join(workspace, 'devup.json'), '{}') + expect(resolveDevupFile(workspace, undefined)).toBe('devup.json') + expect(warn).not.toHaveBeenCalled() + }) + + it('reads the default devup.json of the project root', () => { + writeFileSync(join(project, 'devup.json'), '{}') + writeFileSync(join(workspace, 'devup.json'), '{}') + expect(resolveDevupFile(project, undefined)).toBe( + join(project, 'devup.json'), + ) + expect(warn).not.toHaveBeenCalled() + }) + + it('resolves a devupFile the user set against the root, without fallback', () => { + writeFileSync(join(workspace, 'theme.json'), '{}') + expect(resolveDevupFile(project, 'theme.json')).toBe( + join(project, 'theme.json'), + ) + expect(resolveDevupFile(project, 'devup.json')).toBe( + join(project, 'devup.json'), + ) + expect(warn).not.toHaveBeenCalled() + }) + + it('names the root file when neither the root nor the cwd holds one', () => { + expect(resolveDevupFile(project, undefined)).toBe( + join(project, 'devup.json'), + ) + expect(resolveDevupFile(workspace, undefined)).toBe('devup.json') + expect(warn).not.toHaveBeenCalled() + }) + + it('falls back to the cwd devup.json once, with a warning', () => { + const cwdFile = resolve(workspace, 'devup.json') + writeFileSync(cwdFile, '{}') + + expect(resolveDevupFile(project, undefined)).toBe(cwdFile) + expect(resolveDevupFile(project, undefined)).toBe(cwdFile) + + expect(warn).toHaveBeenCalledTimes(1) + const [message] = warn.mock.calls[0] as [string] + expect(message).toContain(cwdFile) + expect(message).toContain('project root') + expect(message).toContain(join(project, 'devup.json')) + expect(message).toContain('devupFile') + }) +}) diff --git a/packages/plugin-utils/src/index.ts b/packages/plugin-utils/src/index.ts index bfc7b1e1b..7c79cdd04 100644 --- a/packages/plugin-utils/src/index.ts +++ b/packages/plugin-utils/src/index.ts @@ -40,6 +40,7 @@ export { isProjectJsx, seedFileNumbers, } from './numbering' +export { resolveDevupFile, resolveProjectPath } from './project-root' export { collectReservationInputs, PreparedInputConflictError, diff --git a/packages/plugin-utils/src/project-root.ts b/packages/plugin-utils/src/project-root.ts new file mode 100644 index 000000000..324349e75 --- /dev/null +++ b/packages/plugin-utils/src/project-root.ts @@ -0,0 +1,46 @@ +import { existsSync } from 'node:fs' +import { isAbsolute, resolve } from 'node:path' + +const DEFAULT_DEVUP_FILE = 'devup.json' + +/** The roots already warned that their devup.json comes from the cwd */ +const warnedCwdDevupFiles = new Set() + +/** + * `path` resolved against the bundler's project root (Vite `root`, webpack + * `context`, Rsbuild `rootPath`, ...), not against the working directory a + * monorepo tool happens to start the build from. When the build runs from the + * project root itself, the path is returned as given, so the common case passes + * exactly the paths it always did. + */ +export function resolveProjectPath(root: string, path: string): string { + if (isAbsolute(path) || resolve(root) === resolve(process.cwd())) return path + return resolve(root, path) +} + +/** + * The devup.json of the project at `root`. `devupFile` set by the user resolves + * against the root. The default does too, except that a project without one + * whose working directory holds one keeps reading that file, with a one-time + * warning, as it did before the root became the base. + */ +export function resolveDevupFile( + root: string, + devupFile: string | undefined, +): string { + const projectFile = resolveProjectPath(root, devupFile ?? DEFAULT_DEVUP_FILE) + if (devupFile !== undefined || existsSync(projectFile)) return projectFile + const cwdFile = resolve(DEFAULT_DEVUP_FILE) + if (resolve(projectFile) === cwdFile || !existsSync(cwdFile)) + return projectFile + const warning = `${resolve(root)}\0${cwdFile}` + if (!warnedCwdDevupFiles.has(warning)) { + warnedCwdDevupFiles.add(warning) + console.warn( + `[devup-ui] Found devup.json relative to the working directory (${cwdFile}), not the project root (${resolve(root)}). ` + + 'Devup UI now resolves devupFile against the project root by default; ' + + `move devup.json to ${resolve(projectFile)} or set the devupFile option to keep using this file.`, + ) + } + return cwdFile +} diff --git a/packages/rsbuild-plugin/README.md b/packages/rsbuild-plugin/README.md index c94984cf7..11196c03d 100644 --- a/packages/rsbuild-plugin/README.md +++ b/packages/rsbuild-plugin/README.md @@ -197,6 +197,20 @@ The selected compiler serves configuration, reservation, transforms and delayed watch/build callbacks together. Neither engine supports concurrent independent builds in the same process. +## Project root + +Relative `devupFile`, `distDir` and `cssDir` paths, and the `tsconfig.json` the +plugin reads, resolve against Rsbuild's root (`api.context.rootPath`), not +against the directory the build is started from. A build that a monorepo tool +(turbo, nx, ...) runs from a parent directory reads `/devup.json` and +writes `/df`, as a build run from the project itself does. Builds run from +the project root are unchanged. + +When `devupFile` is not set and the project root has no `devup.json` but the +working directory does, that file is still read and a one-time warning is +printed. Move `devup.json` into the project root, or set `devupFile` to the file +you want, to resolve it. + ## Custom Shorthands ```ts diff --git a/packages/rsbuild-plugin/src/__tests__/plugin.test.ts b/packages/rsbuild-plugin/src/__tests__/plugin.test.ts index 15afbd3ad..ea0cd3940 100644 --- a/packages/rsbuild-plugin/src/__tests__/plugin.test.ts +++ b/packages/rsbuild-plugin/src/__tests__/plugin.test.ts @@ -222,6 +222,78 @@ describe('DevupUIRsbuildPlugin', () => { } }) + describe('project root', () => { + async function setupAt( + rootPath: string, + options: Parameters[0] = {}, + ) { + const transform = mock() + writeFileSpy.mockClear() + readFileSpy.mockClear() + const { context } = createSetupContext() + await DevupUI({ engine: 'wasm', atomHoist: 0, ...options }).setup( + createSetupContext({ transform, context: { ...context, rootPath } }), + ) + return { + cssTest: transform.mock.calls[0]?.[0].test as string, + written: writeFileSpy.mock.calls.map(([path]) => path), + } + } + + it('resolves the relative options against the Rsbuild root', async () => { + const root = resolve('apps', 'web') + const { cssTest, written } = await setupAt(root) + + expect(cssTest).toBe(join(root, 'df', 'devup-ui')) + expect(written).toContain(join(root, 'df', '.gitignore')) + expect(written).toContain(join(root, 'df', 'compat.d.ts')) + }) + + it('resolves relative user paths against the root', async () => { + const root = resolve('apps', 'web') + const devupFile = join(root, 'theme', 'devup.json') + existsSyncSpy.mockImplementation((path: string) => path === devupFile) + try { + const { cssTest, written } = await setupAt(root, { + devupFile: 'theme/devup.json', + distDir: 'out', + cssDir: 'out/css', + }) + + expect(cssTest).toBe(join(root, 'out', 'css')) + expect(written).toContain(join(root, 'out', '.gitignore')) + expect(readFileSpy).toHaveBeenCalledWith(devupFile, 'utf-8') + } finally { + existsSyncSpy.mockReturnValue(false) + } + }) + + it('keeps the paths as given when the root is the cwd', async () => { + const { cssTest, written } = await setupAt(process.cwd()) + + expect(cssTest).toBe(resolve('df', 'devup-ui')) + expect(written).toContain(join('df', '.gitignore')) + }) + + it('falls back to the devup.json of the cwd with a warning', async () => { + const warn = spyOn(console, 'warn').mockReturnValue(undefined) + const cwdFile = resolve('devup.json') + existsSyncSpy.mockImplementation((path: string) => path === cwdFile) + try { + const root = resolve('apps', 'rsbuild-fallback') + const { written } = await setupAt(root) + + expect(readFileSpy).toHaveBeenCalledWith(cwdFile, 'utf-8') + expect(written).toContain(join(root, 'df', '.gitignore')) + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0]?.[0]).toContain('devupFile') + } finally { + existsSyncSpy.mockReturnValue(false) + warn.mockRestore() + } + }) + }) + it('should return a plugin object with correct name', async () => { const plugin = DevupUI() expect(plugin).toBeDefined() diff --git a/packages/rsbuild-plugin/src/__tests__/reservation.test.ts b/packages/rsbuild-plugin/src/__tests__/reservation.test.ts index 323760fbf..de641a553 100644 --- a/packages/rsbuild-plugin/src/__tests__/reservation.test.ts +++ b/packages/rsbuild-plugin/src/__tests__/reservation.test.ts @@ -64,7 +64,8 @@ it.each([false, true])( { request: './a.js', context: resolve('external') }, ]) expect(discovery).toMatchObject({ - cwd: process.cwd(), + cwd: resolve('other'), + tsconfigPath: resolve('other', 'tsconfig.json'), include: ['included-ui'], package: '@devup-ui/react', importAliases: {}, diff --git a/packages/rsbuild-plugin/src/plugin.ts b/packages/rsbuild-plugin/src/plugin.ts index 91dae66c8..abc21319f 100644 --- a/packages/rsbuild-plugin/src/plugin.ts +++ b/packages/rsbuild-plugin/src/plugin.ts @@ -23,6 +23,8 @@ import { normalizeShorthands, planAtomHoist, readJsxImportSource, + resolveDevupFile, + resolveProjectPath, tailwindCssFiles, withTailwindCss, } from '@devup-ui/plugin-utils' @@ -127,9 +129,9 @@ export const DevupUI = ({ include = [], package: libPackage = '@devup-ui/react', extractCss = true, - distDir = 'df', - cssDir = resolve(distDir, 'devup-ui'), - devupFile = 'devup.json', + distDir: distDirOption = 'df', + cssDir: cssDirOption, + devupFile: devupFileOption, debug = false, singleCss = false, prefix, @@ -141,10 +143,6 @@ export const DevupUI = ({ const normalizedShorthands = normalizeShorthands(shorthands ?? {}) const compiler = loadCompiler(engine) compiler.registerShorthands(normalizedShorthands) - const importAliases = mergeImportAliases( - userImportAliases, - readJsxImportSource(), - ) const stateWriter = createStateWriter((path, content, encoding) => encoding ? writeFile(path, content, encoding) : writeFile(path, content), ) @@ -158,6 +156,19 @@ export const DevupUI = ({ api.onCloseBuild?.(endBuild) compiler.setDebug(debug) compiler.setPrefix(prefix ?? null) + // The relative options and the tsconfig belong to the Rsbuild root, not + // to the directory a monorepo tool starts the build from + const projectRoot = api.context.rootPath + const distDir = resolveProjectPath(projectRoot, distDirOption) + const cssDir = + cssDirOption === undefined + ? resolve(projectRoot, distDirOption, 'devup-ui') + : resolveProjectPath(projectRoot, cssDirOption) + const devupFile = resolveDevupFile(projectRoot, devupFileOption) + const importAliases = mergeImportAliases( + userImportAliases, + readJsxImportSource(projectRoot), + ) if (!existsSync(distDir)) await mkdir(distDir, { recursive: true }) await writeFile(join(distDir, '.gitignore'), '*', 'utf-8') @@ -240,7 +251,7 @@ export const DevupUI = ({ ) if (atomMode) { try { - const root = process.cwd() + const root = projectRoot const srcDir = resolve(root, 'src') const tsconfigPath = resolve(root, 'tsconfig.json') const canonicalMap = buildCanonicalMap({ diff --git a/packages/rsbuild-plugin/src/reservation.ts b/packages/rsbuild-plugin/src/reservation.ts index 897a03f6d..ab6f88c44 100644 --- a/packages/rsbuild-plugin/src/reservation.ts +++ b/packages/rsbuild-plugin/src/reservation.ts @@ -62,8 +62,8 @@ export function createReservation( })), ), include: options.include, - cwd: process.cwd(), - tsconfigPath: resolve(process.cwd(), 'tsconfig.json'), + cwd: options.root, + tsconfigPath: resolve(options.root, 'tsconfig.json'), package: options.package, importAliases: options.importAliases, toId: (path) => diff --git a/packages/vite-plugin/README.md b/packages/vite-plugin/README.md index 61bf1278b..b7d84532e 100644 --- a/packages/vite-plugin/README.md +++ b/packages/vite-plugin/README.md @@ -195,6 +195,19 @@ engine selection. Configuration, reservation, transforms and delayed callbacks use the same selected compiler. Neither engine supports concurrent independent builds in one process; Vite environments within a build share its compiler state. +## Project root + +Relative `devupFile`, `distDir` and `cssDir` paths, and the `tsconfig.json` the +plugin reads, resolve against Vite's `root`, not against the directory the build +is started from. A build that a monorepo tool (turbo, nx, ...) runs from a parent +directory reads `/devup.json` and writes `/df`, as a build run from +the project itself does. Builds run from the project root are unchanged. + +When `devupFile` is not set and the project root has no `devup.json` but the +working directory does, that file is still read and a one-time warning is +printed. Move `devup.json` into the project root, or set `devupFile` to the file +you want, to resolve it. + ## Custom Shorthands Custom shorthands are build-plugin options, not theme tokens. Every target diff --git a/packages/vite-plugin/src/__tests__/plugin.test.ts b/packages/vite-plugin/src/__tests__/plugin.test.ts index cbc3643da..a2ca31df9 100644 --- a/packages/vite-plugin/src/__tests__/plugin.test.ts +++ b/packages/vite-plugin/src/__tests__/plugin.test.ts @@ -310,6 +310,64 @@ afterEach(() => { consoleErrorSpy.mockRestore() }) +describe('project root', () => { + const written = () => writeFileSpy.mock.calls.map(([path]) => String(path)) + + it("resolves the relative options against Vite's root", async () => { + const root = resolve('apps', 'web') + const plugin = createPlugin() + await plugin.configResolved({ command: 'build', root }) + + expect(written()).toContain(join(root, 'df', '.gitignore')) + expect(written()).toContain(join(root, 'df', 'theme.d.ts')) + expect(written()).toContain(join(root, 'df', 'devup-ui', 'devup-ui.css')) + expect( + plugin.resolveId('./df/devup-ui/devup-ui.css', join(root, 'main.tsx')), + ).toBe(join(root, 'df', 'devup-ui', 'devup-ui.css')) + }) + + it('resolves relative user paths against the root', async () => { + const root = resolve('apps', 'web') + const devupFile = join(root, 'theme', 'devup.json') + existsSyncSpy.mockImplementation((path: string) => path === devupFile) + const plugin = createPlugin({ + devupFile: 'theme/devup.json', + distDir: 'out', + cssDir: 'out/css', + }) + await plugin.configResolved({ command: 'build', root }) + + expect(readFileSpy).toHaveBeenCalledWith(devupFile, 'utf-8') + expect(written()).toContain(join(root, 'out', '.gitignore')) + expect(written()).toContain(join(root, 'out', 'css', 'devup-ui.css')) + }) + + it('keeps the paths as given when the root is the cwd', async () => { + const plugin = createPlugin() + await plugin.configResolved({ command: 'build', root: process.cwd() }) + + expect(written()).toContain(join('df', '.gitignore')) + expect(written()).toContain(resolve('df', 'devup-ui', 'devup-ui.css')) + }) + + it('falls back to the devup.json of the cwd with a warning', async () => { + const warn = spyOn(console, 'warn').mockReturnValue(undefined) + const cwdFile = resolve('devup.json') + existsSyncSpy.mockImplementation((path: string) => path === cwdFile) + try { + const root = resolve('apps', 'vite-fallback') + await createPlugin().configResolved({ command: 'build', root }) + + expect(readFileSpy).toHaveBeenCalledWith(cwdFile, 'utf-8') + expect(written()).toContain(join(root, 'df', '.gitignore')) + expect(warn).toHaveBeenCalledTimes(1) + expect(String(warn.mock.calls[0]?.[0])).toContain('devupFile') + } finally { + warn.mockRestore() + } + }) +}) + describe('devupUIVitePlugin', () => { it('releases extracted Output before publishing CSS while retaining its result', async () => { // Given diff --git a/packages/vite-plugin/src/plugin.ts b/packages/vite-plugin/src/plugin.ts index f9ce736fc..49198d6ad 100644 --- a/packages/vite-plugin/src/plugin.ts +++ b/packages/vite-plugin/src/plugin.ts @@ -22,6 +22,8 @@ import { mergeImportAliases, normalizeShorthands, readJsxImportSource, + resolveDevupFile, + resolveProjectPath, seedFileNumbers, tailwindCssFiles, withTailwindCss, @@ -313,9 +315,9 @@ async function writeDataFiles( export function DevupUI({ package: libPackage = '@devup-ui/react', - devupFile = 'devup.json', - distDir = 'df', - cssDir = resolve(distDir, 'devup-ui'), + devupFile: devupFileOption, + distDir: distDirOption = 'df', + cssDir: cssDirOption, extractCss = true, debug = false, include = [], @@ -368,18 +370,41 @@ export function DevupUI({ compiler.setPrefix(prefix ?? null) } if (ownsEngine) configureEngine() - const importAliases = mergeImportAliases( + // The relative options and the tsconfig belong to the project root, which + // is known once the config resolves; until then the working directory + let distDir = distDirOption + let cssDir = cssDirOption ?? resolve(distDirOption, 'devup-ui') + let devupFile = devupFileOption ?? 'devup.json' + let importAliases = mergeImportAliases( userImportAliases, readJsxImportSource(), ) + function locate(root: string) { + distDir = resolveProjectPath(root, distDirOption) + cssDir = + cssDirOption === undefined + ? resolve(root, distDirOption, 'devup-ui') + : resolveProjectPath(root, cssDirOption) + devupFile = resolveDevupFile(root, devupFileOption) + importAliases = mergeImportAliases( + userImportAliases, + readJsxImportSource(root), + ) + } const reservation = createViteReservation(compiler, { package: libPackage, include, - importAliases, + get importAliases() { + return importAliases + }, singleCss, atomHoist, - cssDir, - distDir, + get cssDir() { + return cssDir + }, + get distDir() { + return distDir + }, relevant: (file) => isConfigFile(file) || isTailwindFile(file) || @@ -497,6 +522,7 @@ export function DevupUI({ resolvedConfig = config isServe = config?.command === 'serve' const projectRoot = config?.root ?? process.cwd() + locate(projectRoot) // Vite ids are POSIX absolute paths compiler.setModuleResolver( createModuleResolver({ diff --git a/packages/webpack-plugin/README.md b/packages/webpack-plugin/README.md index 74927fa6e..66a643582 100644 --- a/packages/webpack-plugin/README.md +++ b/packages/webpack-plugin/README.md @@ -200,6 +200,21 @@ Selection applies to the plugin, source loader, CSS loader and delayed build callbacks as one unit. Native state, like WASM state, does not support concurrent independent builds in the same process. +## Project root + +Relative `devupFile`, `distDir` and `cssDir` paths, the `tsconfig.json` the +plugin reads and the file ids class names are derived from resolve against +webpack's `context`, not against the directory the build is started from. A +build that a monorepo tool (turbo, nx, ...) runs from a parent directory reads +`/devup.json` and writes `/df`, as a build run from the project +itself does. Builds run from the project root are unchanged; builds run from a +parent directory may get different class names once. + +When `devupFile` is not set and the project root has no `devup.json` but the +working directory does, that file is still read and a one-time warning is +printed. Move `devup.json` into the project root, or set `devupFile` to the file +you want, to resolve it. + ## Custom Shorthands ```ts diff --git a/packages/webpack-plugin/src/__tests__/loader.test.ts b/packages/webpack-plugin/src/__tests__/loader.test.ts index 4da6cbe60..18fb0d052 100644 --- a/packages/webpack-plugin/src/__tests__/loader.test.ts +++ b/packages/webpack-plugin/src/__tests__/loader.test.ts @@ -212,6 +212,49 @@ describe('devupUILoader', () => { setModuleResolverSpy.mockRestore() } }) + it('extracts under ids relative to the project root, not the cwd', async () => { + const setModuleResolverSpy = spyOn( + wasm, + 'setModuleResolver', + ).mockReturnValue(undefined) + try { + const root = nodePath.resolve('apps', 'web') + codeExtractSpy.mockReturnValue( + createCodeExtractResult({ dependencies: ['src/tokens.ts'] }), + ) + const callback = mock() + const t = createLoaderContext( + { + package: 'package', + root, + cssDir: join(root, 'df', 'devup-ui'), + sheetFile: 'sheetFile', + classMapFile: 'classMapFile', + fileMapFile: 'fileMapFile', + watch: false, + singleCss: true, + }, + callback, + join(root, 'src', 'Card.tsx'), + ) + devupUILoader.bind(t)(Buffer.from('code'), 'Card.tsx') + await waitFor(() => expect(callback).toHaveBeenCalled()) + expect(codeExtractSpy.mock.calls[0]?.[0]).toBe('src/Card.tsx') + expect(t.addDependency).toHaveBeenCalledWith( + join(root, 'src', 'tokens.ts'), + ) + const resolveModule = setModuleResolverSpy.mock.calls[0][0] as ( + specifier: string, + importer: string, + ) => { path: string } | undefined + expect(resolveModule('./loader.test', import.meta.path)?.path).toBe( + nodePath.relative(root, import.meta.path).replaceAll('\\', '/'), + ) + } finally { + setModuleResolverSpy.mockRestore() + } + }) + it.each( createTestMatrix({ updatedBaseStyle: [true, false], diff --git a/packages/webpack-plugin/src/__tests__/plugin.test.ts b/packages/webpack-plugin/src/__tests__/plugin.test.ts index f22c489e3..6401acd13 100644 --- a/packages/webpack-plugin/src/__tests__/plugin.test.ts +++ b/packages/webpack-plugin/src/__tests__/plugin.test.ts @@ -433,6 +433,96 @@ describe('devupUIWebpackPlugin', () => { }, ) + describe('project root', () => { + const context = resolve('apps', 'web') + + function applyAt( + compilerContext: string | undefined, + options: ConstructorParameters[0] = {}, + ) { + const compiler = createCompiler() + compiler.options.context = compilerContext + const plugin = new DevupUIWebpackPlugin({ engine: 'wasm', ...options }) + plugin.apply(asCompiler(compiler)) + const [sourceRule] = compiler.options.module.rules as { + use: { options: { root: string; sheetFile: string } }[] + }[] + compiler.hooks.shutdown.tap.mock.calls[0][1]() + return { plugin, loader: sourceRule.use[0].options } + } + + it("resolves the relative options against webpack's context", () => { + const { plugin, loader } = applyAt(context, { + include: ['lib'], + productionPrewarmFiles: ['src/b.tsx', join(context, 'src', 'a.tsx')], + }) + + expect(plugin.options).toMatchObject({ + devupFile: join(context, 'devup.json'), + distDir: join(context, 'df'), + cssDir: join(context, 'df', 'devup-ui'), + productionPrewarmFiles: ['src/a.tsx', 'src/b.tsx'], + }) + expect(plugin.sheetFile).toBe(join(context, 'df', 'sheet.json')) + expect(loader.root).toBe(context) + expect(loader.sheetFile).toBe(join(context, 'df', 'sheet.json')) + expect(mkdirSyncSpy).toHaveBeenCalledWith(join(context, 'df'), { + recursive: true, + }) + expect(loadDevupConfigSyncSpy).toHaveBeenCalledWith( + join(context, 'devup.json'), + ) + }) + + it('resolves relative user paths against the context and keeps absolute ones', () => { + const cssDir = resolve('elsewhere', 'css') + const { plugin } = applyAt(context, { + devupFile: 'theme/devup.json', + distDir: 'out', + cssDir, + }) + + expect(plugin.options).toMatchObject({ + devupFile: join(context, 'theme', 'devup.json'), + distDir: join(context, 'out'), + cssDir, + }) + }) + + it('keeps the paths as given when the context is the cwd', () => { + const { plugin, loader } = applyAt(process.cwd(), { + productionPrewarmFiles: ['src/a.tsx'], + }) + + expect(plugin.options).toMatchObject({ + devupFile: 'devup.json', + distDir: 'df', + cssDir: resolve('df', 'devup-ui'), + productionPrewarmFiles: ['src/a.tsx'], + }) + expect(plugin.sheetFile).toBe(join('df', 'sheet.json')) + expect(loader.root).toBe(process.cwd()) + }) + + it('falls back to the devup.json of the cwd with a warning', () => { + const warn = spyOn(console, 'warn').mockReturnValue(undefined) + existsSyncSpy.mockImplementation( + (path: string) => path === resolve('devup.json'), + ) + try { + const fallbackContext = resolve('apps', 'fallback') + const { plugin } = applyAt(fallbackContext) + + expect(plugin.options.devupFile).toBe(resolve('devup.json')) + expect(plugin.options.distDir).toBe(join(fallbackContext, 'df')) + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0]?.[0]).toContain('devupFile') + } finally { + warn.mockRestore() + } + }) + }) + it('also reserves at native watchRun when watch persistence is disabled', async () => { const manager = { invalidate: mock(), @@ -1008,8 +1098,8 @@ describe('devupUIWebpackPlugin', () => { 'src/child.tsx': 'src/parent.tsx', }) computeReachableFilesSpy.mockReturnValue([ - resolve(process.cwd(), 'src', 'parent.tsx'), - resolve(process.cwd(), 'src', 'child.tsx'), + resolve('/project', 'src', 'parent.tsx'), + resolve('/project', 'src', 'child.tsx'), ]) readFileSyncSpy.mockReturnValue('source') const setModuleResolverSpy = spyOn( @@ -1031,8 +1121,8 @@ describe('devupUIWebpackPlugin', () => { plugin.apply(asCompiler(compiler)) compiler.hooks.run.tap.mock.calls[0][1]() expect(computeReachableFilesSpy).toHaveBeenCalledWith({ - srcDir: resolve(process.cwd(), 'src'), - tsconfigPath: resolve(process.cwd(), 'tsconfig.json'), + srcDir: resolve('/project', 'src'), + tsconfigPath: resolve('/project', 'tsconfig.json'), entries: [ resolve('/project', './src/parent'), resolve('/project', './src/other'), @@ -1054,7 +1144,7 @@ describe('devupUIWebpackPlugin', () => { import.meta.path, ) expect(resolved).toMatchObject({ - path: relative(process.cwd(), import.meta.path).replaceAll( + path: relative(resolve('/project'), import.meta.path).replaceAll( '\\', '/', ), diff --git a/packages/webpack-plugin/src/__tests__/reservation-roots.test.ts b/packages/webpack-plugin/src/__tests__/reservation-roots.test.ts index 040ccd725..4e426bfb1 100644 --- a/packages/webpack-plugin/src/__tests__/reservation-roots.test.ts +++ b/packages/webpack-plugin/src/__tests__/reservation-roots.test.ts @@ -151,8 +151,9 @@ for (const project of ['', 'project']) { expect(receipt.final.residual).toBe(0) expect(receipt.final.css).toContain('green') expect(receipt.entryCalls).toBe(receipt.compilations) + // Rows are ids relative to the compiler context, the project root. expect(receipt.reservations.flatMap((batch) => batch.rows)).toContain( - project ? 'project/app/entry.js' : 'app/entry.js', + 'app/entry.js', ) } finally { rmSync(root, { recursive: true, force: true }) diff --git a/packages/webpack-plugin/src/__tests__/reservation.test.ts b/packages/webpack-plugin/src/__tests__/reservation.test.ts index d117e2d10..74aca0281 100644 --- a/packages/webpack-plugin/src/__tests__/reservation.test.ts +++ b/packages/webpack-plugin/src/__tests__/reservation.test.ts @@ -22,7 +22,10 @@ it('maps the physical inventory to the exact loader IDs, CSS directory and flags resolve('context', 'src'), resolve('context', 'app'), ]) - expect(discovery.toId?.(input.physicalPath)).toBe('physical/A.js') + // The loader IDs are relative to webpack's context, the project root + expect(discovery.toId?.(input.physicalPath)).toBe('../physical/A.js') + expect(discovery.cwd).toBe(resolve('context')) + expect(discovery.tsconfigPath).toBe(resolve('context', 'tsconfig.json')) expect(discovery.include).toEqual(['@slot/ui']) expect(discovery.package).toBe('@devup-ui/react') expect(options.singleCss).toBe(true) diff --git a/packages/webpack-plugin/src/loader.ts b/packages/webpack-plugin/src/loader.ts index ee4db747f..dd4d20825 100644 --- a/packages/webpack-plugin/src/loader.ts +++ b/packages/webpack-plugin/src/loader.ts @@ -13,6 +13,8 @@ import type { LoaderContext, RawLoaderDefinitionFunction } from 'webpack' export interface DevupUILoaderOptions { readonly engine?: DevupEngine + /** The project root extraction ids are relative to; the cwd when absent */ + readonly root?: string package: string cssDir: string sheetFile: string @@ -41,15 +43,23 @@ function parseSourceMap(sourceMap: string | undefined): LoaderSourceMap { const stateWriter = createStateWriter((path, content, encoding) => encoding ? writeFile(path, content, encoding) : writeFile(path, content), ) -let moduleResolver: ReturnType | undefined +const moduleResolvers = new Map< + string, + ReturnType +>() -/** Resolve imports to the cwd-relative ids this loader extracts files under */ -function setCwdModuleResolver( +/** Resolve imports to the root-relative ids this loader extracts files under */ +function setRootModuleResolver( compiler: Pick, + root: string, ): void { - moduleResolver ??= createModuleResolver({ - toId: (path) => relative(process.cwd(), path).replaceAll('\\', '/'), - }) + let moduleResolver = moduleResolvers.get(root) + if (!moduleResolver) { + moduleResolver = createModuleResolver({ + toId: (path) => relative(root, path).replaceAll('\\', '/'), + }) + moduleResolvers.set(root, moduleResolver) + } compiler.setModuleResolver(moduleResolver) } @@ -64,6 +74,7 @@ const devupUILoader: RawLoaderDefinitionFunction = fileMapFile, singleCss, engine, + root = process.cwd(), importAliases = {}, } = this.getOptions() const callback = this.async() @@ -83,10 +94,10 @@ const devupUILoader: RawLoaderDefinitionFunction = // FILE_ROUTES keys (built with forward slashes by plugin-utils). Without // this, single-importer collapse and atom hoisting silently no-op on // Windows. No-op on POSIX. - const relativePath = relative(process.cwd(), id).replaceAll('\\', '/') + const relativePath = relative(root, id).replaceAll('\\', '/') if (!relCssDir.startsWith('./')) relCssDir = `./${relCssDir}` - setCwdModuleResolver(compiler) + setRootModuleResolver(compiler, root) const output: DevupCompilerOutput = compiler.codeExtract( relativePath, source.toString(), @@ -122,7 +133,7 @@ const devupUILoader: RawLoaderDefinitionFunction = dependencies, } = snapshot for (const dependency of dependencies) { - this.addDependency(resolve(dependency)) + this.addDependency(resolve(root, dependency)) } const sourceMap = parseSourceMap(map) const promises: Promise[] = [] diff --git a/packages/webpack-plugin/src/plugin.ts b/packages/webpack-plugin/src/plugin.ts index 2c5bd2ed0..d99b3b86e 100644 --- a/packages/webpack-plugin/src/plugin.ts +++ b/packages/webpack-plugin/src/plugin.ts @@ -25,6 +25,8 @@ import { normalizeShorthands, planAtomHoist, readJsxImportSource, + resolveDevupFile, + resolveProjectPath, seedFileNumbers, tailwindCssFiles, type WasmImportAliases, @@ -77,15 +79,22 @@ export class DevupUIWebpackPlugin { sheetFile: string classMapFile: string fileMapFile: string - private importAliases: WasmImportAliases + private importAliases: WasmImportAliases = {} private readonly normalizedShorthands: Record private readonly compiler: DevupCompiler + /** The path options as given, resolved against the project root */ + private readonly paths: Pick< + Partial, + 'cssDir' | 'devupFile' | 'distDir' | 'importAliases' + > & { readonly productionPrewarmFiles?: readonly string[] } + /** Webpack's `context` once applied; the working directory before */ + private root = process.cwd() constructor({ package: libPackage = '@devup-ui/react', - devupFile = 'devup.json', + devupFile, distDir = 'df', - cssDir = resolve(distDir, 'devup-ui'), + cssDir, watch = false, debug = false, include = [], @@ -100,15 +109,18 @@ export class DevupUIWebpackPlugin { this.normalizedShorthands = normalizeShorthands(shorthands ?? {}) this.compiler = loadCompiler(engine) this.compiler.registerShorthands(this.normalizedShorthands) - this.importAliases = mergeImportAliases( - userImportAliases, - readJsxImportSource(), - ) + this.paths = { + cssDir, + devupFile, + distDir, + importAliases: userImportAliases, + productionPrewarmFiles, + } this.options = { package: libPackage, - cssDir, - devupFile, + cssDir: '', + devupFile: '', distDir, watch, debug, @@ -118,6 +130,35 @@ export class DevupUIWebpackPlugin { prefix, shorthands, atomHoist, + productionPrewarmFiles: undefined, + } + this.sheetFile = '' + this.classMapFile = '' + this.fileMapFile = '' + this.locate(this.root) + } + + /** + * Resolve the path options, the tsconfig and the extraction ids against the + * project root, so a build started from a parent directory (as monorepo + * tools do) reads and writes the same files as one started from the root + */ + private locate(root: string) { + this.root = root + const { + cssDir, + devupFile, + distDir = 'df', + productionPrewarmFiles, + } = this.paths + this.options = { + ...this.options, + distDir: resolveProjectPath(root, distDir), + cssDir: + cssDir === undefined + ? resolve(root, distDir, 'devup-ui') + : resolveProjectPath(root, cssDir), + devupFile: resolveDevupFile(root, devupFile), productionPrewarmFiles: productionPrewarmFiles === undefined ? undefined @@ -125,14 +166,17 @@ export class DevupUIWebpackPlugin { ...new Set( productionPrewarmFiles.map((file) => relative( - process.cwd(), - resolve(process.cwd(), file.replaceAll('\\', '/')), + root, + resolve(root, file.replaceAll('\\', '/')), ).replaceAll('\\', '/'), ), ), ].sort(), } - + this.importAliases = mergeImportAliases( + this.paths.importAliases, + readJsxImportSource(root), + ) this.sheetFile = join(this.options.distDir, 'sheet.json') this.classMapFile = join(this.options.distDir, 'classMap.json') this.fileMapFile = join(this.options.distDir, 'fileMap.json') @@ -182,7 +226,7 @@ export class DevupUIWebpackPlugin { */ private prewarmExtractor(entries: string[]) { try { - const cwd = process.cwd() + const cwd = this.root // The same resolver as the loader's, so imported constants and // stylesheets extract to the classes the loader emits this.compiler.setModuleResolver( @@ -243,6 +287,7 @@ export class DevupUIWebpackPlugin { } private initialize(compiler: Compiler) { + this.locate(resolve(compiler.options.context ?? process.cwd())) this.compiler.setDebug(this.options.debug) this.compiler.setPrefix(this.options.prefix ?? null) this.compiler.registerShorthands(this.normalizedShorthands) @@ -286,8 +331,9 @@ export class DevupUIWebpackPlugin { // eligible atoms receive global short counter names. The selected compiler // instance is shared in-process with the loaders. Composes with // single-importer collapse: both keyed by the canonical bucket. The webpack - // loader passes relative(process.cwd(), id) as the extraction filename, so - // the graph maps use cwd-relative keys (keyBy: 'cwd-relative'). + // loader passes the id relative to the project root as the extraction + // filename, so the graph maps use root-relative keys (keyBy: + // 'cwd-relative', with the root as `cwd`). const atomHoist = this.options.atomHoist const atomMode = !this.options.singleCss && @@ -299,9 +345,9 @@ export class DevupUIWebpackPlugin { // The canonical map is built + imported unconditionally; only atom HOISTING // composes on top in effective atom mode. Mirrors next-plugin's pre-pass. try { - const srcDir = resolve(process.cwd(), 'src') - const tsconfigPath = resolve(process.cwd(), 'tsconfig.json') - const cwd = process.cwd() + const srcDir = resolve(this.root, 'src') + const tsconfigPath = resolve(this.root, 'tsconfig.json') + const cwd = this.root const canonicalMap = buildCanonicalMap({ srcDir, tsconfigPath, @@ -342,7 +388,7 @@ export class DevupUIWebpackPlugin { // already handed out (a restored map in watch mode) stay. if (this.options.debug) try { - const cwd = process.cwd() + const cwd = this.root seedFileNumbers( this.compiler, collectNumberedFiles({ @@ -379,7 +425,7 @@ export class DevupUIWebpackPlugin { const reserveBeforeCompile = () => { reserve(compiler.options) if (this.options.watch) return - const { entry, context = process.cwd() } = compiler.options + const { entry, context = this.root } = compiler.options this.prewarmExtractor( typeof entry === 'function' ? [] @@ -546,6 +592,7 @@ export class DevupUIWebpackPlugin { options: { package: this.options.package, engine: this.options.engine, + root: this.root, cssDir: this.options.cssDir, sheetFile: this.sheetFile, classMapFile: this.classMapFile, diff --git a/packages/webpack-plugin/src/reservation.ts b/packages/webpack-plugin/src/reservation.ts index 7caebdc1b..14c52d758 100644 --- a/packages/webpack-plugin/src/reservation.ts +++ b/packages/webpack-plugin/src/reservation.ts @@ -22,7 +22,8 @@ export function createWebpackReservation( }: Pick) => { const cwd = process.cwd() const root = resolve(context ?? cwd) - const toId = (path: string) => relative(cwd, path).replaceAll('\\', '/') + // The loaders extract files under ids relative to the project root + const toId = (path: string) => relative(root, path).replaceAll('\\', '/') compiler.setModuleResolver(createModuleResolver({ toId })) slots.invalidate() slots.reserve( @@ -42,8 +43,8 @@ export function createWebpackReservation( requests.map((request) => ({ request, context: root })), ), include: options.include, - cwd, - tsconfigPath: resolve(cwd, 'tsconfig.json'), + cwd: root, + tsconfigPath: resolve(root, 'tsconfig.json'), package: options.package, importAliases, toId, From 5d43b325edadae46ea26a969c7b11d95cf4f319d Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sun, 15 Nov 2026 19:33:57 +0900 Subject: [PATCH 2/2] refactor(bun-plugin): bind the Tailwind watcher to the located project Each setup updates one project object in place, so the watcher needs no extra closure. Refs #686 Co-Authored-By: Claude Opus 5.5 --- packages/bun-plugin/src/plugin.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/bun-plugin/src/plugin.ts b/packages/bun-plugin/src/plugin.ts index 8fa49b544..bc7d90899 100644 --- a/packages/bun-plugin/src/plugin.ts +++ b/packages/bun-plugin/src/plugin.ts @@ -212,9 +212,10 @@ async function loadSourceFile( function DevupUI(options: DevupUIBunPluginOptions = {}) { const shorthands = normalizeShorthands(options.shorthands ?? {}) const compiler = loadCompiler(options.engine) - let project = locateProject(process.cwd()) - const watchTailwindCss = createTailwindWatcher(() => - writeDataFiles(compiler, project), + // Each setup locates the project again; the watcher reads it then + const project = locateProject(process.cwd()) + const watchTailwindCss = createTailwindWatcher( + writeDataFiles.bind(undefined, compiler, project), ) return { name: 'devup-ui', @@ -224,8 +225,11 @@ function DevupUI(options: DevupUIBunPluginOptions = {}) { const bundling = build.config !== undefined // The relative paths belong to the `root` of `Bun.build` when it sets // one, not to the directory a monorepo tool starts the build from - project = locateProject( - resolve((bundling && build.config.root) || process.cwd()), + Object.assign( + project, + locateProject( + resolve((bundling && build.config.root) || process.cwd()), + ), ) const { root, importAliases, cssDir } = project // A build starts from its own options, not from what an earlier build in