-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
275 lines (249 loc) · 7.36 KB
/
index.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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#!/usr/bin/env node
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { cwd } from 'node:process'
import { parseArgs } from 'node:util'
import {
intro,
outro,
log,
select,
confirm,
spinner,
cancel,
isCancel,
} from '@clack/prompts'
import { execa, ExecaError } from 'execa'
import pico from 'picocolors'
// normalize the prompt answer and deal with cancel operations
async function normalizeAnswer<T>(
maybeCancelPromise: Promise<T | symbol>,
): Promise<T> {
const maybeCancel = await maybeCancelPromise
if (isCancel(maybeCancel)) {
cancel('Operation cancelled.')
process.exit(0)
} else {
return maybeCancel
}
}
// the RELEASE_TAG would be replaced at build time
declare global {
const RELEASE_TAG: 'canary' | 'canary-minor' | 'alpha' | 'beta' | 'rc'
}
// parse the command-line arguments
// npx install-vue@canary --version 3.20230911.0
const { values: args } = parseArgs({
options: {
version: {
type: 'string',
},
},
})
const packageJsonPath = resolve(cwd(), './package.json')
if (!existsSync(packageJsonPath)) {
throw new Error('Cannot find package.json in the current directory')
}
const pkg = JSON.parse(readFileSync(packageJsonPath, 'utf-8'))
intro('Installing Vue.js')
try {
const { stdout: gitStatus } = await execa('git', ['status', '--porcelain'])
if (gitStatus.trim()) {
log.warn(
"There are uncommitted changes in the current repository, it's recommended to commit or stash them first.",
)
const shouldProceed = await normalizeAnswer(
confirm({
message: `Still proceed?`,
initialValue: false,
}),
)
if (!shouldProceed) {
cancel('Operation cancelled.')
process.exit(1)
}
}
} catch (e) {
// Do nothing if git is not available, or if it's not a git repo
}
// decide which package manager to use
const SUPPORTED_PACKAGE_MANAGERS = ['npm', 'pnpm', 'yarn'] as const
type PackageManager = (typeof SUPPORTED_PACKAGE_MANAGERS)[number]
const LOCKFILE_TO_PACKAGE_MANAGER: Record<string, PackageManager> = {
'pnpm-lock.yaml': 'pnpm',
'yarn.lock': 'yarn',
'package-lock.json': 'npm',
'npm-shrinkwrap.json': 'npm',
}
let pm: PackageManager = 'npm'
const pmCandidates: PackageManager[] = []
for (const [lockfile, pmName] of Object.entries(LOCKFILE_TO_PACKAGE_MANAGER)) {
if (existsSync(resolve(cwd(), lockfile))) {
pmCandidates.push(pmName)
}
}
if (pmCandidates.length === 1) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
pm = pmCandidates[0]!
} else if (pmCandidates.length > 1) {
pm = await normalizeAnswer(
select({
message:
'More than one lockfile found, please select the package manager you would like to use',
options: pmCandidates.map((candidate) => ({
value: candidate,
label: candidate,
})),
}),
)
} else {
pm = await normalizeAnswer(
select({
message: 'Cannot infer which package manager to use, please select',
options: SUPPORTED_PACKAGE_MANAGERS.map((candidate) => ({
value: candidate,
label: candidate,
})),
}),
)
}
const CORE_VUE_PACKAGES = [
'vue',
'@vue/compiler-core',
'@vue/compiler-dom',
'@vue/compiler-sfc',
'@vue/compiler-ssr',
'@vue/reactivity',
// TODO: remove reactivity-transform
'@vue/reactivity-transform',
'@vue/runtime-core',
'@vue/runtime-dom',
'@vue/server-renderer',
'@vue/shared',
'@vue/compat',
]
const toCanaryPackageName = (name: string) =>
name === 'vue' ? '@vue/canary' : `${name}-canary`
function getOverrides(version = args.version): Record<string, string> {
return Object.fromEntries(
CORE_VUE_PACKAGES.map((name) => {
const packageName = RELEASE_TAG.startsWith('canary')
? toCanaryPackageName(name)
: name
if (RELEASE_TAG === 'canary') {
return [name, `npm:${packageName}${version ? `@${version}` : ''}`]
} else if (RELEASE_TAG === 'canary-minor') {
return [name, `npm:${packageName}@${version ?? 'minor'}}`]
} else {
return [name, `${version ?? RELEASE_TAG}`]
}
}),
)
}
// apply the overrides to the package.json
if (pm === 'npm') {
// https://github.com/npm/rfcs/blob/main/accepted/0036-overrides.md
// Must use exact version (won't work without version or with `@latest`)
let targetVersion: string
if (args.version) {
targetVersion = args.version
} else {
const corePackageName = RELEASE_TAG.startsWith('canary')
? '@vue/canary'
: 'vue'
let distTag: string = RELEASE_TAG
if (RELEASE_TAG === 'canary') {
distTag = 'latest'
} else if (RELEASE_TAG === 'canary-minor') {
distTag = 'minor'
}
const s = spinner()
s.start(`Checking for the latest ${RELEASE_TAG} version`)
const { stdout } = await execa(
'npm',
['info', `${corePackageName}@${distTag}`, 'version', '--json'],
{ stdio: 'pipe' },
)
targetVersion = JSON.parse(stdout)
s.stop(`Found ${RELEASE_TAG} version ${pico.yellow(targetVersion)}`)
}
let overrides: Record<string, string> = getOverrides(targetVersion)
pkg.overrides = {
...pkg.overrides,
...overrides,
}
// NPM requires direct dependencies to be rewritten too
for (const dependencyName of CORE_VUE_PACKAGES) {
for (const dependencyType of [
'dependencies',
'devDependencies',
'optionalDependencies',
]) {
if (pkg[dependencyType]?.[dependencyName]) {
pkg[dependencyType][dependencyName] = overrides[dependencyName]
}
}
}
} else if (pm === 'pnpm') {
const overrides = getOverrides()
pkg.pnpm ??= {}
// https://pnpm.io/package_json#pnpmoverrides
// pnpm & npm overrides differs slightly on their abilities: https://github.com/npm/rfcs/pull/129/files#r440478558
// so they use different configuration fields
pkg.pnpm.overrides = {
...pkg.pnpm.overrides,
...overrides,
}
// https://pnpm.io/package_json#pnpmpeerdependencyrulesallowany
pkg.pnpm.peerDependencyRules ??= {}
pkg.pnpm.peerDependencyRules.allowAny ??= []
pkg.pnpm.peerDependencyRules.allowAny.push('vue')
} else if (pm === 'yarn') {
// https://github.com/yarnpkg/rfcs/blob/master/implemented/0000-selective-versions-resolutions.md
pkg.resolutions = {
...pkg.resolutions,
...getOverrides(),
}
} else {
// unreachable
}
// write pkg back
writeFileSync(
packageJsonPath,
JSON.stringify(pkg, undefined, 2) + '\n',
'utf-8',
)
log.step(
`Updated ${pico.yellow('package.json')} for ${pico.magenta(
pm,
)} dependency overrides`,
)
// prompt & run install
const shouldInstall = await normalizeAnswer(
confirm({
message: `Run ${pico.magenta(
`${pm} install`,
)} to install the updated dependencies?`,
initialValue: true,
}),
)
// Note:
// there's an issue claiming that `npm install` doesn't always work
// https://github.com/npm/cli/issues/5850
// but I can't reproduce it locally with the vue.js overrides in place
// so I'm not sure if we need to do something special here
if (shouldInstall) {
const s = spinner()
s.start(`Installing via ${pm}`)
try {
await execa(pm, ['install'], { stdio: 'pipe' })
s.stop(`Installed via ${pm}`)
} catch (e) {
s.stop(pico.red('Installation failed'))
log.error((e as ExecaError).stderr || (e as ExecaError).message)
process.exit(1)
}
outro(`Done!`)
} else {
outro(`Done! Don't forget to run ${pico.magenta(`${pm} install`)} later.`)
}