vite-plus 0.1.22 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/binding/index.cjs +119 -52
  2. package/binding/index.d.cts +3222 -2
  3. package/dist/agent-aSGY0osq.js +2461 -0
  4. package/dist/bin.js +6 -5
  5. package/dist/cli-truncate-CWsmbK3p.js +867 -0
  6. package/dist/{compat-OlmU9EQz.js → compat-DXZgnEyq.js} +1 -1
  7. package/dist/config/bin.js +18 -5
  8. package/dist/{constants-kDaYqyWd.js → constants-DCBWlNrn.js} +7 -2
  9. package/dist/create/bin.js +135 -64
  10. package/dist/{define-config-IMCGDS2K.d.ts → define-config-COdn-tsn.d.ts} +7 -5
  11. package/dist/define-config.cjs +1 -1
  12. package/dist/define-config.d.ts +1 -1
  13. package/dist/define-config.js +1 -1
  14. package/dist/dist-Bapm49IR.js +3 -0
  15. package/dist/{dist-owlRxmBM.js → dist-BgQuvbtq.js} +136 -110
  16. package/dist/fmt.d.ts +1 -1
  17. package/dist/index.cjs +1 -1
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/is-fullwidth-code-point-BUNlIICg.js +8 -0
  21. package/dist/lint.d.ts +1 -1
  22. package/dist/{log-update-NRrY6krx.js → log-update-lyIiuflf.js} +111 -24
  23. package/dist/migration/bin.js +71 -30
  24. package/dist/{oxlint-plugin-config-BkQeR4FR.js → oxlint-plugin-config-B89iKTKN.js} +1 -1
  25. package/dist/oxlint-plugin.d.ts +2 -4
  26. package/dist/oxlint-plugin.js +1 -1
  27. package/dist/pack-bin.js +1 -1
  28. package/dist/pack.d.ts +1 -1
  29. package/dist/{package-BoLLED6j.js → package-PmBUZ-ve.js} +2 -2
  30. package/dist/staged/bin.js +10 -10
  31. package/dist/strip-ansi-C3wrWz9t.js +853 -0
  32. package/dist/{agent-BWLe0i9g.js → tsconfig-DlUVXT3J.js} +648 -2089
  33. package/dist/version.js +5 -5
  34. package/dist/versions.js +6 -6
  35. package/dist/{workspace-Bi_9spVt.js → workspace-DElv730L.js} +13 -12
  36. package/dist/wrap-ansi-CeQuiQ31.js +2 -0
  37. package/dist/{wrap-ansi-DtUeUCjE.js → wrap-ansi-k7Dn4VtV.js} +1 -1
  38. package/docs/config/run.md +39 -4
  39. package/docs/guide/cache.md +10 -1
  40. package/docs/guide/env.md +3 -0
  41. package/docs/guide/ide-integration.md +2 -2
  42. package/docs/guide/install.md +2 -0
  43. package/docs/guide/run.md +2 -0
  44. package/docs/guide/troubleshooting.md +5 -2
  45. package/package.json +18 -18
  46. package/templates/monorepo/_gitignore +1 -0
  47. package/dist/cli-truncate-B62YnW2m.js +0 -138
  48. package/dist/dist-DZfItHAr.js +0 -3
  49. package/dist/slice-ansi-e4todZeH.js +0 -113
  50. package/dist/strip-ansi-D-eYYcD2.js +0 -198
  51. package/dist/tsconfig-BVyzXJ_o.js +0 -517
  52. package/dist/wrap-ansi-3S3qJ7j8.js +0 -2
  53. /package/dist/{chunk-q7NCDQ7-.js → chunk-DnnnRqeS.js} +0 -0
  54. /package/dist/{define-config-GqLoRwH9.cjs → define-config-BR1Y88zz.cjs} +0 -0
  55. /package/dist/{define-config-CzWdQTt2.js → define-config-BRC7qPNE.js} +0 -0
  56. /package/dist/{help-DK5wuu34.js → help-YP84FSEz.js} +0 -0
  57. /package/dist/{lib-DpwyUJWo.js → lib-L3DWSRQp.js} +0 -0
  58. /package/dist/{main-DhsO6ndq.js → main-DpJl3LoU.js} +0 -0
  59. /package/dist/{pack-K7H72Cum.d.ts → pack-Ciiho0Tq.d.ts} +0 -0
  60. /package/dist/{report-CYPv1VK1.js → report-DgSBQUdz.js} +0 -0
  61. /package/dist/{resolve-vite-config-C5AjksTj.js → resolve-vite-config-TTvhycU1.js} +0 -0
  62. /package/dist/{terminal-D_Kg-AA6.js → terminal-uTv0ZaMr.js} +0 -0
@@ -0,0 +1,2461 @@
1
+ import { r as __toESM } from "./chunk-DnnnRqeS.js";
2
+ import { a as VITE_PLUS_OVERRIDE_PACKAGES, c as isForceOverrideMode, i as VITE_PLUS_NAME, n as BASEURL_TSCONFIG_WARNING, o as VITE_PLUS_VERSION } from "./constants-DCBWlNrn.js";
3
+ import { i as ensureVitePlusImportRuleDefaults, r as createDefaultVitePlusLintConfig } from "./oxlint-plugin-config-B89iKTKN.js";
4
+ import { A as q, C as log, E as select, M as runCommandSilently, N as require_cross_spawn, a as removeDeprecatedTsconfigFalseOption, i as hasBaseUrlInTsconfig, n as findTsconfigFiles, o as rewriteTypesInTsconfig, s as cancelAndExit, u as getSpinner, v as PackageManager, w as multiselect, x as confirm, y as require_semver } from "./tsconfig-DlUVXT3J.js";
5
+ import { t as require_dist } from "./dist-BgQuvbtq.js";
6
+ import { c as editJsonFile, l as isJsonFile, n as detectPackageMetadata, u as readJsonFile } from "./package-PmBUZ-ve.js";
7
+ import { n as addMigrationWarning, t as addManualStep } from "./report-DgSBQUdz.js";
8
+ import path from "node:path";
9
+ import { hasConfigKey, mergeJsonConfig, mergeTsdownConfig, rewriteEslint, rewriteImportsInDirectory, rewritePrettier, rewriteScripts } from "../binding/index.js";
10
+ import fs from "node:fs";
11
+ import { styleText } from "node:util";
12
+ import fsPromises from "node:fs/promises";
13
+ //#region src/utils/path.ts
14
+ var import_cross_spawn = /* @__PURE__ */ __toESM(require_cross_spawn(), 1);
15
+ var import_semver = /* @__PURE__ */ __toESM(require_semver(), 1);
16
+ var import_dist = require_dist();
17
+ function findPkgRoot() {
18
+ let dir = import.meta.dirname;
19
+ while (dir !== path.dirname(dir)) {
20
+ if (fs.existsSync(path.join(dir, "package.json"))) return dir;
21
+ dir = path.dirname(dir);
22
+ }
23
+ return dir;
24
+ }
25
+ const pkgRoot = findPkgRoot();
26
+ const templatesDir = path.join(pkgRoot, "templates");
27
+ const rulesDir = path.join(pkgRoot, "rules");
28
+ function displayRelative(to, from = process.cwd()) {
29
+ return path.relative(from, to).replaceAll("\\", "/");
30
+ }
31
+ //#endregion
32
+ //#region src/utils/yaml.ts
33
+ function readYamlFile(file) {
34
+ return (0, import_dist.parse)(fs.readFileSync(file, "utf-8"));
35
+ }
36
+ function editYamlFile(file, callback) {
37
+ const doc = (0, import_dist.parseDocument)(fs.readFileSync(file, "utf-8"));
38
+ callback(doc);
39
+ fs.writeFileSync(file, doc.toString({ singleQuote: true }), "utf-8");
40
+ }
41
+ function scalarString(value) {
42
+ return new import_dist.Scalar(value);
43
+ }
44
+ //#endregion
45
+ //#region src/migration/detector.ts
46
+ const PRETTIER_PACKAGE_JSON_CONFIG = "package.json#prettier";
47
+ const PRETTIER_CONFIG_FILES = [
48
+ ".prettierrc",
49
+ ".prettierrc.json",
50
+ ".prettierrc.jsonc",
51
+ ".prettierrc.yaml",
52
+ ".prettierrc.yml",
53
+ ".prettierrc.toml",
54
+ ".prettierrc.js",
55
+ ".prettierrc.cjs",
56
+ ".prettierrc.mjs",
57
+ ".prettierrc.ts",
58
+ ".prettierrc.cts",
59
+ ".prettierrc.mts",
60
+ "prettier.config.js",
61
+ "prettier.config.cjs",
62
+ "prettier.config.mjs",
63
+ "prettier.config.ts",
64
+ "prettier.config.cts",
65
+ "prettier.config.mts"
66
+ ];
67
+ function detectConfigs(projectPath) {
68
+ const configs = {};
69
+ for (const config of [
70
+ "vite.config.ts",
71
+ "vite.config.mts",
72
+ "vite.config.cts",
73
+ "vite.config.js",
74
+ "vite.config.mjs",
75
+ "vite.config.cjs"
76
+ ]) if (fs.existsSync(path.join(projectPath, config))) {
77
+ configs.viteConfig = config;
78
+ break;
79
+ }
80
+ for (const config of [
81
+ "vitest.config.ts",
82
+ "vitest.config.mts",
83
+ "vitest.config.cts",
84
+ "vitest.config.js",
85
+ "vitest.config.mjs",
86
+ "vitest.config.cjs"
87
+ ]) if (fs.existsSync(path.join(projectPath, config))) {
88
+ configs.vitestConfig = config;
89
+ break;
90
+ }
91
+ for (const config of [
92
+ "tsdown.config.ts",
93
+ "tsdown.config.mts",
94
+ "tsdown.config.cts",
95
+ "tsdown.config.js",
96
+ "tsdown.config.mjs",
97
+ "tsdown.config.cjs",
98
+ "tsdown.config.json",
99
+ "tsdown.config"
100
+ ]) if (fs.existsSync(path.join(projectPath, config))) {
101
+ configs.tsdownConfig = config;
102
+ break;
103
+ }
104
+ for (const config of [".oxlintrc.json", ".oxlintrc.jsonc"]) if (fs.existsSync(path.join(projectPath, config))) {
105
+ configs.oxlintConfig = config;
106
+ break;
107
+ }
108
+ for (const config of [".oxfmtrc.json", ".oxfmtrc.jsonc"]) if (fs.existsSync(path.join(projectPath, config))) {
109
+ configs.oxfmtConfig = config;
110
+ break;
111
+ }
112
+ for (const config of [
113
+ "eslint.config.js",
114
+ "eslint.config.mjs",
115
+ "eslint.config.cjs",
116
+ "eslint.config.ts",
117
+ "eslint.config.mts",
118
+ "eslint.config.cts"
119
+ ]) if (fs.existsSync(path.join(projectPath, config))) {
120
+ configs.eslintConfig = config;
121
+ break;
122
+ }
123
+ for (const config of [
124
+ ".eslintrc",
125
+ ".eslintrc.json",
126
+ ".eslintrc.js",
127
+ ".eslintrc.cjs",
128
+ ".eslintrc.yaml",
129
+ ".eslintrc.yml"
130
+ ]) if (fs.existsSync(path.join(projectPath, config))) {
131
+ configs.eslintLegacyConfig = config;
132
+ break;
133
+ }
134
+ for (const config of PRETTIER_CONFIG_FILES) if (fs.existsSync(path.join(projectPath, config))) {
135
+ configs.prettierConfig = config;
136
+ break;
137
+ }
138
+ if (fs.existsSync(path.join(projectPath, ".prettierignore"))) configs.prettierIgnore = true;
139
+ if (fs.existsSync(path.join(projectPath, ".nvmrc"))) configs.nvmrcFile = true;
140
+ const packageJsonPath = path.join(projectPath, "package.json");
141
+ if (fs.existsSync(packageJsonPath)) try {
142
+ const content = fs.readFileSync(packageJsonPath, "utf8");
143
+ const pkg = JSON.parse(content);
144
+ if (!configs.prettierConfig && pkg.prettier) configs.prettierConfig = PRETTIER_PACKAGE_JSON_CONFIG;
145
+ const voltaNode = pkg.volta?.node;
146
+ if (typeof voltaNode === "string") configs.voltaNode = voltaNode;
147
+ } catch {}
148
+ return configs;
149
+ }
150
+ //#endregion
151
+ //#region src/migration/migrator.ts
152
+ const LINT_STAGED_JSON_CONFIG_FILES = [".lintstagedrc.json", ".lintstagedrc"];
153
+ const LINT_STAGED_OTHER_CONFIG_FILES = [
154
+ ".lintstagedrc.yaml",
155
+ ".lintstagedrc.yml",
156
+ ".lintstagedrc.mjs",
157
+ "lint-staged.config.mjs",
158
+ ".lintstagedrc.cjs",
159
+ "lint-staged.config.cjs",
160
+ ".lintstagedrc.js",
161
+ "lint-staged.config.js",
162
+ ".lintstagedrc.ts",
163
+ "lint-staged.config.ts",
164
+ ".lintstagedrc.mts",
165
+ "lint-staged.config.mts",
166
+ ".lintstagedrc.cts",
167
+ "lint-staged.config.cts"
168
+ ];
169
+ const LINT_STAGED_ALL_CONFIG_FILES = [...LINT_STAGED_JSON_CONFIG_FILES, ...LINT_STAGED_OTHER_CONFIG_FILES];
170
+ const REMOVE_PACKAGES = [
171
+ "oxlint",
172
+ "oxlint-tsgolint",
173
+ "oxfmt",
174
+ "tsdown",
175
+ "@vitest/browser",
176
+ "@vitest/browser-preview",
177
+ "@vitest/browser-playwright",
178
+ "@vitest/browser-webdriverio"
179
+ ];
180
+ const BROWSER_PROVIDER_PEER_DEPS = {
181
+ "@vitest/browser-playwright": "playwright",
182
+ "@vitest/browser-webdriverio": "webdriverio"
183
+ };
184
+ const PUBLIC_PEER_DEPENDENCY_FALLBACKS = {
185
+ vite: "*",
186
+ vitest: "*"
187
+ };
188
+ const OXLINT_NATIVE_PLUGINS = new Set([
189
+ "eslint",
190
+ "react",
191
+ "unicorn",
192
+ "typescript",
193
+ "oxc",
194
+ "import",
195
+ "jsdoc",
196
+ "jest",
197
+ "vitest",
198
+ "jsx-a11y",
199
+ "nextjs",
200
+ "react-perf",
201
+ "promise",
202
+ "node",
203
+ "vue"
204
+ ]);
205
+ function warnMigration(message, report) {
206
+ addMigrationWarning(report, message);
207
+ if (!report) log.warn(message);
208
+ }
209
+ function infoMigration(message, report) {
210
+ addManualStep(report, message);
211
+ if (!report) log.info(message);
212
+ }
213
+ function checkViteVersion(projectPath) {
214
+ return checkPackageVersion(projectPath, "vite", "7.0.0");
215
+ }
216
+ function checkVitestVersion(projectPath) {
217
+ return checkPackageVersion(projectPath, "vitest", "4.0.0");
218
+ }
219
+ /**
220
+ * Check the package version is supported by auto migration
221
+ * @param projectPath - The path to the project
222
+ * @param name - The name of the package
223
+ * @param minVersion - The minimum version of the package
224
+ * @returns true if the package version is supported by auto migration
225
+ */
226
+ function checkPackageVersion(projectPath, name, minVersion) {
227
+ const metadata = detectPackageMetadata(projectPath, name);
228
+ if (!metadata || metadata.name !== name) return true;
229
+ if (import_semver.default.satisfies(metadata.version, `<${minVersion}`)) {
230
+ const packageJsonFilePath = path.join(projectPath, "package.json");
231
+ log.error(`✘ ${name}@${metadata.version} in ${displayRelative(packageJsonFilePath)} is not supported by auto migration`);
232
+ log.info(`Please upgrade ${name} to version >=${minVersion} first`);
233
+ return false;
234
+ }
235
+ return true;
236
+ }
237
+ function detectEslintProject(projectPath, packages) {
238
+ const packageJsonPath = path.join(projectPath, "package.json");
239
+ if (!fs.existsSync(packageJsonPath)) return { hasDependency: false };
240
+ const pkg = readJsonFile(packageJsonPath);
241
+ let hasDependency = !!(pkg.devDependencies?.eslint || pkg.dependencies?.eslint);
242
+ const configs = detectConfigs(projectPath);
243
+ let configFile = configs.eslintConfig;
244
+ const legacyConfigFile = configs.eslintLegacyConfig;
245
+ if (!hasDependency && packages) for (const wp of packages) {
246
+ const pkgJsonPath = path.join(projectPath, wp.path, "package.json");
247
+ if (!fs.existsSync(pkgJsonPath)) continue;
248
+ const wpPkg = readJsonFile(pkgJsonPath);
249
+ if (wpPkg.devDependencies?.eslint || wpPkg.dependencies?.eslint) {
250
+ hasDependency = true;
251
+ break;
252
+ }
253
+ }
254
+ return {
255
+ hasDependency,
256
+ configFile,
257
+ legacyConfigFile
258
+ };
259
+ }
260
+ /**
261
+ * Run a `vp dlx @oxlint/migrate` step with graceful error handling.
262
+ * Returns true on success, false on failure (spawn error or non-zero exit).
263
+ */
264
+ async function runOxlintMigrateStep(vpBin, cwd, migratePackage, args, spinner, failMessage, manualHint) {
265
+ try {
266
+ const result = await runCommandSilently({
267
+ command: vpBin,
268
+ args: [
269
+ "dlx",
270
+ migratePackage,
271
+ ...args
272
+ ],
273
+ cwd,
274
+ envs: process.env
275
+ });
276
+ if (result.exitCode !== 0) {
277
+ spinner.stop(failMessage);
278
+ const stderr = result.stderr.toString().trim();
279
+ if (stderr) log.warn(`⚠ ${stderr}`);
280
+ log.info(manualHint);
281
+ return false;
282
+ }
283
+ return true;
284
+ } catch {
285
+ spinner.stop(failMessage);
286
+ log.info(manualHint);
287
+ return false;
288
+ }
289
+ }
290
+ async function migrateEslintToOxlint(projectPath, interactive, eslintConfigFile, packages, options) {
291
+ const vpBin = process.env.VP_CLI_BIN ?? "vp";
292
+ const spinner = options?.silent ? {
293
+ start: () => {},
294
+ stop: () => {},
295
+ pause: () => {},
296
+ resume: () => {},
297
+ cancel: () => {},
298
+ error: () => {},
299
+ clear: () => {},
300
+ message: () => {},
301
+ isCancelled: false
302
+ } : getSpinner(interactive);
303
+ if (eslintConfigFile) {
304
+ const { versions } = await import("./versions.js");
305
+ const migratePackage = `@oxlint/migrate@${versions.oxlint}`;
306
+ const migrateArgs = [
307
+ "--merge",
308
+ ...!hasBaseUrlInTsconfig(projectPath) ? ["--type-aware"] : [],
309
+ "--with-nursery",
310
+ "--details"
311
+ ];
312
+ spinner.start("Migrating ESLint config to Oxlint...");
313
+ if (!await runOxlintMigrateStep(vpBin, projectPath, migratePackage, migrateArgs, spinner, "ESLint migration failed", `You can run \`vp dlx ${migratePackage} ${migrateArgs.join(" ")}\` manually later`)) return false;
314
+ spinner.stop("ESLint config migrated to .oxlintrc.json");
315
+ spinner.start("Replacing ESLint comments with Oxlint equivalents...");
316
+ if (await runOxlintMigrateStep(vpBin, projectPath, migratePackage, ["--replace-eslint-comments"], spinner, "ESLint comment replacement failed", `You can run \`vp dlx ${migratePackage} --replace-eslint-comments\` manually later`)) spinner.stop("ESLint comments replaced");
317
+ }
318
+ if (options?.report) options.report.eslintMigrated = true;
319
+ const preserveJsPlugins = collectJsPluginPackageNames(projectPath);
320
+ const cleanupTargets = [projectPath, ...(packages ?? []).map((p) => path.join(projectPath, p.path))];
321
+ for (const target of cleanupTargets) {
322
+ if (!fs.existsSync(path.join(target, "package.json"))) continue;
323
+ deleteEslintConfigFiles(target, options?.report, options?.silent);
324
+ rewriteEslintPackageJson(path.join(target, "package.json"), preserveJsPlugins);
325
+ rewriteEslintLintStagedConfigFiles(target, options?.report);
326
+ }
327
+ return true;
328
+ }
329
+ /**
330
+ * Read `<projectPath>/.oxlintrc.json` (if any) and collect the package
331
+ * names referenced via `lint.jsPlugins[]` string entries. Object-form
332
+ * entries (`{ name, specifier }`) and local-path specifiers (`./X`,
333
+ * `../X`, `/X`) are excluded — neither maps to a `package.json` entry
334
+ * we'd accidentally strip.
335
+ */
336
+ function collectJsPluginPackageNames(projectPath) {
337
+ const out = /* @__PURE__ */ new Set();
338
+ const oxlintConfigPath = path.join(projectPath, ".oxlintrc.json");
339
+ if (!fs.existsSync(oxlintConfigPath)) return out;
340
+ let config;
341
+ try {
342
+ config = readJsonFile(oxlintConfigPath, true);
343
+ } catch {
344
+ return out;
345
+ }
346
+ const collectFrom = (jsPlugins) => {
347
+ for (const entry of jsPlugins ?? []) {
348
+ if (typeof entry !== "string") continue;
349
+ if (entry.startsWith("./") || entry.startsWith("../") || entry.startsWith("/")) continue;
350
+ out.add(entry);
351
+ }
352
+ };
353
+ collectFrom(config.jsPlugins);
354
+ if (Array.isArray(config.overrides)) for (const override of config.overrides) collectFrom(override.jsPlugins);
355
+ return out;
356
+ }
357
+ function deleteEslintConfigFiles(basePath, report, silent = false) {
358
+ const configs = detectConfigs(basePath);
359
+ for (const file of [configs.eslintConfig, configs.eslintLegacyConfig]) if (file) {
360
+ const configPath = path.join(basePath, file);
361
+ if (fs.existsSync(configPath)) {
362
+ fs.unlinkSync(configPath);
363
+ if (report) report.removedConfigCount++;
364
+ if (!silent) log.success(`✔ Removed ${displayRelative(configPath)}`);
365
+ }
366
+ }
367
+ }
368
+ const ESLINT_ECOSYSTEM_NAMES = new Set([
369
+ "eslint",
370
+ "typescript-eslint",
371
+ "eslintrc",
372
+ "eslint-utils",
373
+ "eslint-visitor-keys",
374
+ "eslint-scope",
375
+ "eslint-define-config",
376
+ "eslint-doc-generator",
377
+ "@typescript-eslint/eslint-plugin",
378
+ "@typescript-eslint/parser",
379
+ "@typescript-eslint/rule-tester"
380
+ ]);
381
+ const ESLINT_ECOSYSTEM_PREFIXES = [
382
+ "eslint-plugin-",
383
+ "eslint-config-",
384
+ "eslint-formatter-"
385
+ ];
386
+ const ESLINT_ECOSYSTEM_SCOPES = [
387
+ "@eslint/",
388
+ "@eslint-community/",
389
+ "@angular-eslint/"
390
+ ];
391
+ /**
392
+ * Decide whether a dependency entry should be removed alongside `eslint`
393
+ * itself. The set is intentionally broad: anything whose only purpose is
394
+ * to extend, configure, format, or wire ESLint becomes dead weight after
395
+ * migration. `@types/<X>` packages are checked symmetrically with `<X>`
396
+ * so type-only counterparts of removed runtime packages also go.
397
+ */
398
+ function isEslintEcosystemDep(name) {
399
+ const stripped = name.startsWith("@types/") ? name.slice(7) : name;
400
+ if (ESLINT_ECOSYSTEM_NAMES.has(stripped)) return true;
401
+ if (ESLINT_ECOSYSTEM_PREFIXES.some((p) => stripped.startsWith(p))) return true;
402
+ if (ESLINT_ECOSYSTEM_SCOPES.some((s) => stripped.startsWith(s))) return true;
403
+ // @vitest/eslint-plugin
404
+ if (/^@[^/]+\/eslint-(plugin|config|formatter)(-.+)?$/.test(stripped)) return true;
405
+ return false;
406
+ }
407
+ /**
408
+ * Rewrite a project's `package.json` after ESLint has been migrated to
409
+ * Oxlint: drop every ESLint-ecosystem dependency (see
410
+ * `isEslintEcosystemDep`), strip empty containers, and rewrite eslint
411
+ * tokens in scripts / lint-staged. Applied uniformly to the root and to
412
+ * every workspace package — the migration treats the whole workspace as
413
+ * in scope for adoption, so a half-cleanup at the workspace level would
414
+ * be inconsistent with the rest of the flow (which already replaces
415
+ * vite-related overrides and adds vite-plus across all packages).
416
+ *
417
+ * `preserveJsPlugins` names packages that `@oxlint/migrate` referenced
418
+ * via `lint.jsPlugins` and that Oxlint will need to `import()` at lint
419
+ * time. They override `isEslintEcosystemDep` so the generated config
420
+ * isn't immediately invalidated by the cleanup step.
421
+ */
422
+ function rewriteEslintPackageJson(packageJsonPath, preserveJsPlugins = /* @__PURE__ */ new Set()) {
423
+ editJsonFile(packageJsonPath, (pkg) => {
424
+ let changed = false;
425
+ for (const field of [
426
+ "devDependencies",
427
+ "dependencies",
428
+ "peerDependencies",
429
+ "optionalDependencies"
430
+ ]) {
431
+ const deps = pkg[field];
432
+ if (!deps) continue;
433
+ let removedAny = false;
434
+ for (const name of Object.keys(deps)) {
435
+ if (preserveJsPlugins.has(name)) continue;
436
+ if (isEslintEcosystemDep(name)) {
437
+ delete deps[name];
438
+ changed = true;
439
+ removedAny = true;
440
+ }
441
+ }
442
+ if (removedAny && Object.keys(deps).length === 0) delete pkg[field];
443
+ }
444
+ if (pkg.scripts) {
445
+ const updated = rewriteEslint(JSON.stringify(pkg.scripts));
446
+ if (updated) {
447
+ pkg.scripts = JSON.parse(updated);
448
+ changed = true;
449
+ }
450
+ }
451
+ if (pkg["lint-staged"]) {
452
+ const updated = rewriteEslint(JSON.stringify(pkg["lint-staged"]));
453
+ if (updated) {
454
+ pkg["lint-staged"] = JSON.parse(updated);
455
+ changed = true;
456
+ }
457
+ }
458
+ return changed ? pkg : void 0;
459
+ });
460
+ }
461
+ /**
462
+ * Rewrite tool references in lint-staged config files (JSON ones are rewritten,
463
+ * non-JSON ones get a warning).
464
+ */
465
+ function rewriteToolLintStagedConfigFiles(projectPath, rewriteFn, toolName, report) {
466
+ for (const filename of LINT_STAGED_JSON_CONFIG_FILES) {
467
+ const configPath = path.join(projectPath, filename);
468
+ if (!fs.existsSync(configPath)) continue;
469
+ if (filename === ".lintstagedrc" && !isJsonFile(configPath)) {
470
+ warnMigration(`${displayRelative(configPath)} is not JSON — please update ${toolName} references manually`, report);
471
+ continue;
472
+ }
473
+ editJsonFile(configPath, (config) => {
474
+ const updated = rewriteFn(JSON.stringify(config));
475
+ if (updated) return JSON.parse(updated);
476
+ });
477
+ }
478
+ for (const filename of LINT_STAGED_OTHER_CONFIG_FILES) {
479
+ const configPath = path.join(projectPath, filename);
480
+ if (!fs.existsSync(configPath)) continue;
481
+ warnMigration(`${displayRelative(configPath)} — please update ${toolName} references manually`, report);
482
+ }
483
+ }
484
+ function rewriteEslintLintStagedConfigFiles(projectPath, report) {
485
+ rewriteToolLintStagedConfigFiles(projectPath, rewriteEslint, "eslint", report);
486
+ }
487
+ function detectPrettierProject(projectPath, packages) {
488
+ const packageJsonPath = path.join(projectPath, "package.json");
489
+ if (!fs.existsSync(packageJsonPath)) return { hasDependency: false };
490
+ const pkg = readJsonFile(packageJsonPath);
491
+ let hasDependency = !!(pkg.devDependencies?.prettier || pkg.dependencies?.prettier);
492
+ const configFile = detectConfigs(projectPath).prettierConfig;
493
+ if (!hasDependency && packages) for (const wp of packages) {
494
+ const pkgJsonPath = path.join(projectPath, wp.path, "package.json");
495
+ if (!fs.existsSync(pkgJsonPath)) continue;
496
+ const wpPkg = readJsonFile(pkgJsonPath);
497
+ if (wpPkg.devDependencies?.prettier || wpPkg.dependencies?.prettier) {
498
+ hasDependency = true;
499
+ break;
500
+ }
501
+ }
502
+ return {
503
+ hasDependency,
504
+ configFile
505
+ };
506
+ }
507
+ /**
508
+ * Run `vp fmt --migrate=prettier` step with graceful error handling.
509
+ * Returns true on success, false on failure.
510
+ */
511
+ async function runPrettierMigrateStep(vpBin, cwd, spinner, failMessage, manualHint) {
512
+ try {
513
+ const result = await runCommandSilently({
514
+ command: vpBin,
515
+ args: ["fmt", "--migrate=prettier"],
516
+ cwd,
517
+ envs: process.env
518
+ });
519
+ if (result.exitCode !== 0) {
520
+ spinner.stop(failMessage);
521
+ const stderr = result.stderr.toString().trim();
522
+ if (stderr) log.warn(`⚠ ${stderr}`);
523
+ log.info(manualHint);
524
+ return false;
525
+ }
526
+ return true;
527
+ } catch {
528
+ spinner.stop(failMessage);
529
+ log.info(manualHint);
530
+ return false;
531
+ }
532
+ }
533
+ async function migratePrettierToOxfmt(projectPath, interactive, prettierConfigFile, packages, options) {
534
+ const vpBin = process.env.VP_CLI_BIN ?? "vp";
535
+ const spinner = options?.silent ? {
536
+ start: () => {},
537
+ stop: () => {},
538
+ pause: () => {},
539
+ resume: () => {},
540
+ cancel: () => {},
541
+ error: () => {},
542
+ clear: () => {},
543
+ message: () => {},
544
+ isCancelled: false
545
+ } : getSpinner(interactive);
546
+ if (prettierConfigFile) {
547
+ let tempPrettierConfig;
548
+ if (prettierConfigFile === "package.json#prettier") {
549
+ const pkg = readJsonFile(path.join(projectPath, "package.json"));
550
+ if (pkg.prettier) {
551
+ tempPrettierConfig = path.join(projectPath, ".prettierrc.json");
552
+ fs.writeFileSync(tempPrettierConfig, JSON.stringify(pkg.prettier, null, 2));
553
+ } else return true;
554
+ }
555
+ try {
556
+ spinner.start("Migrating Prettier config to Oxfmt...");
557
+ if (!await runPrettierMigrateStep(vpBin, projectPath, spinner, "Prettier migration failed", "You can run `vp fmt --migrate=prettier` manually later")) return false;
558
+ spinner.stop("Prettier config migrated to .oxfmtrc.json");
559
+ } finally {
560
+ if (tempPrettierConfig) try {
561
+ fs.unlinkSync(tempPrettierConfig);
562
+ } catch {}
563
+ }
564
+ }
565
+ if (options?.report) options.report.prettierMigrated = true;
566
+ deletePrettierConfigFiles(projectPath, options?.report, options?.silent);
567
+ rewritePrettierPackageJson(path.join(projectPath, "package.json"));
568
+ if (packages) for (const pkg of packages) rewritePrettierPackageJson(path.join(projectPath, pkg.path, "package.json"));
569
+ rewritePrettierLintStagedConfigFiles(projectPath, options?.report);
570
+ const prettierIgnorePath = path.join(projectPath, ".prettierignore");
571
+ if (fs.existsSync(prettierIgnorePath)) warnMigration(`${displayRelative(prettierIgnorePath)} found — Oxfmt supports .prettierignore, but using the \`ignorePatterns\` option is recommended.`, options?.report);
572
+ return true;
573
+ }
574
+ function deletePrettierConfigFiles(basePath, report, silent = false) {
575
+ const configs = detectConfigs(basePath);
576
+ if (configs.prettierConfig && configs.prettierConfig !== "package.json#prettier") {
577
+ const configPath = path.join(basePath, configs.prettierConfig);
578
+ if (fs.existsSync(configPath)) {
579
+ fs.unlinkSync(configPath);
580
+ if (report) report.removedConfigCount++;
581
+ if (!silent) log.success(`✔ Removed ${displayRelative(configPath)}`);
582
+ }
583
+ }
584
+ for (const file of PRETTIER_CONFIG_FILES) {
585
+ if (file === configs.prettierConfig) continue;
586
+ const configPath = path.join(basePath, file);
587
+ if (fs.existsSync(configPath)) {
588
+ fs.unlinkSync(configPath);
589
+ if (report) report.removedConfigCount++;
590
+ if (!silent) log.success(`✔ Removed ${displayRelative(configPath)}`);
591
+ }
592
+ }
593
+ editJsonFile(path.join(basePath, "package.json"), (pkg) => {
594
+ if (pkg.prettier) {
595
+ delete pkg.prettier;
596
+ return pkg;
597
+ }
598
+ });
599
+ }
600
+ function rewritePrettierPackageJson(packageJsonPath) {
601
+ if (!fs.existsSync(packageJsonPath)) return;
602
+ editJsonFile(packageJsonPath, (pkg) => {
603
+ let changed = false;
604
+ if (pkg.devDependencies) {
605
+ for (const dep of Object.keys(pkg.devDependencies)) if (dep === "prettier" || dep.startsWith("prettier-plugin-")) {
606
+ delete pkg.devDependencies[dep];
607
+ changed = true;
608
+ }
609
+ }
610
+ if (pkg.dependencies) {
611
+ for (const dep of Object.keys(pkg.dependencies)) if (dep === "prettier" || dep.startsWith("prettier-plugin-")) {
612
+ delete pkg.dependencies[dep];
613
+ changed = true;
614
+ }
615
+ }
616
+ if (pkg.scripts) {
617
+ const updated = rewritePrettier(JSON.stringify(pkg.scripts));
618
+ if (updated) {
619
+ pkg.scripts = JSON.parse(updated);
620
+ changed = true;
621
+ }
622
+ }
623
+ if (pkg["lint-staged"]) {
624
+ const updated = rewritePrettier(JSON.stringify(pkg["lint-staged"]));
625
+ if (updated) {
626
+ pkg["lint-staged"] = JSON.parse(updated);
627
+ changed = true;
628
+ }
629
+ }
630
+ return changed ? pkg : void 0;
631
+ });
632
+ }
633
+ function rewritePrettierLintStagedConfigFiles(projectPath, report) {
634
+ rewriteToolLintStagedConfigFiles(projectPath, rewritePrettier, "prettier", report);
635
+ }
636
+ function cleanupDeprecatedTsconfigOptions(projectPath, silent = false, report) {
637
+ const deprecatedOptions = ["esModuleInterop", "allowSyntheticDefaultImports"];
638
+ const files = findTsconfigFiles(projectPath);
639
+ for (const filePath of files) for (const name of deprecatedOptions) if (removeDeprecatedTsconfigFalseOption(filePath, name)) {
640
+ if (report) report.removedConfigCount++;
641
+ if (!silent) log.success(`✔ Removed ${name}: false from ${displayRelative(filePath)}`);
642
+ warnMigration(`Removed \`"${name}": false\` from ${displayRelative(filePath)} — this option has been deprecated. See https://github.com/oxc-project/tsgolint/issues/351, https://github.com/microsoft/TypeScript/issues/62529`, report);
643
+ }
644
+ }
645
+ function rewriteTsconfigTypes(projectPath, silent = false, report) {
646
+ const files = findTsconfigFiles(projectPath);
647
+ for (const filePath of files) if (rewriteTypesInTsconfig(filePath)) {
648
+ if (report) report.removedConfigCount++;
649
+ if (!silent) log.success(`✔ Rewrote types in ${displayRelative(filePath)}`);
650
+ }
651
+ }
652
+ const FRAMEWORK_SHIMS = {
653
+ vue: [
654
+ "declare module '*.vue' {",
655
+ " import type { DefineComponent } from 'vue';",
656
+ " const component: DefineComponent<{}, {}, unknown>;",
657
+ " export default component;",
658
+ "}"
659
+ ].join("\n"),
660
+ astro: "/// <reference types=\"astro/client\" />"
661
+ };
662
+ function detectFramework(projectPath) {
663
+ const packageJsonPath = path.join(projectPath, "package.json");
664
+ if (!fs.existsSync(packageJsonPath)) return [];
665
+ const pkg = readJsonFile(packageJsonPath);
666
+ const allDeps = {
667
+ ...pkg.dependencies,
668
+ ...pkg.devDependencies
669
+ };
670
+ return ["vue", "astro"].filter((framework) => !!allDeps[framework]);
671
+ }
672
+ function getEnvDtsPath(projectPath) {
673
+ const srcEnvDts = path.join(projectPath, "src", "env.d.ts");
674
+ const rootEnvDts = path.join(projectPath, "env.d.ts");
675
+ for (const candidate of [srcEnvDts, rootEnvDts]) if (fs.existsSync(candidate)) return candidate;
676
+ return fs.existsSync(path.join(projectPath, "src")) ? srcEnvDts : rootEnvDts;
677
+ }
678
+ function hasFrameworkShim(projectPath, framework) {
679
+ const dirsToScan = [projectPath, path.join(projectPath, "src")];
680
+ for (const dir of dirsToScan) {
681
+ if (!fs.existsSync(dir)) continue;
682
+ let entries;
683
+ try {
684
+ entries = fs.readdirSync(dir);
685
+ } catch {
686
+ continue;
687
+ }
688
+ for (const entry of entries) {
689
+ if (!entry.endsWith(".d.ts")) continue;
690
+ const content = fs.readFileSync(path.join(dir, entry), "utf-8");
691
+ if (framework === "astro") {
692
+ if (content.includes("astro/client")) return true;
693
+ } else if (content.includes(`'*.${framework}'`) || content.includes(`"*.${framework}"`)) return true;
694
+ }
695
+ }
696
+ return false;
697
+ }
698
+ function addFrameworkShim(projectPath, framework, report) {
699
+ const envDtsPath = getEnvDtsPath(projectPath);
700
+ const shim = FRAMEWORK_SHIMS[framework];
701
+ if (fs.existsSync(envDtsPath)) {
702
+ const existing = fs.readFileSync(envDtsPath, "utf-8");
703
+ fs.writeFileSync(envDtsPath, `${existing.trimEnd()}\n\n${shim}\n`, "utf-8");
704
+ } else {
705
+ fs.mkdirSync(path.dirname(envDtsPath), { recursive: true });
706
+ fs.writeFileSync(envDtsPath, `${shim}\n`, "utf-8");
707
+ }
708
+ if (report) report.frameworkShimAdded = true;
709
+ }
710
+ /**
711
+ * Rewrite standalone project to add vite-plus dependencies
712
+ * @param projectPath - The path to the project
713
+ */
714
+ function rewriteStandaloneProject(projectPath, workspaceInfo, skipStagedMigration, silent = false, report) {
715
+ const packageJsonPath = path.join(projectPath, "package.json");
716
+ if (!fs.existsSync(packageJsonPath)) return;
717
+ const packageManager = workspaceInfo.packageManager;
718
+ const catalogDependencyResolver = createCatalogDependencyResolver(projectPath, packageManager);
719
+ let extractedStagedConfig = null;
720
+ let remainingPnpmOverrides;
721
+ let shouldRewritePnpmWorkspaceYaml = false;
722
+ let shouldAddPnpmWorkspaceVitePlusOverride = false;
723
+ let usePnpmWorkspaceYaml = false;
724
+ editJsonFile(packageJsonPath, (pkg) => {
725
+ if (packageManager === PackageManager.yarn) pkg.resolutions = {
726
+ ...pkg.resolutions,
727
+ ...VITE_PLUS_OVERRIDE_PACKAGES
728
+ };
729
+ else if (packageManager === PackageManager.npm || packageManager === PackageManager.bun) pkg.overrides = {
730
+ ...pkg.overrides,
731
+ ...VITE_PLUS_OVERRIDE_PACKAGES
732
+ };
733
+ else if (packageManager === PackageManager.pnpm) {
734
+ usePnpmWorkspaceYaml = !pkg.pnpm;
735
+ if (usePnpmWorkspaceYaml) {
736
+ shouldRewritePnpmWorkspaceYaml = true;
737
+ shouldAddPnpmWorkspaceVitePlusOverride = isForceOverrideMode();
738
+ }
739
+ const overrideKeys = Object.keys(VITE_PLUS_OVERRIDE_PACKAGES);
740
+ if (!usePnpmWorkspaceYaml) pkg.pnpm = {
741
+ ...pkg.pnpm,
742
+ overrides: {
743
+ ...pkg.pnpm?.overrides,
744
+ ...VITE_PLUS_OVERRIDE_PACKAGES,
745
+ ...isForceOverrideMode() ? { [VITE_PLUS_NAME]: VITE_PLUS_VERSION } : {}
746
+ },
747
+ peerDependencyRules: {
748
+ ...pkg.pnpm?.peerDependencyRules,
749
+ allowAny: [...new Set([...pkg.pnpm?.peerDependencyRules?.allowAny ?? [], ...overrideKeys])],
750
+ allowedVersions: {
751
+ ...pkg.pnpm?.peerDependencyRules?.allowedVersions,
752
+ ...Object.fromEntries(overrideKeys.map((key) => [key, "*"]))
753
+ }
754
+ }
755
+ };
756
+ else remainingPnpmOverrides = cleanupPnpmOverridesForWorkspaceYaml(pkg, overrideKeys);
757
+ for (const key in pkg.pnpm?.overrides) if (key.includes(">")) {
758
+ const splits = key.split(">");
759
+ if (splits[splits.length - 1].trim() === "vite") delete pkg.pnpm.overrides[key];
760
+ }
761
+ for (const key of [...overrideKeys, ...REMOVE_PACKAGES]) if (pkg.resolutions?.[key]) delete pkg.resolutions[key];
762
+ }
763
+ extractedStagedConfig = rewritePackageJson(pkg, packageManager, usePnpmWorkspaceYaml, skipStagedMigration, catalogDependencyResolver);
764
+ if (!pkg.devDependencies?.["vite-plus"] || isForceOverrideMode()) {
765
+ const version = usePnpmWorkspaceYaml && !VITE_PLUS_VERSION.startsWith("file:") ? "catalog:" : VITE_PLUS_VERSION;
766
+ pkg.devDependencies = {
767
+ ...pkg.devDependencies,
768
+ [VITE_PLUS_NAME]: version
769
+ };
770
+ }
771
+ return pkg;
772
+ });
773
+ if (shouldRewritePnpmWorkspaceYaml) rewritePnpmWorkspaceYaml(projectPath);
774
+ if (remainingPnpmOverrides) migratePnpmOverridesToWorkspaceYaml(projectPath, remainingPnpmOverrides);
775
+ if (shouldAddPnpmWorkspaceVitePlusOverride) migratePnpmOverridesToWorkspaceYaml(projectPath, { [VITE_PLUS_NAME]: VITE_PLUS_VERSION });
776
+ if (packageManager === PackageManager.yarn) rewriteYarnrcYml(projectPath);
777
+ if (extractedStagedConfig) {
778
+ if (mergeStagedConfigToViteConfig(projectPath, extractedStagedConfig, silent, report)) removeLintStagedFromPackageJson(packageJsonPath);
779
+ }
780
+ if (!skipStagedMigration) rewriteLintStagedConfigFile(projectPath, report);
781
+ cleanupDeprecatedTsconfigOptions(projectPath, silent, report);
782
+ rewriteTsconfigTypes(projectPath, silent, report);
783
+ mergeViteConfigFiles(projectPath, silent, report, workspaceInfo.packages);
784
+ injectLintTypeCheckDefaults(projectPath, silent, report);
785
+ injectFmtDefaults(projectPath, silent, report);
786
+ mergeTsdownConfigFile(projectPath, silent, report);
787
+ rewriteAllImports(projectPath, silent, report);
788
+ setPackageManager(projectPath, workspaceInfo.downloadPackageManager);
789
+ }
790
+ /**
791
+ * Rewrite monorepo to add vite-plus dependencies
792
+ * @param workspaceInfo - The workspace info
793
+ */
794
+ function rewriteMonorepo(workspaceInfo, skipStagedMigration, silent = false, report) {
795
+ const catalogDependencyResolver = createCatalogDependencyResolver(workspaceInfo.rootDir, workspaceInfo.packageManager);
796
+ if (workspaceInfo.packageManager === PackageManager.pnpm) rewritePnpmWorkspaceYaml(workspaceInfo.rootDir);
797
+ else if (workspaceInfo.packageManager === PackageManager.yarn) rewriteYarnrcYml(workspaceInfo.rootDir);
798
+ else if (workspaceInfo.packageManager === PackageManager.bun) rewriteBunCatalog(workspaceInfo.rootDir);
799
+ rewriteRootWorkspacePackageJson(workspaceInfo.rootDir, workspaceInfo.packageManager, skipStagedMigration, catalogDependencyResolver, workspaceInfo.packages);
800
+ const workspaceContext = {
801
+ rootDir: workspaceInfo.rootDir,
802
+ packages: workspaceInfo.packages
803
+ };
804
+ for (const pkg of workspaceInfo.packages) rewriteMonorepoProject(path.join(workspaceInfo.rootDir, pkg.path), workspaceInfo.packageManager, skipStagedMigration, silent, report, catalogDependencyResolver, workspaceContext);
805
+ if (!skipStagedMigration) rewriteLintStagedConfigFile(workspaceInfo.rootDir, report);
806
+ cleanupDeprecatedTsconfigOptions(workspaceInfo.rootDir, silent, report);
807
+ rewriteTsconfigTypes(workspaceInfo.rootDir, silent, report);
808
+ mergeViteConfigFiles(workspaceInfo.rootDir, silent, report, workspaceInfo.packages);
809
+ injectLintTypeCheckDefaults(workspaceInfo.rootDir, silent, report);
810
+ injectFmtDefaults(workspaceInfo.rootDir, silent, report);
811
+ mergeTsdownConfigFile(workspaceInfo.rootDir, silent, report);
812
+ rewriteAllImports(workspaceInfo.rootDir, silent, report);
813
+ setPackageManager(workspaceInfo.rootDir, workspaceInfo.downloadPackageManager);
814
+ }
815
+ /**
816
+ * Rewrite monorepo project to add vite-plus dependencies
817
+ * @param projectPath - The path to the project
818
+ * @param workspaceContext - Full workspace info, used so the lint-config
819
+ * sanitizer can see hoisted deps living elsewhere in the workspace,
820
+ * not just this sub-package's own `package.json`. `rootDir` is the
821
+ * workspace root (paths in `packages` are relative to it); `packages`
822
+ * is the workspace package list.
823
+ */
824
+ function rewriteMonorepoProject(projectPath, packageManager, skipStagedMigration, silent = false, report, catalogDependencyResolver, workspaceContext) {
825
+ cleanupDeprecatedTsconfigOptions(projectPath, silent, report);
826
+ rewriteTsconfigTypes(projectPath, silent, report);
827
+ mergeViteConfigFiles(projectPath, silent, report, workspaceContext?.packages, workspaceContext?.rootDir);
828
+ mergeTsdownConfigFile(projectPath, silent, report);
829
+ const packageJsonPath = path.join(projectPath, "package.json");
830
+ if (!fs.existsSync(packageJsonPath)) return;
831
+ let extractedStagedConfig = null;
832
+ editJsonFile(packageJsonPath, (pkg) => {
833
+ extractedStagedConfig = rewritePackageJson(pkg, packageManager, true, skipStagedMigration, catalogDependencyResolver);
834
+ return pkg;
835
+ });
836
+ if (extractedStagedConfig) {
837
+ if (mergeStagedConfigToViteConfig(projectPath, extractedStagedConfig, silent, report)) removeLintStagedFromPackageJson(packageJsonPath);
838
+ }
839
+ }
840
+ /**
841
+ * Rewrite pnpm-workspace.yaml to add vite-plus dependencies
842
+ * @param projectPath - The path to the project
843
+ */
844
+ function rewritePnpmWorkspaceYaml(projectPath) {
845
+ const pnpmWorkspaceYamlPath = path.join(projectPath, "pnpm-workspace.yaml");
846
+ if (!fs.existsSync(pnpmWorkspaceYamlPath)) fs.writeFileSync(pnpmWorkspaceYamlPath, "");
847
+ editYamlFile(pnpmWorkspaceYamlPath, (doc) => {
848
+ rewriteCatalog(doc);
849
+ const overrides = doc.getIn(["overrides"]);
850
+ for (const key of Object.keys(VITE_PLUS_OVERRIDE_PACKAGES)) {
851
+ const version = getCatalogDependencySpec(getYamlMapScalarStringValue(overrides, key), VITE_PLUS_OVERRIDE_PACKAGES[key], true);
852
+ doc.setIn(["overrides", scalarString(key)], scalarString(version));
853
+ }
854
+ const updatedOverrides = doc.getIn(["overrides"]);
855
+ for (const item of updatedOverrides.items) if (item.key.value.includes(">")) {
856
+ const splits = item.key.value.split(">");
857
+ if (splits[splits.length - 1].trim() === "vite") updatedOverrides.delete(item.key);
858
+ }
859
+ let allowAny = doc.getIn(["peerDependencyRules", "allowAny"]);
860
+ if (!allowAny) allowAny = new import_dist.YAMLSeq();
861
+ const existing = new Set(allowAny.items.map((n) => n.value));
862
+ for (const key of Object.keys(VITE_PLUS_OVERRIDE_PACKAGES)) if (!existing.has(key)) allowAny.add(scalarString(key));
863
+ doc.setIn(["peerDependencyRules", "allowAny"], allowAny);
864
+ let allowedVersions = doc.getIn(["peerDependencyRules", "allowedVersions"]);
865
+ if (!allowedVersions) allowedVersions = new import_dist.YAMLMap();
866
+ for (const key of Object.keys(VITE_PLUS_OVERRIDE_PACKAGES)) allowedVersions.set(scalarString(key), scalarString("*"));
867
+ doc.setIn(["peerDependencyRules", "allowedVersions"], allowedVersions);
868
+ if (doc.has("minimumReleaseAge")) {
869
+ const excludes = [
870
+ "vite-plus",
871
+ "@voidzero-dev/*",
872
+ "oxlint",
873
+ "@oxlint/*",
874
+ "oxlint-tsgolint",
875
+ "@oxlint-tsgolint/*",
876
+ "oxfmt",
877
+ "@oxfmt/*"
878
+ ];
879
+ let minimumReleaseAgeExclude = doc.getIn(["minimumReleaseAgeExclude"]);
880
+ if (!minimumReleaseAgeExclude) minimumReleaseAgeExclude = new import_dist.YAMLSeq();
881
+ const existing = new Set(minimumReleaseAgeExclude.items.map((n) => n.value));
882
+ for (const exclude of excludes) if (!existing.has(exclude)) minimumReleaseAgeExclude.add(scalarString(exclude));
883
+ doc.setIn(["minimumReleaseAgeExclude"], minimumReleaseAgeExclude);
884
+ }
885
+ });
886
+ }
887
+ /**
888
+ * Clean up pnpm.overrides and peerDependencyRules from package.json when migrating
889
+ * to pnpm-workspace.yaml. Returns any remaining non-Vite overrides that need to be
890
+ * moved to pnpm-workspace.yaml.
891
+ */
892
+ function cleanupPnpmOverridesForWorkspaceYaml(pkg, overrideKeys) {
893
+ const catalogOverrides = {};
894
+ const overrides = pkg.pnpm?.overrides;
895
+ for (const key of [...overrideKeys, ...REMOVE_PACKAGES]) {
896
+ const value = overrides?.[key];
897
+ if (value) {
898
+ if (overrideKeys.includes(key) && value.startsWith("catalog:")) catalogOverrides[key] = value;
899
+ delete overrides[key];
900
+ }
901
+ }
902
+ for (const key in pkg.pnpm?.overrides) if (key.includes(">")) {
903
+ const splits = key.split(">");
904
+ if (splits[splits.length - 1].trim() === "vite") delete pkg.pnpm.overrides[key];
905
+ }
906
+ let remaining;
907
+ if (Object.keys(catalogOverrides).length > 0) remaining = { ...catalogOverrides };
908
+ if (pkg.pnpm?.overrides && Object.keys(pkg.pnpm.overrides).length > 0) remaining = {
909
+ ...remaining,
910
+ ...pkg.pnpm.overrides
911
+ };
912
+ delete pkg.pnpm?.overrides;
913
+ cleanupPeerDependencyRules(pkg.pnpm?.peerDependencyRules, overrideKeys);
914
+ if (pkg.pnpm?.peerDependencyRules && Object.keys(pkg.pnpm.peerDependencyRules).length === 0) delete pkg.pnpm.peerDependencyRules;
915
+ if (pkg.pnpm && Object.keys(pkg.pnpm).length === 0) delete pkg.pnpm;
916
+ return remaining;
917
+ }
918
+ /**
919
+ * Move remaining non-Vite pnpm.overrides from package.json to pnpm-workspace.yaml.
920
+ * pnpm ignores workspace-level overrides when pnpm.overrides exists in package.json,
921
+ * so all overrides must live in pnpm-workspace.yaml.
922
+ */
923
+ function migratePnpmOverridesToWorkspaceYaml(projectPath, overrides) {
924
+ editYamlFile(path.join(projectPath, "pnpm-workspace.yaml"), (doc) => {
925
+ for (const [key, value] of Object.entries(overrides)) doc.setIn(["overrides", scalarString(key)], scalarString(value));
926
+ });
927
+ }
928
+ /**
929
+ * Remove only Vite-managed entries from peerDependencyRules, preserving custom ones.
930
+ */
931
+ function cleanupPeerDependencyRules(peerDependencyRules, overrideKeys) {
932
+ if (!peerDependencyRules) return;
933
+ if (Array.isArray(peerDependencyRules.allowAny)) {
934
+ peerDependencyRules.allowAny = peerDependencyRules.allowAny.filter((key) => !overrideKeys.includes(key));
935
+ if (peerDependencyRules.allowAny.length === 0) delete peerDependencyRules.allowAny;
936
+ }
937
+ if (peerDependencyRules.allowedVersions) {
938
+ for (const key of overrideKeys) delete peerDependencyRules.allowedVersions[key];
939
+ if (Object.keys(peerDependencyRules.allowedVersions).length === 0) delete peerDependencyRules.allowedVersions;
940
+ }
941
+ }
942
+ /**
943
+ * Rewrite .yarnrc.yml to add vite-plus dependencies
944
+ * @param projectPath - The path to the project
945
+ */
946
+ function rewriteYarnrcYml(projectPath) {
947
+ const yarnrcYmlPath = path.join(projectPath, ".yarnrc.yml");
948
+ if (!fs.existsSync(yarnrcYmlPath)) fs.writeFileSync(yarnrcYmlPath, "");
949
+ editYamlFile(yarnrcYmlPath, (doc) => {
950
+ if (!doc.has("nodeLinker")) doc.set("nodeLinker", "node-modules");
951
+ rewriteCatalog(doc);
952
+ });
953
+ }
954
+ /**
955
+ * Rewrite catalog in pnpm-workspace.yaml or .yarnrc.yml
956
+ * @param doc - The document to rewrite
957
+ */
958
+ function getCatalogDependencySpec(currentValue, version, supportCatalog, options) {
959
+ if (options?.dependencyField === "peerDependencies") {
960
+ if (currentValue?.startsWith("catalog:") && options.dependencyName) {
961
+ const resolved = options.catalogDependencyResolver?.(currentValue, options.dependencyName);
962
+ if (resolved && !isVitePlusOverrideSpec(resolved)) return resolved;
963
+ return PUBLIC_PEER_DEPENDENCY_FALLBACKS[options.dependencyName] ?? currentValue;
964
+ }
965
+ return currentValue ?? version;
966
+ }
967
+ if (options?.dependencyField === "optionalDependencies" && options?.packageManager === PackageManager.yarn) return version;
968
+ if (!supportCatalog || version.startsWith("file:")) return version;
969
+ return currentValue?.startsWith("catalog:") ? currentValue : "catalog:";
970
+ }
971
+ function isVitePlusOverrideSpec(value) {
972
+ return Object.values(VITE_PLUS_OVERRIDE_PACKAGES).includes(value) || value.startsWith("npm:@voidzero-dev/vite-plus-");
973
+ }
974
+ function createCatalogDependencyResolver(projectPath, packageManager) {
975
+ if (packageManager === PackageManager.pnpm) {
976
+ const pnpmWorkspaceYamlPath = path.join(projectPath, "pnpm-workspace.yaml");
977
+ if (!fs.existsSync(pnpmWorkspaceYamlPath)) return;
978
+ const doc = readYamlFile(pnpmWorkspaceYamlPath);
979
+ return createCatalogDependencyResolverFromCatalogs(doc?.catalog, doc?.catalogs);
980
+ }
981
+ if (packageManager === PackageManager.yarn) {
982
+ const yarnrcYmlPath = path.join(projectPath, ".yarnrc.yml");
983
+ if (!fs.existsSync(yarnrcYmlPath)) return;
984
+ const doc = readYamlFile(yarnrcYmlPath);
985
+ return createCatalogDependencyResolverFromCatalogs(doc?.catalog, doc?.catalogs);
986
+ }
987
+ if (packageManager === PackageManager.bun) {
988
+ const packageJsonPath = path.join(projectPath, "package.json");
989
+ if (!fs.existsSync(packageJsonPath)) return;
990
+ const pkg = readJsonFile(packageJsonPath);
991
+ const workspacesObj = pkg.workspaces && !Array.isArray(pkg.workspaces) ? pkg.workspaces : void 0;
992
+ return (catalogSpec, dependencyName) => {
993
+ const catalogName = catalogSpec.slice(8);
994
+ if (catalogName) return workspacesObj?.catalogs?.[catalogName]?.[dependencyName] ?? pkg.catalogs?.[catalogName]?.[dependencyName];
995
+ return workspacesObj?.catalog?.[dependencyName] ?? pkg.catalog?.[dependencyName];
996
+ };
997
+ }
998
+ }
999
+ function createCatalogDependencyResolverFromCatalogs(catalog, catalogs) {
1000
+ return (catalogSpec, dependencyName) => {
1001
+ const catalogName = catalogSpec.slice(8);
1002
+ if (catalogName) return catalogs?.[catalogName]?.[dependencyName];
1003
+ return catalog?.[dependencyName];
1004
+ };
1005
+ }
1006
+ function getYamlMapScalarStringValue(map, key) {
1007
+ if (!(map instanceof import_dist.YAMLMap)) return;
1008
+ for (const item of map.items) if (item.key instanceof import_dist.Scalar && item.key.value === key && item.value instanceof import_dist.Scalar && typeof item.value.value === "string") return item.value.value;
1009
+ }
1010
+ function rewriteCatalog(doc) {
1011
+ for (const [key, value] of Object.entries(VITE_PLUS_OVERRIDE_PACKAGES)) {
1012
+ if (value.startsWith("file:")) continue;
1013
+ doc.setIn(["catalog", key], scalarString(value));
1014
+ }
1015
+ if (!VITE_PLUS_VERSION.startsWith("file:")) doc.setIn(["catalog", VITE_PLUS_NAME], scalarString(VITE_PLUS_VERSION));
1016
+ for (const name of REMOVE_PACKAGES) {
1017
+ const path = ["catalog", name];
1018
+ if (doc.hasIn(path)) doc.deleteIn(path);
1019
+ }
1020
+ const catalogs = doc.getIn(["catalogs"]);
1021
+ if (!(catalogs instanceof import_dist.YAMLMap)) return;
1022
+ for (const item of catalogs.items) {
1023
+ const catalogName = item.key instanceof import_dist.Scalar ? item.key.value : void 0;
1024
+ if (typeof catalogName !== "string" || !(item.value instanceof import_dist.YAMLMap)) continue;
1025
+ for (const [key, value] of Object.entries(VITE_PLUS_OVERRIDE_PACKAGES)) {
1026
+ const catalogPath = [
1027
+ "catalogs",
1028
+ catalogName,
1029
+ key
1030
+ ];
1031
+ if (!value.startsWith("file:") && doc.hasIn(catalogPath)) doc.setIn(catalogPath, scalarString(value));
1032
+ }
1033
+ const vitePlusPath = [
1034
+ "catalogs",
1035
+ catalogName,
1036
+ VITE_PLUS_NAME
1037
+ ];
1038
+ if (!VITE_PLUS_VERSION.startsWith("file:") && doc.hasIn(vitePlusPath)) doc.setIn(vitePlusPath, scalarString(VITE_PLUS_VERSION));
1039
+ for (const name of REMOVE_PACKAGES) {
1040
+ const catalogPath = [
1041
+ "catalogs",
1042
+ catalogName,
1043
+ name
1044
+ ];
1045
+ if (doc.hasIn(catalogPath)) doc.deleteIn(catalogPath);
1046
+ }
1047
+ }
1048
+ }
1049
+ function rewriteCatalogObject(catalog, addMissing) {
1050
+ for (const [key, value] of Object.entries(VITE_PLUS_OVERRIDE_PACKAGES)) {
1051
+ if (value.startsWith("file:") || !addMissing && !(key in catalog)) continue;
1052
+ catalog[key] = value;
1053
+ }
1054
+ if (!VITE_PLUS_VERSION.startsWith("file:") && (addMissing || "vite-plus" in catalog)) catalog[VITE_PLUS_NAME] = VITE_PLUS_VERSION;
1055
+ for (const name of REMOVE_PACKAGES) delete catalog[name];
1056
+ }
1057
+ function rewriteCatalogsObject(catalogs) {
1058
+ for (const catalog of Object.values(catalogs)) rewriteCatalogObject(catalog, false);
1059
+ }
1060
+ /**
1061
+ * Write catalog entries to root package.json for bun.
1062
+ * Bun stores catalogs in package.json under the `catalog` key,
1063
+ * unlike pnpm which uses pnpm-workspace.yaml.
1064
+ * @see https://bun.sh/docs/pm/catalogs
1065
+ */
1066
+ function rewriteBunCatalog(projectPath) {
1067
+ const packageJsonPath = path.join(projectPath, "package.json");
1068
+ if (!fs.existsSync(packageJsonPath)) return;
1069
+ editJsonFile(packageJsonPath, (pkg) => {
1070
+ const workspacesObj = pkg.workspaces && !Array.isArray(pkg.workspaces) ? pkg.workspaces : void 0;
1071
+ const useWorkspacesCatalog = workspacesObj?.catalog != null || pkg.catalog == null && workspacesObj?.catalogs != null;
1072
+ const catalog = { ...useWorkspacesCatalog ? workspacesObj?.catalog : pkg.catalog };
1073
+ rewriteCatalogObject(catalog, true);
1074
+ if (useWorkspacesCatalog) {
1075
+ workspacesObj.catalog = catalog;
1076
+ if (pkg.catalog) rewriteCatalogObject(pkg.catalog, false);
1077
+ } else {
1078
+ pkg.catalog = catalog;
1079
+ if (workspacesObj?.catalog) rewriteCatalogObject(workspacesObj.catalog, false);
1080
+ }
1081
+ if (workspacesObj?.catalogs) rewriteCatalogsObject(workspacesObj.catalogs);
1082
+ if (pkg.catalogs) rewriteCatalogsObject(pkg.catalogs);
1083
+ const overrides = { ...pkg.overrides };
1084
+ for (const [key, value] of Object.entries(VITE_PLUS_OVERRIDE_PACKAGES)) overrides[key] = getCatalogDependencySpec(overrides[key], value, true);
1085
+ pkg.overrides = overrides;
1086
+ return pkg;
1087
+ });
1088
+ }
1089
+ /**
1090
+ * Rewrite root workspace package.json to add vite-plus dependencies
1091
+ * @param projectPath - The path to the project
1092
+ */
1093
+ function rewriteRootWorkspacePackageJson(projectPath, packageManager, skipStagedMigration, catalogDependencyResolver, packages) {
1094
+ const packageJsonPath = path.join(projectPath, "package.json");
1095
+ if (!fs.existsSync(packageJsonPath)) return;
1096
+ let remainingPnpmOverrides;
1097
+ editJsonFile(packageJsonPath, (pkg) => {
1098
+ if (packageManager === PackageManager.yarn) pkg.resolutions = {
1099
+ ...pkg.resolutions,
1100
+ ...VITE_PLUS_OVERRIDE_PACKAGES
1101
+ };
1102
+ else if (packageManager === PackageManager.npm) pkg.overrides = {
1103
+ ...pkg.overrides,
1104
+ ...VITE_PLUS_OVERRIDE_PACKAGES
1105
+ };
1106
+ else if (packageManager === PackageManager.bun) {} else if (packageManager === PackageManager.pnpm) {
1107
+ const overrideKeys = Object.keys(VITE_PLUS_OVERRIDE_PACKAGES);
1108
+ if (isForceOverrideMode()) pkg.pnpm = {
1109
+ ...pkg.pnpm,
1110
+ overrides: {
1111
+ ...pkg.pnpm?.overrides,
1112
+ ...VITE_PLUS_OVERRIDE_PACKAGES,
1113
+ [VITE_PLUS_NAME]: VITE_PLUS_VERSION
1114
+ }
1115
+ };
1116
+ else {
1117
+ for (const key of [...overrideKeys, ...REMOVE_PACKAGES]) if (pkg.resolutions?.[key]) delete pkg.resolutions[key];
1118
+ remainingPnpmOverrides = cleanupPnpmOverridesForWorkspaceYaml(pkg, overrideKeys);
1119
+ }
1120
+ for (const key in pkg.pnpm?.overrides) if (key.includes(">")) {
1121
+ const splits = key.split(">");
1122
+ if (splits[splits.length - 1].trim() === "vite") delete pkg.pnpm.overrides[key];
1123
+ }
1124
+ }
1125
+ if (!pkg.devDependencies?.["vite-plus"]) pkg.devDependencies = {
1126
+ ...pkg.devDependencies,
1127
+ [VITE_PLUS_NAME]: packageManager === PackageManager.npm || VITE_PLUS_VERSION.startsWith("file:") ? VITE_PLUS_VERSION : "catalog:"
1128
+ };
1129
+ return pkg;
1130
+ });
1131
+ if (remainingPnpmOverrides) migratePnpmOverridesToWorkspaceYaml(projectPath, remainingPnpmOverrides);
1132
+ rewriteMonorepoProject(projectPath, packageManager, skipStagedMigration, void 0, void 0, catalogDependencyResolver, packages ? {
1133
+ rootDir: projectPath,
1134
+ packages
1135
+ } : void 0);
1136
+ }
1137
+ const RULES_YAML_PATH = path.join(rulesDir, "vite-tools.yml");
1138
+ const PREPARE_RULES_YAML_PATH = path.join(rulesDir, "vite-prepare.yml");
1139
+ let cachedRulesYaml;
1140
+ let cachedRulesYamlNoLintStaged;
1141
+ let cachedPrepareRulesYaml;
1142
+ function readRulesYaml() {
1143
+ cachedRulesYaml ??= fs.readFileSync(RULES_YAML_PATH, "utf8");
1144
+ return cachedRulesYaml;
1145
+ }
1146
+ function getScriptRulesYaml(skipStagedMigration) {
1147
+ const yaml = readRulesYaml();
1148
+ if (!skipStagedMigration) return yaml;
1149
+ cachedRulesYamlNoLintStaged ??= yaml.split("\n\n\n").filter((block) => !block.includes("id: replace-lint-staged")).join("\n\n\n");
1150
+ return cachedRulesYamlNoLintStaged;
1151
+ }
1152
+ function readPrepareRulesYaml() {
1153
+ cachedPrepareRulesYaml ??= fs.readFileSync(PREPARE_RULES_YAML_PATH, "utf8");
1154
+ return cachedPrepareRulesYaml;
1155
+ }
1156
+ function rewritePackageJson(pkg, packageManager, isMonorepo, skipStagedMigration, catalogDependencyResolver) {
1157
+ if (pkg.scripts) {
1158
+ const updated = rewriteScripts(JSON.stringify(pkg.scripts), getScriptRulesYaml(skipStagedMigration));
1159
+ if (updated) pkg.scripts = JSON.parse(updated);
1160
+ }
1161
+ let extractedStagedConfig = null;
1162
+ if (!skipStagedMigration && pkg["lint-staged"]) {
1163
+ const config = pkg["lint-staged"];
1164
+ const updated = rewriteScripts(JSON.stringify(config), readRulesYaml());
1165
+ extractedStagedConfig = updated ? JSON.parse(updated) : config;
1166
+ }
1167
+ const supportCatalog = !!isMonorepo && packageManager !== PackageManager.npm;
1168
+ let needVitePlus = false;
1169
+ const dependencyGroups = [
1170
+ {
1171
+ dependencyField: "devDependencies",
1172
+ dependencies: pkg.devDependencies
1173
+ },
1174
+ {
1175
+ dependencyField: "dependencies",
1176
+ dependencies: pkg.dependencies
1177
+ },
1178
+ {
1179
+ dependencyField: "peerDependencies",
1180
+ dependencies: pkg.peerDependencies
1181
+ },
1182
+ {
1183
+ dependencyField: "optionalDependencies",
1184
+ dependencies: pkg.optionalDependencies
1185
+ }
1186
+ ];
1187
+ for (const [key, version] of Object.entries(VITE_PLUS_OVERRIDE_PACKAGES)) for (const { dependencyField, dependencies } of dependencyGroups) if (dependencies?.[key]) {
1188
+ dependencies[key] = getCatalogDependencySpec(dependencies[key], version, supportCatalog, {
1189
+ dependencyField,
1190
+ dependencyName: key,
1191
+ packageManager,
1192
+ catalogDependencyResolver
1193
+ });
1194
+ needVitePlus = true;
1195
+ }
1196
+ for (const name of REMOVE_PACKAGES) {
1197
+ let wasRemoved = false;
1198
+ for (const { dependencies } of dependencyGroups) if (dependencies?.[name]) {
1199
+ delete dependencies[name];
1200
+ wasRemoved = true;
1201
+ }
1202
+ if (wasRemoved) needVitePlus = true;
1203
+ const peerDep = BROWSER_PROVIDER_PEER_DEPS[name];
1204
+ if (wasRemoved && peerDep && !pkg.devDependencies?.[peerDep] && !pkg.dependencies?.[peerDep] && !pkg.peerDependencies?.[peerDep] && !pkg.optionalDependencies?.[peerDep]) {
1205
+ pkg.devDependencies ??= {};
1206
+ pkg.devDependencies[peerDep] = "*";
1207
+ }
1208
+ }
1209
+ const canonicalVitePlusSpec = supportCatalog && !VITE_PLUS_VERSION.startsWith("file:") ? "catalog:" : VITE_PLUS_VERSION;
1210
+ const existingVitePlus = pkg.devDependencies?.[VITE_PLUS_NAME];
1211
+ const shouldNormalizeExistingVitePlus = !!existingVitePlus && supportCatalog && existingVitePlus !== canonicalVitePlusSpec && !isProtocolPinnedSpec(existingVitePlus);
1212
+ if (needVitePlus || shouldNormalizeExistingVitePlus) pkg.devDependencies = {
1213
+ ...pkg.devDependencies,
1214
+ [VITE_PLUS_NAME]: canonicalVitePlusSpec
1215
+ };
1216
+ if (needVitePlus) {
1217
+ const installableDeps = {
1218
+ ...pkg.dependencies,
1219
+ ...pkg.devDependencies,
1220
+ ...pkg.optionalDependencies
1221
+ };
1222
+ if (!installableDeps.vitest && Object.keys(installableDeps).some((name) => name.includes("vitest"))) {
1223
+ const ver = VITE_PLUS_OVERRIDE_PACKAGES.vitest;
1224
+ pkg.devDependencies ??= {};
1225
+ pkg.devDependencies.vitest = getCatalogDependencySpec(void 0, ver, supportCatalog);
1226
+ }
1227
+ }
1228
+ return extractedStagedConfig;
1229
+ }
1230
+ function isProtocolPinnedSpec(spec) {
1231
+ return /^(catalog:|workspace:|link:|file:|npm:|github:|git[+:]|https?:\/\/)/.test(spec);
1232
+ }
1233
+ function removeLintStagedFromPackageJson(packageJsonPath) {
1234
+ editJsonFile(packageJsonPath, (pkg) => {
1235
+ if (pkg["lint-staged"]) {
1236
+ delete pkg["lint-staged"];
1237
+ return pkg;
1238
+ }
1239
+ });
1240
+ }
1241
+ function rewriteLintStagedConfigFile(projectPath, report) {
1242
+ let hasUnsupported = false;
1243
+ for (const filename of LINT_STAGED_JSON_CONFIG_FILES) {
1244
+ const configPath = path.join(projectPath, filename);
1245
+ if (!fs.existsSync(configPath)) continue;
1246
+ if (filename === ".lintstagedrc" && !isJsonFile(configPath)) {
1247
+ warnMigration(`${displayRelative(configPath)} is not JSON format — please migrate to "staged" in vite.config.ts manually`, report);
1248
+ hasUnsupported = true;
1249
+ continue;
1250
+ }
1251
+ if (!hasStagedConfigInViteConfig(projectPath)) {
1252
+ const config = readJsonFile(configPath);
1253
+ const updated = rewriteScripts(JSON.stringify(config), readRulesYaml());
1254
+ if (!mergeStagedConfigToViteConfig(projectPath, updated ? JSON.parse(updated) : config, true, report)) continue;
1255
+ fs.unlinkSync(configPath);
1256
+ if (report) report.inlinedLintStagedConfigCount++;
1257
+ } else warnMigration(`${displayRelative(configPath)} found but "staged" already exists in vite.config.ts — please merge manually`, report);
1258
+ }
1259
+ for (const filename of LINT_STAGED_OTHER_CONFIG_FILES) {
1260
+ const configPath = path.join(projectPath, filename);
1261
+ if (!fs.existsSync(configPath)) continue;
1262
+ warnMigration(`${displayRelative(configPath)} — please migrate to "staged" in vite.config.ts manually`, report);
1263
+ hasUnsupported = true;
1264
+ }
1265
+ if (hasUnsupported) infoMigration("Only \"staged\" in vite.config.ts is supported. See https://viteplus.dev/guide/migrate#lint-staged", report);
1266
+ }
1267
+ /**
1268
+ * Ensure vite.config.ts exists, create it if not
1269
+ * @returns The vite config filename
1270
+ */
1271
+ function ensureViteConfig(projectPath, configs, silent = false, report) {
1272
+ if (!configs.viteConfig) {
1273
+ configs.viteConfig = "vite.config.ts";
1274
+ const viteConfigPath = path.join(projectPath, "vite.config.ts");
1275
+ fs.writeFileSync(viteConfigPath, `import { defineConfig } from '${VITE_PLUS_NAME}';
1276
+
1277
+ export default defineConfig({});
1278
+ `);
1279
+ if (report) report.createdViteConfigCount++;
1280
+ if (!silent) log.success(`✔ Created vite.config.ts in ${displayRelative(viteConfigPath)}`);
1281
+ }
1282
+ return configs.viteConfig;
1283
+ }
1284
+ /**
1285
+ * Merge tsdown.config.* into vite.config.ts
1286
+ * - For JSON files: merge content directly into `pack` field and delete the JSON file
1287
+ * - For TS/JS files: import the config file
1288
+ */
1289
+ function mergeTsdownConfigFile(projectPath, silent = false, report) {
1290
+ const configs = detectConfigs(projectPath);
1291
+ if (!configs.tsdownConfig) return;
1292
+ const viteConfig = ensureViteConfig(projectPath, configs, silent, report);
1293
+ const fullViteConfigPath = path.join(projectPath, viteConfig);
1294
+ const fullTsdownConfigPath = path.join(projectPath, configs.tsdownConfig);
1295
+ if (configs.tsdownConfig.endsWith(".json")) {
1296
+ mergeAndRemoveJsonConfig(projectPath, viteConfig, configs.tsdownConfig, "pack", silent, report);
1297
+ return;
1298
+ }
1299
+ const result = mergeTsdownConfig(fullViteConfigPath, `./${configs.tsdownConfig}`);
1300
+ if (result.updated) {
1301
+ fs.writeFileSync(fullViteConfigPath, result.content);
1302
+ if (report) report.tsdownImportCount++;
1303
+ if (!silent) log.success(`✔ Added import for ${displayRelative(fullTsdownConfigPath)} in ${displayRelative(fullViteConfigPath)}`);
1304
+ }
1305
+ infoMigration(`Please manually merge ${displayRelative(fullTsdownConfigPath)} into ${displayRelative(fullViteConfigPath)}, see https://viteplus.dev/guide/migrate#tsdown`, report);
1306
+ }
1307
+ /**
1308
+ * Best-effort: derive the Oxlint rule-namespace a JS plugin package
1309
+ * contributes. Mirrors the conventions @oxlint/migrate uses when
1310
+ * translating ESLint configs, and the conventions Oxlint-native plugin
1311
+ * authors use (`oxlint-plugin-<name>` — see posva/pinia-colada in the
1312
+ * wild):
1313
+ * `eslint-plugin-unocss` → `unocss` (rules: `unocss/order`)
1314
+ * `oxlint-plugin-posva` → `posva` (rules: `posva/foo`)
1315
+ * `@stylistic/eslint-plugin` → `@stylistic` (rules: `@stylistic/indent`)
1316
+ * `@stylistic/eslint-plugin-ts` → `@stylistic/ts` (rules: `@stylistic/ts/indent`)
1317
+ * `@scope/oxlint-plugin-x` → `@scope/x`
1318
+ * anything else → the package name verbatim
1319
+ */
1320
+ function deriveJsPluginNamespace(packageName) {
1321
+ for (const prefix of ["eslint-plugin-", "oxlint-plugin-"]) if (packageName.startsWith(prefix)) return packageName.slice(prefix.length) || packageName;
1322
+ const scoped = packageName.match(/^(@[^/]+)\/(?:eslint|oxlint)-plugin(?:-(.+))?$/);
1323
+ if (scoped) return scoped[2] ? `${scoped[1]}/${scoped[2]}` : scoped[1];
1324
+ return packageName;
1325
+ }
1326
+ /**
1327
+ * Collect every dependency name declared across the root + workspace
1328
+ * `package.json` files after the ESLint cleanup has run. Used to verify
1329
+ * that JS plugins referenced by the generated `.oxlintrc.json` are
1330
+ * actually installable.
1331
+ */
1332
+ function collectInstalledPackageNames(projectPath, packages) {
1333
+ const names = /* @__PURE__ */ new Set();
1334
+ const paths = [projectPath, ...(packages ?? []).map((p) => path.join(projectPath, p.path))];
1335
+ for (const dir of paths) {
1336
+ const pkgJsonPath = path.join(dir, "package.json");
1337
+ if (!fs.existsSync(pkgJsonPath)) continue;
1338
+ let pkg;
1339
+ try {
1340
+ pkg = readJsonFile(pkgJsonPath);
1341
+ } catch {
1342
+ continue;
1343
+ }
1344
+ for (const field of [
1345
+ "devDependencies",
1346
+ "dependencies",
1347
+ "peerDependencies",
1348
+ "optionalDependencies"
1349
+ ]) {
1350
+ const deps = pkg[field];
1351
+ if (deps) for (const name of Object.keys(deps)) names.add(name);
1352
+ }
1353
+ }
1354
+ return names;
1355
+ }
1356
+ /**
1357
+ * Test whether a rule key (e.g. `@stylistic/ts/indent`) belongs to any
1358
+ * namespace in `namespaces`. We can't just split on the first `/` —
1359
+ * `@stylistic/eslint-plugin-ts` contributes the multi-segment namespace
1360
+ * `@stylistic/ts`, so the lookup has to try progressively longer
1361
+ * prefixes until one matches or we run out of slashes.
1362
+ */
1363
+ function ruleKeyMatchesNamespace(key, namespaces) {
1364
+ if (!key.includes("/")) return true;
1365
+ let idx = key.indexOf("/");
1366
+ while (idx !== -1) {
1367
+ if (namespaces.has(key.slice(0, idx))) return true;
1368
+ idx = key.indexOf("/", idx + 1);
1369
+ }
1370
+ return false;
1371
+ }
1372
+ /** Filter a rules object to only entries whose namespace is recognized. */
1373
+ function filterRulesAgainstNamespaces(rules, namespaces) {
1374
+ const out = {};
1375
+ for (const [key, value] of Object.entries(rules)) if (ruleKeyMatchesNamespace(key, namespaces)) out[key] = value;
1376
+ return out;
1377
+ }
1378
+ /**
1379
+ * Sort a jsPlugins array into installed entries (kept) and string
1380
+ * entries for packages that aren't present in the workspace. Object-form
1381
+ * entries (`{ name, specifier }`) and string entries that look like
1382
+ * local paths (`./X`, `/X`, `../X`) are passed through — Oxlint resolves
1383
+ * them itself.
1384
+ */
1385
+ function partitionJsPlugins(entries, availablePackages) {
1386
+ const kept = [];
1387
+ const dropped = [];
1388
+ for (const entry of entries) {
1389
+ if (typeof entry !== "string") {
1390
+ kept.push(entry);
1391
+ continue;
1392
+ }
1393
+ if (entry.startsWith("./") || entry.startsWith("../") || entry.startsWith("/")) {
1394
+ kept.push(entry);
1395
+ continue;
1396
+ }
1397
+ if (availablePackages.has(entry)) kept.push(entry);
1398
+ else dropped.push(entry);
1399
+ }
1400
+ return {
1401
+ kept,
1402
+ dropped
1403
+ };
1404
+ }
1405
+ /** Build the set of rule-key namespaces backed by a given jsPlugins set. */
1406
+ function jsPluginsToNamespaces(entries) {
1407
+ const ns = /* @__PURE__ */ new Set();
1408
+ for (const entry of entries) if (typeof entry === "string") ns.add(deriveJsPluginNamespace(entry));
1409
+ else if (entry && typeof entry === "object" && "name" in entry && entry.name) ns.add(entry.name);
1410
+ ns.delete("");
1411
+ return ns;
1412
+ }
1413
+ /**
1414
+ * Sanitize the `.oxlintrc.json` produced by `@oxlint/migrate` (in-place)
1415
+ * before it gets merged into `vite.config.ts`. Drop references that
1416
+ * won't resolve at lint time and warn the user.
1417
+ *
1418
+ * Why: `@oxlint/migrate` can emit `jsPlugins[]` / `plugins[]` / `rules`
1419
+ * entries referring to packages the user never installed (e.g.
1420
+ * translating `@unocss/eslint-config` into `eslint-plugin-unocss`),
1421
+ * to plugins outside Oxlint's native set, or under namespaces no
1422
+ * surviving plugin contributes. Without sanitization, `vp lint` aborts
1423
+ * with "Failed to load JS plugin" / "Plugin not found" before running
1424
+ * any rule. This produces a degraded-but-functional config instead.
1425
+ *
1426
+ * Per-override entries (`overrides[].jsPlugins`, `.plugins`, `.rules`)
1427
+ * are sanitized independently — an override can introduce its own
1428
+ * jsPlugin, so namespace availability is computed per-override (base
1429
+ * namespaces ∪ the override's own surviving jsPlugins' namespaces).
1430
+ */
1431
+ function sanitizeMigratedOxlintConfig(config, availablePackages, report) {
1432
+ const allDroppedJsPlugins = /* @__PURE__ */ new Set();
1433
+ const allDroppedPlugins = /* @__PURE__ */ new Set();
1434
+ const baseSplit = partitionJsPlugins(config.jsPlugins ?? [], availablePackages);
1435
+ for (const n of baseSplit.dropped) allDroppedJsPlugins.add(n);
1436
+ if (config.jsPlugins && baseSplit.dropped.length > 0) config.jsPlugins = baseSplit.kept;
1437
+ const baseNamespaces = new Set(OXLINT_NATIVE_PLUGINS);
1438
+ for (const ns of jsPluginsToNamespaces(baseSplit.kept)) baseNamespaces.add(ns);
1439
+ if (config.plugins) {
1440
+ const keptPlugins = [];
1441
+ for (const p of config.plugins) if (baseNamespaces.has(p)) keptPlugins.push(p);
1442
+ else allDroppedPlugins.add(p);
1443
+ if (keptPlugins.length !== config.plugins.length) config.plugins = keptPlugins;
1444
+ }
1445
+ if (config.rules) {
1446
+ const filtered = filterRulesAgainstNamespaces(config.rules, baseNamespaces);
1447
+ if (Object.keys(filtered).length !== Object.keys(config.rules).length) config.rules = filtered;
1448
+ }
1449
+ if (Array.isArray(config.overrides)) for (const override of config.overrides) {
1450
+ let overrideSurvivors = [];
1451
+ if (override.jsPlugins) {
1452
+ const split = partitionJsPlugins(override.jsPlugins, availablePackages);
1453
+ for (const n of split.dropped) allDroppedJsPlugins.add(n);
1454
+ if (split.dropped.length > 0) override.jsPlugins = split.kept;
1455
+ overrideSurvivors = split.kept;
1456
+ }
1457
+ const overrideNamespaces = new Set(baseNamespaces);
1458
+ for (const ns of jsPluginsToNamespaces(overrideSurvivors)) overrideNamespaces.add(ns);
1459
+ if (override.plugins) {
1460
+ const keptOverridePlugins = [];
1461
+ for (const p of override.plugins) if (overrideNamespaces.has(p)) keptOverridePlugins.push(p);
1462
+ else allDroppedPlugins.add(p);
1463
+ if (keptOverridePlugins.length !== override.plugins.length) override.plugins = keptOverridePlugins;
1464
+ }
1465
+ if (override.rules) {
1466
+ const filtered = filterRulesAgainstNamespaces(override.rules, overrideNamespaces);
1467
+ if (Object.keys(filtered).length !== Object.keys(override.rules).length) override.rules = filtered;
1468
+ }
1469
+ }
1470
+ if (allDroppedJsPlugins.size > 0) warnMigration(`Stripped JS plugin reference(s) from the generated lint config: ${[...allDroppedJsPlugins].join(", ")}. No matching package is present in this workspace, so loading them at lint time would fail. If you want their Oxlint coverage back, install each package (e.g. \`vp install <name>\`) and add its name back to \`lint.jsPlugins\` in vite.config.ts.`, report);
1471
+ if (allDroppedPlugins.size > 0) warnMigration(`Stripped unknown plugin reference(s) from the generated lint config: ${[...allDroppedPlugins].join(", ")}. These aren't native Oxlint plugins and no surviving JS plugin contributes them.`, report);
1472
+ }
1473
+ /**
1474
+ * Merge oxlint and oxfmt config into vite.config.ts
1475
+ */
1476
+ function mergeViteConfigFiles(projectPath, silent = false, report, packages, workspaceRoot) {
1477
+ const configs = detectConfigs(projectPath);
1478
+ if (!configs.oxfmtConfig && !configs.oxlintConfig) return;
1479
+ const viteConfig = ensureViteConfig(projectPath, configs, silent, report);
1480
+ if (configs.oxlintConfig) {
1481
+ const fullOxlintPath = path.join(projectPath, configs.oxlintConfig);
1482
+ const oxlintJson = readJsonFile(fullOxlintPath, true);
1483
+ if (!oxlintJson.options) oxlintJson.options = {};
1484
+ if (!hasBaseUrlInTsconfig(projectPath)) {
1485
+ if (oxlintJson.options.typeAware === void 0) oxlintJson.options.typeAware = true;
1486
+ if (oxlintJson.options.typeCheck === void 0) oxlintJson.options.typeCheck = true;
1487
+ } else warnMigration(BASEURL_TSCONFIG_WARNING, report);
1488
+ sanitizeMigratedOxlintConfig(oxlintJson, collectInstalledPackageNames(workspaceRoot ?? projectPath, packages), report);
1489
+ const normalizedOxlintConfig = ensureVitePlusImportRuleDefaults(oxlintJson);
1490
+ fs.writeFileSync(fullOxlintPath, JSON.stringify(normalizedOxlintConfig, null, 2));
1491
+ mergeAndRemoveJsonConfig(projectPath, viteConfig, configs.oxlintConfig, "lint", silent, report);
1492
+ }
1493
+ if (configs.oxfmtConfig) mergeAndRemoveJsonConfig(projectPath, viteConfig, configs.oxfmtConfig, "fmt", silent, report);
1494
+ }
1495
+ /**
1496
+ * Inject typeAware and typeCheck defaults into vite.config.ts lint config.
1497
+ * Called after mergeViteConfigFiles() to handle the case where no .oxlintrc.json exists
1498
+ * (e.g., newly created projects from create-vite templates).
1499
+ */
1500
+ function injectLintTypeCheckDefaults(projectPath, silent = false, report) {
1501
+ if (hasBaseUrlInTsconfig(projectPath)) {
1502
+ warnMigration(BASEURL_TSCONFIG_WARNING, report);
1503
+ return;
1504
+ }
1505
+ injectConfigDefaults(projectPath, "lint", ".vite-plus-lint-init.oxlintrc.json", JSON.stringify(createDefaultVitePlusLintConfig({ includeTypeAwareDefaults: true })), silent, report);
1506
+ }
1507
+ function injectFmtDefaults(projectPath, silent = false, report) {
1508
+ injectConfigDefaults(projectPath, "fmt", ".vite-plus-fmt-init.oxfmtrc.json", JSON.stringify({}), silent, report);
1509
+ }
1510
+ /**
1511
+ * Wire `create.defaultTemplate: '<scope>'` into the new monorepo's
1512
+ * `vite.config.ts`. The caller is `bin.ts`, only when scaffolding a
1513
+ * monorepo from a bundled `@org` manifest entry — that's the case where
1514
+ * the user just picked a template from a specific org and naturally
1515
+ * wants subsequent `vp create` invocations from the workspace to default
1516
+ * to that same org's picker.
1517
+ */
1518
+ function injectCreateDefaultTemplate(projectPath, scope, silent = false, report) {
1519
+ if (!scope) return;
1520
+ injectConfigDefaults(projectPath, "create", ".vite-plus-create-init.json", JSON.stringify({ defaultTemplate: scope }), silent, report);
1521
+ }
1522
+ function injectConfigDefaults(projectPath, configKey, tempFileName, tempFileContent, silent, report) {
1523
+ const configs = detectConfigs(projectPath);
1524
+ if (configs.viteConfig && hasConfigKey(path.join(projectPath, configs.viteConfig), configKey)) return;
1525
+ const viteConfig = ensureViteConfig(projectPath, configs, silent, report);
1526
+ const tempConfigPath = path.join(projectPath, tempFileName);
1527
+ fs.writeFileSync(tempConfigPath, tempFileContent);
1528
+ const fullViteConfigPath = path.join(projectPath, viteConfig);
1529
+ let result;
1530
+ try {
1531
+ result = mergeJsonConfig(fullViteConfigPath, tempConfigPath, configKey);
1532
+ } finally {
1533
+ fs.rmSync(tempConfigPath, { force: true });
1534
+ }
1535
+ if (result.updated) fs.writeFileSync(fullViteConfigPath, result.content);
1536
+ }
1537
+ function mergeAndRemoveJsonConfig(projectPath, viteConfigPath, jsonConfigPath, configKey, silent = false, report) {
1538
+ const fullViteConfigPath = path.join(projectPath, viteConfigPath);
1539
+ const fullJsonConfigPath = path.join(projectPath, jsonConfigPath);
1540
+ if (hasConfigKey(fullViteConfigPath, configKey)) {
1541
+ fs.unlinkSync(fullJsonConfigPath);
1542
+ if (!silent) log.info(`${configKey} config already present in ${displayRelative(fullViteConfigPath)} — removed redundant ${displayRelative(fullJsonConfigPath)}`);
1543
+ return;
1544
+ }
1545
+ const result = mergeJsonConfig(fullViteConfigPath, fullJsonConfigPath, configKey);
1546
+ if (result.updated) {
1547
+ fs.writeFileSync(fullViteConfigPath, result.content);
1548
+ fs.unlinkSync(fullJsonConfigPath);
1549
+ if (report) report.mergedConfigCount++;
1550
+ if (!silent) log.success(`✔ Merged ${displayRelative(fullJsonConfigPath)} into ${displayRelative(fullViteConfigPath)}`);
1551
+ } else {
1552
+ warnMigration(`Failed to merge ${displayRelative(fullJsonConfigPath)} into ${displayRelative(fullViteConfigPath)}`, report);
1553
+ infoMigration("Please complete the merge manually and follow the instructions in the documentation: https://viteplus.dev/config/", report);
1554
+ }
1555
+ }
1556
+ /**
1557
+ * Merge a staged config object into vite.config.ts as `staged: { ... }`.
1558
+ * Writes the config to a temp JSON file, calls mergeJsonConfig NAPI, then cleans up.
1559
+ */
1560
+ function mergeStagedConfigToViteConfig(projectPath, stagedConfig, silent = false, report) {
1561
+ const viteConfig = ensureViteConfig(projectPath, detectConfigs(projectPath), silent, report);
1562
+ const fullViteConfigPath = path.join(projectPath, viteConfig);
1563
+ const tempJsonPath = path.join(projectPath, ".staged-config-temp.json");
1564
+ fs.writeFileSync(tempJsonPath, JSON.stringify(stagedConfig, null, 2));
1565
+ let result;
1566
+ try {
1567
+ result = mergeJsonConfig(fullViteConfigPath, tempJsonPath, "staged");
1568
+ } finally {
1569
+ fs.unlinkSync(tempJsonPath);
1570
+ }
1571
+ if (result.updated) {
1572
+ fs.writeFileSync(fullViteConfigPath, result.content);
1573
+ if (report) report.mergedStagedConfigCount++;
1574
+ if (!silent) log.success(`✔ Merged staged config into ${displayRelative(fullViteConfigPath)}`);
1575
+ return true;
1576
+ } else {
1577
+ warnMigration(`Failed to merge staged config into ${displayRelative(fullViteConfigPath)}`, report);
1578
+ infoMigration(`Please add staged config to ${displayRelative(fullViteConfigPath)} manually, see https://viteplus.dev/guide/migrate#lint-staged`, report);
1579
+ return false;
1580
+ }
1581
+ }
1582
+ /**
1583
+ * Check if vite.config.ts already has a `staged` config key.
1584
+ */
1585
+ function hasStagedConfigInViteConfig(projectPath) {
1586
+ const configs = detectConfigs(projectPath);
1587
+ if (!configs.viteConfig) return false;
1588
+ const viteConfigPath = path.join(projectPath, configs.viteConfig);
1589
+ const content = fs.readFileSync(viteConfigPath, "utf8");
1590
+ return /\bstaged\s*:/.test(content);
1591
+ }
1592
+ /**
1593
+ * Rewrite imports in all TypeScript/JavaScript files under a directory
1594
+ * This rewrites vite/vitest imports to @voidzero-dev/vite-plus
1595
+ * @param projectPath - The root directory to search for files
1596
+ */
1597
+ function rewriteAllImports(projectPath, silent = false, report) {
1598
+ const result = rewriteImportsInDirectory(projectPath);
1599
+ const modified = result.modifiedFiles.length;
1600
+ const errors = result.errors.length;
1601
+ if (report) {
1602
+ report.rewrittenImportFileCount += modified;
1603
+ report.rewrittenImportErrors.push(...result.errors.map((error) => ({
1604
+ path: displayRelative(error.path),
1605
+ message: error.message
1606
+ })));
1607
+ }
1608
+ if (!silent && modified > 0) {
1609
+ log.success(`Rewrote imports in ${modified === 1 ? "one file" : `${modified} files`}`);
1610
+ log.info(result.modifiedFiles.map((file) => ` ${displayRelative(file)}`).join("\n"));
1611
+ }
1612
+ if (errors > 0) if (report) warnMigration(`${errors === 1 ? "one file had an error" : `${errors} files had errors`} while rewriting imports`, report);
1613
+ else {
1614
+ log.warn(`⚠ ${errors === 1 ? "one file had an error" : `${errors} files had errors`}:`);
1615
+ for (const error of result.errors) log.error(` ${displayRelative(error.path)}: ${error.message}`);
1616
+ }
1617
+ }
1618
+ /**
1619
+ * Check if the project has an unsupported husky version (<9.0.0).
1620
+ * Uses `semver.coerce` to handle ranges like `^8.0.0` → `8.0.0`.
1621
+ * When the specifier is not coercible (e.g. `"latest"`), falls back to
1622
+ * the installed version in node_modules via `detectPackageMetadata`.
1623
+ * Returns a reason string if hooks migration should be skipped, or null
1624
+ * if husky is absent or compatible.
1625
+ */
1626
+ function checkUnsupportedHuskyVersion(projectPath, deps, prodDeps) {
1627
+ const huskyVersion = deps?.husky ?? prodDeps?.husky;
1628
+ if (!huskyVersion) return null;
1629
+ let coerced = import_semver.default.coerce(huskyVersion);
1630
+ if (coerced == null) {
1631
+ const installed = detectPackageMetadata(projectPath, "husky");
1632
+ if (installed) coerced = import_semver.default.coerce(installed.version);
1633
+ if (coerced == null) return `Could not determine husky version from "${huskyVersion}" — please specify a semver-compatible version (e.g., "^9.0.0") and re-run migration.`;
1634
+ }
1635
+ if (import_semver.default.satisfies(coerced, "<9.0.0")) return "Detected husky <9.0.0 — please upgrade to husky v9+ first, then re-run migration.";
1636
+ return null;
1637
+ }
1638
+ const OTHER_HOOK_TOOLS = [
1639
+ "simple-git-hooks",
1640
+ "lefthook",
1641
+ "yorkie"
1642
+ ];
1643
+ const REPLACED_HOOK_PACKAGES = ["husky", "lint-staged"];
1644
+ function removeReplacedHookPackages(packageJsonPath) {
1645
+ editJsonFile(packageJsonPath, (pkg) => {
1646
+ for (const name of REPLACED_HOOK_PACKAGES) {
1647
+ if (pkg.devDependencies?.[name]) delete pkg.devDependencies[name];
1648
+ if (pkg.dependencies?.[name]) delete pkg.dependencies[name];
1649
+ }
1650
+ return pkg;
1651
+ });
1652
+ }
1653
+ /**
1654
+ * Walk up from `startPath` looking for `.git` (directory or file — submodules
1655
+ * use a `.git` file). Returns the directory that contains `.git`, or `null`.
1656
+ */
1657
+ function findGitRoot(startPath) {
1658
+ let dir = startPath;
1659
+ while (true) {
1660
+ if (fs.existsSync(path.join(dir, ".git"))) return dir;
1661
+ const parent = path.dirname(dir);
1662
+ if (parent === dir) return null;
1663
+ dir = parent;
1664
+ }
1665
+ }
1666
+ /**
1667
+ * Normalize "husky install [dir]" → "husky [dir]" so downstream regex
1668
+ * and ast-grep rules can match a single pattern.
1669
+ */
1670
+ function collapseHuskyInstall(script) {
1671
+ return script.replace("husky install ", "husky ").replace("husky install", "husky");
1672
+ }
1673
+ /**
1674
+ * High-level helper: detect old hooks dir, set up git hooks, and rewrite
1675
+ * the prepare script. Returns true if hooks were successfully installed.
1676
+ */
1677
+ function installGitHooks(projectPath, silent = false, report) {
1678
+ if (setupGitHooks(projectPath, getOldHooksDir(projectPath), silent, report)) {
1679
+ rewritePrepareScript(projectPath);
1680
+ return true;
1681
+ }
1682
+ return false;
1683
+ }
1684
+ /**
1685
+ * Read-only probe: extract the old husky hooks directory from `scripts.prepare`
1686
+ * without modifying package.json. Returns undefined when no husky reference is found.
1687
+ */
1688
+ function getOldHooksDir(rootDir) {
1689
+ const packageJsonPath = path.join(rootDir, "package.json");
1690
+ if (!fs.existsSync(packageJsonPath)) return;
1691
+ const pkg = readJsonFile(packageJsonPath);
1692
+ if (!pkg.scripts?.prepare) return;
1693
+ const match = collapseHuskyInstall(pkg.scripts.prepare).match(/\bhusky(?:\s+([\w./-]+))?/);
1694
+ if (!match) return;
1695
+ return match[1] ?? ".husky";
1696
+ }
1697
+ /**
1698
+ * Pre-flight check: verify that git hooks can be set up for this project.
1699
+ * Returns `null` if hooks setup can proceed, or a warning reason string
1700
+ * explaining why hooks setup should be skipped.
1701
+ *
1702
+ * These checks are deterministic and read-only — they do not modify
1703
+ * the project in any way, making them safe to call before migration.
1704
+ */
1705
+ function preflightGitHooksSetup(projectPath) {
1706
+ const gitRoot = findGitRoot(projectPath);
1707
+ if (gitRoot && path.resolve(projectPath) !== path.resolve(gitRoot)) return "Subdirectory project detected — skipping git hooks setup. Configure hooks at the repository root.";
1708
+ const packageJsonPath = path.join(projectPath, "package.json");
1709
+ if (!fs.existsSync(packageJsonPath)) return null;
1710
+ const pkgContent = readJsonFile(packageJsonPath);
1711
+ const deps = pkgContent.devDependencies;
1712
+ const prodDeps = pkgContent.dependencies;
1713
+ for (const tool of OTHER_HOOK_TOOLS) if (deps?.[tool] || prodDeps?.[tool] || pkgContent[tool]) return `Detected ${tool} — skipping git hooks setup. Please configure git hooks manually.`;
1714
+ const huskyReason = checkUnsupportedHuskyVersion(projectPath, deps, prodDeps);
1715
+ if (huskyReason) return huskyReason;
1716
+ if (hasUnsupportedLintStagedConfig(projectPath)) return "Unsupported lint-staged config format — skipping git hooks setup. Please configure git hooks manually.";
1717
+ return null;
1718
+ }
1719
+ /**
1720
+ * Set up git hooks with husky + lint-staged via vp commands.
1721
+ * Skips if another hook tool is detected (warns user).
1722
+ * Returns true if hooks were successfully set up, false if skipped.
1723
+ */
1724
+ function setupGitHooks(projectPath, oldHooksDir, silent = false, report) {
1725
+ const reason = preflightGitHooksSetup(projectPath);
1726
+ if (reason) {
1727
+ warnMigration(reason, report);
1728
+ return false;
1729
+ }
1730
+ const packageJsonPath = path.join(projectPath, "package.json");
1731
+ if (!fs.existsSync(packageJsonPath)) return false;
1732
+ const gitRoot = findGitRoot(projectPath);
1733
+ const isCustomDir = oldHooksDir != null && oldHooksDir !== ".husky";
1734
+ const hooksDir = isCustomDir ? oldHooksDir : ".vite-hooks";
1735
+ editJsonFile(packageJsonPath, (pkg) => {
1736
+ if (!pkg.scripts) pkg.scripts = {};
1737
+ if (!pkg.scripts.prepare) pkg.scripts.prepare = "vp config";
1738
+ else if (!pkg.scripts.prepare.includes("vp config") && !/\bhusky\b/.test(pkg.scripts.prepare)) pkg.scripts.prepare = `vp config && ${pkg.scripts.prepare}`;
1739
+ return pkg;
1740
+ });
1741
+ let stagedMerged = hasStagedConfigInViteConfig(projectPath);
1742
+ const hasStandaloneConfig = hasStandaloneLintStagedConfig(projectPath);
1743
+ if (!stagedMerged && !hasStandaloneConfig) {
1744
+ const stagedConfig = readJsonFile(packageJsonPath)?.["lint-staged"] ?? DEFAULT_STAGED_CONFIG;
1745
+ const updated = rewriteScripts(JSON.stringify(stagedConfig), readRulesYaml());
1746
+ stagedMerged = mergeStagedConfigToViteConfig(projectPath, updated ? JSON.parse(updated) : stagedConfig, silent, report);
1747
+ }
1748
+ if (stagedMerged) removeLintStagedFromPackageJson(packageJsonPath);
1749
+ if (oldHooksDir && !isCustomDir) {
1750
+ const oldDir = path.join(projectPath, oldHooksDir);
1751
+ if (fs.existsSync(oldDir)) {
1752
+ const targetDir = path.join(projectPath, hooksDir);
1753
+ fs.mkdirSync(targetDir, { recursive: true });
1754
+ for (const entry of fs.readdirSync(oldDir, { withFileTypes: true })) {
1755
+ if (entry.isDirectory() || entry.name.startsWith(".")) continue;
1756
+ const src = path.join(oldDir, entry.name);
1757
+ const dest = path.join(targetDir, entry.name);
1758
+ fs.copyFileSync(src, dest);
1759
+ fs.chmodSync(dest, 493);
1760
+ }
1761
+ fs.rmSync(oldDir, {
1762
+ recursive: true,
1763
+ force: true
1764
+ });
1765
+ }
1766
+ }
1767
+ if (stagedMerged) createPreCommitHook(projectPath, hooksDir);
1768
+ if (!gitRoot) {
1769
+ removeReplacedHookPackages(packageJsonPath);
1770
+ return true;
1771
+ }
1772
+ if (oldHooksDir) {
1773
+ const checkResult = import_cross_spawn.default.sync("git", [
1774
+ "config",
1775
+ "--local",
1776
+ "core.hooksPath"
1777
+ ], {
1778
+ cwd: projectPath,
1779
+ stdio: "pipe"
1780
+ });
1781
+ const existingPath = checkResult.status === 0 ? checkResult.stdout?.toString().trim() : "";
1782
+ if (existingPath === `${oldHooksDir}/_` || existingPath === oldHooksDir) import_cross_spawn.default.sync("git", [
1783
+ "config",
1784
+ "--local",
1785
+ "--unset",
1786
+ "core.hooksPath"
1787
+ ], {
1788
+ cwd: projectPath,
1789
+ stdio: "pipe"
1790
+ });
1791
+ }
1792
+ const vpBin = process.env.VP_CLI_BIN ?? "vp";
1793
+ const configArgs = isCustomDir ? [
1794
+ "config",
1795
+ "--hooks-only",
1796
+ "--hooks-dir",
1797
+ hooksDir
1798
+ ] : ["config", "--hooks-only"];
1799
+ const configResult = import_cross_spawn.default.sync(vpBin, configArgs, {
1800
+ cwd: projectPath,
1801
+ stdio: "pipe"
1802
+ });
1803
+ if (configResult.status === 0) {
1804
+ const stdout = configResult.stdout?.toString().trim() ?? "";
1805
+ if (stdout) {
1806
+ warnMigration(`Git hooks not configured — ${stdout}`, report);
1807
+ return false;
1808
+ }
1809
+ removeReplacedHookPackages(packageJsonPath);
1810
+ if (report) report.gitHooksConfigured = true;
1811
+ if (!silent) log.success("✔ Git hooks configured");
1812
+ return true;
1813
+ }
1814
+ warnMigration("Failed to install git hooks", report);
1815
+ return false;
1816
+ }
1817
+ /**
1818
+ * Check if a standalone lint-staged config file exists
1819
+ */
1820
+ function hasStandaloneLintStagedConfig(projectPath) {
1821
+ return LINT_STAGED_ALL_CONFIG_FILES.some((file) => fs.existsSync(path.join(projectPath, file)));
1822
+ }
1823
+ /**
1824
+ * Check if a standalone lint-staged config exists in a format that can't be
1825
+ * auto-migrated to "staged" in vite.config.ts (non-JSON files like .yaml,
1826
+ * .mjs, .cjs, .js, or a non-JSON .lintstagedrc).
1827
+ */
1828
+ function hasUnsupportedLintStagedConfig(projectPath) {
1829
+ for (const filename of LINT_STAGED_OTHER_CONFIG_FILES) if (fs.existsSync(path.join(projectPath, filename))) return true;
1830
+ const lintstagedrcPath = path.join(projectPath, ".lintstagedrc");
1831
+ if (fs.existsSync(lintstagedrcPath) && !isJsonFile(lintstagedrcPath)) return true;
1832
+ return false;
1833
+ }
1834
+ /**
1835
+ * Create pre-commit hook file in the hooks directory.
1836
+ */
1837
+ const STALE_LINT_STAGED_PATTERNS = [/^((?:[A-Z_][A-Z0-9_]*(?:=\S*)?\s+)*)(pnpm|pnpm exec|npx|yarn|yarn run|npm exec|npm run|bunx|bun run|bun x)\s+lint-staged\b/, /^((?:[A-Z_][A-Z0-9_]*(?:=\S*)?\s+)*)lint-staged\b/];
1838
+ const DEFAULT_STAGED_CONFIG = { "*": "vp check --fix" };
1839
+ /**
1840
+ * Ensure the pre-commit hook exists with `vp staged`, and that
1841
+ * vite.config.ts contains a `staged` block (using the default config
1842
+ * if none is present). Called by `vp config` after hook installation.
1843
+ */
1844
+ function ensurePreCommitHook(projectPath, dir = ".vite-hooks") {
1845
+ if (!hasStagedConfigInViteConfig(projectPath)) mergeStagedConfigToViteConfig(projectPath, DEFAULT_STAGED_CONFIG, true);
1846
+ createPreCommitHook(projectPath, dir);
1847
+ }
1848
+ function createPreCommitHook(projectPath, dir = ".vite-hooks") {
1849
+ const huskyDir = path.join(projectPath, dir);
1850
+ fs.mkdirSync(huskyDir, { recursive: true });
1851
+ const hookPath = path.join(huskyDir, "pre-commit");
1852
+ if (fs.existsSync(hookPath)) {
1853
+ const existing = fs.readFileSync(hookPath, "utf8");
1854
+ if (existing.includes("vp staged")) return;
1855
+ const lines = existing.split("\n");
1856
+ let replaced = false;
1857
+ const result = [];
1858
+ for (const line of lines) {
1859
+ const trimmed = line.trim();
1860
+ if (!replaced) {
1861
+ let matched = false;
1862
+ for (const pattern of STALE_LINT_STAGED_PATTERNS) {
1863
+ const match = pattern.exec(trimmed);
1864
+ if (match) {
1865
+ const parts = [
1866
+ match[1]?.trim() ?? "",
1867
+ "vp staged",
1868
+ trimmed.slice(match[0].length).trim()
1869
+ ].filter(Boolean);
1870
+ result.push(parts.join(" "));
1871
+ replaced = true;
1872
+ matched = true;
1873
+ break;
1874
+ }
1875
+ }
1876
+ if (matched) continue;
1877
+ }
1878
+ result.push(line);
1879
+ }
1880
+ if (!replaced) fs.writeFileSync(hookPath, `${result.join("\n").trimEnd()}\nvp staged\n`);
1881
+ else fs.writeFileSync(hookPath, result.join("\n"));
1882
+ } else {
1883
+ fs.writeFileSync(hookPath, "vp staged\n");
1884
+ fs.chmodSync(hookPath, 493);
1885
+ }
1886
+ }
1887
+ /**
1888
+ * Rewrite only `scripts.prepare` in the root package.json using vite-prepare.yml rules.
1889
+ * Collapses "husky install" → "husky" before applying ast-grep so that the
1890
+ * replace-husky rule produces "vp config" with any directory argument preserved.
1891
+ * Returns the old husky hooks dir (if any) for migration to .vite-hooks.
1892
+ * Called only when hooks are being set up (not with --no-hooks).
1893
+ */
1894
+ function rewritePrepareScript(rootDir) {
1895
+ const packageJsonPath = path.join(rootDir, "package.json");
1896
+ if (!fs.existsSync(packageJsonPath)) return;
1897
+ let oldDir;
1898
+ editJsonFile(packageJsonPath, (pkg) => {
1899
+ if (!pkg.scripts?.prepare) return pkg;
1900
+ const prepare = collapseHuskyInstall(pkg.scripts.prepare);
1901
+ const updated = rewriteScripts(JSON.stringify({ prepare }), readPrepareRulesYaml());
1902
+ if (updated) {
1903
+ let newPrepare = JSON.parse(updated).prepare;
1904
+ newPrepare = newPrepare.replace(/\bvp config(?:\s+(?!-)([\w./-]+))?/, (_match, dir) => {
1905
+ oldDir = dir ?? ".husky";
1906
+ return dir ? `vp config --hooks-dir ${dir}` : "vp config";
1907
+ });
1908
+ pkg.scripts.prepare = newPrepare;
1909
+ } else if (prepare !== pkg.scripts.prepare) pkg.scripts.prepare = prepare;
1910
+ return pkg;
1911
+ });
1912
+ return oldDir;
1913
+ }
1914
+ function setPackageManager(projectDir, downloadPackageManager) {
1915
+ editJsonFile(path.join(projectDir, "package.json"), (pkg) => {
1916
+ if (!pkg.packageManager) pkg.packageManager = `${downloadPackageManager.name}@${downloadPackageManager.version}`;
1917
+ return pkg;
1918
+ });
1919
+ }
1920
+ /**
1921
+ * Detect a .nvmrc file in the project directory.
1922
+ * If not found, check for a Volta node version in package.json.
1923
+ * If either is found, return the relevant info for migration.
1924
+ * Returns undefined if not found or .node-version already exists.
1925
+ */
1926
+ function detectNodeVersionManagerFile(projectPath) {
1927
+ if (fs.existsSync(path.join(projectPath, ".node-version"))) return;
1928
+ const configs = detectConfigs(projectPath);
1929
+ if (configs.nvmrcFile) return configs.voltaNode ? {
1930
+ file: ".nvmrc",
1931
+ voltaPresent: true
1932
+ } : { file: ".nvmrc" };
1933
+ if (configs.voltaNode) return {
1934
+ file: "package.json",
1935
+ voltaNodeVersion: configs.voltaNode
1936
+ };
1937
+ }
1938
+ /**
1939
+ * Parse a version alias from a .nvmrc file into a .node-version compatible string.
1940
+ * Accepts the first line of .nvmrc (pre-trimmed).
1941
+ * Returns null for unsupported aliases like "system", "default", "iojs".
1942
+ */
1943
+ function parseNvmrcVersion(alias) {
1944
+ const version = alias.trim();
1945
+ if (!version) return null;
1946
+ if (version === "node" || version === "stable") return "lts/*";
1947
+ if (version === "iojs" || version === "system" || version === "default") return null;
1948
+ if (version.startsWith("lts/")) return version;
1949
+ const normalized = version.startsWith("v") ? version.slice(1) : version;
1950
+ if (!normalized || !import_semver.default.validRange(normalized)) return null;
1951
+ return normalized;
1952
+ }
1953
+ /**
1954
+ * Migrate .nvmrc or Volta node version from package.json to .node-version.
1955
+ * - For .nvmrc: the source file is removed after migration.
1956
+ * - For package.json (Volta): the volta field is left as-is; removal is left to the user's discretion.
1957
+ * Returns true on success, false if migration was skipped or failed.
1958
+ */
1959
+ function migrateNodeVersionManagerFile(projectPath, detection, report) {
1960
+ const nodeVersionPath = path.join(projectPath, ".node-version");
1961
+ if (detection.file === "package.json") {
1962
+ const { voltaNodeVersion } = detection;
1963
+ const resolvedVersion = voltaNodeVersion === "lts" ? "lts/*" : voltaNodeVersion;
1964
+ if (!import_semver.default.valid(resolvedVersion) && resolvedVersion !== "lts/*") {
1965
+ warnMigration(`package.json volta.node "${voltaNodeVersion}" is not an exact version. Pin an exact version (e.g. ${voltaNodeVersion}.0 or run \`volta pin node@${voltaNodeVersion}\`) then re-run migration.`, report);
1966
+ return false;
1967
+ }
1968
+ fs.writeFileSync(nodeVersionPath, `${resolvedVersion}\n`);
1969
+ if (report) {
1970
+ report.manualSteps.push("Remove the \"volta\" field from package.json");
1971
+ report.nodeVersionFileMigrated = true;
1972
+ } else log.info("You can now remove the \"volta\" field from package.json manually.");
1973
+ return true;
1974
+ }
1975
+ const sourcePath = path.join(projectPath, ".nvmrc");
1976
+ const originalAlias = fs.readFileSync(sourcePath, "utf8").split("\n")[0]?.trim() ?? "";
1977
+ const version = parseNvmrcVersion(originalAlias);
1978
+ if (!version) {
1979
+ warnMigration(".nvmrc contains an unsupported version alias. Create .node-version manually with your desired Node.js version.", report);
1980
+ return false;
1981
+ }
1982
+ if (version === "lts/*" && (originalAlias === "node" || originalAlias === "stable")) log.info(`"${originalAlias}" in .nvmrc is not a specific version; automatically mapping to "lts/*"`);
1983
+ fs.writeFileSync(nodeVersionPath, `${version}\n`);
1984
+ fs.unlinkSync(sourcePath);
1985
+ if (report) {
1986
+ report.nodeVersionFileMigrated = true;
1987
+ if (detection.voltaPresent) report.manualSteps.push("Remove the \"volta\" field from package.json");
1988
+ } else if (detection.voltaPresent) log.info("You can now remove the \"volta\" field from package.json manually.");
1989
+ return true;
1990
+ }
1991
+ function warnPackageLevelEslint() {
1992
+ log.warn("ESLint detected in workspace packages but no root config found. Package-level ESLint must be migrated manually.");
1993
+ }
1994
+ const INCOMPATIBLE_ESLINT_INTEGRATIONS = ["@nuxt/eslint"];
1995
+ /**
1996
+ * Detect framework-ESLint integration packages whose ESLint migration is
1997
+ * known to be incompatible. Returns the offending package name, or
1998
+ * `undefined` if none is present.
1999
+ */
2000
+ function detectIncompatibleEslintIntegration(projectPath, packages) {
2001
+ const candidates = [projectPath, ...(packages ?? []).map((p) => path.join(projectPath, p.path))];
2002
+ for (const candidate of candidates) {
2003
+ const pkgJsonPath = path.join(candidate, "package.json");
2004
+ if (!fs.existsSync(pkgJsonPath)) continue;
2005
+ let pkg;
2006
+ try {
2007
+ pkg = readJsonFile(pkgJsonPath);
2008
+ } catch {
2009
+ continue;
2010
+ }
2011
+ for (const name of INCOMPATIBLE_ESLINT_INTEGRATIONS) if (pkg.devDependencies?.[name] || pkg.dependencies?.[name]) return name;
2012
+ }
2013
+ }
2014
+ function warnIncompatibleEslintIntegration(name) {
2015
+ log.warn(`${name} detected — automatic ESLint migration is skipped. ${name} wires ESLint into a framework-specific flow that Vite+ cannot migrate cleanly yet. Your ESLint setup is preserved. To migrate manually, remove ${name} from package.json and re-run \`vp migrate\`.`);
2016
+ }
2017
+ function warnLegacyEslintConfig(legacyConfigFile) {
2018
+ log.warn(`Legacy ESLint configuration detected (${legacyConfigFile}). Automatic migration to Oxlint requires ESLint v9+ with flat config format (eslint.config.*). Please upgrade to ESLint v9 first: https://eslint.org/docs/latest/use/migrate-to-9.0.0`);
2019
+ }
2020
+ async function confirmEslintMigration(interactive) {
2021
+ if (interactive) {
2022
+ const confirmed = await confirm({
2023
+ message: "Migrate ESLint rules to Oxlint using @oxlint/migrate?\n " + styleText("gray", "Oxlint is Vite+'s built-in linter — significantly faster than ESLint with compatible rule support. @oxlint/migrate converts your existing rules automatically."),
2024
+ initialValue: true
2025
+ });
2026
+ if (q(confirmed)) cancelAndExit();
2027
+ return confirmed;
2028
+ }
2029
+ return true;
2030
+ }
2031
+ async function promptEslintMigration(projectPath, interactive, packages) {
2032
+ const incompatible = detectIncompatibleEslintIntegration(projectPath, packages);
2033
+ if (incompatible) {
2034
+ warnIncompatibleEslintIntegration(incompatible);
2035
+ return false;
2036
+ }
2037
+ const eslintProject = detectEslintProject(projectPath, packages);
2038
+ if (eslintProject.hasDependency && !eslintProject.configFile && eslintProject.legacyConfigFile) {
2039
+ warnLegacyEslintConfig(eslintProject.legacyConfigFile);
2040
+ return false;
2041
+ }
2042
+ if (!eslintProject.hasDependency) return false;
2043
+ if (!eslintProject.configFile) {
2044
+ warnPackageLevelEslint();
2045
+ return false;
2046
+ }
2047
+ if (!await confirmEslintMigration(interactive)) return false;
2048
+ if (!await migrateEslintToOxlint(projectPath, interactive, eslintProject.configFile, packages)) cancelAndExit("ESLint migration failed.", 1);
2049
+ return true;
2050
+ }
2051
+ function warnPackageLevelPrettier() {
2052
+ log.warn("Prettier detected in workspace packages but no root config found. Package-level Prettier must be migrated manually.");
2053
+ }
2054
+ async function confirmPrettierMigration(interactive) {
2055
+ if (interactive) {
2056
+ const confirmed = await confirm({
2057
+ message: "Migrate Prettier to Oxfmt?\n " + styleText("gray", "Oxfmt is Vite+'s built-in formatter that replaces Prettier with faster performance. Your configuration will be converted automatically."),
2058
+ initialValue: true
2059
+ });
2060
+ if (q(confirmed)) cancelAndExit();
2061
+ return confirmed;
2062
+ }
2063
+ log.info("Prettier configuration detected. Auto-migrating to Oxfmt...");
2064
+ return true;
2065
+ }
2066
+ async function promptPrettierMigration(projectPath, interactive, packages) {
2067
+ const prettierProject = detectPrettierProject(projectPath, packages);
2068
+ if (!prettierProject.hasDependency) return false;
2069
+ if (!prettierProject.configFile) {
2070
+ warnPackageLevelPrettier();
2071
+ return false;
2072
+ }
2073
+ if (!await confirmPrettierMigration(interactive)) return false;
2074
+ if (!await migratePrettierToOxfmt(projectPath, interactive, prettierProject.configFile, packages)) cancelAndExit("Prettier migration failed.", 1);
2075
+ return true;
2076
+ }
2077
+ //#endregion
2078
+ //#region src/utils/agent.ts
2079
+ const AGENTS = [
2080
+ {
2081
+ id: "agents",
2082
+ label: "AGENTS.md",
2083
+ targetPath: "AGENTS.md",
2084
+ hint: "Codex, Amp, OpenCode, and similar agents",
2085
+ aliases: [
2086
+ "agents.md",
2087
+ "chatgpt",
2088
+ "chatgpt-codex",
2089
+ "codex",
2090
+ "amp",
2091
+ "kilo",
2092
+ "kilo-code",
2093
+ "kiro",
2094
+ "kiro-cli",
2095
+ "opencode",
2096
+ "other"
2097
+ ]
2098
+ },
2099
+ {
2100
+ id: "claude",
2101
+ label: "CLAUDE.md",
2102
+ targetPath: "CLAUDE.md",
2103
+ hint: "Claude Code",
2104
+ aliases: ["claude.md", "claude-code"]
2105
+ },
2106
+ {
2107
+ id: "gemini",
2108
+ label: "GEMINI.md",
2109
+ targetPath: "GEMINI.md",
2110
+ hint: "Gemini CLI",
2111
+ aliases: ["gemini.md", "gemini-cli"]
2112
+ },
2113
+ {
2114
+ id: "copilot",
2115
+ label: ".github/copilot-instructions.md",
2116
+ targetPath: ".github/copilot-instructions.md",
2117
+ hint: "GitHub Copilot",
2118
+ aliases: ["github-copilot", "copilot-instructions.md"]
2119
+ },
2120
+ {
2121
+ id: "cursor",
2122
+ label: ".cursor/rules/viteplus.mdc",
2123
+ targetPath: ".cursor/rules/viteplus.mdc",
2124
+ hint: "Cursor",
2125
+ aliases: ["viteplus.mdc"]
2126
+ },
2127
+ {
2128
+ id: "jetbrains",
2129
+ label: ".aiassistant/rules/viteplus.md",
2130
+ targetPath: ".aiassistant/rules/viteplus.md",
2131
+ hint: "JetBrains AI Assistant",
2132
+ aliases: [
2133
+ "jetbrains",
2134
+ "jetbrains-ai-assistant",
2135
+ "aiassistant",
2136
+ "viteplus.md"
2137
+ ]
2138
+ }
2139
+ ];
2140
+ const AGENT_DEFAULT_ID = "agents";
2141
+ const AGENT_STANDARD_PATH = "AGENTS.md";
2142
+ const COPILOT_AGENT_ID = "copilot";
2143
+ const COPILOT_SETUP_WORKFLOW_PATH = ".github/workflows/copilot-setup-steps.yml";
2144
+ const AGENT_INSTRUCTIONS_START_MARKER = "<!--VITE PLUS START-->";
2145
+ const AGENT_INSTRUCTIONS_END_MARKER = "<!--VITE PLUS END-->";
2146
+ const AGENT_ALIASES = Object.fromEntries(AGENTS.flatMap((option) => (option.aliases ?? []).map((alias) => [normalizeAgentName(alias), option.id])));
2147
+ const COPILOT_SETUP_WORKFLOW_CONTENT = `name: "Copilot Setup Steps"
2148
+
2149
+ on:
2150
+ workflow_dispatch:
2151
+ push:
2152
+ paths:
2153
+ - .github/workflows/copilot-setup-steps.yml
2154
+ pull_request:
2155
+ paths:
2156
+ - .github/workflows/copilot-setup-steps.yml
2157
+
2158
+ jobs:
2159
+ copilot-setup-steps:
2160
+ runs-on: ubuntu-latest
2161
+ permissions:
2162
+ contents: read
2163
+ steps:
2164
+ - name: Checkout code
2165
+ uses: actions/checkout@v6
2166
+ with:
2167
+ persist-credentials: false
2168
+ - name: Set up Vite+
2169
+ uses: voidzero-dev/setup-vp@v1
2170
+ with:
2171
+ cache: true
2172
+ run-install: true
2173
+ - name: Verify Vite+
2174
+ run: vp --version
2175
+ `;
2176
+ async function selectAgentTargets({ interactive, agent, onCancel }) {
2177
+ if (agent === false) return {
2178
+ targetPaths: void 0,
2179
+ selectedAgents: []
2180
+ };
2181
+ if (interactive && !agent) {
2182
+ const selectedAgentIds = await multiselect({
2183
+ message: "Which coding agent instruction files should Vite+ create?",
2184
+ options: AGENTS.map((option) => ({
2185
+ label: option.label,
2186
+ value: option.id,
2187
+ hint: option.hint
2188
+ })),
2189
+ initialValues: [AGENT_DEFAULT_ID],
2190
+ required: false
2191
+ });
2192
+ if (q(selectedAgentIds)) {
2193
+ onCancel();
2194
+ return {
2195
+ targetPaths: void 0,
2196
+ selectedAgents: []
2197
+ };
2198
+ }
2199
+ if (selectedAgentIds.length === 0) return {
2200
+ targetPaths: void 0,
2201
+ selectedAgents: []
2202
+ };
2203
+ const selectedAgents = resolveAgentOptions(selectedAgentIds);
2204
+ return {
2205
+ targetPaths: getAgentTargetPaths(selectedAgents),
2206
+ selectedAgents
2207
+ };
2208
+ }
2209
+ const selectedAgents = resolveAgentOptions(agent ?? AGENT_DEFAULT_ID);
2210
+ return {
2211
+ targetPaths: getAgentTargetPaths(selectedAgents),
2212
+ selectedAgents
2213
+ };
2214
+ }
2215
+ async function selectAgentTargetPaths({ interactive, agent, onCancel }) {
2216
+ return (await selectAgentTargets({
2217
+ interactive,
2218
+ agent,
2219
+ onCancel
2220
+ })).targetPaths;
2221
+ }
2222
+ function detectExistingAgentTargetPaths(projectRoot) {
2223
+ const detectedPaths = [];
2224
+ const seenTargetPaths = /* @__PURE__ */ new Set();
2225
+ for (const option of AGENTS) {
2226
+ if (seenTargetPaths.has(option.targetPath)) continue;
2227
+ seenTargetPaths.add(option.targetPath);
2228
+ const targetPath = path.join(projectRoot, option.targetPath);
2229
+ if (fs.existsSync(targetPath) && !fs.lstatSync(targetPath).isSymbolicLink()) detectedPaths.push(option.targetPath);
2230
+ }
2231
+ return detectedPaths.length > 0 ? detectedPaths : void 0;
2232
+ }
2233
+ /**
2234
+ * Silently update agent instruction files that contain Vite+ markers.
2235
+ * - No agent files → no writes
2236
+ * - No Vite+ markers → no writes
2237
+ * - Markers present, content up to date → no writes
2238
+ * - Markers present, content outdated → update marked section
2239
+ */
2240
+ function updateExistingAgentInstructions(projectRoot) {
2241
+ const targetPaths = detectExistingAgentTargetPaths(projectRoot);
2242
+ if (!targetPaths) return;
2243
+ const templatePath = path.join(pkgRoot, "AGENTS.md");
2244
+ if (!fs.existsSync(templatePath)) return;
2245
+ const templateContent = fs.readFileSync(templatePath, "utf-8");
2246
+ for (const targetPath of targetPaths) try {
2247
+ const fullPath = path.join(projectRoot, targetPath);
2248
+ const existing = fs.readFileSync(fullPath, "utf-8");
2249
+ const updated = replaceMarkedAgentInstructionsSection(existing, templateContent);
2250
+ if (updated !== void 0 && updated !== existing) fs.writeFileSync(fullPath, updated);
2251
+ } catch {}
2252
+ }
2253
+ function resolveAgentOptions(agent) {
2254
+ const agentNames = parseAgentNames(agent);
2255
+ const resolvedAgentNames = agentNames.length > 0 ? agentNames : [AGENT_DEFAULT_ID];
2256
+ const dedupedAgents = [];
2257
+ const seenAgentIds = /* @__PURE__ */ new Set();
2258
+ for (const name of resolvedAgentNames) {
2259
+ const option = resolveSingleAgentOption(name);
2260
+ if (seenAgentIds.has(option.id)) continue;
2261
+ seenAgentIds.add(option.id);
2262
+ dedupedAgents.push(option);
2263
+ }
2264
+ return dedupedAgents;
2265
+ }
2266
+ function getAgentTargetPaths(agents) {
2267
+ const dedupedTargetPaths = [];
2268
+ const seenTargetPaths = /* @__PURE__ */ new Set();
2269
+ for (const agent of agents) {
2270
+ if (seenTargetPaths.has(agent.targetPath)) continue;
2271
+ seenTargetPaths.add(agent.targetPath);
2272
+ dedupedTargetPaths.push(agent.targetPath);
2273
+ }
2274
+ return dedupedTargetPaths;
2275
+ }
2276
+ function parseAgentNames(agent) {
2277
+ if (!agent) return [];
2278
+ return (Array.isArray(agent) ? agent : [agent]).filter((value) => typeof value === "string").flatMap((value) => value.split(",")).map((value) => value.trim()).filter((value) => value.length > 0);
2279
+ }
2280
+ function resolveSingleAgentOption(agent) {
2281
+ const normalized = normalizeAgentName(agent);
2282
+ const alias = AGENT_ALIASES[normalized];
2283
+ const resolved = alias ? normalizeAgentName(alias) : normalized;
2284
+ return AGENTS.find((option) => normalizeAgentName(option.id) === resolved || normalizeAgentName(option.label) === resolved || normalizeAgentName(option.targetPath) === resolved || option.aliases?.some((candidate) => normalizeAgentName(candidate) === resolved)) ?? AGENTS.find((option) => option.id === AGENT_DEFAULT_ID);
2285
+ }
2286
+ /**
2287
+ * Detect agent instruction files that would conflict (exist without markers).
2288
+ * Returns only files that need a user decision (append or skip).
2289
+ * Read-only — does not write or modify any files.
2290
+ */
2291
+ async function detectAgentConflicts({ projectRoot, targetPaths }) {
2292
+ if (!targetPaths || targetPaths.length === 0) return [];
2293
+ const sourcePath = path.join(pkgRoot, "AGENTS.md");
2294
+ if (!fs.existsSync(sourcePath)) return [];
2295
+ const incomingContent = await fsPromises.readFile(sourcePath, "utf-8");
2296
+ const shouldLinkToAgents = targetPaths.includes(AGENT_STANDARD_PATH);
2297
+ const orderedPaths = shouldLinkToAgents ? [AGENT_STANDARD_PATH, ...targetPaths.filter((p) => p !== AGENT_STANDARD_PATH)] : targetPaths;
2298
+ const conflicts = [];
2299
+ const seenDestinationPaths = /* @__PURE__ */ new Set();
2300
+ const seenRealPaths = /* @__PURE__ */ new Set();
2301
+ for (const targetPathToCheck of orderedPaths) {
2302
+ const destinationPath = path.join(projectRoot, targetPathToCheck);
2303
+ const destinationKey = path.resolve(destinationPath);
2304
+ if (seenDestinationPaths.has(destinationKey)) continue;
2305
+ seenDestinationPaths.add(destinationKey);
2306
+ if (shouldLinkToAgents && targetPathToCheck !== AGENT_STANDARD_PATH) {
2307
+ if (await getExistingPathKind(destinationPath) !== "file") continue;
2308
+ }
2309
+ if (fs.existsSync(destinationPath)) {
2310
+ if (fs.lstatSync(destinationPath).isSymbolicLink()) continue;
2311
+ const destinationRealPath = await fsPromises.realpath(destinationPath);
2312
+ if (seenRealPaths.has(destinationRealPath)) continue;
2313
+ if (replaceMarkedAgentInstructionsSection(await fsPromises.readFile(destinationPath, "utf-8"), incomingContent) !== void 0) {
2314
+ seenRealPaths.add(destinationRealPath);
2315
+ continue;
2316
+ }
2317
+ conflicts.push({ targetPath: targetPathToCheck });
2318
+ seenRealPaths.add(destinationRealPath);
2319
+ }
2320
+ }
2321
+ return conflicts;
2322
+ }
2323
+ async function writeAgentInstructions({ projectRoot, targetPath, targetPaths, interactive, conflictDecisions, silent = false }) {
2324
+ const paths = [...targetPaths ?? [], ...targetPath ? [targetPath] : []];
2325
+ if (paths.length === 0) return;
2326
+ const sourcePath = path.join(pkgRoot, "AGENTS.md");
2327
+ if (!fs.existsSync(sourcePath)) {
2328
+ if (!silent) log.warn("Agent instructions template not found; skipping.");
2329
+ return;
2330
+ }
2331
+ const seenDestinationPaths = /* @__PURE__ */ new Set();
2332
+ const seenRealPaths = /* @__PURE__ */ new Set();
2333
+ const incomingContent = await fsPromises.readFile(sourcePath, "utf-8");
2334
+ const shouldLinkToAgents = paths.includes(AGENT_STANDARD_PATH);
2335
+ const orderedPaths = shouldLinkToAgents ? [AGENT_STANDARD_PATH, ...paths.filter((p) => p !== AGENT_STANDARD_PATH)] : paths;
2336
+ for (const targetPathToWrite of orderedPaths) {
2337
+ const destinationPath = path.join(projectRoot, targetPathToWrite);
2338
+ const destinationKey = path.resolve(destinationPath);
2339
+ if (seenDestinationPaths.has(destinationKey)) continue;
2340
+ seenDestinationPaths.add(destinationKey);
2341
+ await fsPromises.mkdir(path.dirname(destinationPath), { recursive: true });
2342
+ if (shouldLinkToAgents && targetPathToWrite !== AGENT_STANDARD_PATH) {
2343
+ if (await tryLinkTargetToAgents(projectRoot, targetPathToWrite, silent)) continue;
2344
+ }
2345
+ if (fs.existsSync(destinationPath)) {
2346
+ if (fs.lstatSync(destinationPath).isSymbolicLink()) {
2347
+ if (!silent) log.info(`Skipped writing ${targetPathToWrite} (symlink)`);
2348
+ continue;
2349
+ }
2350
+ const destinationRealPath = await fsPromises.realpath(destinationPath);
2351
+ if (seenRealPaths.has(destinationRealPath)) {
2352
+ if (!silent) log.info(`Skipped writing ${targetPathToWrite} (duplicate target)`);
2353
+ continue;
2354
+ }
2355
+ const existingContent = await fsPromises.readFile(destinationPath, "utf-8");
2356
+ const updatedContent = replaceMarkedAgentInstructionsSection(existingContent, incomingContent);
2357
+ if (updatedContent !== void 0) {
2358
+ if (updatedContent !== existingContent) await fsPromises.writeFile(destinationPath, updatedContent);
2359
+ seenRealPaths.add(destinationRealPath);
2360
+ continue;
2361
+ }
2362
+ let conflictAction;
2363
+ const preResolved = conflictDecisions?.get(targetPathToWrite);
2364
+ if (preResolved) conflictAction = preResolved;
2365
+ else if (interactive) {
2366
+ const action = await select({
2367
+ message: `Agent instructions already exist at ${targetPathToWrite}.\n ` + styleText("gray", "The Vite+ template includes guidance on `vp` commands, the build pipeline, and project conventions."),
2368
+ options: [{
2369
+ label: "Append",
2370
+ value: "append",
2371
+ hint: "Add template content to the end"
2372
+ }, {
2373
+ label: "Skip",
2374
+ value: "skip",
2375
+ hint: "Leave existing file unchanged"
2376
+ }],
2377
+ initialValue: "skip"
2378
+ });
2379
+ conflictAction = q(action) || action === "skip" ? "skip" : "append";
2380
+ } else conflictAction = "skip";
2381
+ if (conflictAction === "append") await appendAgentContent(destinationPath, targetPathToWrite, existingContent, incomingContent, silent);
2382
+ else {
2383
+ const suffix = !preResolved && !interactive ? " (already exists)" : "";
2384
+ if (!silent) log.info(`Skipped writing ${targetPathToWrite}${suffix}`);
2385
+ }
2386
+ seenRealPaths.add(destinationRealPath);
2387
+ continue;
2388
+ }
2389
+ await fsPromises.writeFile(destinationPath, incomingContent);
2390
+ if (!silent) log.success(`Wrote agent instructions to ${targetPathToWrite}`);
2391
+ seenRealPaths.add(await fsPromises.realpath(destinationPath));
2392
+ }
2393
+ }
2394
+ async function writeCopilotSetupWorkflow({ projectRoot, silent = false }) {
2395
+ const destinationPath = path.join(projectRoot, COPILOT_SETUP_WORKFLOW_PATH);
2396
+ await fsPromises.mkdir(path.dirname(destinationPath), { recursive: true });
2397
+ if (fs.existsSync(destinationPath)) {
2398
+ if (!silent) log.info(`Skipped writing ${COPILOT_SETUP_WORKFLOW_PATH} (already exists)`);
2399
+ return;
2400
+ }
2401
+ await fsPromises.writeFile(destinationPath, COPILOT_SETUP_WORKFLOW_CONTENT);
2402
+ if (!silent) log.success(`Wrote Copilot setup workflow to ${COPILOT_SETUP_WORKFLOW_PATH}`);
2403
+ }
2404
+ async function appendAgentContent(destinationPath, targetPath, existingContent, incomingContent, silent = false) {
2405
+ const separator = existingContent.endsWith("\n") ? "" : "\n";
2406
+ await fsPromises.appendFile(destinationPath, `${separator}\n${incomingContent}`);
2407
+ if (!silent) log.success(`Appended agent instructions to ${targetPath}`);
2408
+ }
2409
+ function normalizeAgentName(value) {
2410
+ return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "");
2411
+ }
2412
+ function replaceMarkedAgentInstructionsSection(existing, incoming) {
2413
+ const existingRange = getMarkedRange(existing, AGENT_INSTRUCTIONS_START_MARKER, AGENT_INSTRUCTIONS_END_MARKER);
2414
+ if (!existingRange) return;
2415
+ const incomingRange = getMarkedRange(incoming, AGENT_INSTRUCTIONS_START_MARKER, AGENT_INSTRUCTIONS_END_MARKER);
2416
+ if (!incomingRange) return;
2417
+ return `${existing.slice(0, existingRange.start)}${incoming.slice(incomingRange.start, incomingRange.end)}${existing.slice(existingRange.end)}`;
2418
+ }
2419
+ async function tryLinkTargetToAgents(projectRoot, targetPath, silent = false) {
2420
+ const destinationPath = path.join(projectRoot, targetPath);
2421
+ const agentsPath = path.join(projectRoot, AGENT_STANDARD_PATH);
2422
+ const symlinkTarget = path.relative(path.dirname(destinationPath), agentsPath);
2423
+ const existing = await getExistingPathKind(destinationPath);
2424
+ if (existing === "file") return false;
2425
+ if (existing === "symlink") {
2426
+ const currentLink = await fsPromises.readlink(destinationPath);
2427
+ if (path.resolve(path.dirname(destinationPath), currentLink) === agentsPath) {
2428
+ if (!silent) log.info(`Skipped linking ${targetPath} (already linked to ${AGENT_STANDARD_PATH})`);
2429
+ return true;
2430
+ }
2431
+ await fsPromises.unlink(destinationPath);
2432
+ }
2433
+ try {
2434
+ await fsPromises.symlink(symlinkTarget, destinationPath);
2435
+ } catch (err) {
2436
+ if (err.code === "EPERM") {
2437
+ await fsPromises.copyFile(agentsPath, destinationPath);
2438
+ if (!silent) log.success(`Copied ${AGENT_STANDARD_PATH} to ${targetPath}`);
2439
+ return true;
2440
+ }
2441
+ throw err;
2442
+ }
2443
+ if (!silent) log.success(`Linked ${targetPath} to ${AGENT_STANDARD_PATH}`);
2444
+ return true;
2445
+ }
2446
+ async function getExistingPathKind(filePath) {
2447
+ if (!fs.existsSync(filePath)) return "missing";
2448
+ return (await fsPromises.lstat(filePath)).isSymbolicLink() ? "symlink" : "file";
2449
+ }
2450
+ function getMarkedRange(content, startMarker, endMarker) {
2451
+ const start = content.indexOf(startMarker);
2452
+ if (start === -1) return;
2453
+ const endMarkerIndex = content.indexOf(endMarker, start + startMarker.length);
2454
+ if (endMarkerIndex === -1) return;
2455
+ return {
2456
+ start,
2457
+ end: endMarkerIndex + endMarker.length
2458
+ };
2459
+ }
2460
+ //#endregion
2461
+ export { promptEslintMigration as A, editYamlFile as B, injectLintTypeCheckDefaults as C, migrateNodeVersionManagerFile as D, migrateEslintToOxlint as E, setPackageManager as F, displayRelative as H, warnIncompatibleEslintIntegration as I, warnLegacyEslintConfig as L, rewriteMonorepo as M, rewriteMonorepoProject as N, migratePrettierToOxfmt as O, rewriteStandaloneProject as P, warnPackageLevelEslint as R, injectCreateDefaultTemplate as S, mergeViteConfigFiles as T, templatesDir as U, readYamlFile as V, detectNodeVersionManagerFile as _, selectAgentTargets as a, hasFrameworkShim as b, writeCopilotSetupWorkflow as c, checkVitestVersion as d, confirmEslintMigration as f, detectIncompatibleEslintIntegration as g, detectFramework as h, selectAgentTargetPaths as i, promptPrettierMigration as j, preflightGitHooksSetup as k, addFrameworkShim as l, detectEslintProject as m, detectAgentConflicts as n, updateExistingAgentInstructions as o, confirmPrettierMigration as p, detectExistingAgentTargetPaths as r, writeAgentInstructions as s, COPILOT_AGENT_ID as t, checkViteVersion as u, detectPrettierProject as v, installGitHooks as w, hasStagedConfigInViteConfig as x, ensurePreCommitHook as y, warnPackageLevelPrettier as z };