2023-04-07 15:34:11 +00:00
|
|
|
import { addDependency } from 'nypm'
|
2023-07-30 20:25:00 +00:00
|
|
|
import { resolvePackageJSON } from 'pkg-types'
|
2023-10-17 11:07:31 +00:00
|
|
|
import { logger, useNuxt } from '@nuxt/kit'
|
2023-10-11 10:31:14 +00:00
|
|
|
import { isCI, provider } from 'std-env'
|
2023-04-07 15:34:11 +00:00
|
|
|
|
2023-10-11 10:31:14 +00:00
|
|
|
const isStackblitz = provider === 'stackblitz'
|
|
|
|
|
|
|
|
export interface EnsurePackageInstalledOptions {
|
|
|
|
rootDir: string
|
|
|
|
searchPaths?: string[]
|
|
|
|
prompt?: boolean
|
|
|
|
}
|
|
|
|
|
2023-10-17 11:07:31 +00:00
|
|
|
async function promptToInstall (name: string, installCommand: () => Promise<void>, options: EnsurePackageInstalledOptions) {
|
2023-10-11 10:31:14 +00:00
|
|
|
if (await resolvePackageJSON(name, { url: options.searchPaths }).catch(() => null)) {
|
2023-04-07 15:34:11 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.info(`Package ${name} is missing`)
|
2023-08-14 21:04:47 +00:00
|
|
|
if (isCI) {
|
|
|
|
return false
|
|
|
|
}
|
2023-04-07 15:34:11 +00:00
|
|
|
|
2023-10-11 10:31:14 +00:00
|
|
|
// In StackBlitz we install packages automatically by default
|
|
|
|
if (options.prompt === true || (options.prompt !== false && !isStackblitz)) {
|
|
|
|
const confirm = await logger.prompt(`Do you want to install ${name} package?`, {
|
|
|
|
type: 'confirm',
|
|
|
|
name: 'confirm',
|
|
|
|
initial: true
|
|
|
|
})
|
2023-04-07 15:34:11 +00:00
|
|
|
|
2023-10-11 10:31:14 +00:00
|
|
|
if (!confirm) {
|
|
|
|
return false
|
|
|
|
}
|
2023-04-07 15:34:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
logger.info(`Installing ${name}...`)
|
|
|
|
try {
|
2023-10-17 11:07:31 +00:00
|
|
|
await installCommand()
|
2023-04-07 15:34:11 +00:00
|
|
|
logger.success(`Installed ${name}`)
|
|
|
|
return true
|
|
|
|
} catch (err) {
|
|
|
|
logger.error(err)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
2023-10-17 11:07:31 +00:00
|
|
|
|
|
|
|
// TODO: refactor to Nuxi
|
|
|
|
const installPrompts = new Set<string>()
|
|
|
|
export function installNuxtModule (name: string, options?: EnsurePackageInstalledOptions) {
|
|
|
|
if (installPrompts.has(name)) { return }
|
|
|
|
installPrompts.add(name)
|
|
|
|
const nuxt = useNuxt()
|
|
|
|
return promptToInstall(name, async () => {
|
|
|
|
const { runCommand } = await import('nuxi')
|
|
|
|
await runCommand('module', ['add', name, '--cwd', nuxt.options.rootDir])
|
|
|
|
}, { rootDir: nuxt.options.rootDir, searchPaths: nuxt.options.modulesDir, ...options })
|
|
|
|
}
|
|
|
|
|
|
|
|
export function ensurePackageInstalled (name: string, options: EnsurePackageInstalledOptions) {
|
|
|
|
return promptToInstall(name, () => addDependency(name, {
|
|
|
|
cwd: options.rootDir,
|
|
|
|
dev: true
|
|
|
|
}), options)
|
|
|
|
}
|