diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/nested-catalogs.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/nested-catalogs.json new file mode 100644 index 0000000000..64567eb456 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/nested-catalogs.json @@ -0,0 +1,15 @@ +{ + "name": "plain-workspace", + "private": true, + "packageManager": "bun@1.4.0", + "workspaces": { + "packages": ["apps/*"], + "catalog": { + "is-number": "7.0.0" + } + }, + "catalog": { + "vite": "0.0.0-unused", + "vite-plus": "0.0.0-unused" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/package.json new file mode 100644 index 0000000000..269eb0fa3f --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/package.json @@ -0,0 +1,6 @@ +{ + "name": "plain-workspace", + "private": true, + "packageManager": "bun@1.4.0", + "workspaces": ["apps/*"] +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml new file mode 100644 index 0000000000..75d5fe1d79 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml @@ -0,0 +1,125 @@ +[[case]] +name = "create_existing_bun_workspace" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Creating an application supplies missing Bun catalog entries before installation." +steps = [ + { argv = ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "stat-file", "bun.lock", "--assert", "file"], + ["vpt", "print-file", "package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, +] + +[[case]] +name = "create_existing_bun_split_default_catalog" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Creating and migrating a member keeps Bun's shared default catalog installable without duplicating entries." +steps = [ + { argv = ["vpt", "json-edit", "package.json", "packageManager", "bun@1.4.4"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "catalog.vite", "npm:@voidzero-dev/vite-plus-core@*"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "catalog.vite-plus", "*"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "catalogs.default.react", "19.2.0"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "devDependencies.react", "catalog:default"], snapshot = false }, + { argv = ["vp", "install"], snapshot = false }, + { argv = ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "migrate", "--no-interactive"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, +] + +[[case]] +name = "create_existing_bun_named_default_catalog" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Creating and migrating a member reuses Bun's named default catalog without creating a duplicate shorthand catalog." +steps = [ + { argv = ["vpt", "json-edit", "package.json", "packageManager", "bun@1.4.4"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "catalogs.default.vite-plus", "*"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "catalogs.default.react", "19.2.0"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "devDependencies.react", "catalog:default"], snapshot = false }, + { argv = ["vp", "install"], snapshot = false }, + { argv = ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "migrate", "--no-interactive"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, +] + +[[case]] +name = "migrate_existing_bun_legacy_default_catalogs" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Bun 1.2.14 keeps catalog and catalogs.default separate through migration and a second bootstrap pass." +steps = [ + { argv = ["vpt", "json-edit", "package.json", "packageManager", "bun@1.2.14"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "workspaces", '{"packages":["apps/*"],"catalog":{"vite":"npm:@voidzero-dev/vite-plus-core@*"},"catalogs":{"default":{"react":"19.2.0"}}}'], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "devDependencies", '{"vite":"catalog:","react":"catalog:default"}'], snapshot = false }, + { argv = ["vp", "install"], snapshot = false, timeout = 240000 }, + { argv = ["vp", "migrate", "--no-interactive"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "migrate", "--no-interactive"], snapshot = false, timeout = 240000 }, + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, +] + +[[case]] +name = "create_existing_bun_legacy_default_catalogs" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Bun 1.3.14 still needs shorthand references completed in catalog rather than catalogs.default." +steps = [ + { argv = ["vpt", "json-edit", "package.json", "packageManager", "bun@1.3.14"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "workspaces", '{"packages":["apps/*"],"catalog":{"vite":"npm:@voidzero-dev/vite-plus-core@*"},"catalogs":{"default":{"react":"19.2.0"}}}'], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "devDependencies", '{"vite":"catalog:","react":"catalog:default"}'], snapshot = false }, + { argv = ["vp", "install"], snapshot = false, timeout = 240000 }, + { argv = ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "package.json"], + ["vpt", "print-file", "apps/web/package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, +] + +[[case]] +name = "create_existing_bun_aligned_vitest_catalog" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Creating a member completes aligned Vitest entries in the named toolchain catalog without changing the default catalog." +steps = [ + { argv = ["vpt", "cp", "vitest-template.config.ts", "vite.config.ts"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "catalog.@vitest/utils", "^5.0.0"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "catalogs.tools.vite-plus", "*"], snapshot = false }, + { argv = ["vp", "install"], snapshot = false }, + { argv = ["vp", "create", "vitest-app", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "apps/web/package.json"], + ["vpt", "print-file", "package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, +] + +[[case]] +name = "create_existing_bun_nested_catalogs" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Bun uses nested catalog configuration without falling back to ignored root entries." +steps = [ + { argv = ["vpt", "cp", "nested-catalogs.json", "package.json"], snapshot = false }, + { argv = ["vp", "install"], comment = "The ignored root catalog does not prevent installation before creation.", snapshot = false }, + { argv = ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "stat-file", "bun.lock", "--assert", "file"], + ["vpt", "print-file", "package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_aligned_vitest_catalog.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_aligned_vitest_catalog.md new file mode 100644 index 0000000000..aa50a558ee --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_aligned_vitest_catalog.md @@ -0,0 +1,56 @@ +# create_existing_bun_aligned_vitest_catalog + +Creating a member completes aligned Vitest entries in the named toolchain catalog without changing the default catalog. + +## `vpt cp vitest-template.config.ts vite.config.ts` + + +## `vpt json-edit package.json catalog.@vitest/utils ^5.0.0` + + +## `vpt json-edit package.json catalogs.tools.vite-plus *` + + +## `vp install` + + +## `vp create vitest-app --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt print-file apps/web/package.json` + +``` +{ + "name": "web", + "private": true, + "devDependencies": { + "@vitest/utils": "catalog:tools", + "vite-plus": "catalog:tools" + } +} +``` + +## `vpt print-file package.json` + +``` +{ + "catalog": { + "@vitest/utils": "^5.0.0" + }, + "catalogs": { + "tools": { + "vite-plus": "*", + "@vitest/utils": "" + } + }, + "name": "plain-workspace", + "packageManager": "bun@1.4.0", + "private": true, + "workspaces": [ + "apps/*" + ] +} +``` + +## `vp install --frozen-lockfile` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_legacy_default_catalogs.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_legacy_default_catalogs.md new file mode 100644 index 0000000000..34fb4b035e --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_legacy_default_catalogs.md @@ -0,0 +1,73 @@ +# create_existing_bun_legacy_default_catalogs + +Bun 1.3.14 still needs shorthand references completed in catalog rather than catalogs.default. + +## `vpt json-edit package.json packageManager bun@1.3.14` + + +## `vpt json-edit package.json workspaces '{"packages":["apps/*"],"catalog":{"vite":"npm:@voidzero-dev/vite-plus-core@*"},"catalogs":{"default":{"react":"19.2.0"}}}'` + + +## `vpt json-edit package.json devDependencies '{"vite":"catalog:","react":"catalog:default"}'` + + +## `vp install` + + +## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt print-file package.json` + +``` +{ + "devDependencies": { + "react": "catalog:default", + "vite": "catalog:" + }, + "name": "plain-workspace", + "packageManager": "bun@1.3.14", + "private": true, + "workspaces": { + "catalog": { + "vite": "npm:@voidzero-dev/vite-plus-core@*", + "vite-plus": "" + }, + "catalogs": { + "default": { + "react": "19.2.0" + } + }, + "packages": [ + "apps/*" + ] + } +} +``` + +## `vpt print-file apps/web/package.json` + +``` +{ + "name": "web", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vp dev", + "build": "tsc && vp build", + "preview": "vp preview" + }, + "devDependencies": { + "typescript": "~7.0.2", + "vite": "catalog:", + "vite-plus": "catalog:" + } +} +``` + +## `vp install --frozen-lockfile` + + +## `cd apps/web && vp run build` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_named_default_catalog.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_named_default_catalog.md new file mode 100644 index 0000000000..ab00799adb --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_named_default_catalog.md @@ -0,0 +1,87 @@ +# create_existing_bun_named_default_catalog + +Creating and migrating a member reuses Bun's named default catalog without creating a duplicate shorthand catalog. + +## `vpt json-edit package.json packageManager bun@1.4.4` + + +## `vpt json-edit package.json catalogs.default.vite-plus *` + + +## `vpt json-edit package.json catalogs.default.react 19.2.0` + + +## `vpt json-edit package.json devDependencies.react catalog:default` + + +## `vp install` + + +## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt print-file package.json` + +``` +{ + "catalogs": { + "default": { + "react": "19.2.0", + "vite-plus": "*", + "vite": "npm:@voidzero-dev/vite-plus-core@" + } + }, + "devDependencies": { + "react": "catalog:default" + }, + "name": "plain-workspace", + "packageManager": "bun@1.4.4", + "private": true, + "workspaces": [ + "apps/*" + ] +} +``` + +## `vp install --frozen-lockfile` + + +## `vp migrate --no-interactive` + + +## `vpt print-file package.json` + +``` +{ + "name": "plain-workspace", + "private": true, + "workspaces": [ + "apps/*" + ], + "scripts": { + "prepare": "vp config" + }, + "devDependencies": { + "react": "catalog:default", + "vite": "catalog:", + "vite-plus": "catalog:" + }, + "overrides": { + "vite": "catalog:" + }, + "packageManager": "bun@1.4.4", + "catalogs": { + "default": { + "react": "19.2.0", + "vite-plus": "", + "vite": "npm:@voidzero-dev/vite-plus-core@" + } + } +} +``` + +## `vp install --frozen-lockfile` + + +## `cd apps/web && vp run build` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_nested_catalogs.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_nested_catalogs.md new file mode 100644 index 0000000000..924568bdc0 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_nested_catalogs.md @@ -0,0 +1,50 @@ +# create_existing_bun_nested_catalogs + +Bun uses nested catalog configuration without falling back to ignored root entries. + +## `vpt cp nested-catalogs.json package.json` + + +## `vp install` + +The ignored root catalog does not prevent installation before creation. + + +## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt stat-file bun.lock --assert file` + +``` +bun.lock: file +``` + +## `vpt print-file package.json` + +``` +{ + "name": "plain-workspace", + "private": true, + "packageManager": "bun@1.4.0", + "workspaces": { + "packages": [ + "apps/*" + ], + "catalog": { + "is-number": "7.0.0", + "vite": "npm:@voidzero-dev/vite-plus-core@", + "vite-plus": "" + } + }, + "catalog": { + "vite": "0.0.0-unused", + "vite-plus": "" + } +} +``` + +## `vp install --frozen-lockfile` + + +## `cd apps/web && vp run build` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_split_default_catalog.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_split_default_catalog.md new file mode 100644 index 0000000000..edc15c80cf --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_split_default_catalog.md @@ -0,0 +1,94 @@ +# create_existing_bun_split_default_catalog + +Creating and migrating a member keeps Bun's shared default catalog installable without duplicating entries. + +## `vpt json-edit package.json packageManager bun@1.4.4` + + +## `vpt json-edit package.json catalog.vite npm:@voidzero-dev/vite-plus-core@*` + + +## `vpt json-edit package.json catalog.vite-plus *` + + +## `vpt json-edit package.json catalogs.default.react 19.2.0` + + +## `vpt json-edit package.json devDependencies.react catalog:default` + + +## `vp install` + + +## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt print-file package.json` + +``` +{ + "catalog": { + "vite": "npm:@voidzero-dev/vite-plus-core@*", + "vite-plus": "*" + }, + "catalogs": { + "default": { + "react": "19.2.0" + } + }, + "devDependencies": { + "react": "catalog:default" + }, + "name": "plain-workspace", + "packageManager": "bun@1.4.4", + "private": true, + "workspaces": [ + "apps/*" + ] +} +``` + +## `vp install --frozen-lockfile` + + +## `vp migrate --no-interactive` + + +## `vpt print-file package.json` + +``` +{ + "name": "plain-workspace", + "private": true, + "workspaces": [ + "apps/*" + ], + "scripts": { + "prepare": "vp config" + }, + "devDependencies": { + "react": "catalog:default", + "vite": "catalog:", + "vite-plus": "catalog:" + }, + "overrides": { + "vite": "catalog:" + }, + "packageManager": "bun@1.4.4", + "catalog": { + "vite": "npm:@voidzero-dev/vite-plus-core@", + "vite-plus": "" + }, + "catalogs": { + "default": { + "react": "19.2.0" + } + } +} +``` + +## `vp install --frozen-lockfile` + + +## `cd apps/web && vp run build` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_workspace.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_workspace.md new file mode 100644 index 0000000000..fb50eb0116 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_workspace.md @@ -0,0 +1,35 @@ +# create_existing_bun_workspace + +Creating an application supplies missing Bun catalog entries before installation. + +## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt stat-file bun.lock --assert file` + +``` +bun.lock: file +``` + +## `vpt print-file package.json` + +``` +{ + "name": "plain-workspace", + "private": true, + "packageManager": "bun@1.4.0", + "workspaces": [ + "apps/*" + ], + "catalog": { + "vite": "npm:@voidzero-dev/vite-plus-core@", + "vite-plus": "" + } +} +``` + +## `vp install --frozen-lockfile` + + +## `cd apps/web && vp run build` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/migrate_existing_bun_legacy_default_catalogs.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/migrate_existing_bun_legacy_default_catalogs.md new file mode 100644 index 0000000000..3d01051925 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/migrate_existing_bun_legacy_default_catalogs.md @@ -0,0 +1,62 @@ +# migrate_existing_bun_legacy_default_catalogs + +Bun 1.2.14 keeps catalog and catalogs.default separate through migration and a second bootstrap pass. + +## `vpt json-edit package.json packageManager bun@1.2.14` + + +## `vpt json-edit package.json workspaces '{"packages":["apps/*"],"catalog":{"vite":"npm:@voidzero-dev/vite-plus-core@*"},"catalogs":{"default":{"react":"19.2.0"}}}'` + + +## `vpt json-edit package.json devDependencies '{"vite":"catalog:","react":"catalog:default"}'` + + +## `vp install` + + +## `vp migrate --no-interactive` + + +## `vpt print-file package.json` + +``` +{ + "name": "plain-workspace", + "private": true, + "workspaces": { + "catalog": { + "vite": "npm:@voidzero-dev/vite-plus-core@", + "vite-plus": "" + }, + "catalogs": { + "default": { + "react": "19.2.0" + } + }, + "packages": [ + "apps/*" + ] + }, + "scripts": { + "prepare": "vp config" + }, + "devDependencies": { + "react": "catalog:default", + "vite": "catalog:", + "vite-plus": "catalog:" + }, + "overrides": { + "vite": "catalog:" + }, + "packageManager": "bun@1.2.14" +} +``` + +## `vp install --frozen-lockfile` + + +## `vp migrate --no-interactive` + + +## `vp install --frozen-lockfile` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template.config.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template.config.ts new file mode 100644 index 0000000000..638a6e72b8 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template.config.ts @@ -0,0 +1,7 @@ +export default { + create: { + templates: [ + { name: 'vitest-app', description: 'Create a member with Vitest utilities.', template: './vitest-template' }, + ], + }, +}; diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template/index.mjs b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template/index.mjs new file mode 100644 index 0000000000..c5486fd49d --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template/index.mjs @@ -0,0 +1,12 @@ +#!/usr/bin/env node +import { mkdirSync, writeFileSync } from 'node:fs'; + +mkdirSync('web', { recursive: true }); +writeFileSync('web/package.json', JSON.stringify({ + name: 'web', + private: true, + devDependencies: { + 'vite-plus': 'catalog:tools', + '@vitest/utils': '^5.0.0', + }, +}, null, 2) + '\n'); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template/package.json new file mode 100644 index 0000000000..a6af6ce81d --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template/package.json @@ -0,0 +1,5 @@ +{ + "name": "vitest-template", + "private": true, + "bin": "index.mjs" +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_pnpm_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_pnpm_workspace/snapshots.toml index e6b82e155f..758e58e7b1 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_pnpm_workspace/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_pnpm_workspace/snapshots.toml @@ -11,3 +11,19 @@ steps = [ { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, ] + +[[case]] +name = "migrate_existing_pnpm_catalog_order" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Migration writes Vite+ into the same catalog selected for dependency references when a named catalog precedes the default." +steps = [ + { argv = ["vpt", "write-file", "pnpm-workspace.yaml", "packages:\n - apps/*\ncatalogs:\n legacy:\n vite: 'npm:@voidzero-dev/vite-plus-core@*'\n default:\n vite: 'npm:@voidzero-dev/vite-plus-core@*'\n"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "devDependencies.vite", "catalog:legacy"], snapshot = false }, + { argv = ["vp", "install"], snapshot = false, timeout = 240000 }, + { argv = ["vp", "migrate", "--no-interactive"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "package.json"], + ["vpt", "print-file", "pnpm-workspace.yaml"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_pnpm_workspace/snapshots/migrate_existing_pnpm_catalog_order.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_pnpm_workspace/snapshots/migrate_existing_pnpm_catalog_order.md new file mode 100644 index 0000000000..b32891fa47 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_pnpm_workspace/snapshots/migrate_existing_pnpm_catalog_order.md @@ -0,0 +1,57 @@ +# migrate_existing_pnpm_catalog_order + +Migration writes Vite+ into the same catalog selected for dependency references when a named catalog precedes the default. + +## `vpt write-file pnpm-workspace.yaml 'packages: + - apps/* +catalogs: + legacy: + vite: '\''npm:@voidzero-dev/vite-plus-core@*'\'' + default: + vite: '\''npm:@voidzero-dev/vite-plus-core@*'\'' +'` + + +## `vpt json-edit package.json devDependencies.vite catalog:legacy` + + +## `vp install` + + +## `vp migrate --no-interactive` + + +## `vpt print-file package.json` + +``` +{ + "name": "plain-workspace", + "private": true, + "scripts": { + "prepare": "vp config" + }, + "devDependencies": { + "vite": "catalog:legacy", + "vite-plus": "catalog:legacy" + }, + "packageManager": "pnpm@11.24.0" +} +``` + +## `vpt print-file pnpm-workspace.yaml` + +``` +packages: + - apps/* +catalogs: + legacy: + vite: npm:@voidzero-dev/vite-plus-core@ + vite-plus: + default: + vite: npm:@voidzero-dev/vite-plus-core@ +overrides: + vite@*: catalog:legacy +``` + +## `vp install --frozen-lockfile` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/.yarnrc.yml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/.yarnrc.yml new file mode 100644 index 0000000000..3186f3f079 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/.yarnrc.yml @@ -0,0 +1 @@ +nodeLinker: node-modules diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/package.json new file mode 100644 index 0000000000..93359cc191 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/package.json @@ -0,0 +1,6 @@ +{ + "name": "plain-workspace", + "private": true, + "packageManager": "yarn@4.18.1", + "workspaces": ["apps/*"] +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml new file mode 100644 index 0000000000..e6b7a62a64 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml @@ -0,0 +1,83 @@ +[[case]] +name = "create_existing_yarn_workspace" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Creating an application supplies missing Yarn catalog entries before installation." +env = { YARN_NPM_MINIMAL_AGE_GATE = "0" } +steps = [ + { argv = ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "stat-file", "yarn.lock", "--assert", "file"], + ["vpt", "print-file", ".yarnrc.yml"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, +] + +[[case]] +name = "create_existing_yarn_named_default_catalog" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +env = { YARN_NPM_MINIMAL_AGE_GATE = "0" } +comment = "Yarn's named default catalog must remain catalog:default, not catalog:." +steps = [ + { argv = ["vp", "create", "vite:application", "--directory", "apps/seed", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + { argv = ["vpt", "replace-file-content", ".yarnrc.yml", "catalog:\n", "catalogs:\n default:\n"], snapshot = false }, + { argv = ["vpt", "replace-file-content", ".yarnrc.yml", " vite:", " vite:"], snapshot = false }, + { argv = ["vpt", "replace-file-content", ".yarnrc.yml", " vite-plus:", " vite-plus:"], snapshot = false }, + { argv = ["vpt", "json-edit", "apps/seed/package.json", "devDependencies.vite", "catalog:default"], snapshot = false }, + { argv = ["vpt", "json-edit", "apps/seed/package.json", "devDependencies.vite-plus", "catalog:default"], snapshot = false }, + { argv = ["vp", "install"], comment = "Verify that the existing workspace installs before adding another app.", snapshot = false }, + { argv = ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", ".yarnrc.yml"], + ["vpt", "print-file", "apps/web/package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, +] + +[[case]] +name = "create_existing_yarn_aligned_vitest_catalog" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +env = { YARN_NPM_MINIMAL_AGE_GATE = "0" } +comment = "Creating a member completes aligned Vitest entries in the named toolchain catalog without changing the default catalog." +steps = [ + { argv = ["vpt", "cp", "vitest-template.config.ts", "vite.config.ts"], snapshot = false }, + { argv = ["vpt", "write-file", ".yarnrc.yml", "nodeLinker: node-modules\ncatalog:\n '@vitest/utils': '^5.0.0'\ncatalogs:\n tools:\n vite-plus: '*'\n"], snapshot = false }, + { argv = ["vp", "install"], snapshot = false }, + { argv = ["vp", "create", "vitest-app", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "apps/web/package.json"], + ["vpt", "print-file", ".yarnrc.yml"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, +] + +[[case]] +name = "create_existing_yarn_without_catalog_support" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Yarn before 4.10 receives concrete versions instead of unsupported catalog references." +steps = [ + { argv = ["vpt", "json-edit", "package.json", "packageManager", "yarn@4.9.0"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "resolutions.typescript", "5.9.3"], comment = "Yarn 4.9's built-in TypeScript patch predates TypeScript 7.", snapshot = false }, + { argv = ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "stat-file", "yarn.lock", "--assert", "file"], + ["vpt", "print-file", "apps/web/package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, +] + +[[case]] +name = "create_existing_yarn_template_catalog_without_support" +vp = "local" +local-registry = true +comment = "A template's catalog reference must not add catalog settings that Yarn before 4.10 rejects." +steps = [ + { argv = ["vpt", "json-edit", "package.json", "packageManager", "yarn@4.9.0"], snapshot = false }, + { argv = ["vpt", "cp", "vitest-template.config.ts", "vite.config.ts"], snapshot = false }, + { argv = ["vpt", "write-file", ".yarnrc.yml", "nodeLinker: node-modules\n"], snapshot = false }, + { argv = ["vp", "create", "vitest-app", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", ".yarnrc.yml"], + { argv = ["yarn", "config", "get", "nodeLinker"], comment = "Yarn still accepts the root configuration." }, +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_aligned_vitest_catalog.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_aligned_vitest_catalog.md new file mode 100644 index 0000000000..88399ba958 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_aligned_vitest_catalog.md @@ -0,0 +1,49 @@ +# create_existing_yarn_aligned_vitest_catalog + +Creating a member completes aligned Vitest entries in the named toolchain catalog without changing the default catalog. + +## `vpt cp vitest-template.config.ts vite.config.ts` + + +## `vpt write-file .yarnrc.yml 'nodeLinker: node-modules +catalog: + '\''@vitest/utils'\'': '\''^5.0.0'\'' +catalogs: + tools: + vite-plus: '\''*'\'' +'` + + +## `vp install` + + +## `vp create vitest-app --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt print-file apps/web/package.json` + +``` +{ + "name": "web", + "private": true, + "devDependencies": { + "@vitest/utils": "catalog:tools", + "vite-plus": "catalog:tools" + } +} +``` + +## `vpt print-file .yarnrc.yml` + +``` +nodeLinker: node-modules +catalog: + '@vitest/utils': '^5.0.0' +catalogs: + tools: + vite-plus: '*' + '@vitest/utils': +``` + +## `vp install --frozen-lockfile` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_named_default_catalog.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_named_default_catalog.md new file mode 100644 index 0000000000..5b554c297a --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_named_default_catalog.md @@ -0,0 +1,69 @@ +# create_existing_yarn_named_default_catalog + +Yarn's named default catalog must remain catalog:default, not catalog:. + +## `vp create vite:application --directory apps/seed --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt replace-file-content .yarnrc.yml 'catalog: +' 'catalogs: + default: +'` + + +## `vpt replace-file-content .yarnrc.yml ' vite:' ' vite:'` + + +## `vpt replace-file-content .yarnrc.yml ' vite-plus:' ' vite-plus:'` + + +## `vpt json-edit apps/seed/package.json devDependencies.vite catalog:default` + + +## `vpt json-edit apps/seed/package.json devDependencies.vite-plus catalog:default` + + +## `vp install` + +Verify that the existing workspace installs before adding another app. + + +## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt print-file .yarnrc.yml` + +``` +nodeLinker: node-modules +catalogs: + default: + vite: npm:@voidzero-dev/vite-plus-core@ + vite-plus: +``` + +## `vpt print-file apps/web/package.json` + +``` +{ + "name": "web", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vp dev", + "build": "tsc && vp build", + "preview": "vp preview" + }, + "devDependencies": { + "typescript": "~7.0.2", + "vite": "catalog:default", + "vite-plus": "catalog:default" + } +} +``` + +## `vp install --frozen-lockfile` + + +## `cd apps/web && vp run build` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_template_catalog_without_support.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_template_catalog_without_support.md new file mode 100644 index 0000000000..e8db335c2f --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_template_catalog_without_support.md @@ -0,0 +1,30 @@ +# create_existing_yarn_template_catalog_without_support + +A template's catalog reference must not add catalog settings that Yarn before 4.10 rejects. + +## `vpt json-edit package.json packageManager yarn@4.9.0` + + +## `vpt cp vitest-template.config.ts vite.config.ts` + + +## `vpt write-file .yarnrc.yml 'nodeLinker: node-modules +'` + + +## `vp create vitest-app --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt print-file .yarnrc.yml` + +``` +nodeLinker: node-modules +``` + +## `yarn config get nodeLinker` + +Yarn still accepts the root configuration. + +``` +node-modules +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_without_catalog_support.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_without_catalog_support.md new file mode 100644 index 0000000000..71c303a338 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_without_catalog_support.md @@ -0,0 +1,47 @@ +# create_existing_yarn_without_catalog_support + +Yarn before 4.10 receives concrete versions instead of unsupported catalog references. + +## `vpt json-edit package.json packageManager yarn@4.9.0` + + +## `vpt json-edit package.json resolutions.typescript 5.9.3` + +Yarn 4.9's built-in TypeScript patch predates TypeScript 7. + + +## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt stat-file yarn.lock --assert file` + +``` +yarn.lock: file +``` + +## `vpt print-file apps/web/package.json` + +``` +{ + "name": "web", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vp dev", + "build": "tsc && vp build", + "preview": "vp preview" + }, + "devDependencies": { + "typescript": "~7.0.2", + "vite": "npm:@voidzero-dev/vite-plus-core@", + "vite-plus": "" + } +} +``` + +## `vp install --frozen-lockfile` + + +## `cd apps/web && vp run build` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_workspace.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_workspace.md new file mode 100644 index 0000000000..e5b23038f2 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_workspace.md @@ -0,0 +1,27 @@ +# create_existing_yarn_workspace + +Creating an application supplies missing Yarn catalog entries before installation. + +## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt stat-file yarn.lock --assert file` + +``` +yarn.lock: file +``` + +## `vpt print-file .yarnrc.yml` + +``` +nodeLinker: node-modules +catalog: + vite: npm:@voidzero-dev/vite-plus-core@ + vite-plus: +``` + +## `vp install --frozen-lockfile` + + +## `cd apps/web && vp run build` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template.config.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template.config.ts new file mode 100644 index 0000000000..638a6e72b8 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template.config.ts @@ -0,0 +1,7 @@ +export default { + create: { + templates: [ + { name: 'vitest-app', description: 'Create a member with Vitest utilities.', template: './vitest-template' }, + ], + }, +}; diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template/index.mjs b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template/index.mjs new file mode 100644 index 0000000000..c5486fd49d --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template/index.mjs @@ -0,0 +1,12 @@ +#!/usr/bin/env node +import { mkdirSync, writeFileSync } from 'node:fs'; + +mkdirSync('web', { recursive: true }); +writeFileSync('web/package.json', JSON.stringify({ + name: 'web', + private: true, + devDependencies: { + 'vite-plus': 'catalog:tools', + '@vitest/utils': '^5.0.0', + }, +}, null, 2) + '\n'); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template/package.json new file mode 100644 index 0000000000..a6af6ce81d --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template/package.json @@ -0,0 +1,5 @@ +{ + "name": "vitest-template", + "private": true, + "bin": "index.mjs" +} diff --git a/packages/cli/src/create/__tests__/generator-scaffold.spec.ts b/packages/cli/src/create/__tests__/generator-scaffold.spec.ts index c49ff43274..17b2fc9d84 100644 --- a/packages/cli/src/create/__tests__/generator-scaffold.spec.ts +++ b/packages/cli/src/create/__tests__/generator-scaffold.spec.ts @@ -121,13 +121,20 @@ describe('generator scaffold dependencies', () => { }); it.each([ - [PackageManager.pnpm, '10.0.0'], - [PackageManager.yarn, '4.10.0'], - [PackageManager.bun, '1.3.0'], - ])('resolves catalogs.default for %s %s', async (manager, version) => { - const pkg = await scaffold(manager, version, { - catalogs: { default: { '@types/node': '^22', typescript: '^5' } }, - }); - expect(pkg.devDependencies).toEqual({ '@types/node': 'catalog:', typescript: 'catalog:' }); - }); + [PackageManager.pnpm, '10.0.0', true], + [PackageManager.yarn, '4.10.0', false], + [PackageManager.bun, '1.3.0', false], + [PackageManager.bun, '1.4.0', true], + ] as const)( + 'uses installable versions with catalogs.default for %s %s', + async (manager, version, sharedDefault) => { + const pkg = await scaffold(manager, version, { + catalogs: { default: { '@types/node': '^22', typescript: '^5' } }, + }); + const { catalog } = readYamlFile(path.join(templatesDir, 'monorepo/pnpm-workspace.yaml')); + expect(pkg.devDependencies).toEqual( + sharedDefault ? { '@types/node': 'catalog:', typescript: 'catalog:' } : catalog, + ); + }, + ); }); diff --git a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts index 4786036f72..4d00ccbef6 100644 --- a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts +++ b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts @@ -3,16 +3,24 @@ import os from 'node:os'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { stringify } from 'yaml'; import { createCatalogDependencyResolver, + rewriteBunCatalog, rewriteMonorepoProject, + rewriteYarnrcYml, + yarnrcSatisfiesVitePlus, } from '../../migration/migrator.ts'; import { PackageManager } from '../../types/index.ts'; -import { VITE_PLUS_OVERRIDE_PACKAGES, VITE_PLUS_VERSION } from '../../utils/constants.ts'; +import { + VITEST_VERSION, + VITE_PLUS_OVERRIDE_PACKAGES, + VITE_PLUS_VERSION, +} from '../../utils/constants.ts'; import { readJsonFile } from '../../utils/json.ts'; import { readYamlFile } from '../../utils/yaml.ts'; -import { ensurePnpmCreateCatalogEntries } from '../utils.ts'; +import { ensureCreateCatalogEntries } from '../utils.ts'; let root: string; let project: string; @@ -29,23 +37,454 @@ beforeEach(() => { afterEach(() => fs.rmSync(root, { recursive: true, force: true })); -function integrate(dependencies: Record = { vite: '^8.0.0' }) { +function integrate( + dependencies: Record = { vite: '^8.0.0' }, + pm: PackageManager = PackageManager.pnpm, +) { fs.writeFileSync( path.join(project, 'package.json'), JSON.stringify({ devDependencies: dependencies }), ); rewriteMonorepoProject( project, - PackageManager.pnpm, + pm, true, true, undefined, - createCatalogDependencyResolver(root, PackageManager.pnpm), + createCatalogDependencyResolver(root, pm), ); - ensurePnpmCreateCatalogEntries(root, project); + ensureCreateCatalogEntries(root, project, pm); return readYamlFile(workspaceFile); } +it.each([PackageManager.pnpm, PackageManager.yarn, PackageManager.bun])( + 'completes aligned Vitest entries in the selected %s catalog without replacing existing versions', + (pm) => { + const config = { + catalog: { '@vitest/utils': '^4.0.0' }, + catalogs: { tools: { 'vite-plus': '0.3.2', '@vitest/spy': '^4.0.0' } }, + }; + const file = path.join( + root, + { + [PackageManager.pnpm]: 'pnpm-workspace.yaml', + [PackageManager.yarn]: '.yarnrc.yml', + [PackageManager.bun]: 'package.json', + }[pm], + ); + fs.writeFileSync(file, pm === PackageManager.bun ? JSON.stringify(config) : stringify(config)); + integrate( + { + 'vite-plus': 'catalog:tools', + '@vitest/utils': '^5.0.0', + '@vitest/spy': 'catalog:tools', + }, + pm, + ); + expect(readJsonFile(path.join(project, 'package.json')).devDependencies).toMatchObject({ + '@vitest/utils': 'catalog:tools', + '@vitest/spy': 'catalog:tools', + }); + expect(pm === PackageManager.bun ? readJsonFile(file) : readYamlFile(file)).toMatchObject({ + catalog: config.catalog, + catalogs: { tools: { ...config.catalogs.tools, '@vitest/utils': VITEST_VERSION } }, + }); + const before = fs.readFileSync(file, 'utf8'); + ensureCreateCatalogEntries(root, project, pm); + expect(fs.readFileSync(file, 'utf8')).toBe(before); + }, +); + +it('only completes referenced install dependencies in the aligned Vitest package set', () => { + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + dependencies: { '@vitest/utils': 'catalog:tools' }, + optionalDependencies: { '@vitest/spy': 'catalog:tools' }, + devDependencies: { '@vitest/expect': 'catalog:tools', '@vitest/mocker': '^5.0.0' }, + peerDependencies: { '@vitest/browser': 'catalog:tools' }, + }), + ); + ensureCreateCatalogEntries(root, project, PackageManager.pnpm); + expect(readYamlFile(workspaceFile)).toEqual({ + packages: ['apps/*'], + catalogs: { tools: { '@vitest/utils': VITEST_VERSION, '@vitest/spy': VITEST_VERSION } }, + }); +}); + +it('leaves Vitest ecosystem catalogs unmanaged when the Vitest override is absent', () => { + const version = VITE_PLUS_OVERRIDE_PACKAGES.vitest; + try { + delete VITE_PLUS_OVERRIDE_PACKAGES.vitest; + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + devDependencies: { '@vitest/utils': 'catalog:tools' }, + }), + ); + const before = fs.readFileSync(workspaceFile, 'utf8'); + ensureCreateCatalogEntries(root, project, PackageManager.pnpm); + expect(fs.readFileSync(workspaceFile, 'utf8')).toBe(before); + } finally { + VITE_PLUS_OVERRIDE_PACKAGES.vitest = version; + } +}); + +describe.each([PackageManager.yarn, PackageManager.bun])('%s workspace catalogs', (pm) => { + it.each(['missing', 'partial', 'named', 'default'] as const)( + 'completes a %s catalog without changing existing versions', + (kind) => { + const existing = { 'vite-plus': '0.3.2', react: '^19.0.0' }; + const config = { + missing: {}, + partial: { catalog: existing }, + named: { catalogs: { tools: existing } }, + default: { catalogs: { default: existing } }, + }[kind]; + const file = path.join(root, pm === PackageManager.yarn ? '.yarnrc.yml' : 'package.json'); + const contents = { private: true, workspaces: ['apps/*'], ...config }; + if (pm !== PackageManager.yarn || kind !== 'missing') { + fs.writeFileSync( + file, + pm === PackageManager.yarn ? stringify(config) : JSON.stringify(contents), + ); + } + integrate(undefined, pm); + const spec = + kind === 'named' + ? 'catalog:tools' + : kind === 'default' && pm === PackageManager.yarn + ? 'catalog:default' + : 'catalog:'; + expect(readJsonFile(path.join(project, 'package.json')).devDependencies).toEqual({ + vite: spec, + 'vite-plus': spec, + }); + const result = pm === PackageManager.yarn ? readYamlFile(file) : readJsonFile(file); + const entries = { + ...(kind === 'missing' ? { 'vite-plus': VITE_PLUS_VERSION } : existing), + vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, + }; + const expected = + kind === 'named' + ? { catalogs: { tools: entries } } + : kind === 'default' + ? { catalogs: { default: entries } } + : { catalog: entries }; + expect(result).toEqual( + pm === PackageManager.yarn + ? expected + : { private: true, workspaces: ['apps/*'], ...expected }, + ); + const before = fs.readFileSync(file, 'utf8'); + ensureCreateCatalogEntries(root, project, pm); + expect(fs.readFileSync(file, 'utf8')).toBe(before); + }, + ); +}); + +it('fills the active Bun catalog even when ignored root catalogs have those entries', () => { + const file = path.join(root, 'package.json'); + const ignored = { vite: '0.0.0-unused', 'vite-plus': '0.0.0-unused' }; + fs.writeFileSync( + file, + JSON.stringify({ + workspaces: { packages: ['apps/*'], catalog: { react: '^19.0.0' } }, + catalog: ignored, + catalogs: { tools: ignored }, + }), + ); + const resolver = createCatalogDependencyResolver(root, PackageManager.bun)!; + expect(resolver('catalog:', 'vite')).toBeUndefined(); + expect(resolver('catalog:tools', 'vite')).toBeUndefined(); + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + devDependencies: { vite: 'catalog:', 'vite-plus': 'catalog:tools' }, + }), + ); + ensureCreateCatalogEntries(root, project, PackageManager.bun); + expect(readJsonFile(file)).toEqual({ + workspaces: { + packages: ['apps/*'], + catalog: { react: '^19.0.0', vite: VITE_PLUS_OVERRIDE_PACKAGES.vite }, + catalogs: { tools: { 'vite-plus': VITE_PLUS_VERSION } }, + }, + catalog: ignored, + catalogs: { tools: ignored }, + }); +}); + +it('keeps Yarn default and named default catalog references distinct', () => { + fs.writeFileSync( + path.join(root, '.yarnrc.yml'), + stringify({ + catalog: { vite: '^8.0.0' }, + catalogs: { default: { 'vite-plus': '0.3.2' } }, + }), + ); + const resolver = createCatalogDependencyResolver(root, PackageManager.yarn)!; + expect(resolver.preferredCatalogSpec).toBe('catalog:default'); + expect(resolver('catalog:', 'vite')).toBe('^8.0.0'); + expect(resolver('catalog:', 'vite-plus')).toBeUndefined(); + expect(resolver('catalog:default', 'vite-plus')).toBe('0.3.2'); + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + devDependencies: { vite: 'catalog:default', 'vite-plus': 'catalog:default' }, + }), + ); + ensureCreateCatalogEntries(root, project, PackageManager.yarn); + expect(readYamlFile(path.join(root, '.yarnrc.yml'))).toEqual({ + catalog: { vite: '^8.0.0' }, + catalogs: { default: { 'vite-plus': '0.3.2', vite: VITE_PLUS_OVERRIDE_PACKAGES.vite } }, + }); +}); + +it('uses the same named default catalog when migrating Yarn settings', () => { + const file = path.join(root, '.yarnrc.yml'); + fs.writeFileSync( + file, + stringify({ + catalog: { react: '^19.0.0' }, + catalogs: { default: { 'vite-plus': '0.3.2' } }, + }), + ); + rewriteYarnrcYml(root, false, new Set(), new Set(), true, false); + const config = readYamlFile(file); + expect(config.catalog).toEqual({ react: '^19.0.0' }); + expect(config).toMatchObject({ + catalogs: { + default: { 'vite-plus': VITE_PLUS_VERSION, vite: VITE_PLUS_OVERRIDE_PACKAGES.vite }, + }, + }); + expect(yarnrcSatisfiesVitePlus(root, false, true, false)).toBe(true); +}); + +describe.each(['root', 'nested'])('Bun %s shared default catalog', (location) => { + const config = { + catalog: { vite: '^8.0.0', 'vite-plus': '0.3.2', '@vitest/spy': '^5.0.0' }, + catalogs: { default: { react: '^19.0.0' } }, + }; + let file: string; + + beforeEach(() => { + file = path.join(root, 'package.json'); + fs.writeFileSync( + file, + JSON.stringify( + location === 'nested' + ? { workspaces: { packages: ['apps/*'], ...config } } + : { workspaces: ['apps/*'], ...config }, + ), + ); + }); + + it.each(['catalog:', 'catalog:default'])( + 'resolves and completes %s without duplicating existing entries', + (spec) => { + const resolver = createCatalogDependencyResolver(root, PackageManager.bun)!; + expect(resolver(spec, 'vite')).toBe('^8.0.0'); + expect(resolver(spec, 'vite-plus')).toBe('0.3.2'); + expect(resolver(spec, 'react')).toBe('^19.0.0'); + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + devDependencies: { + vite: spec, + 'vite-plus': spec, + '@vitest/spy': spec, + '@vitest/utils': spec, + }, + }), + ); + ensureCreateCatalogEntries(root, project, PackageManager.bun); + const result = readJsonFile(file); + const active = (location === 'nested' ? result.workspaces : result) as typeof config; + expect(active.catalog).toEqual(config.catalog); + expect(active.catalogs).toEqual({ + default: { react: '^19.0.0', '@vitest/utils': VITEST_VERSION }, + }); + const before = fs.readFileSync(file, 'utf8'); + ensureCreateCatalogEntries(root, project, PackageManager.bun); + expect(fs.readFileSync(file, 'utf8')).toBe(before); + }, + ); + + it('migrates entries in their existing locations and adds only missing entries', () => { + const ecosystem = new Set(['@vitest/spy', '@vitest/utils']); + rewriteBunCatalog(root, false, ecosystem); + const result = readJsonFile(file); + const active = (location === 'nested' ? result.workspaces : result) as typeof config; + expect(active.catalog).toEqual({ + vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, + 'vite-plus': VITE_PLUS_VERSION, + '@vitest/spy': VITEST_VERSION, + }); + expect(active.catalogs).toEqual({ + default: { react: '^19.0.0', '@vitest/utils': VITEST_VERSION }, + }); + const before = fs.readFileSync(file, 'utf8'); + rewriteBunCatalog(root, false, ecosystem); + expect(fs.readFileSync(file, 'utf8')).toBe(before); + }); + + it.each([ + { name: 'default only', catalog: undefined }, + { name: 'split toolchain', catalog: { vite: '^8.0.0' } }, + { name: 'unrelated shorthand', catalog: { react: '^19.0.0' } }, + ])('migrates $name without duplicating named default entries', ({ catalog }) => { + const initial = { catalog, catalogs: { default: { 'vite-plus': '0.3.2' } } }; + fs.writeFileSync( + file, + JSON.stringify( + location === 'nested' + ? { workspaces: { packages: ['apps/*'], ...initial } } + : { workspaces: ['apps/*'], ...initial }, + ), + ); + rewriteBunCatalog(root, false, new Set()); + const result = readJsonFile(file); + const active = (location === 'nested' ? result.workspaces : result) as { + catalog?: Record; + catalogs: Record>; + }; + expect(active.catalog).toEqual( + catalog && { + ...catalog, + ...(catalog.vite ? { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite } : {}), + }, + ); + expect(active.catalogs).toEqual({ + default: { + 'vite-plus': VITE_PLUS_VERSION, + ...(!catalog?.vite ? { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite } : {}), + }, + }); + const before = fs.readFileSync(file, 'utf8'); + rewriteBunCatalog(root, false, new Set()); + expect(fs.readFileSync(file, 'utf8')).toBe(before); + }); + + it('updates pre-existing duplicate entries in place without removing either', () => { + const contents = readJsonFile(file); + const active = (location === 'nested' ? contents.workspaces : contents) as typeof config; + Object.assign(active.catalogs.default, { vite: active.catalog.vite }); + fs.writeFileSync(file, JSON.stringify(contents)); + rewriteBunCatalog(root, false, new Set()); + const result = readJsonFile(file); + expect(location === 'nested' ? result.workspaces : result).toMatchObject({ + catalog: { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite }, + catalogs: { default: { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite } }, + }); + }); +}); + +it.each([ + { name: 'tools', spec: 'catalog:tools' }, + { name: 'default', spec: 'catalog:' }, +])( + 'fills Bun nested $name catalogs without moving or replacing existing settings', + ({ name, spec }) => { + const file = path.join(root, 'package.json'); + const contents = { + private: true, + workspaces: { packages: ['apps/*'], catalogs: { [name]: { 'vite-plus': '0.3.2' } } }, + catalog: { react: '^19.0.0' }, + }; + fs.writeFileSync(file, JSON.stringify(contents)); + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + devDependencies: { vite: spec, 'vite-plus': spec }, + }), + ); + ensureCreateCatalogEntries(root, project, PackageManager.bun); + expect(readJsonFile(file)).toEqual({ + ...contents, + workspaces: { + packages: ['apps/*'], + catalogs: { + [name]: { + 'vite-plus': '0.3.2', + vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, + }, + }, + }, + }); + }, +); + +it.each(['1.2.14', '1.3.14', '1.4.0'])( + 'completes references in the correct default catalog on Bun %s', + (version) => { + const file = path.join(root, 'package.json'); + fs.writeFileSync( + file, + JSON.stringify({ + private: true, + workspaces: { + packages: ['apps/*'], + catalog: { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite }, + catalogs: { default: { react: '^19.0.0' } }, + }, + }), + ); + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + devDependencies: { vite: 'catalog:default', 'vite-plus': 'catalog:' }, + }), + ); + ensureCreateCatalogEntries(root, project, PackageManager.bun, version); + const merged = version === '1.4.0'; + expect(readJsonFile(file)).toEqual({ + private: true, + workspaces: { + packages: ['apps/*'], + catalog: { + vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, + ...(merged ? {} : { 'vite-plus': VITE_PLUS_VERSION }), + }, + catalogs: { + default: { + react: '^19.0.0', + ...(merged + ? { 'vite-plus': VITE_PLUS_VERSION } + : { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite }), + }, + }, + }, + }); + const before = fs.readFileSync(file, 'utf8'); + ensureCreateCatalogEntries(root, project, PackageManager.bun, version); + expect(fs.readFileSync(file, 'utf8')).toBe(before); + }, +); + +it.each([ + { packageManager: 'bun@1.3.14' }, + { devEngines: { packageManager: { name: 'bun', version: '1.3.14' } } }, +])('uses the Bun pin when no resolved version is supplied: %j', (pin) => { + fs.writeFileSync( + path.join(root, 'package.json'), + JSON.stringify({ + ...pin, + workspaces: { + packages: ['apps/*'], + catalog: { vite: '^8.0.0' }, + catalogs: { default: { react: '^19.0.0' } }, + }, + }), + ); + const pinned = createCatalogDependencyResolver(root, PackageManager.bun)!; + expect(pinned('catalog:', 'react')).toBeUndefined(); + expect(pinned('catalog:default', 'vite')).toBeUndefined(); + const resolved = createCatalogDependencyResolver(root, PackageManager.bun, '1.4.0')!; + expect(resolved('catalog:', 'react')).toBe('^19.0.0'); + expect(resolved('catalog:default', 'vite')).toBe('^8.0.0'); +}); + describe('catalogs for applications created in existing pnpm workspaces', () => { it('makes references generated by member integration resolvable in a plain workspace', () => { const workspace = integrate(); @@ -113,7 +552,7 @@ describe('catalogs for applications created in existing pnpm workspaces', () => it('leaves templates without a package manifest alone', () => { const content = fs.readFileSync(workspaceFile, 'utf8'); - ensurePnpmCreateCatalogEntries(root, project); + ensureCreateCatalogEntries(root, project, PackageManager.pnpm); expect(fs.readFileSync(workspaceFile, 'utf8')).toBe(content); }); @@ -129,7 +568,7 @@ describe('catalogs for applications created in existing pnpm workspaces', () => }, }), ); - ensurePnpmCreateCatalogEntries(root, project); + ensureCreateCatalogEntries(root, project, PackageManager.pnpm); expect(fs.readFileSync(workspaceFile, 'utf8')).toBe(content); }); }); diff --git a/packages/cli/src/create/bin.ts b/packages/cli/src/create/bin.ts index 6a8680efe6..42658e2a96 100644 --- a/packages/cli/src/create/bin.ts +++ b/packages/cli/src/create/bin.ts @@ -23,6 +23,7 @@ import { rewriteStandaloneProject, setPackageManager, shouldSkipStagedMigrationForHooks, + workspaceSupportsCatalog, } from '../migration/migrator.ts'; import { DependencyType, PackageManager, type WorkspaceInfo } from '../types/index.ts'; import { @@ -92,7 +93,7 @@ import { BuiltinTemplate, TemplateType } from './templates/types.ts'; import { deriveDefaultPackageName, detectLauncherPackageManager, - ensurePnpmCreateCatalogEntries, + ensureCreateCatalogEntries, ensureDefaultGitignoreEntries, ensureGitignoreVsCodeEditorConfigs, formatLocalVpCommand, @@ -1317,15 +1318,22 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h shouldSetupHooks, workspaceInfo.packageManager, ); + const supportCatalog = workspaceSupportsCatalog( + workspaceInfo.rootDir, + workspaceInfo.packageManager, + workspaceInfo.packageManagerVersion, + ); rewriteMonorepoProject( fullPath, workspaceInfo.packageManager, skipStagedMigration, compactOutput, undefined, - workspaceInfo.packageManager === PackageManager.pnpm - ? createCatalogDependencyResolver(workspaceInfo.rootDir, workspaceInfo.packageManager) - : undefined, + createCatalogDependencyResolver( + workspaceInfo.rootDir, + workspaceInfo.packageManager, + workspaceInfo.packageManagerVersion, + ), { rootDir: workspaceInfo.rootDir, packages: discoverWorkspacePackages( @@ -1333,9 +1341,16 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h workspaceInfo.rootDir, ), }, + false, + supportCatalog, ); - if (workspaceInfo.packageManager === PackageManager.pnpm) { - ensurePnpmCreateCatalogEntries(workspaceInfo.rootDir, fullPath); + if (supportCatalog) { + ensureCreateCatalogEntries( + workspaceInfo.rootDir, + fullPath, + workspaceInfo.packageManager, + workspaceInfo.packageManagerVersion, + ); } for (const framework of detectFramework(fullPath)) { if (!hasFrameworkShim(fullPath, framework)) { diff --git a/packages/cli/src/create/templates/generator.ts b/packages/cli/src/create/templates/generator.ts index aef69f42c7..0ef0570b36 100644 --- a/packages/cli/src/create/templates/generator.ts +++ b/packages/cli/src/create/templates/generator.ts @@ -45,7 +45,11 @@ export async function executeGeneratorScaffold( workspaceInfo.downloadPackageManager.version, workspaceInfo.isMonorepo, ) - ? createCatalogDependencyResolver(workspaceInfo.rootDir, workspaceInfo.packageManager) + ? createCatalogDependencyResolver( + workspaceInfo.rootDir, + workspaceInfo.packageManager, + workspaceInfo.downloadPackageManager.version, + ) : undefined; const { catalog } = readYamlFile(path.join(templatesDir, 'monorepo/pnpm-workspace.yaml')) as { catalog: Record; diff --git a/packages/cli/src/create/utils.ts b/packages/cli/src/create/utils.ts index 83fbddb9e2..a3cc8dea88 100644 --- a/packages/cli/src/create/utils.ts +++ b/packages/cli/src/create/utils.ts @@ -6,11 +6,21 @@ import { parseDocument } from 'yaml'; import { PackageManager } from '../types/index.ts'; import { + bunSupportsMergedDefaultCatalogs, + getBunCatalogConfig, + getYamlCatalogPath, + isNamedCatalog, + readBunCatalogDependencyResolver, +} from '../utils/catalog.ts'; +import { + VITEST_VERSION, VITE_PLUS_NAME, VITE_PLUS_OVERRIDE_PACKAGES, VITE_PLUS_VERSION, } from '../utils/constants.ts'; import { editJsonFile, readJsonFile } from '../utils/json.ts'; +import { VITEST_EXACT_VERSION_PACKAGES } from '../utils/vitest-ecosystem.ts'; +import type { NpmWorkspaces } from '../utils/workspace.ts'; import { getRandomProjectName } from './random-name.ts'; export type CreateEditorOption = string | false | undefined; @@ -18,13 +28,16 @@ export type CreateEditorOption = string | false | undefined; /** Complete only the managed catalog references of a newly created workspace member. * Running the full root migrator here would also change unrelated packages and overrides. */ -export function ensurePnpmCreateCatalogEntries(rootDir: string, projectDir: string): void { - const workspacePath = path.join(rootDir, 'pnpm-workspace.yaml'); +export function ensureCreateCatalogEntries( + rootDir: string, + projectDir: string, + packageManager: PackageManager, + packageManagerVersion = 'latest', +): void { const packageJsonPath = path.join(projectDir, 'package.json'); - if (!fs.existsSync(workspacePath) || !fs.existsSync(packageJsonPath)) { + if (packageManager === PackageManager.npm || !fs.existsSync(packageJsonPath)) { return; } - const doc = parseDocument(fs.readFileSync(workspacePath, 'utf8')); const pkg = readJsonFile(packageJsonPath) as Partial< Record<'dependencies' | 'devDependencies' | 'optionalDependencies', Record> >; @@ -32,24 +45,63 @@ export function ensurePnpmCreateCatalogEntries(rootDir: string, projectDir: stri ...VITE_PLUS_OVERRIDE_PACKAGES, [VITE_PLUS_NAME]: VITE_PLUS_VERSION, }; - let changed = false; - for (const field of ['dependencies', 'devDependencies', 'optionalDependencies'] as const) { - for (const [name, spec] of Object.entries(pkg[field] ?? {})) { - if (!Object.hasOwn(versions, name) || !spec.startsWith('catalog:')) { - continue; - } - const catalogName = spec.slice('catalog:'.length); - const catalogPath = - catalogName && catalogName !== 'default' - ? ['catalogs', catalogName] - : doc.has('catalog') || !doc.hasIn(['catalogs', 'default']) - ? ['catalog'] - : ['catalogs', 'default']; - const entryPath = [...catalogPath, name]; - if (!doc.hasIn(entryPath)) { - doc.setIn(entryPath, versions[name]); + if ('vitest' in VITE_PLUS_OVERRIDE_PACKAGES) { + for (const name of VITEST_EXACT_VERSION_PACKAGES) { + versions[name] ??= VITEST_VERSION; + } + } + const entries = (['dependencies', 'devDependencies', 'optionalDependencies'] as const) + .flatMap((field) => Object.entries(pkg[field] ?? {})) + .filter(([name, spec]) => Object.hasOwn(versions, name) && spec.startsWith('catalog:')); + if (entries.length === 0) { + return; + } + if (packageManager === PackageManager.bun) { + editJsonFile<{ + workspaces?: NpmWorkspaces; + catalog?: Record; + catalogs?: Record>; + }>(path.join(rootDir, 'package.json'), (root) => { + const target = getBunCatalogConfig(root); + const resolveCatalog = readBunCatalogDependencyResolver(root, packageManagerVersion); + const mergeDefaults = bunSupportsMergedDefaultCatalogs(packageManagerVersion); + let changed = false; + for (const [name, spec] of entries) { + if (resolveCatalog(spec, name) !== undefined) { + continue; + } + const catalogName = spec.slice('catalog:'.length); + let catalog: Record; + if (isNamedCatalog(catalogName, packageManager, packageManagerVersion)) { + catalog = (target.catalogs ??= {})[catalogName] ??= {}; + } else if (mergeDefaults && target.catalogs?.default) { + catalog = target.catalogs.default; + } else { + catalog = target.catalog ??= {}; + } + catalog[name] = versions[name]; changed = true; } + return changed ? root : undefined; + }); + return; + } + const workspacePath = path.join( + rootDir, + packageManager === PackageManager.yarn ? '.yarnrc.yml' : 'pnpm-workspace.yaml', + ); + const workspaceExists = fs.existsSync(workspacePath); + if (packageManager === PackageManager.pnpm && !workspaceExists) { + return; + } + const doc = parseDocument(workspaceExists ? fs.readFileSync(workspacePath, 'utf8') : ''); + let changed = false; + for (const [name, spec] of entries) { + const catalogPath = getYamlCatalogPath(doc, spec, packageManager); + const entryPath = [...catalogPath, name]; + if (!doc.hasIn(entryPath)) { + doc.setIn(entryPath, versions[name]); + changed = true; } } if (changed) { diff --git a/packages/cli/src/migration/__tests__/migrator.spec.ts b/packages/cli/src/migration/__tests__/migrator.spec.ts index 81cb42e996..ce5801c1fc 100644 --- a/packages/cli/src/migration/__tests__/migrator.spec.ts +++ b/packages/cli/src/migration/__tests__/migrator.spec.ts @@ -36,6 +36,7 @@ vi.mock('../../utils/constants.js', async (importOriginal) => { const { rewritePackageJson, + createCatalogDependencyResolver, rewriteStandaloneProject, rewriteMonorepo, rewriteMonorepoProject, @@ -2143,6 +2144,123 @@ describe('ensureVitePlusBootstrap', () => { expect(pkg.overrides).toEqual({ vite: 'catalog:' }); }); + it.each(['1.2.14', '1.3.14', '1.4.0'])( + 'keeps split default catalogs resolvable when migrating Bun %s', + (version) => { + const file = path.join(tmpDir, 'package.json'); + fs.writeFileSync( + file, + JSON.stringify({ + name: 'bun-split-default', + packageManager: `bun@${version}`, + devDependencies: { vite: 'catalog:', react: 'catalog:default' }, + workspaces: { + packages: [], + catalog: { vite: '^8.0.0' }, + catalogs: { default: { react: '^19.0.0' } }, + }, + }), + ); + const workspace = makeWorkspaceInfo(tmpDir, PackageManager.bun, version); + rewriteMonorepo(workspace, true); + const pkg = readJson(file) as { + devDependencies: Record; + workspaces: { + catalog: Record; + catalogs: Record>; + }; + }; + const merged = version === '1.4.0'; + expect(pkg.devDependencies['vite-plus']).toBe('catalog:'); + expect(pkg.devDependencies.react).toBe('catalog:default'); + expect(pkg.workspaces.catalog['vite-plus']).toBe(merged ? undefined : 'latest'); + expect(pkg.workspaces.catalogs.default).toEqual( + merged ? { react: '^19.0.0', 'vite-plus': 'latest' } : { react: '^19.0.0' }, + ); + const resolver = createCatalogDependencyResolver(tmpDir, PackageManager.bun, version)!; + expect(resolver('catalog:', 'vite-plus')).toBe('latest'); + expect(resolver('catalog:', 'react')).toBe(merged ? '^19.0.0' : undefined); + const before = fs.readFileSync(file, 'utf8'); + rewriteMonorepo(workspace, true); + expect(fs.readFileSync(file, 'utf8')).toBe(before); + }, + ); + + it.each(['1.2.14', '1.3.14', '1.4.0'])( + 'reconciles a named default catalog with the correct reference on Bun %s', + (version) => { + const file = path.join(tmpDir, 'package.json'); + fs.writeFileSync( + file, + JSON.stringify({ + name: 'bun-named-default', + packageManager: `bun@${version}`, + devDependencies: { vite: 'catalog:default', 'vite-plus': '0.3.2' }, + workspaces: { + packages: [], + catalogs: { default: { vite: '^8.0.0', 'vite-plus': '0.3.2' } }, + }, + }), + ); + const workspace = makeWorkspaceInfo(tmpDir, PackageManager.bun, version); + ensureVitePlusBootstrap(workspace); + const pkg = readJson(file) as { + devDependencies: Record; + workspaces: { catalog?: unknown }; + }; + expect(pkg.devDependencies['vite-plus']).toBe( + version === '1.4.0' ? 'catalog:' : 'catalog:default', + ); + expect(pkg.workspaces.catalog).toBeUndefined(); + const resolver = createCatalogDependencyResolver(tmpDir, PackageManager.bun, version)!; + expect(resolver(pkg.devDependencies['vite-plus'], 'vite-plus')).toBe('latest'); + expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.bun)).toBe(false); + const before = fs.readFileSync(file, 'utf8'); + ensureVitePlusBootstrap(workspace); + expect(fs.readFileSync(file, 'utf8')).toBe(before); + }, + ); + + it.each([ + ['1.3.14', 'root'], + ['1.3.14', 'nested'], + ['1.4.0', 'root'], + ['1.4.0', 'nested'], + ])('fills a missing named-default entry on Bun %s in %s catalogs', (version, location) => { + const file = path.join(tmpDir, 'package.json'); + const catalogs: { + catalog: Record; + catalogs: Record>; + } = { + catalog: { vite: '^8.0.0' }, + catalogs: { default: { 'vite-plus': '0.3.2' } }, + }; + fs.writeFileSync( + file, + JSON.stringify({ + name: 'bun-split-toolchain', + packageManager: `bun@${version}`, + devDependencies: { 'vite-plus': 'catalog:default' }, + ...(location === 'nested' + ? { workspaces: { packages: [], ...catalogs } } + : { workspaces: [], ...catalogs }), + }), + ); + ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.bun, version)); + const pkg = readJson(file) as { + devDependencies: Record; + workspaces: typeof catalogs; + } & typeof catalogs; + const active = location === 'nested' ? pkg.workspaces : pkg; + expect(active.catalog.vite).toBe(VITE_PLUS_OVERRIDE_PACKAGES.vite); + expect(active.catalogs.default.vite).toBe( + version === '1.4.0' ? undefined : VITE_PLUS_OVERRIDE_PACKAGES.vite, + ); + const resolver = createCatalogDependencyResolver(tmpDir, PackageManager.bun)!; + expect(resolver(pkg.devDependencies.vite, 'vite')).toBe(VITE_PLUS_OVERRIDE_PACKAGES.vite); + expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.bun)).toBe(false); + }); + it('adds a missing @vitest/* entry to the bun catalog it now references', () => { fs.writeFileSync( path.join(tmpDir, 'package.json'), @@ -5626,6 +5744,48 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); }); + it.each([ + ['legacy', 'default'], + ['default', 'legacy'], + ])('keeps pnpm catalog references resolvable when %s precedes %s', (first, second) => { + fs.writeFileSync( + path.join(tmpDir, 'package.json'), + JSON.stringify({ + name: 'catalog-order-workspace', + devDependencies: { vite: 'catalog:legacy' }, + }), + ); + const contents = [ + 'packages: [packages/*]', + 'catalogs:', + ` ${first}:`, + ' vite: ^8.0.0', + ` ${second}:`, + ' vite: ^8.0.0', + '', + ].join('\n'); + fs.writeFileSync(path.join(tmpDir, 'pnpm-workspace.yaml'), contents); + const expectedSpec = first === 'default' ? 'catalog:' : `catalog:${first}`; + const resolver = createCatalogDependencyResolver(tmpDir, PackageManager.pnpm)!; + expect(resolver.preferredCatalogSpec).toBe(expectedSpec); + + rewriteMonorepo(makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true); + + const pkg = readJson(path.join(tmpDir, 'package.json')) as { + devDependencies: Record; + }; + expect(pkg.devDependencies.vite).toBe('catalog:legacy'); + expect(pkg.devDependencies['vite-plus']).toBe(expectedSpec); + const migratedResolver = createCatalogDependencyResolver(tmpDir, PackageManager.pnpm)!; + expect(migratedResolver(pkg.devDependencies['vite-plus'], 'vite-plus')).toBe('latest'); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { + catalog?: unknown; + catalogs: Record>; + }; + expect(workspace.catalog).toBeUndefined(); + expect(workspace.catalogs[second]['vite-plus']).toBeUndefined(); + }); + it('writes managed dependencies into an active catalogs.default definition', () => { fs.writeFileSync( path.join(tmpDir, 'package.json'), diff --git a/packages/cli/src/migration/migrator/README.md b/packages/cli/src/migration/migrator/README.md index acd19f4eb8..ac3e6b7e33 100644 --- a/packages/cli/src/migration/migrator/README.md +++ b/packages/cli/src/migration/migrator/README.md @@ -71,7 +71,7 @@ Pick the file by what a function _does_, not by where it happens to be called. time, so they must be imported from a fully-evaluated leaf: ```ts - import { REMOVE_PACKAGES, type CatalogDependencyResolver } from './shared.ts'; + import { REMOVE_PACKAGES, type PackageJsonDependencyField } from './shared.ts'; ``` Keep `shared.ts` a **pure leaf**: it may import external packages and diff --git a/packages/cli/src/migration/migrator/catalog.ts b/packages/cli/src/migration/migrator/catalog.ts index fe85046cb5..b1aaa34448 100644 --- a/packages/cli/src/migration/migrator/catalog.ts +++ b/packages/cli/src/migration/migrator/catalog.ts @@ -2,10 +2,20 @@ import fs from 'node:fs'; import path from 'node:path'; import tsrsPkg from 'tsrs/package.json' with { type: 'json' }; -import { coerce, isGreaterThanOrEqual, isLessThan } from 'verkit'; +import { coerce, isLessThan } from 'verkit'; import { Scalar, YAMLMap, YAMLSeq } from 'yaml'; import { PackageManager, type WorkspacePackage } from '../../types/index.ts'; +import { + bunSupportsMergedDefaultCatalogs, + createCatalogDependencyResolverFromCatalogs, + getBunCatalogConfig, + getYamlCatalogPath, + readBunCatalogDependencyResolver, + selectPreferredCatalogSpec, + versionAtLeast, + type CatalogDependencyResolver, +} from '../../utils/catalog.ts'; import { VITEST_AGE_GATE_EXEMPT_PACKAGES, VITEST_VERSION, @@ -43,10 +53,10 @@ import { REMOVE_PACKAGES, VITEST_IS_MANAGED_OVERRIDE, isPlainRecord, + pinnedPackageManagerVersion, pnpmOverrideKey, readPackageJsonIfExists, vitePeerDependencyRuleRequired, - type CatalogDependencyResolver, type PackageJsonDependencyField, type PnpmPackageJsonSettings, } from './shared.ts'; @@ -94,17 +104,6 @@ function hasTsrsTrustPolicyException(excludes: readonly unknown[]): boolean { return excludes.includes('tsrs') || excludes.includes(PNPM_TSRS_TRUST_POLICY_EXCLUDE); } -// Whether `version` is at least `minVersion`. A non-coercible version passes -// only when it is one of the given dist-tags, which always point at a current -// (feature-capable) release. -function versionAtLeast(version: string, minVersion: string, tags: string[]): boolean { - const coerced = coerce(version); - if (coerced) { - return isGreaterThanOrEqual(coerced, minVersion); - } - return tags.includes(version); -} - // The packages field became optional in pnpm 10.5.0. // https://github.com/pnpm/pnpm/releases/tag/v10.5.0 export function pnpmRequiresWorkspacePackages(version: string): boolean { @@ -173,18 +172,12 @@ const BUN_TOP_LEVEL_CATALOG_MIN_VERSION = '1.2.21'; // needs the nested location that `rewriteBunCatalog` keeps in place. Otherwise // `catalog:` edges make `bun install` abort with "vite@catalog: failed to // resolve", so the toolchain edges must stay concrete. -export function bunSupportsCatalog( - pkg: { workspaces?: NpmWorkspaces; catalog?: Record }, - version: string, -): boolean { +export function bunSupportsCatalog(pkg: { workspaces?: NpmWorkspaces }, version: string): boolean { const { workspaces } = pkg; if (workspaces == null) { return false; } - // Mirrors `useWorkspacesCatalog` in rewriteBunCatalog. - const writesNestedCatalog = - !Array.isArray(workspaces) && - (workspaces.catalog != null || (pkg.catalog == null && workspaces.catalogs != null)); + const writesNestedCatalog = getBunCatalogConfig(pkg) !== pkg; return ( writesNestedCatalog || versionAtLeast(version, BUN_TOP_LEVEL_CATALOG_MIN_VERSION, ['latest', 'canary']) @@ -211,6 +204,20 @@ export function supportsCatalog( } } +// `supportsCatalog` for a workspace root, reading Bun's workspace state from its package.json. +export function workspaceSupportsCatalog( + rootDir: string, + packageManager: PackageManager, + version: string, +): boolean { + return supportsCatalog( + packageManager, + version, + packageManager === PackageManager.bun && + bunSupportsCatalog(readJsonFile(path.join(rootDir, 'package.json')), version), + ); +} + // These are the root package.json#pnpm settings pnpm 10.6.2+ accepts at the // top level of pnpm-workspace.yaml. Unknown keys may belong to third-party // tooling and stay in package.json. @@ -347,6 +354,7 @@ export function rewritePnpmWorkspaceYaml( usesVitest, vitestEcosystemPackages, catalogAdditions, + PackageManager.pnpm, ); if (!writeWorkspaceSettings) { return; @@ -761,17 +769,10 @@ function isVitePlusOverrideSpec(value: string): boolean { export function createCatalogDependencyResolver( projectPath: string, packageManager: PackageManager, + packageManagerVersion?: string, ): CatalogDependencyResolver | undefined { if (packageManager === PackageManager.pnpm) { - const pnpmWorkspaceYamlPath = path.join(projectPath, 'pnpm-workspace.yaml'); - if (!fs.existsSync(pnpmWorkspaceYamlPath)) { - return undefined; - } - const doc = readYamlFile(pnpmWorkspaceYamlPath) as { - catalog?: Record; - catalogs?: Record>; - } | null; - return createCatalogDependencyResolverFromCatalogs(doc?.catalog, doc?.catalogs); + return readPnpmWorkspaceCatalogDependencyResolver(projectPath); } if (packageManager === PackageManager.yarn) { const yarnrcYmlPath = path.join(projectPath, '.yarnrc.yml'); @@ -782,7 +783,7 @@ export function createCatalogDependencyResolver( catalog?: Record; catalogs?: Record>; } | null; - return createCatalogDependencyResolverFromCatalogs(doc?.catalog, doc?.catalogs); + return createCatalogDependencyResolverFromCatalogs(doc?.catalog, doc?.catalogs, packageManager); } if (packageManager === PackageManager.bun) { const packageJsonPath = path.join(projectPath, 'package.json'); @@ -793,70 +794,17 @@ export function createCatalogDependencyResolver( workspaces?: NpmWorkspaces; catalog?: Record; catalogs?: Record>; + packageManager?: string; + devEngines?: { packageManager?: unknown }; }; - // A missing/absent `workspaces.catalog` resolves identically whether the - // fallback is `undefined` (optional chaining) or `{}`, so this shares the - // exact bun catalog resolution used by the in-memory callers. - return readBunCatalogDependencyResolver(pkg); + return readBunCatalogDependencyResolver( + pkg, + packageManagerVersion ?? pinnedPackageManagerVersion(pkg), + ); } return undefined; } -export function createCatalogDependencyResolverFromCatalogs( - catalog: Record | undefined, - catalogs: Record> | undefined, -): CatalogDependencyResolver { - const preferredCatalogSpec = selectPreferredCatalogSpec(catalog, catalogs); - const resolver = (catalogSpec: string, dependencyName: string) => { - const catalogName = catalogSpec.slice('catalog:'.length); - // pnpm accepts the default catalog in either `catalog` or - // `catalogs.default`, but rejects a workspace that defines both. Both - // `catalog:` and `catalog:default` resolve through that one logical - // default catalog. - if (catalogName && catalogName !== 'default') { - return catalogs?.[catalogName]?.[dependencyName]; - } - return (catalog ?? catalogs?.default)?.[dependencyName]; - }; - return Object.assign(resolver, { preferredCatalogSpec }); -} - -function selectPreferredCatalogSpec( - catalog: Record | undefined, - catalogs: Record> | undefined, -): string { - const candidates: Array<{ spec: string; values: Record }> = []; - if (catalog) { - candidates.push({ spec: 'catalog:', values: catalog }); - } - for (const [name, values] of Object.entries(catalogs ?? {})) { - candidates.push({ - spec: name === 'default' ? 'catalog:' : `catalog:${name}`, - values, - }); - } - - // Keep the managed toolchain together when a project already has a catalog - // for it (for example Vize's `catalogs.vite-stack` and Rari's - // `catalogs.build`). Prefer vite-plus as the strongest signal, followed by - // vite and vitest. Existing dependency references keep their exact catalog - // spec; this choice is for newly injected dependencies and overrides. - for (const dependencyName of [VITE_PLUS_NAME, 'vite', 'vitest']) { - const matching = candidates.find(({ values }) => Object.hasOwn(values, dependencyName)); - if (matching) { - return matching.spec; - } - } - - // Reuse either valid spelling of the default catalog. Do not repurpose an - // unrelated named catalog; when no managed/default catalog exists, create - // the conventional top-level `catalog` instead. - if (catalog || catalogs?.default) { - return 'catalog:'; - } - return 'catalog:'; -} - function getYamlMapScalarStringValue(map: unknown, key: string): string | undefined { if (!(map instanceof YAMLMap)) { return undefined; @@ -942,19 +890,18 @@ export function rewriteCatalog( usesVitest: boolean, vitestEcosystemPackages: ReadonlySet, catalogAdditions: ReadonlySet, + packageManager: PackageManager, ): string { const parsed = doc.toJS() as { catalog?: Record; catalogs?: Record>; } | null; - const preferredCatalogSpec = selectPreferredCatalogSpec(parsed?.catalog, parsed?.catalogs); - const preferredCatalogName = preferredCatalogSpec.slice('catalog:'.length); - const targetPath: readonly string[] = - preferredCatalogName && preferredCatalogName !== 'default' - ? ['catalogs', preferredCatalogName] - : doc.has('catalog') || !doc.hasIn(['catalogs', 'default']) - ? ['catalog'] - : ['catalogs', 'default']; + const preferredCatalogSpec = selectPreferredCatalogSpec( + parsed?.catalog, + parsed?.catalogs, + packageManager, + ); + const targetPath = getYamlCatalogPath(doc, preferredCatalogSpec, packageManager); rewriteYamlCatalogAtPath( doc, @@ -1076,11 +1023,22 @@ function rewriteVitestEcosystemYamlCatalog( } } +function shouldWriteCatalogEntry( + name: string, + catalog: Record, + addMissing: boolean, + otherDefaultCatalog?: Record, +): boolean { + // Merged Bun default catalogs reject names defined in both. + return name in catalog || (addMissing && !Object.hasOwn(otherDefaultCatalog ?? {}, name)); +} + function rewriteCatalogObject( catalog: Record, addMissing: boolean, usesVitest: boolean, vitestEcosystemPackages: ReadonlySet, + otherDefaultCatalog?: Record, ): void { const managed = managedOverridePackages(usesVitest); // Common case (no direct vitest): strip a lingering managed `vitest` catalog @@ -1089,12 +1047,18 @@ function rewriteCatalogObject( removeManagedVitestEntry(catalog); } for (const [key, value] of Object.entries(managed)) { - if (value.startsWith('file:') || (!addMissing && !(key in catalog))) { + if ( + value.startsWith('file:') || + !shouldWriteCatalogEntry(key, catalog, addMissing, otherDefaultCatalog) + ) { continue; } catalog[key] = value; } - if (!VITE_PLUS_VERSION.startsWith('file:') && (addMissing || VITE_PLUS_NAME in catalog)) { + if ( + !VITE_PLUS_VERSION.startsWith('file:') && + shouldWriteCatalogEntry(VITE_PLUS_NAME, catalog, addMissing, otherDefaultCatalog) + ) { catalog[VITE_PLUS_NAME] = VITE_PLUS_VERSION; } for (const name of REMOVE_PACKAGES) { @@ -1107,7 +1071,11 @@ function rewriteCatalogObject( ? new Set([...Object.keys(catalog), ...vitestEcosystemPackages]) : Object.keys(catalog); for (const name of names) { - if (vitestEcosystemPackages.has(name) && isAlignableVitestEcosystemPackage(name)) { + if ( + vitestEcosystemPackages.has(name) && + isAlignableVitestEcosystemPackage(name) && + shouldWriteCatalogEntry(name, catalog, addMissing, otherDefaultCatalog) + ) { catalog[name] = VITEST_VERSION; } } @@ -1119,9 +1087,16 @@ function rewriteCatalogsObject( usesVitest: boolean, vitestEcosystemPackages: ReadonlySet, targetCatalog?: Record, + defaultCatalog?: Record, ): void { - for (const catalog of Object.values(catalogs)) { - rewriteCatalogObject(catalog, catalog === targetCatalog, usesVitest, vitestEcosystemPackages); + for (const [name, catalog] of Object.entries(catalogs)) { + rewriteCatalogObject( + catalog, + catalog === targetCatalog, + usesVitest, + vitestEcosystemPackages, + name === 'default' ? defaultCatalog : undefined, + ); } } @@ -1136,6 +1111,7 @@ export function rewriteBunCatalog( usesVitest: boolean, vitestEcosystemPackages: ReadonlySet, usesWebdriverioProvider = false, + packageManagerVersion = 'latest', ): void { const packageJsonPath = path.join(projectPath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { @@ -1153,17 +1129,19 @@ export function rewriteBunCatalog( // prefer the location the user already chose to avoid moving their config. const workspacesObj = pkg.workspaces && !Array.isArray(pkg.workspaces) ? pkg.workspaces : undefined; - const useWorkspacesCatalog = - workspacesObj?.catalog != null || (pkg.catalog == null && workspacesObj?.catalogs != null); + const activeCatalogs = getBunCatalogConfig(pkg); + const useWorkspacesCatalog = activeCatalogs === workspacesObj; // Like the pnpm catalog, add missing entries to the catalog the new // `catalog:` references point at. A named one such as `catalogs.build` // takes them instead of a newly created default catalog. - const { preferredCatalogSpec } = readBunCatalogDependencyResolver(pkg); + const { preferredCatalogSpec } = readBunCatalogDependencyResolver(pkg, packageManagerVersion); + const mergeDefaults = bunSupportsMergedDefaultCatalogs(packageManagerVersion); const preferredName = preferredCatalogSpec.slice('catalog:'.length); - const namedTarget = preferredName - ? (workspacesObj?.catalogs?.[preferredName] ?? pkg.catalogs?.[preferredName]) - : undefined; - const defaultCatalog = useWorkspacesCatalog ? workspacesObj?.catalog : pkg.catalog; + const namedTarget = + preferredName || mergeDefaults + ? activeCatalogs.catalogs?.[preferredName || 'default'] + : undefined; + const defaultCatalog = activeCatalogs.catalog; const catalog: Record = { ...defaultCatalog }; rewriteCatalogObject(catalog, !namedTarget, usesVitest, vitestEcosystemPackages); @@ -1190,13 +1168,20 @@ export function rewriteBunCatalog( usesVitest, vitestEcosystemPackages, namedTarget, + mergeDefaults ? workspacesObj.catalog : undefined, ); for (const named of Object.values(workspacesObj.catalogs)) { pruneLegacyWrapperAliases(named); } } if (pkg.catalogs) { - rewriteCatalogsObject(pkg.catalogs, usesVitest, vitestEcosystemPackages, namedTarget); + rewriteCatalogsObject( + pkg.catalogs, + usesVitest, + vitestEcosystemPackages, + namedTarget, + mergeDefaults ? pkg.catalog : undefined, + ); for (const named of Object.values(pkg.catalogs)) { pruneLegacyWrapperAliases(named); } @@ -1406,7 +1391,11 @@ export function readPnpmWorkspaceCatalogDependencyResolver( catalog?: Record; catalogs?: Record>; } | null; - return createCatalogDependencyResolverFromCatalogs(doc?.catalog, doc?.catalogs); + return createCatalogDependencyResolverFromCatalogs( + doc?.catalog, + doc?.catalogs, + PackageManager.pnpm, + ); } export function readPnpmWorkspaceOverrides( @@ -1556,24 +1545,3 @@ export function ensurePnpmWorkspacePackages( }); return changed; } - -export function readBunCatalogDependencyResolver(pkg: { - workspaces?: NpmWorkspaces; - catalog?: Record; - catalogs?: Record>; -}): CatalogDependencyResolver { - const workspacesObj = pkg.workspaces && !Array.isArray(pkg.workspaces) ? pkg.workspaces : {}; - const fromWorkspaces = createCatalogDependencyResolverFromCatalogs( - workspacesObj.catalog, - workspacesObj.catalogs, - ); - const fromPkg = createCatalogDependencyResolverFromCatalogs(pkg.catalog, pkg.catalogs); - const resolver = (catalogSpec: string, dependencyName: string) => - fromWorkspaces(catalogSpec, dependencyName) ?? fromPkg(catalogSpec, dependencyName); - return Object.assign(resolver, { - preferredCatalogSpec: - workspacesObj.catalog || workspacesObj.catalogs - ? fromWorkspaces.preferredCatalogSpec - : fromPkg.preferredCatalogSpec, - }); -} diff --git a/packages/cli/src/migration/migrator/orchestrators.ts b/packages/cli/src/migration/migrator/orchestrators.ts index d32bb6f176..0280aac009 100644 --- a/packages/cli/src/migration/migrator/orchestrators.ts +++ b/packages/cli/src/migration/migrator/orchestrators.ts @@ -2,12 +2,12 @@ import fs from 'node:fs'; import path from 'node:path'; import { PackageManager, type WorkspaceInfo, type WorkspacePackage } from '../../types/index.ts'; +import type { CatalogDependencyResolver } from '../../utils/catalog.ts'; import { VITE_PLUS_NAME, VITE_PLUS_VERSION, isForceOverrideMode } from '../../utils/constants.ts'; -import { editJsonFile, readJsonFile } from '../../utils/json.ts'; +import { editJsonFile } from '../../utils/json.ts'; import { applyBuildAllowanceToPackageJsonPnpm, applyYarnWorkspaceHoistingFix, - bunSupportsCatalog, cleanupDeprecatedTsconfigOptions, collectInjectedProviderNames, collectOxlintDependencyNames, @@ -60,6 +60,7 @@ import { usesWebdriverioProvider, workspaceUsesVitestDirectly, workspaceUsesWebdriverio, + workspaceSupportsCatalog, workspaceUsesWebdriverioProvider, yarnSupportsPreapprovedPackages, wrapLazyPluginsInViteConfig, @@ -68,7 +69,6 @@ import { type MigrationReport } from '../report.ts'; import { PROVIDER_OVERRIDE_DROP_NAMES, pnpmMajor, - type CatalogDependencyResolver, type PnpmPackageJsonSettings, type PreparedOxlintConfigs, } from './shared.ts'; @@ -92,7 +92,11 @@ export function rewriteStandaloneProject( report, workspaceInfo.downloadPackageManager.version, ); - const catalogDependencyResolver = createCatalogDependencyResolver(projectPath, packageManager); + const catalogDependencyResolver = createCatalogDependencyResolver( + projectPath, + packageManager, + workspaceInfo.downloadPackageManager.version, + ); const vitestEcosystemPackages = collectVitestEcosystemInstallDependencyNames(projectPath); // Captured before `rewritePackageJson` strips `oxlint`; the import rewriter // reads the manifests afterwards and would no longer see the signal. @@ -377,6 +381,7 @@ export function rewriteMonorepo( const catalogDependencyResolver = createCatalogDependencyResolver( workspaceInfo.rootDir, workspaceInfo.packageManager, + workspaceInfo.downloadPackageManager.version, ); // Captured before `rewritePackageJson` strips `oxlint`; the import rewriter // reads the manifests afterwards and would no longer see the signal. @@ -414,14 +419,10 @@ export function rewriteMonorepo( ); // Catalog support: pnpm >= 9.5.0, Yarn >= 4.10.0, bun per `bunSupportsCatalog`. // An older PM falls back to concrete. - const supportCatalog = supportsCatalog( + const supportCatalog = workspaceSupportsCatalog( + workspaceInfo.rootDir, workspaceInfo.packageManager, workspaceInfo.downloadPackageManager.version, - workspaceInfo.packageManager === PackageManager.bun && - bunSupportsCatalog( - readJsonFile(path.join(workspaceInfo.rootDir, 'package.json')), - workspaceInfo.downloadPackageManager.version, - ), ); const workspaceContext = { rootDir: workspaceInfo.rootDir, @@ -447,6 +448,7 @@ export function rewriteMonorepo( workspaceUsesVitest, vitestEcosystemPackages, usesWebdriverio, + workspaceInfo.downloadPackageManager.version, ); } rewriteRootWorkspacePackageJson( diff --git a/packages/cli/src/migration/migrator/package-json.ts b/packages/cli/src/migration/migrator/package-json.ts index 95f06a2d38..31d313c822 100644 --- a/packages/cli/src/migration/migrator/package-json.ts +++ b/packages/cli/src/migration/migrator/package-json.ts @@ -1,5 +1,6 @@ import { rewriteScripts } from '../../../binding/index.js'; import { PackageManager } from '../../types/index.ts'; +import type { CatalogDependencyResolver } from '../../utils/catalog.ts'; import { VITEST_VERSION, VITE_PLUS_NAME, @@ -32,7 +33,6 @@ import { REMOVE_PACKAGES, VITEST_BROWSER_DEP_NAMES, VITEST_IS_MANAGED_OVERRIDE, - type CatalogDependencyResolver, type PackageJsonDependencyField, } from './shared.ts'; diff --git a/packages/cli/src/migration/migrator/shared.ts b/packages/cli/src/migration/migrator/shared.ts index 95a6cfcf68..690e9bf7fc 100644 --- a/packages/cli/src/migration/migrator/shared.ts +++ b/packages/cli/src/migration/migrator/shared.ts @@ -5,6 +5,7 @@ import * as prompts from '@voidzero-dev/vite-plus-prompts'; import type { OxlintConfig } from 'oxlint'; import { coerce, isLessThan, satisfies, tryParse } from 'verkit'; +import type { CatalogDependencyResolver } from '../../utils/catalog.ts'; import { VITEST_VERSION, VITE_PLUS_OVERRIDE_PACKAGES, @@ -334,13 +335,6 @@ export type PackageJsonDependencyField = | 'peerDependencies' | 'optionalDependencies'; -export type CatalogDependencyResolver = (( - catalogSpec: string, - dependencyName: string, -) => string | undefined) & { - preferredCatalogSpec: string; -}; - export function warnMigration(message: string, report?: MigrationReport) { addMigrationWarning(report, message); if (!report) { @@ -422,6 +416,29 @@ export function readPackageJsonIfExists(packageJsonPath: string): DependencyBag } } +export function pinnedPackageManagerVersion(pkg: { + packageManager?: string; + devEngines?: { packageManager?: unknown }; +}): string | undefined { + if (typeof pkg.packageManager === 'string') { + const separator = pkg.packageManager.indexOf('@'); + if (separator !== -1) { + return pkg.packageManager.slice(separator + 1); + } + } + const devEngine = pkg.devEngines?.packageManager; + if ( + typeof devEngine === 'object' && + devEngine !== null && + !Array.isArray(devEngine) && + 'version' in devEngine && + typeof devEngine.version === 'string' + ) { + return devEngine.version; + } + return undefined; +} + // pnpm v10 introduced the map-shaped `allowBuilds` and removed the implicit // "build everything" default; v9 (>= 9.5) gates builds via the list-shaped // `onlyBuiltDependencies`. Both live in pnpm-workspace.yaml or in diff --git a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts index 7cf4de01ed..ace12a90cd 100644 --- a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts +++ b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts @@ -2,6 +2,10 @@ 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 { VITEST_VERSION, VITE_PLUS_NAME, @@ -40,7 +44,6 @@ import { pnpmWorkspaceTsrsTrustPolicyExceptionPending, projectUsesVitestDirectly, pruneLegacyWrapperAliases, - readBunCatalogDependencyResolver, readPnpmWorkspaceCatalogDependencyResolver, readPnpmWorkspaceOverrides, readPnpmWorkspacePeerDependencyRules, @@ -70,9 +73,9 @@ import { REMOVE_PACKAGES, VITEST_IS_MANAGED_OVERRIDE, managedOverrideKey, + pinnedPackageManagerVersion, pnpmMajor, pnpmOverrideKey, - type CatalogDependencyResolver, type ManagedOverrideKeyStyle, type PnpmPackageJsonSettings, } from './shared.ts'; @@ -176,26 +179,6 @@ export function overridesSatisfyVitePlus( ); } -function pinnedPackageManagerVersion(pkg: BootstrapPackageJson): string | undefined { - if (typeof pkg.packageManager === 'string') { - const separator = pkg.packageManager.indexOf('@'); - if (separator !== -1) { - return pkg.packageManager.slice(separator + 1); - } - } - const devEngine = pkg.devEngines?.packageManager; - if ( - typeof devEngine === 'object' && - devEngine !== null && - !Array.isArray(devEngine) && - 'version' in devEngine && - typeof devEngine.version === 'string' - ) { - return devEngine.version; - } - return undefined; -} - function vitePlusDependencyNeedsConcreteVersion(pkg: BootstrapPackageJson): boolean { const dependencyGroups = [pkg.devDependencies, pkg.dependencies, pkg.optionalDependencies]; return dependencyGroups.some( @@ -686,7 +669,11 @@ export function detectVitePlusBootstrapPending( packageManager === PackageManager.bun && bunSupportsCatalog(pkg, resolvedPackageManagerVersion), ); - const catalogDependencyResolver = createCatalogDependencyResolver(projectPath, packageManager); + const catalogDependencyResolver = createCatalogDependencyResolver( + projectPath, + packageManager, + resolvedPackageManagerVersion, + ); const canonicalVitePlusSpec = supportCatalog ? (catalogDependencyResolver?.preferredCatalogSpec ?? 'catalog:') : VITE_PLUS_VERSION; @@ -755,7 +742,9 @@ 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) : undefined; + const bunCatalogResolver = supportCatalog + ? readBunCatalogDependencyResolver(pkg, resolvedPackageManagerVersion) + : undefined; // A `catalog:` vite-plus spec looks current, so judge its catalog value too. return ( (supportCatalog && @@ -1016,6 +1005,7 @@ export function ensureVitePlusBootstrap( const catalogDependencyResolver = createCatalogDependencyResolver( projectPath, workspaceInfo.packageManager, + workspaceInfo.downloadPackageManager.version, ); const canonicalVitePlusSpec = supportCatalog ? (catalogDependencyResolver?.preferredCatalogSpec ?? 'catalog:') @@ -1116,7 +1106,9 @@ export function ensureVitePlusBootstrap( const ensured = ensureOverrideEntries( pkg.overrides, usesVitest, - supportCatalog ? readBunCatalogDependencyResolver(pkg) : undefined, + supportCatalog + ? readBunCatalogDependencyResolver(pkg, workspaceInfo.downloadPackageManager.version) + : undefined, 'bare', usesWebdriverio, ); @@ -1293,7 +1285,13 @@ export function ensureVitePlusBootstrap( // rewriteBunCatalog runs only on monorepo roots). A standalone bun project // keeps the concrete overrides set by `ensureOverrideEntries` above. const before = fs.readFileSync(packageJsonPath, 'utf-8'); - rewriteBunCatalog(projectPath, usesVitest, vitestEcosystemPackages, usesWebdriverio); + rewriteBunCatalog( + projectPath, + usesVitest, + vitestEcosystemPackages, + usesWebdriverio, + workspaceInfo.downloadPackageManager.version, + ); const after = fs.readFileSync(packageJsonPath, 'utf-8'); result.packageJson = result.packageJson || before !== after; } diff --git a/packages/cli/src/migration/migrator/vitest-ecosystem.ts b/packages/cli/src/migration/migrator/vitest-ecosystem.ts index ba065f75a3..12df14be9d 100644 --- a/packages/cli/src/migration/migrator/vitest-ecosystem.ts +++ b/packages/cli/src/migration/migrator/vitest-ecosystem.ts @@ -4,6 +4,7 @@ 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 { VITEST_VERSION, VITE_PLUS_NAME, @@ -30,7 +31,6 @@ import { isPlainRecord, pnpmOverrideKey, vitePeerDependencyRuleRequired, - type CatalogDependencyResolver, type ManagedOverrideKeyStyle, type PackageJsonDependencyField, type PnpmPeerDependencyRules, diff --git a/packages/cli/src/migration/migrator/yarn.ts b/packages/cli/src/migration/migrator/yarn.ts index 2f042e9bfc..3717466c5d 100644 --- a/packages/cli/src/migration/migrator/yarn.ts +++ b/packages/cli/src/migration/migrator/yarn.ts @@ -5,7 +5,8 @@ import path from 'node:path'; import { coerce } from 'verkit'; import { Scalar, YAMLSeq } from 'yaml'; -import { type WorkspacePackage } from '../../types/index.ts'; +import { PackageManager, type WorkspacePackage } from '../../types/index.ts'; +import { createCatalogDependencyResolverFromCatalogs } from '../../utils/catalog.ts'; import { VITEST_AGE_GATE_EXEMPT_PACKAGES, VITE_PLUS_NAME, @@ -13,12 +14,7 @@ import { } from '../../utils/constants.ts'; import { readJsonFile } from '../../utils/json.ts'; import { editYamlFile, readYamlFile, scalarString } from '../../utils/yaml.ts'; -import { - createCatalogDependencyResolverFromCatalogs, - overridesSatisfyVitePlus, - rewriteCatalog, - usesWebdriverioProvider, -} from '../migrator.ts'; +import { overridesSatisfyVitePlus, rewriteCatalog, usesWebdriverioProvider } from '../migrator.ts'; import { type MigrationReport } from '../report.ts'; import { WEBDRIVERIO_PROVIDER, @@ -393,7 +389,13 @@ export function rewriteYarnrcYml( } // catalog (Yarn >= 4.10.0 only) if (supportCatalog) { - rewriteCatalog(doc, usesVitest, vitestEcosystemPackages, catalogAdditions); + rewriteCatalog( + doc, + usesVitest, + vitestEcosystemPackages, + catalogAdditions, + PackageManager.yarn, + ); } }); } @@ -434,12 +436,13 @@ export function yarnrcSatisfiesVitePlus( if (!supportCatalog) { return Object.hasOwn(doc, 'nodeLinker') && npmPreapprovedSatisfied; } - const resolver = createCatalogDependencyResolverFromCatalogs(doc?.catalog, doc?.catalogs); + const resolver = createCatalogDependencyResolverFromCatalogs( + doc?.catalog, + doc?.catalogs, + PackageManager.yarn, + ); const catalogName = resolver.preferredCatalogSpec.slice('catalog:'.length); - const managedCatalog = - catalogName && catalogName !== 'default' - ? doc?.catalogs?.[catalogName] - : (doc?.catalog ?? doc?.catalogs?.default); + const managedCatalog = catalogName ? doc?.catalogs?.[catalogName] : doc?.catalog; return ( Object.hasOwn(doc, 'nodeLinker') && npmPreapprovedSatisfied && diff --git a/packages/cli/src/utils/catalog.ts b/packages/cli/src/utils/catalog.ts new file mode 100644 index 0000000000..e5cd1c4ea5 --- /dev/null +++ b/packages/cli/src/utils/catalog.ts @@ -0,0 +1,150 @@ +import { coerce, isGreaterThanOrEqual } from 'verkit'; + +import { PackageManager } from '../types/index.ts'; +import { VITE_PLUS_NAME } from './constants.ts'; +import type { NpmWorkspaces } from './workspace.ts'; +import type { YamlDocument } from './yaml.ts'; + +export type CatalogDependencyResolver = (( + catalogSpec: string, + dependencyName: string, +) => string | undefined) & { + preferredCatalogSpec: string; +}; + +// Whether `version` is at least `minVersion`. A non-coercible version passes +// only when it is one of the given dist-tags, which always point at a current +// (feature-capable) release. +export function versionAtLeast(version: string, minVersion: string, tags: string[]): boolean { + const coerced = coerce(version); + if (coerced) { + return isGreaterThanOrEqual(coerced, minVersion); + } + return tags.includes(version); +} + +export function bunSupportsMergedDefaultCatalogs(version: string): boolean { + // Bun 1.4.0 unified the default catalogs: https://github.com/oven-sh/bun/pull/38333. + return versionAtLeast(version, '1.4.0', ['latest', 'canary']); +} + +export function isNamedCatalog( + catalogName: string, + packageManager: PackageManager, + version = 'latest', +): boolean { + return ( + catalogName !== '' && + (catalogName !== 'default' || + packageManager === PackageManager.yarn || + (packageManager === PackageManager.bun && !bunSupportsMergedDefaultCatalogs(version))) + ); +} + +export function createCatalogDependencyResolverFromCatalogs( + catalog: Record | undefined, + catalogs: Record> | undefined, + packageManager: PackageManager, + version = 'latest', +): CatalogDependencyResolver { + let defaultCatalog = catalog ?? catalogs?.default; + if (isNamedCatalog('default', packageManager, version)) { + defaultCatalog = catalog; + } else if (packageManager === PackageManager.bun) { + defaultCatalog = { ...catalog, ...catalogs?.default }; + } + const preferredCatalogSpec = selectPreferredCatalogSpec( + packageManager === PackageManager.bun ? defaultCatalog : catalog, + catalogs, + packageManager, + version, + ); + const resolver = (catalogSpec: string, dependencyName: string) => { + const catalogName = catalogSpec.slice('catalog:'.length); + if (isNamedCatalog(catalogName, packageManager, version)) { + return catalogs?.[catalogName]?.[dependencyName]; + } + return defaultCatalog?.[dependencyName]; + }; + return Object.assign(resolver, { preferredCatalogSpec }); +} + +export function selectPreferredCatalogSpec( + catalog: Record | undefined, + catalogs: Record> | undefined, + packageManager: PackageManager, + version = 'latest', +): string { + const candidates: Array<{ spec: string; values: Record }> = []; + if (catalog) { + candidates.push({ spec: 'catalog:', values: catalog }); + } + for (const [name, values] of Object.entries(catalogs ?? {})) { + candidates.push({ + spec: isNamedCatalog(name, packageManager, version) ? `catalog:${name}` : 'catalog:', + values, + }); + } + + // Keep the managed toolchain together when a project already has a catalog + // for it (for example Vize's `catalogs.vite-stack` and Rari's + // `catalogs.build`). Prefer vite-plus as the strongest signal, followed by + // vite and vitest. Existing dependency references keep their exact catalog + // spec; this choice is for newly injected dependencies and overrides. + for (const dependencyName of [VITE_PLUS_NAME, 'vite', 'vitest']) { + const matching = candidates.find(({ values }) => Object.hasOwn(values, dependencyName)); + if (matching) { + return matching.spec; + } + } + + if (!catalog && catalogs?.default && isNamedCatalog('default', packageManager, version)) { + return 'catalog:default'; + } + return 'catalog:'; +} + +export function getYamlCatalogPath( + doc: YamlDocument, + catalogSpec: string, + packageManager: PackageManager, +): string[] { + const catalogName = catalogSpec.slice('catalog:'.length); + if (isNamedCatalog(catalogName, packageManager)) { + return ['catalogs', catalogName]; + } + if (packageManager === PackageManager.yarn || doc.has('catalog')) { + return ['catalog']; + } + if (doc.hasIn(['catalogs', 'default'])) { + return ['catalogs', 'default']; + } + return ['catalog']; +} + +export function getBunCatalogConfig(pkg: { + workspaces?: NpmWorkspaces; + catalog?: Record; + catalogs?: Record>; +}) { + const nested = pkg.workspaces && !Array.isArray(pkg.workspaces) ? pkg.workspaces : undefined; + // Bun uses the nested catalog configuration as a whole, without falling back to root entries. + return nested?.catalog != null || nested?.catalogs != null ? nested : pkg; +} + +export function readBunCatalogDependencyResolver( + pkg: { + workspaces?: NpmWorkspaces; + catalog?: Record; + catalogs?: Record>; + }, + version = 'latest', +): CatalogDependencyResolver { + const { catalog, catalogs } = getBunCatalogConfig(pkg); + return createCatalogDependencyResolverFromCatalogs( + catalog, + catalogs, + PackageManager.bun, + version, + ); +}