diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_eslint_monorepo_plugins_in_packages/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_eslint_monorepo_plugins_in_packages/snapshots.toml index c624dac127..e9a3089e2c 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_eslint_monorepo_plugins_in_packages/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_eslint_monorepo_plugins_in_packages/snapshots.toml @@ -2,10 +2,10 @@ name = "migration_eslint_monorepo_plugins_in_packages" vp = "global" steps = [ - { argv = ["vp", "migrate", "--no-interactive"], comment = "workspace packages get the SAME aggressive cleanup as the root (deps, configs, lint-staged)", continue-on-failure = true }, + { argv = ["vp", "migrate", "--no-interactive"], comment = "migrate ESLint across the workspace", continue-on-failure = true }, { argv = ["vpt", "print-file", "package.json"], comment = "root: eslint + eslint-config-airbnb removed", continue-on-failure = true }, { argv = ["vpt", "print-file", "packages/app/package.json"], comment = "workspace: eslint, eslint-plugin-vue, @typescript-eslint/parser removed; @typescript-eslint/utils preserved (reusable AST lib)", continue-on-failure = true }, - { argv = ["vpt", "print-file", "packages/lint-config/package.json"], comment = "workspace: all eslint-plugin-* removed; peerDeps.eslint scrubbed (field deleted when empty)", continue-on-failure = true }, + { argv = ["vpt", "print-file", "packages/lint-config/package.json"], comment = "the shared lint config keeps its plugin dependencies and ESLint peer", continue-on-failure = true }, { argv = ["vpt", "stat-file", "packages/app/eslint.config.mjs", "--assert-not", "file"], comment = "workspace eslint config is deleted", continue-on-failure = true }, { argv = ["vpt", "print-file", "packages/app/.lintstagedrc.json"], comment = "workspace lint-staged rewritten (eslint --fix → vp lint --fix)", continue-on-failure = true }, ] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_eslint_monorepo_plugins_in_packages/snapshots/migration_eslint_monorepo_plugins_in_packages.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_eslint_monorepo_plugins_in_packages/snapshots/migration_eslint_monorepo_plugins_in_packages.md index c73e619613..9bb0fd2f27 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_eslint_monorepo_plugins_in_packages/snapshots/migration_eslint_monorepo_plugins_in_packages.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_eslint_monorepo_plugins_in_packages/snapshots/migration_eslint_monorepo_plugins_in_packages.md @@ -2,7 +2,7 @@ ## `vp migrate --no-interactive` -workspace packages get the SAME aggressive cleanup as the root (deps, configs, lint-staged) +migrate ESLint across the workspace ``` VITE+ - The Unified Toolchain for the Web @@ -55,13 +55,21 @@ workspace: eslint, eslint-plugin-vue, @typescript-eslint/parser removed; @typesc ## `vpt print-file packages/lint-config/package.json` -workspace: all eslint-plugin-* removed; peerDeps.eslint scrubbed (field deleted when empty) +the shared lint config keeps its plugin dependencies and ESLint peer ``` { "name": "@test/lint-config", "scripts": { "lint": "vp lint ." + }, + "dependencies": { + "@stylistic/eslint-plugin": "^2.0.0", + "eslint-plugin-import": "^2.0.0", + "eslint-plugin-vue": "^10.0.0" + }, + "peerDependencies": { + "eslint": ">=9" } } ``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_eslint_plugins_cleanup/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_eslint_plugins_cleanup/snapshots.toml index ef2d46119d..f726ae0939 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_eslint_plugins_cleanup/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_eslint_plugins_cleanup/snapshots.toml @@ -2,8 +2,8 @@ name = "migration_eslint_plugins_cleanup" vp = "global" steps = [ - { argv = ["vp", "migrate", "--no-interactive"], comment = "migration should remove ESLint, plugins, configs, scopes, formatters, and peer eslint", continue-on-failure = true }, - { argv = ["vpt", "print-file", "package.json"], comment = "verify the comprehensive ESLint ecosystem cleanup", continue-on-failure = true }, + { argv = ["vp", "migrate", "--no-interactive"], comment = "migrate the ESLint configuration", continue-on-failure = true }, + { argv = ["vpt", "print-file", "package.json"], comment = "remove dev-only ESLint tooling and keep both declarations of the ESLint peer", continue-on-failure = true }, { argv = ["vpt", "stat-file", "eslint.config.mjs", "--assert-not", "file"], comment = "check eslint config is removed", continue-on-failure = true }, { argv = ["vpt", "print-file", "vite.config.ts"], comment = "verify the generated vite.config.ts", continue-on-failure = true }, ] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_eslint_plugins_cleanup/snapshots/migration_eslint_plugins_cleanup.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_eslint_plugins_cleanup/snapshots/migration_eslint_plugins_cleanup.md index 4656977751..ba4d4990d1 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_eslint_plugins_cleanup/snapshots/migration_eslint_plugins_cleanup.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_eslint_plugins_cleanup/snapshots/migration_eslint_plugins_cleanup.md @@ -2,7 +2,7 @@ ## `vp migrate --no-interactive` -migration should remove ESLint, plugins, configs, scopes, formatters, and peer eslint +migrate the ESLint configuration ``` VITE+ - The Unified Toolchain for the Web @@ -16,7 +16,7 @@ VITE+ - The Unified Toolchain for the Web ## `vpt print-file package.json` -verify the comprehensive ESLint ecosystem cleanup +remove dev-only ESLint tooling and keep both declarations of the ESLint peer ``` { @@ -32,9 +32,13 @@ verify the comprehensive ESLint ecosystem cleanup "@types/node": "^22.0.0", "@typescript-eslint/utils": "^8.0.0", "@vitejs/plugin-vue": "^6.0.0", + "eslint": "^9.0.0", "vite": "catalog:", "vue": "^3.5.0", "vite-plus": "catalog:" + }, + "peerDependencies": { + "eslint": ">=9" } } ``` diff --git a/crates/vp_migration/src/import_rewriter.rs b/crates/vp_migration/src/import_rewriter.rs index 23dc8ac3af..bea62cec8c 100644 --- a/crates/vp_migration/src/import_rewriter.rs +++ b/crates/vp_migration/src/import_rewriter.rs @@ -2066,10 +2066,10 @@ struct SkipPackages { skip_vite: bool, /// Skip rewriting vitest imports (vitest is in peerDependencies or dependencies) skip_vitest: bool, - /// Skip rewriting tsdown imports (tsdown is in peerDependencies or dependencies) + /// Skip rewriting tsdown imports (tsdown is in dependencies, optionalDependencies, or peerDependencies) skip_tsdown: bool, /// Skip rewriting Oxlint JS-plugin API imports (`oxlint` or `@oxlint/plugins` - /// is in peerDependencies or dependencies, or @oxlint/plugins is optional). + /// is in dependencies, optionalDependencies, or peerDependencies). /// Published plugin consumers may not have Vite+. DevDependencies alone /// do not mark a published plugin and do not prevent rewriting. skip_oxlint: bool, @@ -2090,9 +2090,9 @@ pub struct RewriteImportsOptions { /// whose nearest package.json declares `@nuxt/test-utils`. pub preserve_vitest_in_nuxt_packages: bool, /// Directories of packages that declared `oxlint` or `@oxlint/plugins` in - /// `dependencies` or `peerDependencies`, or optional `@oxlint/plugins`, - /// before migration. Capture these before manifest edits so ownership - /// does not depend on which dependency declarations survive those edits. + /// `dependencies`, `optionalDependencies`, or `peerDependencies` before + /// migration. Capture these before manifest edits so ownership does not + /// depend on which dependency declarations survive those edits. pub oxlint_owner_dirs: Vec, } @@ -2266,10 +2266,18 @@ fn get_package_rewrite_context(package_json_path: &Path) -> PackageRewriteContex .and_then(|v| v.as_object()) .is_some_and(|deps| deps.contains_key(package_name)) }; + // Matches `declaresRuntimeDependency` in `migrator/shared.ts`: such a package keeps its + // declaration of a bundled tool, so its imports must keep resolving to that tool. + let declares_runtime = |package_name: &str| -> bool { + ["dependencies", "optionalDependencies", "peerDependencies"] + .into_iter() + .any(|key| has_package(key, package_name)) + }; // Peer and runtime dependencies preserve the existing whole-package skip - // behavior. Nuxt compatibility is narrower and accepts the three install - // groups where @nuxt/test-utils is normally declared. + // behavior; bundled tools also count optional declarations. Nuxt + // compatibility is narrower and accepts the three install groups where + // @nuxt/test-utils is normally declared. // // `vite` is additionally skipped when the package follows a published-plugin // naming convention: an unscoped name starting with `vite-plugin-` @@ -2288,13 +2296,8 @@ fn get_package_rewrite_context(package_json_path: &Path) -> PackageRewriteContex || package_name_is_plugin(&pkg), skip_vitest: has_package("peerDependencies", "vitest") || has_package("dependencies", "vitest"), - skip_tsdown: has_package("peerDependencies", "tsdown") - || has_package("dependencies", "tsdown"), - skip_oxlint: has_package("peerDependencies", "oxlint") - || has_package("dependencies", "oxlint") - || has_package("peerDependencies", "@oxlint/plugins") - || has_package("dependencies", "@oxlint/plugins") - || has_package("optionalDependencies", "@oxlint/plugins"), + skip_tsdown: declares_runtime("tsdown"), + skip_oxlint: declares_runtime("oxlint") || declares_runtime("@oxlint/plugins"), }, uses_nuxt_test_utils: ["dependencies", "devDependencies", "optionalDependencies"] .into_iter() @@ -5042,23 +5045,25 @@ export default defineConfig({});"#; } #[test] - fn test_optional_oxlint_keeps_existing_rewrite_policy() { - let temp = tempdir().unwrap(); - std::fs::write( - temp.path().join("package.json"), - r#"{"optionalDependencies":{"oxlint":"^1.79.0"}}"#, - ) - .unwrap(); - let file = temp.path().join("plugin.js"); - std::fs::write(&file, "import { defineRule } from 'oxlint';").unwrap(); + fn test_optional_bundled_tools_keep_upstream_imports() { + for (package, content) in [ + ("oxlint", "import { defineRule } from 'oxlint';"), + ("tsdown", "const { build } = await import('tsdown');"), + ] { + let temp = tempdir().unwrap(); + std::fs::write( + temp.path().join("package.json"), + format!(r#"{{"optionalDependencies":{{"{package}":"*"}}}}"#), + ) + .unwrap(); + let file = temp.path().join("index.js"); + std::fs::write(&file, content).unwrap(); - let result = rewrite_imports_in_directory(temp.path()).unwrap(); + let result = rewrite_imports_in_directory(temp.path()).unwrap(); - assert_eq!(result.modified_files, vec![file.clone()]); - assert_eq!( - std::fs::read_to_string(file).unwrap(), - "import { defineRule } from 'vite-plus/lint/plugins';" - ); + assert!(result.modified_files.is_empty(), "{package}"); + assert_eq!(std::fs::read_to_string(file).unwrap(), content); + } } #[test] diff --git a/docs/guide/migrate-rules.md b/docs/guide/migrate-rules.md index 94a87b558c..301dcd095c 100644 --- a/docs/guide/migrate-rules.md +++ b/docs/guide/migrate-rules.md @@ -135,6 +135,10 @@ What happens to each toolchain dependency, at a glance: | `@vitest/*` | Directly installed lockstep packages aligned to the bundled Vitest version (see [Vitest Ecosystem Packages](#vitest-ecosystem-packages)). | | `@voidzero-dev/vite-plus-test` | Removed everywhere: dependencies, overrides, resolutions, and catalog aliases. Imports are rewritten to the current `vite-plus/test*` surface. | +Vite+ bundles Oxlint, Oxfmt, tsdown, `@vitest/browser`, and `@vitest/browser-preview`, so migration removes their `devDependencies` entries. A package that also lists one of them in `dependencies`, `optionalDependencies`, or `peerDependencies` keeps every declaration of it, including the development copy. Such a package publishes or runs the tool, and its consumers may not use Vite+. A tsdown plugin, for example, keeps `tsdown` as a peer and as the devDependency it tests against. Its `tsdown` imports also stay unchanged instead of moving to `vite-plus/pack`. Migration also keeps the catalog entries for these declarations, so a kept `catalog:` reference still resolves. + +The same rule applies to the tools that migration replaces: ESLint and its plugins, Prettier and `prettier-plugin-*`, lint-staged, tsup, tsx, oxnode, and ts-node. A package that keeps tsup also keeps its tsup config and scripts, because migration does not run `tsdown-migrate` there. + ### Version Selection - `vite-plus` is pinned to the concrete version of the CLI running the migration, never the `latest` dist-tag. @@ -239,7 +243,7 @@ The migration leaves three forms alone: - Default and namespace `oxlint` imports. They name no binding, so the migration cannot tell the two surfaces apart. - Bare side-effect `oxlint` imports, for the same reason. -The migration also skips a package that declares `oxlint` or `@oxlint/plugins` in `dependencies` or `peerDependencies`, or `@oxlint/plugins` in `optionalDependencies`. These dependencies can supply a published Oxlint plugin. Its consumers may not run Vite+. +The migration also skips a package that declares `oxlint` or `@oxlint/plugins` in `dependencies`, `optionalDependencies`, or `peerDependencies`. These dependencies can supply a published Oxlint plugin. Its consumers may not run Vite+. The cleanup retains a development dependency on `@oxlint/plugins` when source, package import aliases, or built plugins still reference it. This includes ignored output in directories such as `dist`, `build`, and `out`. diff --git a/packages/cli/src/__tests__/oxlint-plugin.spec.ts b/packages/cli/src/__tests__/oxlint-plugin.spec.ts index 34acac6d23..5eea19505a 100644 --- a/packages/cli/src/__tests__/oxlint-plugin.spec.ts +++ b/packages/cli/src/__tests__/oxlint-plugin.spec.ts @@ -332,6 +332,11 @@ new RuleTester({ `export { 'defineRule' as rule } from 'oxlint'`, `import { RuleTester } from 'oxlint/plugins-dev'`, ].map((code) => ({ code, filename: oxlintOptionalPluginPackageFilename })), + // Migration keeps optional `oxlint`, so its plugin API imports stay upstream too. + { + code: `import { defineRule } from 'oxlint'`, + filename: oxlintOptionalToolPackageFilename, + }, // `declare module` keeps the upstream module identity, so augmentations // still merge with the upstream declarations. { @@ -447,13 +452,6 @@ new RuleTester({ }, ], invalid: [ - { - // Optional oxlint retains the existing tool-migration policy. - code: `import { defineRule } from 'oxlint'`, - filename: oxlintOptionalToolPackageFilename, - errors: 1, - output: `import { defineRule } from 'vite-plus/lint/plugins'`, - }, { code: `import { definePlugin, defineRule } from '@oxlint/plugins'`, errors: 1, diff --git a/packages/cli/src/migration/__tests__/migrator.spec.ts b/packages/cli/src/migration/__tests__/migrator.spec.ts index b306677972..4d2f1dd837 100644 --- a/packages/cli/src/migration/__tests__/migrator.spec.ts +++ b/packages/cli/src/migration/__tests__/migrator.spec.ts @@ -272,7 +272,7 @@ describe('rewritePackageJson', () => { }; rewritePackageJson(pkg, packageManager, isMonorepo); expect(pkg).toEqual({ - dependencies: { foo: '1.0.0' }, + dependencies: { foo: '1.0.0', tsdown: '1.0.0' }, devDependencies: { 'vite-plus': vitePlusSpec }, }); }, @@ -529,9 +529,9 @@ describe('rewritePackageJson', () => { rewritePackageJson(pkg, PackageManager.pnpm, true); expect(pkg.peerDependencies.vite).toBe('*'); - expect(pkg.peerDependencies).not.toHaveProperty('tsdown'); + expect(pkg.peerDependencies).toHaveProperty('tsdown'); expect(pkg.optionalDependencies.vitest).toBe('catalog:test'); - expect(pkg.optionalDependencies).not.toHaveProperty('oxlint'); + expect(pkg.optionalDependencies).toHaveProperty('oxlint'); expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:'); }); @@ -840,7 +840,7 @@ describe('rewriteEslintPackageJson', () => { rewriteEslintPackageJson(pkgPath); const pkg = readJson(pkgPath); expect(pkg.devDependencies).toEqual({ vite: '^7.0.0' }); - expect(pkg.dependencies).toEqual({ vue: '^3.5.0' }); + expect(pkg.dependencies).toEqual({ 'eslint-plugin-import': '^2.0.0', vue: '^3.5.0' }); }); it('removes scoped ESLint plugin/config packages (e.g. @vue/eslint-config-typescript)', () => { @@ -956,22 +956,28 @@ describe('rewriteEslintPackageJson', () => { expect(pkg.devDependencies).toEqual({ '@types/node': '^22.0.0' }); }); - it('scrubs peerDependencies and optionalDependencies', () => { - const pkgPath = writePkg({ - peerDependencies: { - eslint: '>=9', + // An ESLint plugin package tests its rules with the ESLint its consumers provide. + it('keeps ESLint packages that the project also declares at runtime', () => { + const pkg = { + peerDependencies: { eslint: '>=9' }, + optionalDependencies: { '@typescript-eslint/parser': '^8.0.0' }, + devDependencies: { + eslint: '^9.0.0', + '@typescript-eslint/parser': '^8.0.0', 'eslint-plugin-vue': '^10.0.0', + vite: '^7.0.0', }, - optionalDependencies: { + }; + const pkgPath = writePkg(pkg); + rewriteEslintPackageJson(pkgPath); + expect(readJson(pkgPath)).toEqual({ + ...pkg, + devDependencies: { + eslint: '^9.0.0', '@typescript-eslint/parser': '^8.0.0', + vite: '^7.0.0', }, - devDependencies: { vite: '^7.0.0' }, }); - rewriteEslintPackageJson(pkgPath); - const pkg = readJson(pkgPath); - expect(pkg.peerDependencies).toBeUndefined(); - expect(pkg.optionalDependencies).toBeUndefined(); - expect(pkg.devDependencies).toEqual({ vite: '^7.0.0' }); }); it('deletes the dependency field entirely when our cleanup emptied it', () => { @@ -985,7 +991,7 @@ describe('rewriteEslintPackageJson', () => { rewriteEslintPackageJson(pkgPath); const pkg = readJson(pkgPath); expect(pkg.devDependencies).toBeUndefined(); - expect(pkg.dependencies).toBeUndefined(); + expect(pkg.dependencies).toEqual({ 'eslint-config-airbnb': '^19.0.0' }); }); it('preserves unrelated dependencies (e.g. @vitejs/plugin-vue, vue, vite, @nuxt/kit)', () => { @@ -5634,7 +5640,8 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { expect(yaml).toHaveProperty(['catalogs', 'vite7', 'vite-plus'], 'latest'); const testCatalog = fixtureObject(yaml, 'catalogs', 'test'); expect(testCatalog.vitest).toBeUndefined(); - expect(testCatalog.tsdown).toBeUndefined(); + // The tsdown peer survives migration, so its catalog entry does too. + expect(testCatalog.tsdown).toBe('^0.1.0'); expect(testCatalog['vite-plus']).toBeUndefined(); const pkg = readJson(path.join(tmpDir, 'package.json')); @@ -5645,7 +5652,48 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { // catalog entry to its public range before pruning it so the peer cannot // dangle after migration. expect(pkg).toHaveProperty(['peerDependencies', 'vitest'], '^4.0.0'); - expect(pkg.peerDependencies).not.toHaveProperty('tsdown'); + expect(pkg).toHaveProperty(['peerDependencies', 'tsdown'], 'catalog:test'); + }); + + // A tsdown plugin builds and tests against the tsdown its consumers provide. + it('keeps a bundled package that the project also declares as a peer', () => { + const packageJsonPath = path.join(tmpDir, 'package.json'); + fs.writeFileSync( + packageJsonPath, + JSON.stringify({ + name: 'tsdown-plugin-example', + peerDependencies: { tsdown: '^0.23.0' }, + devDependencies: { tsdown: '^0.23.0' }, + }), + ); + const workspace = makeWorkspaceInfo(tmpDir, PackageManager.pnpm); + + rewriteStandaloneProject(tmpDir, workspace, true, true); + + const pkg = readJson(packageJsonPath); + expect(pkg.peerDependencies).toEqual({ tsdown: '^0.23.0' }); + expect(pkg.devDependencies).toEqual({ tsdown: '^0.23.0', 'vite-plus': 'catalog:' }); + checkBootstrapPass(workspace, false); + expect(readJson(packageJsonPath)).toEqual(pkg); + }); + + // Vitest alignment turns the range into `catalog:`, so the kept runtime dependency needs its catalog entry. + it('adds a catalog entry for an aligned bundled package kept at runtime', () => { + const packageJsonPath = path.join(tmpDir, 'package.json'); + writePkgAt(tmpDir, { name: 'test', dependencies: { '@vitest/browser-preview': '^4.1.0' } }); + fs.writeFileSync(path.join(tmpDir, 'pnpm-workspace.yaml'), 'catalog:\n vite: ^7.0.0\n'); + const workspace = makeWorkspaceInfo(tmpDir, PackageManager.pnpm); + + rewriteStandaloneProject(tmpDir, workspace, true, true); + + const pkg = readJson(packageJsonPath); + expect(pkg).toHaveProperty(['dependencies', '@vitest/browser-preview'], 'catalog:'); + expect(readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml'))).toHaveProperty( + ['catalog', '@vitest/browser-preview'], + VITEST_VERSION, + ); + checkBootstrapPass(workspace, false); + expect(readJson(packageJsonPath)).toEqual(pkg); }); it('reuses catalogs.default without creating a duplicate top-level catalog', () => { diff --git a/packages/cli/src/migration/__tests__/oxlint-plugin-dependency.spec.ts b/packages/cli/src/migration/__tests__/oxlint-plugin-dependency.spec.ts index a25a90d576..8aecc8cc9d 100644 --- a/packages/cli/src/migration/__tests__/oxlint-plugin-dependency.spec.ts +++ b/packages/cli/src/migration/__tests__/oxlint-plugin-dependency.spec.ts @@ -589,8 +589,7 @@ describe('Oxlint plugin dependency cleanup', () => { expect(ensureVitePlusBootstrap(workspace).changed).toBe(false); expect(readJsonFile(packageJsonPath).dependencies).toEqual({ oxlint: '^1.0.0' }); - // An existing Vite+ project can still reference a catalog entry that the - // bootstrap deletes, so the kept dependency takes the concrete range. + // A kept `catalog:` reference keeps the catalog entry it points at. const pkg = readJsonFile(packageJsonPath); writeJsonFile(packageJsonPath, { ...pkg, dependencies: { oxlint: 'catalog:' } }); fs.writeFileSync( @@ -600,18 +599,17 @@ describe('Oxlint plugin dependency cleanup', () => { .replace('catalog:\n', 'catalog:\n oxlint: ^1.0.0\n'), ); - expect(pending()).toBe(true); - expect(ensureVitePlusBootstrap(workspace).changed).toBe(true); - expect(readJsonFile(packageJsonPath).dependencies).toEqual({ oxlint: '^1.0.0' }); - expect(fs.readFileSync(workspaceYamlPath, 'utf8')).not.toContain('oxlint: ^1.0.0'); expect(pending()).toBe(false); + expect(ensureVitePlusBootstrap(workspace).changed).toBe(false); + expect(readJsonFile(packageJsonPath).dependencies).toEqual({ oxlint: 'catalog:' }); + expect(fs.readFileSync(workspaceYamlPath, 'utf8')).toContain('oxlint: ^1.0.0'); }); - it('keeps optional oxlint on the existing tool-migration path', () => { + it('keeps optional oxlint as a runtime dependency', () => { const pkg = { optionalDependencies: { oxlint: '^1.79.0' } }; - expect(packageOwnsOxlintApi(pkg)).toBe(false); + expect(packageOwnsOxlintApi(pkg)).toBe(true); rewritePackageJson(pkg, PackageManager.pnpm); - expect(pkg.optionalDependencies).toEqual({}); + expect(pkg.optionalDependencies).toEqual({ oxlint: '^1.79.0' }); }); }); diff --git a/packages/cli/src/migration/__tests__/tsup.spec.ts b/packages/cli/src/migration/__tests__/tsup.spec.ts index 39a89adf94..e9f0aa25cd 100644 --- a/packages/cli/src/migration/__tests__/tsup.spec.ts +++ b/packages/cli/src/migration/__tests__/tsup.spec.ts @@ -327,6 +327,73 @@ describe('tsup migration', () => { }); }); + it('ignores a package that declares tsup at runtime', () => { + fs.writeFileSync( + path.join(projectPath, 'package.json'), + `${JSON.stringify( + { + name: 'tsup-plugin', + peerDependencies: { tsup: '^8.0.0' }, + devDependencies: { tsup: '^8.5.0' }, + }, + null, + 2, + )}\n`, + ); + + expect(detectTsupProject(projectPath)).toEqual({ + hasDependency: false, + hasConfig: false, + configFile: undefined, + }); + }); + + it('keeps the tsup setup of a workspace package that declares tsup at runtime', async () => { + fs.writeFileSync( + path.join(projectPath, 'package.json'), + '{"name":"workspace","private":true}\n', + ); + fs.unlinkSync(path.join(projectPath, 'tsup.config.ts')); + const packages = [ + { name: 'app', path: 'packages/app' }, + { name: 'plugin', path: 'packages/plugin' }, + ]; + const manifests = [ + { name: 'app', devDependencies: { tsup: '^8.5.0' } }, + { + name: 'plugin', + peerDependencies: { tsup: '^8.0.0' }, + devDependencies: { tsup: '^8.5.0' }, + }, + ]; + for (const manifest of manifests) { + const packagePath = path.join(projectPath, 'packages', manifest.name); + fs.mkdirSync(packagePath, { recursive: true }); + fs.writeFileSync( + path.join(packagePath, 'package.json'), + `${JSON.stringify({ ...manifest, scripts: { build: 'tsup' } }, null, 2)}\n`, + ); + fs.writeFileSync(path.join(packagePath, 'tsup.config.ts'), 'export default {};\n'); + } + const pluginPath = path.join(projectPath, 'packages/plugin'); + const originalPluginPackage = fs.readFileSync(path.join(pluginPath, 'package.json'), 'utf8'); + + await expect( + migrateTsupToTsdown(projectPath, false, PackageManager.pnpm, undefined, packages, { + silent: true, + }), + ).resolves.toBe(true); + + expect(mockRunCommandSilently).toHaveBeenCalledTimes(1); + expect(mockRunCommandSilently).toHaveBeenCalledWith( + expect.objectContaining({ cwd: path.join(projectPath, 'packages/app') }), + ); + expect(fs.readFileSync(path.join(pluginPath, 'package.json'), 'utf8')).toBe( + originalPluginPackage, + ); + expect(fs.existsSync(path.join(pluginPath, 'tsup.config.ts'))).toBe(true); + }); + it('restores all workspace targets when a later migration fails', async () => { fs.writeFileSync( path.join(projectPath, 'package.json'), diff --git a/packages/cli/src/migration/migrator/eslint.ts b/packages/cli/src/migration/migrator/eslint.ts index 0cacc3fe48..3133aff0c3 100644 --- a/packages/cli/src/migration/migrator/eslint.ts +++ b/packages/cli/src/migration/migrator/eslint.ts @@ -27,6 +27,7 @@ import type { MigrationReport } from '../report.ts'; import { LINT_STAGED_JSON_CONFIG_FILES, LINT_STAGED_OTHER_CONFIG_FILES, + removeReplacedDevDependency, rewritePackageScriptFields, rewriteScriptMap, warnMigration, @@ -454,33 +455,20 @@ export function rewriteEslintPackageJson( 'lint-staged'?: Record>; }>(packageJsonPath, (pkg) => { let changed = false; - for (const field of [ - 'devDependencies', - 'dependencies', - 'peerDependencies', - 'optionalDependencies', - ] as const) { - const deps = pkg[field]; - if (!deps) { - continue; - } - let removedAny = false; - for (const name of Object.keys(deps)) { - if (preserveJsPlugins.has(name)) { - continue; - } - if (isEslintEcosystemDep(name)) { - delete deps[name]; - changed = true; - removedAny = true; - } - } - // Drop the field entirely if our cleanup emptied it — avoid - // leaving `"devDependencies": {}` noise in the output. - if (removedAny && Object.keys(deps).length === 0) { - delete pkg[field]; + for (const name of Object.keys(pkg.devDependencies ?? {})) { + if ( + !preserveJsPlugins.has(name) && + isEslintEcosystemDep(name) && + removeReplacedDevDependency(pkg, name) + ) { + changed = true; } } + // Drop the field entirely if our cleanup emptied it — avoid + // leaving `"devDependencies": {}` noise in the output. + if (changed && Object.keys(pkg.devDependencies ?? {}).length === 0) { + delete pkg.devDependencies; + } const scriptsChanged = rewritePackageScriptFields(pkg, rewriteEslint); return changed || scriptsChanged ? pkg : undefined; }); diff --git a/packages/cli/src/migration/migrator/git-hooks.ts b/packages/cli/src/migration/migrator/git-hooks.ts index 7a22d8e533..0958d0b9e5 100644 --- a/packages/cli/src/migration/migrator/git-hooks.ts +++ b/packages/cli/src/migration/migrator/git-hooks.ts @@ -25,11 +25,13 @@ import { removeLintStagedFromPackageJson, } from '../migrator.ts'; import type { MigrationReport } from '../report.ts'; +import type { DependencyBag } from './shared.ts'; import { rewriteScriptMap } from './shared.ts'; import { getCommandStartIndex, LINT_STAGED_ALL_CONFIG_FILES, LINT_STAGED_OTHER_CONFIG_FILES, + removeReplacedDevDependency, SHELL_STATE_COMMANDS, warnMigration, } from './shared.ts'; @@ -38,18 +40,9 @@ const OTHER_HOOK_TOOLS = ['simple-git-hooks', 'lefthook', 'yorkie'] as const; const SUPPORTED_GIT_HOOK_NAME_SET = new Set(SUPPORTED_GIT_HOOK_NAMES); function removeReplacedStagedPackage(packageJsonPath: string): void { - editJsonFile<{ - devDependencies?: Record; - dependencies?: Record; - }>(packageJsonPath, (pkg) => { - if (pkg.devDependencies?.['lint-staged']) { - delete pkg.devDependencies['lint-staged']; - } - if (pkg.dependencies?.['lint-staged']) { - delete pkg.dependencies['lint-staged']; - } - return pkg; - }); + editJsonFile(packageJsonPath, (pkg) => + removeReplacedDevDependency(pkg, 'lint-staged') ? pkg : undefined, + ); } export function detectLegacyGitHooksMigrationCandidate(projectPath: string): boolean { diff --git a/packages/cli/src/migration/migrator/orchestrators.ts b/packages/cli/src/migration/migrator/orchestrators.ts index 093bff699d..9db144e858 100644 --- a/packages/cli/src/migration/migrator/orchestrators.ts +++ b/packages/cli/src/migration/migrator/orchestrators.ts @@ -11,7 +11,7 @@ import { applyBuildAllowanceToPackageJsonPnpm, applyYarnWorkspaceHoistingFix, cleanupDeprecatedTsconfigOptions, - collectBrowserCatalogAdditions, + collectCatalogAdditions, collectOxlintDependencyNames, collectOxlintOwnerDirs, collectRetainedImportDependencies, @@ -112,7 +112,7 @@ export function rewriteStandaloneProject( workspaceInfo.packages, ); // Source-tree scan signals are computed once here and reused below (and inside - // projectUsesVitestDirectly / collectBrowserCatalogAdditions) so the source tree + // projectUsesVitestDirectly / collectCatalogAdditions) so the source tree // is traversed once each instead of repeatedly. They do not depend on // package.json contents and no scanned source files are mutated before they // are consumed, so the values match the previous lazy per-call scans exactly. @@ -126,7 +126,7 @@ export function rewriteStandaloneProject( const retainedVitestModule = retainedImportDependencies.vitest.has(projectPath) || sourceTreeReferencesRetainedVitestModule(projectPath); - const browserCatalogAdditions = collectBrowserCatalogAdditions( + const catalogAdditions = collectCatalogAdditions( projectPath, undefined, retainedImportDependencies.browser, @@ -274,7 +274,7 @@ export function rewriteStandaloneProject( usesVitest, retainedVitestModule, requiredVitestPeer, - browserCatalogAdditions, + catalogAdditions, retainedImportDependencies.browser.get(projectPath), ); @@ -316,7 +316,7 @@ export function rewriteStandaloneProject( usesVitest, vitestEcosystemPackages, usePnpmWorkspaceYaml, - browserCatalogAdditions, + catalogAdditions, usesWebdriverio, workspaceInfo.downloadPackageManager.version, ); @@ -343,7 +343,7 @@ export function rewriteStandaloneProject( projectPath, usesVitest, vitestEcosystemPackages, - browserCatalogAdditions, + catalogAdditions, supportCatalog, yarnSupportsPreapprovedPackages(workspaceInfo.downloadPackageManager.version), ); @@ -430,7 +430,7 @@ export function rewriteMonorepo( workspaceInfo.rootDir, workspaceInfo.packages, ); - const browserCatalogAdditions = collectBrowserCatalogAdditions( + const catalogAdditions = collectCatalogAdditions( workspaceInfo.rootDir, workspaceInfo.packages, retainedImportDependencies.browser, @@ -454,7 +454,7 @@ export function rewriteMonorepo( workspaceInfo.rootDir, workspaceUsesVitest, vitestEcosystemPackages, - browserCatalogAdditions, + catalogAdditions, supportCatalog, yarnSupportsPreapprovedPackages(workspaceInfo.downloadPackageManager.version), ); @@ -481,7 +481,7 @@ export function rewriteMonorepo( workspaceUsesVitest, vitestEcosystemPackages, usePnpmWorkspaceSettings, - browserCatalogAdditions, + catalogAdditions, usesWebdriverio, workspaceInfo.downloadPackageManager.version, ); @@ -499,7 +499,7 @@ export function rewriteMonorepo( vitestEcosystemPackages, usesWebdriverio, workspaceInfo.downloadPackageManager.version, - browserCatalogAdditions, + catalogAdditions, ); } // (mergeViteConfigFiles below will sanitize the merged lint config @@ -524,7 +524,7 @@ export function rewriteMonorepo( workspaceContext, true, supportCatalog, - browserCatalogAdditions, + catalogAdditions, ); } @@ -589,8 +589,8 @@ export function rewriteMonorepoProject( // Yarn >= 4.10.0; pnpm/bun monorepos always manage a catalog. Defaults to true // so the `vp create` callers (always a catalog-capable bundled PM) are covered. supportCatalog = true, - // An installed provider references the shared catalog entry added for a sibling. - browserCatalogAdditions: ReadonlySet = new Set(), + // Catalog entries that migration keeps or adds. An installed provider references one added for a sibling. + catalogAdditions: ReadonlySet = new Set(), ): void { cleanupDeprecatedTsconfigOptions(projectPath, silent, report); rewriteTsconfigTypes(projectPath, silent, report); @@ -652,7 +652,7 @@ export function rewriteMonorepoProject( }), retainedVitestModule, requiredVitestPeer, - browserCatalogAdditions, + catalogAdditions, workspaceContext?.retainedImportDependencies?.browser.get(projectPath), ); // If this SUB-workspace now depends on `vite-plus` and Yarn isolates its diff --git a/packages/cli/src/migration/migrator/package-json.ts b/packages/cli/src/migration/migrator/package-json.ts index 8842463c28..fe134d50e6 100644 --- a/packages/cli/src/migration/migrator/package-json.ts +++ b/packages/cli/src/migration/migrator/package-json.ts @@ -30,9 +30,9 @@ import { resolveProviderPeerSpec, OPT_IN_BROWSER_PROVIDERS, OXLINT_PLUGINS_PACKAGE, - OXLINT_PLUGIN_API_PACKAGES, packageOwnsOxlintApi, bundledPackagesToRemove, + removeBundledDevDependencies, VITEST_BROWSER_DEP_NAMES, VITEST_IS_MANAGED_OVERRIDE, } from './shared.ts'; @@ -67,8 +67,8 @@ export function rewritePackageJson( // Installed dependency metadata can reveal required Vitest peers whose // package names do not include "vitest". requiredVitestPeer = false, - // An installed provider references the shared catalog entry added for a sibling. - browserCatalogAdditions: ReadonlySet = new Set(), + // Catalog entries that migration keeps or adds. An installed provider references one added for a sibling. + catalogAdditions: ReadonlySet = new Set(), // Bundled browser packages that this package still imports. retainedBrowserPackages?: ReadonlySet, ): Record> | null { @@ -186,43 +186,14 @@ export function rewritePackageJson( const hasBrowserDepSignal = VITEST_BROWSER_DEP_NAMES.some((name) => dependencyGroups.some(({ dependencies }) => dependencies?.[name] !== undefined), ); - // Published plugins keep their upstream imports and the dependencies that - // supply them, including optional @oxlint/plugins integrations. - const ownsOxlintApi = packageOwnsOxlintApi(pkg); - // Rewritten imports need a direct vite-plus dependency. Defer removal of - // @oxlint/plugins until dropDeadOxlintPluginsDependency checks the final source. - if (pkg.devDependencies?.[OXLINT_PLUGINS_PACKAGE] !== undefined && !ownsOxlintApi) { + // Rewritten imports need a direct vite-plus dependency, but published plugins + // keep their upstream imports. Defer removal of @oxlint/plugins until + // dropDeadOxlintPluginsDependency checks the final source. + if (pkg.devDependencies?.[OXLINT_PLUGINS_PACKAGE] !== undefined && !packageOwnsOxlintApi(pkg)) { needVitePlus = true; } - // remove packages that are replaced with vite-plus - for (const name of bundledPackagesToRemove(retainedBrowserPackages)) { - let wasRemoved = false; - for (const { dependencyField, dependencies } of dependencyGroups) { - if ( - ownsOxlintApi && - (dependencyField === 'peerDependencies' || dependencyField === 'dependencies') && - (OXLINT_PLUGIN_API_PACKAGES as ReadonlyArray).includes(name) - ) { - // A `catalog:` reference would dangle once the catalog entry for a - // REMOVE_PACKAGES name is dropped, and the next install fails. Resolve - // it to the concrete range the catalog currently points at. - const current = dependencies?.[name]; - if (current?.startsWith('catalog:') && dependencies) { - const resolved = catalogDependencyResolver?.(current, name); - if (resolved) { - dependencies[name] = resolved; - } - } - continue; - } - if (dependencies?.[name]) { - delete dependencies[name]; - wasRemoved = true; - } - } - if (wasRemoved) { - needVitePlus = true; - } + if (removeBundledDevDependencies(pkg, bundledPackagesToRemove(retainedBrowserPackages))) { + needVitePlus = true; } // Official opt-in providers remain project dependencies. Align their versions // with bundled Vitest and ensure the framework peer required by each shim. @@ -256,7 +227,7 @@ export function rewritePackageJson( provider, installGroupEntry.dependencyField, packageManager, - browserCatalogAdditions.has(provider) + catalogAdditions.has(provider) ? supportCatalog && packageManager !== PackageManager.bun : supportCatalog, catalogDependencyResolver, diff --git a/packages/cli/src/migration/migrator/prettier.ts b/packages/cli/src/migration/migrator/prettier.ts index 72ae8afc36..50c5c43edc 100644 --- a/packages/cli/src/migration/migrator/prettier.ts +++ b/packages/cli/src/migration/migrator/prettier.ts @@ -18,7 +18,12 @@ import { getSilentSpinner, getSpinner } from '../../utils/spinner.ts'; import { PRETTIER_CONFIG_FILES, PRETTIER_PACKAGE_JSON_CONFIG, detectConfigs } from '../detector.ts'; import { hasOnlyInjectedDefaults, rewriteToolLintStagedConfigFiles } from '../migrator.ts'; import type { MigrationReport } from '../report.ts'; -import { rewritePackageScriptFields, warnMigration } from './shared.ts'; +import type { DependencyBag } from './shared.ts'; +import { + removeReplacedDevDependency, + rewritePackageScriptFields, + warnMigration, +} from './shared.ts'; export function detectPrettierProject(projectPath: string, packages?: Array) { const packageJsonPath = path.join(projectPath, 'package.json'); @@ -255,28 +260,19 @@ function rewritePrettierPackageJson(packageJsonPath: string): void { if (!fs.existsSync(packageJsonPath)) { return; } - editJsonFile<{ - devDependencies?: Record; - dependencies?: Record; - scripts?: Record; - 'lint-staged'?: Record>; - }>(packageJsonPath, (pkg) => { - let changed = false; - // Remove prettier and prettier-plugin-* dependencies - if (pkg.devDependencies) { - for (const dep of Object.keys(pkg.devDependencies)) { - if (dep === 'prettier' || dep.startsWith('prettier-plugin-')) { - delete pkg.devDependencies[dep]; - changed = true; - } - } + editJsonFile< + DependencyBag & { + scripts?: Record; + 'lint-staged'?: Record>; } - if (pkg.dependencies) { - for (const dep of Object.keys(pkg.dependencies)) { - if (dep === 'prettier' || dep.startsWith('prettier-plugin-')) { - delete pkg.dependencies[dep]; - changed = true; - } + >(packageJsonPath, (pkg) => { + let changed = false; + for (const dep of Object.keys(pkg.devDependencies ?? {})) { + if ( + (dep === 'prettier' || dep.startsWith('prettier-plugin-')) && + removeReplacedDevDependency(pkg, dep) + ) { + changed = true; } } const scriptsChanged = rewritePackageScriptFields(pkg, rewritePrettier); diff --git a/packages/cli/src/migration/migrator/script-runner.ts b/packages/cli/src/migration/migrator/script-runner.ts index 69f465ee9b..3939a4e43c 100644 --- a/packages/cli/src/migration/migrator/script-runner.ts +++ b/packages/cli/src/migration/migrator/script-runner.ts @@ -15,6 +15,7 @@ import { sourceTreeMatches } from '../migrator.ts'; import type { MigrationReport } from '../report.ts'; import type { DependencyBag } from './shared.ts'; import { + declaresRuntimeDependency, getCommandStartIndex, isPlainRecord, LINT_STAGED_JSON_CONFIG_FILES, @@ -944,17 +945,9 @@ function lintStagedJsonFiles(dir: string): Array { ); } -/** - * A package that lists a runner outside devDependencies keeps it: published code or - * production scripts can need it, and `vpx` comes from the vite-plus devDependency. - */ +// `vpx` comes from the vite-plus devDependency, so it cannot replace a runner the package needs at runtime. function ownsRunnerAtRuntime(runner: ScriptRunnerMigration, pkg: DependencyBag): boolean { - return runner.dependencies.some( - (dependency) => - pkg.dependencies?.[dependency] !== undefined || - pkg.optionalDependencies?.[dependency] !== undefined || - pkg.peerDependencies?.[dependency] !== undefined, - ); + return runner.dependencies.some((dependency) => declaresRuntimeDependency(pkg, dependency)); } function packageDirs(rootDir: string, packages?: ReadonlyArray): Array { diff --git a/packages/cli/src/migration/migrator/shared.ts b/packages/cli/src/migration/migrator/shared.ts index f136365131..226b834694 100644 --- a/packages/cli/src/migration/migrator/shared.ts +++ b/packages/cli/src/migration/migrator/shared.ts @@ -469,23 +469,56 @@ export function pnpmMajor(version: string | undefined): number | undefined { return version ? coerce(version)?.major : undefined; } -// Packages that own the Oxlint JS-plugin authoring API as a published contract. -// Optional `@oxlint/plugins` is also a runtime contract for consumers of a -// published integration. Optional `oxlint` keeps the existing tool policy. export const OXLINT_PLUGINS_PACKAGE = '@oxlint/plugins'; -export const OXLINT_PLUGIN_API_PACKAGES = ['oxlint', OXLINT_PLUGINS_PACKAGE] as const; +const OXLINT_PLUGIN_API_PACKAGES = ['oxlint', OXLINT_PLUGINS_PACKAGE] as const; +// A package that declares either at runtime owns the Oxlint JS-plugin authoring API as a published contract. export function packageOwnsOxlintApi(pkg: DependencyBag): boolean { + return OXLINT_PLUGIN_API_PACKAGES.some((name) => declaresRuntimeDependency(pkg, name)); +} + +/** + * Vite+ replaces only a devDependency. A package that also lists it in + * `dependencies`, `optionalDependencies`, or `peerDependencies` publishes or + * runs it, and its consumers may not use Vite+. + */ +export function declaresRuntimeDependency(pkg: DependencyBag, name: string): boolean { return ( - pkg.optionalDependencies?.[OXLINT_PLUGINS_PACKAGE] !== undefined || - OXLINT_PLUGIN_API_PACKAGES.some( - (name) => - pkg.dependencies?.[name] !== undefined || pkg.peerDependencies?.[name] !== undefined, - ) + pkg.dependencies?.[name] !== undefined || + pkg.optionalDependencies?.[name] !== undefined || + pkg.peerDependencies?.[name] !== undefined ); } +/** Remove a devDependency that Vite+ replaces. Returns whether it was removed. */ +export function removeReplacedDevDependency(pkg: DependencyBag, name: string): boolean { + if (pkg.devDependencies?.[name] === undefined || declaresRuntimeDependency(pkg, name)) { + return false; + } + delete pkg.devDependencies[name]; + return true; +} + +/** + * Remove the bundled packages that Vite+ replaces. Returns whether the package + * lists any of them as a devDependency, kept or not. + */ +export function removeBundledDevDependencies( + pkg: DependencyBag, + names: ReadonlyArray, +): boolean { + let declared = false; + for (const name of names) { + declared ||= pkg.devDependencies?.[name] !== undefined; + // A kept `catalog:` reference still resolves because `collectCatalogAdditions` keeps its entry. + if (!declaresRuntimeDependency(pkg, name)) { + delete pkg.devDependencies?.[name]; + } + } + return declared; +} + /** * Capture plugin owners before manifest edits, so the import rewriter can * preserve their upstream API imports after those edits. diff --git a/packages/cli/src/migration/migrator/tsup.ts b/packages/cli/src/migration/migrator/tsup.ts index f1ff937c5c..0e67d5b74c 100644 --- a/packages/cli/src/migration/migrator/tsup.ts +++ b/packages/cli/src/migration/migrator/tsup.ts @@ -21,6 +21,12 @@ import { getSilentSpinner, getSpinner } from '../../utils/spinner.ts'; import { detectConfigs, TSUP_CONFIG_FILES, TSUP_PACKAGE_JSON_CONFIG } from '../detector.ts'; import type { MigrationReport } from '../report.ts'; import { addMigrationWarning } from '../report.ts'; +import type { DependencyBag } from './shared.ts'; +import { + declaresRuntimeDependency, + readPackageJsonIfExists, + removeReplacedDevDependency, +} from './shared.ts'; function showTsdownMigrationOptions( targetLabel = 'the project root', @@ -50,36 +56,31 @@ function showTsdownMigrationSkillGuidance(instructions: Array): void { ); } +// A package that declares tsup at runtime publishes or runs it, so it keeps its +// tsup setup. tsdown-migrate would rewrite those declarations to tsdown. +function keepsTsup(packagePath: string): boolean { + const pkg = readPackageJsonIfExists(path.join(packagePath, 'package.json')); + return !!pkg && declaresRuntimeDependency(pkg, 'tsup'); +} + +function hasReplaceableTsup(packagePath: string): boolean { + const pkg = readPackageJsonIfExists(path.join(packagePath, 'package.json')); + return pkg?.devDependencies?.tsup !== undefined && !declaresRuntimeDependency(pkg, 'tsup'); +} + +function hasMigratableTsupConfig(packagePath: string): boolean { + return !!detectConfigs(packagePath).tsupConfig && !keepsTsup(packagePath); +} + export function detectTsupProject(projectPath: string, packages?: Array) { - const packageJsonPath = path.join(projectPath, 'package.json'); - let hasDependency = false; - if (fs.existsSync(packageJsonPath)) { - const pkg = readJsonFile(packageJsonPath) as { - devDependencies?: Record; - dependencies?: Record; - }; - hasDependency = !!(pkg.devDependencies?.tsup || pkg.dependencies?.tsup); - } - const configs = detectConfigs(projectPath); - const configFile = configs.tsupConfig; + let hasDependency = hasReplaceableTsup(projectPath); + const configFile = keepsTsup(projectPath) ? undefined : detectConfigs(projectPath).tsupConfig; let hasConfig = !!configFile; for (const wp of packages ?? []) { const workspacePath = path.join(projectPath, wp.path); - hasConfig ||= !!detectConfigs(workspacePath).tsupConfig; - - if (!hasDependency) { - const workspacePackageJsonPath = path.join(workspacePath, 'package.json'); - if (fs.existsSync(workspacePackageJsonPath)) { - const workspacePackageJson = readJsonFile(workspacePackageJsonPath) as { - devDependencies?: Record; - dependencies?: Record; - }; - hasDependency = !!( - workspacePackageJson.devDependencies?.tsup || workspacePackageJson.dependencies?.tsup - ); - } - } + hasConfig ||= hasMigratableTsupConfig(workspacePath); + hasDependency ||= hasReplaceableTsup(workspacePath); } return { hasDependency, hasConfig, configFile }; @@ -425,7 +426,7 @@ export async function migrateTsupToTsdown( const rootPath = path.resolve(projectPath); const targets = [rootPath, ...(packages ?? []).map((p) => path.resolve(rootPath, p.path))]; const tsupTargets = targets.filter((target) => - target === rootPath ? !!tsupConfigFile : !!detectConfigs(target).tsupConfig, + target === rootPath ? !!tsupConfigFile && !keepsTsup(target) : hasMigratableTsupConfig(target), ); const configCollisions = collectTsupConfigCollisions(tsupTargets); if (configCollisions.length > 0) { @@ -614,11 +615,7 @@ function rewriteTsupPackageJson(packageJsonPath: string, preserveTsupDependency if (!fs.existsSync(packageJsonPath)) { return; } - editJsonFile<{ - scripts?: Record; - devDependencies?: Record; - dependencies?: Record; - }>(packageJsonPath, (pkg) => { + editJsonFile }>(packageJsonPath, (pkg) => { let changed = false; // tsdown-migrate rewrites the command to tsdown. Vite+ Pack automatically // loads standard tsdown config files and does not accept `--config`, so @@ -633,13 +630,8 @@ function rewriteTsupPackageJson(packageJsonPath: string, preserveTsupDependency // Remove any tsup dependency left by the external migrator. The tsdown // dependency is removed later because vite-plus bundles it. - if (!preserveTsupDependency) { - for (const field of ['devDependencies', 'dependencies'] as const) { - if (pkg[field]?.tsup) { - delete pkg[field].tsup; - changed = true; - } - } + if (!preserveTsupDependency && removeReplacedDevDependency(pkg, 'tsup')) { + changed = true; } return changed ? pkg : undefined; }); diff --git a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts index bcb0737a07..e2b9cf5677 100644 --- a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts +++ b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts @@ -75,9 +75,10 @@ import { hasProviderPeerDependency, resolveProviderPeerSpec, OPT_IN_BROWSER_PROVIDERS, - OXLINT_PLUGIN_API_PACKAGES, - packageOwnsOxlintApi, bundledPackagesToRemove, + declaresRuntimeDependency, + REMOVE_PACKAGES, + removeBundledDevDependencies, VITEST_IS_MANAGED_OVERRIDE, managedOverrideKey, pinnedPackageManagerVersion, @@ -301,8 +302,8 @@ function reconcileVitePlusBootstrapPackage( supportCatalog: boolean, ensureVitePlus: boolean, catalogDependencyResolver?: CatalogDependencyResolver, - // An installed provider references the shared catalog entry added for a sibling. - browserCatalogAdditions: ReadonlySet = new Set(), + // Catalog entries that migration keeps or adds. An installed provider references one added for a sibling. + catalogAdditions: ReadonlySet = new Set(), retainedImportDependencies?: RetainedImportDependencies, ): boolean { const before = JSON.stringify(pkg); @@ -366,7 +367,7 @@ function reconcileVitePlusBootstrapPackage( provider, installGroupEntry.dependencyField, packageManager, - browserCatalogAdditions.has(provider) + catalogAdditions.has(provider) ? supportCatalog && packageManager !== PackageManager.bun : supportCatalog, catalogDependencyResolver, @@ -394,34 +395,10 @@ function reconcileVitePlusBootstrapPackage( // Match the fresh migration and catalog cleanup. A preserved browser import // still needs its declared browser dependency in this package. - const ownsOxlintApi = packageOwnsOxlintApi(pkg); - for (const bundledPackage of bundledPackagesToRemove( - retainedImportDependencies?.browser.get(projectPath), - )) { - for (const dependencies of installGroups) { - if ( - ownsOxlintApi && - dependencies !== undefined && - dependencies === pkg.dependencies && - (OXLINT_PLUGIN_API_PACKAGES as ReadonlyArray).includes(bundledPackage) - ) { - // A published plugin keeps the runtime dependency that supplies its - // upstream imports, as the fresh path does. Its `catalog:` reference - // becomes the concrete range because the catalog entry is deleted. - const current = dependencies[bundledPackage]; - if (current?.startsWith('catalog:')) { - const resolved = catalogDependencyResolver?.(current, bundledPackage); - if (resolved) { - dependencies[bundledPackage] = resolved; - } - } - continue; - } - if (dependencies?.[bundledPackage] !== undefined) { - delete dependencies[bundledPackage]; - } - } - } + removeBundledDevDependencies( + pkg, + bundledPackagesToRemove(retainedImportDependencies?.browser.get(projectPath)), + ); if (usesAnyOptInProvider && packageManager === PackageManager.npm) { const viteAlreadyDirect = installGroups.some( @@ -505,8 +482,11 @@ export function bootstrapProjectPaths( return getWorkspaceProjectPaths({ rootDir, packages }); } -/** Catalog entries needed for retained browser imports and newly installed providers. */ -export function collectBrowserCatalogAdditions( +/** + * Catalog entries needed for retained browser imports, newly installed + * providers, and bundled packages that a package declares at runtime. + */ +export function collectCatalogAdditions( rootDir: string, packages?: Array, retainedBrowserPackages?: RetainedImportDependencies['browser'], @@ -525,6 +505,12 @@ export function collectBrowserCatalogAdditions( continue; } const pkg = readJsonFile(packageJsonPath) as BootstrapPackageJson; + // Migration keeps these declarations, and a `catalog:` reference among them still needs its entry. + for (const name of REMOVE_PACKAGES) { + if (declaresRuntimeDependency(pkg, name)) { + names.add(name); + } + } const sourceModes = precomputedSourceModes?.get(packagePath) ?? collectProviderSourceModes(packagePath); const installGroups = [pkg.devDependencies, pkg.dependencies, pkg.optionalDependencies]; @@ -689,7 +675,7 @@ export function detectVitePlusBootstrapPending( // Match the actual reconcile so an already-installed provider whose catalog // entry the migration will add is reported pending (its spec must become // `catalog:`). See #2005. - const browserCatalogAdditions = collectBrowserCatalogAdditions( + const catalogAdditions = collectCatalogAdditions( projectPath, packages, retainedImportDependencies?.browser, @@ -710,7 +696,7 @@ export function detectVitePlusBootstrapPending( supportCatalog, index === 0, catalogDependencyResolver, - browserCatalogAdditions, + catalogAdditions, retainedImportDependencies, ) ) { @@ -1035,7 +1021,7 @@ export function ensureVitePlusBootstrap( projectPath, workspaceInfo.packages, ); - const browserCatalogAdditions = collectBrowserCatalogAdditions( + const catalogAdditions = collectCatalogAdditions( projectPath, workspaceInfo.packages, retainedImportDependencies?.browser, @@ -1066,7 +1052,7 @@ export function ensureVitePlusBootstrap( usesVitest, vitestEcosystemPackages, false, - browserCatalogAdditions, + catalogAdditions, usesWebdriverio, workspaceInfo.downloadPackageManager.version, ); @@ -1082,7 +1068,7 @@ export function ensureVitePlusBootstrap( supportCatalog, true, catalogDependencyResolver, - browserCatalogAdditions, + catalogAdditions, retainedImportDependencies, ); @@ -1182,7 +1168,7 @@ export function ensureVitePlusBootstrap( supportCatalog, false, catalogDependencyResolver, - browserCatalogAdditions, + catalogAdditions, retainedImportDependencies, ); if ( @@ -1241,7 +1227,7 @@ export function ensureVitePlusBootstrap( usesVitest, vitestEcosystemPackages, true, - browserCatalogAdditions, + catalogAdditions, usesWebdriverio, workspaceInfo.downloadPackageManager.version, ); @@ -1269,7 +1255,7 @@ export function ensureVitePlusBootstrap( projectPath, usesVitest, vitestEcosystemPackages, - browserCatalogAdditions, + catalogAdditions, supportCatalog, yarnSupportsPreapprovedPackages(workspaceInfo.downloadPackageManager.version), ); @@ -1283,7 +1269,7 @@ export function ensureVitePlusBootstrap( vitestEcosystemPackages, usesWebdriverio, workspaceInfo.downloadPackageManager.version, - browserCatalogAdditions, + catalogAdditions, ); const after = fs.readFileSync(packageJsonPath, 'utf8'); result.packageJson = result.packageJson || before !== after; diff --git a/packages/cli/src/oxlint-plugin.ts b/packages/cli/src/oxlint-plugin.ts index ea46f9be4e..a255285687 100644 --- a/packages/cli/src/oxlint-plugin.ts +++ b/packages/cli/src/oxlint-plugin.ts @@ -304,20 +304,15 @@ function nearestPackageKeepsVitest(filename: string): boolean { } // Match the migrator's published-plugin exemption. Development-only APIs do not -// exempt a package; optional @oxlint/plugins is a consumer runtime dependency. +// exempt a package; optional declarations are consumer runtime dependencies. function nearestPackageOwnsOxlintApi(filename: string): boolean { - return nearestPackageMatches( - filename, - oxlintOwnerPackageCache, - (pkg) => - (isObjectValue(pkg.optionalDependencies) && - pkg.optionalDependencies[OXLINT_PLUGINS_PACKAGE] !== undefined) || - [pkg.dependencies, pkg.peerDependencies].some( - (dependencies) => - isObjectValue(dependencies) && - (dependencies[OXLINT_PACKAGE] !== undefined || - dependencies[OXLINT_PLUGINS_PACKAGE] !== undefined), - ), + return nearestPackageMatches(filename, oxlintOwnerPackageCache, (pkg) => + [pkg.dependencies, pkg.optionalDependencies, pkg.peerDependencies].some( + (dependencies) => + isObjectValue(dependencies) && + (dependencies[OXLINT_PACKAGE] !== undefined || + dependencies[OXLINT_PLUGINS_PACKAGE] !== undefined), + ), ); }