1 import { execShell } from '../../helpers/core-utils'
2 import { logger } from '../../helpers/logger'
3 import { isNpmPluginNameValid, isPluginVersionValid } from '../../helpers/custom-validators/plugins'
4 import { CONFIG } from '../../initializers/config'
5 import { outputJSON, pathExists } from 'fs-extra'
6 import { join } from 'path'
8 async function installNpmPlugin (npmName: string, version?: string) {
10 checkNpmPluginNameOrThrow(npmName)
11 if (version) checkPluginVersionOrThrow(version)
13 let toInstall = npmName
14 if (version) toInstall += `@${version}`
16 const { stdout } = await execYarn('add ' + toInstall)
18 logger.debug('Added a yarn package.', { yarnStdout: stdout })
21 async function installNpmPluginFromDisk (path: string) {
22 await execYarn('add file:' + path)
25 async function removeNpmPlugin (name: string) {
26 checkNpmPluginNameOrThrow(name)
28 await execYarn('remove ' + name)
31 // ############################################################################
35 installNpmPluginFromDisk,
39 // ############################################################################
41 async function execYarn (command: string) {
43 const pluginDirectory = CONFIG.STORAGE.PLUGINS_DIR
44 const pluginPackageJSON = join(pluginDirectory, 'package.json')
46 // Create empty package.json file if needed
47 if (!await pathExists(pluginPackageJSON)) {
48 await outputJSON(pluginPackageJSON, {})
51 return execShell(`yarn ${command}`, { cwd: pluginDirectory })
53 logger.error('Cannot exec yarn.', { command, err: result.err, stderr: result.stderr })
59 function checkNpmPluginNameOrThrow (name: string) {
60 if (!isNpmPluginNameValid(name)) throw new Error('Invalid NPM plugin name to install')
63 function checkPluginVersionOrThrow (name: string) {
64 if (!isPluginVersionValid(name)) throw new Error('Invalid NPM plugin version to install')