/
PluginManager.js
661 lines (594 loc) · 22.2 KB
/
PluginManager.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
'use strict';
const path = require('path');
const config = require('@serverless/utils/config');
const cjsResolve = require('ncjsm/resolve/sync');
const BbPromise = require('bluebird');
const _ = require('lodash');
const crypto = require('crypto');
const isModuleNotFoundError = require('ncjsm/is-module-not-found-error');
const writeFile = require('../utils/fs/writeFile');
const getCacheFilePath = require('../utils/getCacheFilePath');
const serverlessConfigFileUtils = require('../utils/getServerlessConfigFile');
const getCommandSuggestion = require('../utils/getCommandSuggestion');
const requireServicePlugin = (servicePath, pluginPath, localPluginsPath) => {
if (localPluginsPath && !pluginPath.startsWith('./')) {
// TODO (BREAKING): Consider removing support for localPluginsPath with next major
const absoluteLocalPluginPath = path.resolve(localPluginsPath, pluginPath);
try {
return require(absoluteLocalPluginPath);
} catch (error) {
if (!isModuleNotFoundError(error, absoluteLocalPluginPath)) throw error;
}
}
try {
return require(cjsResolve(servicePath, pluginPath).realPath);
} catch (error) {
if (!isModuleNotFoundError(error, pluginPath) || pluginPath.startsWith('.')) {
throw error;
}
}
// Search in "node_modules" in which framework is placed
return require(cjsResolve(__dirname, pluginPath).realPath);
};
/**
* @private
* Error type to terminate the currently running hook chain successfully without
* executing the rest of the current command's lifecycle chain.
*/
class TerminateHookChain extends Error {
constructor(commands) {
const commandChain = commands.join(':');
const message = `Terminating ${commandChain}`;
super(message);
this.message = message;
this.name = 'TerminateHookChain';
}
}
class PluginManager {
constructor(serverless) {
this.serverless = serverless;
this.serverlessConfigFile = null;
this.cliOptions = {};
this.cliCommands = [];
this.pluginIndependentCommands = new Set(['help', 'plugin']);
this.plugins = [];
this.commands = {};
this.aliases = {};
this.hooks = {};
this.deprecatedEvents = {};
}
loadConfigFile() {
return serverlessConfigFileUtils.getServerlessConfigFile(this.serverless).then(
serverlessConfigFile => {
this.serverlessConfigFile = serverlessConfigFile;
return;
},
error => {
if (this.serverless.cli.isHelpRequest(this.serverless.processedInput)) {
this.serverless.config.servicePath = null;
return null;
}
throw error;
}
);
}
setCliOptions(options) {
this.cliOptions = options;
}
setCliCommands(commands) {
this.cliCommands = commands;
}
addPlugin(Plugin) {
const pluginInstance = new Plugin(this.serverless, this.cliOptions);
let pluginProvider = null;
// check if plugin is provider agnostic
if (pluginInstance.provider) {
if (typeof pluginInstance.provider === 'string') {
pluginProvider = pluginInstance.provider;
} else if (_.isObject(pluginInstance.provider)) {
pluginProvider = pluginInstance.provider.constructor.getProviderName();
}
}
// ignore plugins that specify a different provider than the current one
if (pluginProvider && pluginProvider !== this.serverless.service.provider.name) {
return;
}
// don't load plugins twice
if (this.plugins.some(plugin => plugin instanceof Plugin)) {
this.serverless.cli.log(`WARNING: duplicate plugin ${Plugin.name} was not loaded\n`);
return;
}
this.loadCommands(pluginInstance);
this.loadHooks(pluginInstance);
this.loadVariableResolvers(pluginInstance);
this.plugins.push(pluginInstance);
}
loadAllPlugins(servicePlugins) {
const EnterprisePlugin = this.resolveEnterprisePlugin();
[...require('../plugins'), ...this.resolveServicePlugins(servicePlugins)]
.filter(Boolean)
.forEach(Plugin => this.addPlugin(Plugin));
if (EnterprisePlugin) this.addPlugin(EnterprisePlugin);
return this.asyncPluginInit();
}
resolveServicePlugins(servicePlugs) {
const pluginsObject = this.parsePluginsObject(servicePlugs);
const servicePath = this.serverless.config.servicePath;
return pluginsObject.modules
.filter(name => name !== '@serverless/enterprise-plugin')
.map(name => {
let Plugin;
try {
Plugin = requireServicePlugin(servicePath, name, pluginsObject.localPath);
} catch (error) {
if (!isModuleNotFoundError(error, name)) throw error;
// Plugin not installed
if (this.cliOptions.help || this.pluginIndependentCommands.has(this.cliCommands[0])) {
// User may intend to install plugins just listed in serverless config
// Therefore skip on MODULE_NOT_FOUND case
return null;
}
throw new this.serverless.classes.Error(
[
`Serverless plugin "${name}" not found.`,
' Make sure it\'s installed and listed in the "plugins" section',
' of your serverless config file.',
].join('')
);
}
if (!Plugin) {
throw new this.serverless.classes.Error(
`Serverless plugin "${name}", didn't export Plugin constructor.`
);
}
return Plugin;
});
}
resolveEnterprisePlugin() {
if (config.getGlobalConfig().enterpriseDisabled) return null;
this.pluginIndependentCommands
.add('login')
.add('logout')
.add('dashboard');
return require('@serverless/enterprise-plugin');
}
parsePluginsObject(servicePlugs) {
let localPath =
this.serverless &&
this.serverless.config &&
this.serverless.config.servicePath &&
path.join(this.serverless.config.servicePath, '.serverless_plugins');
let modules = [];
if (Array.isArray(servicePlugs)) {
modules = servicePlugs;
} else if (servicePlugs) {
localPath =
servicePlugs.localPath && typeof servicePlugs.localPath === 'string'
? servicePlugs.localPath
: localPath;
if (Array.isArray(servicePlugs.modules)) {
modules = servicePlugs.modules;
}
}
return { modules, localPath };
}
createCommandAlias(alias, command) {
// Deny self overrides
if (command.startsWith(alias)) {
throw new this.serverless.classes.Error(`Command "${alias}" cannot be overriden by an alias`);
}
const splitAlias = alias.split(':');
const aliasTarget = splitAlias.reduce((__, aliasPath) => {
const currentAlias = __;
if (!currentAlias[aliasPath]) {
currentAlias[aliasPath] = {};
}
return currentAlias[aliasPath];
}, this.aliases);
// Check if the alias is already defined
if (aliasTarget.command) {
throw new this.serverless.classes.Error(
`Alias "${alias}" is already defined for command ${aliasTarget.command}`
);
}
// Check if the alias would overwrite an exiting command
if (
splitAlias.reduce((__, aliasPath) => {
if (!__ || !__.commands || !__.commands[aliasPath]) {
return null;
}
return __.commands[aliasPath];
}, this)
) {
throw new this.serverless.classes.Error(`Command "${alias}" cannot be overriden by an alias`);
}
aliasTarget.command = command;
}
loadCommand(pluginName, details, key, isEntryPoint) {
const commandIsEntryPoint = details.type === 'entrypoint' || isEntryPoint;
if (process.env.SLS_DEBUG && !commandIsEntryPoint) {
this.serverless.cli.log(`Load command ${key}`);
}
// Check if there is already an alias for the same path as the command
const aliasCommand = this.getAliasCommandTarget(key.split(':'));
if (aliasCommand) {
throw new this.serverless.classes.Error(`Command "${key}" cannot override an existing alias`);
}
// Load the command
const commands = _.mapValues(details.commands, (subDetails, subKey) =>
this.loadCommand(pluginName, subDetails, `${key}:${subKey}`, commandIsEntryPoint)
);
// Handle command aliases
(details.aliases || []).forEach(alias => {
if (process.env.SLS_DEBUG) {
this.serverless.cli.log(` -> @${alias}`);
}
this.createCommandAlias(alias, key);
});
return Object.assign({}, details, { key, pluginName, commands });
}
loadCommands(pluginInstance) {
const pluginName = pluginInstance.constructor.name;
if (pluginInstance.commands) {
Object.entries(pluginInstance.commands).forEach(([key, details]) => {
const command = this.loadCommand(pluginName, details, key);
// Grab and extract deprecated events
command.lifecycleEvents = (command.lifecycleEvents || []).map(event => {
if (event.startsWith('deprecated#')) {
// Extract event and optional redirect
const transformedEvent = /^deprecated#(.*?)(?:->(.*?))?$/.exec(event);
this.deprecatedEvents[`${command.key}:${transformedEvent[1]}`] =
transformedEvent[2] || null;
return transformedEvent[1];
}
return event;
});
this.commands[key] = _.merge({}, this.commands[key], command);
});
}
}
loadHooks(pluginInstance) {
const pluginName = pluginInstance.constructor.name;
if (pluginInstance.hooks) {
Object.entries(pluginInstance.hooks).forEach(([event, hook]) => {
let target = event;
const baseEvent = event.replace(/^(?:after:|before:)/, '');
if (this.deprecatedEvents[baseEvent]) {
const redirectedEvent = this.deprecatedEvents[baseEvent];
if (process.env.SLS_DEBUG) {
this.serverless.cli.log(`WARNING: Plugin ${pluginName} uses deprecated hook ${event},
use ${redirectedEvent} hook instead`);
}
if (redirectedEvent) {
target = event.replace(baseEvent, redirectedEvent);
}
}
this.hooks[target] = this.hooks[target] || [];
this.hooks[target].push({
pluginName,
hook,
});
});
}
}
loadVariableResolvers(pluginInstance) {
const pluginName = pluginInstance.constructor.name;
for (const [variablePrefix, resolverOrOptions] of Object.entries(
pluginInstance.variableResolvers || {}
)) {
let options = resolverOrOptions;
if (!options) {
this.serverless.cli.log(
`Warning! Ignoring falsy variableResolver for ${variablePrefix} in ${pluginName}.`
);
continue;
}
if (typeof resolverOrOptions === 'function') {
options = {
resolver: resolverOrOptions,
};
}
if (!_.isObject(options)) {
throw new Error(
`Custom variable resolver {${variablePrefix}: ${JSON.stringify(
options
)}} defined by ${pluginName} isn't an object`
);
} else if (!variablePrefix.match(/[0-9a-zA-Z_-]+/)) {
throw new Error(
`Custom variable resolver prefix ${variablePrefix} defined by ${pluginName} may only contain alphanumeric characters, hyphens or underscores.`
);
}
if (typeof options.resolver !== 'function') {
throw new Error(
`Custom variable resolver for ${variablePrefix} defined by ${pluginName} specifies a resolver that isn't a function: ${options.resolver}`
);
}
if (options.isDisabledAtPrepopulation && typeof options.serviceName !== 'string') {
throw new Error(
`Custom variable resolver for ${variablePrefix} defined by ${pluginName} specifies isDisabledAtPrepopulation but doesn't provide a string for a name`
);
}
this.serverless.variables.variableResolvers.push({
regex: new RegExp(`^${variablePrefix}:`),
resolver: options.resolver.bind(this.serverless.variables),
isDisabledAtPrepopulation: options.isDisabledAtPrepopulation || false,
serviceName: options.serviceName || null,
});
}
}
getCommands() {
const result = {};
// Iterate through the commands and stop at entrypoints to include only public
// command throughout the hierarchy.
const stack = [{ commands: this.commands, target: result }];
while (stack.length) {
const currentCommands = stack.pop();
const commands = currentCommands.commands;
const target = currentCommands.target;
if (commands) {
Object.entries(commands).forEach(([name, command]) => {
if (command.type !== 'entrypoint') {
_.set(target, name, _.omit(command, 'commands'));
if (
Object.values(command.commands).some(
childCommand => childCommand.type !== 'entrypoint'
)
) {
target[name].commands = {};
stack.push({ commands: command.commands, target: target[name].commands });
}
}
});
}
}
// Iterate through the existing aliases and add them as commands
_.remove(stack);
stack.push({ aliases: this.aliases, target: result });
while (stack.length) {
const currentAlias = stack.pop();
const aliases = currentAlias.aliases;
const target = currentAlias.target;
if (aliases) {
Object.entries(aliases).forEach(([name, alias]) => {
if (name === 'command') {
return;
}
if (alias.command) {
const commandPath = alias.command.split(':').join('.commands.');
_.set(target, name, _.get(this.commands, commandPath));
} else {
target[name] = target[name] || {};
target[name].commands = target[name].commands || {};
}
stack.push({ aliases: alias, target: target[name].commands });
});
}
}
return result;
}
getAliasCommandTarget(aliasArray) {
// Check if the command references an alias
const aliasCommand = aliasArray.reduce((__, commandPath) => {
if (!__ || !__[commandPath]) {
return null;
}
return __[commandPath];
}, this.aliases);
return _.get(aliasCommand, 'command');
}
/**
* Retrieve the command specified by a command list. The method can be configured
* to include entrypoint commands (which are invisible to the CLI and can only
* be used by plugins).
* @param commandsArray {Array<String>} Commands
* @param allowEntryPoints {undefined|boolean} Allow entrypoint commands to be returned
* @returns {Object} Command
*/
getCommand(commandsArray, allowEntryPoints) {
// Check if the command references an alias
const aliasCommandTarget = this.getAliasCommandTarget(commandsArray);
const commandOrAlias = aliasCommandTarget ? aliasCommandTarget.split(':') : commandsArray;
return commandOrAlias.reduce(
(current, name, index) => {
const commandExists = name in current.commands;
const isNotContainer = commandExists && current.commands[name].type !== 'container';
const isNotEntrypoint = commandExists && current.commands[name].type !== 'entrypoint';
const remainingIterationsLeft = index < commandOrAlias.length - 1;
if (
commandExists &&
(isNotContainer || remainingIterationsLeft) &&
(isNotEntrypoint || allowEntryPoints)
) {
return current.commands[name];
}
// if user is using a top level command properly, but sub commands are not
if (this.serverless.cli.loadedCommands[commandOrAlias[0]]) {
const errorMessage = [`"${name}" is not a valid sub command. Run "serverless `];
for (let i = 0; commandOrAlias[i] !== name; i++) {
errorMessage.push(`${commandOrAlias[i]}`);
if (commandOrAlias[i + 1] !== name) {
errorMessage.push(' ');
}
}
errorMessage.push('" to see a more helpful error message for this command.');
throw new this.serverless.classes.Error(errorMessage.join(''));
}
// top level command isn't valid. give a suggestion
const commandName = commandOrAlias.slice(0, index + 1).join(' ');
const suggestedCommand = getCommandSuggestion(
commandName,
this.serverless.cli.loadedCommands
);
const errorMessage = [
`Serverless command "${commandName}" not found. Did you mean "${suggestedCommand}"?`,
' Run "serverless help" for a list of all available commands.',
].join('');
throw new this.serverless.classes.Error(errorMessage);
},
{ commands: this.commands }
);
}
getEvents(command) {
return _.flatMap(command.lifecycleEvents, event => [
`before:${command.key}:${event}`,
`${command.key}:${event}`,
`after:${command.key}:${event}`,
]);
}
getPlugins() {
return this.plugins;
}
getHooks(events) {
return _.flatMap([].concat(events), event => this.hooks[event] || []);
}
invoke(commandsArray, allowEntryPoints) {
const command = this.getCommand(commandsArray, allowEntryPoints);
this.convertShortcutsIntoOptions(command);
this.validateServerlessConfigDependency(command);
this.assignDefaultOptions(command);
this.validateOptions(command);
const events = this.getEvents(command);
const hooks = this.getHooks(events);
if (process.env.SLS_DEBUG) {
this.serverless.cli.log(`Invoke ${commandsArray.join(':')}`);
if (hooks.length === 0) {
const warningMessage = 'Warning: The command you entered did not catch on any hooks';
this.serverless.cli.log(warningMessage);
}
}
return BbPromise.reduce(hooks, (__, hook) => hook.hook(), null).catch(
TerminateHookChain,
() => {
if (process.env.SLS_DEBUG) {
this.serverless.cli.log(`Terminate ${commandsArray.join(':')}`);
}
return BbPromise.resolve();
}
);
}
/**
* Invokes the given command and starts the command's lifecycle.
* This method can be called by plugins directly to spawn a separate sub lifecycle.
*/
spawn(commandsArray, options) {
let commands = commandsArray;
if (typeof commandsArray === 'string') {
commands = commandsArray.split(':');
}
return this.invoke(commands, true).then(() => {
if (_.get(options, 'terminateLifecycleAfterExecution', false)) {
return BbPromise.reject(new TerminateHookChain(commands));
}
return BbPromise.resolve();
});
}
/**
* Called by the CLI to start a public command.
*/
run(commandsArray) {
// first initialize hooks
return this.getHooks(['initialize'])
.reduce((chain, { hook }) => chain.then(hook), BbPromise.resolve())
.then(() => this.invoke(commandsArray));
}
/**
* Check if the command is valid. Internally this function will only find
* CLI accessible commands (command.type !== 'entrypoint')
*/
validateCommand(commandsArray) {
this.getCommand(commandsArray);
}
/**
* If the command has no use when operated in a working directory with no serverless
* configuration file, throw an error
*/
validateServerlessConfigDependency(command) {
if ('configDependent' in command && command.configDependent) {
if (!this.serverlessConfigFile) {
const msg = [
'This command can only be run in a Serverless service directory. ',
"Make sure to reference a valid config file in the current working directory if you're using a custom config file",
].join('');
throw new this.serverless.classes.Error(msg);
}
}
}
validateOptions(command) {
if (command.options) {
Object.entries(command.options).forEach(([key, value]) => {
if (value.required && (this.cliOptions[key] === true || !this.cliOptions[key])) {
let requiredThings = `the --${key} option`;
if (value.shortcut) {
requiredThings += ` / -${value.shortcut} shortcut`;
}
let errorMessage = `This command requires ${requiredThings}.`;
if (value.usage) {
errorMessage = `${errorMessage} Usage: ${value.usage}`;
}
throw new this.serverless.classes.Error(errorMessage);
}
if (
_.isPlainObject(value.customValidation) &&
value.customValidation.regularExpression instanceof RegExp &&
typeof value.customValidation.errorMessage === 'string' &&
!value.customValidation.regularExpression.test(this.cliOptions[key])
) {
throw new this.serverless.classes.Error(value.customValidation.errorMessage);
}
});
}
}
updateAutocompleteCacheFile() {
const commands = _.clone(this.getCommands());
const cacheFile = {
commands: {},
validationHash: '',
};
Object.entries(commands).forEach(([commandName, commandObj]) => {
const command = commandObj;
if (!command.options) {
command.options = {};
}
if (!command.commands) {
command.commands = {};
}
cacheFile.commands[commandName] = Object.keys(command.options)
.map(option => `--${option}`)
.concat(Object.keys(command.commands));
});
const serverlessConfigFileHash = crypto
.createHash('sha256')
.update(JSON.stringify(this.serverlessConfigFile))
.digest('hex');
cacheFile.validationHash = serverlessConfigFileHash;
const cacheFilePath = getCacheFilePath(this.serverless.config.servicePath);
return writeFile(cacheFilePath, cacheFile);
}
convertShortcutsIntoOptions(command) {
if (command.options) {
Object.entries(command.options).forEach(([optionKey, optionObject]) => {
if (optionObject.shortcut && Object.keys(this.cliOptions).includes(optionObject.shortcut)) {
Object.keys(this.cliOptions).forEach(option => {
if (option === optionObject.shortcut) {
this.cliOptions[optionKey] = this.cliOptions[option];
}
});
}
});
}
}
assignDefaultOptions(command) {
if (command.options) {
Object.entries(command.options).forEach(([key, value]) => {
if (value.default != null && (!this.cliOptions[key] || this.cliOptions[key] === true)) {
this.cliOptions[key] = value.default;
}
});
}
}
asyncPluginInit() {
return BbPromise.all(this.plugins.map(plugin => plugin.asyncInit && plugin.asyncInit()));
}
}
module.exports = PluginManager;