Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 34 additions & 29 deletions crates/vp_migration/src/import_rewriter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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<PathBuf>,
}

Expand Down Expand Up @@ -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-`
Expand All @@ -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()
Expand Down Expand Up @@ -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]
Expand Down
4 changes: 3 additions & 1 deletion docs/guide/migrate-rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,8 @@ 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.

### Version Selection

- `vite-plus` is pinned to the concrete version of the CLI running the migration, never the `latest` dist-tag.
Expand Down Expand Up @@ -239,7 +241,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`.

Expand Down
12 changes: 5 additions & 7 deletions packages/cli/src/__tests__/oxlint-plugin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
{
Expand Down Expand Up @@ -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,
Expand Down
52 changes: 47 additions & 5 deletions packages/cli/src/migration/__tests__/migrator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
});
},
Expand Down Expand Up @@ -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:');
});

Expand Down Expand Up @@ -5634,7 +5634,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'));
Expand All @@ -5645,7 +5646,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', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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' });
});
});

Expand Down
28 changes: 14 additions & 14 deletions packages/cli/src/migration/migrator/orchestrators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
applyBuildAllowanceToPackageJsonPnpm,
applyYarnWorkspaceHoistingFix,
cleanupDeprecatedTsconfigOptions,
collectBrowserCatalogAdditions,
collectCatalogAdditions,
collectOxlintDependencyNames,
collectOxlintOwnerDirs,
collectRetainedImportDependencies,
Expand Down Expand Up @@ -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.
Expand All @@ -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,
Expand Down Expand Up @@ -274,7 +274,7 @@ export function rewriteStandaloneProject(
usesVitest,
retainedVitestModule,
requiredVitestPeer,
browserCatalogAdditions,
catalogAdditions,
retainedImportDependencies.browser.get(projectPath),
);

Expand Down Expand Up @@ -316,7 +316,7 @@ export function rewriteStandaloneProject(
usesVitest,
vitestEcosystemPackages,
usePnpmWorkspaceYaml,
browserCatalogAdditions,
catalogAdditions,
usesWebdriverio,
workspaceInfo.downloadPackageManager.version,
);
Expand All @@ -343,7 +343,7 @@ export function rewriteStandaloneProject(
projectPath,
usesVitest,
vitestEcosystemPackages,
browserCatalogAdditions,
catalogAdditions,
supportCatalog,
yarnSupportsPreapprovedPackages(workspaceInfo.downloadPackageManager.version),
);
Expand Down Expand Up @@ -430,7 +430,7 @@ export function rewriteMonorepo(
workspaceInfo.rootDir,
workspaceInfo.packages,
);
const browserCatalogAdditions = collectBrowserCatalogAdditions(
const catalogAdditions = collectCatalogAdditions(
workspaceInfo.rootDir,
workspaceInfo.packages,
retainedImportDependencies.browser,
Expand All @@ -454,7 +454,7 @@ export function rewriteMonorepo(
workspaceInfo.rootDir,
workspaceUsesVitest,
vitestEcosystemPackages,
browserCatalogAdditions,
catalogAdditions,
supportCatalog,
yarnSupportsPreapprovedPackages(workspaceInfo.downloadPackageManager.version),
);
Expand All @@ -481,7 +481,7 @@ export function rewriteMonorepo(
workspaceUsesVitest,
vitestEcosystemPackages,
usePnpmWorkspaceSettings,
browserCatalogAdditions,
catalogAdditions,
usesWebdriverio,
workspaceInfo.downloadPackageManager.version,
);
Expand All @@ -499,7 +499,7 @@ export function rewriteMonorepo(
vitestEcosystemPackages,
usesWebdriverio,
workspaceInfo.downloadPackageManager.version,
browserCatalogAdditions,
catalogAdditions,
);
}
// (mergeViteConfigFiles below will sanitize the merged lint config
Expand All @@ -524,7 +524,7 @@ export function rewriteMonorepo(
workspaceContext,
true,
supportCatalog,
browserCatalogAdditions,
catalogAdditions,
);
}

Expand Down Expand Up @@ -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<string> = new Set(),
// Catalog entries that migration keeps or adds. An installed provider references one added for a sibling.
catalogAdditions: ReadonlySet<string> = new Set(),
): void {
cleanupDeprecatedTsconfigOptions(projectPath, silent, report);
rewriteTsconfigTypes(projectPath, silent, report);
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading