/
npm.ts
158 lines (129 loc) · 4.88 KB
/
npm.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import fs from 'node:fs/promises'
import { startSubprocess } from '@nuxt/devtools-kit'
import isInstalledGlobally from 'is-installed-globally'
import { detectPackageManager } from 'nypm'
import { parseModule } from 'magicast'
import { addNuxtModule, getDefaultExportOptions } from 'magicast/helpers'
import { checkForUpdateOf } from '../npm'
import type { NpmCommandOptions, NpmCommandType, NuxtDevtoolsServerContext, PackageManagerName, PackageUpdateInfo, ServerFunctions } from '../types'
export function setupNpmRPC({ nuxt }: NuxtDevtoolsServerContext) {
let detectPromise: Promise<PackageManagerName> | undefined
const updatesPromise = new Map<string, Promise<PackageUpdateInfo | undefined>>()
function getPackageManager() {
detectPromise ||= detectPackageManager(nuxt.options.rootDir).then(r => r?.name || 'npm')
return detectPromise
}
async function getNpmCommand(command: NpmCommandType, packageName: string, options: NpmCommandOptions = {}) {
const {
dev = true,
global = (packageName === '@nuxt/devtools' && isInstalledGlobally),
} = options
const agent = await getPackageManager()
// TODO: smartly detect dev/global installs as default
if (command === 'install' || command === 'update')
return [agent, agent === 'npm' ? 'install' : 'add', `${packageName}@latest`, dev ? '-D' : '', global ? '-g' : '', '--ignore-scripts'].filter(Boolean)
if (command === 'uninstall')
return [agent, agent === 'npm' ? 'uninstall' : 'remove', packageName, global ? '-g' : ''].filter(Boolean)
}
async function runNpmCommand(command: NpmCommandType, packageName: string, options: NpmCommandOptions = {}) {
const args = await getNpmCommand(command, packageName, options)
if (!args)
return
const processId = `npm:${command}:${packageName}`
startSubprocess({
command: args[0],
args: args.slice(1),
}, {
id: processId,
name: `${command} ${packageName}`,
icon: 'i-mdi-npm-variant-outline text-rose',
restartable: false,
})
return {
processId,
}
}
return {
checkForUpdateFor(name: string) {
if (!updatesPromise.has(name))
updatesPromise.set(name, checkForUpdateOf(name, undefined, nuxt))
return updatesPromise.get(name)!
},
getPackageManager,
getNpmCommand,
runNpmCommand,
async installNuxtModule(name: string, dry = true) {
const commands = (await getNpmCommand('install', name, { dev: true }))!
const filepath = nuxt.options._nuxtConfigFile
const source = await fs.readFile(filepath, 'utf-8')
const mod = await parseModule(source, { sourceFileName: filepath })
addNuxtModule(mod, name)
const generated = mod.generate().code
const processId = `nuxt:add-module:${name}`
if (!dry) {
const process = startSubprocess({
command: commands[0],
args: commands.slice(1),
}, {
id: processId,
name: `Install ${name}`,
icon: 'carbon:intent-request-create',
restartable: false,
})
const execa = process.getProcess()
await execa
const code = execa.exitCode
if (code !== 0) {
console.error(execa.stderr)
throw new Error(`Failed to install module, process exited with ${code}`)
}
await fs.writeFile(filepath, generated, 'utf-8')
}
return {
configOriginal: source,
configGenerated: generated,
commands,
processId,
}
},
async uninstallNuxtModule(name: string, dry = true) {
const commands = (await getNpmCommand('uninstall', name))!
const filepath = nuxt.options._nuxtConfigFile
const source = await fs.readFile(filepath, 'utf-8')
const mod = parseModule(source, { sourceFileName: filepath })
// TODO: remove module from config
// removeNuxtModule(mod, name)
const config = getDefaultExportOptions(mod)
config.modules ||= []
if (config.modules.includes(name)) {
Object.values(config.modules).forEach((value, index) => {
if (value === name)
config.modules.splice(index - 1, 1)
})
}
const generated = mod.generate().code
const processId = `nuxt:remove-module:${name}`
if (!dry) {
const process = startSubprocess({
command: commands[0],
args: commands.slice(1),
}, {
id: processId,
name: `Uninstall ${name}`,
icon: 'carbon:intent-request-uninstall',
restartable: false,
})
await process.getProcess()
if (process.getProcess().exitCode !== 0)
throw new Error('Failed to uninstall module')
await fs.writeFile(filepath, generated, 'utf-8')
}
return {
configOriginal: source,
configGenerated: generated,
commands,
processId,
}
},
} satisfies Partial<ServerFunctions>
}