From b9402a63e23adf1804e6d552f5c703da610a7af3 Mon Sep 17 00:00:00 2001 From: Nicolas Charpentier Date: Mon, 27 Jul 2026 15:13:54 -0400 Subject: [PATCH 1/4] fix(migrate): tolerate nested npm overrides during bootstrap detection --- .../src/migration/__tests__/migrator.spec.ts | 34 +++++++++++++++++++ .../migration/migrator/vite-plus-bootstrap.ts | 5 ++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/migration/__tests__/migrator.spec.ts b/packages/cli/src/migration/__tests__/migrator.spec.ts index 92199c1c7b..3d7a8a496f 100644 --- a/packages/cli/src/migration/__tests__/migrator.spec.ts +++ b/packages/cli/src/migration/__tests__/migrator.spec.ts @@ -2565,6 +2565,40 @@ describe('ensureVitePlusBootstrap', () => { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(false); }); + it('tolerates nested npm override objects under managed keys', () => { + fs.writeFileSync( + path.join(tmpDir, 'package.json'), + JSON.stringify({ + name: 'test', + devDependencies: { 'vite-plus': 'latest' }, + // Nested npm override objects: user overrides scoped UNDER the managed + // keys. Neither aliases the package itself. + overrides: { + vite: { rollup: '^4.0.0' }, + vitest: { '@vitest/expect': '4.0.0' }, + }, + devEngines: { + packageManager: { name: 'npm', version: '10.33.0', onFail: 'download' }, + }, + }), + ); + + expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(true); + const result = ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.npm)); + + expect(result.changed).toBe(true); + expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(false); + const pkg = readJson(path.join(tmpDir, 'package.json')) as { + overrides: Record; + }; + // The nested object under `vite` does not satisfy the managed alias, so it + // is replaced with the managed override. + expect(pkg.overrides.vite).toContain('@voidzero-dev/vite-plus-core'); + // The project does NOT use vitest directly, so `vitest` is not managed; the + // user override scoped under it is left intact rather than removed. + expect(pkg.overrides.vitest).toEqual({ '@vitest/expect': '4.0.0' }); + }); + it('replaces protocol-pinned migration targets in force-override mode', () => { const savedForceMigrate = process.env.VP_FORCE_MIGRATE; process.env.VP_FORCE_MIGRATE = '1'; diff --git a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts index a6602e5e5f..aae8498d19 100644 --- a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts +++ b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts @@ -127,7 +127,10 @@ function overrideSpecSatisfiesVitePlus( spec: string | undefined, catalogDependencyResolver?: CatalogDependencyResolver, ): boolean { - if (!spec) { + // npm/bun `overrides` may hold a nested object value — a user override scoped + // UNDER the dependency (e.g. `{"vite": {"rollup": "..."}}`) that does not + // alias the dependency itself, so it never satisfies the managed override. + if (typeof spec !== 'string' || !spec) { return false; } if (isSemanticVitePlusOverrideSpec(dependencyName, spec)) { From 32849d36c0865a41aa78044aae0a59efd070f719 Mon Sep 17 00:00:00 2001 From: MK Date: Sun, 22 Nov 2026 13:31:47 +0800 Subject: [PATCH 2/4] fix(migrate): preserve child overrides under managed npm packages --- .../package.json | 4 +- .../snapshots.toml | 4 +- ...tion_upgrade_nested_vitest_override_npm.md | 9 +- docs/guide/migrate-rules.md | 1 + .../src/migration/__tests__/migrator.spec.ts | 100 ++++++++++++++---- .../cli/src/migration/migrator/catalog.ts | 8 +- .../src/migration/migrator/orchestrators.ts | 27 ++--- .../migration/migrator/vite-plus-bootstrap.ts | 28 +++-- .../migration/migrator/vitest-ecosystem.ts | 36 ++++++- 9 files changed, 155 insertions(+), 62 deletions(-) diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_nested_vitest_override_npm/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_nested_vitest_override_npm/package.json index 7d344a220d..a7a7298f80 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_nested_vitest_override_npm/package.json +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_nested_vitest_override_npm/package.json @@ -4,7 +4,9 @@ "vite-plus": "latest" }, "overrides": { - "vite": "npm:@voidzero-dev/vite-plus-core@latest", + "vite": { + "rollup": "^4.0.0" + }, "vitest": { "@vitest/runner": "4.0.0" } diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_nested_vitest_override_npm/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_nested_vitest_override_npm/snapshots.toml index 5fba7e2b39..ebb5468efc 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_nested_vitest_override_npm/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_nested_vitest_override_npm/snapshots.toml @@ -2,7 +2,7 @@ name = "migration_upgrade_nested_vitest_override_npm" vp = "global" steps = [ - { argv = ["vp", "migrate", "--no-interactive"], comment = "nested Vitest override is user-owned and not pending removal", continue-on-failure = true }, - { argv = ["vpt", "print-file", "package.json"], comment = "object-valued override is preserved", continue-on-failure = true }, + { argv = ["vp", "migrate", "--no-interactive"], comment = "add the Vite alias to the nested override", continue-on-failure = true }, + { argv = ["vpt", "print-file", "package.json"], comment = "preserve the Rollup and Vitest runner overrides", continue-on-failure = true }, { argv = ["vp", "migrate", "--no-interactive"], comment = "nested override must not make migration permanently pending", continue-on-failure = true }, ] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_nested_vitest_override_npm/snapshots/migration_upgrade_nested_vitest_override_npm.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_nested_vitest_override_npm/snapshots/migration_upgrade_nested_vitest_override_npm.md index 0c6a15853f..f506c62bd5 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_nested_vitest_override_npm/snapshots/migration_upgrade_nested_vitest_override_npm.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_nested_vitest_override_npm/snapshots/migration_upgrade_nested_vitest_override_npm.md @@ -2,7 +2,7 @@ ## `vp migrate --no-interactive` -nested Vitest override is user-owned and not pending removal +add the Vite alias to the nested override ``` VITE+ - The Unified Toolchain for the Web @@ -17,7 +17,7 @@ VITE+ - The Unified Toolchain for the Web ## `vpt print-file package.json` -object-valued override is preserved +preserve the Rollup and Vitest runner overrides ``` { @@ -26,7 +26,10 @@ object-valued override is preserved "vite-plus": "" }, "overrides": { - "vite": "npm:@voidzero-dev/vite-plus-core@", + "vite": { + "rollup": "^4.0.0", + ".": "npm:@voidzero-dev/vite-plus-core@" + }, "vitest": { "@vitest/runner": "" } diff --git a/docs/guide/migrate-rules.md b/docs/guide/migrate-rules.md index b32ecf636e..b7d8c174cf 100644 --- a/docs/guide/migrate-rules.md +++ b/docs/guide/migrate-rules.md @@ -410,6 +410,7 @@ Migration converts the Volta `volta.node` pin to `.node-version`, because Vite+ ### npm +- If a managed package has a nested override, migration writes its version or alias to the `"."` entry and keeps the child overrides. For example, a pin in `overrides.vite.rollup` stays in place when migration sets `overrides.vite["."]`. - Direct aliases are normalized before the matching override is added, so npm does not fail with `EOVERRIDE`. - When a real Vite installation changes to the core alias, stale Vite install and lockfile state is removed before reinstalling. - Opt-in browser-provider layouts get a top-level `vite` edge when nested Vitest packages otherwise cannot resolve it. diff --git a/packages/cli/src/migration/__tests__/migrator.spec.ts b/packages/cli/src/migration/__tests__/migrator.spec.ts index 3d7a8a496f..2f178e4df2 100644 --- a/packages/cli/src/migration/__tests__/migrator.spec.ts +++ b/packages/cli/src/migration/__tests__/migrator.spec.ts @@ -2565,38 +2565,64 @@ describe('ensureVitePlusBootstrap', () => { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(false); }); - it('tolerates nested npm override objects under managed keys', () => { + it('adds the Vite alias to a nested npm override and preserves its child overrides', () => { + const packageJsonPath = path.join(tmpDir, 'package.json'); + const workspace = makeWorkspaceInfo(tmpDir, PackageManager.npm); + const rollup = { '.': '^4.0.0', fsevents: '^2.3.3' }; + const vitest = { '@vitest/expect': '4.0.0' }; fs.writeFileSync( - path.join(tmpDir, 'package.json'), + packageJsonPath, JSON.stringify({ name: 'test', devDependencies: { 'vite-plus': 'latest' }, - // Nested npm override objects: user overrides scoped UNDER the managed - // keys. Neither aliases the package itself. + overrides: { vite: { rollup }, vitest }, + }), + ); + + expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(true); + expect(ensureVitePlusBootstrap(workspace).changed).toBe(true); + expect(readJson(packageJsonPath).overrides).toEqual({ + vite: { '.': VITE_PLUS_OVERRIDE_PACKAGES.vite, rollup }, + vitest, + }); + expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(false); + expect(ensureVitePlusBootstrap(workspace).changed).toBe(false); + }); + + it.each([ + { + usage: 'with Vitest coverage', + devDependencies: { vitest: VITEST_VERSION, '@vitest/coverage-v8': VITEST_VERSION }, + expected: { '.': VITEST_VERSION, '@vitest/expect': '4.0.0' }, + }, + { + usage: 'without direct Vitest usage', + devDependencies: {}, + expected: { '@vitest/expect': '4.0.0' }, + }, + ])('reconciles a stale nested npm vitest override $usage', ({ devDependencies, expected }) => { + const packageJsonPath = path.join(tmpDir, 'package.json'); + const workspace = makeWorkspaceInfo(tmpDir, PackageManager.npm); + fs.writeFileSync( + packageJsonPath, + JSON.stringify({ + name: 'test', + devDependencies: { 'vite-plus': 'latest', ...devDependencies }, overrides: { - vite: { rollup: '^4.0.0' }, - vitest: { '@vitest/expect': '4.0.0' }, - }, - devEngines: { - packageManager: { name: 'npm', version: '10.33.0', onFail: 'download' }, + vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, + vitest: { '.': 'npm:@voidzero-dev/vite-plus-test@0.1.0', '@vitest/expect': '4.0.0' }, }, }), ); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(true); - const result = ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.npm)); - - expect(result.changed).toBe(true); + expect(ensureVitePlusBootstrap(workspace).changed).toBe(true); + expect(readJson(packageJsonPath).overrides).toEqual({ + vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, + vitest: expected, + }); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(false); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - overrides: Record; - }; - // The nested object under `vite` does not satisfy the managed alias, so it - // is replaced with the managed override. - expect(pkg.overrides.vite).toContain('@voidzero-dev/vite-plus-core'); - // The project does NOT use vitest directly, so `vitest` is not managed; the - // user override scoped under it is left intact rather than removed. - expect(pkg.overrides.vitest).toEqual({ '@vitest/expect': '4.0.0' }); + expect(ensureVitePlusBootstrap(workspace).changed).toBe(false); }); it('replaces protocol-pinned migration targets in force-override mode', () => { @@ -6133,6 +6159,38 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { expect(overrides).not.toHaveProperty('@vitest/browser-preview'); }); + it.each(['standalone', 'workspace'])( + 'preserves nested npm overrides during a fresh %s migration', + (layout) => { + const packageJsonPath = path.join(tmpDir, 'package.json'); + const workspace = makeWorkspaceInfo(tmpDir, PackageManager.npm); + workspace.isMonorepo = layout === 'workspace'; + fs.writeFileSync( + packageJsonPath, + JSON.stringify({ + name: 'app', + workspaces: workspace.isMonorepo ? ['packages/*'] : undefined, + devDependencies: { vite: '^7.0.0', '@vitest/coverage-v8': '^4.0.0' }, + overrides: { + vite: { rollup: { picomatch: '^4.0.0' } }, + vitest: { '.': '^4.0.0', chai: '^5.0.0' }, + }, + }), + ); + + if (workspace.isMonorepo) { + rewriteMonorepo(workspace, true, true); + } else { + rewriteStandaloneProject(tmpDir, workspace, true, true); + } + + expect(readJson(packageJsonPath).overrides).toEqual({ + vite: { '.': VITE_PLUS_OVERRIDE_PACKAGES.vite, rollup: { picomatch: '^4.0.0' } }, + vitest: { '.': VITEST_VERSION, chai: '^5.0.0' }, + }); + }, + ); + it('preserves a provider override scoped under an unrelated parent', () => { // npm/bun nested overrides are SCOPED: a provider pin under `some-pkg` // forces the provider only within some-pkg's subtree, NOT vite-plus's own diff --git a/packages/cli/src/migration/migrator/catalog.ts b/packages/cli/src/migration/migrator/catalog.ts index d2d531b37d..c1a8a7d725 100644 --- a/packages/cli/src/migration/migrator/catalog.ts +++ b/packages/cli/src/migration/migrator/catalog.ts @@ -29,6 +29,7 @@ import { type NpmWorkspaces } from '../../utils/workspace.ts'; import { editYamlFile, readYamlFile, scalarString, type YamlDocument } from '../../utils/yaml.ts'; import { dropRemovePackageOverrideKeys, + ensureNpmOverrideEntries, ensurePnpmExoticSubdepsSetting, hasDirectVitePlusInstallEntry, isAlignableVitestEcosystemPackage, @@ -1223,7 +1224,7 @@ export function rewriteRootWorkspacePackageJson( let movedPnpmSettings: Record | undefined; editJsonFile<{ resolutions?: Record; - overrides?: Record; + overrides?: Record; devDependencies?: Record; dependencies?: Record; peerDependencies?: Record; @@ -1253,10 +1254,7 @@ export function rewriteRootWorkspacePackageJson( ...managed, }; } else if (packageManager === PackageManager.npm) { - pkg.overrides = { - ...pkg.overrides, - ...managed, - }; + pkg.overrides = ensureNpmOverrideEntries(pkg.overrides, managed).overrides; } else if (packageManager === PackageManager.bun) { // bun overrides are handled in rewriteBunCatalog() with catalog: references // when the workspace supports a catalog. Otherwise they stay concrete. diff --git a/packages/cli/src/migration/migrator/orchestrators.ts b/packages/cli/src/migration/migrator/orchestrators.ts index 53645daa03..d814d8600a 100644 --- a/packages/cli/src/migration/migrator/orchestrators.ts +++ b/packages/cli/src/migration/migrator/orchestrators.ts @@ -18,6 +18,7 @@ import { createCatalogDependencyResolver, dropDeadOxlintPluginsDependency, dropRemovePackageOverrideKeys, + ensureNpmOverrideEntries, ensurePnpmWorkspaceExoticSubdepsSetting, ensurePnpmWorkspacePackages, findYarnWorkspaceHoisting, @@ -156,7 +157,7 @@ export function rewriteStandaloneProject( workspaceInfo.downloadPackageManager.version, ); editJsonFile<{ - overrides?: Record; + overrides?: Record; resolutions?: Record; devDependencies?: Record; dependencies?: Record; @@ -193,22 +194,22 @@ export function rewriteStandaloneProject( ...pkg.resolutions, ...managed, }; - } else if (packageManager === PackageManager.npm || packageManager === PackageManager.bun) { + } else if (packageManager === PackageManager.npm) { + pkg.overrides = ensureNpmOverrideEntries(pkg.overrides, managed).overrides; + } else if (packageManager === PackageManager.bun) { pkg.overrides = { ...pkg.overrides, ...managed, }; - if (packageManager === PackageManager.bun) { - // Bun walks transitive peer-deps before resolving overrides; vitest - // 4.1.9 declares peer `vite ^6 || ^7 || ^8` and aborts with - // "vite@... failed to resolve" if `vite` isn't a direct dep somewhere - // in the tree, even when the override would redirect it. Mirror the - // override as a devDep so bun's resolver sees `vite` immediately. A - // standalone bun project has no catalog (supportCatalog=false), so the - // shared helper resolves this to the concrete core alias. Verified on - // bun 1.3.11. See https://github.com/oven-sh/bun/issues/8406. - setDirectViteEdge(pkg, supportCatalog, catalogDependencyResolver); - } + // Bun walks transitive peer-deps before resolving overrides; vitest + // 4.1.9 declares peer `vite ^6 || ^7 || ^8` and aborts with + // "vite@... failed to resolve" if `vite` isn't a direct dep somewhere + // in the tree, even when the override would redirect it. Mirror the + // override as a devDep so bun's resolver sees `vite` immediately. A + // standalone bun project has no catalog (supportCatalog=false), so the + // shared helper resolves this to the concrete core alias. Verified on + // bun 1.3.11. See https://github.com/oven-sh/bun/issues/8406. + setDirectViteEdge(pkg, supportCatalog, catalogDependencyResolver); } else if (packageManager === PackageManager.pnpm) { if (usePnpmWorkspaceYaml) { shouldAddPnpmWorkspaceVitePlusOverride = isForceOverrideMode(); diff --git a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts index aae8498d19..4af4cde8fb 100644 --- a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts +++ b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts @@ -23,6 +23,7 @@ import { collectProviderSourceModes, collectVitestEcosystemInstallDependencyNames, createCatalogDependencyResolver, + ensureNpmOverrideEntries, ensurePnpmWorkspacePackages, findYarnWorkspaceHoisting, getAlignedVitestEcosystemDependencySpec, @@ -83,7 +84,7 @@ import { } from './shared.ts'; export type BootstrapPackageJson = { - overrides?: Record; + overrides?: Record; resolutions?: Record; devDependencies?: Record; dependencies?: Record; @@ -124,12 +125,9 @@ function isSemanticVitePlusOverrideSpec(dependencyName: string, spec: string | u function overrideSpecSatisfiesVitePlus( dependencyName: string, - spec: string | undefined, + spec: unknown, catalogDependencyResolver?: CatalogDependencyResolver, ): boolean { - // npm/bun `overrides` may hold a nested object value — a user override scoped - // UNDER the dependency (e.g. `{"vite": {"rollup": "..."}}`) that does not - // alias the dependency itself, so it never satisfies the managed override. if (typeof spec !== 'string' || !spec) { return false; } @@ -146,7 +144,7 @@ function overrideSpecSatisfiesVitePlus( } export function overridesSatisfyVitePlus( - overrides: Record | undefined, + overrides: Record | undefined, usesVitest: boolean, catalogDependencyResolver?: CatalogDependencyResolver, keyStyle: ManagedOverrideKeyStyle = 'bare', @@ -746,7 +744,8 @@ export function detectVitePlusBootstrapPending( if (packageManager === PackageManager.npm) { return ( vitePlusDependencyNeedsConcreteVersion(pkg) || - !overridesSatisfyVitePlus(pkg.overrides, usesVitest, undefined, 'bare', usesWebdriverio) || + ensureNpmOverrideEntries(pkg.overrides, managedOverridePackages(usesVitest, usesWebdriverio)) + .changed || npmVitePlusManagedDependenciesPending(pkg, usesVitest) ); } @@ -912,14 +911,14 @@ function readTextFileIfExists(filePath: string): string | undefined { return fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf-8') : undefined; } -function ensureOverrideEntries( - overrides: Record | undefined, +function ensureOverrideEntries( + overrides: Record | undefined, usesVitest: boolean, catalogDependencyResolver?: CatalogDependencyResolver, keyStyle: ManagedOverrideKeyStyle = 'bare', usesWebdriverioProvider = false, -): { overrides: Record; changed: boolean } { - const next = { ...overrides }; +): { overrides: Record; changed: boolean } { + const next: Record = { ...overrides }; let changed = false; // Common case: drop a lingering managed `vitest` override. if (!usesVitest && removeManagedVitestEntry(next, keyStyle)) { @@ -1108,12 +1107,9 @@ export function ensureVitePlusBootstrap( packageJsonChanged = true; } } else if (workspaceInfo.packageManager === PackageManager.npm) { - const ensured = ensureOverrideEntries( + const ensured = ensureNpmOverrideEntries( pkg.overrides, - usesVitest, - undefined, - 'bare', - usesWebdriverio, + managedOverridePackages(usesVitest, usesWebdriverio), ); if (ensured.changed) { pkg.overrides = ensured.overrides; diff --git a/packages/cli/src/migration/migrator/vitest-ecosystem.ts b/packages/cli/src/migration/migrator/vitest-ecosystem.ts index 12df14be9d..f809c07fe0 100644 --- a/packages/cli/src/migration/migrator/vitest-ecosystem.ts +++ b/packages/cli/src/migration/migrator/vitest-ecosystem.ts @@ -356,6 +356,40 @@ export function managedOverridePackages( : managed; } +// In npm's object form, "." overrides the package itself. All other keys +// constrain its children and must survive a change to the package's own pin. +export function ensureNpmOverrideEntries( + overrides: Record | undefined, + managed: Record, +): { overrides: Record; changed: boolean } { + const next = { ...overrides }; + let changed = false; + if (VITEST_IS_MANAGED_OVERRIDE && !('vitest' in managed)) { + const vitest = next.vitest; + if (isPlainRecord(vitest) && typeof vitest['.'] === 'string') { + const children = { ...vitest }; + delete children['.']; + if (Object.keys(children).length) { + next.vitest = children; + } else { + delete next.vitest; + } + changed = true; + } else { + changed = removeManagedVitestEntry(next); + } + } + + for (const [name, spec] of Object.entries(managed)) { + const current = next[name]; + if ((isPlainRecord(current) ? current['.'] : current) !== spec) { + next[name] = isPlainRecord(current) ? { ...current, '.': spec } : spec; + changed = true; + } + } + return { overrides: next, changed }; +} + // True iff a dependency field lists a vitest ecosystem package — any name that // contains `vitest` other than bare `vitest` itself (e.g. `@vitest/coverage-v8`, // `@vitest/browser-playwright`, `vitest-browser-svelte`). A bare `vitest` @@ -501,7 +535,7 @@ export function projectUsesVitestDirectly( // `bare`. npm also accepts a range in an override key, so a user-authored // `"vitest@*"` in npm `overrides` belongs to the user. Do not delete it. export function removeManagedVitestEntry( - record: Record | undefined, + record: Record | undefined, keyStyle: ManagedOverrideKeyStyle = 'bare', ): boolean { if (!VITEST_IS_MANAGED_OVERRIDE || !record) { From ff2825754484e4809bc1a4bca9d780bc57c5adcd Mon Sep 17 00:00:00 2001 From: MK Date: Sun, 22 Nov 2026 13:45:49 +0800 Subject: [PATCH 3/4] fix(migrate): preserve child overrides in Bun projects --- .../package.json | 7 +- .../snapshots.toml | 3 +- .../migration_upgrade_bun_catalog.md | 17 ++- docs/guide/migrate-rules.md | 3 +- .../src/migration/__tests__/migrator.spec.ts | 115 ++++++++++++------ .../cli/src/migration/migrator/catalog.ts | 81 ++++++------ .../src/migration/migrator/orchestrators.ts | 49 ++++---- .../migration/migrator/vite-plus-bootstrap.ts | 65 ++++------ .../migration/migrator/vitest-ecosystem.ts | 17 ++- 9 files changed, 196 insertions(+), 161 deletions(-) diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_bun_catalog/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_bun_catalog/package.json index 5002f0480f..6f86a331c0 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_bun_catalog/package.json +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_bun_catalog/package.json @@ -8,13 +8,16 @@ "vitest": "catalog:" }, "overrides": { - "vite": "catalog:", + "vite": { + ".": "catalog:", + "postcss": "8.5.32" + }, "vitest": "catalog:" }, "devEngines": { "packageManager": { "name": "bun", - "version": "1.3.11", + "version": "1.4.5", "onFail": "download" } }, diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_bun_catalog/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_bun_catalog/snapshots.toml index 0abbb20d42..bf22b4d477 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_bun_catalog/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_bun_catalog/snapshots.toml @@ -3,5 +3,6 @@ name = "migration_upgrade_bun_catalog" vp = "global" steps = [ { argv = ["vp", "migrate", "--no-interactive"], comment = "existing bun Vite+ catalog WORKSPACE gains a direct vite edge for bun#8406 (bun resolves catalog: only inside a workspace)", continue-on-failure = true }, - { argv = ["vpt", "print-file", "package.json"], comment = "the direct vite edge is catalog: (resolving through the bun catalog), not a concrete alias", continue-on-failure = true }, + { argv = ["vp", "migrate", "--no-interactive"], comment = "the second migration finds the workspace up to date", continue-on-failure = true }, + { argv = ["vpt", "print-file", "package.json"], comment = "the direct Vite dependency and its override use the catalog, and the PostCSS pin survives both runs", continue-on-failure = true }, ] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_bun_catalog/snapshots/migration_upgrade_bun_catalog.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_bun_catalog/snapshots/migration_upgrade_bun_catalog.md index b694a66f21..ae30d900aa 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_bun_catalog/snapshots/migration_upgrade_bun_catalog.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_bun_catalog/snapshots/migration_upgrade_bun_catalog.md @@ -15,9 +15,19 @@ VITE+ - The Unified Toolchain for the Web • Package manager settings configured ``` +## `vp migrate --no-interactive` + +the second migration finds the workspace up to date + +``` +VITE+ - The Unified Toolchain for the Web + +This project is already using Vite+! Happy coding! +``` + ## `vpt print-file package.json` -the direct vite edge is catalog: (resolving through the bun catalog), not a concrete alias +the direct Vite dependency and its override use the catalog, and the PostCSS pin survives both runs ``` { @@ -30,7 +40,10 @@ the direct vite edge is catalog: (resolving through the bun catalog), not a conc "vite-plus": "catalog:" }, "overrides": { - "vite": "catalog:" + "vite": { + ".": "catalog:", + "postcss": "8.5.32" + } }, "devEngines": { "packageManager": { diff --git a/docs/guide/migrate-rules.md b/docs/guide/migrate-rules.md index b7d8c174cf..a34df36d1c 100644 --- a/docs/guide/migrate-rules.md +++ b/docs/guide/migrate-rules.md @@ -193,7 +193,7 @@ Migration detects Playwright usage before it rewrites imports, including legacy `vp migrate` restores removed Vite+ WebDriverIO aliases to `@vitest/browser-webdriverio` and adds `^5.0.0` if the provider is missing. It upgrades older versions, narrows ranges that allow versions below `5.0.0`, updates referenced catalog entries, and removes overrides that force an older provider. Versions and ranges that meet the minimum stay unchanged. Migration ensures the required `webdriverio` peer and adds an `@vitest/browser` override matching bundled Vitest (`resolutions` for Yarn). You manage later community provider upgrades. See [Community WebDriverIO provider](./vitest-v5.md#community-webdriverio-provider). -Object-valued nested npm and Bun overrides are preserved: they are user-defined scopes rather than scalar version pins. +For npm and Bun, migration reads or updates the `"."` entry of a nested override for a managed package. It preserves child entries in `package.json`, including pins such as `overrides.vite.postcss`. ## Source Rewrite Rules @@ -410,7 +410,6 @@ Migration converts the Volta `volta.node` pin to `.node-version`, because Vite+ ### npm -- If a managed package has a nested override, migration writes its version or alias to the `"."` entry and keeps the child overrides. For example, a pin in `overrides.vite.rollup` stays in place when migration sets `overrides.vite["."]`. - Direct aliases are normalized before the matching override is added, so npm does not fail with `EOVERRIDE`. - When a real Vite installation changes to the core alias, stale Vite install and lockfile state is removed before reinstalling. - Opt-in browser-provider layouts get a top-level `vite` edge when nested Vitest packages otherwise cannot resolve it. diff --git a/packages/cli/src/migration/__tests__/migrator.spec.ts b/packages/cli/src/migration/__tests__/migrator.spec.ts index 2f178e4df2..fe6caf57dc 100644 --- a/packages/cli/src/migration/__tests__/migrator.spec.ts +++ b/packages/cli/src/migration/__tests__/migrator.spec.ts @@ -2020,12 +2020,6 @@ describe('ensureVitePlusBootstrap', () => { }); it('keeps a bun WORKSPACE `catalog:` override instead of inlining it against a stale catalog', () => { - // Same ordering as the pnpm < 10.6.2 case: the override is reconciled against - // the still-stale in-memory catalog, so it is transiently inlined to the core - // alias. Unlike pnpm < 10.6.2 (which skipped the workspace rewrite, leaving the - // inline stuck until that bug was fixed), `rewriteBunCatalog` then rewrites the - // catalog AND re-catalogs the now-matching override back to `catalog:`, so the - // final result is correct. This test guards that self-heal. fs.writeFileSync( path.join(tmpDir, 'package.json'), JSON.stringify({ @@ -2049,8 +2043,6 @@ describe('ensureVitePlusBootstrap', () => { overrides: Record; catalog: Record; }; - // The vite override references the catalog (rewritten below), so it stays - // `catalog:` rather than being inlined against the stale pre-rewrite catalog. expect(pkg.overrides.vite).toBe('catalog:'); // The catalog is rewritten off the stale core@0.1.0 alias. expect(pkg.catalog.vite).toContain('@voidzero-dev/vite-plus-core'); @@ -2119,6 +2111,54 @@ describe('ensureVitePlusBootstrap', () => { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.bun)).toBe(false); }); + it.each([ + ['current alias', VITE_PLUS_OVERRIDE_PACKAGES.vite, false], + ['stale alias', 'npm:@voidzero-dev/vite-plus-core@0.1.0', true], + ] as const)('preserves nested Bun overrides with a %s on upgrade', (_, alias, pending) => { + const packageJsonPath = path.join(tmpDir, 'package.json'); + const workspace = makeWorkspaceInfo(tmpDir, PackageManager.bun, '1.4.5'); + fs.writeFileSync( + packageJsonPath, + JSON.stringify({ + name: 'app', + devDependencies: { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, 'vite-plus': 'latest' }, + overrides: { vite: { '.': alias, postcss: '8.5.32' } }, + }), + ); + + for (const changed of [pending, false]) { + expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.bun)).toBe(changed); + expect(ensureVitePlusBootstrap(workspace).changed).toBe(changed); + expect(readJson(packageJsonPath).overrides).toEqual({ + vite: { '.': VITE_PLUS_OVERRIDE_PACKAGES.vite, postcss: '8.5.32' }, + }); + } + }); + + it('keeps the named catalog reference in nested Bun overrides when its alias changes', () => { + const packageJsonPath = path.join(tmpDir, 'package.json'); + const workspace = makeWorkspaceInfo(tmpDir, PackageManager.bun, '1.4.5'); + fs.writeFileSync( + packageJsonPath, + JSON.stringify({ + name: 'app', + workspaces: ['packages/*'], + devDependencies: { vite: 'catalog:', 'vite-plus': 'catalog:' }, + catalog: { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, 'vite-plus': 'latest' }, + catalogs: { build: { vite: 'npm:@voidzero-dev/vite-plus-core@0.1.0' } }, + overrides: { vite: { '.': 'catalog:build', postcss: '8.5.32' } }, + }), + ); + + for (const changed of [true, false]) { + expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.bun, [], '1.4.5')).toBe(changed); + expect(ensureVitePlusBootstrap(workspace).changed).toBe(changed); + const pkg = readJson(packageJsonPath); + expect(pkg.overrides).toEqual({ vite: { '.': 'catalog:build', postcss: '8.5.32' } }); + expect(pkg.catalogs).toEqual({ build: { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite } }); + } + }); + it('keeps `catalog:` specs in a bun project whose `workspaces.packages` is empty (#3375)', () => { // Bun resolves catalogs whenever the root has a `workspaces` field, even an // empty one, so a single-package project may keep its toolchain there. A @@ -6534,34 +6574,41 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { expect(overrides['some-pkg']).toEqual({}); }); - it('does not crash on a nested object value under a managed bun catalog override key', () => { - // Bun monorepo: a nested object value under a MANAGED override key (e.g. - // `vitest`) is a user override scoped under that key, not a version pin. - // The bun catalog rewrite must not pass it to getCatalogDependencySpec - // (which calls `.startsWith` and would crash / clobber it to a string). - fs.writeFileSync( - path.join(tmpDir, 'package.json'), - JSON.stringify({ - name: 'bun-monorepo', - workspaces: ['packages/*'], - devDependencies: { vite: '^7.0.0' }, - overrides: { - vitest: { '@vitest/runner': '4.0.0' }, - }, - }), - ); + it.each(['standalone', 'workspace'])( + 'preserves nested Bun overrides during a fresh %s migration and the following upgrade', + (layout) => { + const packageJsonPath = path.join(tmpDir, 'package.json'); + const workspace = makeWorkspaceInfo(tmpDir, PackageManager.bun, '1.4.5'); + workspace.isMonorepo = layout === 'workspace'; + fs.writeFileSync( + packageJsonPath, + JSON.stringify({ + name: 'app', + workspaces: workspace.isMonorepo ? ['packages/*'] : undefined, + devDependencies: { vite: '^7.0.0' }, + overrides: { vite: { postcss: '8.5.32' }, vitest: { '@vitest/runner': '4.0.0' } }, + }), + ); - expect(() => - rewriteMonorepo(makeWorkspaceInfo(tmpDir, PackageManager.bun), true), - ).not.toThrow(); + if (workspace.isMonorepo) { + rewriteMonorepo(workspace, true, true); + } else { + rewriteStandaloneProject(tmpDir, workspace, true, true); + } - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - overrides?: Record; - }; - const overrides = pkg.overrides ?? {}; - // The nested override object is left intact, not clobbered to a string. - expect(overrides.vitest).toEqual({ '@vitest/runner': '4.0.0' }); - }); + const expected = { + vite: { + '.': workspace.isMonorepo ? 'catalog:' : VITE_PLUS_OVERRIDE_PACKAGES.vite, + postcss: '8.5.32', + }, + vitest: { '@vitest/runner': '4.0.0' }, + }; + expect(readJson(packageJsonPath).overrides).toEqual(expected); + expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.bun, [], '1.4.5')).toBe(false); + expect(ensureVitePlusBootstrap(workspace).changed).toBe(false); + expect(readJson(packageJsonPath).overrides).toEqual(expected); + }, + ); it('drops stale @vitest/browser* overrides from pnpm-workspace.yaml', () => { // The migration moves provider packages out of project manifests and adds diff --git a/packages/cli/src/migration/migrator/catalog.ts b/packages/cli/src/migration/migrator/catalog.ts index c1a8a7d725..1ea7394ef1 100644 --- a/packages/cli/src/migration/migrator/catalog.ts +++ b/packages/cli/src/migration/migrator/catalog.ts @@ -29,7 +29,7 @@ import { type NpmWorkspaces } from '../../utils/workspace.ts'; import { editYamlFile, readYamlFile, scalarString, type YamlDocument } from '../../utils/yaml.ts'; import { dropRemovePackageOverrideKeys, - ensureNpmOverrideEntries, + ensurePackageJsonOverrides, ensurePnpmExoticSubdepsSetting, hasDirectVitePlusInstallEntry, isAlignableVitestEcosystemPackage, @@ -1104,11 +1104,27 @@ export function rewriteBunCatalog( } const managed = managedOverridePackages(usesVitest, usesWebdriverioProvider); + function rewriteCatalog( + target: Record, + addMissing: boolean, + otherDefaultCatalog?: Record, + ): void { + rewriteCatalogObject( + target, + addMissing, + usesVitest, + vitestEcosystemPackages, + catalogAdditions, + otherDefaultCatalog, + ); + pruneLegacyWrapperAliases(target); + } + editJsonFile<{ workspaces?: NpmWorkspaces; catalog?: Record; catalogs?: Record>; - overrides?: Record; + overrides?: Record; }>(packageJsonPath, (pkg) => { // Bun supports catalogs in both workspaces.catalog and top-level catalog; // prefer the location the user already chose to avoid moving their config. @@ -1125,21 +1141,6 @@ export function rewriteBunCatalog( preferredName || mergeDefaults ? activeCatalogs.catalogs?.[preferredName || 'default'] : undefined; - function rewriteCatalog( - target: Record, - addMissing: boolean, - otherDefaultCatalog?: Record, - ): void { - rewriteCatalogObject( - target, - addMissing, - usesVitest, - vitestEcosystemPackages, - catalogAdditions, - otherDefaultCatalog, - ); - pruneLegacyWrapperAliases(target); - } if (!namedTarget || activeCatalogs.catalog) { const catalog = { ...activeCatalogs.catalog }; rewriteCatalog(catalog, !namedTarget); @@ -1157,29 +1158,20 @@ export function rewriteBunCatalog( } } - // bun overrides support catalog: references - const overrides: Record = { ...pkg.overrides }; - pruneLegacyWrapperAliases(overrides); - // Common case (no direct vitest): strip a lingering managed `vitest` - // override (string-valued only — a nested user override is left intact; - // removeManagedVitestEntry also no-ops when vitest is not a managed key). - if (!usesVitest && typeof overrides.vitest === 'string') { - removeManagedVitestEntry(overrides); - } - for (const [key, value] of Object.entries(managed)) { - const current = overrides[key] as unknown; - // A nested object value is a user override scoped under this managed key, - // not a version pin — leave it intact (getCatalogDependencySpec expects a - // string and would otherwise clobber it / throw on `.startsWith`). - if (current !== undefined && typeof current !== 'string') { - continue; + pruneLegacyWrapperAliases(pkg.overrides); + // Resolve against the updated catalogs so a stale named entry keeps its + // reference. A missing entry uses the catalog that now owns the package. + const resolveCatalog = readBunCatalogDependencyResolver(pkg, packageManagerVersion); + pkg.overrides = ensurePackageJsonOverrides(pkg.overrides, managed, (name, current, target) => { + if (name === '@vitest/browser') { + return target; } - overrides[key] = - key === '@vitest/browser' - ? value - : getCatalogDependencySpec(current, value, true, { preferredCatalogSpec }); - } - pkg.overrides = overrides; + const catalog = + current?.startsWith('catalog:') && resolveCatalog(current, name) === target + ? current + : undefined; + return getCatalogDependencySpec(catalog, target, true, { preferredCatalogSpec }); + }).overrides; return pkg; }); @@ -1254,16 +1246,11 @@ export function rewriteRootWorkspacePackageJson( ...managed, }; } else if (packageManager === PackageManager.npm) { - pkg.overrides = ensureNpmOverrideEntries(pkg.overrides, managed).overrides; + pkg.overrides = ensurePackageJsonOverrides(pkg.overrides, managed).overrides; } else if (packageManager === PackageManager.bun) { - // bun overrides are handled in rewriteBunCatalog() with catalog: references - // when the workspace supports a catalog. Otherwise they stay concrete. - // The browser override has no catalog entry and was pruned above with - // stale bundled-package pins. Restore its current concrete version. + // Catalog workspaces write their overrides after root cleanup. if (!supportCatalog) { - pkg.overrides = { ...pkg.overrides, ...managed }; - } else if (managed['@vitest/browser']) { - pkg.overrides = { ...pkg.overrides, '@vitest/browser': managed['@vitest/browser'] }; + pkg.overrides = ensurePackageJsonOverrides(pkg.overrides, managed).overrides; } // Bun walks transitive peer-deps before resolving overrides; vitest 4.1.9 // declares peer `vite ^6 || ^7 || ^8` and aborts unless `vite` is a direct diff --git a/packages/cli/src/migration/migrator/orchestrators.ts b/packages/cli/src/migration/migrator/orchestrators.ts index d814d8600a..ffeefc7926 100644 --- a/packages/cli/src/migration/migrator/orchestrators.ts +++ b/packages/cli/src/migration/migrator/orchestrators.ts @@ -18,7 +18,7 @@ import { createCatalogDependencyResolver, dropDeadOxlintPluginsDependency, dropRemovePackageOverrideKeys, - ensureNpmOverrideEntries, + ensurePackageJsonOverrides, ensurePnpmWorkspaceExoticSubdepsSetting, ensurePnpmWorkspacePackages, findYarnWorkspaceHoisting, @@ -194,22 +194,19 @@ export function rewriteStandaloneProject( ...pkg.resolutions, ...managed, }; - } else if (packageManager === PackageManager.npm) { - pkg.overrides = ensureNpmOverrideEntries(pkg.overrides, managed).overrides; - } else if (packageManager === PackageManager.bun) { - pkg.overrides = { - ...pkg.overrides, - ...managed, - }; - // Bun walks transitive peer-deps before resolving overrides; vitest - // 4.1.9 declares peer `vite ^6 || ^7 || ^8` and aborts with - // "vite@... failed to resolve" if `vite` isn't a direct dep somewhere - // in the tree, even when the override would redirect it. Mirror the - // override as a devDep so bun's resolver sees `vite` immediately. A - // standalone bun project has no catalog (supportCatalog=false), so the - // shared helper resolves this to the concrete core alias. Verified on - // bun 1.3.11. See https://github.com/oven-sh/bun/issues/8406. - setDirectViteEdge(pkg, supportCatalog, catalogDependencyResolver); + } else if (packageManager === PackageManager.npm || packageManager === PackageManager.bun) { + pkg.overrides = ensurePackageJsonOverrides(pkg.overrides, managed).overrides; + if (packageManager === PackageManager.bun) { + // Bun walks transitive peer-deps before resolving overrides; vitest + // 4.1.9 declares peer `vite ^6 || ^7 || ^8` and aborts with + // "vite@... failed to resolve" if `vite` isn't a direct dep somewhere + // in the tree, even when the override would redirect it. Mirror the + // override as a devDep so bun's resolver sees `vite` immediately. A + // standalone bun project has no catalog (supportCatalog=false), so the + // shared helper resolves this to the concrete core alias. Verified on + // bun 1.3.11. See https://github.com/oven-sh/bun/issues/8406. + setDirectViteEdge(pkg, supportCatalog, catalogDependencyResolver); + } } else if (packageManager === PackageManager.pnpm) { if (usePnpmWorkspaceYaml) { shouldAddPnpmWorkspaceVitePlusOverride = isForceOverrideMode(); @@ -460,15 +457,6 @@ export function rewriteMonorepo( supportCatalog, yarnSupportsPreapprovedPackages(workspaceInfo.downloadPackageManager.version), ); - } else if (workspaceInfo.packageManager === PackageManager.bun && supportCatalog) { - rewriteBunCatalog( - workspaceInfo.rootDir, - workspaceUsesVitest, - vitestEcosystemPackages, - usesWebdriverio, - workspaceInfo.downloadPackageManager.version, - browserCatalogAdditions, - ); } rewriteRootWorkspacePackageJson( workspaceInfo.rootDir, @@ -502,6 +490,15 @@ export function rewriteMonorepo( [VITE_PLUS_NAME]: VITE_PLUS_VERSION, }); } + } else if (workspaceInfo.packageManager === PackageManager.bun && supportCatalog) { + rewriteBunCatalog( + workspaceInfo.rootDir, + workspaceUsesVitest, + vitestEcosystemPackages, + usesWebdriverio, + workspaceInfo.downloadPackageManager.version, + browserCatalogAdditions, + ); } // (mergeViteConfigFiles below will sanitize the merged lint config // against this workspace's full package set.) diff --git a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts index 4af4cde8fb..1cd755f0a0 100644 --- a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts +++ b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts @@ -2,10 +2,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { PackageManager, type WorkspaceInfo, type WorkspacePackage } from '../../types/index.ts'; -import { - readBunCatalogDependencyResolver, - type CatalogDependencyResolver, -} from '../../utils/catalog.ts'; +import type { CatalogDependencyResolver } from '../../utils/catalog.ts'; import { VITEST_VERSION, VITE_PLUS_NAME, @@ -23,7 +20,7 @@ import { collectProviderSourceModes, collectVitestEcosystemInstallDependencyNames, createCatalogDependencyResolver, - ensureNpmOverrideEntries, + ensurePackageJsonOverrides, ensurePnpmWorkspacePackages, findYarnWorkspaceHoisting, getAlignedVitestEcosystemDependencySpec, @@ -744,8 +741,10 @@ export function detectVitePlusBootstrapPending( if (packageManager === PackageManager.npm) { return ( vitePlusDependencyNeedsConcreteVersion(pkg) || - ensureNpmOverrideEntries(pkg.overrides, managedOverridePackages(usesVitest, usesWebdriverio)) - .changed || + ensurePackageJsonOverrides( + pkg.overrides, + managedOverridePackages(usesVitest, usesWebdriverio), + ).changed || npmVitePlusManagedDependenciesPending(pkg, usesVitest) ); } @@ -754,20 +753,19 @@ export function detectVitePlusBootstrapPending( // `catalog:` references, so the catalog resolver must NOT be consulted — // otherwise a dangling `catalog:` override resolves through the dead catalog // field and is mistaken for satisfied, masking the pending rewrite. - const bunCatalogResolver = supportCatalog - ? readBunCatalogDependencyResolver(pkg, resolvedPackageManagerVersion) - : undefined; + const bunCatalogResolver = supportCatalog ? catalogDependencyResolver : undefined; // A `catalog:` vite-plus spec looks current, so judge its catalog value too. return ( (supportCatalog && workspaceCatalogVitePlusDependencyPending(projectPath, packages, bunCatalogResolver)) || - !overridesSatisfyVitePlus( + ensurePackageJsonOverrides( pkg.overrides, - usesVitest, - bunCatalogResolver, - 'bare', - usesWebdriverio, - ) + managedOverridePackages(usesVitest, usesWebdriverio), + (name, current, target) => + current && overrideSpecSatisfiesVitePlus(name, current, bunCatalogResolver) + ? current + : target, + ).changed ); } if (packageManager === PackageManager.pnpm) { @@ -911,14 +909,14 @@ function readTextFileIfExists(filePath: string): string | undefined { return fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf-8') : undefined; } -function ensureOverrideEntries( - overrides: Record | undefined, +function ensureOverrideEntries( + overrides: Record | undefined, usesVitest: boolean, catalogDependencyResolver?: CatalogDependencyResolver, keyStyle: ManagedOverrideKeyStyle = 'bare', usesWebdriverioProvider = false, -): { overrides: Record; changed: boolean } { - const next: Record = { ...overrides }; +): { overrides: Record; changed: boolean } { + const next = { ...overrides }; let changed = false; // Common case: drop a lingering managed `vitest` override. if (!usesVitest && removeManagedVitestEntry(next, keyStyle)) { @@ -1106,8 +1104,11 @@ export function ensureVitePlusBootstrap( pkg.resolutions = ensured.overrides; packageJsonChanged = true; } - } else if (workspaceInfo.packageManager === PackageManager.npm) { - const ensured = ensureNpmOverrideEntries( + } else if ( + workspaceInfo.packageManager === PackageManager.npm || + (workspaceInfo.packageManager === PackageManager.bun && !isBunWorkspace) + ) { + const ensured = ensurePackageJsonOverrides( pkg.overrides, managedOverridePackages(usesVitest, usesWebdriverio), ); @@ -1115,24 +1116,6 @@ export function ensureVitePlusBootstrap( pkg.overrides = ensured.overrides; packageJsonChanged = true; } - } else if (workspaceInfo.packageManager === PackageManager.bun) { - // Standalone bun (`supportCatalog === false`) has no catalog support, so a - // `catalog:` override must be rewritten to the concrete core alias rather - // than left dangling — the catalog resolver is only consulted for a real - // bun workspace where `rewriteBunCatalog` maintains the catalog field. - const ensured = ensureOverrideEntries( - pkg.overrides, - usesVitest, - supportCatalog - ? readBunCatalogDependencyResolver(pkg, workspaceInfo.downloadPackageManager.version) - : undefined, - 'bare', - usesWebdriverio, - ); - if (ensured.changed) { - pkg.overrides = ensured.overrides; - packageJsonChanged = true; - } } else if (workspaceInfo.packageManager === PackageManager.pnpm && !usePnpmWorkspaceYaml) { pkg.pnpm ??= {}; // Below pnpm 10.6.2 the settings stay here, but catalogs (>= 9.5.0) still @@ -1301,7 +1284,7 @@ export function ensureVitePlusBootstrap( } else if (isBunWorkspace) { // Only a bun WORKSPACE writes a catalog (matching the fresh path, where // rewriteBunCatalog runs only on monorepo roots). A standalone bun project - // keeps the concrete overrides set by `ensureOverrideEntries` above. + // keeps the concrete overrides set by `ensurePackageJsonOverrides` above. const before = fs.readFileSync(packageJsonPath, 'utf-8'); rewriteBunCatalog( projectPath, diff --git a/packages/cli/src/migration/migrator/vitest-ecosystem.ts b/packages/cli/src/migration/migrator/vitest-ecosystem.ts index f809c07fe0..981330dcc9 100644 --- a/packages/cli/src/migration/migrator/vitest-ecosystem.ts +++ b/packages/cli/src/migration/migrator/vitest-ecosystem.ts @@ -356,11 +356,12 @@ export function managedOverridePackages( : managed; } -// In npm's object form, "." overrides the package itself. All other keys +// In npm and Bun's object form, "." overrides the package itself. All other keys // constrain its children and must survive a change to the package's own pin. -export function ensureNpmOverrideEntries( +export function ensurePackageJsonOverrides( overrides: Record | undefined, managed: Record, + selectSpec?: (name: string, current: string | undefined, target: string) => string, ): { overrides: Record; changed: boolean } { const next = { ...overrides }; let changed = false; @@ -380,10 +381,14 @@ export function ensureNpmOverrideEntries( } } - for (const [name, spec] of Object.entries(managed)) { - const current = next[name]; - if ((isPlainRecord(current) ? current['.'] : current) !== spec) { - next[name] = isPlainRecord(current) ? { ...current, '.': spec } : spec; + for (const [name, target] of Object.entries(managed)) { + const entry = next[name]; + const nested = isPlainRecord(entry); + const current = nested ? entry['.'] : entry; + const spec = + selectSpec?.(name, typeof current === 'string' ? current : undefined, target) ?? target; + if (current !== spec) { + next[name] = nested ? { ...entry, '.': spec } : spec; changed = true; } } From a860cb003d798dbe4768612d27eb61ec288ff03d Mon Sep 17 00:00:00 2001 From: MK Date: Sun, 22 Nov 2026 13:55:19 +0800 Subject: [PATCH 4/4] fix(migrate): apply Bun child overrides to the Vite core alias --- .../check-postcss.mjs | 9 +++ .../package.json | 8 +- .../snapshots.toml | 1 + .../migration_standalone_bun_install.md | 15 +++- .../migration_upgrade_bun_catalog.md | 3 + docs/guide/migrate-rules.md | 1 + .../src/migration/__tests__/migrator.spec.ts | 78 +++++++++++++++++-- .../cli/src/migration/migrator/catalog.ts | 38 +++++---- .../src/migration/migrator/orchestrators.ts | 29 ++++--- .../migration/migrator/vite-plus-bootstrap.ts | 15 ++-- .../migration/migrator/vitest-ecosystem.ts | 44 ++++++++++- 11 files changed, 199 insertions(+), 42 deletions(-) create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_standalone_bun_install/check-postcss.mjs diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_standalone_bun_install/check-postcss.mjs b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_standalone_bun_install/check-postcss.mjs new file mode 100644 index 0000000000..a74b7921b0 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_standalone_bun_install/check-postcss.mjs @@ -0,0 +1,9 @@ +import assert from 'node:assert/strict'; +import { createRequire } from 'node:module'; + +const project = createRequire(import.meta.url); +const vite = createRequire(project.resolve('vite/package.json')); +assert.equal(vite('./package.json').name, '@voidzero-dev/vite-plus-core'); +assert.equal(vite('postcss/package.json').version, '8.5.32'); +assert.equal(project('postcss/package.json').version, '8.5.33'); +console.log('The installed Vite alias uses its own PostCSS pin.'); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_standalone_bun_install/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_standalone_bun_install/package.json index 11d8286b7d..38741a564b 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_standalone_bun_install/package.json +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_standalone_bun_install/package.json @@ -2,16 +2,20 @@ "name": "migration-standalone-bun-install", "private": true, "devDependencies": { + "postcss": "8.5.33", "vite": "npm:@voidzero-dev/vite-plus-core@0.1.24", "vite-plus": "0.1.24" }, "overrides": { - "vite": "npm:@voidzero-dev/vite-plus-core@0.1.24" + "vite": { + ".": "npm:@voidzero-dev/vite-plus-core@0.1.24", + "postcss": "8.5.32" + } }, "devEngines": { "packageManager": { "name": "bun", - "version": "1.3.11", + "version": "1.4.5", "onFail": "download" } } diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_standalone_bun_install/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_standalone_bun_install/snapshots.toml index d0b98dacd4..318edfa924 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_standalone_bun_install/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_standalone_bun_install/snapshots.toml @@ -6,5 +6,6 @@ unset-env = ["VP_SKIP_INSTALL", "CI"] local-registry = true steps = [ { argv = ["vp", "migrate", "--no-interactive", "--no-hooks"], comment = "standalone (non-workspace) bun upgrade must keep concrete specs so `bun install` resolves instead of failing with `vite@catalog: failed to resolve`", continue-on-failure = true }, + ["node", "check-postcss.mjs"], { argv = ["vpt", "print-file", "package.json"], comment = "vite/vite-plus stay concrete (vite via the @voidzero-dev/vite-plus-core alias); NO top-level catalog field is written", continue-on-failure = true }, ] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_standalone_bun_install/snapshots/migration_standalone_bun_install.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_standalone_bun_install/snapshots/migration_standalone_bun_install.md index 77e56db9f1..0a52f14341 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_standalone_bun_install/snapshots/migration_standalone_bun_install.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_standalone_bun_install/snapshots/migration_standalone_bun_install.md @@ -18,6 +18,12 @@ VITE+ - The Unified Toolchain for the Web • Package manager settings configured ``` +## `node check-postcss.mjs` + +``` +The installed Vite alias uses its own PostCSS pin. +``` + ## `vpt print-file package.json` vite/vite-plus stay concrete (vite via the @voidzero-dev/vite-plus-core alias); NO top-level catalog field is written @@ -27,11 +33,18 @@ vite/vite-plus stay concrete (vite via the @voidzero-dev/vite-plus-core alias); "name": "migration-standalone-bun-install", "private": true, "devDependencies": { + "postcss": "8.5.33", "vite": "npm:@voidzero-dev/vite-plus-core@", "vite-plus": "" }, "overrides": { - "vite": "npm:@voidzero-dev/vite-plus-core@" + "@voidzero-dev/vite-plus-core": { + "postcss": "8.5.32" + }, + "vite": { + ".": "npm:@voidzero-dev/vite-plus-core@", + "postcss": "8.5.32" + } }, "devEngines": { "packageManager": { diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_bun_catalog/snapshots/migration_upgrade_bun_catalog.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_bun_catalog/snapshots/migration_upgrade_bun_catalog.md index ae30d900aa..fec09f4031 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_bun_catalog/snapshots/migration_upgrade_bun_catalog.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_upgrade_bun_catalog/snapshots/migration_upgrade_bun_catalog.md @@ -43,6 +43,9 @@ the direct Vite dependency and its override use the catalog, and the PostCSS pin "vite": { ".": "catalog:", "postcss": "8.5.32" + }, + "@voidzero-dev/vite-plus-core": { + "postcss": "8.5.32" } }, "devEngines": { diff --git a/docs/guide/migrate-rules.md b/docs/guide/migrate-rules.md index a34df36d1c..74a2d0bcd8 100644 --- a/docs/guide/migrate-rules.md +++ b/docs/guide/migrate-rules.md @@ -426,6 +426,7 @@ Migration converts the Volta `volta.node` pin to `.node-version`, because Vite+ - Bun before 1.2.21 reads only catalogs under `workspaces`. On those versions, migration uses catalogs only when the project already has one under `workspaces`, and keeps concrete specs otherwise. - When an existing named catalog already owns `vite-plus`, `vite`, or `vitest`, migration adds missing toolchain entries to that catalog instead of creating a default catalog beside it. - The core alias is mirrored as a direct `vite` dependency so Bun sees the peer provider before applying overrides. +- Bun 1.4 and later match child overrides by the installed package name. When migration aliases `vite` to `@voidzero-dev/vite-plus-core`, it also copies child pins such as `overrides.vite.postcss` to the core package's overrides. Existing overrides for the core package take precedence. To change the pin for the aliased Vite after migration, edit the core package's override. ## After the Migration diff --git a/packages/cli/src/migration/__tests__/migrator.spec.ts b/packages/cli/src/migration/__tests__/migrator.spec.ts index fe6caf57dc..e8cba76a51 100644 --- a/packages/cli/src/migration/__tests__/migrator.spec.ts +++ b/packages/cli/src/migration/__tests__/migrator.spec.ts @@ -49,6 +49,7 @@ const { readRulesYaml, detectVitePlusBootstrapPending, ensureVitePlusBootstrap, + ensureBunOverrides, finalizeCoreMigrationForExistingVitePlus, detectNodeVersionManagerFile, migrateNodeVersionManagerFile, @@ -2112,9 +2113,9 @@ describe('ensureVitePlusBootstrap', () => { }); it.each([ - ['current alias', VITE_PLUS_OVERRIDE_PACKAGES.vite, false], - ['stale alias', 'npm:@voidzero-dev/vite-plus-core@0.1.0', true], - ] as const)('preserves nested Bun overrides with a %s on upgrade', (_, alias, pending) => { + ['current alias', VITE_PLUS_OVERRIDE_PACKAGES.vite], + ['stale alias', 'npm:@voidzero-dev/vite-plus-core@0.1.0'], + ])('preserves nested Bun overrides with a %s on upgrade', (_, alias) => { const packageJsonPath = path.join(tmpDir, 'package.json'); const workspace = makeWorkspaceInfo(tmpDir, PackageManager.bun, '1.4.5'); fs.writeFileSync( @@ -2126,15 +2127,78 @@ describe('ensureVitePlusBootstrap', () => { }), ); - for (const changed of [pending, false]) { + for (const changed of [true, false]) { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.bun)).toBe(changed); expect(ensureVitePlusBootstrap(workspace).changed).toBe(changed); expect(readJson(packageJsonPath).overrides).toEqual({ vite: { '.': VITE_PLUS_OVERRIDE_PACKAGES.vite, postcss: '8.5.32' }, + '@voidzero-dev/vite-plus-core': { postcss: '8.5.32' }, }); } }); + it.each([ + { + source: 'a scalar core override and a scoped child selector', + version: '1.4.5', + overrides: { + '@voidzero-dev/vite-plus-core': '8.3.8000', + '@voidzero-dev/vite-plus-core>picomatch': '~4.0.1', + }, + expected: { '.': '8.3.8000', postcss: '8.5.32' }, + }, + { + source: 'existing core child overrides', + version: '1.4.5', + overrides: { '@voidzero-dev/vite-plus-core': { postcss: '8.5.31', rolldown: '1.0.0' } }, + expected: { postcss: '8.5.31', rolldown: '1.0.0', picomatch: '^4.0.0' }, + }, + { + source: 'a scalar core override on Bun 1.3', + version: '1.3.14', + overrides: { '@voidzero-dev/vite-plus-core': '8.3.8000' }, + expected: '8.3.8000', + }, + ])( + 'preserves $source when migrating nested Bun overrides', + ({ version, overrides, expected }) => { + const packageJsonPath = path.join(tmpDir, 'package.json'); + const workspace = makeWorkspaceInfo(tmpDir, PackageManager.bun, version); + fs.writeFileSync( + packageJsonPath, + JSON.stringify({ + name: 'app', + devDependencies: { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, 'vite-plus': 'latest' }, + overrides: { + vite: { postcss: '8.5.32', picomatch: '^4.0.0' }, + ...overrides, + }, + }), + ); + + for (const changed of [true, false]) { + expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.bun, [], version)).toBe( + changed, + ); + expect(ensureVitePlusBootstrap(workspace).changed).toBe(changed); + expect(readJson(packageJsonPath).overrides).toEqual({ + ...overrides, + vite: { '.': VITE_PLUS_OVERRIDE_PACKAGES.vite, postcss: '8.5.32', picomatch: '^4.0.0' }, + '@voidzero-dev/vite-plus-core': expected, + }); + } + }, + ); + + it('keeps nested Bun overrides under Vite when its target is a local tarball', () => { + const vite = 'file:../vite.tgz'; + const overrides = { + vite: { '.': vite, postcss: '8.5.32' }, + '@voidzero-dev/vite-plus-core': '8.3.8000', + }; + expect(ensureBunOverrides(overrides, { vite }, '1.4.5')).toEqual({ overrides, changed: false }); + }); + it('keeps the named catalog reference in nested Bun overrides when its alias changes', () => { const packageJsonPath = path.join(tmpDir, 'package.json'); const workspace = makeWorkspaceInfo(tmpDir, PackageManager.bun, '1.4.5'); @@ -2154,7 +2218,10 @@ describe('ensureVitePlusBootstrap', () => { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.bun, [], '1.4.5')).toBe(changed); expect(ensureVitePlusBootstrap(workspace).changed).toBe(changed); const pkg = readJson(packageJsonPath); - expect(pkg.overrides).toEqual({ vite: { '.': 'catalog:build', postcss: '8.5.32' } }); + expect(pkg.overrides).toEqual({ + vite: { '.': 'catalog:build', postcss: '8.5.32' }, + '@voidzero-dev/vite-plus-core': { postcss: '8.5.32' }, + }); expect(pkg.catalogs).toEqual({ build: { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite } }); } }); @@ -6601,6 +6668,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { '.': workspace.isMonorepo ? 'catalog:' : VITE_PLUS_OVERRIDE_PACKAGES.vite, postcss: '8.5.32', }, + '@voidzero-dev/vite-plus-core': { postcss: '8.5.32' }, vitest: { '@vitest/runner': '4.0.0' }, }; expect(readJson(packageJsonPath).overrides).toEqual(expected); diff --git a/packages/cli/src/migration/migrator/catalog.ts b/packages/cli/src/migration/migrator/catalog.ts index 1ea7394ef1..2bc231f955 100644 --- a/packages/cli/src/migration/migrator/catalog.ts +++ b/packages/cli/src/migration/migrator/catalog.ts @@ -29,6 +29,7 @@ import { type NpmWorkspaces } from '../../utils/workspace.ts'; import { editYamlFile, readYamlFile, scalarString, type YamlDocument } from '../../utils/yaml.ts'; import { dropRemovePackageOverrideKeys, + ensureBunOverrides, ensurePackageJsonOverrides, ensurePnpmExoticSubdepsSetting, hasDirectVitePlusInstallEntry, @@ -1162,16 +1163,21 @@ export function rewriteBunCatalog( // Resolve against the updated catalogs so a stale named entry keeps its // reference. A missing entry uses the catalog that now owns the package. const resolveCatalog = readBunCatalogDependencyResolver(pkg, packageManagerVersion); - pkg.overrides = ensurePackageJsonOverrides(pkg.overrides, managed, (name, current, target) => { - if (name === '@vitest/browser') { - return target; - } - const catalog = - current?.startsWith('catalog:') && resolveCatalog(current, name) === target - ? current - : undefined; - return getCatalogDependencySpec(catalog, target, true, { preferredCatalogSpec }); - }).overrides; + pkg.overrides = ensureBunOverrides( + pkg.overrides, + managed, + packageManagerVersion, + (name, current, target) => { + if (name === '@vitest/browser') { + return target; + } + const catalog = + current?.startsWith('catalog:') && resolveCatalog(current, name) === target + ? current + : undefined; + return getCatalogDependencySpec(catalog, target, true, { preferredCatalogSpec }); + }, + ).overrides; return pkg; }); @@ -1191,7 +1197,7 @@ export function rewriteRootWorkspacePackageJson( // just the root's own `package.json`. packages?: WorkspacePackage[], pnpmMajorVersion?: number, - pnpmVersion?: string, + packageManagerVersion?: string, shouldAllowBrowserBuilds = false, // Workspace-wide direct-vitest signal: the root resolution/override sinks are // shared by every package, so `vitest` stays managed here iff ANY package uses @@ -1250,7 +1256,11 @@ export function rewriteRootWorkspacePackageJson( } else if (packageManager === PackageManager.bun) { // Catalog workspaces write their overrides after root cleanup. if (!supportCatalog) { - pkg.overrides = ensurePackageJsonOverrides(pkg.overrides, managed).overrides; + pkg.overrides = ensureBunOverrides( + pkg.overrides, + managed, + packageManagerVersion ?? 'latest', + ).overrides; } // Bun walks transitive peer-deps before resolving overrides; vitest 4.1.9 // declares peer `vite ^6 || ^7 || ^8` and aborts unless `vite` is a direct @@ -1259,7 +1269,7 @@ export function rewriteRootWorkspacePackageJson( // See https://github.com/oven-sh/bun/issues/8406. setDirectViteEdge(pkg, supportCatalog, catalogDependencyResolver); } else if (packageManager === PackageManager.pnpm) { - const usePnpmWorkspaceSettings = pnpmSupportsWorkspaceSettings(pnpmVersion ?? ''); + const usePnpmWorkspaceSettings = pnpmSupportsWorkspaceSettings(packageManagerVersion ?? ''); if (!usePnpmWorkspaceSettings) { // Strip selector-shaped overrides (e.g. `parent>@vitest/browser-playwright`) // whose target is a removed package, before re-merging the user's @@ -1275,7 +1285,7 @@ export function rewriteRootWorkspacePackageJson( overrides: mergeManagedPnpmOverrides(pkg.pnpm?.overrides, managed), peerDependencyRules: mergeManagedPnpmPeerDependencyRules( pkg.pnpm?.peerDependencyRules, - pnpmPeerDependencyRuleKeys(workspaceUsesVitest, pnpmVersion), + pnpmPeerDependencyRuleKeys(workspaceUsesVitest, packageManagerVersion), ), }; } else { diff --git a/packages/cli/src/migration/migrator/orchestrators.ts b/packages/cli/src/migration/migrator/orchestrators.ts index ffeefc7926..81c6383eae 100644 --- a/packages/cli/src/migration/migrator/orchestrators.ts +++ b/packages/cli/src/migration/migrator/orchestrators.ts @@ -18,6 +18,7 @@ import { createCatalogDependencyResolver, dropDeadOxlintPluginsDependency, dropRemovePackageOverrideKeys, + ensureBunOverrides, ensurePackageJsonOverrides, ensurePnpmWorkspaceExoticSubdepsSetting, ensurePnpmWorkspacePackages, @@ -194,19 +195,23 @@ export function rewriteStandaloneProject( ...pkg.resolutions, ...managed, }; - } else if (packageManager === PackageManager.npm || packageManager === PackageManager.bun) { + } else if (packageManager === PackageManager.npm) { pkg.overrides = ensurePackageJsonOverrides(pkg.overrides, managed).overrides; - if (packageManager === PackageManager.bun) { - // Bun walks transitive peer-deps before resolving overrides; vitest - // 4.1.9 declares peer `vite ^6 || ^7 || ^8` and aborts with - // "vite@... failed to resolve" if `vite` isn't a direct dep somewhere - // in the tree, even when the override would redirect it. Mirror the - // override as a devDep so bun's resolver sees `vite` immediately. A - // standalone bun project has no catalog (supportCatalog=false), so the - // shared helper resolves this to the concrete core alias. Verified on - // bun 1.3.11. See https://github.com/oven-sh/bun/issues/8406. - setDirectViteEdge(pkg, supportCatalog, catalogDependencyResolver); - } + } else if (packageManager === PackageManager.bun) { + pkg.overrides = ensureBunOverrides( + pkg.overrides, + managed, + workspaceInfo.downloadPackageManager.version, + ).overrides; + // Bun walks transitive peer-deps before resolving overrides; vitest + // 4.1.9 declares peer `vite ^6 || ^7 || ^8` and aborts with + // "vite@... failed to resolve" if `vite` isn't a direct dep somewhere + // in the tree, even when the override would redirect it. Mirror the + // override as a devDep so bun's resolver sees `vite` immediately. A + // standalone bun project has no catalog (supportCatalog=false), so the + // shared helper resolves this to the concrete core alias. Verified on + // bun 1.3.11. See https://github.com/oven-sh/bun/issues/8406. + setDirectViteEdge(pkg, supportCatalog, catalogDependencyResolver); } else if (packageManager === PackageManager.pnpm) { if (usePnpmWorkspaceYaml) { shouldAddPnpmWorkspaceVitePlusOverride = isForceOverrideMode(); diff --git a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts index 1cd755f0a0..4e9605f3a3 100644 --- a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts +++ b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts @@ -20,6 +20,7 @@ import { collectProviderSourceModes, collectVitestEcosystemInstallDependencyNames, createCatalogDependencyResolver, + ensureBunOverrides, ensurePackageJsonOverrides, ensurePnpmWorkspacePackages, findYarnWorkspaceHoisting, @@ -758,9 +759,10 @@ export function detectVitePlusBootstrapPending( return ( (supportCatalog && workspaceCatalogVitePlusDependencyPending(projectPath, packages, bunCatalogResolver)) || - ensurePackageJsonOverrides( + ensureBunOverrides( pkg.overrides, managedOverridePackages(usesVitest, usesWebdriverio), + resolvedPackageManagerVersion, (name, current, target) => current && overrideSpecSatisfiesVitePlus(name, current, bunCatalogResolver) ? current @@ -1108,10 +1110,11 @@ export function ensureVitePlusBootstrap( workspaceInfo.packageManager === PackageManager.npm || (workspaceInfo.packageManager === PackageManager.bun && !isBunWorkspace) ) { - const ensured = ensurePackageJsonOverrides( - pkg.overrides, - managedOverridePackages(usesVitest, usesWebdriverio), - ); + const managed = managedOverridePackages(usesVitest, usesWebdriverio); + const ensured = + workspaceInfo.packageManager === PackageManager.bun + ? ensureBunOverrides(pkg.overrides, managed, workspaceInfo.downloadPackageManager.version) + : ensurePackageJsonOverrides(pkg.overrides, managed); if (ensured.changed) { pkg.overrides = ensured.overrides; packageJsonChanged = true; @@ -1284,7 +1287,7 @@ export function ensureVitePlusBootstrap( } else if (isBunWorkspace) { // Only a bun WORKSPACE writes a catalog (matching the fresh path, where // rewriteBunCatalog runs only on monorepo roots). A standalone bun project - // keeps the concrete overrides set by `ensurePackageJsonOverrides` above. + // keeps the concrete overrides set by `ensureBunOverrides` above. const before = fs.readFileSync(packageJsonPath, 'utf-8'); rewriteBunCatalog( projectPath, diff --git a/packages/cli/src/migration/migrator/vitest-ecosystem.ts b/packages/cli/src/migration/migrator/vitest-ecosystem.ts index 981330dcc9..e76f588090 100644 --- a/packages/cli/src/migration/migrator/vitest-ecosystem.ts +++ b/packages/cli/src/migration/migrator/vitest-ecosystem.ts @@ -4,11 +4,13 @@ import path from 'node:path'; import { YAMLMap } from 'yaml'; import { PackageManager, type WorkspacePackage } from '../../types/index.ts'; -import type { CatalogDependencyResolver } from '../../utils/catalog.ts'; +import { versionAtLeast, type CatalogDependencyResolver } from '../../utils/catalog.ts'; import { VITEST_VERSION, + VITE_PLUS_CORE_NAME, VITE_PLUS_NAME, VITE_PLUS_OVERRIDE_PACKAGES, + coreAliasVersion, } from '../../utils/constants.ts'; import { readJsonFile } from '../../utils/json.ts'; import { extractOverrideTargetName } from '../../utils/package-overrides.ts'; @@ -356,12 +358,14 @@ export function managedOverridePackages( : managed; } +type SelectOverrideSpec = (name: string, current: string | undefined, target: string) => string; + // In npm and Bun's object form, "." overrides the package itself. All other keys // constrain its children and must survive a change to the package's own pin. export function ensurePackageJsonOverrides( overrides: Record | undefined, managed: Record, - selectSpec?: (name: string, current: string | undefined, target: string) => string, + selectSpec?: SelectOverrideSpec, ): { overrides: Record; changed: boolean } { const next = { ...overrides }; let changed = false; @@ -395,6 +399,42 @@ export function ensurePackageJsonOverrides( return { overrides: next, changed }; } +// Bun matches child overrides against the installed parent's package name, +// even when the project imports it through the `vite` alias. +export function ensureBunOverrides( + overrides: Record | undefined, + managed: Record, + bunVersion: string, + selectSpec?: SelectOverrideSpec, +): { overrides: Record; changed: boolean } { + const result = ensurePackageJsonOverrides(overrides, managed, selectSpec); + const next = result.overrides; + if ( + !isPlainRecord(next.vite) || + !coreAliasVersion(managed.vite) || + !versionAtLeast(bunVersion, '1.4.0', ['latest', 'canary']) + ) { + return result; + } + + const core = next[VITE_PLUS_CORE_NAME]; + const coreEntry = typeof core === 'string' ? { '.': core } : core; + const coreRules = isPlainRecord(coreEntry) ? coreEntry : {}; + // Bun accepts both nested and flat child overrides. Keep an explicit core rule in either form. + const missingChildren = Object.entries(next.vite).filter( + ([child]) => + child !== '.' && + !Object.hasOwn(coreRules, child) && + !Object.hasOwn(next, `${VITE_PLUS_CORE_NAME}>${child}`) && + !Object.hasOwn(next, `${VITE_PLUS_CORE_NAME}/${child}`), + ); + if (missingChildren.length > 0) { + next[VITE_PLUS_CORE_NAME] = { ...coreRules, ...Object.fromEntries(missingChildren) }; + result.changed = true; + } + return result; +} + // True iff a dependency field lists a vitest ecosystem package — any name that // contains `vitest` other than bare `vitest` itself (e.g. `@vitest/coverage-v8`, // `@vitest/browser-playwright`, `vitest-browser-svelte`). A bare `vitest`