WIP plugins: install/uninstall
[oweals/peertube.git] / server / lib / plugins / yarn.ts
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'
7
8 async function installNpmPlugin (name: string, version: string) {
9   // Security check
10   checkNpmPluginNameOrThrow(name)
11   checkPluginVersionOrThrow(version)
12
13   const toInstall = `${name}@${version}`
14   await execYarn('add ' + toInstall)
15 }
16
17 async function installNpmPluginFromDisk (path: string) {
18   await execYarn('add file:' + path)
19 }
20
21 async function removeNpmPlugin (name: string) {
22   checkNpmPluginNameOrThrow(name)
23
24   await execYarn('remove ' + name)
25 }
26
27 // ############################################################################
28
29 export {
30   installNpmPlugin,
31   installNpmPluginFromDisk,
32   removeNpmPlugin
33 }
34
35 // ############################################################################
36
37 async function execYarn (command: string) {
38   try {
39     const pluginDirectory = CONFIG.STORAGE.PLUGINS_DIR
40     const pluginPackageJSON = join(pluginDirectory, 'package.json')
41
42     // Create empty package.json file if needed
43     if (!await pathExists(pluginPackageJSON)) {
44       await outputJSON(pluginPackageJSON, {})
45     }
46
47     await execShell(`yarn ${command}`, { cwd: pluginDirectory })
48   } catch (result) {
49     logger.error('Cannot exec yarn.', { command, err: result.err, stderr: result.stderr })
50
51     throw result.err
52   }
53 }
54
55 function checkNpmPluginNameOrThrow (name: string) {
56   if (!isNpmPluginNameValid(name)) throw new Error('Invalid NPM plugin name to install')
57 }
58
59 function checkPluginVersionOrThrow (name: string) {
60   if (!isPluginVersionValid(name)) throw new Error('Invalid NPM plugin version to install')
61 }