]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/plugins/plugin-manager.ts
Bumped to version v5.2.1
[github/Chocobozzz/PeerTube.git] / server / lib / plugins / plugin-manager.ts
CommitLineData
41fb13c3 1import express from 'express'
67ed6552 2import { createReadStream, createWriteStream } from 'fs'
302eba0d 3import { ensureDir, outputFile, readJSON } from 'fs-extra'
9d4c60dc 4import { Server } from 'http'
f023a19c 5import { basename, join } from 'path'
ca87d95b 6import { decachePlugin } from '@server/helpers/decache'
c795e196 7import { ApplicationModel } from '@server/models/application/application'
67ed6552 8import { MOAuthTokenUser, MUser } from '@server/types/models'
428ccb8b 9import { getCompleteLocale } from '@shared/core-utils'
e5d91a9b
C
10import {
11 ClientScriptJSON,
12 PluginPackageJSON,
13 PluginTranslation,
14 PluginTranslationPathsJSON,
15 RegisterServerHookOptions
16} from '@shared/models'
67ed6552 17import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks'
345da516 18import { PluginType } from '../../../shared/models/plugins/plugin.type'
428ccb8b 19import { ServerHook, ServerHookName } from '../../../shared/models/plugins/server/server-hook.model'
67ed6552
C
20import { isLibraryCodeValid, isPackageJSONValid } from '../../helpers/custom-validators/plugins'
21import { logger } from '../../helpers/logger'
22import { CONFIG } from '../../initializers/config'
23import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants'
24import { PluginModel } from '../../models/server/plugin'
25import { PluginLibrary, RegisterServerAuthExternalOptions, RegisterServerAuthPassOptions, RegisterServerOptions } from '../../types/plugins'
a8b666e9 26import { ClientHtml } from '../client-html'
1896bca0 27import { RegisterHelpers } from './register-helpers'
c795e196 28import { installNpmPlugin, installNpmPluginFromDisk, rebuildNativePlugins, removeNpmPlugin } from './yarn'
345da516
C
29
30export interface RegisteredPlugin {
b5f919ac 31 npmName: string
345da516
C
32 name: string
33 version: string
34 description: string
35 peertubeEngine: string
36
37 type: PluginType
38
39 path: string
40
41 staticDirs: { [name: string]: string }
c7cdac44 42 clientScripts: { [name: string]: ClientScriptJSON }
345da516
C
43
44 css: string[]
45
46 // Only if this is a plugin
1896bca0 47 registerHelpers?: RegisterHelpers
345da516
C
48 unregister?: Function
49}
50
51export interface HookInformationValue {
b5f919ac 52 npmName: string
345da516
C
53 pluginName: string
54 handler: Function
55 priority: number
56}
57
d75db01f 58type PluginLocalesTranslations = {
a1587156 59 [locale: string]: PluginTranslation
d75db01f
C
60}
61
b4055e1c 62export class PluginManager implements ServerHook {
345da516
C
63
64 private static instance: PluginManager
65
a1587156 66 private registeredPlugins: { [name: string]: RegisteredPlugin } = {}
7fed6375 67
a1587156 68 private hooks: { [name: string]: HookInformationValue[] } = {}
d75db01f 69 private translations: PluginLocalesTranslations = {}
345da516 70
9d4c60dc
C
71 private server: Server
72
345da516
C
73 private constructor () {
74 }
75
9d4c60dc
C
76 init (server: Server) {
77 this.server = server
78 }
79
80 registerWebSocketRouter () {
81 this.server.on('upgrade', (request, socket, head) => {
82d1653d
C
82 // Check if it's a plugin websocket connection
83 // No need to destroy the stream when we abort the request
84 // Other handlers in PeerTube will catch this upgrade event too (socket.io, tracker etc)
85
9d4c60dc
C
86 const url = request.url
87
88 const matched = url.match(`/plugins/([^/]+)/([^/]+/)?ws(/.*)`)
89 if (!matched) return
90
91 const npmName = PluginModel.buildNpmName(matched[1], PluginType.PLUGIN)
92 const subRoute = matched[3]
93
94 const result = this.getRegisteredPluginOrTheme(npmName)
95 if (!result) return
96
97 const routes = result.registerHelpers.getWebSocketRoutes()
98
99 const wss = routes.find(r => r.route.startsWith(subRoute))
100 if (!wss) return
101
82d1653d
C
102 try {
103 wss.handler(request, socket, head)
104 } catch (err) {
105 logger.error('Exception in plugin handler ' + npmName, { err })
106 }
9d4c60dc
C
107 })
108 }
109
ad91e700 110 // ###################### Getters ######################
345da516 111
6702a1b2
C
112 isRegistered (npmName: string) {
113 return !!this.getRegisteredPluginOrTheme(npmName)
114 }
115
b5f919ac
C
116 getRegisteredPluginOrTheme (npmName: string) {
117 return this.registeredPlugins[npmName]
7cd4d2ba
C
118 }
119
e1c55031 120 getRegisteredPluginByShortName (name: string) {
b5f919ac
C
121 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
122 const registered = this.getRegisteredPluginOrTheme(npmName)
7cd4d2ba
C
123
124 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
125
126 return registered
345da516
C
127 }
128
e1c55031 129 getRegisteredThemeByShortName (name: string) {
b5f919ac
C
130 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
131 const registered = this.getRegisteredPluginOrTheme(npmName)
345da516
C
132
133 if (!registered || registered.type !== PluginType.THEME) return undefined
134
135 return registered
136 }
137
18a6f04c 138 getRegisteredPlugins () {
7cd4d2ba
C
139 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
140 }
141
142 getRegisteredThemes () {
143 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
18a6f04c
C
144 }
145
7fed6375
C
146 getIdAndPassAuths () {
147 return this.getRegisteredPlugins()
ebefc902
C
148 .map(p => ({
149 npmName: p.npmName,
150 name: p.name,
151 version: p.version,
1896bca0 152 idAndPassAuths: p.registerHelpers.getIdAndPassAuths()
ebefc902 153 }))
7fed6375
C
154 .filter(v => v.idAndPassAuths.length !== 0)
155 }
156
157 getExternalAuths () {
158 return this.getRegisteredPlugins()
ebefc902
C
159 .map(p => ({
160 npmName: p.npmName,
161 name: p.name,
162 version: p.version,
1896bca0 163 externalAuths: p.registerHelpers.getExternalAuths()
ebefc902
C
164 }))
165 .filter(v => v.externalAuths.length !== 0)
7fed6375
C
166 }
167
b5f919ac 168 getRegisteredSettings (npmName: string) {
7fed6375
C
169 const result = this.getRegisteredPluginOrTheme(npmName)
170 if (!result || result.type !== PluginType.PLUGIN) return []
5e2b2e27 171
1896bca0 172 return result.registerHelpers.getSettings()
5e2b2e27
C
173 }
174
175 getRouter (npmName: string) {
7fed6375
C
176 const result = this.getRegisteredPluginOrTheme(npmName)
177 if (!result || result.type !== PluginType.PLUGIN) return null
5e2b2e27 178
1896bca0 179 return result.registerHelpers.getRouter()
ad91e700
C
180 }
181
d75db01f
C
182 getTranslations (locale: string) {
183 return this.translations[locale] || {}
184 }
185
e307e4fc
C
186 async isTokenValid (token: MOAuthTokenUser, type: 'access' | 'refresh') {
187 const auth = this.getAuth(token.User.pluginAuth, token.authName)
188 if (!auth) return true
189
190 if (auth.hookTokenValidity) {
191 try {
192 const { valid } = await auth.hookTokenValidity({ token, type })
193
194 if (valid === false) {
195 logger.info('Rejecting %s token validity from auth %s of plugin %s', type, token.authName, token.User.pluginAuth)
196 }
197
198 return valid
199 } catch (err) {
200 logger.warn('Cannot run check token validity from auth %s of plugin %s.', token.authName, token.User.pluginAuth, { err })
201 return true
202 }
203 }
204
205 return true
206 }
207
a5896799
C
208 // ###################### External events ######################
209
74fd2643 210 async onLogout (npmName: string, authName: string, user: MUser, req: express.Request) {
a5896799
C
211 const auth = this.getAuth(npmName, authName)
212
213 if (auth?.onLogout) {
214 logger.info('Running onLogout function from auth %s of plugin %s', authName, npmName)
215
216 try {
74fd2643
C
217 // Force await, in case or onLogout returns a promise
218 const result = await auth.onLogout(user, req)
219
220 return typeof result === 'string'
221 ? result
222 : undefined
a5896799
C
223 } catch (err) {
224 logger.warn('Cannot run onLogout function from auth %s of plugin %s.', authName, npmName, { err })
225 }
226 }
74fd2643
C
227
228 return undefined
a5896799
C
229 }
230
24a79240 231 async onSettingsChanged (name: string, settings: any) {
a5896799
C
232 const registered = this.getRegisteredPluginByShortName(name)
233 if (!registered) {
234 logger.error('Cannot find plugin %s to call on settings changed.', name)
235 }
236
1896bca0 237 for (const cb of registered.registerHelpers.getOnSettingsChangedCallbacks()) {
a5896799 238 try {
24a79240 239 await cb(settings)
a5896799
C
240 } catch (err) {
241 logger.error('Cannot run on settings changed callback for %s.', registered.npmName, { err })
242 }
243 }
244 }
245
ad91e700
C
246 // ###################### Hooks ######################
247
a1587156 248 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
89cd1275 249 if (!this.hooks[hookName]) return Promise.resolve(result)
dba85a1e 250
b4055e1c 251 const hookType = getHookType(hookName)
18a6f04c
C
252
253 for (const hook of this.hooks[hookName]) {
89cd1275
C
254 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
255
22df69fd
C
256 result = await internalRunHook({
257 handler: hook.handler,
258 hookType,
259 result,
260 params,
261 onError: err => { logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err }) }
b4055e1c 262 })
18a6f04c
C
263 }
264
265 return result
266 }
267
ad91e700
C
268 // ###################### Registration ######################
269
270 async registerPluginsAndThemes () {
271 await this.resetCSSGlobalFile()
272
273 const plugins = await PluginModel.listEnabledPluginsAndThemes()
274
275 for (const plugin of plugins) {
276 try {
277 await this.registerPluginOrTheme(plugin)
278 } catch (err) {
587568e1
C
279 // Try to unregister the plugin
280 try {
281 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
282 } catch {
283 // we don't care if we cannot unregister it
284 }
285
ad91e700
C
286 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
287 }
288 }
289
290 this.sortHooksByPriority()
291 }
292
b5f919ac
C
293 // Don't need the plugin type since themes cannot register server code
294 async unregister (npmName: string) {
295 logger.info('Unregister plugin %s.', npmName)
296
297 const plugin = this.getRegisteredPluginOrTheme(npmName)
345da516
C
298
299 if (!plugin) {
b5f919ac 300 throw new Error(`Unknown plugin ${npmName} to unregister`)
345da516
C
301 }
302
60cfd4cb
C
303 delete this.registeredPlugins[plugin.npmName]
304
d75db01f
C
305 this.deleteTranslations(plugin.npmName)
306
b5f919ac
C
307 if (plugin.type === PluginType.PLUGIN) {
308 await plugin.unregister()
345da516 309
b5f919ac
C
310 // Remove hooks of this plugin
311 for (const key of Object.keys(this.hooks)) {
98da1a7b 312 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
b5f919ac 313 }
2c053942 314
1896bca0 315 const store = plugin.registerHelpers
5e2b2e27 316 store.reinitVideoConstants(plugin.npmName)
1896bca0 317 store.reinitTranscodingProfilesAndEncoders(plugin.npmName)
5e2b2e27 318
b5f919ac
C
319 logger.info('Regenerating registered plugin CSS to global file.')
320 await this.regeneratePluginGlobalCSS()
2c053942 321 }
2769876f
C
322
323 ClientHtml.invalidCache()
345da516
C
324 }
325
ad91e700
C
326 // ###################### Installation ######################
327
841ddf88
C
328 async install (options: {
329 toInstall: string
330 version?: string
331 fromDisk?: boolean // default false
332 register?: boolean // default true
333 }) {
334 const { toInstall, version, fromDisk = false, register = true } = options
335
f023a19c 336 let plugin: PluginModel
b5f919ac 337 let npmName: string
f023a19c
C
338
339 logger.info('Installing plugin %s.', toInstall)
340
341 try {
342 fromDisk
343 ? await installNpmPluginFromDisk(toInstall)
344 : await installNpmPlugin(toInstall, version)
345
b5f919ac
C
346 npmName = fromDisk ? basename(toInstall) : toInstall
347 const pluginType = PluginModel.getTypeFromNpmName(npmName)
348 const pluginName = PluginModel.normalizePluginName(npmName)
f023a19c 349
09071200 350 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
9157d598
C
351
352 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
f023a19c
C
353
354 [ plugin ] = await PluginModel.upsert({
355 name: pluginName,
356 description: packageJSON.description,
dba85a1e 357 homepage: packageJSON.homepage,
f023a19c
C
358 type: pluginType,
359 version: packageJSON.version,
360 enabled: true,
361 uninstalled: false,
362 peertubeEngine: packageJSON.engine.peertube
363 }, { returning: true })
9c2e051c
C
364
365 logger.info('Successful installation of plugin %s.', toInstall)
366
841ddf88
C
367 if (register) {
368 await this.registerPluginOrTheme(plugin)
369 }
9c2e051c
C
370 } catch (rootErr) {
371 logger.error('Cannot install plugin %s, removing it...', toInstall, { err: rootErr })
f023a19c 372
f86ff3a0 373 if (npmName) {
9c2e051c 374 try {
f86ff3a0 375 await this.uninstall({ npmName })
9c2e051c 376 } catch (err) {
f86ff3a0
C
377 logger.error('Cannot uninstall plugin %s after failed installation.', toInstall, { err })
378
379 try {
380 await removeNpmPlugin(npmName)
381 } catch (err) {
382 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
383 }
9c2e051c 384 }
f023a19c
C
385 }
386
9c2e051c 387 throw rootErr
f023a19c
C
388 }
389
b5f919ac
C
390 return plugin
391 }
392
8280d0c2 393 async update (toUpdate: string, fromDisk = false) {
b5f919ac
C
394 const npmName = fromDisk ? basename(toUpdate) : toUpdate
395
396 logger.info('Updating plugin %s.', npmName)
397
8280d0c2
C
398 // Use the latest version from DB, to not upgrade to a version that does not support our PeerTube version
399 let version: string
400 if (!fromDisk) {
401 const plugin = await PluginModel.loadByNpmName(toUpdate)
402 version = plugin.latestVersion
403 }
404
b5f919ac
C
405 // Unregister old hooks
406 await this.unregister(npmName)
407
841ddf88 408 return this.install({ toInstall: toUpdate, version, fromDisk })
f023a19c
C
409 }
410
841ddf88
C
411 async uninstall (options: {
412 npmName: string
413 unregister?: boolean // default true
414 }) {
6bcb854c 415 const { npmName, unregister = true } = options
841ddf88 416
dba85a1e 417 logger.info('Uninstalling plugin %s.', npmName)
2c053942 418
841ddf88
C
419 if (unregister) {
420 try {
421 await this.unregister(npmName)
422 } catch (err) {
423 logger.warn('Cannot unregister plugin %s.', npmName, { err })
424 }
2c053942
C
425 }
426
dba85a1e 427 const plugin = await PluginModel.loadByNpmName(npmName)
2c053942 428 if (!plugin || plugin.uninstalled === true) {
dba85a1e 429 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
2c053942
C
430 return
431 }
432
433 plugin.enabled = false
434 plugin.uninstalled = true
435
436 await plugin.save()
f023a19c 437
dba85a1e 438 await removeNpmPlugin(npmName)
2c053942 439
dba85a1e 440 logger.info('Plugin %s uninstalled.', npmName)
f023a19c
C
441 }
442
c795e196
C
443 async rebuildNativePluginsIfNeeded () {
444 if (!await ApplicationModel.nodeABIChanged()) return
445
446 return rebuildNativePlugins()
447 }
448
ad91e700
C
449 // ###################### Private register ######################
450
345da516 451 private async registerPluginOrTheme (plugin: PluginModel) {
b5f919ac
C
452 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
453
454 logger.info('Registering plugin or theme %s.', npmName)
345da516 455
09071200 456 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
f023a19c 457 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
345da516 458
9157d598 459 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
345da516
C
460
461 let library: PluginLibrary
1896bca0 462 let registerHelpers: RegisterHelpers
345da516 463 if (plugin.type === PluginType.PLUGIN) {
7fed6375
C
464 const result = await this.registerPlugin(plugin, pluginPath, packageJSON)
465 library = result.library
1896bca0 466 registerHelpers = result.registerStore
345da516
C
467 }
468
c7cdac44 469 const clientScripts: { [id: string]: ClientScriptJSON } = {}
2c053942
C
470 for (const c of packageJSON.clientScripts) {
471 clientScripts[c.script] = c
472 }
473
a1587156 474 this.registeredPlugins[npmName] = {
b5f919ac 475 npmName,
345da516
C
476 name: plugin.name,
477 type: plugin.type,
478 version: plugin.version,
479 description: plugin.description,
480 peertubeEngine: plugin.peertubeEngine,
481 path: pluginPath,
482 staticDirs: packageJSON.staticDirs,
2c053942 483 clientScripts,
345da516 484 css: packageJSON.css,
1896bca0 485 registerHelpers: registerHelpers || undefined,
345da516
C
486 unregister: library ? library.unregister : undefined
487 }
d75db01f
C
488
489 await this.addTranslations(plugin, npmName, packageJSON.translations)
2769876f
C
490
491 ClientHtml.invalidCache()
345da516
C
492 }
493
c7cdac44 494 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJSON) {
b5f919ac
C
495 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
496
09071200
C
497 // Delete cache if needed
498 const modulePath = join(pluginPath, packageJSON.library)
07880c36 499 decachePlugin(modulePath)
09071200 500 const library: PluginLibrary = require(modulePath)
f023a19c 501
345da516
C
502 if (!isLibraryCodeValid(library)) {
503 throw new Error('Library code is not valid (miss register or unregister function)')
504 }
505
7fed6375 506 const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin)
302eba0d
C
507
508 await ensureDir(registerOptions.peertubeHelpers.plugin.getDataDirectoryPath())
509
9c2e051c 510 await library.register(registerOptions)
345da516 511
b5f919ac 512 logger.info('Add plugin %s CSS to global file.', npmName)
345da516
C
513
514 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
515
7fed6375 516 return { library, registerStore }
345da516
C
517 }
518
d75db01f
C
519 // ###################### Translations ######################
520
c7cdac44 521 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PluginTranslationPathsJSON) {
d75db01f
C
522 for (const locale of Object.keys(translationPaths)) {
523 const path = translationPaths[locale]
524 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
525
67baf647 526 const completeLocale = getCompleteLocale(locale)
d75db01f 527
67baf647
C
528 if (!this.translations[completeLocale]) this.translations[completeLocale] = {}
529 this.translations[completeLocale][npmName] = json
530
531 logger.info('Added locale %s of plugin %s.', completeLocale, npmName)
d75db01f
C
532 }
533 }
534
535 private deleteTranslations (npmName: string) {
536 for (const locale of Object.keys(this.translations)) {
537 delete this.translations[locale][npmName]
538
539 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
540 }
541 }
542
ad91e700 543 // ###################### CSS ######################
345da516 544
2c053942
C
545 private resetCSSGlobalFile () {
546 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
547 }
548
345da516
C
549 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
550 for (const cssPath of cssRelativePaths) {
551 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
552 }
553 }
554
555 private concatFiles (input: string, output: string) {
556 return new Promise<void>((res, rej) => {
2c053942
C
557 const inputStream = createReadStream(input)
558 const outputStream = createWriteStream(output, { flags: 'a' })
345da516
C
559
560 inputStream.pipe(outputStream)
561
562 inputStream.on('end', () => res())
563 inputStream.on('error', err => rej(err))
564 })
565 }
566
ad91e700
C
567 private async regeneratePluginGlobalCSS () {
568 await this.resetCSSGlobalFile()
569
1198edf4 570 for (const plugin of this.getRegisteredPlugins()) {
ad91e700
C
571 await this.addCSSToGlobalFile(plugin.path, plugin.css)
572 }
573 }
574
575 // ###################### Utils ######################
576
577 private sortHooksByPriority () {
578 for (const hookName of Object.keys(this.hooks)) {
579 this.hooks[hookName].sort((a, b) => {
580 return b.priority - a.priority
581 })
582 }
583 }
584
f023a19c
C
585 private getPackageJSON (pluginName: string, pluginType: PluginType) {
586 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
587
c7cdac44 588 return readJSON(pluginPath) as Promise<PluginPackageJSON>
f023a19c
C
589 }
590
591 private getPluginPath (pluginName: string, pluginType: PluginType) {
b5f919ac 592 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
f023a19c 593
b5f919ac 594 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
f023a19c
C
595 }
596
e307e4fc
C
597 private getAuth (npmName: string, authName: string) {
598 const plugin = this.getRegisteredPluginOrTheme(npmName)
599 if (!plugin || plugin.type !== PluginType.PLUGIN) return null
600
1896bca0
C
601 let auths: (RegisterServerAuthPassOptions | RegisterServerAuthExternalOptions)[] = plugin.registerHelpers.getIdAndPassAuths()
602 auths = auths.concat(plugin.registerHelpers.getExternalAuths())
9107d791
C
603
604 return auths.find(a => a.authName === authName)
e307e4fc
C
605 }
606
ad91e700 607 // ###################### Private getters ######################
2c053942 608
7cd4d2ba
C
609 private getRegisteredPluginsOrThemes (type: PluginType) {
610 const plugins: RegisteredPlugin[] = []
611
b5f919ac 612 for (const npmName of Object.keys(this.registeredPlugins)) {
a1587156 613 const plugin = this.registeredPlugins[npmName]
7cd4d2ba
C
614 if (plugin.type !== type) continue
615
616 plugins.push(plugin)
617 }
618
619 return plugins
620 }
621
32fe0013
C
622 // ###################### Generate register helpers ######################
623
7fed6375
C
624 private getRegisterHelpers (
625 npmName: string,
626 plugin: PluginModel
1896bca0 627 ): { registerStore: RegisterHelpers, registerOptions: RegisterServerOptions } {
5e2b2e27 628 const onHookAdded = (options: RegisterServerHookOptions) => {
32fe0013
C
629 if (!this.hooks[options.target]) this.hooks[options.target] = []
630
631 this.hooks[options.target].push({
ba2684ce 632 npmName,
32fe0013
C
633 pluginName: plugin.name,
634 handler: options.handler,
635 priority: options.priority || 0
636 })
637 }
638
9d4c60dc 639 const registerHelpers = new RegisterHelpers(npmName, plugin, this.server, onHookAdded.bind(this))
32fe0013 640
7fed6375 641 return {
1896bca0
C
642 registerStore: registerHelpers,
643 registerOptions: registerHelpers.buildRegisterHelpers()
7fed6375 644 }
ee286591
C
645 }
646
c7cdac44 647 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJSON, pluginType: PluginType) {
9157d598
C
648 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
649 if (!packageJSON.css) packageJSON.css = []
650 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
651 if (!packageJSON.translations) packageJSON.translations = {}
652
653 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
654 if (!packageJSONValid) {
655 const formattedFields = badFields.map(f => `"${f}"`)
a1587156 656 .join(', ')
9157d598
C
657
658 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
659 }
660 }
661
345da516
C
662 static get Instance () {
663 return this.instance || (this.instance = new this())
664 }
665}