1 import { outputJSON, pathExists } from 'fs-extra'
2 import { join } from 'path'
3 import { execShell } from '../../helpers/core-utils'
4 import { isNpmPluginNameValid, isPluginStableOrUnstableVersionValid } from '../../helpers/custom-validators/plugins'
5 import { logger } from '../../helpers/logger'
6 import { CONFIG } from '../../initializers/config'
7 import { getLatestPluginVersion } from './plugin-index'
9 async function installNpmPlugin (npmName: string, versionArg?: string) {
11 checkNpmPluginNameOrThrow(npmName)
12 if (versionArg) checkPluginVersionOrThrow(versionArg)
14 const version = versionArg || await getLatestPluginVersion(npmName)
16 let toInstall = npmName
17 if (version) toInstall += `@${version}`
19 const { stdout } = await execYarn('add ' + toInstall)
21 logger.debug('Added a yarn package.', { yarnStdout: stdout })
24 async function installNpmPluginFromDisk (path: string) {
25 await execYarn('add file:' + path)
28 async function removeNpmPlugin (name: string) {
29 checkNpmPluginNameOrThrow(name)
31 await execYarn('remove ' + name)
34 async function rebuildNativePlugins () {
35 await execYarn('install --pure-lockfile')
38 // ############################################################################
42 installNpmPluginFromDisk,
47 // ############################################################################
49 async function execYarn (command: string) {
51 const pluginDirectory = CONFIG.STORAGE.PLUGINS_DIR
52 const pluginPackageJSON = join(pluginDirectory, 'package.json')
54 // Create empty package.json file if needed
55 if (!await pathExists(pluginPackageJSON)) {
56 await outputJSON(pluginPackageJSON, {})
59 return execShell(`yarn ${command}`, { cwd: pluginDirectory })
61 logger.error('Cannot exec yarn.', { command, err: result.err, stderr: result.stderr })
67 function checkNpmPluginNameOrThrow (name: string) {
68 if (!isNpmPluginNameValid(name)) throw new Error('Invalid NPM plugin name to install')
71 function checkPluginVersionOrThrow (name: string) {
72 if (!isPluginStableOrUnstableVersionValid(name)) throw new Error('Invalid NPM plugin version to install')