1 import path from "path"
2 import execute, { VerboseOptions } from "./execute.js"
3 import logMessage from "./log-message.js"
4 import ProcessManager from "./process-manager.js"
5 import { existsSync, readFileSync, rmSync, writeFileSync } from "fs"
6 import { parse as parseYaml } from "yaml"
7
8 export type PackageManagerType = "npm" | "yarn" | "pnpm" | "nub"
9
10 type PackageManagerOptions = {
11 verbose?: boolean
12 useNpm?: boolean
13 usePnpm?: boolean
14 useYarn?: boolean
15 }
16
17 export default class PackageManager {
18 protected packageManager?: PackageManagerType
19 protected packageManagerVersion?: string
20 protected processManager: ProcessManager
21 protected verbose
22 protected chosenPackageManager?: PackageManagerType
23
24 constructor(
25 processManager: ProcessManager,
26 options: PackageManagerOptions = {}
27 ) {
28 this.processManager = processManager
29 this.verbose = options.verbose || false
30
31 if (options.useNpm) {
32 this.chosenPackageManager = "npm"
33 } else if (options.usePnpm) {
34 this.chosenPackageManager = "pnpm"
35 } else if (options.useYarn) {
36 this.chosenPackageManager = "yarn"
37 }
38 }
39
40 private detectFromUserAgent(): {
41 manager: PackageManagerType
42 version?: string
43 } {
44 const userAgent = process.env.npm_config_user_agent
45
46 if (!userAgent) {
47 return { manager: "npm" }
48 }
49
50 // Extract package manager and version (e.g., "yarn/4.9.0" -> ["yarn", "4.9.0"])
51 const match = userAgent.match(/(pnpm|pnpx|yarn|npm|nub)\/(\d+\.\d+\.\d+)/)
52 if (match) {
53 const [, manager, version] = match
54
55 if (this.verbose) {
56 logMessage({
57 type: "info",
58 message: `Detected from user agent: ${manager}@${version}`,
59 })
60 }
61
62 // pnpx is an alias for pnpm
63 if (manager === "pnpx") {
64 return { manager: "pnpm", version }
65 }
66
67 return { manager: manager as PackageManagerType, version }
68 }
69
70 // Fallback detection without version
71 if (userAgent.includes("pnpm") || userAgent.includes("pnpx")) {
72 return { manager: "pnpm" }
73 }
74 if (userAgent.includes("yarn")) {
75 return { manager: "yarn" }
76 }
77 if (userAgent.includes("nub")) {
78 return { manager: "nub" }
79 }
80
81 return { manager: "npm" }
82 }
83
84 private async getVersion(
85 pm: PackageManagerType,
86 execOptions: Record<string, unknown>
87 ): Promise<string | undefined> {
88 const commands: Record<PackageManagerType, string> = {
89 yarn: "yarn -v",
90 pnpm: "pnpm -v",
91 npm: "npm -v",
92 nub: "nub -v",
93 }
94
95 try {
96 const result = await execute([commands[pm], execOptions], {
97 verbose: false,
98 })
99 const version = result.stdout?.trim()
100 if (this.verbose) {
101 logMessage({
102 type: "info",
103 message: `Detected ${pm} version: ${version}`,
104 })
105 }
106 return version
107 } catch {
108 if (this.verbose) {
109 logMessage({
110 type: "info",
111 message: `Failed to get version for package manager: ${pm}`,
112 })
113 }
114 return undefined
115 }
116 }
117
118 async setPackageManager(execOptions: Record<string, unknown>): Promise<void> {
119 if (this.packageManager) {
120 return
121 }
122
123 // check whether package manager is available and get version
124 await this.processManager.runProcess({
125 process: async () => {
126 if (this.chosenPackageManager) {
127 const version = await this.getVersion(
128 this.chosenPackageManager,
129 execOptions
130 )
131
132 if (version) {
133 this.packageManager = this.chosenPackageManager
134 // Store version if we don't have it from user agent
135 if (!this.packageManagerVersion) {
136 this.packageManagerVersion = version
137 }
138 return
139 }
140
141 // Error logs exit the process, so command execution will stop here
142 logMessage({
143 type: "error",
144 message: `The specified package manager "${this.chosenPackageManager}" is not available. Please install it or choose another package manager.`,
145 })
146 }
147
148 const detectedResult = this.detectFromUserAgent()
149 // fallback to npm if detection fails
150 this.packageManager = detectedResult.manager || "npm"
151 this.packageManagerVersion = detectedResult.version
152 if (!this.packageManagerVersion) {
153 // get version for the detected package manager (or npm fallback)
154 this.packageManagerVersion = await this.getVersion(
155 this.packageManager,
156 execOptions
157 )
158
159 if (this.verbose) {
160 logMessage({
161 type: "info",
162 message: `Falling back to ${this.packageManager} as the package manager.`,
163 })
164 }
165 } else {
166 if (this.verbose) {
167 logMessage({
168 type: "info",
169 message: `Using detected package manager "${this.packageManager}".`,
170 })
171 }
172 }
173 },
174 ignoreERESOLVE: true,
175 })
176 }
177
178 private applyYarnWorkspaceChanges(directory: string): void {
179 writeFileSync(path.join(directory, "yarn.lock"), "")
180 writeFileSync(
181 path.join(directory, ".yarnrc.yml"),
182 "nodeLinker: node-modules\n"
183 )
184 }
185
186 private applyNpmWorkspaceChanges(packageJson: Record<string, unknown>): void {
187 // npm's flat hoisting can only keep a single ajv major at the workspace
188 // root, but Medusa's stack needs two: the backend's migration tooling
189 // (@mikro-orm/migrations -> umzug -> @rushstack/node-core-library ->
190 // ajv-draft-04) does `require('ajv/dist/core')`, which only exists in ajv
191 // v8+, while ESLint (`eslint` core and `@eslint/eslintrc`) needs ajv v6.
192 // Both `ajv-draft-04` and `eslint` hoist to the root and resolve `ajv`
193 // from there, so whichever major loses the root slot breaks. We pin v8 to
194 // the root with a direct devDependency (this is what the hoisted
195 // `ajv-draft-04` resolves against) and scope v6 back under ESLint via
196 // overrides, which npm then nests. This lets both the backend
197 // (`medusa db:migrate`/`build`) and the storefront (`next lint`) resolve a
198 // compatible ajv from a single npm install.
199 packageJson.devDependencies = {
200 ...(packageJson.devDependencies as Record<string, unknown>),
201 ajv: "^8.13.0",
202 }
203 packageJson.overrides = {
204 ...(packageJson.overrides as Record<string, unknown>),
205 eslint: {
206 ...((packageJson.overrides as Record<string, any>)?.eslint ?? {}),
207 ajv: "^6.12.4",
208 },
209 "@eslint/eslintrc": {
210 ...((packageJson.overrides as Record<string, any>)?.[
211 "@eslint/eslintrc"
212 ] ?? {}),
213 ajv: "^6.12.4",
214 },
215 }
216 }
217
218 async transformWorkspaceConfig(directory: string): Promise<void> {
219 if (this.packageManager === "pnpm") {
220 return
221 }
222
223 const workspaceYamlPath = path.join(directory, "pnpm-workspace.yaml")
224 if (!existsSync(workspaceYamlPath)) {
225 return
226 }
227
228 const yamlContent = readFileSync(workspaceYamlPath, "utf-8")
229 const workspacePackages: string[] = parseYaml(yamlContent)?.packages ?? []
230
231 const packageJsonPath = path.join(directory, "package.json")
232 const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"))
233 packageJson.workspaces = workspacePackages
234
235 if (packageJson.scripts) {
236 const pm = this.packageManager!
237 packageJson.scripts = Object.fromEntries(
238 Object.entries(packageJson.scripts as Record<string, string>).map(
239 ([key, value]) => [
240 key,
241 value
242 .replace(/\bpnpm\s+-r\s+(\S+)/g, "turbo $1")
243 .replace(/\bpnpm\b/g, pm),
244 ]
245 )
246 )
247 }
248
249 if (this.packageManager === "yarn") {
250 this.applyYarnWorkspaceChanges(directory)
251 } else if (this.packageManager === "npm") {
252 this.applyNpmWorkspaceChanges(packageJson)
253 }
254
255 writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2))
256
257 rmSync(workspaceYamlPath, { force: true })
258 }
259
260 async removeLockFiles(directory: string): Promise<void> {
261 const lockFiles: Record<PackageManagerType, string[]> = {
262 npm: ["yarn.lock", "pnpm-lock.yaml", ".yarn"],
263 yarn: ["package-lock.json", "pnpm-lock.yaml"],
264 pnpm: ["yarn.lock", "package-lock.json", ".yarn"],
265 nub: ["yarn.lock", "package-lock.json", "pnpm-lock.yaml", ".yarn"],
266 }
267
268 if (!this.packageManager) {
269 return
270 }
271
272 const filesToRemove = lockFiles[this.packageManager] || []
273 for (const file of filesToRemove) {
274 const filePath = path.join(directory, file)
275 if (existsSync(filePath)) {
276 rmSync(filePath, {
277 force: true,
278 recursive: true,
279 })
280 }
281 }
282 }
283
284 async installDependencies(
285 execOptions: Record<string, unknown>,
286 installOptions?: {
287 installLegacyPeerDeps?: boolean
288 }
289 ) {
290 if (!this.packageManager) {
291 await this.setPackageManager(execOptions)
292 }
293
294 if (execOptions.cwd && typeof execOptions.cwd === "string") {
295 await this.transformWorkspaceConfig(execOptions.cwd)
296 await this.removeLockFiles(execOptions.cwd)
297 }
298
299 const commands: Record<PackageManagerType, string> = {
300 yarn: "yarn",
301 pnpm: "pnpm install",
302 npm: `npm install${
303 installOptions?.installLegacyPeerDeps ? " --legacy-peer-deps" : ""
304 }`,
305 nub: "nub install",
306 }
307
308 const command = commands[this.packageManager || "npm"]
309
310 await this.processManager.runProcess({
311 process: async () => {
312 try {
313 await execute([command, execOptions], {
314 verbose: this.verbose,
315 })
316 } catch (error) {
317 const errorStr =
318 typeof error === "string"
319 ? error
320 : (error as any)?.stderr ||
321 (error as any)?.message ||
322 String(error)
323 const packageManagerConflictMatch = errorStr.match(
324 /This project is configured to use (\w+) because (.+) has a "packageManager" field/
325 )
326 if (this.packageManager === "pnpm" && packageManagerConflictMatch) {
327 const conflictingFile = packageManagerConflictMatch[2]
328 throw new Error(
329 `Cannot install with pnpm because ${conflictingFile} has a "packageManager" field that specifies a different package manager. Consider removing that field from ${conflictingFile}, or create your Medusa project in a different directory.`
330 )
331 }
332 throw error
333 }
334
335 // For npm, run npm ci after npm install to validate installation
336 if (this.packageManager === "npm") {
337 try {
338 await execute(["npm ci", execOptions], {
339 verbose: this.verbose,
340 })
341 } catch (error) {
342 // If npm ci fails, re-run npm install
343 if (this.verbose) {
344 logMessage({
345 type: "info",
346 message: "npm ci validation failed, re-running npm install...",
347 })
348 }
349 await execute(["npm install", execOptions], {
350 verbose: this.verbose,
351 })
352 }
353 }
354 },
355 ignoreERESOLVE: true,
356 })
357 }
358
359 async runCommand(
360 command: string,
361 execOptions: Record<string, unknown>,
362 verboseOptions: VerboseOptions = {}
363 ) {
364 if (!this.packageManager) {
365 await this.setPackageManager(execOptions)
366 }
367
368 const commandStr = this.getCommandStr(command)
369
370 return await this.processManager.runProcess({
371 process: async () => {
372 return await execute([commandStr, execOptions], {
373 verbose: this.verbose,
374 ...verboseOptions,
375 })
376 },
377 ignoreERESOLVE: true,
378 })
379 }
380
381 async runMedusaCommand(
382 command: string,
383 execOptions: Record<string, unknown>,
384 verboseOptions: VerboseOptions = {}
385 ) {
386 if (!this.packageManager) {
387 await this.setPackageManager(execOptions)
388 }
389
390 const formats: Record<PackageManagerType, string> = {
391 yarn: `yarn medusa ${command}`,
392 pnpm: `pnpm medusa ${command}`,
393 npm: `npx medusa ${command}`,
394 nub: `nubx medusa ${command}`,
395 }
396
397 const commandStr = formats[this.packageManager || "npm"]
398
399 return await this.processManager.runProcess({
400 process: async () => {
401 return await execute([commandStr, execOptions], {
402 verbose: this.verbose,
403 ...verboseOptions,
404 })
405 },
406 ignoreERESOLVE: true,
407 })
408 }
409
410 getCommandStr(command: string): string {
411 if (!this.packageManager) {
412 throw new Error("Package manager not set")
413 }
414
415 const formats: Record<PackageManagerType, string> = {
416 yarn: `yarn ${command}`,
417 pnpm: `pnpm ${command}`,
418 npm: `npm run ${command}`,
419 nub: `nub run ${command}`,
420 }
421
422 return formats[this.packageManager]
423 }
424
425 getPackageManager(): PackageManagerType | undefined {
426 return this.packageManager
427 }
428
429 async getPackageManagerString(): Promise<string | undefined> {
430 if (!this.packageManager) {
431 await this.setPackageManager({})
432 }
433 if (!this.packageManagerVersion) {
434 if (this.verbose) {
435 logMessage({
436 type: "info",
437 message: `No version detected for package manager: ${this.packageManager}`,
438 })
439 }
440 return undefined
441 }
442 const result = `${this.packageManager}@${this.packageManagerVersion}`
443 if (this.verbose) {
444 logMessage({
445 type: "info",
446 message: `Package manager string: ${result}`,
447 })
448 }
449 return result
450 }
451 }