diff --git a/README.md b/README.md index 35894cdc256..b6e957a7fcd 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,6 @@ In 2020, the Serverless Framework began introducing advanced functionality for s | [![serverless framework fullstack application](https://s3.amazonaws.com/assets.github.serverless/components/ad-components-fullstack.png)](https://github.com/serverless-components/fullstack-app) | [![serverless framework express.js](https://s3.amazonaws.com/public.assets.serverless.com/images/ads/ad-components-express.png)](https://github.com/serverless-components/express) | [![serverless framework website](https://s3.amazonaws.com/public.assets.serverless.com/images/ads/ad-components-website.png)](https://github.com/serverless-components/website) | [![serverless framework dynamodb](https://s3.amazonaws.com/public.assets.serverless.com/images/ads/ad-components-dynamodb.png)](https://github.com/serverless-components/aws-dynamodb) | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | - ## Contents diff --git a/docs/cn/providers/tencent/components/high-level-components/tencent-express.md b/docs/cn/providers/tencent/components/high-level-components/tencent-express.md index 5f6223f8036..7233b3bc357 100644 --- a/docs/cn/providers/tencent/components/high-level-components/tencent-express.md +++ b/docs/cn/providers/tencent/components/high-level-components/tencent-express.md @@ -57,7 +57,7 @@ $ npm i --save express # 安装express const express = require('express'); const app = express(); -app.get('/', function(req, res) { +app.get('/', function (req, res) { res.send('Hello Express'); }); diff --git a/docs/guides/sdk/nodejs.md b/docs/guides/sdk/nodejs.md index 57d236e314e..5e29d32d59d 100644 --- a/docs/guides/sdk/nodejs.md +++ b/docs/guides/sdk/nodejs.md @@ -45,7 +45,7 @@ And to import it instead, import with ```javascript const { captureError } = require('./serverless_sdk'); -module.exports.hello = async event => { +module.exports.hello = async (event) => { try { // do some real stuff but it throws an error, oh no! throw new Error('aa'); diff --git a/docs/providers/aws/events/apigateway.md b/docs/providers/aws/events/apigateway.md index 630317b83ce..6ca7fe0c701 100644 --- a/docs/providers/aws/events/apigateway.md +++ b/docs/providers/aws/events/apigateway.md @@ -105,7 +105,7 @@ functions: 'use strict'; -module.exports.hello = function(event, context, callback) { +module.exports.hello = function (event, context, callback) { console.log(event); // Contains incoming request data (e.g., query params, headers and more) const response = { @@ -351,7 +351,7 @@ If you want to use CORS with the lambda-proxy integration, remember to include t 'use strict'; -module.exports.hello = function(event, context, callback) { +module.exports.hello = function (event, context, callback) { const response = { statusCode: 200, headers: { diff --git a/docs/providers/aws/examples/hello-world/node/handler.js b/docs/providers/aws/examples/hello-world/node/handler.js index 6c0df82417b..12a311f420e 100644 --- a/docs/providers/aws/examples/hello-world/node/handler.js +++ b/docs/providers/aws/examples/hello-world/node/handler.js @@ -1,7 +1,7 @@ 'use strict'; // Your function handler -module.exports.helloWorldHandler = function(event, context, callback) { +module.exports.helloWorldHandler = function (event, context, callback) { const message = { message: 'Hello World', event, diff --git a/docs/providers/aws/guide/functions.md b/docs/providers/aws/guide/functions.md index d607ad8fb03..4f39980c116 100644 --- a/docs/providers/aws/guide/functions.md +++ b/docs/providers/aws/guide/functions.md @@ -50,7 +50,7 @@ The `handler` property points to the file and module containing the code you wan ```javascript // handler.js -module.exports.functionOne = function(event, context, callback) {}; +module.exports.functionOne = function (event, context, callback) {}; ``` You can add as many functions as you want within this property. diff --git a/docs/providers/aws/guide/testing.md b/docs/providers/aws/guide/testing.md index 35c79e54c40..e84d49a32d4 100644 --- a/docs/providers/aws/guide/testing.md +++ b/docs/providers/aws/guide/testing.md @@ -40,7 +40,7 @@ module.exports.saveUser = (event, context, callback) => { created_at: Date.now(), }; - db.saveUser(user, function(err) { + db.saveUser(user, function (err) { if (err) { callback(err); } else { @@ -73,7 +73,7 @@ class Users { created_at: Date.now(), }; - this.db.saveUser(user, function(err) { + this.db.saveUser(user, function (err) { if (err) { callback(err); } else { diff --git a/docs/providers/aws/guide/variables.md b/docs/providers/aws/guide/variables.md index 64504921f45..cdd65f36706 100644 --- a/docs/providers/aws/guide/variables.md +++ b/docs/providers/aws/guide/variables.md @@ -451,7 +451,7 @@ module.exports.rate = 'rate(10 minutes)'; ```js // config.js -module.exports = serverless => { +module.exports = (serverless) => { serverless.cli.consoleLog('You can access Serverless config and methods as well!'); return { diff --git a/docs/providers/azure/events/blobstorage.md b/docs/providers/azure/events/blobstorage.md index 661df424ab1..71e276af5b5 100644 --- a/docs/providers/azure/events/blobstorage.md +++ b/docs/providers/azure/events/blobstorage.md @@ -46,7 +46,7 @@ functions: 'use strict'; -module.exports.hello = function(context, item) { +module.exports.hello = function (context, item) { context.log('Received item: ${item}'); context.done(); }; diff --git a/docs/providers/azure/events/cosmosdb.md b/docs/providers/azure/events/cosmosdb.md index 10c484ed915..3100c277512 100644 --- a/docs/providers/azure/events/cosmosdb.md +++ b/docs/providers/azure/events/cosmosdb.md @@ -65,7 +65,7 @@ functions: 'use strict'; const uuidv4 = require('uuid/v4'); -module.exports.write = async function(context, req) { +module.exports.write = async function (context, req) { context.log('JavaScript HTTP trigger function processed a request.'); const input = req.body; diff --git a/docs/providers/azure/events/eventhubs.md b/docs/providers/azure/events/eventhubs.md index de203160d53..d6054fe38f5 100644 --- a/docs/providers/azure/events/eventhubs.md +++ b/docs/providers/azure/events/eventhubs.md @@ -46,7 +46,7 @@ functions: 'use strict'; -module.exports.hello = function(context, item) { +module.exports.hello = function (context, item) { context.log('Received item: ${item}'); context.done(); }; diff --git a/docs/providers/azure/events/http.md b/docs/providers/azure/events/http.md index a7edd438d0f..8f6319f9760 100644 --- a/docs/providers/azure/events/http.md +++ b/docs/providers/azure/events/http.md @@ -57,7 +57,7 @@ URL paths for the serverless functions are prefixed with "api" by default, e.g. 'use strict'; -module.exports.hello = function(context, req) { +module.exports.hello = function (context, req) { context.res = { body: 'Hello world!', }; @@ -78,7 +78,7 @@ In Node.js, the request object looks like an express request object. 'use strict'; -module.exports.hello = function(context, req) { +module.exports.hello = function (context, req) { const query = req.query; // dictionary of query strings const body = req.body; // Parsed body based on content-type const method = req.method; // HTTP Method (GET, POST, PUT, etc.) diff --git a/docs/providers/azure/events/queuestorage.md b/docs/providers/azure/events/queuestorage.md index 10e6ad731e2..c0ca93baa54 100644 --- a/docs/providers/azure/events/queuestorage.md +++ b/docs/providers/azure/events/queuestorage.md @@ -44,7 +44,7 @@ functions: 'use strict'; -module.exports.hello = function(context, item) { +module.exports.hello = function (context, item) { context.log('Received item: ${item}'); context.done(); }; diff --git a/docs/providers/azure/events/servicebus.md b/docs/providers/azure/events/servicebus.md index fb60ac85791..b826cb4401f 100644 --- a/docs/providers/azure/events/servicebus.md +++ b/docs/providers/azure/events/servicebus.md @@ -44,7 +44,7 @@ functions: 'use strict'; -module.exports.hello = function(context, item) { +module.exports.hello = function (context, item) { context.log('Received item: ${item}'); context.done(); }; @@ -76,7 +76,7 @@ functions: 'use strict'; -module.exports.hello = function(context, item) { +module.exports.hello = function (context, item) { context.log('Received item: ${item}'); context.done(); }; diff --git a/docs/providers/azure/events/timer.md b/docs/providers/azure/events/timer.md index 33f8d474fde..0dc0e31efa7 100644 --- a/docs/providers/azure/events/timer.md +++ b/docs/providers/azure/events/timer.md @@ -43,7 +43,7 @@ functions: 'use strict'; -module.exports.hello = function(context, timerObj) { +module.exports.hello = function (context, timerObj) { context.log('Timer ran'); context.done(); }; diff --git a/docs/providers/azure/guide/functions.md b/docs/providers/azure/guide/functions.md index 25bd4cb1be5..e5e2e836492 100644 --- a/docs/providers/azure/guide/functions.md +++ b/docs/providers/azure/guide/functions.md @@ -44,7 +44,7 @@ module containing the code you want to run in your function. ```javascript // handler.js -exports.handler = function(params) {}; +exports.handler = function (params) {}; ``` You can add as many functions as you want within this property. diff --git a/docs/providers/azure/guide/testing.md b/docs/providers/azure/guide/testing.md index 17d91206522..089cfd31773 100644 --- a/docs/providers/azure/guide/testing.md +++ b/docs/providers/azure/guide/testing.md @@ -41,7 +41,7 @@ module.exports.saveUser = (context, req) => { created_at: Date.now(), }; - db.saveUser(user, function(err) { + db.saveUser(user, function (err) { if (err) { reject(err); } else { @@ -77,7 +77,7 @@ class Users { created_at: Date.now(), }; - this.db.saveUser(user, function(err) { + this.db.saveUser(user, function (err) { if (err) { reject(err); } else { diff --git a/docs/providers/cloudflare/guide/debugging.md b/docs/providers/cloudflare/guide/debugging.md index 5c4406434e9..26e3deb437c 100644 --- a/docs/providers/cloudflare/guide/debugging.md +++ b/docs/providers/cloudflare/guide/debugging.md @@ -19,7 +19,7 @@ How can we debug errors in our Cloudflare Workers functions? Let's imagine that we have deployed the following code as a Cloudflare Worker function using Serverless: ```javascript -addEventListener('fetch', event => { +addEventListener('fetch', (event) => { event.respondWith(handleRequest(event.request)); }); async function handleRequest(request) { diff --git a/docs/providers/cloudflare/guide/functions.md b/docs/providers/cloudflare/guide/functions.md index b9fc1eea3dc..b8343f922ce 100644 --- a/docs/providers/cloudflare/guide/functions.md +++ b/docs/providers/cloudflare/guide/functions.md @@ -55,7 +55,7 @@ The `script` property points to the file containing your Cloudflare Worker. ```javascript // helloWorld.js -addEventListener('fetch', event => { +addEventListener('fetch', (event) => { event.respondWith(handleRequest(event.request)); }); diff --git a/docs/providers/fn/guide/debugging.md b/docs/providers/fn/guide/debugging.md index 09cd4c46a1a..d914c71111d 100644 --- a/docs/providers/fn/guide/debugging.md +++ b/docs/providers/fn/guide/debugging.md @@ -21,7 +21,7 @@ Let's imagine that we have deployed the following Nodejs code as a Fn function u ```javascript const fdk = require('@fnproject/fdk'); -fdk.handle(input => { +fdk.handle((input) => { input = JSON.parse(input); let name = 'World'; if (input.name) { diff --git a/docs/providers/openwhisk/events/apigateway.md b/docs/providers/openwhisk/events/apigateway.md index 916f34b4b4e..cda39a6b05c 100644 --- a/docs/providers/openwhisk/events/apigateway.md +++ b/docs/providers/openwhisk/events/apigateway.md @@ -46,7 +46,7 @@ URL paths for the serverless functions are prefixed with the function name, e.g. 'use strict'; -module.exports.hello = function(params) { +module.exports.hello = function (params) { // Your function handler return { payload: 'Hello world!' }; }; @@ -86,7 +86,7 @@ functions: 'use strict'; -module.exports.handler = function(params) { +module.exports.handler = function (params) { const name = params.name || 'stranger'; // Your function handler return { payload: `Hello ${name}!` }; diff --git a/docs/providers/openwhisk/examples/hello-world/node/handler.js b/docs/providers/openwhisk/examples/hello-world/node/handler.js index 0687ec854d5..98edcb3eacf 100644 --- a/docs/providers/openwhisk/examples/hello-world/node/handler.js +++ b/docs/providers/openwhisk/examples/hello-world/node/handler.js @@ -1,7 +1,7 @@ 'use strict'; // Your function handler -module.exports.helloWorldHandler = function(params) { +module.exports.helloWorldHandler = function (params) { const name = params.name || 'World'; return { payload: `Hello, ${name}!` }; }; diff --git a/docs/providers/openwhisk/guide/functions.md b/docs/providers/openwhisk/guide/functions.md index 8c38f3595c8..450149485d3 100644 --- a/docs/providers/openwhisk/guide/functions.md +++ b/docs/providers/openwhisk/guide/functions.md @@ -45,7 +45,7 @@ The `handler` property points to the file and module containing the code you wan ```javascript // handler.js -exports.handler = function(params) {}; +exports.handler = function (params) {}; ``` You can add as many functions as you want within this property. diff --git a/docs/providers/openwhisk/guide/testing.md b/docs/providers/openwhisk/guide/testing.md index 8a676456c4b..6df1b4940f8 100644 --- a/docs/providers/openwhisk/guide/testing.md +++ b/docs/providers/openwhisk/guide/testing.md @@ -34,14 +34,14 @@ Here is an example in Node.js of how to follow the practices above. The job this const db = require('db').connect(); const mailer = require('mailer'); -module.exports.saveUser = params => { +module.exports.saveUser = (params) => { return Promise((resolve, reject) => { const user = { email: params.email, created_at: Date.now(), }; - db.saveUser(user, function(err) { + db.saveUser(user, function (err) { if (err) { reject(err); } else { @@ -76,7 +76,7 @@ class Users { created_at: Date.now(), }; - this.db.saveUser(user, function(err) { + this.db.saveUser(user, function (err) { if (err) { reject(err); } else { @@ -98,7 +98,7 @@ const Users = require('users'); let users = new Users(db, mailer); -module.exports.saveUser = params => { +module.exports.saveUser = (params) => { return users.save(params.email); }; ``` diff --git a/lib/classes/CLI.js b/lib/classes/CLI.js index f2222d4c8f0..f75f3193947 100644 --- a/lib/classes/CLI.js +++ b/lib/classes/CLI.js @@ -62,7 +62,7 @@ class CLI { // Make "log" no-op to suppress warnings. // But preserve "consoleLog" which "print" command use to print config. - this.log = function() {}; + this.log = function () {}; } isHelpRequest(processedInput) { @@ -233,31 +233,31 @@ class CLI { this.consoleLog(''); const internalCommands = Object.values(this.loadedCommands).filter( - command => command && !command.isExternal + (command) => command && !command.isExternal ); const sortedInternalCommands = internalCommands.sort((command1, command2) => command1.key.localeCompare(command2.key) ); - sortedInternalCommands.forEach(command => { + sortedInternalCommands.forEach((command) => { this.displayCommandUsage(command, command.key); }); this.consoleLog(''); const externalPlugins = this.loadedPlugins - .filter(plugin => this.serverless.pluginManager.externalPlugins.has(plugin)) + .filter((plugin) => this.serverless.pluginManager.externalPlugins.has(plugin)) .sort((plugin1, plugin2) => plugin1.constructor.name.localeCompare(plugin2.constructor.name)); if (externalPlugins.length) { // print all the installed plugins this.consoleLog(chalk.yellow.underline('Plugins')); - this.consoleLog(externalPlugins.map(plugin => plugin.constructor.name).join(', ')); + this.consoleLog(externalPlugins.map((plugin) => plugin.constructor.name).join(', ')); let pluginCommands = {}; // add commands to pluginCommands based on command's plugin - const addToPluginCommands = cmd => { + const addToPluginCommands = (cmd) => { const pcmd = _.clone(cmd); // remove subcommand from clone @@ -273,24 +273,21 @@ class CLI { // check for subcommands if ('commands' in cmd) { - Object.values(cmd.commands).forEach(d => { + Object.values(cmd.commands).forEach((d) => { addToPluginCommands(d); }); } }; // fill up pluginCommands with commands in loadedCommands - Object.values(this.loadedCommands).forEach(details => { + Object.values(this.loadedCommands).forEach((details) => { if (details.isExternal) { addToPluginCommands(details); } }); // sort plugins alphabetically - pluginCommands = _(Object.entries(pluginCommands)) - .sortBy(0) - .fromPairs() - .value(); + pluginCommands = _(Object.entries(pluginCommands)).sortBy(0).fromPairs().value(); if (!_.isEmpty(pluginCommands)) { this.consoleLog(''); @@ -299,7 +296,7 @@ class CLI { Object.entries(pluginCommands).forEach(([plugin, details]) => { this.consoleLog(plugin); - details.forEach(cmd => { + details.forEach((cmd) => { // display command usage with single(1) indent this.displayCommandUsage(cmd, cmd.key.split(':').join(' '), 1); }); @@ -317,8 +314,9 @@ class CLI { functionalities related to given service or current environment.` ) ); - const command = this.loadedPlugins.find(plugin => plugin.constructor.name === 'InteractiveCli') - .commands.interactiveCli; + const command = this.loadedPlugins.find( + (plugin) => plugin.constructor.name === 'InteractiveCli' + ).commands.interactiveCli; this.displayCommandOptions(command); } diff --git a/lib/classes/ConfigSchemaHandler/index.js b/lib/classes/ConfigSchemaHandler/index.js index d9f7708de67..a191e0b6580 100644 --- a/lib/classes/ConfigSchemaHandler/index.js +++ b/lib/classes/ConfigSchemaHandler/index.js @@ -25,7 +25,7 @@ const normalizeSchemaObject = (object, instanceSchema) => { // Normalizer is introduced to workaround https://github.com/ajv-validator/ajv/issues/1287 // normalizedObjectsMap allows to handle circular structures without issues -const normalizeUserConfig = userConfig => { +const normalizeUserConfig = (userConfig) => { const normalizedObjectsSet = new WeakSet(); const removedValuesMap = []; const normalizeObject = (object, path) => { @@ -108,7 +108,7 @@ class ConfigSchemaHandler { validate(userConfig); denormalizeUserConfig(userConfig, denormalizeOptions); if (validate.errors && this.serverless.service.configValidationMode !== 'off') { - const messages = normalizeAjvErrors(validate.errors).map(err => err.message); + const messages = normalizeAjvErrors(validate.errors).map((err) => err.message); this.handleErrorMessages(messages); } } @@ -245,7 +245,7 @@ class ConfigSchemaHandler { const existingFunctionEvents = new Set( this.schema.properties.functions.patternProperties[ FUNCTION_NAME_PATTERN - ].properties.events.items.anyOf.map(functionEventSchema => + ].properties.events.items.anyOf.map((functionEventSchema) => Object.keys(functionEventSchema.properties).pop() ) ); @@ -274,7 +274,7 @@ class ConfigSchemaHandler { const existingEventDefinition = this.schema.properties.functions.patternProperties[ FUNCTION_NAME_PATTERN - ].properties.events.items.anyOf.find(eventDefinition => name === eventDefinition.required[0]); + ].properties.events.items.anyOf.find((eventDefinition) => name === eventDefinition.required[0]); if (!existingEventDefinition) { throw new this.serverless.classes.Error( @@ -290,7 +290,7 @@ class ConfigSchemaHandler { } else if (existingEventDefinition.properties[name].anyOf) { // Event root definition has multiple definitions. Finding the object definition definitionToUpdate = existingEventDefinition.properties[name].anyOf.find( - definition => definition.type === 'object' + (definition) => definition.type === 'object' ); } @@ -370,7 +370,7 @@ class PropertyCollisionError extends Error { function addPropertiesToSchema(subSchema, extension = { properties: {}, required: [] }) { let collidingExtensionPropertyKey; const existingSubSchemaPropertiesKeys = new Set(Object.keys(subSchema.properties)); - Object.keys(extension.properties).some(extensionPropertiesKey => { + Object.keys(extension.properties).some((extensionPropertiesKey) => { const isColliding = existingSubSchemaPropertiesKeys.has(extensionPropertiesKey); if (isColliding) collidingExtensionPropertyKey = extensionPropertiesKey; return isColliding; diff --git a/lib/classes/ConfigSchemaHandler/normalizeAjvErrors.js b/lib/classes/ConfigSchemaHandler/normalizeAjvErrors.js index a5bcbe96dc7..48e30cf6633 100644 --- a/lib/classes/ConfigSchemaHandler/normalizeAjvErrors.js +++ b/lib/classes/ConfigSchemaHandler/normalizeAjvErrors.js @@ -9,7 +9,7 @@ const isAnyOfPathTypePostfix = RegExp.prototype.test.bind(/^\/\d+\/type$/); const dataPathPropertyBracketsPattern = /\['([a-zA-Z_0-9]+)'\]/g; const oneOfKeywords = new Set(['anyOf', 'oneOf']); -const filterIrreleventEventConfigurationErrors = resultErrorsSet => { +const filterIrreleventEventConfigurationErrors = (resultErrorsSet) => { // 1. Resolve all errors at event type configuration level const eventTypeErrors = Array.from(resultErrorsSet).filter(({ dataPath }) => isEventTypeDataPath(dataPath) @@ -43,7 +43,7 @@ const filterIrreleventEventConfigurationErrors = resultErrorsSet => { // 3.4 If there are no event type configuration errors for intended event type if ( !Array.from(resultErrorsSet).some( - error => error.dataPath.startsWith(dataPath) && error.dataPath !== dataPath + (error) => error.dataPath.startsWith(dataPath) && error.dataPath !== dataPath ) ) { // 3.4.1 If there are no event configuration errors, it means it's not supported event type: @@ -79,7 +79,7 @@ const filterIrreleventEventConfigurationErrors = resultErrorsSet => { } }; -const filterIrrelevantAnyOfErrors = resultErrorsSet => { +const filterIrrelevantAnyOfErrors = (resultErrorsSet) => { // 1. Group errors by anyOf/oneOf schema path const oneOfErrorsByPath = {}; for (const error of resultErrorsSet) { @@ -114,7 +114,7 @@ const filterIrrelevantAnyOfErrors = resultErrorsSet => { } return currentDataPath; }) - ).forEach(dataPathOneOfPathErrors => { + ).forEach((dataPathOneOfPathErrors) => { // 2.2.1.If just one error, set was already filtered by event configuration errors filter if (dataPathOneOfPathErrors.length === 1) return; // 2.2.2 Group by anyOf variant @@ -139,7 +139,7 @@ const filterIrrelevantAnyOfErrors = resultErrorsSet => { // 2.2.5 If errors reported for more than one variant // 2.2.5.1 Filter variants where value type was not met dataPathOneOfPathVariants = dataPathOneOfPathVariants.filter( - dataPathOneOfPathVariantErrors => { + (dataPathOneOfPathVariantErrors) => { if (dataPathOneOfPathVariantErrors.length !== 1) return true; if (dataPathOneOfPathVariantErrors[0].keyword !== 'type') return true; if ( @@ -168,7 +168,7 @@ const filterIrrelevantAnyOfErrors = resultErrorsSet => { } dataPathOneOfPathVariants = dataPathOneOfPathVariants.filter( - dataPathAnyOfPathVariantErrors => { + (dataPathAnyOfPathVariantErrors) => { if (dataPathAnyOfPathVariantErrors.deepestDataPathSize === deepestDataPathSize) { return true; } @@ -198,14 +198,14 @@ const filterIrrelevantAnyOfErrors = resultErrorsSet => { } }; -const normalizeDataPath = dataPath => { +const normalizeDataPath = (dataPath) => { if (!dataPath) return 'root'; // This regex helps replace functions['someFunc'].foo with functions.someFunc.foo return `'${dataPath.slice(1).replace(dataPathPropertyBracketsPattern, '.$1')}'`; }; -const improveMessages = resultErrorsSet => { +const improveMessages = (resultErrorsSet) => { for (const error of resultErrorsSet) { switch (error.keyword) { case 'additionalProperties': @@ -228,7 +228,7 @@ const improveMessages = resultErrorsSet => { error.message = 'unsupported configuration format'; break; case 'enum': - if (error.params.allowedValues.every(value => typeof value === 'string')) { + if (error.params.allowedValues.every((value) => typeof value === 'string')) { error.message += ` [${error.params.allowedValues.join(', ')}]`; } break; @@ -241,7 +241,7 @@ const improveMessages = resultErrorsSet => { /* * For error object structure, see https://github.com/ajv-validator/ajv/#error-objects */ -module.exports = ajvErrors => { +module.exports = (ajvErrors) => { const resultErrorsSet = new Set(ajvErrors); // 1. Filter eventual irrelevant errors for faulty event type configurations diff --git a/lib/classes/ConfigSchemaHandler/resolveDataPathSize.js b/lib/classes/ConfigSchemaHandler/resolveDataPathSize.js index d7275490d6e..beeccbc0e95 100644 --- a/lib/classes/ConfigSchemaHandler/resolveDataPathSize.js +++ b/lib/classes/ConfigSchemaHandler/resolveDataPathSize.js @@ -3,7 +3,7 @@ const memoizee = require('memoizee'); module.exports = memoizee( - dataPath => { + (dataPath) => { let index; let size = 0; let mode = 'literal'; diff --git a/lib/classes/Error.js b/lib/classes/Error.js index 924d5f7a84c..58be18fecb0 100644 --- a/lib/classes/Error.js +++ b/lib/classes/Error.js @@ -8,11 +8,11 @@ const isStandaloneExecutable = require('../utils/isStandaloneExecutable'); const sfeVersion = require('@serverless/enterprise-plugin/package.json').version; const { sdkVersion } = require('@serverless/enterprise-plugin'); -const consoleLog = message => { +const consoleLog = (message) => { console.log(message); // eslint-disable-line no-console }; -const resolveExceptionMeta = exception => { +const resolveExceptionMeta = (exception) => { if (isError(exception)) { return { name: exception.name, @@ -131,7 +131,7 @@ module.exports.logError = (exception, { forceExit = false, serverless } = {}) => possiblyExit(); }; -module.exports.logWarning = message => { +module.exports.logWarning = (message) => { if (process.env.SLS_WARNING_DISABLE) { return; } @@ -139,6 +139,6 @@ module.exports.logWarning = message => { writeMessage('Serverless Warning', message); }; -module.exports.logInfo = message => { +module.exports.logInfo = (message) => { writeMessage('Serverless Information', message); }; diff --git a/lib/classes/PluginManager.js b/lib/classes/PluginManager.js index 84a95fd2efd..a1880ab7fd3 100644 --- a/lib/classes/PluginManager.js +++ b/lib/classes/PluginManager.js @@ -69,11 +69,11 @@ class PluginManager { loadConfigFile() { return serverlessConfigFileUtils.getServerlessConfigFile(this.serverless).then( - serverlessConfigFile => { + (serverlessConfigFile) => { this.serverlessConfigFile = serverlessConfigFile; return; }, - error => { + (error) => { if (this.serverless.cli.isHelpRequest(this.serverless.processedInput)) { this.serverless.config.servicePath = null; return null; @@ -114,7 +114,7 @@ class PluginManager { } // don't load plugins twice - if (this.plugins.some(plugin => plugin instanceof Plugin)) { + if (this.plugins.some((plugin) => plugin instanceof Plugin)) { this.serverless.cli.log(`WARNING: duplicate plugin ${Plugin.name} was not loaded\n`); return; } @@ -131,11 +131,11 @@ class PluginManager { require('../plugins') .filter(Boolean) - .forEach(Plugin => this.addPlugin(Plugin)); + .forEach((Plugin) => this.addPlugin(Plugin)); this.resolveServicePlugins(servicePlugins) .filter(Boolean) - .forEach(Plugin => this.addPlugin(Plugin, { isExternal: true })); + .forEach((Plugin) => this.addPlugin(Plugin, { isExternal: true })); if (EnterprisePlugin) this.addPlugin(EnterprisePlugin); @@ -146,8 +146,8 @@ class PluginManager { const pluginsObject = this.parsePluginsObject(servicePlugs); const servicePath = this.serverless.config.servicePath; return pluginsObject.modules - .filter(name => name !== '@serverless/enterprise-plugin') - .map(name => { + .filter((name) => name !== '@serverless/enterprise-plugin') + .map((name) => { let Plugin; try { Plugin = requireServicePlugin(servicePath, name, pluginsObject.localPath); @@ -180,10 +180,7 @@ class PluginManager { resolveEnterprisePlugin() { if (config.getGlobalConfig().enterpriseDisabled) return null; - this.pluginIndependentCommands - .add('login') - .add('logout') - .add('dashboard'); + this.pluginIndependentCommands.add('login').add('logout').add('dashboard'); return require('@serverless/enterprise-plugin'); } @@ -259,7 +256,7 @@ class PluginManager { this.loadCommand(pluginName, subDetails, `${key}:${subKey}`, commandIsEntryPoint) ); // Handle command aliases - (details.aliases || []).forEach(alias => { + (details.aliases || []).forEach((alias) => { if (process.env.SLS_DEBUG) { this.serverless.cli.log(` -> @${alias}`); } @@ -274,7 +271,7 @@ class PluginManager { 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 => { + command.lifecycleEvents = (command.lifecycleEvents || []).map((event) => { if (event.startsWith('deprecated#')) { // Extract event and optional redirect const transformedEvent = /^deprecated#(.*?)(?:->(.*?))?$/.exec(event); @@ -379,7 +376,7 @@ class PluginManager { _.set(target, name, _.omit(command, 'commands')); if ( Object.values(command.commands).some( - childCommand => childCommand.type !== 'entrypoint' + (childCommand) => childCommand.type !== 'entrypoint' ) ) { target[name].commands = {}; @@ -484,7 +481,7 @@ class PluginManager { } getEvents(command) { - return _.flatMap(command.lifecycleEvents, event => [ + return _.flatMap(command.lifecycleEvents, (event) => [ `before:${command.key}:${event}`, `${command.key}:${event}`, `after:${command.key}:${event}`, @@ -496,7 +493,7 @@ class PluginManager { } getHooks(events) { - return _.flatMap([].concat(events), event => this.hooks[event] || []); + return _.flatMap([].concat(events), (event) => this.hooks[event] || []); } invoke(commandsArray, allowEntryPoints) { @@ -626,7 +623,7 @@ class PluginManager { command.commands = {}; } cacheFile.commands[commandName] = Object.keys(command.options) - .map(option => `--${option}`) + .map((option) => `--${option}`) .concat(Object.keys(command.commands)); }); @@ -644,7 +641,7 @@ class PluginManager { 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 => { + Object.keys(this.cliOptions).forEach((option) => { if (option === optionObject.shortcut) { this.cliOptions[optionKey] = this.cliOptions[option]; } @@ -665,7 +662,7 @@ class PluginManager { } asyncPluginInit() { - return BbPromise.all(this.plugins.map(plugin => plugin.asyncInit && plugin.asyncInit())); + return BbPromise.all(this.plugins.map((plugin) => plugin.asyncInit && plugin.asyncInit())); } } diff --git a/lib/classes/PromiseTracker.js b/lib/classes/PromiseTracker.js index d379d746995..1e15942d7b3 100644 --- a/lib/classes/PromiseTracker.js +++ b/lib/classes/PromiseTracker.js @@ -31,7 +31,7 @@ class PromiseTracker { `# ${delta}: ${this.getSettled().length} of ${this.getAll().length} promises have settled`, `# ${delta}: ${pending.length} are taking longer than expected:`, ] - .concat(pending.map(promise => `# ${delta}: ${promise.waitList}`)) + .concat(pending.map((promise) => `# ${delta}: ${promise.waitList}`)) .concat([ '# This can result from latent connections but may represent a cyclic variable dependency', '##########################################################################################', @@ -83,16 +83,16 @@ class PromiseTracker { return promise; } getPending() { - return this.promiseList.filter(p => p.state === constants.pending); + return this.promiseList.filter((p) => p.state === constants.pending); } getSettled() { - return this.promiseList.filter(p => p.state !== constants.pending); + return this.promiseList.filter((p) => p.state !== constants.pending); } getResolved() { - return this.promiseList.filter(p => p.state === constants.resolved); + return this.promiseList.filter((p) => p.state === constants.resolved); } getRejected() { - return this.promiseList.filter(p => p.state === constants.rejected); + return this.promiseList.filter((p) => p.state === constants.rejected); } getAll() { return this.promiseList; diff --git a/lib/classes/Service.js b/lib/classes/Service.js index 5a1f1ee7b5f..067cf98ec3b 100644 --- a/lib/classes/Service.js +++ b/lib/classes/Service.js @@ -50,8 +50,8 @@ class Service { serverlessConfigFileUtils.getServerlessConfigFilePath(this.serverless), serverlessConfigFileUtils.getServerlessConfigFile(this.serverless), ]) - .then(args => this.loadServiceFileParam(...args)) - .catch(error => { + .then((args) => this.loadServiceFileParam(...args)) + .catch((error) => { if (this.serverless.cli.isHelpRequest(this.serverless.processedInput)) { return null; } @@ -195,7 +195,7 @@ class Service { } mergeArrays() { - ['resources', 'functions'].forEach(key => { + ['resources', 'functions'].forEach((key) => { if (Array.isArray(this[key])) { this[key] = this[key].reduce((memo, value) => { if (value) { @@ -245,7 +245,7 @@ class Service { } getAllFunctionsNames() { - return this.getAllFunctions().map(func => this.getFunction(func).name); + return this.getAllFunctions().map((func) => this.getFunction(func).name); } getFunction(functionName) { @@ -263,7 +263,9 @@ class Service { } getEventInFunction(eventName, functionName) { - const event = this.getFunction(functionName).events.find(e => Object.keys(e)[0] === eventName); + const event = this.getFunction(functionName).events.find( + (e) => Object.keys(e)[0] === eventName + ); if (event) { return event; } diff --git a/lib/classes/Utils.js b/lib/classes/Utils.js index f6685ad13c5..447d3ebaac3 100644 --- a/lib/classes/Utils.js +++ b/lib/classes/Utils.js @@ -93,9 +93,7 @@ class Utils { } generateShortId(length) { - return Math.random() - .toString(36) - .substr(2, length); + return Math.random().toString(36).substr(2, length); } findServicePath(customPath) { @@ -137,7 +135,7 @@ class Utils { return Object.keys(functions).reduce((accum, key) => { const events = functions[key].events || []; if (events.length) { - events.forEach(event => { + events.forEach((event) => { if (Object.keys(event)[0] === eventName) { accum = true; // eslint-disable-line no-param-reassign } diff --git a/lib/classes/Variables.js b/lib/classes/Variables.js index 930f86bd1d2..b3d33178bcf 100644 --- a/lib/classes/Variables.js +++ b/lib/classes/Variables.js @@ -129,7 +129,7 @@ class Variables { // save original resolver.original = resolver.resolver; // knock out - resolver.resolver = variableString => + resolver.resolver = (variableString) => BbPromise.reject(dependencyMessage(variableString, resolver.serviceName)); } } @@ -175,9 +175,9 @@ class Variables { }, ]; return this.disableDepedentServices(() => { - const prepopulations = requiredConfigs.map(config => + const prepopulations = requiredConfigs.map((config) => this.populateValue(config.value, true) // populate - .then(populated => Object.assign(config, { populated })) + .then((populated) => Object.assign(config, { populated })) ); return this.assignProperties(provider, prepopulations); }); @@ -287,10 +287,10 @@ class Variables { */ populateVariables(properties) { const variables = properties.filter( - property => typeof property.value === 'string' && property.value.match(this.variableSyntax) + (property) => typeof property.value === 'string' && property.value.match(this.variableSyntax) ); - return variables.map(variable => - this.populateValue(variable.value, false).then(populated => + return variables.map((variable) => + this.populateValue(variable.value, false).then((populated) => Object.assign({}, variable, { populated }) ) ); @@ -304,8 +304,8 @@ class Variables { */ assignProperties(target, populations) { // eslint-disable-line class-methods-use-this - return BbPromise.all(populations).then(results => - results.forEach(result => { + return BbPromise.all(populations).then((results) => + results.forEach((result) => { if (result.value !== result.populated) { _.set(target, result.path, result.populated); } @@ -365,7 +365,7 @@ class Variables { if (!matches || !matches.length) { return property; } - return matches.map(match => ({ + return matches.map((match) => ({ match, variable: this.cleanVariable(match), })); @@ -377,7 +377,7 @@ class Variables { * @returns {Promise[]} Promises for the eventual populated values of the given matches */ populateMatches(matches, property) { - return matches.map(match => this.splitAndGet(match, property)); + return matches.map((match) => this.splitAndGet(match, property)); } /** * Render the given matches and their associated results to the given value @@ -410,8 +410,8 @@ class Variables { } const populations = this.populateMatches(matches, valueToPopulate); return BbPromise.all(populations) - .then(results => this.renderMatches(property, matches, results)) - .then(result => { + .then((results) => this.renderMatches(property, matches, results)) + .then((result) => { if (root && matches.length) { return this.populateValue(result, root); } @@ -513,7 +513,7 @@ class Variables { } let prior = 0; const results = []; - commaReplacements.forEach(replacement => { + commaReplacements.forEach((replacement) => { results.push(input.slice(prior, replacement.start)); prior = replacement.end; }); @@ -531,18 +531,18 @@ class Variables { overwrite(variableStrings, variableMatch, propertyString) { // A sentinel to rid rejected Promises, so any of resolved value can be used as fallback. const FAIL_TOKEN = {}; - const variableValues = variableStrings.map(variableString => + const variableValues = variableStrings.map((variableString) => this.getValueFromSource(variableString, propertyString).catch(() => FAIL_TOKEN) ); // eslint-disable-line no-unused-vars - const validValue = value => + const validValue = (value) => value !== null && typeof value !== 'undefined' && (Array.isArray(value) || !(typeof value === 'object' && !Object.keys(value).length)); return BbPromise.all(variableValues) - .then(values => values.filter(v => v !== FAIL_TOKEN)) - .then(values => { + .then((values) => values.filter((v) => v !== FAIL_TOKEN)) + .then((values) => { let deepPropertyString = variableMatch; let deepProperties = 0; values.forEach((value, index) => { @@ -586,7 +586,7 @@ class Variables { } ret = this.tracker.add(variableString, ret, propertyString); } - return ret.then(resolvedValue => { + return ret.then((resolvedValue) => { if (!Array.isArray(resolvedValue) && !_.isPlainObject(resolvedValue)) return resolvedValue; if (resolvedValuesWeak.has(resolvedValue)) { try { @@ -668,7 +668,7 @@ class Variables { const deepProperties = variable .split(':')[1] .split('.') - .filter(property => property); + .filter((property) => property); return this.getDeeperValue(deepProperties, valueToPopulate); } @@ -716,12 +716,12 @@ class Variables { valueToPopulate = returnValue; } - return BbPromise.resolve(valueToPopulate).then(valueToPopulateResolved => { + return BbPromise.resolve(valueToPopulate).then((valueToPopulateResolved) => { let deepProperties = variableString.replace(matchedFileRefString, ''); deepProperties = deepProperties.slice(1).split('.'); deepProperties.splice(0, 1); return this.getDeeperValue(deepProperties, valueToPopulateResolved).then( - deepValueToPopulateResolved => { + (deepValueToPopulateResolved) => { if (unsupportedJsTypes.has(typeof deepValueToPopulateResolved)) { const errorMessage = [ 'Invalid variable syntax when referencing', @@ -777,9 +777,9 @@ class Variables { { StackName: stackName }, this.buildOptions(regionSuffix) ) - .then(result => { + .then((result) => { const outputs = result.Stacks[0].Outputs; - const output = outputs.find(x => x.OutputKey === outputLogicalId); + const output = outputs.find((x) => x.OutputKey === outputLogicalId); if (!output) { const errorMessage = [ @@ -808,8 +808,8 @@ class Variables { }, { useCache: true } ) // Use request cache - .then(response => BbPromise.resolve(response.Body.toString())) - .catch(err => { + .then((response) => BbPromise.resolve(response.Body.toString())) + .catch((err) => { const errorMessage = `Error getting value for ${variableString}. ${err.message}`; return BbPromise.reject(new this.serverless.classes.Error(errorMessage)); }); @@ -833,7 +833,7 @@ class Variables { this.buildOptions(regionSuffix) ) // Use request cache .then( - response => { + (response) => { const plainText = response.Parameter.Value; const type = response.Parameter.Type; // Only if Secrets Manager. Parameter Store does not support JSON. @@ -854,7 +854,7 @@ class Variables { } return plainText; }, - err => { + (err) => { if (!err.providerError || err.providerError.statusCode !== 400) { throw new this.serverless.classes.Error(err.message); } @@ -898,7 +898,7 @@ class Variables { let ret = this.populateValue(variable); if (deepRef.length) { // if there is a deep reference remaining - ret = ret.then(result => { + ret = ret.then((result) => { if (typeof result === 'string' && result.match(this.variableSyntax)) { const deepVariable = this.makeDeepVariable(result); return BbPromise.resolve(this.appendDeepVariable(deepVariable, deepRef)); @@ -910,7 +910,7 @@ class Variables { } makeDeepVariable(variable) { - let index = this.deep.findIndex(item => variable === item); + let index = this.deep.findIndex((item) => variable === item); if (index < 0) { index = this.deep.push(variable) - 1; } diff --git a/lib/classes/YamlParser.js b/lib/classes/YamlParser.js index 714eae3513c..1578a095469 100644 --- a/lib/classes/YamlParser.js +++ b/lib/classes/YamlParser.js @@ -19,7 +19,7 @@ class YamlParser { }, location: yamlFilePath, }; - return resolve(root, options).then(res => res.resolved); + return resolve(root, options).then((res) => res.resolved); } } diff --git a/lib/loadEnv.js b/lib/loadEnv.js index 40113204414..5ec4f2a0ee8 100644 --- a/lib/loadEnv.js +++ b/lib/loadEnv.js @@ -4,14 +4,14 @@ const dotenv = require('dotenv'); const path = require('path'); const ServerlessError = require('./classes/Error').ServerlessError; -const isMissingFileError = error => error.code === 'ENOENT'; +const isMissingFileError = (error) => error.code === 'ENOENT'; const throwDotenvError = (error, filePath) => { const errorMessage = `Failed to load environment variables from "${filePath}": ${error}`; throw new ServerlessError(errorMessage); }; -module.exports = async stage => { +module.exports = async (stage) => { const defaultEnvFilePath = path.join(process.cwd(), '.env'); const stageEnvFilePath = path.join(process.cwd(), `.env.${stage}`); diff --git a/lib/plugins/aws/customResources/generateZip.js b/lib/plugins/aws/customResources/generateZip.js index 08b7637d89d..d8181566a83 100644 --- a/lib/plugins/aws/customResources/generateZip.js +++ b/lib/plugins/aws/customResources/generateZip.js @@ -11,7 +11,7 @@ const srcDirPath = path.join(__dirname, 'resources'); const artifactName = 'custom-resources.zip'; -const ensureCustomResourcesArtifact = getEnsureArtifact(artifactName, cachePath => +const ensureCustomResourcesArtifact = getEnsureArtifact(artifactName, (cachePath) => BbPromise.try(() => { const tmpDirPath = getTmpDirPath(); const tmpInstalledLambdaPath = path.resolve(tmpDirPath, 'resource-lambda'); @@ -25,4 +25,4 @@ const ensureCustomResourcesArtifact = getEnsureArtifact(artifactName, cachePath ); module.exports = () => - ensureCustomResourcesArtifact().then(cachePath => path.resolve(cachePath, artifactName)); + ensureCustomResourcesArtifact().then((cachePath) => path.resolve(cachePath, artifactName)); diff --git a/lib/plugins/aws/customResources/index.js b/lib/plugins/aws/customResources/index.js index 1cf321bedfa..ccdc46ba30f 100644 --- a/lib/plugins/aws/customResources/index.js +++ b/lib/plugins/aws/customResources/index.js @@ -7,7 +7,7 @@ const BbPromise = require('bluebird'); const fse = require('fs-extra'); const generateZip = require('./generateZip'); -const prepareCustomResourcePackage = _.memoize(zipFilePath => +const prepareCustomResourcePackage = _.memoize((zipFilePath) => BbPromise.all([generateZip(), fse.mkdirs(path.dirname(zipFilePath))]) .then(([cachedZipFilePath]) => fse.copy(cachedZipFilePath, zipFilePath)) .then(() => path.basename(zipFilePath)) @@ -150,8 +150,8 @@ async function addCustomResourceToService(awsProvider, resourceName, iamRoleStat } } const { Statement } = customResourceRole.Properties.Policies[0].PolicyDocument; - iamRoleStatements.forEach(newStmt => { - if (!Statement.find(existingStmt => existingStmt.Resource === newStmt.Resource)) { + iamRoleStatements.forEach((newStmt) => { + if (!Statement.find((existingStmt) => existingStmt.Resource === newStmt.Resource)) { Statement.push(newStmt); } }); diff --git a/lib/plugins/aws/customResources/resources/apiGatewayCloudWatchRole/handler.js b/lib/plugins/aws/customResources/resources/apiGatewayCloudWatchRole/handler.js index eb33c4318a4..da6986674c3 100644 --- a/lib/plugins/aws/customResources/resources/apiGatewayCloudWatchRole/handler.js +++ b/lib/plugins/aws/customResources/resources/apiGatewayCloudWatchRole/handler.js @@ -62,7 +62,9 @@ async function create(event, context) { })(); if ( - !attachedPolicies.some(policy => policy.PolicyArn === apiGatewayPushToCloudWatchLogsPolicyArn) + !attachedPolicies.some( + (policy) => policy.PolicyArn === apiGatewayPushToCloudWatchLogsPolicyArn + ) ) { await awsRequest('IAM', 'attachRolePolicy', { PolicyArn: apiGatewayPushToCloudWatchLogsPolicyArn, diff --git a/lib/plugins/aws/customResources/resources/cognitoUserPool/handler.js b/lib/plugins/aws/customResources/resources/cognitoUserPool/handler.js index bc74dce0c46..683aecb67ee 100644 --- a/lib/plugins/aws/customResources/resources/cognitoUserPool/handler.js +++ b/lib/plugins/aws/customResources/resources/cognitoUserPool/handler.js @@ -21,7 +21,7 @@ function create(event, context) { const lambdaArn = getLambdaArn(Partition, Region, AccountId, FunctionName); - return findUserPoolByName({ userPoolName: UserPoolName, region: Region }).then(userPool => + return findUserPoolByName({ userPoolName: UserPoolName, region: Region }).then((userPool) => addPermission({ functionName: FunctionName, userPoolName: UserPoolName, diff --git a/lib/plugins/aws/customResources/resources/cognitoUserPool/lib/userPool.js b/lib/plugins/aws/customResources/resources/cognitoUserPool/lib/userPool.js index c53a0caee9d..f2b186c6ca2 100644 --- a/lib/plugins/aws/customResources/resources/cognitoUserPool/lib/userPool.js +++ b/lib/plugins/aws/customResources/resources/cognitoUserPool/lib/userPool.js @@ -39,8 +39,8 @@ function findUserPoolByName(config) { { name: 'CognitoIdentityServiceProvider', params: { region } }, 'listUserPools', payload - ).then(result => { - const matches = result.UserPools.filter(pool => pool.Name === userPoolName); + ).then((result) => { + const matches = result.UserPools.filter((pool) => pool.Name === userPoolName); if (matches.length) { return matches.shift(); } @@ -55,7 +55,7 @@ function findUserPoolByName(config) { function getConfiguration(config) { const { region } = config; - return findUserPoolByName(config).then(userPool => + return findUserPoolByName(config).then((userPool) => awsRequest({ name: 'CognitoIdentityServiceProvider', params: { region } }, 'describeUserPool', { UserPoolId: userPool.Id, }) @@ -65,7 +65,7 @@ function getConfiguration(config) { function updateConfiguration(config) { const { lambdaArn, userPoolConfigs, region } = config; - return getConfiguration(config).then(res => { + return getConfiguration(config).then((res) => { const UserPoolId = res.UserPool.Id; let { LambdaConfig } = res.UserPool; // remove configurations for this specific function @@ -74,7 +74,7 @@ function updateConfiguration(config) { return accum; }, LambdaConfig); - userPoolConfigs.forEach(poolConfig => { + userPoolConfigs.forEach((poolConfig) => { LambdaConfig[poolConfig.Trigger] = lambdaArn; }); @@ -95,7 +95,7 @@ function updateConfiguration(config) { function removeConfiguration(config) { const { lambdaArn, region } = config; - return getConfiguration(config).then(res => { + return getConfiguration(config).then((res) => { const UserPoolId = res.UserPool.Id; let { LambdaConfig } = res.UserPool; // remove configurations for this specific function diff --git a/lib/plugins/aws/customResources/resources/s3/lib/bucket.js b/lib/plugins/aws/customResources/resources/s3/lib/bucket.js index 51985e47a1b..0fffd3a681c 100644 --- a/lib/plugins/aws/customResources/resources/s3/lib/bucket.js +++ b/lib/plugins/aws/customResources/resources/s3/lib/bucket.js @@ -4,17 +4,14 @@ const crypto = require('crypto'); const { awsRequest } = require('../../utils'); function generateId(functionName, bucketConfig) { - const md5 = crypto - .createHash('md5') - .update(JSON.stringify(bucketConfig)) - .digest('hex'); + const md5 = crypto.createHash('md5').update(JSON.stringify(bucketConfig)).digest('hex'); return `${functionName}-${md5}`; } function createFilter(config) { const rules = config.Rules; if (rules && rules.length) { - const FilterRules = rules.map(rule => { + const FilterRules = rules.map((rule) => { const key = Object.keys(rule)[0]; const Name = key.toLowerCase(); const Value = rule[key]; @@ -42,21 +39,21 @@ function getConfiguration(config) { { name: 'S3', params: { region } }, 'getBucketNotificationConfiguration', payload - ).then(data => data); + ).then((data) => data); } function updateConfiguration(config) { const { lambdaArn, functionName, bucketName, bucketConfigs, region } = config; const Bucket = bucketName; - return getConfiguration(config).then(NotificationConfiguration => { + return getConfiguration(config).then((NotificationConfiguration) => { // remove configurations for this specific function NotificationConfiguration.LambdaFunctionConfigurations = NotificationConfiguration.LambdaFunctionConfigurations.filter( - conf => !conf.Id.startsWith(functionName) + (conf) => !conf.Id.startsWith(functionName) ); // add the events to the existing NotificationConfiguration - bucketConfigs.forEach(bucketConfig => { + bucketConfigs.forEach((bucketConfig) => { const Events = [bucketConfig.Event]; const LambdaFunctionArn = lambdaArn; const Id = generateId(functionName, bucketConfig); @@ -85,10 +82,10 @@ function removeConfiguration(config) { const { functionName, bucketName, region } = config; const Bucket = bucketName; - return getConfiguration(config).then(NotificationConfiguration => { + return getConfiguration(config).then((NotificationConfiguration) => { // remove configurations for this specific function NotificationConfiguration.LambdaFunctionConfigurations = NotificationConfiguration.LambdaFunctionConfigurations.filter( - conf => !conf.Id.startsWith(functionName) + (conf) => !conf.Id.startsWith(functionName) ); const payload = { diff --git a/lib/plugins/aws/customResources/resources/utils.js b/lib/plugins/aws/customResources/resources/utils.js index d1c046bc5c1..3ac2a1a4515 100644 --- a/lib/plugins/aws/customResources/resources/utils.js +++ b/lib/plugins/aws/customResources/resources/utils.js @@ -35,13 +35,13 @@ function response(event, context, status, data = {}, err) { }; return new Promise((resolve, reject) => { - const request = https.request(options, resp => { + const request = https.request(options, (resp) => { logger.log(`STATUS: ${resp.statusCode}`); logger.log(`HEADERS: ${JSON.stringify(resp.headers)}`); return resolve(data); }); - request.on('error', error => { + request.on('error', (error) => { logger.log(`sendResponse Error:\n${error}`); return reject(error); }); @@ -80,15 +80,15 @@ function handlerWrapper(handler, PhysicalResourceId) { event = Object.assign({}, event, { PhysicalResourceId }); return Promise.resolve(handler(event, context, callback)) .then( - result => response(event, context, 'SUCCESS', result), - error => response(event, context, 'FAILED', {}, error) + (result) => response(event, context, 'SUCCESS', result), + (error) => response(event, context, 'FAILED', {}, error) ) - .then(result => callback(null, result), callback); + .then((result) => callback(null, result), callback); }; } function wait(ms) { - return new Promise(resolve => setTimeout(resolve, ms)); + return new Promise((resolve) => setTimeout(resolve, ms)); } const MAX_AWS_REQUEST_TRY = (() => { @@ -97,7 +97,7 @@ const MAX_AWS_REQUEST_TRY = (() => { return userValue >= 0 ? userValue : DEFAULT_MAX_AWS_REQUEST_TRY; })(); -const getServiceInstance = nameInput => { +const getServiceInstance = (nameInput) => { let name; let params = {}; if (typeof nameInput === 'string') { @@ -111,7 +111,7 @@ const getServiceInstance = nameInput => { async function awsRequest(service, method, ...args) { const serviceInstance = getServiceInstance(service); - const callAws = async requestTry => { + const callAws = async (requestTry) => { try { return await serviceInstance[method](...args).promise(); } catch (error) { diff --git a/lib/plugins/aws/deploy/index.js b/lib/plugins/aws/deploy/index.js index c2534760f49..64bd547ef2c 100644 --- a/lib/plugins/aws/deploy/index.js +++ b/lib/plugins/aws/deploy/index.js @@ -99,9 +99,7 @@ class AwsDeploy { 'aws:deploy:deploy:createStack': () => BbPromise.bind(this).then(this.createStack), 'aws:deploy:deploy:checkForChanges': () => - BbPromise.bind(this) - .then(this.setBucketName) - .then(this.checkForChanges), + BbPromise.bind(this).then(this.setBucketName).then(this.checkForChanges), 'aws:deploy:deploy:uploadArtifacts': () => BbPromise.bind(this).then(() => { diff --git a/lib/plugins/aws/deploy/lib/checkForChanges.js b/lib/plugins/aws/deploy/lib/checkForChanges.js index 151f097ff1c..f066346bed8 100644 --- a/lib/plugins/aws/deploy/lib/checkForChanges.js +++ b/lib/plugins/aws/deploy/lib/checkForChanges.js @@ -18,7 +18,7 @@ module.exports = { return BbPromise.bind(this) .then(this.getMostRecentObjects) - .then(objs => { + .then((objs) => { return BbPromise.all([ this.getObjectMetadata(objs), this.getFunctionsEarliestLastModifiedDate(), @@ -47,7 +47,7 @@ module.exports = { return this.provider .request('S3', 'listObjectsV2', params) - .catch(reason => { + .catch((reason) => { if (!reason.message.includes('The specified bucket does not exist')) { return BbPromise.reject(reason); } @@ -62,7 +62,7 @@ module.exports = { ) ); }) - .then(result => { + .then((result) => { if (result && result.Contents && result.Contents.length) { const objects = result.Contents; @@ -71,7 +71,7 @@ module.exports = { const firstKey = ordered[0].Key; const directory = firstKey.substring(0, firstKey.lastIndexOf('/')); - const mostRecentObjects = ordered.filter(obj => { + const mostRecentObjects = ordered.filter((obj) => { const objKey = obj.Key; const objDirectory = objKey.substring(0, objKey.lastIndexOf('/')); @@ -87,17 +87,17 @@ module.exports = { // Gives the least recent last modify date across all the functions in the service. getFunctionsEarliestLastModifiedDate() { - const getFunctionResults = this.serverless.service.getAllFunctions().map(funName => { + const getFunctionResults = this.serverless.service.getAllFunctions().map((funName) => { const functionObj = this.serverless.service.getFunction(funName); return this.provider .request('Lambda', 'getFunction', { FunctionName: functionObj.name, }) - .then(res => new Date(res.Configuration.LastModified)) + .then((res) => new Date(res.Configuration.LastModified)) .catch(() => new Date(0)); // Function is missing, needs to be deployed }); - return BbPromise.all(getFunctionResults).then(results => + return BbPromise.all(getFunctionResults).then((results) => results.reduce((currentMin, date) => { if (!currentMin || date < currentMin) return date; return currentMin; @@ -107,14 +107,14 @@ module.exports = { getObjectMetadata(objects) { if (objects && objects.length) { - const headObjectObjects = objects.map(obj => + const headObjectObjects = objects.map((obj) => this.provider.request('S3', 'headObject', { Bucket: this.bucketName, Key: obj.Key, }) ); - return BbPromise.all(headObjectObjects).then(result => result); + return BbPromise.all(headObjectObjects).then((result) => result); } return BbPromise.resolve([]); @@ -122,7 +122,7 @@ module.exports = { checkIfDeploymentIsNecessary(objects, funcLastModifiedDate) { if (objects && objects.length) { - const remoteHashes = objects.map(object => object.Metadata.filesha256 || ''); + const remoteHashes = objects.map((object) => object.Metadata.filesha256 || ''); const serverlessDirPath = path.join(this.serverless.config.servicePath, '.serverless'); @@ -143,26 +143,23 @@ module.exports = { } // resolve paths and ensure we only hash each unique file once. const zipFilePaths = Array.from( - new Set(zipFiles.map(zipFile => path.resolve(serverlessDirPath, zipFile))) + new Set(zipFiles.map((zipFile) => path.resolve(serverlessDirPath, zipFile))) ); const readFile = BbPromise.promisify(fs.readFile); - const zipFileHashesPromises = zipFilePaths.map(zipFilePath => - readFile(zipFilePath).then(zipFile => - crypto - .createHash('sha256') - .update(zipFile) - .digest('base64') + const zipFileHashesPromises = zipFilePaths.map((zipFilePath) => + readFile(zipFilePath).then((zipFile) => + crypto.createHash('sha256').update(zipFile).digest('base64') ) ); - return BbPromise.all(zipFileHashesPromises).then(zipFileHashes => { + return BbPromise.all(zipFileHashesPromises).then((zipFileHashes) => { const localHashes = zipFileHashes; localHashes.push(localCfHash); // If any objects were changed after the last time the function was updated // there could have been a failed deploy. - const changedAfterDeploy = objects.some(object => { + const changedAfterDeploy = objects.some((object) => { return object.LastModified && object.LastModified > funcLastModifiedDate; }); @@ -192,9 +189,9 @@ module.exports = { const region = this.provider.getRegion(); const cloudWatchLogsSdk = new this.provider.sdk.CloudWatchLogs({ region }); - return this.provider.getAccountInfo().then(account => + return this.provider.getAccountInfo().then((account) => Promise.all( - this.serverless.service.getAllFunctions().map(functionName => { + this.serverless.service.getAllFunctions().map((functionName) => { const functionObj = this.serverless.service.getFunction(functionName); if (!functionObj.events) { @@ -202,7 +199,7 @@ module.exports = { } let logSubscriptionSerialNumber = 0; - const promises = functionObj.events.map(event => { + const promises = functionObj.events.map((event) => { if (!event.cloudwatchLog) { return BbPromise.resolve(); } @@ -260,7 +257,7 @@ module.exports = { cloudWatchLogsSdk .describeSubscriptionFilters({ logGroupName }) .promise() - .then(response => { + .then((response) => { const subscriptionFilter = response.subscriptionFilters[0]; // log group doesn't have any subscription filters currently diff --git a/lib/plugins/aws/deploy/lib/cleanupS3Bucket.js b/lib/plugins/aws/deploy/lib/cleanupS3Bucket.js index a08889bf789..d84a50fb894 100644 --- a/lib/plugins/aws/deploy/lib/cleanupS3Bucket.js +++ b/lib/plugins/aws/deploy/lib/cleanupS3Bucket.js @@ -22,7 +22,7 @@ module.exports = { Bucket: this.bucketName, Prefix: `${prefix}/${service}/${stage}`, }) - .then(response => { + .then((response) => { const stacks = findAndGroupDeployments(response, prefix, service, stage); const stacksToRemove = stacks.slice(0, -stacksToKeepCount || Infinity); @@ -50,8 +50,6 @@ module.exports = { }, cleanupS3Bucket() { - return BbPromise.bind(this) - .then(this.getObjectsToRemove) - .then(this.removeObjects); + return BbPromise.bind(this).then(this.getObjectsToRemove).then(this.removeObjects); }, }; diff --git a/lib/plugins/aws/deploy/lib/createStack.js b/lib/plugins/aws/deploy/lib/createStack.js index 54512a0a70c..5fd749c10d8 100644 --- a/lib/plugins/aws/deploy/lib/createStack.js +++ b/lib/plugins/aws/deploy/lib/createStack.js @@ -13,8 +13,8 @@ module.exports = { // Merge additional stack tags if (this.serverless.service.provider.stackTags) { const customKeys = Object.keys(this.serverless.service.provider.stackTags); - const collisions = Object.keys(stackTags).filter(defaultKey => - customKeys.some(key => defaultKey.toLowerCase() === key.toLowerCase()) + const collisions = Object.keys(stackTags).filter((defaultKey) => + customKeys.some((key) => defaultKey.toLowerCase() === key.toLowerCase()) ); // Delete collisions upfront @@ -31,7 +31,7 @@ module.exports = { Capabilities: ['CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM'], Parameters: [], TemplateBody: JSON.stringify(this.serverless.service.provider.coreCloudFormationTemplate), - Tags: Object.keys(stackTags).map(key => ({ Key: key, Value: stackTags[key] })), + Tags: Object.keys(stackTags).map((key) => ({ Key: key, Value: stackTags[key] })), }; if ( @@ -51,7 +51,7 @@ module.exports = { return this.provider .request('CloudFormation', 'createStack', params) - .then(cfData => this.monitorStack('create', cfData)); + .then((cfData) => this.monitorStack('create', cfData)); }, createStack() { @@ -71,7 +71,7 @@ module.exports = { .then(() => this.provider .request('CloudFormation', 'describeStacks', { StackName: stackName }) - .then(data => { + .then((data) => { const shouldCheckStackOutput = // check stack output only if acceleration is requested this.provider.isS3TransferAccelerationEnabled() && @@ -79,7 +79,7 @@ module.exports = { !this.serverless.service.provider.deploymentBucket; if (shouldCheckStackOutput) { const isAlreadyAccelerated = data.Stacks[0].Outputs.some( - output => output.OutputKey === 'ServerlessDeploymentBucketAccelerated' + (output) => output.OutputKey === 'ServerlessDeploymentBucketAccelerated' ); if (!isAlreadyAccelerated) { @@ -90,7 +90,7 @@ module.exports = { return BbPromise.resolve('alreadyCreated'); }) ) - .catch(e => { + .catch((e) => { if (e.message.indexOf('does not exist') > -1) { if (this.serverless.service.provider.deploymentBucket) { this.createLater = true; diff --git a/lib/plugins/aws/deploy/lib/existsDeploymentBucket.js b/lib/plugins/aws/deploy/lib/existsDeploymentBucket.js index 32929bac88f..00bfbadf2b2 100644 --- a/lib/plugins/aws/deploy/lib/existsDeploymentBucket.js +++ b/lib/plugins/aws/deploy/lib/existsDeploymentBucket.js @@ -10,7 +10,7 @@ module.exports = { Bucket: bucketName, }) ) - .then(resultParam => { + .then((resultParam) => { const result = resultParam; if (result.LocationConstraint === '') result.LocationConstraint = 'us-east-1'; if (result.LocationConstraint === 'EU') result.LocationConstraint = 'eu-west-1'; @@ -21,7 +21,7 @@ module.exports = { } return BbPromise.resolve(); }) - .catch(err => { + .catch((err) => { throw new this.serverless.classes.Error( `Could not locate deployment bucket. Error: ${err.message}` ); diff --git a/lib/plugins/aws/deploy/lib/extendedValidate.js b/lib/plugins/aws/deploy/lib/extendedValidate.js index e173d5335f2..9ba9bd73cb6 100644 --- a/lib/plugins/aws/deploy/lib/extendedValidate.js +++ b/lib/plugins/aws/deploy/lib/extendedValidate.js @@ -21,7 +21,7 @@ module.exports = { } const state = this.serverless.utils.readFileSync(serviceStateFilePath); const selfReferences = findReferences(state.service, '${self:}'); - selfReferences.forEach(ref => _.set(state.service, ref, this.serverless.service)); + selfReferences.forEach((ref) => _.set(state.service, ref, this.serverless.service)); Object.assign(this.serverless.service, state.service); @@ -37,12 +37,12 @@ module.exports = { // Check function's attached to API Gateway timeout if (Object.keys(this.serverless.service.functions).length) { - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObject = this.serverless.service.getFunction(functionName); // Check if function timeout is greater than API Gateway timeout if (functionObject.timeout > 30 && functionObject.events) { - functionObject.events.forEach(event => { + functionObject.events.forEach((event) => { if (Object.keys(event)[0] === 'http') { const warnMessage = [ `WARNING: Function ${functionName} has timeout of ${functionObject.timeout} `, @@ -58,7 +58,7 @@ module.exports = { } if (Object.keys(this.serverless.service.functions).length) { - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObject = this.serverless.service.getFunction(functionName); if (functionObject.image) return; const individually = diff --git a/lib/plugins/aws/deploy/lib/uploadArtifacts.js b/lib/plugins/aws/deploy/lib/uploadArtifacts.js index 89d251048b3..233ddce65ab 100644 --- a/lib/plugins/aws/deploy/lib/uploadArtifacts.js +++ b/lib/plugins/aws/deploy/lib/uploadArtifacts.js @@ -55,10 +55,7 @@ module.exports = { // TODO refactor to be async (use util function to compute checksum async) const data = fs.readFileSync(artifactFilePath); - const fileHash = crypto - .createHash('sha256') - .update(data) - .digest('base64'); + const fileHash = crypto.createHash('sha256').update(data).digest('base64'); let params = { Bucket: this.bucketName, @@ -84,7 +81,7 @@ module.exports = { const functionNames = this.serverless.service.getAllFunctions(); let artifactFilePaths = _.uniq( functionNames - .map(name => { + .map((name) => { const functionObject = this.serverless.service.getFunction(name); if (functionObject.image) return null; const functionArtifactFileName = this.provider.naming.getFunctionArtifactName(name); @@ -114,7 +111,7 @@ module.exports = { const layerNames = this.serverless.service.getAllLayers(); artifactFilePaths = artifactFilePaths.concat( layerNames - .map(name => { + .map((name) => { const layerObject = this.serverless.service.getLayer(name); if (layerObject.artifactAlreadyUploaded) { this.serverless.cli.log(`Skip uploading ${name}`); @@ -132,7 +129,7 @@ module.exports = { return BbPromise.map( artifactFilePaths, - artifactFilePath => { + (artifactFilePath) => { const stats = fs.statSync(artifactFilePath); const fileName = path.basename(artifactFilePath); this.serverless.cli.log( @@ -171,7 +168,7 @@ function setServersideEncryptionOptions(putParams, deploymentBucketOptions) { const params = putParams; - encryptionFields.forEach(element => { + encryptionFields.forEach((element) => { if (deploymentBucketOptions[element[0]]) { params[element[1]] = deploymentBucketOptions[element[0]]; } diff --git a/lib/plugins/aws/deploy/lib/validateTemplate.js b/lib/plugins/aws/deploy/lib/validateTemplate.js index 35256439459..5b9120c155e 100644 --- a/lib/plugins/aws/deploy/lib/validateTemplate.js +++ b/lib/plugins/aws/deploy/lib/validateTemplate.js @@ -13,7 +13,7 @@ module.exports = { TemplateURL: `https://${s3Endpoint}/${bucketName}/${artifactDirectoryName}/${compiledTemplateFileName}`, }; - return this.provider.request('CloudFormation', 'validateTemplate', params).catch(error => { + return this.provider.request('CloudFormation', 'validateTemplate', params).catch((error) => { const errorMessage = ['The CloudFormation template is invalid:', ` ${error.message}`].join( '' ); diff --git a/lib/plugins/aws/deployFunction.js b/lib/plugins/aws/deployFunction.js index e9aff8460e0..d1984ab6183 100644 --- a/lib/plugins/aws/deployFunction.js +++ b/lib/plugins/aws/deployFunction.js @@ -151,10 +151,10 @@ class AwsDeployFunction { functionObj.environment ); - if (Object.values(params.Environment.Variables).some(value => _.isObject(value))) { + if (Object.values(params.Environment.Variables).some((value) => _.isObject(value))) { delete params.Environment; } else { - Object.keys(params.Environment.Variables).forEach(key => { + Object.keys(params.Environment.Variables).forEach((key) => { // taken from the bash man pages if (!key.match(/^[A-Za-z_][a-zA-Z0-9_]*$/)) { const errorMessage = 'Invalid characters in environment variable'; @@ -228,10 +228,7 @@ class AwsDeployFunction { const remoteHash = this.serverless.service.provider.remoteFunctionData.Configuration .CodeSha256; - const localHash = crypto - .createHash('sha256') - .update(data) - .digest('base64'); + const localHash = crypto.createHash('sha256').update(data).digest('base64'); if (remoteHash === localHash && !this.options.force) { this.serverless.cli.log('Code not changed. Skipping function deployment.'); diff --git a/lib/plugins/aws/deployList.js b/lib/plugins/aws/deployList.js index c7e34dcd3fa..7ef14b54994 100644 --- a/lib/plugins/aws/deployList.js +++ b/lib/plugins/aws/deployList.js @@ -44,13 +44,13 @@ class AwsDeployList { } this.serverless.cli.log('Listing deployments:'); - deployments.forEach(deployment => { + deployments.forEach((deployment) => { this.serverless.cli.log('-------------'); const match = deployment[0].directory.match(directoryRegex); this.serverless.cli.log(`Timestamp: ${match[1]}`); this.serverless.cli.log(`Datetime: ${match[2]}`); this.serverless.cli.log('Files:'); - deployment.forEach(entry => { + deployment.forEach((entry) => { this.serverless.cli.log(`- ${entry.file}`); }); }); @@ -67,7 +67,7 @@ class AwsDeployList { const funcs = this.serverless.service.getAllFunctionsNames(); const result = await Promise.all( - funcs.map(funcName => { + funcs.map((funcName) => { const params = { FunctionName: funcName, }; @@ -76,7 +76,7 @@ class AwsDeployList { }) ); - return result.map(item => item.Configuration); + return result.map((item) => item.Configuration); } async getFunctionPaginatedVersions(params, totalVersions) { @@ -95,7 +95,7 @@ class AwsDeployList { async getFunctionVersions(funcs) { return Promise.all( - funcs.map(func => { + funcs.map((func) => { const params = { FunctionName: func.FunctionName, }; @@ -109,7 +109,7 @@ class AwsDeployList { this.serverless.cli.log('Listing functions and their last 5 versions:'); this.serverless.cli.log('-------------'); - funcs.forEach(func => { + funcs.forEach((func) => { let message = ''; let name = func.Versions[0].FunctionName; @@ -117,7 +117,7 @@ class AwsDeployList { name = name.replace(`${this.provider.getStage()}-`, ''); message += `${name}: `; - const versions = func.Versions.map(funcEntry => funcEntry.Version).slice( + const versions = func.Versions.map((funcEntry) => funcEntry.Version).slice( Math.max(0, func.Versions.length - 5) ); diff --git a/lib/plugins/aws/info/display.js b/lib/plugins/aws/info/display.js index 3a8ef3e836c..6c08a61121b 100644 --- a/lib/plugins/aws/info/display.js +++ b/lib/plugins/aws/info/display.js @@ -31,7 +31,7 @@ module.exports = { let apiKeysMessage = `${chalk.yellow('api keys:')}`; if (info.apiKeys && info.apiKeys.length > 0) { - info.apiKeys.forEach(apiKeyInfo => { + info.apiKeys.forEach((apiKeyInfo) => { const description = apiKeyInfo.description ? ` - ${apiKeyInfo.description}` : ''; if (conceal) { apiKeysMessage += `\n ${apiKeyInfo.name}${description}`; @@ -52,11 +52,11 @@ module.exports = { let endpointsMessage = `${chalk.yellow('endpoints:')}`; if (info.endpoints && info.endpoints.length) { - info.endpoints.forEach(endpoint => { + info.endpoints.forEach((endpoint) => { // if the endpoint is of type http(s) if (endpoint.startsWith('https://')) { - Object.values(this.serverless.service.functions).forEach(functionObject => { - functionObject.events.forEach(event => { + Object.values(this.serverless.service.functions).forEach((functionObject) => { + functionObject.events.forEach((event) => { if (event.http) { let method; let path; @@ -72,7 +72,7 @@ module.exports = { path !== '/' ? `/${path .split('/') - .filter(p => p !== '') + .filter((p) => p !== '') .join('/')}` : ''; endpointsMessage += `\n ${method} - ${endpoint}${path}`; @@ -87,8 +87,9 @@ module.exports = { for (const functionData of Object.values(this.serverless.service.functions)) { for (const event of functionData.events) { if (!event.httpApi) continue; - endpointsMessage += `\n ${event.resolvedMethod} - ${endpoint}${event.resolvedPath || - ''}`; + endpointsMessage += `\n ${event.resolvedMethod} - ${endpoint}${ + event.resolvedPath || '' + }`; } } } else { @@ -115,7 +116,7 @@ module.exports = { let functionsMessage = `${chalk.yellow('functions:')}`; if (info.functions && info.functions.length > 0) { - info.functions.forEach(f => { + info.functions.forEach((f) => { functionsMessage += `\n ${f.name}: ${f.deployedName}`; }); } else { @@ -131,7 +132,7 @@ module.exports = { let layersMessage = `${chalk.yellow('layers:')}`; if (info.layers && info.layers.length > 0) { - info.layers.forEach(l => { + info.layers.forEach((l) => { layersMessage += `\n ${l.name}: ${l.arn}`; }); } else { @@ -146,7 +147,7 @@ module.exports = { let message = ''; if (this.options.verbose) { message = `${chalk.yellow.underline('\nStack Outputs\n')}`; - this.gatheredData.outputs.forEach(output => { + this.gatheredData.outputs.forEach((output) => { message += `${chalk.yellow(output.OutputKey)}: ${output.OutputValue}\n`; }); diff --git a/lib/plugins/aws/info/getApiKeyValues.js b/lib/plugins/aws/info/getApiKeyValues.js index b3c2ecc71a7..9c9d58ddda4 100644 --- a/lib/plugins/aws/info/getApiKeyValues.js +++ b/lib/plugins/aws/info/getApiKeyValues.js @@ -14,12 +14,12 @@ module.exports = { this.serverless.service.provider.apiKeys; const apiKeyNames = []; if (Array.isArray(apiKeyDefinitions) && apiKeyDefinitions.length) { - apiKeyDefinitions.forEach(definition => { + apiKeyDefinitions.forEach((definition) => { // different API key types are nested in separate arrays if (_.isObject(definition)) { const keyTypeName = Object.keys(definition)[0]; if (Array.isArray(definition[keyTypeName])) { - definition[keyTypeName].forEach(keyName => apiKeyNames.push(keyName)); + definition[keyTypeName].forEach((keyName) => apiKeyNames.push(keyName)); } else if (definition.name) { apiKeyNames.push(definition.name); } @@ -35,13 +35,13 @@ module.exports = { .request('CloudFormation', 'describeStackResources', { StackName: this.provider.naming.getStackName(), }) - .then(resources => { + .then((resources) => { const apiKeys = _(resources.StackResources) - .filter(resource => resource.ResourceType === 'AWS::ApiGateway::ApiKey') - .map(resource => resource.PhysicalResourceId) + .filter((resource) => resource.ResourceType === 'AWS::ApiGateway::ApiKey') + .map((resource) => resource.PhysicalResourceId) .value(); return Promise.all( - apiKeys.map(apiKey => + apiKeys.map((apiKey) => this.provider.request('APIGateway', 'getApiKey', { apiKey, includeValue: true, @@ -49,9 +49,9 @@ module.exports = { ) ); }) - .then(apiKeys => { + .then((apiKeys) => { if (apiKeys && apiKeys.length) { - info.apiKeys = apiKeys.map(apiKey => + info.apiKeys = apiKeys.map((apiKey) => _.pick(apiKey, ['name', 'value', 'description', 'customerId']) ); } diff --git a/lib/plugins/aws/info/getResourceCount.js b/lib/plugins/aws/info/getResourceCount.js index 54cb03f40f8..dde3bdedddb 100644 --- a/lib/plugins/aws/info/getResourceCount.js +++ b/lib/plugins/aws/info/getResourceCount.js @@ -8,7 +8,7 @@ module.exports = { StackName: this.provider.naming.getStackName(), NextToken: nextToken, }; - return this.provider.request('CloudFormation', 'listStackResources', params).then(result => { + return this.provider.request('CloudFormation', 'listStackResources', params).then((result) => { if (Object.keys(result).length) { this.gatheredData.info.resourceCount = resourceCount + result.StackResourceSummaries.length; if (result.NextToken) { diff --git a/lib/plugins/aws/info/getStackInfo.js b/lib/plugins/aws/info/getStackInfo.js index 82341ca86be..eb925258a90 100644 --- a/lib/plugins/aws/info/getStackInfo.js +++ b/lib/plugins/aws/info/getStackInfo.js @@ -25,7 +25,7 @@ module.exports = { const sdkRequests = [ this.provider .request('CloudFormation', 'describeStacks', { StackName: stackName }) - .then(result => { + .then((result) => { if (result) stackData.outputs = result.Stacks[0].Outputs; }), ]; @@ -37,14 +37,14 @@ module.exports = { ? resolveCfImportValue(this.provider, httpApiId['Fn::ImportValue']) : BbPromise.resolve(httpApiId) ) - .then(id => { + .then((id) => { return this.provider.request('ApiGatewayV2', 'getApi', { ApiId: id }); }) .then( - result => { + (result) => { stackData.externalHttpApiEndpoint = result.ApiEndpoint; }, - error => { + (error) => { throw new this.serverless.classes.Error( `Could not resolve provider.httpApi.id parameter. ${error.message}` ); @@ -66,7 +66,7 @@ module.exports = { this.gatheredData.outputs = outputs; // Functions - this.serverless.service.getAllFunctions().forEach(func => { + this.serverless.service.getAllFunctions().forEach((func) => { const functionInfo = {}; functionInfo.name = func; functionInfo.deployedName = this.serverless.service.getFunction(func).name; @@ -74,7 +74,7 @@ module.exports = { }); // Layers - this.serverless.service.getAllLayers().forEach(layer => { + this.serverless.service.getAllLayers().forEach((layer) => { const layerInfo = {}; layerInfo.name = layer; const layerOutputId = this.provider.naming.getLambdaLayerOutputLogicalId(layer); @@ -89,7 +89,7 @@ module.exports = { // CloudFront const cloudFrontDomainName = outputs.find( - output => + (output) => output.OutputKey === this.provider.naming.getCloudFrontDistributionDomainNameLogicalId() ); if (cloudFrontDomainName) { @@ -98,8 +98,8 @@ module.exports = { // Endpoints outputs - .filter(x => x.OutputKey.match(serviceEndpointOutputRegex)) - .forEach(x => { + .filter((x) => x.OutputKey.match(serviceEndpointOutputRegex)) + .forEach((x) => { if (x.OutputKey === 'HttpApiUrl') { this.gatheredData.info.endpoints.push(`httpApi: ${x.OutputValue}`); } else { diff --git a/lib/plugins/aws/invoke.js b/lib/plugins/aws/invoke.js index afab664bdc1..37af84b78db 100644 --- a/lib/plugins/aws/invoke.js +++ b/lib/plugins/aws/invoke.js @@ -103,7 +103,7 @@ class AwsInvoke { } log(invocationReply) { - const color = !invocationReply.FunctionError ? x => x : chalk.red; + const color = !invocationReply.FunctionError ? (x) => x : chalk.red; if (invocationReply.Payload) { const response = JSON.parse(invocationReply.Payload); @@ -116,7 +116,7 @@ class AwsInvoke { chalk.gray('--------------------------------------------------------------------') ); const logResult = Buffer.from(invocationReply.LogResult, 'base64').toString(); - logResult.split('\n').forEach(line => this.consoleLog(formatLambdaLogEvent(line))); + logResult.split('\n').forEach((line) => this.consoleLog(formatLambdaLogEvent(line))); } if (invocationReply.FunctionError) { diff --git a/lib/plugins/aws/invokeLocal/index.js b/lib/plugins/aws/invokeLocal/index.js index 64c185c1a18..eb9d52c4b86 100644 --- a/lib/plugins/aws/invokeLocal/index.js +++ b/lib/plugins/aws/invokeLocal/index.js @@ -25,7 +25,7 @@ const resolveCfRefValue = require('../utils/resolveCfRefValue'); const cachePath = path.join(cachedir('serverless'), 'invokeLocal'); const ensureRuntimeWrappers = isStandalone - ? getEnsureArtifact('runtimeWrappers/validationFile', async artifactsPath => { + ? getEnsureArtifact('runtimeWrappers/validationFile', async (artifactsPath) => { await fse.copy( path.resolve(__dirname, 'runtimeWrappers'), path.resolve(artifactsPath, 'runtimeWrappers') @@ -297,7 +297,7 @@ class AwsInvokeLocal { return Promise.all( (this.options.functionObj.layers || this.serverless.service.provider.layers || []).map( - async layer => { + async (layer) => { if (layer.Ref) { const targetLayer = layers[layer.Ref]; @@ -453,10 +453,10 @@ class AwsInvokeLocal { await this.ensurePackage(); await this.checkDockerDaemonStatus(); const results = await Promise.all([ - this.checkDockerImage(`lambci/lambda:${runtime}`).then(exists => { + this.checkDockerImage(`lambci/lambda:${runtime}`).then((exists) => { return exists ? {} : this.pullDockerImage(); }), - this.getLayerPaths().then(layerPaths => this.buildDockerImage(layerPaths)), + this.getLayerPaths().then((layerPaths) => this.buildDockerImage(layerPaths)), this.extractArtifact(), ]); const imageName = results[1]; @@ -513,7 +513,7 @@ class AwsInvokeLocal { getDockerArgsFromOptions() { const dockerArgOptions = this.options['docker-arg']; - return _.flatMap([].concat(dockerArgOptions || []), dockerArgOption => { + return _.flatMap([].concat(dockerArgOptions || []), (dockerArgOption) => { const splitItems = dockerArgOption.split(' '); return [splitItems[0], splitItems.slice(1).join(' ')]; }); @@ -554,11 +554,11 @@ class AwsInvokeLocal { { env: process.env }, { shell: true } ); - python.stdout.on('data', buf => this.serverless.cli.consoleLog(buf.toString())); - python.stderr.on('data', buf => this.serverless.cli.consoleLog(buf.toString())); + python.stdout.on('data', (buf) => this.serverless.cli.consoleLog(buf.toString())); + python.stderr.on('data', (buf) => this.serverless.cli.consoleLog(buf.toString())); python.on('close', () => resolve()); let isRejected = false; - python.on('error', error => { + python.on('error', (error) => { isRejected = true; reject(error); }); @@ -600,11 +600,11 @@ class AwsInvokeLocal { ].join('') ); - java.stdout.on('data', buf => this.serverless.cli.consoleLog(buf.toString())); - java.stderr.on('data', buf => this.serverless.cli.consoleLog(buf.toString())); + java.stdout.on('data', (buf) => this.serverless.cli.consoleLog(buf.toString())); + java.stderr.on('data', (buf) => this.serverless.cli.consoleLog(buf.toString())); java.on('close', () => resolve()); let isRejected = false; - java.on('error', error => { + java.on('error', (error) => { isRejected = true; reject(error); }); @@ -647,16 +647,16 @@ class AwsInvokeLocal { this.serverless.cli.log('Building Java bridge, first invocation might take a bit longer.'); - mvn.stderr.on('data', buf => + mvn.stderr.on('data', (buf) => this.serverless.cli.consoleLog(`mvn(stderr) - ${buf.toString()}`) ); const chunk = []; if (process.env.SLS_DEBUG) { - mvn.stdout.on('data', buf => chunk.push(buf)); + mvn.stdout.on('data', (buf) => chunk.push(buf)); } let isRejected = false; - mvn.on('error', error => { + mvn.on('error', (error) => { if (!isRejected) { isRejected = true; reject(error); @@ -669,10 +669,10 @@ class AwsInvokeLocal { } else if (!isRejected) { if (process.env.SLS_DEBUG) { chunk - .map(elem => elem.toString()) + .map((elem) => elem.toString()) .join('') .split(/\n/) - .forEach(line => { + .forEach((line) => { this.serverless.cli.consoleLog(`mvn(stdout) - ${line}`); }); } @@ -703,11 +703,11 @@ class AwsInvokeLocal { env: process.env, shell: true, }); - ruby.stdout.on('data', buf => this.serverless.cli.consoleLog(buf.toString())); - ruby.stderr.on('data', buf => this.serverless.cli.consoleLog(buf.toString())); + ruby.stdout.on('data', (buf) => this.serverless.cli.consoleLog(buf.toString())); + ruby.stderr.on('data', (buf) => this.serverless.cli.consoleLog(buf.toString())); ruby.on('close', () => resolve()); let isRejected = false; - ruby.on('error', error => { + ruby.on('error', (error) => { isRejected = true; reject(error); }); @@ -779,7 +779,7 @@ class AwsInvokeLocal { this.serverless.cli.consoleLog(JSON.stringify(result, null, 4)); } - return new Promise(resolve => { + return new Promise((resolve) => { const callback = (err, result) => { if (!hasResponded) { hasResponded = true; diff --git a/lib/plugins/aws/lib/cloudformationSchema.js b/lib/plugins/aws/lib/cloudformationSchema.js index c40f871c5e7..2c4e464bc04 100644 --- a/lib/plugins/aws/lib/cloudformationSchema.js +++ b/lib/plugins/aws/lib/cloudformationSchema.js @@ -27,7 +27,7 @@ const yamlType = (name, kind) => { const functionName = ['Ref', 'Condition'].includes(name) ? name : `Fn::${name}`; return new YAML.Type(`!${name}`, { kind, - construct: data => { + construct: (data) => { if (name === 'GetAtt') { // special GetAtt dot syntax if (typeof data === 'string') { @@ -42,8 +42,8 @@ const yamlType = (name, kind) => { const createSchema = () => { const types = _.flatten( - functionNames.map(functionName => - ['mapping', 'scalar', 'sequence'].map(kind => yamlType(functionName, kind)) + functionNames.map((functionName) => + ['mapping', 'scalar', 'sequence'].map((kind) => yamlType(functionName, kind)) ) ); return YAML.Schema.create(types); diff --git a/lib/plugins/aws/lib/monitorStack.js b/lib/plugins/aws/lib/monitorStack.js index 81a3b90dfdf..91644a03ac7 100644 --- a/lib/plugins/aws/lib/monitorStack.js +++ b/lib/plugins/aws/lib/monitorStack.js @@ -37,7 +37,7 @@ module.exports = { stackEvents.reverse(); // Loop through stack events - stackEvents.forEach(event => { + stackEvents.forEach((event) => { if (loggedEventIds.has(event.EventId)) return; let eventStatus = event.ResourceStatus || null; // Keep track of stack status @@ -93,7 +93,7 @@ module.exports = { throw new this.serverless.classes.Error(errorMessage); } }, - e => { + (e) => { if (action === 'delete' && e.message.endsWith('does not exist')) { // empty console.log for a prettier output if (!this.options.verbose) this.serverless.cli.consoleLog(''); @@ -129,7 +129,7 @@ module.exports = { this.serverless.cli.log(`Checking Stack ${action} progress...`); - return this.checkStackProgress(action, cfData, stackUrl, options, {}).then(stackStatus => { + return this.checkStackProgress(action, cfData, stackUrl, options, {}).then((stackStatus) => { // empty console.log for a prettier output if (!this.options.verbose) this.serverless.cli.consoleLog(''); this.serverless.cli.log(`Stack ${action} finished...`); diff --git a/lib/plugins/aws/lib/naming.js b/lib/plugins/aws/lib/naming.js index 6e055db3c06..412576b0673 100644 --- a/lib/plugins/aws/lib/naming.js +++ b/lib/plugins/aws/lib/naming.js @@ -267,10 +267,7 @@ module.exports = { return `${this.getNormalizedAuthorizerName(functionName)}ApiGatewayAuthorizer`; }, normalizePath(resourcePath) { - return resourcePath - .split('/') - .map(this.normalizePathPart.bind(this)) - .join(''); + return resourcePath.split('/').map(this.normalizePathPart.bind(this)).join(''); }, getResourceLogicalId(resourcePath) { return `ApiGatewayResource${this.normalizePath(resourcePath)}`; @@ -482,9 +479,9 @@ module.exports = { return `${this.getNormalizedFunctionName(functionName)}LambdaPermissionHttpApi`; }, getLambdaAlexaSkillPermissionLogicalId(functionName, alexaSkillIndex) { - return `${this.getNormalizedFunctionName( - functionName - )}LambdaPermissionAlexaSkill${alexaSkillIndex || '0'}`; + return `${this.getNormalizedFunctionName(functionName)}LambdaPermissionAlexaSkill${ + alexaSkillIndex || '0' + }`; }, getLambdaAlexaSmartHomePermissionLogicalId(functionName, alexaSmartHomeIndex) { return `${this.getNormalizedFunctionName( diff --git a/lib/plugins/aws/lib/setBucketName.js b/lib/plugins/aws/lib/setBucketName.js index 8a32960996a..ffd0c6e9466 100644 --- a/lib/plugins/aws/lib/setBucketName.js +++ b/lib/plugins/aws/lib/setBucketName.js @@ -8,7 +8,7 @@ module.exports = { return BbPromise.resolve(this.bucketName); } - return this.provider.getServerlessDeploymentBucketName().then(bucketName => { + return this.provider.getServerlessDeploymentBucketName().then((bucketName) => { this.bucketName = bucketName; }); }, diff --git a/lib/plugins/aws/lib/updateStack.js b/lib/plugins/aws/lib/updateStack.js index 79f83399dd7..ed81728ffc8 100644 --- a/lib/plugins/aws/lib/updateStack.js +++ b/lib/plugins/aws/lib/updateStack.js @@ -19,8 +19,8 @@ module.exports = { // Merge additional stack tags if (this.serverless.service.provider.stackTags) { const customKeys = Object.keys(this.serverless.service.provider.stackTags); - const collisions = Object.keys(stackTags).filter(defaultKey => - customKeys.some(key => defaultKey.toLowerCase() === key.toLowerCase()) + const collisions = Object.keys(stackTags).filter((defaultKey) => + customKeys.some((key) => defaultKey.toLowerCase() === key.toLowerCase()) ); // Delete collisions upfront @@ -37,7 +37,7 @@ module.exports = { Capabilities: ['CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM'], Parameters: [], TemplateURL: templateUrl, - Tags: Object.keys(stackTags).map(key => ({ Key: key, Value: stackTags[key] })), + Tags: Object.keys(stackTags).map((key) => ({ Key: key, Value: stackTags[key] })), }; if ( @@ -61,7 +61,7 @@ module.exports = { return this.provider .request('CloudFormation', 'createStack', params) - .then(cfData => this.monitorStack('create', cfData)); + .then((cfData) => this.monitorStack('create', cfData)); }, update() { @@ -76,8 +76,8 @@ module.exports = { // Merge additional stack tags if (this.serverless.service.provider.stackTags) { const customKeys = Object.keys(this.serverless.service.provider.stackTags); - const collisions = Object.keys(stackTags).filter(defaultKey => - customKeys.some(key => defaultKey.toLowerCase() === key.toLowerCase()) + const collisions = Object.keys(stackTags).filter((defaultKey) => + customKeys.some((key) => defaultKey.toLowerCase() === key.toLowerCase()) ); // Delete collisions upfront @@ -93,7 +93,7 @@ module.exports = { Capabilities: ['CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM'], Parameters: [], TemplateURL: templateUrl, - Tags: Object.keys(stackTags).map(key => ({ Key: key, Value: stackTags[key] })), + Tags: Object.keys(stackTags).map((key) => ({ Key: key, Value: stackTags[key] })), }; if ( @@ -131,8 +131,8 @@ module.exports = { return this.provider .request('CloudFormation', 'updateStack', params) - .then(cfData => this.monitorStack('update', cfData)) - .catch(e => { + .then((cfData) => this.monitorStack('update', cfData)) + .catch((e) => { if (e.message === NO_UPDATE_MESSAGE) { return BbPromise.resolve(); } diff --git a/lib/plugins/aws/logs.js b/lib/plugins/aws/logs.js index 09b2ea27637..2a8bc32f85f 100644 --- a/lib/plugins/aws/logs.js +++ b/lib/plugins/aws/logs.js @@ -49,7 +49,7 @@ class AwsLogs { throw new this.serverless.classes.Error('No existing streams for the function'); } - return reply.logStreams.map(logStream => logStream.logStreamName); + return reply.logStreams.map((logStream) => logStream.logStreamName); } async showLogs(logStreamNames) { @@ -84,19 +84,15 @@ class AwsLogs { params.startTime = dayjs.utc(this.options.startTime).valueOf(); } } else { - params.startTime = dayjs() - .subtract(10, 'm') - .valueOf(); + params.startTime = dayjs().subtract(10, 'm').valueOf(); if (this.options.tail) { - params.startTime = dayjs() - .subtract(10, 's') - .valueOf(); + params.startTime = dayjs().subtract(10, 's').valueOf(); } } const results = await this.provider.request('CloudWatchLogs', 'filterLogEvents', params); if (results.events) { - results.events.forEach(e => { + results.events.forEach((e) => { process.stdout.write(formatLambdaLogEvent(e.message)); }); } diff --git a/lib/plugins/aws/metrics.js b/lib/plugins/aws/metrics.js index 5ce68b4b0b8..cd68973ca3d 100644 --- a/lib/plugins/aws/metrics.js +++ b/lib/plugins/aws/metrics.js @@ -31,16 +31,12 @@ class AwsMetrics { this.validate(); const today = new Date(); - const yesterday = dayjs() - .subtract(1, 'day') - .toDate(); + const yesterday = dayjs().subtract(1, 'day').toDate(); if (this.options.startTime) { const sinceDateMatch = this.options.startTime.match(/(\d+)(m|h|d)/); if (sinceDateMatch) { - this.options.startTime = dayjs() - .subtract(sinceDateMatch[1], sinceDateMatch[2]) - .valueOf(); + this.options.startTime = dayjs().subtract(sinceDateMatch[1], sinceDateMatch[2]).valueOf(); } } @@ -59,7 +55,7 @@ class AwsMetrics { : this.serverless.service.getAllFunctionsNames(); return Promise.all( - functions.map(async functionName => { + functions.map(async (functionName) => { const commonParams = { StartTime, EndTime, @@ -89,7 +85,7 @@ class AwsMetrics { Unit: 'Milliseconds', }); - const getMetrics = params => + const getMetrics = (params) => this.provider.request('CloudWatch', 'getMetricStatistics', params); return BbPromise.all([ @@ -116,11 +112,11 @@ class AwsMetrics { message += `${formattedStartTime} - ${formattedEndTime}\n\n`; if (metrics && metrics.length > 0) { - const getDatapointsByLabel = Label => + const getDatapointsByLabel = (Label) => _.flatten( _.flatten(metrics) - .filter(metric => metric.Label === Label) - .map(metric => metric.Datapoints) + .filter((metric) => metric.Label === Label) + .map((metric) => metric.Datapoints) ); const invocationsCount = _.sumBy(getDatapointsByLabel('Invocations'), 'Sum'); diff --git a/lib/plugins/aws/package/compile/events/alb/lib/listenerRules.js b/lib/plugins/aws/package/compile/events/alb/lib/listenerRules.js index 503e24a4797..860559fd0ab 100644 --- a/lib/plugins/aws/package/compile/events/alb/lib/listenerRules.js +++ b/lib/plugins/aws/package/compile/events/alb/lib/listenerRules.js @@ -4,7 +4,7 @@ module.exports = { compileListenerRules() { const { authorizers, events } = this.validated; - events.forEach(event => { + events.forEach((event) => { const listenerRuleLogicalId = this.provider.naming.getAlbListenerRuleLogicalId( event.functionName, event.priority @@ -18,7 +18,7 @@ module.exports = { let Order = 0; const Actions = []; if (event.authorizers) { - event.authorizers.forEach(authName => { + event.authorizers.forEach((authName) => { const auth = authorizers[authName]; if (auth.type === 'cognito') { const config = { @@ -109,7 +109,7 @@ module.exports = { Conditions.push({ Field: 'query-string', QueryStringConfig: { - Values: Object.keys(event.conditions.query).map(key => ({ + Values: Object.keys(event.conditions.query).map((key) => ({ Key: key, Value: event.conditions.query[key], })), diff --git a/lib/plugins/aws/package/compile/events/alb/lib/permissions.js b/lib/plugins/aws/package/compile/events/alb/lib/permissions.js index aeb8ea1ca06..3c705e7d17f 100644 --- a/lib/plugins/aws/package/compile/events/alb/lib/permissions.js +++ b/lib/plugins/aws/package/compile/events/alb/lib/permissions.js @@ -5,7 +5,7 @@ const resolveLambdaTarget = require('../../../../../utils/resolveLambdaTarget'); module.exports = { compilePermissions() { - this.validated.events.forEach(event => { + this.validated.events.forEach((event) => { const { functionName, albId, multiValueHeaders } = event; const albPermissionLogicalId = this.provider.naming.getLambdaAlbPermissionLogicalId( diff --git a/lib/plugins/aws/package/compile/events/alb/lib/targetGroups.js b/lib/plugins/aws/package/compile/events/alb/lib/targetGroups.js index 4380ce7bac8..009ceeb91d7 100644 --- a/lib/plugins/aws/package/compile/events/alb/lib/targetGroups.js +++ b/lib/plugins/aws/package/compile/events/alb/lib/targetGroups.js @@ -14,7 +14,7 @@ const healthCheckDefaults = { module.exports = { compileTargetGroups() { - this.validated.events.forEach(event => { + this.validated.events.forEach((event) => { const { functionName, albId, multiValueHeaders = false, healthCheck } = event; const targetGroupLogicalId = this.provider.naming.getAlbTargetGroupLogicalId( diff --git a/lib/plugins/aws/package/compile/events/alb/lib/validate.js b/lib/plugins/aws/package/compile/events/alb/lib/validate.js index 76328a98d5b..3a0afa8da84 100644 --- a/lib/plugins/aws/package/compile/events/alb/lib/validate.js +++ b/lib/plugins/aws/package/compile/events/alb/lib/validate.js @@ -20,7 +20,7 @@ module.exports = { const events = []; Object.entries(this.serverless.service.functions).forEach(([functionName, functionObject]) => { - functionObject.events.forEach(event => { + functionObject.events.forEach((event) => { if (event.alb) { if (_.isObject(event.alb)) { const { albId, listenerId } = this.validateListenerArn( diff --git a/lib/plugins/aws/package/compile/events/alexaSkill.js b/lib/plugins/aws/package/compile/events/alexaSkill.js index 9efe5927e10..49f689bfc57 100644 --- a/lib/plugins/aws/package/compile/events/alexaSkill.js +++ b/lib/plugins/aws/package/compile/events/alexaSkill.js @@ -27,7 +27,7 @@ class AwsCompileAlexaSkillEvents { if ( this.serverless.service.provider.name === 'aws' && Object.values(this.serverless.service.functions).some(({ events }) => - events.some(event => event === 'alexaSkill') + events.some((event) => event === 'alexaSkill') ) ) { this.serverless._logDeprecation( @@ -41,11 +41,11 @@ class AwsCompileAlexaSkillEvents { } compileAlexaSkillEvents() { - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObj = this.serverless.service.getFunction(functionName); let alexaSkillNumberInFunction = 0; - functionObj.events.forEach(event => { + functionObj.events.forEach((event) => { if (event === 'alexaSkill' || event.alexaSkill) { let enabled = true; let appId; diff --git a/lib/plugins/aws/package/compile/events/alexaSmartHome.js b/lib/plugins/aws/package/compile/events/alexaSmartHome.js index 625b33a835e..910bbf4e485 100644 --- a/lib/plugins/aws/package/compile/events/alexaSmartHome.js +++ b/lib/plugins/aws/package/compile/events/alexaSmartHome.js @@ -28,12 +28,12 @@ class AwsCompileAlexaSmartHomeEvents { } compileAlexaSmartHomeEvents() { - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObj = this.serverless.service.getFunction(functionName); let alexaSmartHomeNumberInFunction = 0; if (functionObj.events) { - functionObj.events.forEach(event => { + functionObj.events.forEach((event) => { if (event.alexaSmartHome) { alexaSmartHomeNumberInFunction++; let EventSourceToken; diff --git a/lib/plugins/aws/package/compile/events/apiGateway/index.js b/lib/plugins/aws/package/compile/events/apiGateway/index.js index 2376fd15561..5d517e3576a 100644 --- a/lib/plugins/aws/package/compile/events/apiGateway/index.js +++ b/lib/plugins/aws/package/compile/events/apiGateway/index.js @@ -303,9 +303,7 @@ class AwsCompileApigEvents { const disassociateUsagePlan = require('./lib/hack/disassociateUsagePlan') .disassociateUsagePlan; - return BbPromise.bind(this) - .then(validate) - .then(disassociateUsagePlan); + return BbPromise.bind(this).then(validate).then(disassociateUsagePlan); }, }; } diff --git a/lib/plugins/aws/package/compile/events/apiGateway/lib/apiKeys.js b/lib/plugins/aws/package/compile/events/apiGateway/lib/apiKeys.js index b1c27d16802..02d4b1b049e 100644 --- a/lib/plugins/aws/package/compile/events/apiGateway/lib/apiKeys.js +++ b/lib/plugins/aws/package/compile/events/apiGateway/lib/apiKeys.js @@ -37,7 +37,7 @@ module.exports = { if (apiKeys) { const resources = this.serverless.service.provider.compiledCloudFormationTemplate.Resources; let keyNumber = 0; - apiKeys.forEach(apiKeyDefinition => { + apiKeys.forEach((apiKeyDefinition) => { // if multiple API key types are used const name = Object.keys(apiKeyDefinition)[0]; const usagePlan = @@ -46,10 +46,10 @@ module.exports = { if ( _.isObject(apiKeyDefinition) && Array.isArray(usagePlan) && - _.flatten(usagePlan.map(item => Object.keys(item))).includes(name) + _.flatten(usagePlan.map((item) => Object.keys(item))).includes(name) ) { keyNumber = 0; - apiKeyDefinition[name].forEach(key => { + apiKeyDefinition[name].forEach((key) => { keyNumber += 1; const apiKeyLogicalId = this.provider.naming.getApiKeyLogicalId(keyNumber, name); const resourceTemplate = createApiKeyResource(this, key); diff --git a/lib/plugins/aws/package/compile/events/apiGateway/lib/authorizers.js b/lib/plugins/aws/package/compile/events/apiGateway/lib/authorizers.js index 33637cbb05c..f81d35c23c1 100644 --- a/lib/plugins/aws/package/compile/events/apiGateway/lib/authorizers.js +++ b/lib/plugins/aws/package/compile/events/apiGateway/lib/authorizers.js @@ -6,7 +6,7 @@ const awsArnRegExs = require('../../../../../utils/arnRegularExpressions'); module.exports = { compileAuthorizers() { - this.validated.events.forEach(event => { + this.validated.events.forEach((event) => { if (event.http.authorizer && event.http.authorizer.arn) { const authorizer = event.http.authorizer; const authorizerProperties = { diff --git a/lib/plugins/aws/package/compile/events/apiGateway/lib/cors.js b/lib/plugins/aws/package/compile/events/apiGateway/lib/cors.js index 6e0017da058..542ccd0140f 100644 --- a/lib/plugins/aws/package/compile/events/apiGateway/lib/cors.js +++ b/lib/plugins/aws/package/compile/events/apiGateway/lib/cors.js @@ -18,7 +18,7 @@ module.exports = { let origins = config.origins && Array.isArray(config.origins) ? config.origins : undefined; if (origin && origin.indexOf(',') !== -1) { - origins = origin.split(',').map(a => a.trim()); + origins = origin.split(',').map((a) => a.trim()); } if (Array.isArray(origins) && origins.length) { @@ -87,7 +87,7 @@ module.exports = { generateCorsMethodResponses(preflightHeaders) { const methodResponseHeaders = {}; - Object.keys(preflightHeaders).forEach(header => { + Object.keys(preflightHeaders).forEach((header) => { methodResponseHeaders[`method.response.header.${header}`] = true; }); @@ -121,7 +121,7 @@ module.exports = { }, regexifyWildcards(orig) { - return orig.map(str => str.replace(/\./g, '[.]').replace('*', '.+')); + return orig.map((str) => str.replace(/\./g, '[.]').replace('*', '.+')); }, generateCorsResponseTemplate(origins) { diff --git a/lib/plugins/aws/package/compile/events/apiGateway/lib/hack/disassociateUsagePlan.js b/lib/plugins/aws/package/compile/events/apiGateway/lib/hack/disassociateUsagePlan.js index 174e73f88a3..f3d942fb5e8 100644 --- a/lib/plugins/aws/package/compile/events/apiGateway/lib/hack/disassociateUsagePlan.js +++ b/lib/plugins/aws/package/compile/events/apiGateway/lib/hack/disassociateUsagePlan.js @@ -19,18 +19,18 @@ module.exports = { }), this.provider.request('APIGateway', 'getUsagePlans', {}), ]) - .then(data => - data[1].items.filter(item => + .then((data) => + data[1].items.filter((item) => item.apiStages - .map(apistage => apistage.apiId) + .map((apistage) => apistage.apiId) .includes(data[0].StackResourceDetail.PhysicalResourceId) ) ) - .then(items => + .then((items) => BbPromise.all( _.flattenDeep( - items.map(item => - item.apiStages.map(apiStage => + items.map((item) => + item.apiStages.map((apiStage) => this.provider.request('APIGateway', 'updateUsagePlan', { usagePlanId: item.id, patchOperations: [ diff --git a/lib/plugins/aws/package/compile/events/apiGateway/lib/hack/updateStage.js b/lib/plugins/aws/package/compile/events/apiGateway/lib/hack/updateStage.js index 0ca5917f79b..f0245b66cb9 100644 --- a/lib/plugins/aws/package/compile/events/apiGateway/lib/hack/updateStage.js +++ b/lib/plugins/aws/package/compile/events/apiGateway/lib/hack/updateStage.js @@ -101,7 +101,7 @@ module.exports = { function resolveAccountInfo() { // eslint-disable-next-line no-return-assign - return this.provider.getAccountInfo().then(account => { + return this.provider.getAccountInfo().then((account) => { this.accountId = account.accountId; this.partition = account.partition; }); @@ -110,13 +110,13 @@ function resolveAccountInfo() { function resolveApiGatewayResource(resources) { const apiGatewayResources = _.pickBy( resources, - resource => resource.Type === 'AWS::ApiGateway::RestApi' + (resource) => resource.Type === 'AWS::ApiGateway::RestApi' ); const apiGatewayResourcesIds = Object.keys(apiGatewayResources); if (apiGatewayResourcesIds.length !== 1) return null; const apiGatewayResourceId = apiGatewayResourcesIds[0]; if ( - !Object.keys(resources).some(key => { + !Object.keys(resources).some((key) => { const resource = resources[key]; if (resource.Type !== 'AWS::ApiGateway::Deployment') return false; if (!resource.Properties || !resource.Properties.RestApiId) return false; @@ -129,7 +129,7 @@ function resolveApiGatewayResource(resources) { } function resolveRestApiId() { - return new BbPromise(resolve => { + return new BbPromise((resolve) => { const provider = this.state.service.provider; const externalRestApiId = provider.apiGateway && provider.apiGateway.restApiId; if (externalRestApiId) { @@ -152,15 +152,17 @@ function resolveRestApiId() { const apiName = apiGatewayResource ? apiGatewayResource.Properties.Name : provider.apiName || `${this.options.stage}-${this.state.service.service}`; - const resolveFromAws = position => - this.provider.request('APIGateway', 'getRestApis', { position, limit: 500 }).then(result => { - const restApi = result.items.find(api => api.name === apiName); - if (restApi) return restApi.id; - if (result.position) return resolveFromAws(result.position); - return null; - }); + const resolveFromAws = (position) => + this.provider + .request('APIGateway', 'getRestApis', { position, limit: 500 }) + .then((result) => { + const restApi = result.items.find((api) => api.name === apiName); + if (restApi) return restApi.id; + if (result.position) return resolveFromAws(result.position); + return null; + }); resolve(resolveFromAws()); - }).then(restApiId => { + }).then((restApiId) => { this.apiGatewayRestApiId = restApiId; }); } @@ -173,7 +175,7 @@ function resolveStage() { restApiId, stageName: this.options.stage, }) - .then(res => { + .then((res) => { this.apiGatewayStageState = res; }) .catch(() => { @@ -190,7 +192,7 @@ function resolveDeploymentId() { restApiId, limit: 500, }) - .then(res => { + .then((res) => { if (res.items.length) { // there will ever only be 1 deployment associated const deployment = res.items.shift(); @@ -198,7 +200,7 @@ function resolveDeploymentId() { } return null; }) - .then(deploymentId => { + .then((deploymentId) => { this.apiGatewayDeploymentId = deploymentId; }); } @@ -317,12 +319,12 @@ function handleLogs() { function handleTags() { if (!this.hasTagsConfigured) return; const provider = this.state.service.provider; - const tagsMerged = _.mapValues(Object.assign({}, provider.stackTags, provider.tags), v => + const tagsMerged = _.mapValues(Object.assign({}, provider.stackTags, provider.tags), (v) => String(v) ); const currentTags = this.apiGatewayStageState.tags || {}; const tagKeysToBeRemoved = Object.keys(currentTags).filter( - currentKey => typeof tagsMerged[currentKey] !== 'string' + (currentKey) => typeof tagsMerged[currentKey] !== 'string' ); const restApiId = this.apiGatewayRestApiId; @@ -346,14 +348,14 @@ function handleTags() { } function addTags() { - const requests = this.apiGatewayTagResourceParams.map(tagResourceParam => + const requests = this.apiGatewayTagResourceParams.map((tagResourceParam) => this.provider.request('APIGateway', 'tagResource', tagResourceParam) ); return BbPromise.all(requests); } function removeTags() { - const requests = this.apiGatewayUntagResourceParams.map(untagResourceParam => + const requests = this.apiGatewayUntagResourceParams.map((untagResourceParam) => this.provider.request('APIGateway', 'untagResource', untagResourceParam) ); return BbPromise.all(requests); diff --git a/lib/plugins/aws/package/compile/events/apiGateway/lib/method/index.js b/lib/plugins/aws/package/compile/events/apiGateway/lib/method/index.js index f89cac963b0..d5bd8b7b74a 100644 --- a/lib/plugins/aws/package/compile/events/apiGateway/lib/method/index.js +++ b/lib/plugins/aws/package/compile/events/apiGateway/lib/method/index.js @@ -7,7 +7,7 @@ module.exports = { compileMethods() { this.permissionMapping = []; - this.validated.events.forEach(event => { + this.validated.events.forEach((event) => { const resourceId = this.getResourceId(event.http.path); const resourceName = this.getResourceName(event.http.path); @@ -74,7 +74,7 @@ module.exports = { let extraCognitoPoolClaims; if (event.http.authorizer) { const claims = event.http.authorizer.claims || []; - extraCognitoPoolClaims = claims.map(claim => { + extraCognitoPoolClaims = claims.map((claim) => { if (typeof claim === 'string') { const colonIndex = claim.indexOf(':'); if (colonIndex !== -1) { diff --git a/lib/plugins/aws/package/compile/events/apiGateway/lib/method/responses.js b/lib/plugins/aws/package/compile/events/apiGateway/lib/method/responses.js index 83e668ab1a1..5a178acfe26 100644 --- a/lib/plugins/aws/package/compile/events/apiGateway/lib/method/responses.js +++ b/lib/plugins/aws/package/compile/events/apiGateway/lib/method/responses.js @@ -66,7 +66,7 @@ module.exports = { getMethodResponseHeaders(headers) { const methodResponseHeaders = {}; - Object.keys(headers).forEach(header => { + Object.keys(headers).forEach((header) => { methodResponseHeaders[`method.response.header.${header}`] = true; }); diff --git a/lib/plugins/aws/package/compile/events/apiGateway/lib/resources.js b/lib/plugins/aws/package/compile/events/apiGateway/lib/resources.js index f848fcbeabe..ffb802d9872 100644 --- a/lib/plugins/aws/package/compile/events/apiGateway/lib/resources.js +++ b/lib/plugins/aws/package/compile/events/apiGateway/lib/resources.js @@ -8,7 +8,7 @@ module.exports = { this.apiGatewayResources = this.getResourcePaths(); // ['users', 'users/create', 'users/create/something'] - Object.keys(this.apiGatewayResources).forEach(path => { + Object.keys(this.apiGatewayResources).forEach((path) => { const resource = this.apiGatewayResources[path]; if (resource.resourceId) { return; @@ -44,7 +44,7 @@ module.exports = { r[node.path].name = self.provider.naming.normalizePath(node.path); } - node.children.forEach(child => getNodePaths(result, child)); + node.children.forEach((child) => getNodePaths(result, child)); } return trees.reduce((result, tree) => { @@ -68,7 +68,7 @@ module.exports = { if (node.parent.children.length <= 1) { n.parent.children = []; } else { - n.parent.children = node.parent.children.filter(c => c.path !== n.path); + n.parent.children = node.parent.children.filter((c) => c.path !== n.path); n.parent.isCut = true; } n.parent = null; @@ -88,13 +88,13 @@ module.exports = { n.name = resource.name; if (resource.resourceId) { n.resourceId = resource.resourceId; - if (predefinedResourceNodes.every(iter => iter.path !== n.path)) { + if (predefinedResourceNodes.every((iter) => iter.path !== n.path)) { predefinedResourceNodes.push(node); } } if (isMethod && !node.hasMethod) { n.hasMethod = true; - if (methodNodes.every(iter => iter.path !== n.path)) { + if (methodNodes.every((iter) => iter.path !== n.path)) { methodNodes.push(node); } } @@ -105,7 +105,7 @@ module.exports = { pathParts.forEach((pathPart, index) => { currentPath = currentPath ? `${currentPath}/${pathPart}` : pathPart; - root = root || trees.find(node => node.path === currentPath); + root = root || trees.find((node) => node.path === currentPath); parent = parent || root; let node; @@ -114,7 +114,7 @@ module.exports = { applyNodeResource(parent, pathParts, index); return; } else if (parent.children.length > 0) { - node = parent.children.find(n => n.path === currentPath); + node = parent.children.find((n) => n.path === currentPath); if (node) { applyNodeResource(node, pathParts, index); return; @@ -145,7 +145,7 @@ module.exports = { } predefinedResources.forEach(applyResource); - this.validated.events.forEach(event => { + this.validated.events.forEach((event) => { if (event.http.path) { applyResource(event.http, true); } @@ -158,8 +158,8 @@ module.exports = { // if all methods have resource ID already, no need to validate resource trees if ( - this.validated.events.every(event => - predefinedResourceNodes.some(node => node.path === event.http.path) + this.validated.events.every((event) => + predefinedResourceNodes.some((node) => node.path === event.http.path) ) ) { return predefinedResources.reduce((resourceMap, resource) => { @@ -198,12 +198,12 @@ module.exports = { } // get branches that begin from root resource - methodNodes.forEach(node => { + methodNodes.forEach((node) => { let iter = node; while (iter) { if (iter.resourceId) { cutBranch(iter); - if (validatedTrees.every(t => t.path !== node.path)) { + if (validatedTrees.every((t) => t.path !== node.path)) { validatedTrees.push(iter); } diff --git a/lib/plugins/aws/package/compile/events/apiGateway/lib/stage.js b/lib/plugins/aws/package/compile/events/apiGateway/lib/stage.js index 46e8e30c5f3..22aae9041d6 100644 --- a/lib/plugins/aws/package/compile/events/apiGateway/lib/stage.js +++ b/lib/plugins/aws/package/compile/events/apiGateway/lib/stage.js @@ -24,7 +24,7 @@ module.exports = { // Tags const tagsMerged = Object.assign({}, provider.stackTags, provider.tags); - const Tags = Object.entries(tagsMerged).map(pair => ({ + const Tags = Object.entries(tagsMerged).map((pair) => ({ Key: pair[0], Value: pair[1], })); diff --git a/lib/plugins/aws/package/compile/events/apiGateway/lib/usagePlan.js b/lib/plugins/aws/package/compile/events/apiGateway/lib/usagePlan.js index b3cdbd82fb2..f7ef7aec121 100644 --- a/lib/plugins/aws/package/compile/events/apiGateway/lib/usagePlan.js +++ b/lib/plugins/aws/package/compile/events/apiGateway/lib/usagePlan.js @@ -109,7 +109,7 @@ module.exports = { this.apiGatewayUsagePlanNames = []; if (Array.isArray(usagePlan)) { - usagePlan.forEach(planObject => { + usagePlan.forEach((planObject) => { const usagePlanName = Object.keys(planObject)[0]; const logicalId = this.provider.naming.getUsagePlanLogicalId(usagePlanName); const resourceTemplate = createUsagePlanResource(this, usagePlanName); diff --git a/lib/plugins/aws/package/compile/events/apiGateway/lib/usagePlanKeys.js b/lib/plugins/aws/package/compile/events/apiGateway/lib/usagePlanKeys.js index ce9f8bf0e28..414b16b728d 100644 --- a/lib/plugins/aws/package/compile/events/apiGateway/lib/usagePlanKeys.js +++ b/lib/plugins/aws/package/compile/events/apiGateway/lib/usagePlanKeys.js @@ -31,7 +31,7 @@ module.exports = { const resources = this.serverless.service.provider.compiledCloudFormationTemplate.Resources; let keyNumber = 0; - apiKeys.forEach(apiKeyDefinition => { + apiKeys.forEach((apiKeyDefinition) => { // if multiple API key types are used const apiKey = Object.entries(apiKeyDefinition)[0]; const name = apiKey[0]; diff --git a/lib/plugins/aws/package/compile/events/apiGateway/lib/validate.js b/lib/plugins/aws/package/compile/events/apiGateway/lib/validate.js index 209b7da780d..41111bf3f15 100644 --- a/lib/plugins/aws/package/compile/events/apiGateway/lib/validate.js +++ b/lib/plugins/aws/package/compile/events/apiGateway/lib/validate.js @@ -41,7 +41,7 @@ module.exports = { const corsPreflight = {}; Object.entries(this.serverless.service.functions).forEach(([functionName, functionObject]) => { - (functionObject.events || []).forEach(event => { + (functionObject.events || []).forEach((event) => { if (event.http) { const http = this.getHttp(event); @@ -117,7 +117,7 @@ module.exports = { const requestWarningMessage = [ `Warning! You're using the ${http.integration} in combination with a request`, ` configuration in your function "${functionName}". Only the `, - allowedKeys.map(value => `request.${value}`).join(', '), + allowedKeys.map((value) => `request.${value}`).join(', '), ` configs are available in conjunction with ${http.integration}.`, ' Serverless will remove this configuration automatically', ' before deployment.', @@ -398,7 +398,7 @@ module.exports = { const parameters = {}; // only these locations are currently supported const locations = ['querystrings', 'paths', 'headers']; - locations.forEach(location => { + locations.forEach((location) => { // strip the plural s const singular = location.substring(0, location.length - 1); const parameter = httpRequest.parameters[location]; @@ -435,7 +435,7 @@ module.exports = { if (response.statusCodes) { response.statusCodes = Object.assign({}, response.statusCodes); - if (!Object.values(response.statusCodes).some(code => code.pattern === '')) { + if (!Object.values(response.statusCodes).some((code) => code.pattern === '')) { response.statusCodes['200'] = DEFAULT_STATUS_CODES['200']; } } else { diff --git a/lib/plugins/aws/package/compile/events/cloudFront.js b/lib/plugins/aws/package/compile/events/cloudFront.js index 340909d4bd7..4dc7108481c 100644 --- a/lib/plugins/aws/package/compile/events/cloudFront.js +++ b/lib/plugins/aws/package/compile/events/cloudFront.js @@ -228,9 +228,9 @@ class AwsCompileCloudFrontEvents { let isEventUsed = false; const funcKeys = this.serverless.service.getAllFunctions(); if (funcKeys.length) { - isEventUsed = funcKeys.some(funcKey => { + isEventUsed = funcKeys.some((funcKey) => { const func = this.serverless.service.getFunction(funcKey); - return func.events && func.events.find(e => Object.keys(e)[0] === 'cloudFront'); + return func.events && func.events.find((e) => Object.keys(e)[0] === 'cloudFront'); }); } if (isEventUsed) { @@ -244,7 +244,7 @@ class AwsCompileCloudFrontEvents { } validate() { - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObj = this.serverless.service.getFunction(functionName); functionObj.events.forEach(({ cloudFront }) => { if (!cloudFront) return; @@ -266,9 +266,9 @@ class AwsCompileCloudFrontEvents { prepareFunctions() { // Lambda@Edge functions need to be versioned - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObj = this.serverless.service.getFunction(functionName); - if (functionObj.events.find(event => event.cloudFront)) { + if (functionObj.events.find((event) => event.cloudFront)) { // ensure that functions are versioned Object.assign(functionObj, { versionFunction: true }); // set the maximum memory size if not explicitly configured @@ -364,13 +364,13 @@ class AwsCompileCloudFrontEvents { } const unusedUserDefinedCachePolicies = new Set(this.cachePolicies); - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObj = this.serverless.service.getFunction(functionName); if (functionObj.events) { - functionObj.events.forEach(event => { + functionObj.events.forEach((event) => { if (event.cloudFront) { const lambdaFunctionLogicalId = Object.keys(Resources).find( - key => + (key) => Resources[key].Type === 'AWS::Lambda::Function' && Resources[key].Properties.FunctionName === functionObj.name ); @@ -382,7 +382,7 @@ class AwsCompileCloudFrontEvents { // Retain Lambda@Edge functions to avoid issues when removing the CloudFormation stack Object.assign(Resources[lambdaFunctionLogicalId], { DeletionPolicy: 'Retain' }); - const lambdaVersionLogicalId = Object.keys(Resources).find(key => { + const lambdaVersionLogicalId = Object.keys(Resources).find((key) => { const resource = Resources[key]; if (resource.Type !== 'AWS::Lambda::Version') return false; return _.get(resource, 'Properties.FunctionName.Ref') === lambdaFunctionLogicalId; @@ -394,7 +394,7 @@ class AwsCompileCloudFrontEvents { : undefined; let origin = createOrigin(event.cloudFront.origin, this.provider.naming); - const existingOrigin = origins.find(o => o.Id === origin.Id); + const existingOrigin = origins.find((o) => o.Id === origin.Id); if (!existingOrigin) { origins.push(origin); @@ -483,7 +483,7 @@ class AwsCompileCloudFrontEvents { } const existingBehaviour = behaviors.find( - o => + (o) => o.PathPattern === behavior.PathPattern && o.TargetOriginId === behavior.TargetOriginId ); @@ -502,7 +502,7 @@ class AwsCompileCloudFrontEvents { } }); - unusedUserDefinedCachePolicies.forEach(unusedUserDefinedCachePolicy => { + unusedUserDefinedCachePolicies.forEach((unusedUserDefinedCachePolicy) => { this.serverless.cli.log( `WARNING: provider.cloudFront.cachePolicies.${unusedUserDefinedCachePolicy} ` + 'not used by any cloudFront event configuration' @@ -534,7 +534,7 @@ class AwsCompileCloudFrontEvents { // Check if all event types in every behavior is unique if ( - behaviors.some(o => { + behaviors.some((o) => { return ( o.LambdaFunctionAssociations.length !== _.uniqBy(o.LambdaFunctionAssociations, 'EventType').length @@ -611,7 +611,7 @@ class AwsCompileCloudFrontEvents { ); } else { const lambdaAssumeStatement = Resources.IamRoleLambdaExecution.Properties.AssumeRolePolicyDocument.Statement.find( - statement => statement.Principal.Service.includes('lambda.amazonaws.com') + (statement) => statement.Principal.Service.includes('lambda.amazonaws.com') ); if (lambdaAssumeStatement) { lambdaAssumeStatement.Principal.Service.push('edgelambda.amazonaws.com'); diff --git a/lib/plugins/aws/package/compile/events/cloudWatchEvent.js b/lib/plugins/aws/package/compile/events/cloudWatchEvent.js index 94c9f1c8410..363721b474f 100644 --- a/lib/plugins/aws/package/compile/events/cloudWatchEvent.js +++ b/lib/plugins/aws/package/compile/events/cloudWatchEvent.js @@ -40,12 +40,12 @@ class AwsCompileCloudWatchEventEvents { } compileCloudWatchEventEvents() { - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObj = this.serverless.service.getFunction(functionName); let cloudWatchEventNumberInFunction = 0; if (functionObj.events) { - functionObj.events.forEach(event => { + functionObj.events.forEach((event) => { if (event.cloudwatchEvent) { cloudWatchEventNumberInFunction++; let State; diff --git a/lib/plugins/aws/package/compile/events/cloudWatchLog.js b/lib/plugins/aws/package/compile/events/cloudWatchLog.js index 63cb9a7ce4e..58ee3899857 100644 --- a/lib/plugins/aws/package/compile/events/cloudWatchLog.js +++ b/lib/plugins/aws/package/compile/events/cloudWatchLog.js @@ -30,14 +30,14 @@ class AwsCompileCloudWatchLogEvents { compileCloudWatchLogEvents() { const logGroupNames = []; - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObj = this.serverless.service.getFunction(functionName); let cloudWatchLogNumberInFunction = 0; if (functionObj.events) { const logGroupNamesThisFunction = []; - functionObj.events.forEach(event => { + functionObj.events.forEach((event) => { if (event.cloudwatchLog) { cloudWatchLogNumberInFunction++; let LogGroupName; diff --git a/lib/plugins/aws/package/compile/events/cognitoUserPool.js b/lib/plugins/aws/package/compile/events/cognitoUserPool.js index e6102ed03fd..f612e960b21 100644 --- a/lib/plugins/aws/package/compile/events/cognitoUserPool.js +++ b/lib/plugins/aws/package/compile/events/cognitoUserPool.js @@ -46,10 +46,10 @@ class AwsCompileCognitoUserPoolEvents { newCognitoUserPools() { const { service } = this.serverless; - service.getAllFunctions().forEach(functionName => { + service.getAllFunctions().forEach((functionName) => { const functionObj = service.getFunction(functionName); if (functionObj.events) { - functionObj.events.forEach(event => { + functionObj.events.forEach((event) => { if (event.cognitoUserPool) { // return immediately if it's an existing Cognito User Pool event since we treat them differently if (event.cognitoUserPool.existing) return null; @@ -59,9 +59,9 @@ class AwsCompileCognitoUserPoolEvents { const userPools = result.userPools; // Generate CloudFormation templates for Cognito User Pool changes - userPools.forEach(poolName => { + userPools.forEach((poolName) => { const currentPoolTriggerFunctions = cognitoUserPoolTriggerFunctions.filter( - triggerFn => triggerFn.poolName === poolName + (triggerFn) => triggerFn.poolName === poolName ); const userPoolCFResource = this.generateTemplateForPool( poolName, @@ -75,7 +75,7 @@ class AwsCompileCognitoUserPoolEvents { }); // Generate CloudFormation templates for IAM permissions to allow Cognito to trigger Lambda - cognitoUserPoolTriggerFunctions.forEach(cognitoUserPoolTriggerFunction => { + cognitoUserPoolTriggerFunctions.forEach((cognitoUserPoolTriggerFunction) => { const userPoolLogicalId = this.provider.naming.getCognitoUserPoolLogicalId( cognitoUserPoolTriggerFunction.poolName ); @@ -128,7 +128,7 @@ class AwsCompileCognitoUserPoolEvents { // used to keep track of the custom resources created for each Cognito User Pool const poolResources = {}; - service.getAllFunctions().forEach(functionName => { + service.getAllFunctions().forEach((functionName) => { let numEventsForFunc = 0; let currentPoolName = null; let funcUsesExistingCognitoUserPool = false; @@ -136,7 +136,7 @@ class AwsCompileCognitoUserPoolEvents { const FunctionName = functionObj.name; if (functionObj.events) { - functionObj.events.forEach(event => { + functionObj.events.forEach((event) => { if (event.cognitoUserPool && event.cognitoUserPool.existing) { numEventsForFunc++; const { pool, trigger } = event.cognitoUserPool; @@ -234,7 +234,7 @@ class AwsCompileCognitoUserPoolEvents { // check if we need to add DependsOn clauses in case more than 1 // custom resources are created for one Cognito User Pool (to avoid race conditions) if (Object.keys(poolResources).length > 0) { - Object.keys(poolResources).forEach(pool => { + Object.keys(poolResources).forEach((pool) => { const resources = poolResources[pool]; if (resources.length > 1) { resources.forEach((currResourceLogicalId, idx) => { @@ -259,11 +259,11 @@ class AwsCompileCognitoUserPoolEvents { const cognitoUserPoolTriggerFunctions = []; // Iterate through all functions declared in `serverless.yml` - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObj = this.serverless.service.getFunction(functionName); if (functionObj.events) { - functionObj.events.forEach(event => { + functionObj.events.forEach((event) => { if (event.cognitoUserPool) { if (event.cognitoUserPool.existing) return; @@ -301,7 +301,7 @@ class AwsCompileCognitoUserPoolEvents { const userPoolLogicalId = this.provider.naming.getCognitoUserPoolLogicalId(poolName); // Attach `DependsOn` for any relevant Lambdas - const DependsOn = currentPoolTriggerFunctions.map(value => + const DependsOn = currentPoolTriggerFunctions.map((value) => this.provider.naming.getLambdaLogicalId(value.functionName) ); @@ -322,9 +322,9 @@ class AwsCompileCognitoUserPoolEvents { const cognitoUserPoolTriggerFunctions = result.cognitoUserPoolTriggerFunctions; const userPools = result.userPools; - userPools.forEach(poolName => { + userPools.forEach((poolName) => { const currentPoolTriggerFunctions = cognitoUserPoolTriggerFunctions.filter( - triggerFn => triggerFn.poolName === poolName + (triggerFn) => triggerFn.poolName === poolName ); const userPoolLogicalId = this.provider.naming.getCognitoUserPoolLogicalId(poolName); diff --git a/lib/plugins/aws/package/compile/events/eventBridge/index.js b/lib/plugins/aws/package/compile/events/eventBridge/index.js index 389b5c91034..0211cd002c3 100644 --- a/lib/plugins/aws/package/compile/events/eventBridge/index.js +++ b/lib/plugins/aws/package/compile/events/eventBridge/index.js @@ -61,7 +61,7 @@ class AwsCompileEventBridgeEvents { let hasEventBusesIamRoleStatement = false; let anyFuncUsesEventBridge = false; - service.getAllFunctions().forEach(functionName => { + service.getAllFunctions().forEach((functionName) => { const functionObj = service.getFunction(functionName); const FunctionName = functionObj.name; diff --git a/lib/plugins/aws/package/compile/events/httpApi.js b/lib/plugins/aws/package/compile/events/httpApi.js index 4d1ecd2eb8e..a50009aed27 100644 --- a/lib/plugins/aws/package/compile/events/httpApi.js +++ b/lib/plugins/aws/package/compile/events/httpApi.js @@ -31,7 +31,7 @@ const defaultCors = { ]), }; -const toSet = item => new Set(Array.isArray(item) ? item : [item]); +const toSet = (item) => new Set(Array.isArray(item) ? item : [item]); class HttpApiEvents { constructor(serverless) { @@ -230,7 +230,7 @@ class HttpApiEvents { Object.defineProperties( HttpApiEvents.prototype, memoizeeMethods({ - resolveConfiguration: d(function() { + resolveConfiguration: d(function () { const routes = new Map(); const providerConfig = this.serverless.service.provider; const userConfig = providerConfig.httpApi || {}; @@ -361,8 +361,8 @@ Object.defineProperties( if ( Array.from( allowedMethods, - allowedMethod => `${allowedMethod} ${path}` - ).some(duplicateRouteKey => routes.has(duplicateRouteKey)) + (allowedMethod) => `${allowedMethod} ${path}` + ).some((duplicateRouteKey) => routes.has(duplicateRouteKey)) ) { throw new this.serverless.classes.Error( `Duplicate method for "${path}" path in function ${functionName} for httpApi event in serverless.yml`, @@ -455,7 +455,7 @@ Object.defineProperties( routeTargetData.timeout = Math.min(functionTimeout + 0.5, 29); } }), - compileIntegration: d(function(routeTargetData) { + compileIntegration: d(function (routeTargetData) { const providerConfig = this.serverless.service.provider; const userConfig = providerConfig.httpApi || {}; @@ -475,7 +475,7 @@ Object.defineProperties( Properties: properties, }; }), - compileLambdaPermissions: d(function(routeTargetData) { + compileLambdaPermissions: d(function (routeTargetData) { this.cfTemplate.Resources[ this.provider.naming.getLambdaHttpApiPermissionLogicalId(routeTargetData.functionName) ] = { diff --git a/lib/plugins/aws/package/compile/events/iot.js b/lib/plugins/aws/package/compile/events/iot.js index 38409919365..4031f8cb486 100644 --- a/lib/plugins/aws/package/compile/events/iot.js +++ b/lib/plugins/aws/package/compile/events/iot.js @@ -37,12 +37,12 @@ class AwsCompileIoTEvents { } compileIoTEvents() { - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObj = this.serverless.service.getFunction(functionName); let iotNumberInFunction = 0; if (functionObj.events) { - functionObj.events.forEach(event => { + functionObj.events.forEach((event) => { if (event.iot) { iotNumberInFunction++; diff --git a/lib/plugins/aws/package/compile/events/iotFleetProvisioning.js b/lib/plugins/aws/package/compile/events/iotFleetProvisioning.js index 87794ea271d..fff6ab21d96 100644 --- a/lib/plugins/aws/package/compile/events/iotFleetProvisioning.js +++ b/lib/plugins/aws/package/compile/events/iotFleetProvisioning.js @@ -25,17 +25,17 @@ class AwsCompileIotFleetProvisioningEvents { } compileIotFleetProvisioningEvents() { - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObj = this.serverless.service.getFunction(functionName); - if (functionObj.events.filter(event => event.iotFleetProvisioning).length > 1) { + if (functionObj.events.filter((event) => event.iotFleetProvisioning).length > 1) { throw new ServerlessError( `Found more than one iotFleetProvision event for function ${functionName}`, 'MULTIPLE_IOT_PROVISIONING_TEMPLATE_HOOK' ); } - functionObj.events.forEach(event => { + functionObj.events.forEach((event) => { if (!event.iotFleetProvisioning) return; const provisioningRoleArn = event.iotFleetProvisioning.provisioningRoleArn; diff --git a/lib/plugins/aws/package/compile/events/lib/ensureApiGatewayCloudWatchRole.js b/lib/plugins/aws/package/compile/events/lib/ensureApiGatewayCloudWatchRole.js index 503cbcedcee..305ed19cc00 100644 --- a/lib/plugins/aws/package/compile/events/lib/ensureApiGatewayCloudWatchRole.js +++ b/lib/plugins/aws/package/compile/events/lib/ensureApiGatewayCloudWatchRole.js @@ -4,7 +4,7 @@ const { memoize } = require('lodash'); const BbPromise = require('bluebird'); const { addCustomResourceToService } = require('../../../../customResources'); -module.exports = memoize(provider => +module.exports = memoize((provider) => BbPromise.try(() => { // There may be a specific role ARN provided in the configuration const config = provider.serverless.service.provider; diff --git a/lib/plugins/aws/package/compile/events/msk/getMskClusterNameToken.js b/lib/plugins/aws/package/compile/events/msk/getMskClusterNameToken.js index ce0fdd5d37a..4f6804a23aa 100644 --- a/lib/plugins/aws/package/compile/events/msk/getMskClusterNameToken.js +++ b/lib/plugins/aws/package/compile/events/msk/getMskClusterNameToken.js @@ -1,6 +1,6 @@ 'use strict'; -const getMskClusterNameToken = eventSourceArn => { +const getMskClusterNameToken = (eventSourceArn) => { if (eventSourceArn['Fn::ImportValue']) { return eventSourceArn['Fn::ImportValue']; } else if (eventSourceArn.Ref) { diff --git a/lib/plugins/aws/package/compile/events/msk/index.js b/lib/plugins/aws/package/compile/events/msk/index.js index 3d593e1e644..42afca5c406 100644 --- a/lib/plugins/aws/package/compile/events/msk/index.js +++ b/lib/plugins/aws/package/compile/events/msk/index.js @@ -43,7 +43,7 @@ class AwsCompileMSKEvents { } compileMSKEvents() { - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObj = this.serverless.service.getFunction(functionName); const cfTemplate = this.serverless.service.provider.compiledCloudFormationTemplate; @@ -66,7 +66,7 @@ class AwsCompileMSKEvents { Resource: [], }; - functionObj.events.forEach(event => { + functionObj.events.forEach((event) => { if (event.msk) { const eventSourceArn = event.msk.arn; const topic = event.msk.topic; diff --git a/lib/plugins/aws/package/compile/events/s3/configSchema.js b/lib/plugins/aws/package/compile/events/s3/configSchema.js index 473b296e374..ef31596f6b1 100644 --- a/lib/plugins/aws/package/compile/events/s3/configSchema.js +++ b/lib/plugins/aws/package/compile/events/s3/configSchema.js @@ -337,7 +337,7 @@ module.exports = { 'NoncurrentVersionTransitions', 'Transition', 'Transitions', - ].map(field => ({ required: [field] })), + ].map((field) => ({ required: [field] })), additionalProperties: false, }, }, diff --git a/lib/plugins/aws/package/compile/events/s3/index.js b/lib/plugins/aws/package/compile/events/s3/index.js index 92a8890f9c4..59c1a446489 100644 --- a/lib/plugins/aws/package/compile/events/s3/index.js +++ b/lib/plugins/aws/package/compile/events/s3/index.js @@ -40,9 +40,7 @@ class AwsCompileS3Events { this.hooks = { 'package:compileEvents': () => { - return BbPromise.bind(this) - .then(this.newS3Buckets) - .then(this.existingS3Buckets); + return BbPromise.bind(this).then(this.newS3Buckets).then(this.existingS3Buckets); }, }; } @@ -53,11 +51,11 @@ class AwsCompileS3Events { const s3EnabledFunctions = []; const providerS3 = this.serverless.service.provider.s3 || {}; - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObj = this.serverless.service.getFunction(functionName); if (functionObj.events) { - functionObj.events.forEach(event => { + functionObj.events.forEach((event) => { if (event.s3) { // return immediately if it's an existing S3 event since we treat them differently if (event.s3.existing) return null; @@ -73,7 +71,7 @@ class AwsCompileS3Events { } if (event.s3.rules) { const rules = []; - event.s3.rules.forEach(rule => { + event.s3.rules.forEach((rule) => { const name = Object.keys(rule)[0]; const value = rule[name]; rules.push({ Name: name, Value: value }); @@ -182,9 +180,11 @@ class AwsCompileS3Events { }; // create the DependsOn properties for the buckets permissions (which are created later on) - const dependsOnToCreate = s3EnabledFunctions.filter(func => func.bucketName === bucketName); + const dependsOnToCreate = s3EnabledFunctions.filter( + (func) => func.bucketName === bucketName + ); - dependsOnToCreate.forEach(item => { + dependsOnToCreate.forEach((item) => { const lambdaPermissionLogicalId = this.provider.naming.getLambdaS3PermissionLogicalId( item.functionName, (bucketsMeta[item.bucketName] && bucketsMeta[item.bucketName].bucketRef) || @@ -210,7 +210,7 @@ class AwsCompileS3Events { // iterate over all functions with S3 events // and give S3 permission to invoke them all // by adding Lambda::Permission resource for each - s3EnabledFunctions.forEach(s3EnabledFunction => { + s3EnabledFunctions.forEach((s3EnabledFunction) => { const lambdaLogicalId = this.provider.naming.getLambdaLogicalId( s3EnabledFunction.functionName ); @@ -258,14 +258,14 @@ class AwsCompileS3Events { // used to keep track of the custom resources created for each bucket const bucketResources = {}; - service.getAllFunctions().forEach(functionName => { + service.getAllFunctions().forEach((functionName) => { let numEventsForFunc = 0; let currentBucketName = null; const functionObj = service.getFunction(functionName); const FunctionName = functionObj.name; if (functionObj.events) { - functionObj.events.forEach(event => { + functionObj.events.forEach((event) => { if (event.s3 && _.isObject(event.s3) && event.s3.existing) { numEventsForFunc++; let rules = null; @@ -284,7 +284,7 @@ class AwsCompileS3Events { throw new this.serverless.classes.Error(errorMessage); } - rules = (event.s3.rules || []).map(rule => { + rules = (event.s3.rules || []).map((rule) => { const key = Object.keys(rule)[0]; const value = rule[key]; return { @@ -376,7 +376,7 @@ class AwsCompileS3Events { // check if we need to add DependsOn clauses in case more than 1 // custom resources are created for one bucket (to avoid race conditions) if (Object.keys(bucketResources).length > 0) { - Object.keys(bucketResources).forEach(bucket => { + Object.keys(bucketResources).forEach((bucket) => { const resources = bucketResources[bucket]; if (resources.length > 1) { resources.forEach((currResourceLogicalId, idx) => { diff --git a/lib/plugins/aws/package/compile/events/schedule.js b/lib/plugins/aws/package/compile/events/schedule.js index 961516de972..2fc78694f57 100644 --- a/lib/plugins/aws/package/compile/events/schedule.js +++ b/lib/plugins/aws/package/compile/events/schedule.js @@ -70,12 +70,12 @@ class AwsCompileScheduledEvents { } compileScheduledEvents() { - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObj = this.serverless.service.getFunction(functionName); let scheduleNumberInFunction = 0; if (functionObj.events) { - functionObj.events.forEach(event => { + functionObj.events.forEach((event) => { if (event.schedule) { scheduleNumberInFunction++; let ScheduleExpression; diff --git a/lib/plugins/aws/package/compile/events/sns.js b/lib/plugins/aws/package/compile/events/sns.js index 1d3b76605d7..4bbac3ce6ea 100644 --- a/lib/plugins/aws/package/compile/events/sns.js +++ b/lib/plugins/aws/package/compile/events/sns.js @@ -55,11 +55,11 @@ class AwsCompileSNSEvents { compileSNSEvents() { const template = this.serverless.service.provider.compiledCloudFormationTemplate; - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObj = this.serverless.service.getFunction(functionName); if (functionObj.events) { - functionObj.events.forEach(event => { + functionObj.events.forEach((event) => { if (event.sns) { let topicArn; let topicName; @@ -76,7 +76,7 @@ class AwsCompileSNSEvents { const splitArn = topicArn .replace(/::/g, '@@') .split(':') - .map(s => s.replace(/@@/g, '::')); + .map((s) => s.replace(/@@/g, '::')); topicName = splitArn[splitArn.length - 1]; if (splitArn[3] !== this.options.region) { region = splitArn[3]; diff --git a/lib/plugins/aws/package/compile/events/sqs.js b/lib/plugins/aws/package/compile/events/sqs.js index ca4e9073037..0c3cdcdc9c6 100644 --- a/lib/plugins/aws/package/compile/events/sqs.js +++ b/lib/plugins/aws/package/compile/events/sqs.js @@ -31,7 +31,7 @@ class AwsCompileSQSEvents { } compileSQSEvents() { - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObj = this.serverless.service.getFunction(functionName); if (functionObj.events) { @@ -41,7 +41,7 @@ class AwsCompileSQSEvents { Resource: [], }; - functionObj.events.forEach(event => { + functionObj.events.forEach((event) => { if (event.sqs) { let EventSourceArn; let BatchSize = 10; @@ -57,7 +57,7 @@ class AwsCompileSQSEvents { EventSourceArn = event.sqs; } - const queueName = (function() { + const queueName = (function () { if (EventSourceArn['Fn::GetAtt']) { return EventSourceArn['Fn::GetAtt'][0]; } else if (EventSourceArn['Fn::ImportValue']) { diff --git a/lib/plugins/aws/package/compile/events/stream.js b/lib/plugins/aws/package/compile/events/stream.js index a2464e8fc3d..987c99c578a 100644 --- a/lib/plugins/aws/package/compile/events/stream.js +++ b/lib/plugins/aws/package/compile/events/stream.js @@ -89,7 +89,7 @@ class AwsCompileStreamEvents { } compileStreamEvents() { - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObj = this.serverless.service.getFunction(functionName); if (functionObj.events) { @@ -139,7 +139,7 @@ class AwsCompileStreamEvents { Resource: [], }; - functionObj.events.forEach(event => { + functionObj.events.forEach((event) => { if (event.stream) { let EventSourceArn; let BatchSize = 10; @@ -162,7 +162,7 @@ class AwsCompileStreamEvents { } const streamType = event.stream.type || EventSourceArn.split(':')[2]; - const streamName = (function() { + const streamName = (function () { if (EventSourceArn['Fn::GetAtt']) { return EventSourceArn['Fn::GetAtt'][0]; } else if (EventSourceArn['Fn::ImportValue']) { diff --git a/lib/plugins/aws/package/compile/events/websockets/lib/authorizers.js b/lib/plugins/aws/package/compile/events/websockets/lib/authorizers.js index ba277f7a735..88f78e282b9 100644 --- a/lib/plugins/aws/package/compile/events/websockets/lib/authorizers.js +++ b/lib/plugins/aws/package/compile/events/websockets/lib/authorizers.js @@ -5,7 +5,7 @@ const BbPromise = require('bluebird'); module.exports = { compileAuthorizers() { - this.validated.events.forEach(event => { + this.validated.events.forEach((event) => { if (!event.authorizer) { return; } diff --git a/lib/plugins/aws/package/compile/events/websockets/lib/deployment.js b/lib/plugins/aws/package/compile/events/websockets/lib/deployment.js index 1323a2f79b2..608ad352737 100644 --- a/lib/plugins/aws/package/compile/events/websockets/lib/deployment.js +++ b/lib/plugins/aws/package/compile/events/websockets/lib/deployment.js @@ -8,7 +8,7 @@ const pickWebsocketsTemplatePart = require('./pickWebsocketsTemplatePart'); module.exports = { compileDeployment() { const dependentResourceIds = _.flatten( - this.validated.events.map(event => { + this.validated.events.map((event) => { const result = []; if (event.routeResponseSelectionExpression) { result.push(this.provider.naming.getWebsocketsRouteResponseLogicalId(event.route)); diff --git a/lib/plugins/aws/package/compile/events/websockets/lib/integrations.js b/lib/plugins/aws/package/compile/events/websockets/lib/integrations.js index 5eaf0d25bba..7006151d83c 100644 --- a/lib/plugins/aws/package/compile/events/websockets/lib/integrations.js +++ b/lib/plugins/aws/package/compile/events/websockets/lib/integrations.js @@ -5,7 +5,7 @@ const BbPromise = require('bluebird'); module.exports = { compileIntegrations() { - this.validated.events.forEach(event => { + this.validated.events.forEach((event) => { const websocketsIntegrationLogicalId = this.provider.naming.getWebsocketsIntegrationLogicalId( event.functionName ); diff --git a/lib/plugins/aws/package/compile/events/websockets/lib/permissions.js b/lib/plugins/aws/package/compile/events/websockets/lib/permissions.js index 4899d03626d..d534ff8621b 100644 --- a/lib/plugins/aws/package/compile/events/websockets/lib/permissions.js +++ b/lib/plugins/aws/package/compile/events/websockets/lib/permissions.js @@ -5,7 +5,7 @@ const BbPromise = require('bluebird'); module.exports = { compilePermissions() { - this.validated.events.forEach(event => { + this.validated.events.forEach((event) => { const websocketApiId = this.provider.getApiGatewayWebsocketApiId(); const lambdaLogicalId = this.provider.naming.getLambdaLogicalId(event.functionName); diff --git a/lib/plugins/aws/package/compile/events/websockets/lib/routeResponses.js b/lib/plugins/aws/package/compile/events/websockets/lib/routeResponses.js index 6e079e807d1..2af12cb3968 100644 --- a/lib/plugins/aws/package/compile/events/websockets/lib/routeResponses.js +++ b/lib/plugins/aws/package/compile/events/websockets/lib/routeResponses.js @@ -2,7 +2,7 @@ module.exports = { compileRouteResponses() { - this.validated.events.forEach(event => { + this.validated.events.forEach((event) => { if (!event.routeResponseSelectionExpression) { return; } diff --git a/lib/plugins/aws/package/compile/events/websockets/lib/routes.js b/lib/plugins/aws/package/compile/events/websockets/lib/routes.js index f6ac3cef34b..b19febca63d 100644 --- a/lib/plugins/aws/package/compile/events/websockets/lib/routes.js +++ b/lib/plugins/aws/package/compile/events/websockets/lib/routes.js @@ -5,7 +5,7 @@ const BbPromise = require('bluebird'); module.exports = { compileRoutes() { - this.validated.events.forEach(event => { + this.validated.events.forEach((event) => { const websocketsIntegrationLogicalId = this.provider.naming.getWebsocketsIntegrationLogicalId( event.functionName ); diff --git a/lib/plugins/aws/package/compile/events/websockets/lib/validate.js b/lib/plugins/aws/package/compile/events/websockets/lib/validate.js index b5245ecc836..3638f09877c 100644 --- a/lib/plugins/aws/package/compile/events/websockets/lib/validate.js +++ b/lib/plugins/aws/package/compile/events/websockets/lib/validate.js @@ -7,13 +7,13 @@ module.exports = { validate() { const events = []; - const getAuthorizerNameFromArn = arn => { + const getAuthorizerNameFromArn = (arn) => { const splitArn = arn.split(':'); return splitArn[splitArn.length - 1]; }; Object.entries(this.serverless.service.functions).forEach(([functionName, functionObject]) => { - functionObject.events.forEach(event => { + functionObject.events.forEach((event) => { if (event.websocket) { // dealing with the extended object definition if (_.isObject(event.websocket)) { diff --git a/lib/plugins/aws/package/compile/functions.js b/lib/plugins/aws/package/compile/functions.js index 17ce961c08c..75d5cca32f8 100644 --- a/lib/plugins/aws/package/compile/functions.js +++ b/lib/plugins/aws/package/compile/functions.js @@ -62,9 +62,7 @@ class AwsCompileFunctions { } }, 'package:compileFunctions': () => - BbPromise.bind(this) - .then(this.downloadPackageArtifacts) - .then(this.compileFunctions), + BbPromise.bind(this).then(this.downloadPackageArtifacts).then(this.compileFunctions), }; } @@ -448,7 +446,7 @@ class AwsCompileFunctions { } // Include all referenced layer code in the version id hash const layerArtifactPaths = []; - layerConfigurations.forEach(layer => { + layerConfigurations.forEach((layer) => { const layerArtifactPath = this.provider.resolveLayerArtifactName(layer.name); layerArtifactPaths.push(layerArtifactPath); }); @@ -647,12 +645,14 @@ class AwsCompileFunctions { downloadPackageArtifacts() { const allFunctions = this.serverless.service.getAllFunctions(); - return BbPromise.each(allFunctions, functionName => this.downloadPackageArtifact(functionName)); + return BbPromise.each(allFunctions, (functionName) => + this.downloadPackageArtifact(functionName) + ); } compileFunctions() { const allFunctions = this.serverless.service.getAllFunctions(); - return Promise.all(allFunctions.map(functionName => this.compileFunction(functionName))); + return Promise.all(allFunctions.map((functionName) => this.compileFunction(functionName))); } cfLambdaFunctionTemplate() { @@ -690,15 +690,15 @@ function addFileContentsToHashes(filePath, hashes) { return new Promise((resolve, reject) => { const readStream = fs.createReadStream(filePath); readStream - .on('data', chunk => { - hashes.forEach(hash => { + .on('data', (chunk) => { + hashes.forEach((hash) => { hash.write(chunk); }); }) .on('close', () => { resolve(); }) - .on('error', error => { + .on('error', (error) => { reject(new Error(`Could not add file content to hash: ${error}`)); }); }); @@ -707,7 +707,7 @@ function addFileContentsToHashes(filePath, hashes) { function extractLayerConfigurationsFromFunction(functionProperties, cfTemplate) { const layerConfigurations = []; if (!functionProperties.Layers) return layerConfigurations; - functionProperties.Layers.forEach(potentialLocalLayerObject => { + functionProperties.Layers.forEach((potentialLocalLayerObject) => { if (potentialLocalLayerObject.Ref) { const configuration = cfTemplate.Resources[potentialLocalLayerObject.Ref]; layerConfigurations.push({ @@ -724,7 +724,7 @@ Object.defineProperties( AwsCompileFunctions.prototype, memoizeeMethods({ resolveImageUriAndSha: d( - async function(image) { + async function (image) { const providedImageSha = image.split('@')[1]; if (providedImageSha) { return { diff --git a/lib/plugins/aws/package/compile/layers.js b/lib/plugins/aws/package/compile/layers.js index e22879172fd..7cd75ea0314 100644 --- a/lib/plugins/aws/package/compile/layers.js +++ b/lib/plugins/aws/package/compile/layers.js @@ -56,7 +56,7 @@ class AwsCompileLayers { this.provider.serverless.service, this.provider.naming ); - return fsAsync.readFileAsync(layerArtifactPath).then(layerArtifactBinary => { + return fsAsync.readFileAsync(layerArtifactPath).then((layerArtifactBinary) => { const sha = crypto .createHash('sha1') .update(JSON.stringify(_.omit(newLayer, ['Properties.Content.S3Key']))) @@ -71,7 +71,7 @@ class AwsCompileLayers { }; if (layerObject.allowedAccounts) { - layerObject.allowedAccounts.map(account => { + layerObject.allowedAccounts.map((account) => { const newPermission = this.cfLambdaLayerPermissionTemplate(); newPermission.Properties.LayerVersionArn = { Ref: layerLogicalId }; newPermission.Properties.Principal = account; @@ -126,9 +126,9 @@ class AwsCompileLayers { ); return this.provider.request('CloudFormation', 'describeStacks', { StackName: stackName }).then( - data => { + (data) => { const lastHash = data.Stacks[0].Outputs.find( - output => output.OutputKey === layerHashOutputLogicalId + (output) => output.OutputKey === layerHashOutputLogicalId ); const compiledCloudFormationTemplate = this.serverless.service.provider .compiledCloudFormationTemplate; @@ -141,7 +141,7 @@ class AwsCompileLayers { layerName ); const lastS3Key = data.Stacks[0].Outputs.find( - output => output.OutputKey === layerS3keyOutputLogicalId + (output) => output.OutputKey === layerS3keyOutputLogicalId ); compiledCloudFormationTemplate.Outputs[layerS3keyOutputLogicalId].Value = lastS3Key.OutputValue; @@ -154,7 +154,7 @@ class AwsCompileLayers { layerObject.artifactAlreadyUploaded = true; this.serverless.cli.log(`Layer ${layerName} is already uploaded.`); }, - e => { + (e) => { if (e.message.includes('does not exist')) { return; } @@ -166,7 +166,7 @@ class AwsCompileLayers { compileLayers() { const allLayers = this.serverless.service.getAllLayers(); return Promise.all( - allLayers.map(layerName => + allLayers.map((layerName) => this.compileLayer(layerName).then(() => this.compareWithLastLayer(layerName)) ) ); diff --git a/lib/plugins/aws/package/lib/generateCoreTemplate.js b/lib/plugins/aws/package/lib/generateCoreTemplate.js index 99fa4164dd2..877aefdf86f 100644 --- a/lib/plugins/aws/package/lib/generateCoreTemplate.js +++ b/lib/plugins/aws/package/lib/generateCoreTemplate.js @@ -26,7 +26,7 @@ module.exports = { if (deploymentBucketObject.tags && Object.keys(deploymentBucketObject.tags).length) { const tags = deploymentBucketObject.tags; - const bucketTags = Object.keys(tags).map(key => ({ + const bucketTags = Object.keys(tags).map((key) => ({ Key: key, Value: tags[key], })); diff --git a/lib/plugins/aws/package/lib/getHashForFilePath.js b/lib/plugins/aws/package/lib/getHashForFilePath.js index d3b3921bfb2..3fa6220a2d9 100644 --- a/lib/plugins/aws/package/lib/getHashForFilePath.js +++ b/lib/plugins/aws/package/lib/getHashForFilePath.js @@ -5,20 +5,20 @@ const crypto = require('crypto'); const fs = require('fs'); const getHashForFilePath = memoize( - filePath => { + (filePath) => { const fileHash = crypto.createHash('sha256'); fileHash.setEncoding('base64'); return new Promise((resolve, reject) => { const readStream = fs.createReadStream(filePath); readStream - .on('data', chunk => { + .on('data', (chunk) => { fileHash.write(chunk); }) .on('close', () => { fileHash.end(); resolve(fileHash.read()); }) - .on('error', error => { + .on('error', (error) => { reject( new Error( `Error: ${error} encountered during hash calculation for provided filePath: ${filePath}` diff --git a/lib/plugins/aws/package/lib/mergeIamTemplates.js b/lib/plugins/aws/package/lib/mergeIamTemplates.js index 47d3fc89ad8..2b8084da379 100644 --- a/lib/plugins/aws/package/lib/mergeIamTemplates.js +++ b/lib/plugins/aws/package/lib/mergeIamTemplates.js @@ -14,8 +14,8 @@ module.exports = { // create log group resources this.serverless.service .getAllFunctions() - .filter(functionName => !this.serverless.service.getFunction(functionName).disableLogs) - .forEach(functionName => { + .filter((functionName) => !this.serverless.service.getFunction(functionName).disableLogs) + .forEach((functionName) => { const functionObject = this.serverless.service.getFunction(functionName); const logGroupLogicalId = this.provider.naming.getLogGroupLogicalId(functionName); const newLogGroup = { @@ -45,7 +45,7 @@ module.exports = { // resolve early if all functions contain a custom role const customRolesProvided = []; - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObject = this.serverless.service.getFunction(functionName); customRolesProvided.push('role' in functionObject); }); @@ -90,7 +90,7 @@ module.exports = { const disableLogsCanonicallyNamedFunctions = []; // Ensure policies for functions with custom name resolution - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const { name: resolvedFunctionName, disableLogs: areLogsDisabled, @@ -138,7 +138,7 @@ module.exports = { }); if (disableLogsCanonicallyNamedFunctions.length > 0) { // add deny rule for disabled logs function - const arnOfdisableLogGroups = disableLogsCanonicallyNamedFunctions.map(functionName => { + const arnOfdisableLogGroups = disableLogsCanonicallyNamedFunctions.map((functionName) => { return { 'Fn::Sub': 'arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}' + @@ -174,7 +174,7 @@ module.exports = { // check if one of the functions contains vpc configuration const vpcConfigProvided = []; - this.serverless.service.getAllFunctions().forEach(functionName => { + this.serverless.service.getAllFunctions().forEach((functionName) => { const functionObject = this.serverless.service.getFunction(functionName); if ('vpc' in functionObject) { vpcConfigProvided.push(true); diff --git a/lib/plugins/aws/package/lib/saveServiceState.js b/lib/plugins/aws/package/lib/saveServiceState.js index 7decf42b998..ed4a24e15f8 100644 --- a/lib/plugins/aws/package/lib/saveServiceState.js +++ b/lib/plugins/aws/package/lib/saveServiceState.js @@ -21,7 +21,7 @@ module.exports = { _.omit(this.serverless.service, ['serverless', 'package']) ); const selfReferences = findReferences(strippedService, this.serverless.service); - selfReferences.forEach(refPath => _.set(strippedService, refPath, '${self:}')); + selfReferences.forEach((refPath) => _.set(strippedService, refPath, '${self:}')); const state = { service: strippedService, diff --git a/lib/plugins/aws/provider.js b/lib/plugins/aws/provider.js index 9b8f7320af8..51363f4c18b 100644 --- a/lib/plugins/aws/provider.js +++ b/lib/plugins/aws/provider.js @@ -65,7 +65,7 @@ const impl = { * @param credentials The credentials to test for validity * @return {boolean} Whether the given credentials were valid */ - validCredentials: credentials => { + validCredentials: (credentials) => { let result = false; if (credentials) { if ( @@ -119,7 +119,7 @@ const impl = { // Setup a MFA callback for asking the code from the user. params.tokenCodeFn = (mfaSerial, callback) => { const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); - rl.question(`Enter MFA code for ${mfaSerial}: `, answer => { + rl.question(`Enter MFA code for ${mfaSerial}: `, (answer) => { rl.close(); callback(null, answer); }); @@ -1174,7 +1174,7 @@ class AwsProvider { // Can be a single certificate or multiple, comma separated. const caArr = ca.split(','); // Replace the newline -- https://stackoverflow.com/questions/30400341 - caCerts = caCerts.concat(caArr.map(cert => cert.replace(/\\n/g, '\n'))); + caCerts = caCerts.concat(caArr.map((cert) => cert.replace(/\\n/g, '\n'))); } const cafile = process.env.cafile || process.env.HTTPS_CAFILE || process.env.https_cafile; @@ -1182,7 +1182,7 @@ class AwsProvider { if (cafile) { // Can be a single certificate file path or multiple paths, comma separated. const caPathArr = cafile.split(','); - caCerts = caCerts.concat(caPathArr.map(cafilePath => fs.readFileSync(cafilePath.trim()))); + caCerts = caCerts.concat(caPathArr.map((cafilePath) => fs.readFileSync(cafilePath.trim()))); } if (caCerts.length > 0) { @@ -1231,12 +1231,12 @@ class AwsProvider { }); const paramsHash = objectHash.sha1(paramsWithRegion); const BASE_BACKOFF = 5000; - const persistentRequest = f => + const persistentRequest = (f) => new BbPromise((resolve, reject) => { - const doCall = numTry => { + const doCall = (numTry) => { f() // We're resembling if/else logic, therefore single `then` instead of `then`/`catch` pair - .then(resolve, e => { + .then(resolve, (e) => { const { providerError } = e; if ( numTry < MAX_RETRIES && @@ -1300,10 +1300,10 @@ class AwsProvider { const promise = req.promise ? req.promise() - : BbPromise.fromCallback(cb => { + : BbPromise.fromCallback((cb) => { req.send(cb); }); - return promise.catch(err => { + return promise.catch((err) => { let message = err.message != null ? err.message : String(err.code); if (message.startsWith('Missing credentials in config')) { // Credentials error @@ -1338,7 +1338,7 @@ class AwsProvider { }) ); }); - }).then(data => { + }).then((data) => { const result = BbPromise.resolve(data); if (shouldCache) { _.set(this.requestCache, `${service}.${method}.${paramsHash}`, result); @@ -1439,7 +1439,7 @@ class AwsProvider { } getValues(source, objectPaths) { - return objectPaths.map(objectPath => ({ + return objectPaths.map((objectPath) => ({ path: objectPath, value: _.get(source, objectPath.join('.')), })); @@ -1499,7 +1499,7 @@ class AwsProvider { return this.request('CloudFormation', 'describeStackResource', { StackName: this.naming.getStackName(), LogicalResourceId: this.naming.getDeploymentBucketLogicalId(), - }).then(result => result.StackResourceDetail.PhysicalResourceId); + }).then((result) => result.StackResourceDetail.PhysicalResourceId); } getDeploymentPrefix() { @@ -1593,11 +1593,11 @@ class AwsProvider { } getAccountId() { - return this.getAccountInfo().then(result => result.accountId); + return this.getAccountInfo().then((result) => result.accountId); } getAccountInfo() { - return this.request('STS', 'getCallerIdentity', {}).then(result => { + return this.request('STS', 'getCallerIdentity', {}).then((result) => { const arn = result.Arn; const accountId = result.Account; const partition = arn.split(':')[1]; // ex: arn:aws:iam:acctId:user/xyz @@ -1662,7 +1662,7 @@ class AwsProvider { return this.serverless.service.provider.apiGateway.restApiResources; } - return Object.keys(this.serverless.service.provider.apiGateway.restApiResources).map(key => ({ + return Object.keys(this.serverless.service.provider.apiGateway.restApiResources).map((key) => ({ path: key, resourceId: this.serverless.service.provider.apiGateway.restApiResources[key], })); @@ -1690,7 +1690,7 @@ class AwsProvider { if (!resources) resources = []; if (next) params.NextToken = next; - return this.request('CloudFormation', 'listStackResources', params).then(res => { + return this.request('CloudFormation', 'listStackResources', params).then((res) => { const allResources = resources.concat(res.StackResourceSummaries); if (!res.NextToken) { return allResources; diff --git a/lib/plugins/aws/remove/index.js b/lib/plugins/aws/remove/index.js index 80a96809992..4a2dc28e974 100644 --- a/lib/plugins/aws/remove/index.js +++ b/lib/plugins/aws/remove/index.js @@ -20,7 +20,7 @@ class AwsRemove { .then(this.validate) .then(this.emptyS3Bucket) .then(this.removeStack) - .then(cfData => this.monitorStack('delete', cfData)), + .then((cfData) => this.monitorStack('delete', cfData)), }; } } diff --git a/lib/plugins/aws/remove/lib/bucket.js b/lib/plugins/aws/remove/lib/bucket.js index f5d48332162..0468692791b 100644 --- a/lib/plugins/aws/remove/lib/bucket.js +++ b/lib/plugins/aws/remove/lib/bucket.js @@ -4,7 +4,7 @@ const BbPromise = require('bluebird'); module.exports = { setServerlessDeploymentBucketName() { - return this.provider.getServerlessDeploymentBucketName().then(bucketName => { + return this.provider.getServerlessDeploymentBucketName().then((bucketName) => { this.bucketName = bucketName; }); }, @@ -20,9 +20,9 @@ module.exports = { Bucket: this.bucketName, Prefix: `${this.provider.getDeploymentPrefix()}/${serviceStage}`, }) - .then(result => { + .then((result) => { if (result) { - result.Contents.forEach(object => { + result.Contents.forEach((object) => { this.objectsInBucket.push({ Key: object.Key, }); diff --git a/lib/plugins/aws/rollback.js b/lib/plugins/aws/rollback.js index 63f4abe8cdf..efeaca921dd 100644 --- a/lib/plugins/aws/rollback.js +++ b/lib/plugins/aws/rollback.js @@ -49,7 +49,7 @@ class AwsRollback { Bucket: this.bucketName, Prefix: prefix, }) - .then(response => { + .then((response) => { const deployments = findAndGroupDeployments(response, deploymentPrefix, serviceName, stage); if (deployments.length === 0) { @@ -66,9 +66,9 @@ class AwsRollback { } const dateString = `${date.getTime().toString()}-${date.toISOString()}`; - const exists = deployments.some(deployment => + const exists = deployments.some((deployment) => deployment.some( - item => + (item) => item.directory === dateString && item.file === this.provider.naming.getCompiledTemplateS3Suffix() ) diff --git a/lib/plugins/aws/rollbackFunction.js b/lib/plugins/aws/rollbackFunction.js index f3f9b2116ee..d91c327eb65 100644 --- a/lib/plugins/aws/rollbackFunction.js +++ b/lib/plugins/aws/rollbackFunction.js @@ -70,8 +70,8 @@ class AwsRollbackFunction { return this.provider .request('Lambda', 'getFunction', params) - .then(func => func) - .catch(error => { + .then((func) => func) + .catch((error) => { if (error.message.match(/not found/)) { const errorMessage = [ `Function "${funcName}" with version "${funcVersion}" not found.`, @@ -88,7 +88,7 @@ class AwsRollbackFunction { fetchFunctionCode(func) { const codeUrl = func.Code.Location; - return fetch(codeUrl).then(response => response.buffer()); + return fetch(codeUrl).then((response) => response.buffer()); } restoreFunction(zipBuffer) { diff --git a/lib/plugins/aws/utils/credentials.js b/lib/plugins/aws/utils/credentials.js index 5cf1953ea50..e603e009c87 100644 --- a/lib/plugins/aws/utils/credentials.js +++ b/lib/plugins/aws/utils/credentials.js @@ -17,7 +17,7 @@ const settingMap = new Map([ ['aws_secret_access_key', 'secretAccessKey'], ['aws_session_token', 'sessionToken'], ]); -const parseFileProfiles = content => { +const parseFileProfiles = (content) => { const profiles = new Map(); let currentProfile; for (const line of content.split(/[\n\r]+/)) { @@ -43,19 +43,23 @@ const parseFileProfiles = content => { return profiles; }; -const writeCredentialsContent = content => +const writeCredentialsContent = (content) => new BbPromise((resolve, reject) => writeFile( credentialsFilePath, content, !isWindows ? { mode: constants.S_IRUSR | constants.S_IWUSR } : null, - writeFileError => { + (writeFileError) => { if (writeFileError) { if (writeFileError.code === 'ENOENT') { - mkdir(awsConfigDirPath, !isWindows ? { mode: constants.S_IRWXU } : null, mkdirError => { - if (mkdirError) reject(mkdirError); - else resolve(writeCredentialsContent(content)); - }); + mkdir( + awsConfigDirPath, + !isWindows ? { mode: constants.S_IRWXU } : null, + (mkdirError) => { + if (mkdirError) reject(mkdirError); + else resolve(writeCredentialsContent(content)); + } + ); } else { reject(writeFileError); } @@ -96,7 +100,7 @@ module.exports = { }, saveFileProfiles(profiles) { - return new BbPromise(resolve => { + return new BbPromise((resolve) => { if (!credentialsFilePath) throw new Error('Could not resolve path to user credentials file'); resolve( writeCredentialsContent( diff --git a/lib/plugins/aws/utils/findAndGroupDeployments.js b/lib/plugins/aws/utils/findAndGroupDeployments.js index 5a0065c4f0a..7987972bd92 100644 --- a/lib/plugins/aws/utils/findAndGroupDeployments.js +++ b/lib/plugins/aws/utils/findAndGroupDeployments.js @@ -5,8 +5,8 @@ const _ = require('lodash'); module.exports = (s3Response, prefix, service, stage) => { if (s3Response.Contents.length) { const regex = new RegExp(`${prefix}/${service}/${stage}/(.+-.+-.+-.+)/(.+)`); - const s3Objects = s3Response.Contents.filter(s3Object => s3Object.Key.match(regex)); - const names = s3Objects.map(s3Object => { + const s3Objects = s3Response.Contents.filter((s3Object) => s3Object.Key.match(regex)); + const names = s3Objects.map((s3Object) => { const match = s3Object.Key.match(regex); return { directory: match[1], diff --git a/lib/plugins/aws/utils/formatLambdaLogEvent.js b/lib/plugins/aws/utils/formatLambdaLogEvent.js index a0f3469dbeb..05aa5183501 100644 --- a/lib/plugins/aws/utils/formatLambdaLogEvent.js +++ b/lib/plugins/aws/utils/formatLambdaLogEvent.js @@ -4,7 +4,7 @@ const dayjs = require('dayjs'); const chalk = require('chalk'); const os = require('os'); -module.exports = msgParam => { +module.exports = (msgParam) => { let msg = msgParam; const dateFormat = 'YYYY-MM-DD HH:mm:ss.SSS (Z)'; diff --git a/lib/plugins/aws/utils/getS3ObjectsFromStacks.js b/lib/plugins/aws/utils/getS3ObjectsFromStacks.js index 8d55d0f7f6e..82ad6213184 100644 --- a/lib/plugins/aws/utils/getS3ObjectsFromStacks.js +++ b/lib/plugins/aws/utils/getS3ObjectsFromStacks.js @@ -3,6 +3,6 @@ const _ = require('lodash'); module.exports = (stacks, prefix, service, stage) => - _.flatten(stacks).map(entry => ({ + _.flatten(stacks).map((entry) => ({ Key: `${prefix}/${service}/${stage}/${entry.directory}/${entry.file}`, })); diff --git a/lib/plugins/aws/utils/resolveCfImportValue.js b/lib/plugins/aws/utils/resolveCfImportValue.js index 53facaa2337..c4ed6fab50a 100644 --- a/lib/plugins/aws/utils/resolveCfImportValue.js +++ b/lib/plugins/aws/utils/resolveCfImportValue.js @@ -3,8 +3,8 @@ const ServerlessError = require('../../../classes/Error').ServerlessError; function resolveCfImportValue(provider, name, sdkParams = {}) { - return provider.request('CloudFormation', 'listExports', sdkParams).then(result => { - const targetExportMeta = result.Exports.find(exportMeta => exportMeta.Name === name); + return provider.request('CloudFormation', 'listExports', sdkParams).then((result) => { + const targetExportMeta = result.Exports.find((exportMeta) => exportMeta.Name === name); if (targetExportMeta) return targetExportMeta.Value; if (result.NextToken) { return resolveCfImportValue(provider, name, { NextToken: result.NextToken }); diff --git a/lib/plugins/aws/utils/resolveCfRefValue.js b/lib/plugins/aws/utils/resolveCfRefValue.js index ead12d2179c..4a8e70ff3c4 100644 --- a/lib/plugins/aws/utils/resolveCfRefValue.js +++ b/lib/plugins/aws/utils/resolveCfRefValue.js @@ -9,9 +9,9 @@ function resolveCfRefValue(provider, resourceLogicalId, sdkParams = {}) { 'listStackResources', Object.assign(sdkParams, { StackName: provider.naming.getStackName() }) ) - .then(result => { + .then((result) => { const targetStackResource = result.StackResourceSummaries.find( - stackResource => stackResource.LogicalResourceId === resourceLogicalId + (stackResource) => stackResource.LogicalResourceId === resourceLogicalId ); if (targetStackResource) return targetStackResource.PhysicalResourceId; if (result.NextToken) { diff --git a/lib/plugins/create/create.js b/lib/plugins/create/create.js index 37603d58607..d5953ca03aa 100644 --- a/lib/plugins/create/create.js +++ b/lib/plugins/create/create.js @@ -94,7 +94,7 @@ const humanReadableTemplateList = (() => { return result; })(); -const handleServiceCreationError = error => { +const handleServiceCreationError = (error) => { if (error.code !== 'EACCESS') throw error; const errorMessage = [ 'Error unable to create a service in this directory. ', @@ -154,7 +154,7 @@ class Create { this.options.name, this.options.path ) - .then(serviceName => { + .then((serviceName) => { const message = [ `Successfully installed "${serviceName}" `, `${ @@ -166,7 +166,7 @@ class Create { this.serverless.cli.log(message); }) - .catch(err => { + .catch((err) => { throw new this.serverless.classes.Error(err); }); } else if ('template-path' in this.options) { @@ -237,7 +237,7 @@ class Create { // ensure no template file already exists in cwd that we may overwrite const templateFullFilePaths = this.serverless.utils.walkDirSync(templateSrcDir); - templateFullFilePaths.forEach(ffp => { + templateFullFilePaths.forEach((ffp) => { const filename = path.basename(ffp); if (this.serverless.utils.fileExistsSync(path.join(process.cwd(), filename))) { const errorMessage = [ diff --git a/lib/plugins/create/templates/aws-nodejs-ecma-script/first.js b/lib/plugins/create/templates/aws-nodejs-ecma-script/first.js index 81886dd5ca4..d6bb3321459 100644 --- a/lib/plugins/create/templates/aws-nodejs-ecma-script/first.js +++ b/lib/plugins/create/templates/aws-nodejs-ecma-script/first.js @@ -1,6 +1,6 @@ // eslint-disable-next-line import/prefer-default-export export const hello = (event, context, callback) => { - const p = new Promise(resolve => { + const p = new Promise((resolve) => { resolve('success'); }); p.then(() => @@ -8,5 +8,5 @@ export const hello = (event, context, callback) => { message: 'Go Serverless Webpack (Ecma Script) v1.0! First module!', event, }) - ).catch(e => callback(e)); + ).catch((e) => callback(e)); }; diff --git a/lib/plugins/create/templates/aws-nodejs-ecma-script/second.js b/lib/plugins/create/templates/aws-nodejs-ecma-script/second.js index 9517398c3f5..4900b3e27bb 100644 --- a/lib/plugins/create/templates/aws-nodejs-ecma-script/second.js +++ b/lib/plugins/create/templates/aws-nodejs-ecma-script/second.js @@ -1,6 +1,6 @@ // eslint-disable-next-line import/prefer-default-export export const hello = (event, context, cb) => { - const p = new Promise(resolve => { + const p = new Promise((resolve) => { resolve('success'); }); const response = { @@ -14,5 +14,5 @@ export const hello = (event, context, cb) => { 2 ), }; - p.then(() => cb(null, response)).catch(e => cb(e)); + p.then(() => cb(null, response)).catch((e) => cb(e)); }; diff --git a/lib/plugins/create/templates/aws-nodejs/handler.js b/lib/plugins/create/templates/aws-nodejs/handler.js index 13dd03fcd23..7f8b0cc5af3 100644 --- a/lib/plugins/create/templates/aws-nodejs/handler.js +++ b/lib/plugins/create/templates/aws-nodejs/handler.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports.hello = async event => { +module.exports.hello = async (event) => { return { statusCode: 200, body: JSON.stringify( diff --git a/lib/plugins/create/templates/azure-nodejs/src/handlers/goodbye.js b/lib/plugins/create/templates/azure-nodejs/src/handlers/goodbye.js index e2b35a57dc7..e271995d2c4 100644 --- a/lib/plugins/create/templates/azure-nodejs/src/handlers/goodbye.js +++ b/lib/plugins/create/templates/azure-nodejs/src/handlers/goodbye.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports.sayGoodbye = async function(context, req) { +module.exports.sayGoodbye = async function (context, req) { context.log('JavaScript HTTP trigger function processed a request.'); if (req.query.name || (req.body && req.body.name)) { diff --git a/lib/plugins/create/templates/azure-nodejs/src/handlers/hello.js b/lib/plugins/create/templates/azure-nodejs/src/handlers/hello.js index 9a5a253c63f..1111d8f8ec6 100644 --- a/lib/plugins/create/templates/azure-nodejs/src/handlers/hello.js +++ b/lib/plugins/create/templates/azure-nodejs/src/handlers/hello.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports.sayHello = async function(context, req) { +module.exports.sayHello = async function (context, req) { context.log('JavaScript HTTP trigger function processed a request.'); if (req.query.name || (req.body && req.body.name)) { diff --git a/lib/plugins/create/templates/cloudflare-workers-enterprise/bar.js b/lib/plugins/create/templates/cloudflare-workers-enterprise/bar.js index 0d537fadf0b..6a0fe8909ec 100644 --- a/lib/plugins/create/templates/cloudflare-workers-enterprise/bar.js +++ b/lib/plugins/create/templates/cloudflare-workers-enterprise/bar.js @@ -1,4 +1,4 @@ -addEventListener('fetch', event => { +addEventListener('fetch', (event) => { event.respondWith(handleRequest(event.request)); }); diff --git a/lib/plugins/create/templates/cloudflare-workers-enterprise/helloWorld.js b/lib/plugins/create/templates/cloudflare-workers-enterprise/helloWorld.js index 8e780d2b0ec..4002fc719a8 100644 --- a/lib/plugins/create/templates/cloudflare-workers-enterprise/helloWorld.js +++ b/lib/plugins/create/templates/cloudflare-workers-enterprise/helloWorld.js @@ -1,4 +1,4 @@ -addEventListener('fetch', event => { +addEventListener('fetch', (event) => { event.respondWith(handleRequest(event.request)); }); diff --git a/lib/plugins/create/templates/cloudflare-workers-rust/helloWorld.js b/lib/plugins/create/templates/cloudflare-workers-rust/helloWorld.js index 7f7d962b5d7..d5b912f9821 100644 --- a/lib/plugins/create/templates/cloudflare-workers-rust/helloWorld.js +++ b/lib/plugins/create/templates/cloudflare-workers-rust/helloWorld.js @@ -1,4 +1,4 @@ -addEventListener('fetch', event => { +addEventListener('fetch', (event) => { event.respondWith(handleRequest(event.request)); }); diff --git a/lib/plugins/create/templates/cloudflare-workers/helloWorld.js b/lib/plugins/create/templates/cloudflare-workers/helloWorld.js index 8e780d2b0ec..4002fc719a8 100644 --- a/lib/plugins/create/templates/cloudflare-workers/helloWorld.js +++ b/lib/plugins/create/templates/cloudflare-workers/helloWorld.js @@ -1,4 +1,4 @@ -addEventListener('fetch', event => { +addEventListener('fetch', (event) => { event.respondWith(handleRequest(event.request)); }); diff --git a/lib/plugins/create/templates/fn-nodejs/hello/func.js b/lib/plugins/create/templates/fn-nodejs/hello/func.js index 911c30efc49..88fcfa078e7 100644 --- a/lib/plugins/create/templates/fn-nodejs/hello/func.js +++ b/lib/plugins/create/templates/fn-nodejs/hello/func.js @@ -1,6 +1,6 @@ const fdk = require('@fnproject/fdk'); -fdk.handle(input => { +fdk.handle((input) => { let name = 'World'; if (input.name) { name = input.name; diff --git a/lib/plugins/create/templates/twilio-nodejs/handler.js b/lib/plugins/create/templates/twilio-nodejs/handler.js index 6ea383c3ae2..1a9cc8fd338 100644 --- a/lib/plugins/create/templates/twilio-nodejs/handler.js +++ b/lib/plugins/create/templates/twilio-nodejs/handler.js @@ -1,6 +1,6 @@ const logo = require('asciiart-logo'); -exports.handler = function(context, event, callback) { +exports.handler = function (context, event, callback) { callback( null, logo({ diff --git a/lib/plugins/install.js b/lib/plugins/install.js index cddda72247e..f14023ef586 100644 --- a/lib/plugins/install.js +++ b/lib/plugins/install.js @@ -35,7 +35,7 @@ class Install { install() { return download .downloadTemplateFromRepo(this.options.url, this.options.name) - .then(serviceName => { + .then((serviceName) => { const message = [ `Successfully installed "${serviceName}" `, `${ diff --git a/lib/plugins/interactiveCli/index.js b/lib/plugins/interactiveCli/index.js index 5976b6324f8..75e70da180c 100644 --- a/lib/plugins/interactiveCli/index.js +++ b/lib/plugins/interactiveCli/index.js @@ -25,7 +25,7 @@ module.exports = class InteractiveCli { return initializeService.run(serverless); }, 'interactiveCli:setupAws': () => { - return setupAws.check(serverless).then(isApplicable => { + return setupAws.check(serverless).then((isApplicable) => { if (!isApplicable) return null; process.stdout.write('\n'); return setupAws.run(serverless); @@ -37,7 +37,7 @@ module.exports = class InteractiveCli { await autoUpdate.run(serverless); }, 'interactiveCli:tabCompletion': () => { - return tabCompletion.check(serverless).then(isApplicable => { + return tabCompletion.check(serverless).then((isApplicable) => { if (!isApplicable) return null; process.stdout.write('\n'); return tabCompletion.run(serverless); diff --git a/lib/plugins/interactiveCli/initializeService.js b/lib/plugins/interactiveCli/initializeService.js index 3128cf88312..60b056a553b 100644 --- a/lib/plugins/interactiveCli/initializeService.js +++ b/lib/plugins/interactiveCli/initializeService.js @@ -28,13 +28,13 @@ const projectTypeChoice = () => }) .then(({ projectType }) => projectType); -const projectNameInput = workingDir => +const projectNameInput = (workingDir) => inquirer .prompt({ message: 'What do you want to call this project?', type: 'input', name: 'projectName', - validate: input => { + validate: (input) => { input = input.trim(); if (!isValidServiceName(input)) { return ( @@ -44,7 +44,7 @@ const projectNameInput = workingDir => " - Shouldn't exceed 128 characters" ); } - return getConfigFilePath(join(workingDir, input)).then(configFilePath => { + return getConfigFilePath(join(workingDir, input)).then((configFilePath) => { return configFilePath ? `Serverless project already found at ${input} directory` : true; }); }, @@ -60,9 +60,9 @@ module.exports = { const workingDir = process.cwd(); return confirm('No project detected. Do you want to create a new one?', { name: 'shouldCreateNewProject', - }).then(isConfirmed => { + }).then((isConfirmed) => { if (!isConfirmed) return null; - return projectTypeChoice().then(projectType => { + return projectTypeChoice().then((projectType) => { if (projectType === 'other') { process.stdout.write( '\nRun “serverless create --help” to view available templates and create a new project ' + @@ -70,7 +70,7 @@ module.exports = { ); return null; } - return projectNameInput(workingDir).then(projectName => { + return projectNameInput(workingDir).then((projectName) => { const projectDir = join(workingDir, projectName); return createFromTemplate(projectType, projectDir) .then(() => { @@ -83,7 +83,7 @@ module.exports = { getServerlessConfigFile.delete(serverless); getServerlessConfigFile(serverless); }) - .then(serverlessConfigFile => { + .then((serverlessConfigFile) => { serverless.pluginManager.serverlessConfigFile = serverlessConfigFile; return serverless.service.load(); }) diff --git a/lib/plugins/interactiveCli/setupAws.js b/lib/plugins/interactiveCli/setupAws.js index 84022777af9..a1dd0af421f 100644 --- a/lib/plugins/interactiveCli/setupAws.js +++ b/lib/plugins/interactiveCli/setupAws.js @@ -16,7 +16,7 @@ const awsAccessKeyIdInput = () => message: 'AWS Access Key Id:', type: 'input', name: 'accessKeyId', - validate: input => { + validate: (input) => { if (isValidAwsAccessKeyId(input.trim())) return true; return 'AWS Access Key Id seems not valid.\n Expected something like AKIAIOSFODNN7EXAMPLE'; }, @@ -29,7 +29,7 @@ const awsSecretAccessKeyInput = () => message: 'AWS Secret Access Key:', type: 'input', name: 'secretAccessKey', - validate: input => { + validate: (input) => { if (isValidAwsSecretAccessKey(input.trim())) return true; return ( 'AWS Secret Access Key seems not valid.\n' + @@ -46,13 +46,13 @@ const steps = { http://slss.io/aws-creds-setup\n`), shouldSetupAwsCredentials: () => confirm('Do you want to set them up now?', { name: 'shouldSetupAwsCredentials' }).then( - isConfirmed => { + (isConfirmed) => { if (!isConfirmed) steps.writeOnSetupSkip(); return isConfirmed; } ), ensureAwsAccount: () => - confirm('Do you have an AWS account?', { name: 'hasAwsAccount' }).then(hasAccount => { + confirm('Do you have an AWS account?', { name: 'hasAwsAccount' }).then((hasAccount) => { if (!hasAccount) { openBrowser('https://portal.aws.amazon.com/billing/signup'); return inquirer.prompt({ @@ -62,7 +62,7 @@ const steps = { } return null; }), - ensureAwsCredentials: serverless => { + ensureAwsCredentials: (serverless) => { const region = serverless.getProvider('aws').getRegion(); openBrowser( `https://console.aws.amazon.com/iam/home?region=${region}#/users$new?step=final&accessKey&userNames=serverless&permissionType=policies&policies=arn:aws:iam::aws:policy%2FAdministratorAccess` @@ -73,8 +73,8 @@ const steps = { }); }, inputAwsCredentials: () => { - return awsAccessKeyIdInput().then(accessKeyId => - awsSecretAccessKeyInput().then(secretAccessKey => + return awsAccessKeyIdInput().then((accessKeyId) => + awsSecretAccessKeyInput().then((secretAccessKey) => awsCredentials .saveFileProfiles(new Map([['default', { accessKeyId, secretAccessKey }]])) .then(() => @@ -112,8 +112,8 @@ module.exports = { return module.exports.runSteps(serverless); }, steps, - runSteps: serverless => - steps.shouldSetupAwsCredentials().then(isConfirmed => { + runSteps: (serverless) => + steps.shouldSetupAwsCredentials().then((isConfirmed) => { if (!isConfirmed) return null; return steps .ensureAwsAccount() diff --git a/lib/plugins/interactiveCli/tabCompletion.js b/lib/plugins/interactiveCli/tabCompletion.js index 71520dc21d1..8d35c3e2bba 100644 --- a/lib/plugins/interactiveCli/tabCompletion.js +++ b/lib/plugins/interactiveCli/tabCompletion.js @@ -27,7 +27,7 @@ module.exports = { .statAsync(path.resolve(os.homedir(), `.config/tabtab/serverless.${shellExtension}`)) .then( () => false, - error => { + (error) => { if (error.code !== 'ENOENT') throw error; return !configUtils.get(promptDisabledConfigPropertyName); } @@ -38,7 +38,7 @@ module.exports = { return BbPromise.try(() => { return confirm('Would you like to setup a command line completion?', { name: 'shouldSetupTabCompletion', - }).then(isConfirmed => { + }).then((isConfirmed) => { if (!isConfirmed) { configUtils.set(promptDisabledConfigPropertyName, true); return null; diff --git a/lib/plugins/interactiveCli/utils.js b/lib/plugins/interactiveCli/utils.js index 0c48679d8ab..b29b060bb9c 100644 --- a/lib/plugins/interactiveCli/utils.js +++ b/lib/plugins/interactiveCli/utils.js @@ -11,6 +11,6 @@ module.exports = { type: 'confirm', name, }) - .then(result => result[name]); + .then((result) => result[name]); }, }; diff --git a/lib/plugins/invoke.js b/lib/plugins/invoke.js index 84c6b17b63f..e03899a3d4a 100644 --- a/lib/plugins/invoke.js +++ b/lib/plugins/invoke.js @@ -139,7 +139,7 @@ class Invoke { // Turn zero or more --env options into an array // ...then split --env NAME=value and put into process.env. - [].concat(this.options.env || []).forEach(itm => { + [].concat(this.options.env || []).forEach((itm) => { const splitItm = itm.split('='); process.env[splitItm[0]] = splitItm[1] || ''; }); diff --git a/lib/plugins/package/lib/packageService.js b/lib/plugins/package/lib/packageService.js index 6d8d621a104..dfe40f47348 100644 --- a/lib/plugins/package/lib/packageService.js +++ b/lib/plugins/package/lib/packageService.js @@ -30,7 +30,7 @@ module.exports = { getExcludes(exclude, excludeLayers) { return serverlessConfigFileUtils .getServerlessConfigFilePath(this.serverless) - .then(configFilePath => { + .then((configFilePath) => { const packageExcludes = this.serverless.service.package.exclude || []; // add local service plugins Path const pluginsLocalPath = this.serverless.pluginManager.parsePluginsObject( @@ -41,7 +41,7 @@ module.exports = { const layerExcludes = excludeLayers ? this.serverless.service .getAllLayers() - .map(layer => `${this.serverless.service.getLayer(layer).path}/**`) + .map((layer) => `${this.serverless.service.getLayer(layer).path}/**`) : []; // add defaults for exclude @@ -67,7 +67,7 @@ module.exports = { this.serverless.cli.log('Packaging service...'); let shouldPackageService = false; const allFunctions = this.serverless.service.getAllFunctions(); - let packagePromises = allFunctions.map(async functionName => { + let packagePromises = allFunctions.map(async (functionName) => { const functionObject = this.serverless.service.getFunction(functionName); if (functionObject.image) return; functionObject.package = functionObject.package || {}; @@ -84,7 +84,7 @@ module.exports = { }); const allLayers = this.serverless.service.getAllLayers(); packagePromises = packagePromises.concat( - allLayers.map(async layerName => { + allLayers.map(async (layerName) => { const layerObject = this.serverless.service.getLayer(layerName); layerObject.package = layerObject.package || {}; if (layerObject.package.artifact) return; @@ -99,8 +99,8 @@ module.exports = { packageAll() { const zipFileName = `${this.serverless.service.service}.zip`; - return this.resolveFilePathsAll().then(filePaths => - this.zipFiles(filePaths, zipFileName).then(filePath => { + return this.resolveFilePathsAll().then((filePaths) => + this.zipFiles(filePaths, zipFileName).then((filePath) => { // only set the default artifact for backward-compatibility // when no explicit artifact is defined if (!this.serverless.service.package.artifact) { @@ -150,25 +150,27 @@ module.exports = { const zipFileName = `${layerName}.zip`; return this.resolveFilePathsLayer(layerName) - .then(filePaths => filePaths.map(f => path.resolve(path.join(layerObject.path, f)))) - .then(filePaths => - this.zipFiles(filePaths, zipFileName, path.resolve(layerObject.path)).then(artifactPath => { - layerObject.package = { - artifact: artifactPath, - }; - return artifactPath; - }) + .then((filePaths) => filePaths.map((f) => path.resolve(path.join(layerObject.path, f)))) + .then((filePaths) => + this.zipFiles(filePaths, zipFileName, path.resolve(layerObject.path)).then( + (artifactPath) => { + layerObject.package = { + artifact: artifactPath, + }; + return artifactPath; + } + ) ); }, resolveFilePathsAll() { return this.getExcludes([], true) - .then(exclude => { + .then((exclude) => { const params = { exclude, include: this.getIncludes() }; return params; }) - .then(params => this.excludeDevDependencies(params)) - .then(params => this.resolveFilePathsFromPatterns(params)); + .then((params) => this.excludeDevDependencies(params)) + .then((params) => this.resolveFilePathsFromPatterns(params)); }, resolveFilePathsFunction(functionName) { @@ -176,12 +178,12 @@ module.exports = { const funcPackageConfig = functionObject.package || {}; return this.getExcludes(funcPackageConfig.exclude, true) - .then(exclude => { + .then((exclude) => { const params = { exclude, include: this.getIncludes(funcPackageConfig.include) }; return params; }) - .then(params => this.excludeDevDependencies(params)) - .then(params => this.resolveFilePathsFromPatterns(params)); + .then((params) => this.excludeDevDependencies(params)) + .then((params) => this.resolveFilePathsFromPatterns(params)); }, resolveFilePathsLayer(layerName) { @@ -189,18 +191,18 @@ module.exports = { const layerPackageConfig = layerObject.package || {}; return this.getExcludes(layerPackageConfig.exclude, false) - .then(exclude => { + .then((exclude) => { const params = { exclude, include: this.getIncludes(layerPackageConfig.include) }; return params; }) - .then(params => this.excludeDevDependencies(params)) - .then(params => this.resolveFilePathsFromPatterns(params, layerObject.path)); + .then((params) => this.excludeDevDependencies(params)) + .then((params) => this.resolveFilePathsFromPatterns(params, layerObject.path)); }, resolveFilePathsFromPatterns(params, prefix) { const patterns = []; - params.exclude.forEach(pattern => { + params.exclude.forEach((pattern) => { if (pattern.charAt(0) !== '!') { patterns.push(`!${pattern}`); } else { @@ -210,7 +212,7 @@ module.exports = { // push the include globs to the end of the array // (files and folders will be re-added again even if they were excluded beforehand) - params.include.forEach(pattern => { + params.include.forEach((pattern) => { patterns.push(pattern); }); @@ -224,23 +226,23 @@ module.exports = { follow: true, nodir: true, expandDirectories: false, - }).then(allFilePaths => { + }).then((allFilePaths) => { const filePathStates = allFilePaths.reduce((p, c) => Object.assign(p, { [c]: true }), {}); patterns // micromatch only does / style path delimiters, so convert them if on windows - .map(p => { + .map((p) => { return process.platform === 'win32' ? p.replace(/\\/g, '/') : p; }) - .forEach(p => { + .forEach((p) => { const exclude = p.startsWith('!'); const pattern = exclude ? p.slice(1) : p; - micromatch(allFilePaths, [pattern], { dot: true }).forEach(key => { + micromatch(allFilePaths, [pattern], { dot: true }).forEach((key) => { filePathStates[key] = !exclude; }); }); const filePaths = Object.entries(filePathStates) - .filter(r => r[1] === true) - .map(r => r[0]); + .filter((r) => r[1] === true) + .map((r) => r[0]); if (filePaths.length !== 0) return filePaths; throw new this.serverless.classes.Error('No file matches include / exclude patterns'); }); diff --git a/lib/plugins/package/lib/zipService.js b/lib/plugins/package/lib/zipService.js index 41017a86a0b..f05be9287b3 100644 --- a/lib/plugins/package/lib/zipService.js +++ b/lib/plugins/package/lib/zipService.js @@ -44,7 +44,7 @@ module.exports = { }, zip(params) { - return this.resolveFilePathsFromPatterns(params).then(filePaths => + return this.resolveFilePathsFromPatterns(params).then((filePaths) => this.zipFiles(filePaths, params.zipFileName) ); }, @@ -74,20 +74,20 @@ module.exports = { return new BbPromise((resolve, reject) => { output.on('close', () => resolve(artifactFilePath)); - output.on('error', err => reject(err)); - zip.on('error', err => reject(err)); + output.on('error', (err) => reject(err)); + zip.on('error', (err) => reject(err)); output.on('open', () => { zip.pipe(output); // normalize both maps to avoid problems with e.g. Path Separators in different shells - const normalizedFiles = _.uniq(files.map(file => path.normalize(file))); + const normalizedFiles = _.uniq(files.map((file) => path.normalize(file))); return BbPromise.all(normalizedFiles.map(this.getFileContentAndStat.bind(this))) - .then(contents => { + .then((contents) => { contents .sort((content1, content2) => content1.filePath.localeCompare(content2.filePath)) - .forEach(file => { + .forEach((file) => { const name = file.filePath.slice(prefix ? `${prefix}${path.sep}`.length : 0); // Ensure file is executable if it is locally executable or // it's forced (via normalizedFilesToChmodPlusX) to be executable @@ -114,12 +114,12 @@ module.exports = { this.getFileContent(fullPath), fs.statAsync(fullPath), ]).then( - result => ({ + (result) => ({ data: result[0], stat: result[1], filePath, }), - error => { + (error) => { throw new ServerlessError(`Cannot read file ${filePath} due to: ${error.message}`); } ); @@ -159,7 +159,7 @@ function excludeNodeDevDependencies(servicePath) { ); // filter out non node_modules file paths - const packageJsonPaths = packageJsonFilePaths.filter(filePath => { + const packageJsonPaths = packageJsonFilePaths.filter((filePath) => { const isNodeModulesDir = !!filePath.match(/node_modules/); return !isNodeModulesDir; }); @@ -170,14 +170,14 @@ function excludeNodeDevDependencies(servicePath) { // NOTE: using mapSeries here for a sequential computation (w/o race conditions) return ( - BbPromise.mapSeries(packageJsonPaths, packageJsonPath => { + BbPromise.mapSeries(packageJsonPaths, (packageJsonPath) => { // the path where the package.json file lives const fullPath = path.join(servicePath, packageJsonPath); const dirWithPackageJson = fullPath.replace(path.join(path.sep, 'package.json'), ''); // we added a catch which resolves so that npm commands with an exit code of 1 // (e.g. if the package.json is invalid) won't crash the dev dependency exclusion process - return BbPromise.map(['dev', 'prod'], env => { + return BbPromise.map(['dev', 'prod'], (env) => { const depFile = env === 'dev' ? nodeDevDepFile : nodeProdDepFile; return childProcess .execAsync( @@ -189,15 +189,17 @@ function excludeNodeDevDependencies(servicePath) { }) // NOTE: using mapSeries here for a sequential computation (w/o race conditions) .then(() => - BbPromise.mapSeries(['dev', 'prod'], env => { + BbPromise.mapSeries(['dev', 'prod'], (env) => { const depFile = env === 'dev' ? nodeDevDepFile : nodeProdDepFile; return fs .readFileAsync(depFile) - .then(fileContent => _.uniq(fileContent.toString('utf8').split('\n')).filter(Boolean)) + .then((fileContent) => + _.uniq(fileContent.toString('utf8').split('\n')).filter(Boolean) + ) .catch(() => BbPromise.resolve()); }) ) - .then(devAndProDependencies => { + .then((devAndProDependencies) => { const devDependencies = devAndProDependencies[0]; const prodDependencies = devAndProDependencies[1]; @@ -206,14 +208,14 @@ function excludeNodeDevDependencies(servicePath) { const nodeModulesRegex = new RegExp(`${path.join('node_modules', path.sep)}.*`, 'g'); if (dependencies.length) { - return BbPromise.map(dependencies, item => + return BbPromise.map(dependencies, (item) => item.replace(path.join(servicePath, path.sep), '') ) - .filter(item => item.length > 0 && item.match(nodeModulesRegex)) + .filter((item) => item.length > 0 && item.match(nodeModulesRegex)) .reduce((globs, item) => { const packagePath = path.join(servicePath, item, 'package.json'); return fs.readFileAsync(packagePath, 'utf-8').then( - packageJsonFile => { + (packageJsonFile) => { const lastIndex = item.lastIndexOf(path.sep) + 1; const moduleName = item.substr(lastIndex); const modulePath = item.substr(0, lastIndex); @@ -225,7 +227,7 @@ function excludeNodeDevDependencies(servicePath) { // NOTE: pkg.bin can be object, string, or undefined if (typeof bin === 'object') { - Object.keys(bin).forEach(executable => { + Object.keys(bin).forEach((executable) => { baseGlobs.push(path.join(modulePath, '.bin', executable)); }); // only 1 executable with same name as lib @@ -238,7 +240,7 @@ function excludeNodeDevDependencies(servicePath) { () => globs ); }, []) - .then(globs => { + .then((globs) => { exAndIn.exclude = exAndIn.exclude.concat(globs); return exAndIn; }); diff --git a/lib/plugins/plugin/install.js b/lib/plugins/plugin/install.js index 0771400135a..e8154402323 100644 --- a/lib/plugins/plugin/install.js +++ b/lib/plugins/plugin/install.js @@ -47,8 +47,8 @@ class PluginInstall { return BbPromise.bind(this) .then(this.validate) .then(this.getPlugins) - .then(plugins => { - const plugin = plugins.find(item => item.name === this.options.pluginName); + .then((plugins) => { + const plugin = plugins.find((item) => item.name === this.options.pluginName); if (!plugin) { this.serverless.cli.log('Plugin not found in serverless registry, continuing to install'); } @@ -71,7 +71,7 @@ class PluginInstall { const packageJsonFilePath = path.join(servicePath, 'package.json'); return fileExists(packageJsonFilePath) - .then(exists => { + .then((exists) => { // check if package.json is already present. Otherwise create one if (!exists) { this.serverless.cli.log('Creating an empty package.json file in your service directory'); @@ -100,7 +100,7 @@ class PluginInstall { } addPluginToServerlessFile() { - return this.getServerlessFilePath().then(serverlessFilePath => { + return this.getServerlessFilePath().then((serverlessFilePath) => { const fileExtension = path.extname(serverlessFilePath); if (fileExtension === '.js' || fileExtension === '.ts') { this.serverless.cli.log(` @@ -110,11 +110,11 @@ class PluginInstall { return BbPromise.resolve(); } - const checkIsArrayPluginsObject = pluginsObject => + const checkIsArrayPluginsObject = (pluginsObject) => pluginsObject == null || Array.isArray(pluginsObject); // pluginsObject type determined based on the value loaded during the serverless init. if (_.last(serverlessFilePath.split('.')) === 'json') { - return fse.readJson(serverlessFilePath).then(serverlessFileObj => { + return fse.readJson(serverlessFilePath).then((serverlessFileObj) => { const newServerlessFileObj = serverlessFileObj; const isArrayPluginsObject = checkIsArrayPluginsObject(newServerlessFileObj.plugins); // null modules property is not supported @@ -141,7 +141,7 @@ class PluginInstall { return this.serverless.yamlParser .parse(serverlessFilePath) - .then(serverlessFileObj => + .then((serverlessFileObj) => yamlAstParser.addNewArrayItem( serverlessFilePath, checkIsArrayPluginsObject(serverlessFileObj.plugins) ? 'plugins' : 'plugins.modules', @@ -158,7 +158,7 @@ class PluginInstall { this.options.pluginName, 'package.json' ); - return fse.readJson(pluginPackageJsonFilePath).then(pluginPackageJson => { + return fse.readJson(pluginPackageJsonFilePath).then((pluginPackageJson) => { if (pluginPackageJson.peerDependencies) { const pluginsArray = []; Object.entries(pluginPackageJson.peerDependencies).forEach(([k, v]) => { @@ -171,7 +171,7 @@ class PluginInstall { } npmInstall(name) { - return npmCommandDeferred.then(npmCommand => + return npmCommandDeferred.then((npmCommand) => childProcess.execAsync(`${npmCommand} install --save-dev ${name}`, { stdio: 'ignore', }) diff --git a/lib/plugins/plugin/lib/utils.js b/lib/plugins/plugin/lib/utils.js index cb8cf86d0aa..8ec3ef8cec2 100644 --- a/lib/plugins/plugin/lib/utils.js +++ b/lib/plugins/plugin/lib/utils.js @@ -20,7 +20,7 @@ module.exports = { }, getServerlessFilePath() { - return getServerlessConfigFilePath(this.serverless).then(filePath => { + return getServerlessConfigFilePath(this.serverless).then((filePath) => { if (filePath) return filePath; throw new this.serverless.classes.Error( 'Could not find any serverless service definition file.' @@ -45,8 +45,8 @@ module.exports = { } return fetch(endpoint, options) - .then(result => result.json()) - .then(json => json); + .then((result) => result.json()) + .then((json) => json); }, getPluginInfo(name) { @@ -65,7 +65,7 @@ module.exports = { if (plugins && plugins.length) { // order plugins by name const orderedPlugins = _.orderBy(plugins, ['name'], ['asc']); - orderedPlugins.forEach(plugin => { + orderedPlugins.forEach((plugin) => { message += `${chalk.yellow.underline(plugin.name)} - ${plugin.description}\n`; }); // remove last two newlines for a prettier output diff --git a/lib/plugins/plugin/list.js b/lib/plugins/plugin/list.js index b72dfc24080..b878de9eeb3 100644 --- a/lib/plugins/plugin/list.js +++ b/lib/plugins/plugin/list.js @@ -29,7 +29,7 @@ class PluginList { list() { return BbPromise.bind(this) .then(this.getPlugins) - .then(plugins => this.display(plugins)); + .then((plugins) => this.display(plugins)); } } diff --git a/lib/plugins/plugin/search.js b/lib/plugins/plugin/search.js index ff43503faf5..791b584979c 100644 --- a/lib/plugins/plugin/search.js +++ b/lib/plugins/plugin/search.js @@ -37,12 +37,12 @@ class PluginSearch { search() { return BbPromise.bind(this) .then(this.getPlugins) - .then(plugins => { + .then((plugins) => { // filter out plugins which match the query const regex = new RegExp(this.options.query); const filteredPlugins = plugins.filter( - plugin => plugin.name.match(regex) || plugin.description.match(regex) + (plugin) => plugin.name.match(regex) || plugin.description.match(regex) ); // print a message with the search result @@ -53,7 +53,7 @@ class PluginSearch { return filteredPlugins; }) - .then(plugins => { + .then((plugins) => { this.display(plugins); }); } diff --git a/lib/plugins/plugin/uninstall.js b/lib/plugins/plugin/uninstall.js index d760cbf670f..f201420a712 100644 --- a/lib/plugins/plugin/uninstall.js +++ b/lib/plugins/plugin/uninstall.js @@ -45,8 +45,8 @@ class PluginUninstall { return BbPromise.bind(this) .then(this.validate) .then(this.getPlugins) - .then(plugins => { - const plugin = plugins.find(item => item.name === this.options.pluginName); + .then((plugins) => { + const plugin = plugins.find((item) => item.name === this.options.pluginName); if (!plugin) { this.serverless.cli.log( 'Plugin not found in serverless registry, continuing to uninstall' @@ -71,7 +71,7 @@ class PluginUninstall { } removePluginFromServerlessFile() { - return this.getServerlessFilePath().then(serverlessFilePath => { + return this.getServerlessFilePath().then((serverlessFilePath) => { const fileExtension = path.extname(serverlessFilePath); if (fileExtension === '.js' || fileExtension === '.ts') { this.serverless.cli.log(` @@ -82,7 +82,7 @@ class PluginUninstall { } if (_.last(serverlessFilePath.split('.')) === 'json') { - return fse.readJson(serverlessFilePath).then(serverlessFileObj => { + return fse.readJson(serverlessFilePath).then((serverlessFileObj) => { const isArrayPluginsObject = Array.isArray(serverlessFileObj.plugins); const plugins = isArrayPluginsObject ? serverlessFileObj.plugins @@ -105,7 +105,7 @@ class PluginUninstall { return this.serverless.yamlParser .parse(serverlessFilePath) - .then(serverlessFileObj => + .then((serverlessFileObj) => yamlAstParser.removeExistingArrayItem( serverlessFilePath, Array.isArray(serverlessFileObj.plugins) ? 'plugins' : 'plugins.modules', @@ -124,10 +124,10 @@ class PluginUninstall { ); return fse .readJson(pluginPackageJsonFilePath) - .then(pluginPackageJson => { + .then((pluginPackageJson) => { if (pluginPackageJson.peerDependencies) { const pluginsArray = []; - Object.keys(pluginPackageJson.peerDependencies).forEach(k => { + Object.keys(pluginPackageJson.peerDependencies).forEach((k) => { pluginsArray.push(k); }); return BbPromise.map(pluginsArray, this.npmUninstall); diff --git a/lib/plugins/print.js b/lib/plugins/print.js index f163c7f2747..ada749c2e6f 100644 --- a/lib/plugins/print.js +++ b/lib/plugins/print.js @@ -95,14 +95,14 @@ class Print { // the codebase. Avoiding that, this method must read the serverless.yml file itself, adorn it // as the Service class would and then populate it, reversing the adornments thereafter in // preparation for printing the service for the user. - return getServerlessConfigFile(this.serverless).then(svc => { + return getServerlessConfigFile(this.serverless).then((svc) => { const service = svc; this.adorn(service); // Need to delete variableSyntax to avoid self-matching errors this.serverless.variables.loadVariableSyntax(); delete service.provider.variableSyntax; // cached by adorn, restored by strip this.serverless.variables.service = service; - return this.serverless.variables.populateObject(service).then(populated => { + return this.serverless.variables.populateObject(service).then((populated) => { let conf = populated; this.strip(conf); diff --git a/lib/utils/analytics/generatePayload.js b/lib/utils/analytics/generatePayload.js index bf4542e960f..08d4a5f15cd 100644 --- a/lib/utils/analytics/generatePayload.js +++ b/lib/utils/analytics/generatePayload.js @@ -15,7 +15,7 @@ const versions = { const checkIsTabAutocompletionInstalled = async () => { try { - return (await fs.readdir(path.resolve(os.homedir(), '.config/tabtab'))).some(filename => + return (await fs.readdir(path.resolve(os.homedir(), '.config/tabtab'))).some((filename) => filename.startsWith('serverless.') ); } catch { @@ -23,7 +23,7 @@ const checkIsTabAutocompletionInstalled = async () => { } }; -module.exports = async serverless => { +module.exports = async (serverless) => { const { service: serviceConfig, config } = serverless; const { provider: providerConfig } = serviceConfig; const provider = serverless.getProvider(providerConfig.name); @@ -61,9 +61,9 @@ module.exports = async serverless => { region: isAwsProvider ? provider.getRegion() : providerConfig.region, }, plugins: serviceConfig.plugins ? serviceConfig.plugins.modules || serviceConfig.plugins : [], - functions: Object.values(serviceConfig.functions).map(functionConfig => ({ + functions: Object.values(serviceConfig.functions).map((functionConfig) => ({ runtime: functionConfig.runtime || defaultRuntime, - events: functionConfig.events.map(eventConfig => ({ + events: functionConfig.events.map((eventConfig) => ({ type: Object.keys(eventConfig)[0] || null, })), })), diff --git a/lib/utils/analytics/index.js b/lib/utils/analytics/index.js index eeb67cc176e..98c7f9f844b 100644 --- a/lib/utils/analytics/index.js +++ b/lib/utils/analytics/index.js @@ -31,7 +31,7 @@ const markServerlessRunEnd = () => (serverlessRunEndTime = Date.now()); const processResponseBody = (response, id, startTime) => { return response.json().then( - result => { + (result) => { const endTime = Date.now(); --ongoingRequestsCount; if (serverlessRunEndTime && !ongoingRequestsCount && process.env.SLS_STATS_DEBUG) { @@ -45,7 +45,7 @@ const processResponseBody = (response, id, startTime) => { } return result; }, - error => { + (error) => { --ongoingRequestsCount; logError(`Response processing error for ${id || ''}`, error); return null; @@ -67,7 +67,7 @@ function request(payload, { id, timeout } = {}) { timeout: timeout || 3500, body: JSON.stringify(payload), }).then( - response => { + (response) => { if (response.status < 200 || response.status >= 300) { logError('Unexpected request response', response); return processResponseBody(response, id, startTime); @@ -75,13 +75,13 @@ function request(payload, { id, timeout } = {}) { if (!id) return processResponseBody(response, id, startTime); return fse.unlink(join(cacheDirPath, id)).then( () => processResponseBody(response, id, startTime), - error => { + (error) => { logError(`Could not remove cache file ${id}`, error); return processResponseBody(response, id, startTime); } ); }, - networkError => { + (networkError) => { logError('Request network error', networkError); return null; } @@ -101,9 +101,9 @@ function report(payload, options = {}) { (function self() { return fse .writeJson(join(cacheDirPath, id), { payload, timestamp: Date.now() }) - .catch(error => { + .catch((error) => { if (error.code === 'ENOENT') { - return fse.ensureDir(cacheDirPath).then(self, ensureDirError => { + return fse.ensureDir(cacheDirPath).then(self, (ensureDirError) => { logError('Cache dir creation error:', ensureDirError); }); } @@ -127,15 +127,15 @@ function sendPending(options = {}) { if (!cacheDirPath) return null; const limit = pLimit(3); return fse.readdir(cacheDirPath).then( - dirFilenames => { + (dirFilenames) => { if (!options.serverlessExecutionSpan) process.nextTick(markServerlessRunEnd); return BbPromise.all( - dirFilenames.map(dirFilename => + dirFilenames.map((dirFilename) => limit(() => { if (serverlessRunEndTime) return null; if (!isUuid(dirFilename)) return null; return fse.readJson(join(cacheDirPath, dirFilename)).then( - data => { + (data) => { if (data && data.payload) { const timestamp = Number(data.timestamp); if (timestamp > timestampWeekBefore) { @@ -149,14 +149,14 @@ function sendPending(options = {}) { logError(`Invalid cached data ${dirFilename}`, data); } // Invalid or stale event, do not send, and remove from cache - return fse.unlink(join(cacheDirPath, dirFilename)).catch(error => { + return fse.unlink(join(cacheDirPath, dirFilename)).catch((error) => { logError(`Could not remove cache file ${dirFilename}`, error); }); }, - readJsonError => { + (readJsonError) => { if (readJsonError.code === 'ENOENT') return null; // Race condition logError(`Cannot read cache file: ${dirFilename}`, readJsonError); - return fse.unlink(join(cacheDirPath, dirFilename)).catch(error => { + return fse.unlink(join(cacheDirPath, dirFilename)).catch((error) => { logError(`Could not remove cache file ${dirFilename}`, error); }); } @@ -165,7 +165,7 @@ function sendPending(options = {}) { ) ); }, - readdirError => { + (readdirError) => { if (readdirError.code !== 'ENOENT') logError('Cannot access cache dir', readdirError); } ); diff --git a/lib/utils/autocomplete.js b/lib/utils/autocomplete.js index 9ff36455a45..5c30a31fdd9 100644 --- a/lib/utils/autocomplete.js +++ b/lib/utils/autocomplete.js @@ -13,7 +13,7 @@ const getSuggestions = (commands, env) => { switch (tokens.length) { case 1: case 2: - log(Object.keys(commands).filter(commandName => !commands[commandName].isHidden)); + log(Object.keys(commands).filter((commandName) => !commands[commandName].isHidden)); return; case 3: if (commands[env.prev]) log(commands[env.prev]); @@ -35,16 +35,16 @@ const cacheFileValid = (serverlessConfigFile, validationHash) => { const autocomplete = () => { const servicePath = process.cwd(); return getServerlessConfigFile({ processedInput: { options: {} }, config: { servicePath } }).then( - serverlessConfigFile => + (serverlessConfigFile) => getCacheFile(servicePath) - .then(cacheFile => { + .then((cacheFile) => { if (!cacheFile || !cacheFileValid(serverlessConfigFile, cacheFile.validationHash)) { const serverless = new Serverless(); return serverless.init().then(() => getCacheFile(servicePath)); } return cacheFile; }) - .then(cacheFile => { + .then((cacheFile) => { if (!cacheFile || !cacheFileValid(serverlessConfigFile, cacheFile.validationHash)) { return null; } diff --git a/lib/utils/awsSdkPatch.js b/lib/utils/awsSdkPatch.js index 02f730879a0..0e330fefb8d 100644 --- a/lib/utils/awsSdkPatch.js +++ b/lib/utils/awsSdkPatch.js @@ -4,7 +4,7 @@ const metadataServicePrototype = require('aws-sdk/lib/metadata_service').prototy const originalRequest = metadataServicePrototype.request; -metadataServicePrototype.request = function(path, options, callback) { +metadataServicePrototype.request = function (path, options, callback) { this.maxRetries = 0; if (!this.httpOptions.connectTimeout) this.httpOptions.connectTimeout = 1000; return originalRequest.call(this, path, options, callback); diff --git a/lib/utils/createFromTemplate.js b/lib/utils/createFromTemplate.js index 69fb811727f..84538a8ec6f 100644 --- a/lib/utils/createFromTemplate.js +++ b/lib/utils/createFromTemplate.js @@ -7,7 +7,7 @@ const { renameService } = require('./renameService'); const serverlessPath = join(__dirname, '../../'); -const resolveServiceName = path => { +const resolveServiceName = (path) => { let serviceName = basename(path) .toLowerCase() .replace(/[^0-9a-z.]+/g, '-'); @@ -36,7 +36,7 @@ module.exports = (templateName, destPath, options = {}) => })(); if (packageName) options.name = packageName; } - copy(templateSrcDir, destPath, copyError => { + copy(templateSrcDir, destPath, (copyError) => { if (copyError) { reject(copyError); return; @@ -45,12 +45,12 @@ module.exports = (templateName, destPath, options = {}) => BbPromise.all([ new BbPromise((gitignoreRenameResolve, gitIgnoreRenameReject) => { const gitignorePath = join(destPath, 'gitignore'); - exists(gitignorePath, hasGitignore => { + exists(gitignorePath, (hasGitignore) => { if (!hasGitignore) { gitignoreRenameResolve(); return; } - rename(gitignorePath, join(destPath, '.gitignore'), renameError => { + rename(gitignorePath, join(destPath, '.gitignore'), (renameError) => { if (renameError) gitIgnoreRenameReject(renameError); else gitignoreRenameResolve(); }); diff --git a/lib/utils/deepSortObjectByKey.js b/lib/utils/deepSortObjectByKey.js index 070c5580e45..b88aecb1adc 100644 --- a/lib/utils/deepSortObjectByKey.js +++ b/lib/utils/deepSortObjectByKey.js @@ -2,7 +2,7 @@ const _ = require('lodash'); -const deepSortObjectByKey = obj => { +const deepSortObjectByKey = (obj) => { if (Array.isArray(obj)) { return obj.map(deepSortObjectByKey); } diff --git a/lib/utils/downloadTemplateFromRepo.js b/lib/utils/downloadTemplateFromRepo.js index a6af2689db1..705298a06c4 100644 --- a/lib/utils/downloadTemplateFromRepo.js +++ b/lib/utils/downloadTemplateFromRepo.js @@ -25,10 +25,7 @@ function getPathDirectory(length, parts) { if (!parts) { return ''; } - return parts - .slice(length) - .filter(Boolean) - .join(path.sep); + return parts.slice(length).filter(Boolean).join(path.sep); } /** @@ -150,8 +147,8 @@ function retrieveBitbucketServerInfo(url) { const versionInfoPath = `${url.protocol}//${url.hostname}/rest/api/1.0/application-properties`; return fetch(versionInfoPath) - .then(resp => resp.json()) - .then(body => body.displayName === 'Bitbucket'); + .then((resp) => resp.json()) + .then((body) => body.displayName === 'Bitbucket'); } /** @@ -239,7 +236,7 @@ function parseRepoURL(inputUrl) { const err = new ServerlessError(msg); // test if it's a private bitbucket server return retrieveBitbucketServerInfo(url) - .then(isBitbucket => { + .then((isBitbucket) => { if (!isBitbucket) { return reject(err); } @@ -258,7 +255,7 @@ function parseRepoURL(inputUrl) { * @returns {Promise} */ function downloadTemplateFromRepo(inputUrl, templateName, downloadPath) { - return parseRepoURL(inputUrl).then(repoInformation => { + return parseRepoURL(inputUrl).then((repoInformation) => { let serviceName; let dirName; let downloadServicePath; diff --git a/lib/utils/eventuallyUpdate.js b/lib/utils/eventuallyUpdate.js index e9ae5cac41e..607d2c57fce 100644 --- a/lib/utils/eventuallyUpdate.js +++ b/lib/utils/eventuallyUpdate.js @@ -83,7 +83,7 @@ const standaloneUpdate = async (serverless, { newVersion, abortHandler }) => { } }; -module.exports = async serverless => { +module.exports = async (serverless) => { if (!serverless.onExitPromise) return; // Not intended for programmatic Serverless instances if (serverless.isLocallyInstalled) return; if (serverless.isStandaloneExecutable) { diff --git a/lib/utils/fs/copyDirContentsSync.js b/lib/utils/fs/copyDirContentsSync.js index 7dbb70a14bd..25198417f58 100644 --- a/lib/utils/fs/copyDirContentsSync.js +++ b/lib/utils/fs/copyDirContentsSync.js @@ -2,7 +2,7 @@ const fse = require('fs-extra'); -const isNotSymbolicLink = src => !fse.lstatSync(src).isSymbolicLink(); +const isNotSymbolicLink = (src) => !fse.lstatSync(src).isSymbolicLink(); function copyDirContentsSync(srcDir, destDir, { noLinks = false } = {}) { const copySyncOptions = { diff --git a/lib/utils/fs/createZipFile.js b/lib/utils/fs/createZipFile.js index 5207313ec4a..73e48939837 100644 --- a/lib/utils/fs/createZipFile.js +++ b/lib/utils/fs/createZipFile.js @@ -7,7 +7,7 @@ const BbPromise = require('bluebird'); const walkDirSync = require('../fs/walkDirSync'); function createZipFile(srcDirPath, outputFilePath) { - const files = walkDirSync(srcDirPath).map(file => ({ + const files = walkDirSync(srcDirPath).map((file) => ({ input: file, output: file.replace(path.join(srcDirPath, path.sep), ''), })); @@ -21,7 +21,7 @@ function createZipFile(srcDirPath, outputFilePath) { output.on('open', () => { archive.pipe(output); - files.forEach(file => { + files.forEach((file) => { // TODO: update since this is REALLY slow if (fs.lstatSync(file.input).isFile()) { archive.append(fs.createReadStream(file.input), { name: file.output }); @@ -31,7 +31,7 @@ function createZipFile(srcDirPath, outputFilePath) { archive.finalize(); }); - archive.on('error', err => reject(err)); + archive.on('error', (err) => reject(err)); output.on('close', () => resolve(outputFilePath)); }); } diff --git a/lib/utils/fs/dirExists.js b/lib/utils/fs/dirExists.js index ecada53c440..38902056059 100644 --- a/lib/utils/fs/dirExists.js +++ b/lib/utils/fs/dirExists.js @@ -4,8 +4,8 @@ const fse = require('fs-extra'); function dirExists(path) { return fse.lstat(path).then( - stats => stats.isDirectory(), - error => { + (stats) => stats.isDirectory(), + (error) => { if (error.code === 'ENOENT') { return false; } diff --git a/lib/utils/fs/fileExists.js b/lib/utils/fs/fileExists.js index 1043a0d7172..9de09bf01aa 100644 --- a/lib/utils/fs/fileExists.js +++ b/lib/utils/fs/fileExists.js @@ -5,7 +5,7 @@ const fse = require('fs-extra'); function fileExists(filePath) { return fse .lstat(filePath) - .then(stats => stats.isFile()) + .then((stats) => stats.isFile()) .catch(() => false); } diff --git a/lib/utils/fs/readFile.js b/lib/utils/fs/readFile.js index e9d776447b0..3276a9afeb6 100644 --- a/lib/utils/fs/readFile.js +++ b/lib/utils/fs/readFile.js @@ -4,7 +4,7 @@ const fse = require('fs-extra'); const parse = require('./parse'); function readFile(filePath) { - return fse.readFile(filePath, 'utf8').then(contents => parse(filePath, contents)); + return fse.readFile(filePath, 'utf8').then((contents) => parse(filePath, contents)); } module.exports = readFile; diff --git a/lib/utils/fs/walkDirSync.js b/lib/utils/fs/walkDirSync.js index d0038ceddbf..77f4cc4b2c6 100644 --- a/lib/utils/fs/walkDirSync.js +++ b/lib/utils/fs/walkDirSync.js @@ -12,7 +12,7 @@ function walkDirSync(dirPath, opts) { ); let filePaths = []; const list = fs.readdirSync(dirPath); - list.forEach(filePathParam => { + list.forEach((filePathParam) => { let filePath = filePathParam; filePath = path.join(dirPath, filePath); const stat = options.noLinks ? fs.lstatSync(filePath) : fs.statSync(filePath); diff --git a/lib/utils/getCacheFile.js b/lib/utils/getCacheFile.js index e44ffda6950..0875574e399 100644 --- a/lib/utils/getCacheFile.js +++ b/lib/utils/getCacheFile.js @@ -4,9 +4,9 @@ const fileExists = require('./fs/fileExists'); const readFile = require('./fs/readFile'); const getCacheFilePath = require('./getCacheFilePath'); -const getCacheFile = function(servicePath) { +const getCacheFile = function (servicePath) { const cacheFilePath = getCacheFilePath(servicePath); - return fileExists(cacheFilePath).then(exists => { + return fileExists(cacheFilePath).then((exists) => { if (!exists) { return false; } diff --git a/lib/utils/getCacheFilePath.js b/lib/utils/getCacheFilePath.js index 72ec74097b1..adf6d5d259f 100644 --- a/lib/utils/getCacheFilePath.js +++ b/lib/utils/getCacheFilePath.js @@ -4,12 +4,9 @@ const homedir = require('os').homedir(); const path = require('path'); const crypto = require('crypto'); -const getCacheFilePath = function(srvcPath) { +const getCacheFilePath = function (srvcPath) { const servicePath = srvcPath || process.cwd(); - const servicePathHash = crypto - .createHash('sha256') - .update(servicePath) - .digest('hex'); + const servicePathHash = crypto.createHash('sha256').update(servicePath).digest('hex'); return path.join(homedir, '.serverless', 'cache', servicePathHash, 'autocomplete.json'); }; diff --git a/lib/utils/getCommandSuggestion.js b/lib/utils/getCommandSuggestion.js index 0299df02a64..67c3af8b660 100644 --- a/lib/utils/getCommandSuggestion.js +++ b/lib/utils/getCommandSuggestion.js @@ -19,7 +19,7 @@ const getCommandSuggestion = (inputCommand, allCommandsObject) => { let suggestion; const commandWordsArray = getCollectCommandWords(allCommandsObject); let minValue = 0; - commandWordsArray.forEach(correctCommand => { + commandWordsArray.forEach((correctCommand) => { const distance = getDistance(inputCommand, correctCommand); if (minValue === 0) { suggestion = correctCommand; diff --git a/lib/utils/getEnsureArtifact.js b/lib/utils/getEnsureArtifact.js index 44ffcf84540..ddb8737eed4 100644 --- a/lib/utils/getEnsureArtifact.js +++ b/lib/utils/getEnsureArtifact.js @@ -15,16 +15,16 @@ const ensureArtifact = memoizee( return fse .lstat(path.resolve(cachePath, fileName)) .then( - stats => { + (stats) => { if (stats.isFile()) return true; return false; }, - error => { + (error) => { if (error.code === 'ENOENT') return false; throw error; } ) - .then(isGenerated => { + .then((isGenerated) => { if (!isGenerated) return fse.ensureDir(cachePath).then(() => generate(cachePath)); return null; }) diff --git a/lib/utils/getServerlessConfigFile.js b/lib/utils/getServerlessConfigFile.js index b5e52d641aa..819937dc787 100644 --- a/lib/utils/getServerlessConfigFile.js +++ b/lib/utils/getServerlessConfigFile.js @@ -13,7 +13,7 @@ const ServerlessError = require('../classes/Error').ServerlessError; const getConfigFilePath = async (servicePath, options = {}) => { if (options.config) { const customPath = path.join(servicePath, options.config); - return fileExists(customPath).then(exists => { + return fileExists(customPath).then((exists) => { return exists ? customPath : null; }); } @@ -47,18 +47,18 @@ const getConfigFilePath = async (servicePath, options = {}) => { return null; }; -const getServerlessConfigFilePath = serverless => { +const getServerlessConfigFilePath = (serverless) => { return getConfigFilePath( serverless.config.servicePath || process.cwd(), serverless.processedInput.options ); }; -const resolveTsNode = serviceDir => { +const resolveTsNode = (serviceDir) => { const resolveModuleRealPath = (...args) => resolveModulePath(...args).then(({ realPath }) => realPath); - const ifNotFoundContinueWith = cb => error => { + const ifNotFoundContinueWith = (cb) => (error) => { if (error.code !== 'MODULE_NOT_FOUND') throw error; return cb(); }; @@ -68,7 +68,7 @@ const resolveTsNode = serviceDir => { const resolveAsGlobalInstallation = () => spawn('npm', ['root', '-g']).then( ({ stdoutBuffer }) => require.resolve(`${String(stdoutBuffer).trim()}/ts-node`), - error => { + (error) => { if (error.code !== 'ENOENT') throw error; throw Object.assign(new Error('npm not installed', { code: 'MODULE_NOT_FOUND' })); } @@ -86,10 +86,10 @@ const resolveTsNode = serviceDir => { .catch(ifNotFoundContinueWith(throwTsNodeError)); }; -const handleJsOrTsConfigFile = configFile => +const handleJsOrTsConfigFile = (configFile) => BbPromise.try(() => { if (!configFile.endsWith('.ts')) return null; - return resolveTsNode(path.dirname(configFile)).then(tsNodePath => { + return resolveTsNode(path.dirname(configFile)).then((tsNodePath) => { try { require(tsNodePath).register(); } catch (error) { @@ -108,8 +108,8 @@ const handleJsOrTsConfigFile = configFile => } }); -const getServerlessConfigFile = memoizee(serverless => - getServerlessConfigFilePath(serverless).then(configFilePath => { +const getServerlessConfigFile = memoizee((serverless) => + getServerlessConfigFilePath(serverless).then((configFilePath) => { if (!configFilePath) return null; const fileExtension = path.extname(configFilePath); const isJSOrTsConfigFile = fileExtension === '.js' || fileExtension === '.ts'; @@ -117,7 +117,7 @@ const getServerlessConfigFile = memoizee(serverless => return (isJSOrTsConfigFile ? handleJsOrTsConfigFile(configFilePath) : readFile(configFilePath) - ).then(config => { + ).then((config) => { if (_.isPlainObject(config)) return config; throw new ServerlessError( `${path.basename(configFilePath)} must export plain object`, diff --git a/lib/utils/log/consoleLog.js b/lib/utils/log/consoleLog.js index b256d8efb72..4bbe9966199 100644 --- a/lib/utils/log/consoleLog.js +++ b/lib/utils/log/consoleLog.js @@ -1,6 +1,6 @@ 'use strict'; -const consoleLog = function(...args) { +const consoleLog = function (...args) { console.log(args); // eslint-disable-line no-console }; diff --git a/lib/utils/log/fileLog.js b/lib/utils/log/fileLog.js index a3ed8ae77f0..4b7e5f0f640 100644 --- a/lib/utils/log/fileLog.js +++ b/lib/utils/log/fileLog.js @@ -3,7 +3,7 @@ const fs = require('fs'); const path = require('path'); -const fileLog = function(...args) { +const fileLog = function (...args) { // TODO BRN: This does not guarantee order, is not multi process safe, // TODO BRN: and is not guaranteed to complete before exit. fs.appendFileSync(path.join(process.cwd(), 'sls.log'), `${args.join()}\n`); diff --git a/lib/utils/log/log.js b/lib/utils/log/log.js index bba119acc88..f79ec5fcfad 100644 --- a/lib/utils/log/log.js +++ b/lib/utils/log/log.js @@ -8,8 +8,8 @@ const loggers = [ fileLog, ]; -const log = function(...args) { - loggers.forEach(logger => logger(...args)); +const log = function (...args) { + loggers.forEach((logger) => logger(...args)); }; module.exports = log; diff --git a/lib/utils/log/muteConsoleLog.js b/lib/utils/log/muteConsoleLog.js index bd2a9985daf..a076b1a7dd9 100644 --- a/lib/utils/log/muteConsoleLog.js +++ b/lib/utils/log/muteConsoleLog.js @@ -5,7 +5,7 @@ 'use strict'; -module.exports = callback => { +module.exports = (callback) => { const original = console.log; console.log = () => {}; const restore = () => (console.log = original); @@ -18,11 +18,11 @@ module.exports = callback => { } if (result && typeof result.then === 'function') { return result.then( - resolution => { + (resolution) => { restore(); return resolution; }, - error => { + (error) => { restore(); throw error; } diff --git a/lib/utils/log/serverlessLog.js b/lib/utils/log/serverlessLog.js index b1675b114df..94ba61795e0 100644 --- a/lib/utils/log/serverlessLog.js +++ b/lib/utils/log/serverlessLog.js @@ -4,7 +4,7 @@ const chalk = require('chalk'); -const log = function(message) { +const log = function (message) { console.log(`Serverless: ${chalk.yellow(message)}`); }; diff --git a/lib/utils/logDeprecation.js b/lib/utils/logDeprecation.js index ac0605c2d5a..cb0a22e187f 100644 --- a/lib/utils/logDeprecation.js +++ b/lib/utils/logDeprecation.js @@ -14,7 +14,7 @@ function extractCodes(codesStr) { return new Set(codesStr.split(',')); } -const resolveDeprecatedByService = weakMemoizee(serviceConfig => { +const resolveDeprecatedByService = weakMemoizee((serviceConfig) => { let disabledDeprecations = []; if (typeof serviceConfig.disabledDeprecations === 'string') { disabledDeprecations = [serviceConfig.disabledDeprecations]; diff --git a/lib/utils/npm-command-deferred.js b/lib/utils/npm-command-deferred.js index bae5234693d..baea3a106a7 100644 --- a/lib/utils/npm-command-deferred.js +++ b/lib/utils/npm-command-deferred.js @@ -8,12 +8,12 @@ const localNpmBinPath = path.join(__dirname, '../../node_modules/npm/bin/npm-cli module.exports = fse .stat(localNpmBinPath) .then( - stats => stats.isFile(), - error => { + (stats) => stats.isFile(), + (error) => { if (error.code === 'ENOENT') return null; throw error; } ) - .then(isNpmInstalledLocaly => { + .then((isNpmInstalledLocaly) => { return isNpmInstalledLocaly ? `node ${localNpmBinPath}` : 'npm'; }); diff --git a/lib/utils/npmPackage/isWritable.js b/lib/utils/npmPackage/isWritable.js index 10e3eb024fc..91bb772b541 100644 --- a/lib/utils/npmPackage/isWritable.js +++ b/lib/utils/npmPackage/isWritable.js @@ -6,7 +6,7 @@ const fs = require('fs').promises; const npmPackageRoot = path.resolve(__dirname, '../../../'); -module.exports = async serverless => { +module.exports = async (serverless) => { const stats = await fs.stat(npmPackageRoot); try { await fs.utimes(npmPackageRoot, String(stats.atimeMs / 1000), String(stats.mtimeMs / 1000)); diff --git a/lib/utils/open.js b/lib/utils/open.js index 57301c712d4..e6ad9468c56 100644 --- a/lib/utils/open.js +++ b/lib/utils/open.js @@ -23,7 +23,7 @@ const localXdgOpenPath = path.join(__dirname, 'xdg-open'); // Convert a path from WSL format to Windows format: // `/mnt/c/Program Files/Example/MyApp.exe` → `C:\Program Files\Example\MyApp.exe` -const wslToWindowsPath = filePath => +const wslToWindowsPath = (filePath) => pExecFile('wslpath', ['-w', filePath]).then(({ stdout }) => stdout.trim()); module.exports = (target, options) => { @@ -79,7 +79,7 @@ module.exports = (target, options) => { .then(() => { if (options.app) { if (isWsl && options.app.startsWith('/mnt/')) { - return wslToWindowsPath(options.app).then(windowsPath => { + return wslToWindowsPath(options.app).then((windowsPath) => { options.app = windowsPath; cliArguments.push(options.app); }); @@ -108,7 +108,7 @@ module.exports = (target, options) => { return pAccess(localXdgOpenPath, fs.constants.X_OK) .then(() => true) .catch(() => false) - .then(exeLocalXdgOpen => { + .then((exeLocalXdgOpen) => { const useSystemXdgOpen = process.versions.electron || process.platform === 'android' || @@ -146,7 +146,7 @@ module.exports = (target, options) => { return new Promise((resolve, reject) => { subprocess.once('error', reject); - subprocess.once('close', exitCode => { + subprocess.once('close', (exitCode) => { if (exitCode > 0) { reject(new Error(`Exited with code ${exitCode}`)); return; @@ -156,7 +156,7 @@ module.exports = (target, options) => { }); }); } - subprocess.once('error', error => { + subprocess.once('error', (error) => { if (process.env.SLS_DEBUG) { process.stdout.write( `Serverless: ${chalk.red(`Opening of browser window errored with ${error.stack}`)}\n` diff --git a/lib/utils/openBrowser.js b/lib/utils/openBrowser.js index cd3f382d04e..2bbf0e35673 100644 --- a/lib/utils/openBrowser.js +++ b/lib/utils/openBrowser.js @@ -14,7 +14,7 @@ module.exports = function openBrowser(url) { if (browser === 'none' || isDockerContainer()) return; if (process.platform === 'darwin' && browser === 'open') browser = undefined; const options = { wait: false, app: browser }; - opn(url, options).catch(err => { + opn(url, options).catch((err) => { if (process.env.SLS_DEBUG) { process.stdout.write( `Serverless: ${chalk.red(`Opening of browser window errored with ${err.stack}`)}\n` diff --git a/lib/utils/processBackendNotificationRequest.js b/lib/utils/processBackendNotificationRequest.js index 153d84af0cd..681589abc7e 100644 --- a/lib/utils/processBackendNotificationRequest.js +++ b/lib/utils/processBackendNotificationRequest.js @@ -4,7 +4,7 @@ const chalk = require('chalk'); const processBackendNotificationRequest = require('@serverless/utils/process-backend-notification-request'); -module.exports = notifications => { +module.exports = (notifications) => { const notification = processBackendNotificationRequest(notifications); if (!notification) return; diff --git a/lib/utils/resolveCliInput.js b/lib/utils/resolveCliInput.js index 2d774d45a3f..c113c74477d 100644 --- a/lib/utils/resolveCliInput.js +++ b/lib/utils/resolveCliInput.js @@ -11,7 +11,7 @@ const yargsOptions = { configuration: { 'parse-numbers': false }, }; -module.exports = _.memoize(inputArray => { +module.exports = _.memoize((inputArray) => { const argv = yargsParser(inputArray, yargsOptions); const commands = [].concat(argv._); diff --git a/lib/utils/standalone-patch.js b/lib/utils/standalone-patch.js index 23198756740..dca7c1f7699 100644 --- a/lib/utils/standalone-patch.js +++ b/lib/utils/standalone-patch.js @@ -33,7 +33,7 @@ fs.copyFile = function copyFile(src, dest, flags, callback) { return; } if (flags & fs.constants.COPYFILE_EXCL) { - fs.stat(dest, statError => { + fs.stat(dest, (statError) => { if (!statError) { callback(Object.assign(new Error('File already exists'), { code: 'EEXIST' })); return; diff --git a/lib/utils/standalone.js b/lib/utils/standalone.js index 8d17db1294b..484c9b1ddcc 100644 --- a/lib/utils/standalone.js +++ b/lib/utils/standalone.js @@ -33,7 +33,7 @@ module.exports = { ); return isInChina ? body : JSON.parse(body).tag_name; }, - resolveUrl: tagName => { + resolveUrl: (tagName) => { return isInChina ? `https://sls-standalone-sv-1300963013.cos.na-siliconvalley.myqcloud.com/${tagName}/` + `serverless-${platform}-${arch}` diff --git a/lib/utils/tabCompletion/tabtabOptions.js b/lib/utils/tabCompletion/tabtabOptions.js index ccd49c637c0..57328ecc9ea 100644 --- a/lib/utils/tabCompletion/tabtabOptions.js +++ b/lib/utils/tabCompletion/tabtabOptions.js @@ -1,3 +1,3 @@ 'use strict'; -module.exports = ['serverless', 'sls'].map(name => ({ name, completer: name })); +module.exports = ['serverless', 'sls'].map((name) => ({ name, completer: name })); diff --git a/lib/utils/yamlAstParser.js b/lib/utils/yamlAstParser.js index abc16521e9c..1d35a209e5e 100644 --- a/lib/utils/yamlAstParser.js +++ b/lib/utils/yamlAstParser.js @@ -8,7 +8,7 @@ const os = require('os'); const chalk = require('chalk'); const log = require('./log/serverlessLog'); -const findKeyChain = astContent => { +const findKeyChain = (astContent) => { let content = astContent; const chain = [content.key.value]; while (content.parent) { @@ -23,7 +23,7 @@ const findKeyChain = astContent => { const parseAST = (ymlAstContent, astObject) => { let newAstObject = astObject || {}; if (ymlAstContent.mappings && Array.isArray(ymlAstContent.mappings)) { - ymlAstContent.mappings.forEach(v => { + ymlAstContent.mappings.forEach((v) => { if (!v.value) { const errorMessage = [ 'Serverless: ', @@ -56,7 +56,7 @@ const parseAST = (ymlAstContent, astObject) => { const constructPlainObject = (ymlAstContent, branchObject) => { const newbranchObject = branchObject || {}; if (ymlAstContent.mappings && Array.isArray(ymlAstContent.mappings)) { - ymlAstContent.mappings.forEach(v => { + ymlAstContent.mappings.forEach((v) => { if (!v.value) { // no need to log twice, parseAST will log errors return; @@ -68,7 +68,7 @@ const constructPlainObject = (ymlAstContent, branchObject) => { newbranchObject[v.key.value] = constructPlainObject(v.value, {}); } else if (v.key.kind === 0 && v.value.kind === 3) { const plainArray = []; - v.value.items.forEach(c => { + v.value.items.forEach((c) => { plainArray.push(c.value); }); newbranchObject[v.key.value] = plainArray; @@ -80,7 +80,7 @@ const constructPlainObject = (ymlAstContent, branchObject) => { }; const addNewArrayItem = (ymlFile, pathInYml, newValue) => - fs.readFileAsync(ymlFile, 'utf8').then(yamlContent => { + fs.readFileAsync(ymlFile, 'utf8').then((yamlContent) => { const rawAstObject = yaml.load(yamlContent); const astObject = parseAST(rawAstObject); const plainObject = constructPlainObject(rawAstObject); @@ -126,7 +126,7 @@ const addNewArrayItem = (ymlFile, pathInYml, newValue) => }); const removeExistingArrayItem = (ymlFile, pathInYml, removeValue) => - fs.readFileAsync(ymlFile, 'utf8').then(yamlContent => { + fs.readFileAsync(ymlFile, 'utf8').then((yamlContent) => { const rawAstObject = yaml.load(yamlContent); const astObject = parseAST(rawAstObject); diff --git a/package.json b/package.json index 71ba9a4d4ea..fa50cae9ccc 100644 --- a/package.json +++ b/package.json @@ -93,7 +93,7 @@ "mock-require": "^3.0.3", "nyc": "^15.1.0", "pkg": "^4.4.9", - "prettier": "^1.19.1", + "prettier": "^2.2.1", "process-utils": "^4.0.0", "proxyquire": "^2.1.3", "semver-regex": "^3.1.2", diff --git a/scripts/pkg/generate-choco-package.js b/scripts/pkg/generate-choco-package.js index 8470e288561..da05c080547 100755 --- a/scripts/pkg/generate-choco-package.js +++ b/scripts/pkg/generate-choco-package.js @@ -90,7 +90,7 @@ const chocoPackageTemplatePath = path.join(__dirname, 'choco-package-template'); metadata.releaseNotes[0] = `https://github.com/serverless/serverless/releases/tag/${versionTag}`; metadata.copyright[0] = `${new Date().getFullYear()}, Serverless Inc.`; metadata.tags[0] = packageMeta.keywords - .filter(keyword => !keyword.includes(' ')) + .filter((keyword) => !keyword.includes(' ')) .join(' '); metadata.summary[0] = packageMeta.description; metadata.description[0] = packageMeta.description; @@ -102,7 +102,7 @@ const chocoPackageTemplatePath = path.join(__dirname, 'choco-package-template'); ), // Download binary into package tools folder - fetch(binaryUrl).then(response => { + fetch(binaryUrl).then((response) => { if (response.status >= 400) { throw new Error(`${response.status}: Request to ${binaryUrl} was rejected`); } diff --git a/scripts/pkg/upload/world.js b/scripts/pkg/upload/world.js index e86db58bf02..bd58eb47f36 100755 --- a/scripts/pkg/upload/world.js +++ b/scripts/pkg/upload/world.js @@ -31,23 +31,23 @@ module.exports = async (versionTag, { isLegacyVersion }) => { }; const releaseIdDeferred = request(`${API_URL}tags/${versionTag}`, requestOptions).then( - result => result.id + (result) => result.id ); - const releaseAssetsDeferred = releaseIdDeferred.then(releaseId => + const releaseAssetsDeferred = releaseIdDeferred.then((releaseId) => request(`${API_URL}${releaseId}/assets`, requestOptions) ); const distFileBasenames = await fs.promises.readdir(distPath); await Promise.all( distFileBasenames - .map(async distFileBasename => { + .map(async (distFileBasename) => { const distFileBasenameTokens = distFileBasename.match(binaryBasenameMatcher); if (!distFileBasenameTokens) throw new Error(`Unexpected dist file ${distFileBasename}`); - const targetBinaryName = `serverless-${ - distFileBasenameTokens[1] - }-${distFileBasenameTokens[2] || 'x64'}${distFileBasenameTokens[3] || ''}`; + const targetBinaryName = `serverless-${distFileBasenameTokens[1]}-${ + distFileBasenameTokens[2] || 'x64' + }${distFileBasenameTokens[3] || ''}`; const existingAssetData = (await releaseAssetsDeferred).find( - assetData => assetData.name === targetBinaryName + (assetData) => assetData.name === targetBinaryName ); if (existingAssetData) { await request(`${API_URL}assets/${existingAssetData.id}`, { @@ -72,7 +72,7 @@ module.exports = async (versionTag, { isLegacyVersion }) => { }) .concat( isLegacyVersion - ? releaseIdDeferred.then(releaseId => + ? releaseIdDeferred.then((releaseId) => request(`${API_URL}${releaseId}`, { method: 'PATCH', headers: requestOptions.headers, diff --git a/scripts/postinstall.js b/scripts/postinstall.js index b5ab8b13dde..bebf691af91 100644 --- a/scripts/postinstall.js +++ b/scripts/postinstall.js @@ -6,7 +6,7 @@ const isStandaloneExecutable = require('../lib/utils/isStandaloneExecutable'); const isWindows = process.platform === 'win32'; -const truthyStr = val => val && !['0', 'false', 'f', 'n', 'no'].includes(val.toLowerCase()); +const truthyStr = (val) => val && !['0', 'false', 'f', 'n', 'no'].includes(val.toLowerCase()); const { CI, ADBLOCK, SILENT } = process.env; if (!truthyStr(CI) && !truthyStr(ADBLOCK) && !truthyStr(SILENT)) { const messageTokens = ['Serverless Framework successfully installed!']; diff --git a/scripts/serverless.js b/scripts/serverless.js index 383f5bdb3c7..321ae79dad3 100755 --- a/scripts/serverless.js +++ b/scripts/serverless.js @@ -21,7 +21,7 @@ const invocationId = uuid.v4(); let serverless; -process.on('uncaughtException', error => logError(error, { forceExit: true, serverless })); +process.on('uncaughtException', (error) => logError(error, { forceExit: true, serverless })); if (process.env.SLS_DEBUG) { // For performance reasons enabled only in SLS_DEBUG mode @@ -35,7 +35,7 @@ const Serverless = require('../lib/Serverless'); serverless = new Serverless(); let resolveOnExitPromise; -serverless.onExitPromise = new Promise(resolve => (resolveOnExitPromise = resolve)); +serverless.onExitPromise = new Promise((resolve) => (resolveOnExitPromise = resolve)); serverless.invocationId = invocationId; require('../lib/utils/analytics').sendPending({ @@ -50,11 +50,11 @@ serverless .then(() => serverless.run()) .then( () => resolveOnExitPromise(), - err => { + (err) => { resolveOnExitPromise(); // If Enterprise Plugin, capture error let enterpriseErrorHandler = null; - serverless.pluginManager.plugins.forEach(p => { + serverless.pluginManager.plugins.forEach((p) => { if (p.enterprise && p.enterprise.errorHandler) { enterpriseErrorHandler = p.enterprise.errorHandler; } @@ -64,7 +64,7 @@ serverless return null; } return enterpriseErrorHandler(err, invocationId) - .catch(error => { + .catch((error) => { process.stdout.write(`${error.stack}\n`); }) .then(() => { diff --git a/scripts/test/integration-teardown.js b/scripts/test/integration-teardown.js index 6442c3e2959..8d732e7f2e6 100755 --- a/scripts/test/integration-teardown.js +++ b/scripts/test/integration-teardown.js @@ -35,7 +35,7 @@ const { }); try { await Promise.all( - describeResponse.NetworkInterfaces.map(networkInterface => + describeResponse.NetworkInterfaces.map((networkInterface) => awsRequest('EC2', 'deleteNetworkInterface', { NetworkInterfaceId: networkInterface.NetworkInterfaceId, }) diff --git a/test/fixtures/apiGatewayExtended/core.js b/test/fixtures/apiGatewayExtended/core.js index 24b040dabbe..030d8a7fe1c 100644 --- a/test/fixtures/apiGatewayExtended/core.js +++ b/test/fixtures/apiGatewayExtended/core.js @@ -44,7 +44,7 @@ async function apiKeys(event) { } async function timeout(event) { - return new Promise(resolve => + return new Promise((resolve) => setTimeout( () => resolve({ diff --git a/test/fixtures/functionMsk/core.js b/test/fixtures/functionMsk/core.js index e00ec4ab8fd..724de281d4d 100644 --- a/test/fixtures/functionMsk/core.js +++ b/test/fixtures/functionMsk/core.js @@ -7,7 +7,7 @@ const { Kafka } = require('kafkajs'); function consumer(event, context, callback) { const functionName = 'consumer'; const { records } = event; - const messages = Object.values(records)[0].map(record => + const messages = Object.values(records)[0].map((record) => Buffer.from(record.value, 'base64').toString() ); // eslint-disable-next-line no-console diff --git a/test/fixtures/invocation/doubled-resolution-callback-first.js b/test/fixtures/invocation/doubled-resolution-callback-first.js index f8cc1ee9610..bf7e0abf893 100644 --- a/test/fixtures/invocation/doubled-resolution-callback-first.js +++ b/test/fixtures/invocation/doubled-resolution-callback-first.js @@ -9,7 +9,7 @@ module.exports.handler = (event, context, callback) => { }), }) ); - return new Promise(resolve => + return new Promise((resolve) => setTimeout(() => resolve({ statusCode: 200, diff --git a/test/fixtures/iotFleetProvisioning/registerDevice.js b/test/fixtures/iotFleetProvisioning/registerDevice.js index 47a780adecf..adce2fb7f4f 100644 --- a/test/fixtures/iotFleetProvisioning/registerDevice.js +++ b/test/fixtures/iotFleetProvisioning/registerDevice.js @@ -37,7 +37,7 @@ const subscribe = (fn, deffered, options) => { }); }; -const executeKeys = async identity => { +const executeKeys = async (identity) => { console.log('Subscribing to CreateKeysAndCertificate Accepted and Rejected topics..'); const keysSubRequest = {}; diff --git a/test/fixtures/locallyInstalledServerless/_setup.js b/test/fixtures/locallyInstalledServerless/_setup.js index b26e14634dd..29c9d54401d 100644 --- a/test/fixtures/locallyInstalledServerless/_setup.js +++ b/test/fixtures/locallyInstalledServerless/_setup.js @@ -6,7 +6,7 @@ const path = require('path'); const fixturePath = path.resolve(__dirname, 'node_modules/serverless'); const fixtureModulePath = path.resolve(fixturePath, 'index.js'); -module.exports = originalFixturePath => { +module.exports = (originalFixturePath) => { const content = fs.readFileSync(fixtureModulePath); fs.writeFileSync( fixtureModulePath, diff --git a/test/fixtures/provisionedConcurrency/core.js b/test/fixtures/provisionedConcurrency/core.js index 6ee142cb123..46e5845584e 100644 --- a/test/fixtures/provisionedConcurrency/core.js +++ b/test/fixtures/provisionedConcurrency/core.js @@ -3,7 +3,7 @@ function handler(event, context, callback) { const functionName = 'provisionedFunc'; const { Records } = event; - const messages = Records.map(record => { + const messages = Records.map((record) => { if (record.eventSource === 'aws:sqs') { return record.body; } else if (record.eventSource === 'aws:kinesis') { diff --git a/test/integration/apiGateway.test.js b/test/integration/apiGateway.test.js index 661c624fba7..4904e1fd3d1 100644 --- a/test/integration/apiGateway.test.js +++ b/test/integration/apiGateway.test.js @@ -9,7 +9,7 @@ const { confirmCloudWatchLogs } = require('../utils/misc'); const { deployService, removeService, fetch } = require('../utils/integration'); const { createRestApi, deleteRestApi, getResources } = require('../utils/apiGateway'); -describe('AWS - API Gateway Integration Test', function() { +describe('AWS - API Gateway Integration Test', function () { this.timeout(1000 * 60 * 10); // Involves time-taking deploys let serviceName; let endpoint; @@ -25,7 +25,7 @@ describe('AWS - API Gateway Integration Test', function() { const resolveEndpoint = async () => { const result = await awsRequest('CloudFormation', 'describeStacks', { StackName: stackName }); const endpointOutput = result.Stacks[0].Outputs.find( - output => output.OutputKey === 'ServiceEndpoint' + (output) => output.OutputKey === 'ServiceEndpoint' ).OutputValue; endpoint = endpointOutput.match(/https:\/\/.+\.execute-api\..+\.amazonaws\.com.+/)[0]; }; @@ -54,32 +54,32 @@ describe('AWS - API Gateway Integration Test', function() { const testEndpoint = `${endpoint}`; return fetch(testEndpoint, { method: 'GET' }) - .then(response => response.json()) - .then(json => expect(json.message).to.equal(expectedMessage)); + .then((response) => response.json()) + .then((json) => expect(json.message).to.equal(expectedMessage)); }); it('should expose an accessible POST HTTP endpoint', () => { const testEndpoint = `${endpoint}/minimal-1`; return fetch(testEndpoint, { method: 'POST' }) - .then(response => response.json()) - .then(json => expect(json.message).to.equal(expectedMessage)); + .then((response) => response.json()) + .then((json) => expect(json.message).to.equal(expectedMessage)); }); it('should expose an accessible PUT HTTP endpoint', () => { const testEndpoint = `${endpoint}/minimal-2`; return fetch(testEndpoint, { method: 'PUT' }) - .then(response => response.json()) - .then(json => expect(json.message).to.equal(expectedMessage)); + .then((response) => response.json()) + .then((json) => expect(json.message).to.equal(expectedMessage)); }); it('should expose an accessible DELETE HTTP endpoint', () => { const testEndpoint = `${endpoint}/minimal-3`; return fetch(testEndpoint, { method: 'DELETE' }) - .then(response => response.json()) - .then(json => expect(json.message).to.equal(expectedMessage)); + .then((response) => response.json()) + .then((json) => expect(json.message).to.equal(expectedMessage)); }); }); @@ -87,7 +87,7 @@ describe('AWS - API Gateway Integration Test', function() { it('should setup simple CORS support via cors: true config', () => { const testEndpoint = `${endpoint}/simple-cors`; - return fetch(testEndpoint, { method: 'OPTIONS' }).then(response => { + return fetch(testEndpoint, { method: 'OPTIONS' }).then((response) => { const headers = response.headers; const allowHeaders = [ 'Content-Type', @@ -107,7 +107,7 @@ describe('AWS - API Gateway Integration Test', function() { it('should setup CORS support with complex object config', () => { const testEndpoint = `${endpoint}/complex-cors`; - return fetch(testEndpoint, { method: 'OPTIONS' }).then(response => { + return fetch(testEndpoint, { method: 'OPTIONS' }).then((response) => { const headers = response.headers; const allowHeaders = [ 'Content-Type', @@ -133,7 +133,7 @@ describe('AWS - API Gateway Integration Test', function() { }); it('should reject requests without authorization', () => { - return fetch(testEndpoint).then(response => { + return fetch(testEndpoint).then((response) => { expect(response.status).to.equal(401); }); }); @@ -141,15 +141,15 @@ describe('AWS - API Gateway Integration Test', function() { it('should reject requests with wrong authorization', () => { return fetch(testEndpoint, { headers: { Authorization: 'Bearer ShouldNotBeAuthorized' }, - }).then(response => { + }).then((response) => { expect(response.status).to.equal(401); }); }); it('should authorize requests with correct authorization', () => { return fetch(testEndpoint, { headers: { Authorization: 'Bearer ShouldBeAuthorized' } }) - .then(response => response.json()) - .then(json => { + .then((response) => response.json()) + .then((json) => { expect(json.message).to.equal('Hello from API Gateway! - (customAuthorizers)'); expect(json.event.requestContext.authorizer.principalId).to.equal('SomeRandomId'); expect(json.event.headers.Authorization).to.equal('Bearer ShouldBeAuthorized'); @@ -180,7 +180,7 @@ describe('AWS - API Gateway Integration Test', function() { }); it('should reject a request with an invalid API Key', () => { - return fetch(testEndpoint).then(response => { + return fetch(testEndpoint).then((response) => { expect(response.status).to.equal(403); }); }); @@ -213,17 +213,17 @@ describe('AWS - API Gateway Integration Test', function() { `/aws/api-gateway/${stackName}`, () => fetch(`${testEndpoint}`, { method: 'GET' }) - .then(response => response.json()) + .then((response) => response.json()) // Confirm that APIGW responds as expected - .then(json => expect(json.message).to.equal('Hello from API Gateway! - (minimal)')) + .then((json) => expect(json.message).to.equal('Hello from API Gateway! - (minimal)')) // Confirm that CloudWatch logs for APIGW are written - ).then(events => expect(events.length > 0).to.equal(true)); + ).then((events) => expect(events.length > 0).to.equal(true)); }); }); describe('Integration Lambda Timeout', () => { it('should result with 504 status code', () => - fetch(`${endpoint}/integration-lambda-timeout`).then(response => + fetch(`${endpoint}/integration-lambda-timeout`).then((response) => expect(response.status).to.equal(504) )); }); @@ -234,11 +234,11 @@ describe('AWS - API Gateway Integration Test', function() { // create an external REST API const externalRestApiName = `${stage}-${serviceName}-ext-api`; await createRestApi(externalRestApiName) - .then(restApiMeta => { + .then((restApiMeta) => { restApiId = restApiMeta.id; return getResources(restApiId); }) - .then(resources => { + .then((resources) => { restApiRootResourceId = resources[0].id; log.notice( 'Created external rest API ' + @@ -290,8 +290,8 @@ describe('AWS - API Gateway Integration Test', function() { const testEndpoint = `${endpoint}/minimal-1`; return fetch(testEndpoint, { method: 'POST' }) - .then(response => response.json()) - .then(json => expect(json.message).to.equal('Hello from API Gateway! - (minimal)')); + .then((response) => response.json()) + .then((json) => expect(json.message).to.equal('Hello from API Gateway! - (minimal)')); }); }); }); diff --git a/test/integration/cognitoUserPool.test.js b/test/integration/cognitoUserPool.test.js index 540d8c529e6..bbeb414377e 100644 --- a/test/integration/cognitoUserPool.test.js +++ b/test/integration/cognitoUserPool.test.js @@ -19,7 +19,7 @@ const { const { deployService, removeService } = require('../utils/integration'); const { confirmCloudWatchLogs } = require('../utils/misc'); -describe('AWS - Cognito User Pool Integration Test', function() { +describe('AWS - Cognito User Pool Integration Test', function () { this.timeout(1000 * 60 * 10); // Involves time-taking deploys let stackName; let servicePath; @@ -54,7 +54,7 @@ describe('AWS - Cognito User Pool Integration Test', function() { return deployService(servicePath); }); - after(async function() { + after(async function () { if (!servicePath) return null; // Do not clean on fail, to allow further state investigation if (hasFailed(this.test.parent)) return null; @@ -78,7 +78,7 @@ describe('AWS - Cognito User Pool Integration Test', function() { `/aws/lambda/${stackName}-${functionName}`, async () => createUser(userPoolId, `johndoe${++counter}`, '!!!wAsD123456wAsD!!!'), { - checkIsComplete: soFarEvents => { + checkIsComplete: (soFarEvents) => { const logs = soFarEvents.reduce((data, event) => data + event.message, ''); return logs.includes('userName'); }, @@ -103,7 +103,7 @@ describe('AWS - Cognito User Pool Integration Test', function() { `/aws/lambda/${stackName}-${functionName}`, async () => createUser(userPoolId, `janedoe${++counter}`, '!!!wAsD123456wAsD!!!'), { - checkIsComplete: soFarEvents => { + checkIsComplete: (soFarEvents) => { const logs = soFarEvents.reduce((data, event) => data + event.message, ''); return logs.includes('userName'); }, @@ -148,7 +148,7 @@ describe('AWS - Cognito User Pool Integration Test', function() { await initiateAuth(clientId, username, password); }, { - checkIsComplete: soFarEvents => + checkIsComplete: (soFarEvents) => soFarEvents .reduce((data, event) => data + event.message, '') .includes('PreAuthentication_Authentication'), diff --git a/test/integration/eventBridge.test.js b/test/integration/eventBridge.test.js index 7e525d76b5d..b5de7c61761 100644 --- a/test/integration/eventBridge.test.js +++ b/test/integration/eventBridge.test.js @@ -14,7 +14,7 @@ const { const { deployService, removeService, getMarkers } = require('../utils/integration'); -describe('AWS - Event Bridge Integration Test', function() { +describe('AWS - Event Bridge Integration Test', function () { this.timeout(1000 * 60 * 10); // Involves time-taking deploys let serviceName; let stackName; @@ -92,12 +92,12 @@ describe('AWS - Event Bridge Integration Test', function() { `/aws/lambda/${stackName}-${functionName}`, () => putEvents('default', putEventEntries), { - checkIsComplete: events => - events.find(event => event.message.includes(markers.start)) && - events.find(event => event.message.includes(markers.end)), + checkIsComplete: (events) => + events.find((event) => event.message.includes(markers.start)) && + events.find((event) => event.message.includes(markers.end)), } - ).then(events => { - const logs = events.map(event => event.message).join('\n'); + ).then((events) => { + const logs = events.map((event) => event.message).join('\n'); expect(logs).to.include(`"source":"${eventSource}"`); expect(logs).to.include(`"detail-type":"${putEventEntries[0].DetailType}"`); expect(logs).to.include(`"detail":${putEventEntries[0].Detail}`); @@ -114,12 +114,12 @@ describe('AWS - Event Bridge Integration Test', function() { `/aws/lambda/${stackName}-${functionName}`, () => putEvents(namedEventBusName, putEventEntries), { - checkIsComplete: events => - events.find(event => event.message.includes(markers.start)) && - events.find(event => event.message.includes(markers.end)), + checkIsComplete: (events) => + events.find((event) => event.message.includes(markers.start)) && + events.find((event) => event.message.includes(markers.end)), } - ).then(events => { - const logs = events.map(event => event.message).join('\n'); + ).then((events) => { + const logs = events.map((event) => event.message).join('\n'); expect(logs).to.include(`"source":"${eventSource}"`); expect(logs).to.include(`"detail-type":"${putEventEntries[0].DetailType}"`); expect(logs).to.include(`"detail":${putEventEntries[0].Detail}`); @@ -136,12 +136,12 @@ describe('AWS - Event Bridge Integration Test', function() { `/aws/lambda/${stackName}-${functionName}`, () => putEvents(arnEventBusName, putEventEntries), { - checkIsComplete: events => - events.find(event => event.message.includes(markers.start)) && - events.find(event => event.message.includes(markers.end)), + checkIsComplete: (events) => + events.find((event) => event.message.includes(markers.start)) && + events.find((event) => event.message.includes(markers.end)), } - ).then(events => { - const logs = events.map(event => event.message).join('\n'); + ).then((events) => { + const logs = events.map((event) => event.message).join('\n'); expect(logs).to.include(`"source":"${eventSource}"`); expect(logs).to.include(`"detail-type":"${putEventEntries[0].DetailType}"`); expect(logs).to.include(`"detail":${putEventEntries[0].Detail}`); diff --git a/test/integration/functionDestinations.test.js b/test/integration/functionDestinations.test.js index 16f2327b466..6665079b837 100644 --- a/test/integration/functionDestinations.test.js +++ b/test/integration/functionDestinations.test.js @@ -7,7 +7,7 @@ const { confirmCloudWatchLogs } = require('../utils/misc'); const { deployService, removeService } = require('../utils/integration'); -describe('Function destinations Integration Test', function() { +describe('Function destinations Integration Test', function () { this.timeout(1000 * 60 * 20); // Involves time-taking deploys let stackName; let servicePath; @@ -35,8 +35,8 @@ describe('Function destinations Integration Test', function() { InvocationType: 'Event', }); }, - { checkIsComplete: events => events.length } - ).then(events => { + { checkIsComplete: (events) => events.length } + ).then((events) => { expect(events.length > 0).to.equal(true); })); }); diff --git a/test/integration/httpApi.test.js b/test/integration/httpApi.test.js index cd5665d5c98..e475a3023a7 100644 --- a/test/integration/httpApi.test.js +++ b/test/integration/httpApi.test.js @@ -8,7 +8,7 @@ const { confirmCloudWatchLogs } = require('../utils/misc'); const { deployService, removeService, fetch } = require('../utils/integration'); -describe('HTTP API Integration Test', function() { +describe('HTTP API Integration Test', function () { this.timeout(1000 * 60 * 20); // Involves time-taking deploys let endpoint; let stackName; @@ -18,7 +18,7 @@ describe('HTTP API Integration Test', function() { const resolveEndpoint = async () => { const result = await awsRequest('CloudFormation', 'describeStacks', { StackName: stackName }); const endpointOutput = result.Stacks[0].Outputs.find( - output => output.OutputKey === 'HttpApiUrl' + (output) => output.OutputKey === 'HttpApiUrl' ).OutputValue; endpoint = endpointOutput.match(/https:\/\/.+\.execute-api\..+\.amazonaws\.com/)[0]; }; @@ -41,7 +41,7 @@ describe('HTTP API Integration Test', function() { UserPoolId: poolId, ExplicitAuthFlows: ['ALLOW_USER_PASSWORD_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'], PreventUserExistenceErrors: 'ENABLED', - }).then(result => result.UserPoolClient.ClientId), + }).then((result) => result.UserPoolClient.ClientId), awsRequest('CognitoIdentityServiceProvider', 'adminCreateUser', { UserPoolId: poolId, Username: userName, @@ -174,7 +174,7 @@ describe('HTTP API Integration Test', function() { confirmCloudWatchLogs(`/aws/http-api/${stackName}`, async () => { const response = await fetch(`${endpoint}/some-post`, { method: 'POST' }); await response.json(); - }).then(events => { + }).then((events) => { expect(events.length > 0).to.equal(true); })); }); @@ -189,10 +189,10 @@ describe('HTTP API Integration Test', function() { return resolveEndpoint(); }); - after(async function() { + after(async function () { // Added temporarily to inspect random fails // TODO: Remove once properly diagnosed - if (this.test.parent.tests.some(test => test.state === 'failed')) return; + if (this.test.parent.tests.some((test) => test.state === 'failed')) return; log.notice('Removing service...'); await removeService(servicePath); }); diff --git a/test/integration/infra-dependent/fileSystemConfig.test.js b/test/integration/infra-dependent/fileSystemConfig.test.js index 42ca27f3f56..556a21e0753 100644 --- a/test/integration/infra-dependent/fileSystemConfig.test.js +++ b/test/integration/infra-dependent/fileSystemConfig.test.js @@ -20,7 +20,7 @@ const retryableMountErrors = new Set([ 'EFSIOException', ]); -describe('AWS - FileSystemConfig Integration Test', function() { +describe('AWS - FileSystemConfig Integration Test', function () { this.timeout(1000 * 60 * 100); // Involves time-taking deploys let stackName; let startTime; diff --git a/test/integration/infra-dependent/msk.test.js b/test/integration/infra-dependent/msk.test.js index 6fc74732492..eba05b64903 100644 --- a/test/integration/infra-dependent/msk.test.js +++ b/test/integration/infra-dependent/msk.test.js @@ -13,7 +13,7 @@ const awsRequest = require('@serverless/test/aws-request'); const crypto = require('crypto'); const { deployService, removeService } = require('../../utils/integration'); -describe('AWS - MSK Integration Test', function() { +describe('AWS - MSK Integration Test', function () { this.timeout(1000 * 60 * 100); // Involves time-taking deploys let stackName; let servicePath; diff --git a/test/integration/iot.test.js b/test/integration/iot.test.js index 86e85f90da9..9ffde3490da 100644 --- a/test/integration/iot.test.js +++ b/test/integration/iot.test.js @@ -7,7 +7,7 @@ const { publishIotData } = require('../utils/iot'); const { confirmCloudWatchLogs } = require('../utils/misc'); const { deployService, removeService } = require('../utils/integration'); -describe('AWS - IoT Integration Test', function() { +describe('AWS - IoT Integration Test', function () { this.timeout(1000 * 60 * 100); // Involves time-taking deploys let iotTopic; let servicePath; diff --git a/test/integration/iotFleetProvisioning.test.js b/test/integration/iotFleetProvisioning.test.js index 87787091441..f73db22cffd 100644 --- a/test/integration/iotFleetProvisioning.test.js +++ b/test/integration/iotFleetProvisioning.test.js @@ -6,7 +6,7 @@ const fixtures = require('../fixtures'); const { deployService, removeService } = require('../utils/integration'); const { resolveIotEndpoint } = require('../utils/iot'); -describe('test/integration/iotFleetProvisioning.test.js', function() { +describe('test/integration/iotFleetProvisioning.test.js', function () { this.timeout(1000 * 60 * 100); // Involves time-taking deploys const thingName = 'IotDevice'; const stage = 'dev'; @@ -17,12 +17,13 @@ describe('test/integration/iotFleetProvisioning.test.js', function() { const resolveTemplateName = async () => { const result = await awsRequest('CloudFormation', 'describeStacks', { StackName: stackName }); - return result.Stacks[0].Outputs.find(output => output.OutputKey === 'ProvisioningTemplateName') - .OutputValue; + return result.Stacks[0].Outputs.find( + (output) => output.OutputKey === 'ProvisioningTemplateName' + ).OutputValue; }; const resolveIoTPolicyName = async () => { const result = await awsRequest('CloudFormation', 'describeStacks', { StackName: stackName }); - return result.Stacks[0].Outputs.find(output => output.OutputKey === 'IoTPolicyName') + return result.Stacks[0].Outputs.find((output) => output.OutputKey === 'IoTPolicyName') .OutputValue; }; diff --git a/test/integration/provisionedConcurrency.test.js b/test/integration/provisionedConcurrency.test.js index 53a758a1086..027cd62e820 100644 --- a/test/integration/provisionedConcurrency.test.js +++ b/test/integration/provisionedConcurrency.test.js @@ -9,7 +9,7 @@ const { createSqsQueue, deleteSqsQueue, sendSqsMessage } = require('../utils/sqs const { confirmCloudWatchLogs } = require('../utils/misc'); const { deployService, removeService } = require('../utils/integration'); -describe('AWS - Provisioned Concurrency Integration Test', function() { +describe('AWS - Provisioned Concurrency Integration Test', function () { this.timeout(1000 * 60 * 100); // Involves time-taking deploys let stackName; let servicePath; @@ -45,7 +45,7 @@ describe('AWS - Provisioned Concurrency Integration Test', function() { `/aws/lambda/${stackName}-${functionName}`, () => sendSqsMessage(queueName, message), { - checkIsComplete: items => items.find(item => item.message.includes(message)), + checkIsComplete: (items) => items.find((item) => item.message.includes(message)), } ); @@ -62,7 +62,7 @@ describe('AWS - Provisioned Concurrency Integration Test', function() { `/aws/lambda/${stackName}-${functionName}`, () => putKinesisRecord(streamName, message), { - checkIsComplete: items => items.find(item => item.message.includes(message)), + checkIsComplete: (items) => items.find((item) => item.message.includes(message)), } ); diff --git a/test/integration/s3.test.js b/test/integration/s3.test.js index 0faa678f5fe..453ad7248a7 100644 --- a/test/integration/s3.test.js +++ b/test/integration/s3.test.js @@ -9,7 +9,7 @@ const { createBucket, createAndRemoveInBucket, deleteBucket } = require('../util const { deployService, removeService } = require('../utils/integration'); const { confirmCloudWatchLogs } = require('../utils/misc'); -describe('AWS - S3 Integration Test', function() { +describe('AWS - S3 Integration Test', function () { this.timeout(1000 * 60 * 10); // Involves time-taking deploys let stackName; let servicePath; @@ -56,7 +56,7 @@ describe('AWS - S3 Integration Test', function() { return confirmCloudWatchLogs(`/aws/lambda/${stackName}-${functionName}`, () => createAndRemoveInBucket(bucketMinimalSetup) - ).then(events => { + ).then((events) => { const logs = events.reduce((data, event) => data + event.message, ''); expect(/aws:s3/g.test(logs)).to.equal(true); expect(/ObjectCreated:Put/g.test(logs)).to.equal(true); @@ -72,7 +72,7 @@ describe('AWS - S3 Integration Test', function() { return confirmCloudWatchLogs(`/aws/lambda/${stackName}-${functionName}`, () => createAndRemoveInBucket(bucketExtendedSetup, { prefix: 'photos/', suffix: '.jpg' }) - ).then(events => { + ).then((events) => { const logs = events.reduce((data, event) => data + event.message, ''); expect(/aws:s3/g.test(logs)).to.equal(true); expect(/ObjectRemoved:Delete/g.test(logs)).to.equal(true); @@ -88,7 +88,7 @@ describe('AWS - S3 Integration Test', function() { return confirmCloudWatchLogs(`/aws/lambda/${stackName}-${functionName}`, () => createAndRemoveInBucket(bucketCustomName) - ).then(events => { + ).then((events) => { const logs = events.reduce((data, event) => data + event.message, ''); expect(/aws:s3/g.test(logs)).to.equal(true); expect(/ObjectCreated:Put/g.test(logs)).to.equal(true); @@ -108,7 +108,7 @@ describe('AWS - S3 Integration Test', function() { prefix: 'Files/', suffix: '.TXT', }) - ).then(events => { + ).then((events) => { const logs = events.reduce((data, event) => data + event.message, ''); expect(/aws:s3/g.test(logs)).to.equal(true); expect(/ObjectCreated:Put/g.test(logs)).to.equal(true); @@ -127,7 +127,7 @@ describe('AWS - S3 Integration Test', function() { prefix: 'photos', suffix: '.jpg', }) - ).then(events => { + ).then((events) => { const logs = events.reduce((data, event) => data + event.message, ''); expect(/aws:s3/g.test(logs)).to.equal(true); expect(/ObjectCreated:Put/g.test(logs)).to.equal(true); @@ -143,7 +143,7 @@ describe('AWS - S3 Integration Test', function() { prefix: 'photos', suffix: '.jpg', }) - ).then(events => { + ).then((events) => { const logs = events.reduce((data, event) => data + event.message, ''); expect(/aws:s3/g.test(logs)).to.equal(true); expect(/ObjectRemoved:Delete/g.test(logs)).to.equal(true); @@ -159,7 +159,7 @@ describe('AWS - S3 Integration Test', function() { prefix: 'photos', suffix: '.png', }) - ).then(events => { + ).then((events) => { const logs = events.reduce((data, event) => data + event.message, ''); expect(/aws:s3/g.test(logs)).to.equal(true); expect(/ObjectCreated:Put/g.test(logs)).to.equal(true); @@ -175,7 +175,7 @@ describe('AWS - S3 Integration Test', function() { prefix: 'photos', suffix: '.png', }) - ).then(events => { + ).then((events) => { const logs = events.reduce((data, event) => data + event.message, ''); expect(/aws:s3/g.test(logs)).to.equal(true); expect(/ObjectRemoved:Delete/g.test(logs)).to.equal(true); diff --git a/test/integration/schedule.test.js b/test/integration/schedule.test.js index 235f0cdf7bb..10b88a159e5 100644 --- a/test/integration/schedule.test.js +++ b/test/integration/schedule.test.js @@ -6,7 +6,7 @@ const fixtures = require('../fixtures'); const { deployService, removeService } = require('../utils/integration'); const { confirmCloudWatchLogs } = require('../utils/misc'); -describe('AWS - Schedule Integration Test', function() { +describe('AWS - Schedule Integration Test', function () { this.timeout(1000 * 60 * 100); // Involves time-taking deploys let servicePath; let stackName; @@ -28,7 +28,7 @@ describe('AWS - Schedule Integration Test', function() { return confirmCloudWatchLogs(`/aws/lambda/${stackName}-${functionName}`, async () => {}, { timeout: 3 * 60 * 1000, - }).then(events => { + }).then((events) => { const logs = events.reduce((data, event) => data + event.message, ''); expect(logs).to.include(functionName); }); @@ -41,11 +41,11 @@ describe('AWS - Schedule Integration Test', function() { return confirmCloudWatchLogs(`/aws/lambda/${stackName}-${functionName}`, async () => {}, { timeout: 3 * 60 * 1000, - checkIsComplete: soFarEvents => { + checkIsComplete: (soFarEvents) => { const logs = soFarEvents.reduce((data, event) => data + event.message, ''); return logs.includes('transformedInput'); }, - }).then(events => { + }).then((events) => { const logs = events.reduce((data, event) => data + event.message, ''); expect(logs).to.include(functionName); expect(logs).to.include('transformedInput'); diff --git a/test/integration/sns.test.js b/test/integration/sns.test.js index 57c1c4179fe..40856431a02 100644 --- a/test/integration/sns.test.js +++ b/test/integration/sns.test.js @@ -9,7 +9,7 @@ const { confirmCloudWatchLogs } = require('../utils/misc'); const { createSnsTopic, removeSnsTopic, publishSnsMessage } = require('../utils/sns'); const { deployService, removeService } = require('../utils/integration'); -describe('AWS - SNS Integration Test', function() { +describe('AWS - SNS Integration Test', function () { this.timeout(1000 * 60 * 100); // Involves time-taking deploys let stackName; let servicePath; @@ -51,12 +51,12 @@ describe('AWS - SNS Integration Test', function() { `/aws/lambda/${stackName}-${functionName}`, () => publishSnsMessage(minimalTopicName, message), { - checkIsComplete: soFarEvents => { + checkIsComplete: (soFarEvents) => { const logs = soFarEvents.reduce((data, event) => data + event.message, ''); return logs.includes(message); }, } - ).then(events => { + ).then((events) => { const logs = events.reduce((data, event) => data + event.message, ''); expect(logs).to.include(functionName); expect(logs).to.include(message); @@ -79,7 +79,7 @@ describe('AWS - SNS Integration Test', function() { confirmCloudWatchLogs(`/aws/lambda/${stackName}-${leftFunctionName}`, async () => { await publishSnsMessage(filteredTopicName, middleMessage, middleAttributes); await publishSnsMessage(filteredTopicName, leftMessage, leftAttributes); - }).then(events => { + }).then((events) => { const logs = events.reduce((data, event) => data + event.message, ''); expect(logs).to.include(leftFunctionName); expect(logs).to.include(leftMessage); @@ -89,7 +89,7 @@ describe('AWS - SNS Integration Test', function() { confirmCloudWatchLogs(`/aws/lambda/${stackName}-${rightFunctionName}`, async () => { await publishSnsMessage(filteredTopicName, middleMessage, middleAttributes); await publishSnsMessage(filteredTopicName, rightMessage, rightAttributes); - }).then(events => { + }).then((events) => { const logs = events.reduce((data, event) => data + event.message, ''); expect(logs).to.include(rightFunctionName); expect(logs).not.to.include(leftMessage); @@ -107,7 +107,7 @@ describe('AWS - SNS Integration Test', function() { return confirmCloudWatchLogs(`/aws/lambda/${stackName}-${functionName}`, () => publishSnsMessage(existingTopicName, message) - ).then(events => { + ).then((events) => { const logs = events.reduce((data, event) => data + event.message, ''); expect(logs).to.include(functionName); expect(logs).to.include(message); diff --git a/test/integration/sqs.test.js b/test/integration/sqs.test.js index 940eaad8d25..97041077412 100644 --- a/test/integration/sqs.test.js +++ b/test/integration/sqs.test.js @@ -9,7 +9,7 @@ const { createSqsQueue, deleteSqsQueue, sendSqsMessage } = require('../utils/sqs const { confirmCloudWatchLogs } = require('../utils/misc'); const { deployService, removeService } = require('../utils/integration'); -describe('AWS - SQS Integration Test', function() { +describe('AWS - SQS Integration Test', function () { this.timeout(1000 * 60 * 100); // Involves time-taking deploys let stackName; let servicePath; @@ -31,7 +31,7 @@ describe('AWS - SQS Integration Test', function() { }); }); - after(async function() { + after(async function () { if (hasFailed(this.test.parent)) return null; await removeService(servicePath); log.notice('Deleting SQS queue'); @@ -45,7 +45,7 @@ describe('AWS - SQS Integration Test', function() { return confirmCloudWatchLogs(`/aws/lambda/${stackName}-${functionName}`, () => sendSqsMessage(queueName, message) - ).then(events => { + ).then((events) => { const logs = events.reduce((data, event) => data + event.message, ''); expect(logs).to.include(functionName); expect(logs).to.include(message); diff --git a/test/integration/stream.test.js b/test/integration/stream.test.js index 58cab944971..a3edc9120f8 100644 --- a/test/integration/stream.test.js +++ b/test/integration/stream.test.js @@ -9,7 +9,7 @@ const { putDynamoDbItem } = require('../utils/dynamodb'); const { confirmCloudWatchLogs } = require('../utils/misc'); const { deployService, removeService } = require('../utils/integration'); -describe('AWS - Stream Integration Test', function() { +describe('AWS - Stream Integration Test', function () { this.timeout(1000 * 60 * 100); // Involves time-taking deploys let stackName; let servicePath; @@ -49,7 +49,7 @@ describe('AWS - Stream Integration Test', function() { `/aws/lambda/${stackName}-${functionName}`, () => putKinesisRecord(streamName, message), { timeout: 120 * 1000 } - ).then(events => { + ).then((events) => { const logs = events.reduce((data, event) => data + event.message, ''); expect(logs).to.include(functionName); expect(logs).to.include(message); @@ -67,16 +67,14 @@ describe('AWS - Stream Integration Test', function() { return confirmCloudWatchLogs( `/aws/lambda/${stackName}-${functionName}`, () => { - item.hello = `from dynamo!${Math.random() - .toString(36) - .slice(2)}`; + item.hello = `from dynamo!${Math.random().toString(36).slice(2)}`; return putDynamoDbItem(tableName, item); }, { - checkIsComplete: events => + checkIsComplete: (events) => events.reduce((data, event) => data + event.message, '').includes(functionName), } - ).then(events => { + ).then((events) => { const logs = events.reduce((data, event) => data + event.message, ''); expect(logs).to.include(functionName); diff --git a/test/integration/websocket.test.js b/test/integration/websocket.test.js index c69a38645fa..ac6d27734b0 100644 --- a/test/integration/websocket.test.js +++ b/test/integration/websocket.test.js @@ -11,7 +11,7 @@ const { confirmCloudWatchLogs } = require('../utils/misc'); const { deployService, removeService } = require('../utils/integration'); const { createApi, deleteApi, getRoutes, createStage, deleteStage } = require('../utils/websocket'); -describe('AWS - API Gateway Websocket Integration Test', function() { +describe('AWS - API Gateway Websocket Integration Test', function () { this.timeout(1000 * 60 * 10); // Involves time-taking deploys let stackName; let serviceName; @@ -37,7 +37,7 @@ describe('AWS - API Gateway Websocket Integration Test', function() { async function getWebSocketServerUrl() { const result = await awsRequest('CloudFormation', 'describeStacks', { StackName: stackName }); const webSocketServerUrl = result.Stacks[0].Outputs.find( - output => output.OutputKey === 'ServiceEndpointWebsocket' + (output) => output.OutputKey === 'ServiceEndpointWebsocket' ).OutputValue; return webSocketServerUrl; } @@ -51,7 +51,7 @@ describe('AWS - API Gateway Websocket Integration Test', function() { return new Promise((resolve, reject) => { const ws = new WebSocket(webSocketServerUrl); - reject = (promiseReject => error => { + reject = ((promiseReject) => (error) => { promiseReject(error); try { ws.close(); @@ -71,7 +71,7 @@ describe('AWS - API Gateway Websocket Integration Test', function() { ws.on('close', resolve); - ws.on('message', event => { + ws.on('message', (event) => { twoWayPassed = true; clearTimeout(timeoutId); try { @@ -86,7 +86,7 @@ describe('AWS - API Gateway Websocket Integration Test', function() { }); describe('Minimal Setup', () => { - it('should expose an accessible websocket endpoint', async function() { + it('should expose an accessible websocket endpoint', async function () { if (!twoWayPassed) this.skip(); const webSocketServerUrl = await getWebSocketServerUrl(); @@ -95,7 +95,7 @@ describe('AWS - API Gateway Websocket Integration Test', function() { return new Promise((resolve, reject) => { const ws = new WebSocket(webSocketServerUrl); let isRejected = false; - reject = (promiseReject => error => { + reject = ((promiseReject) => (error) => { isRejected = true; promiseReject(error); try { @@ -110,7 +110,7 @@ describe('AWS - API Gateway Websocket Integration Test', function() { if (isRejected) throw new Error('Stop propagation'); ws.send('test message'); return wait(500); - }).then(events => { + }).then((events) => { expect(events.length > 0).to.equal(true); ws.close(); }, reject); @@ -118,7 +118,7 @@ describe('AWS - API Gateway Websocket Integration Test', function() { ws.on('close', resolve); - ws.on('message', event => { + ws.on('message', (event) => { log.debug('Unexpected WebSocket message', event); reject(new Error('Unexpected message')); }); @@ -128,7 +128,7 @@ describe('AWS - API Gateway Websocket Integration Test', function() { // NOTE: this test should be at the very end because we're using an external REST API here describe('when using an existing websocket API', () => { let websocketApiId; - before(async function() { + before(async function () { if (!twoWayPassed) this.skip(); // create an external websocket API const externalWebsocketApiName = `${stage}-${serviceName}-ext-api`; diff --git a/test/integrationBasic.test.js b/test/integrationBasic.test.js index 667f5896a0e..fe3dbc26ecf 100644 --- a/test/integrationBasic.test.js +++ b/test/integrationBasic.test.js @@ -14,7 +14,7 @@ const { getTmpDirPath } = require('./utils/fs'); const serverlessExec = require('./serverlessBinary'); -describe('Service Lifecyle Integration Test', function() { +describe('Service Lifecyle Integration Test', function () { this.timeout(1000 * 60 * 10); // Involves time-taking deploys const templateName = 'aws-nodejs'; const tmpDir = getTmpDirPath(); @@ -37,7 +37,7 @@ describe('Service Lifecyle Integration Test', function() { }); // Do not continue if any of the tests failed - beforeEach(function() { + beforeEach(function () { if (hasFailed(this.test.parent)) this.skip(); }); diff --git a/test/integrationPackage/fixtures/artifact/handler.js b/test/integrationPackage/fixtures/artifact/handler.js index 773780bbd7f..531f36d0b0e 100644 --- a/test/integrationPackage/fixtures/artifact/handler.js +++ b/test/integrationPackage/fixtures/artifact/handler.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports.hello = function(event) { +module.exports.hello = function (event) { return { statusCode: 200, body: JSON.stringify( diff --git a/test/integrationPackage/fixtures/individually-function/handler.js b/test/integrationPackage/fixtures/individually-function/handler.js index 773780bbd7f..531f36d0b0e 100644 --- a/test/integrationPackage/fixtures/individually-function/handler.js +++ b/test/integrationPackage/fixtures/individually-function/handler.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports.hello = function(event) { +module.exports.hello = function (event) { return { statusCode: 200, body: JSON.stringify( diff --git a/test/integrationPackage/fixtures/individually-function/handler2.js b/test/integrationPackage/fixtures/individually-function/handler2.js index 773780bbd7f..531f36d0b0e 100644 --- a/test/integrationPackage/fixtures/individually-function/handler2.js +++ b/test/integrationPackage/fixtures/individually-function/handler2.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports.hello = function(event) { +module.exports.hello = function (event) { return { statusCode: 200, body: JSON.stringify( diff --git a/test/integrationPackage/fixtures/individually/handler.js b/test/integrationPackage/fixtures/individually/handler.js index 773780bbd7f..531f36d0b0e 100644 --- a/test/integrationPackage/fixtures/individually/handler.js +++ b/test/integrationPackage/fixtures/individually/handler.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports.hello = function(event) { +module.exports.hello = function (event) { return { statusCode: 200, body: JSON.stringify( diff --git a/test/integrationPackage/fixtures/individually/handler2.js b/test/integrationPackage/fixtures/individually/handler2.js index 773780bbd7f..531f36d0b0e 100644 --- a/test/integrationPackage/fixtures/individually/handler2.js +++ b/test/integrationPackage/fixtures/individually/handler2.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports.hello = function(event) { +module.exports.hello = function (event) { return { statusCode: 200, body: JSON.stringify( diff --git a/test/integrationPackage/fixtures/regular/handler.js b/test/integrationPackage/fixtures/regular/handler.js index 773780bbd7f..531f36d0b0e 100644 --- a/test/integrationPackage/fixtures/regular/handler.js +++ b/test/integrationPackage/fixtures/regular/handler.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports.hello = function(event) { +module.exports.hello = function (event) { return { statusCode: 200, body: JSON.stringify( diff --git a/test/integrationPackage/lambda-files.tests.js b/test/integrationPackage/lambda-files.tests.js index 33fc7399975..57a77891725 100644 --- a/test/integrationPackage/lambda-files.tests.js +++ b/test/integrationPackage/lambda-files.tests.js @@ -13,7 +13,7 @@ const fixturePaths = { individuallyFunction: path.join(__dirname, 'fixtures/individually-function'), }; -describe('Integration test - Packaging - Lambda Files', function() { +describe('Integration test - Packaging - Lambda Files', function () { this.timeout(15000); let cwd; beforeEach(() => { @@ -23,7 +23,7 @@ describe('Integration test - Packaging - Lambda Files', function() { it('packages the default aws template correctly in the zip', () => { fse.copySync(fixturePaths.regular, cwd); execSync(`${serverlessExec} package`, { cwd }); - return listZipFiles(path.join(cwd, '.serverless/aws-nodejs.zip')).then(zipfiles => { + return listZipFiles(path.join(cwd, '.serverless/aws-nodejs.zip')).then((zipfiles) => { expect(zipfiles).to.deep.equal(['handler.js']); }); }); @@ -33,11 +33,11 @@ describe('Integration test - Packaging - Lambda Files', function() { execSync('npm init --yes', { cwd }); execSync('npm i lodash', { cwd }); execSync(`${serverlessExec} package`, { cwd }); - return listZipFiles(path.join(cwd, '.serverless/aws-nodejs.zip')).then(zipfiles => { + return listZipFiles(path.join(cwd, '.serverless/aws-nodejs.zip')).then((zipfiles) => { const nodeModules = new Set( - zipfiles.filter(f => f.startsWith('node_modules')).map(f => f.split(path.sep)[1]) + zipfiles.filter((f) => f.startsWith('node_modules')).map((f) => f.split(path.sep)[1]) ); - const nonNodeModulesFiles = zipfiles.filter(f => !f.startsWith('node_modules')); + const nonNodeModulesFiles = zipfiles.filter((f) => !f.startsWith('node_modules')); expect(nodeModules).to.deep.equal(new Set(['lodash'])); expect(nonNodeModulesFiles).to.deep.equal([ 'handler.js', @@ -52,11 +52,11 @@ describe('Integration test - Packaging - Lambda Files', function() { execSync('npm init --yes', { cwd }); execSync('npm i --save-dev lodash', { cwd }); execSync(`${serverlessExec} package`, { cwd }); - return listZipFiles(path.join(cwd, '.serverless/aws-nodejs.zip')).then(zipfiles => { + return listZipFiles(path.join(cwd, '.serverless/aws-nodejs.zip')).then((zipfiles) => { const nodeModules = new Set( - zipfiles.filter(f => f.startsWith('node_modules')).map(f => f.split(path.sep)[1]) + zipfiles.filter((f) => f.startsWith('node_modules')).map((f) => f.split(path.sep)[1]) ); - const nonNodeModulesFiles = zipfiles.filter(f => !f.startsWith('node_modules')); + const nonNodeModulesFiles = zipfiles.filter((f) => !f.startsWith('node_modules')); expect(nodeModules).to.deep.equal(new Set([])); expect(nonNodeModulesFiles).to.deep.equal([ 'handler.js', @@ -72,11 +72,11 @@ describe('Integration test - Packaging - Lambda Files', function() { execSync('echo \'package: {exclude: ["package*.json"]}\' >> serverless.yml', { cwd }); execSync('npm i lodash', { cwd }); execSync(`${serverlessExec} package`, { cwd }); - return listZipFiles(path.join(cwd, '.serverless/aws-nodejs.zip')).then(zipfiles => { + return listZipFiles(path.join(cwd, '.serverless/aws-nodejs.zip')).then((zipfiles) => { const nodeModules = new Set( - zipfiles.filter(f => f.startsWith('node_modules')).map(f => f.split(path.sep)[1]) + zipfiles.filter((f) => f.startsWith('node_modules')).map((f) => f.split(path.sep)[1]) ); - const nonNodeModulesFiles = zipfiles.filter(f => !f.startsWith('node_modules')); + const nonNodeModulesFiles = zipfiles.filter((f) => !f.startsWith('node_modules')); expect(nodeModules).to.deep.equal(new Set(['lodash'])); expect(nonNodeModulesFiles).to.deep.equal(['handler.js']); }); @@ -86,17 +86,17 @@ describe('Integration test - Packaging - Lambda Files', function() { fse.copySync(fixturePaths.individually, cwd); execSync(`${serverlessExec} package`, { cwd }); return listZipFiles(path.join(cwd, '.serverless/hello.zip')) - .then(zipfiles => expect(zipfiles).to.deep.equal(['handler.js'])) + .then((zipfiles) => expect(zipfiles).to.deep.equal(['handler.js'])) .then(() => listZipFiles(path.join(cwd, '.serverless/hello2.zip'))) - .then(zipfiles => expect(zipfiles).to.deep.equal(['handler2.js'])); + .then((zipfiles) => expect(zipfiles).to.deep.equal(['handler2.js'])); }); it('handles package individually on function level with include/excludes correctly', () => { fse.copySync(fixturePaths.individuallyFunction, cwd); execSync(`${serverlessExec} package`, { cwd }); return listZipFiles(path.join(cwd, '.serverless/hello.zip')) - .then(zipfiles => expect(zipfiles).to.deep.equal(['handler.js'])) + .then((zipfiles) => expect(zipfiles).to.deep.equal(['handler.js'])) .then(() => listZipFiles(path.join(cwd, '.serverless/hello2.zip'))) - .then(zipfiles => expect(zipfiles).to.deep.equal(['handler2.js'])); + .then((zipfiles) => expect(zipfiles).to.deep.equal(['handler2.js'])); }); }); diff --git a/test/mochaPatch.js b/test/mochaPatch.js index 7261079ceeb..f0aed88db76 100644 --- a/test/mochaPatch.js +++ b/test/mochaPatch.js @@ -14,8 +14,8 @@ BbPromise.config({ const { runnerEmitter } = require('@serverless/test/setup/patch'); -runnerEmitter.on('runner', runner => { - runner.on('suite end', suite => { +runnerEmitter.on('runner', (runner) => { + runner.on('suite end', (suite) => { if (!suite.parent || !suite.parent.root) return; // Ensure to reset memoization on artifacts generation after each test file run. diff --git a/test/unit/lib/classes/CLI.test.js b/test/unit/lib/classes/CLI.test.js index 4474722883f..f86b8d55ad0 100644 --- a/test/unit/lib/classes/CLI.test.js +++ b/test/unit/lib/classes/CLI.test.js @@ -620,7 +620,7 @@ describe('CLI', () => { }); }); - describe('Integration tests', function() { + describe('Integration tests', function () { this.timeout(1000 * 60 * 10); const serverlessExec = require('../../../serverlessBinary'); const env = resolveAwsEnv(); diff --git a/test/unit/lib/classes/ConfigSchemaHandler/index.test.js b/test/unit/lib/classes/ConfigSchemaHandler/index.test.js index a1d676277c8..a6dd4e963c5 100644 --- a/test/unit/lib/classes/ConfigSchemaHandler/index.test.js +++ b/test/unit/lib/classes/ConfigSchemaHandler/index.test.js @@ -14,7 +14,7 @@ describe('ConfigSchemaHandler', () => { return runServerless({ fixture: 'configSchemaExtensions', cliArgs: ['info'], - }).then(serverless => { + }).then((serverless) => { expect(() => { serverless.configSchemaHandler.schema.properties.service.name = 'changed'; }).to.throw(Error); @@ -25,7 +25,7 @@ describe('ConfigSchemaHandler', () => { return runServerless({ fixture: 'configSchemaExtensions', cliArgs: ['info'], - }).then(serverless => { + }).then((serverless) => { expect(() => { serverless.configSchemaHandler.schema.properties.plugins.properties = 'changed'; }).to.throw(Error); @@ -36,7 +36,7 @@ describe('ConfigSchemaHandler', () => { return runServerless({ fixture: 'configSchemaExtensions', cliArgs: ['info'], - }).then(serverless => { + }).then((serverless) => { expect(() => { serverless.configSchemaHandler.schema.properties.resources.something = 'changed'; }).to.throw(Error); @@ -47,7 +47,7 @@ describe('ConfigSchemaHandler', () => { return runServerless({ fixture: 'configSchemaExtensions', cliArgs: ['info'], - }).then(serverless => { + }).then((serverless) => { expect(() => { serverless.configSchemaHandler.schema.properties.package.properties.oneMore = { type: 'string', @@ -60,7 +60,7 @@ describe('ConfigSchemaHandler', () => { return runServerless({ fixture: 'configSchemaExtensions', cliArgs: ['info'], - }).then(serverless => { + }).then((serverless) => { expect(() => { serverless.configSchemaHandler.schema.properties.layers.properties = 'changed'; }).to.throw(Error); @@ -82,7 +82,7 @@ describe('ConfigSchemaHandler', () => { return runServerless({ fixture: 'configSchemaExtensions', cliArgs: ['info'], - }).then(serverless => { + }).then((serverless) => { const expectedPieceOfSchema = { type: 'object', properties: { @@ -103,7 +103,9 @@ describe('ConfigSchemaHandler', () => { expect( serverless.serverless.configSchemaHandler.schema.properties.functions.patternProperties[ FUNCTION_NAME_PATTERN - ].properties.events.items.anyOf.find(definition => definition.required[0] === 'someEvent') + ].properties.events.items.anyOf.find( + (definition) => definition.required[0] === 'someEvent' + ) ).to.deep.equal(expectedPieceOfSchema); return; }); @@ -131,8 +133,9 @@ describe('ConfigSchemaHandler', () => { const existingEventDefinition = serverless.serverless.configSchemaHandler.schema.properties.functions.patternProperties[ FUNCTION_NAME_PATTERN - ].properties.events.items.anyOf.find(definition => definition.required[0] === 'existingEvent') - .properties.existingEvent; + ].properties.events.items.anyOf.find( + (definition) => definition.required[0] === 'existingEvent' + ).properties.existingEvent; expect(existingEventDefinition.properties).to.have.deep.property( 'somePluginAdditionalEventProp', @@ -152,7 +155,7 @@ describe('ConfigSchemaHandler', () => { const existingEventDefinition = serverless.serverless.configSchemaHandler.schema.properties.functions.patternProperties[ FUNCTION_NAME_PATTERN ].properties.events.items.anyOf.find( - definition => definition.required[0] === 'existingComplexEvent' + (definition) => definition.required[0] === 'existingComplexEvent' ).properties.existingComplexEvent; expect(existingEventDefinition).to.deep.equal({ @@ -212,7 +215,7 @@ describe('ConfigSchemaHandler', () => { return runServerless({ fixture: 'configSchemaExtensions', cliArgs: ['info'], - }).then(serverless => { + }).then((serverless) => { const actualFunctionProperties = serverless.serverless.configSchemaHandler.schema.properties.functions.patternProperties[ FUNCTION_NAME_PATTERN @@ -248,7 +251,7 @@ describe('ConfigSchemaHandler', () => { return runServerless({ fixture: 'configSchemaExtensions', cliArgs: ['info'], - }).then(serverless => { + }).then((serverless) => { const someCustomStringProp = { type: 'string', }; @@ -278,7 +281,7 @@ describe('ConfigSchemaHandler', () => { return runServerless({ fixture: 'configSchemaExtensions', cliArgs: ['info'], - }).then(serverless => { + }).then((serverless) => { const expectedAppPropSchema = { type: 'string', }; @@ -307,7 +310,7 @@ describe('ConfigSchemaHandler', () => { return runServerless({ fixture: 'configSchemaExtensions', cliArgs: ['info'], - }).then(serverless => { + }).then((serverless) => { const providerPieceOfSchema = { type: 'object', properties: { diff --git a/test/unit/lib/classes/ConfigSchemaHandler/normalizeAjvErrors.test.js b/test/unit/lib/classes/ConfigSchemaHandler/normalizeAjvErrors.test.js index c175d906d7a..4366b3a8376 100644 --- a/test/unit/lib/classes/ConfigSchemaHandler/normalizeAjvErrors.test.js +++ b/test/unit/lib/classes/ConfigSchemaHandler/normalizeAjvErrors.test.js @@ -10,7 +10,7 @@ describe('#normalizeAjvErrors', () => { const resolveAjv = memoize( () => new Ajv({ allErrors: true, coerceTypes: 'array', verbose: true }) ); - const resolveValidate = memoize(schema => resolveAjv().compile(schema)); + const resolveValidate = memoize((schema) => resolveAjv().compile(schema)); const schema = { type: 'object', @@ -122,7 +122,7 @@ describe('#normalizeAjvErrors', () => { additionalProperties: false, }; - const resolveNormalizedErrors = config => { + const resolveNormalizedErrors = (config) => { const validate = resolveValidate(schema); validate(config); if (!validate.errors) return []; @@ -175,7 +175,7 @@ describe('#normalizeAjvErrors', () => { describe('Reporting', () => { it('should report error for unrecognized root property', () => expect( - errors.some(error => { + errors.some((error) => { if (error.dataPath !== '') return false; if (error.keyword !== 'additionalProperties') return false; error.isExpected = true; @@ -184,7 +184,7 @@ describe('#normalizeAjvErrors', () => { ).to.be.true); it('should report error for unrecognized deep level property', () => expect( - errors.some(error => { + errors.some((error) => { if (error.dataPath !== '.package') return false; if (error.keyword !== 'additionalProperties') return false; error.isExpected = true; @@ -193,7 +193,7 @@ describe('#normalizeAjvErrors', () => { ).to.be.true); it('should report error for invalid function name', () => expect( - errors.some(error => { + errors.some((error) => { if (error.dataPath !== '.functions') return false; if (error.keyword !== 'additionalProperties') return false; error.isExpected = true; @@ -202,7 +202,7 @@ describe('#normalizeAjvErrors', () => { ).to.be.true); it('should report error for unrecognized event', () => expect( - errors.some(error => { + errors.some((error) => { if (error.dataPath !== ".functions['foo'].events[0]") return false; if (error.keyword !== 'anyOf') return false; error.isExpected = true; @@ -211,7 +211,7 @@ describe('#normalizeAjvErrors', () => { ).to.be.true); it('should report error for unrecognized property at event type configuration level', () => expect( - errors.some(error => { + errors.some((error) => { if (error.dataPath !== ".functions['foo'].events[1]") return false; if (error.keyword !== 'additionalProperties') return false; error.isExpected = true; @@ -230,7 +230,7 @@ describe('#normalizeAjvErrors', () => { // - http: // method: GET # Should be additionally indented expect( - errors.some(error => { + errors.some((error) => { if (error.dataPath !== ".functions['foo'].events[2]") return false; if (error.keyword !== 'additionalProperties') return false; error.isExpected = true; @@ -243,7 +243,7 @@ describe('#normalizeAjvErrors', () => { 'and object with unrecognized property was used', () => expect( - errors.some(error => { + errors.some((error) => { if (error.dataPath !== ".functions['foo'].events[3].http") return false; if (error.keyword !== 'additionalProperties') return false; error.isExpected = true; @@ -256,7 +256,7 @@ describe('#normalizeAjvErrors', () => { 'and invalid string was used', () => expect( - errors.some(error => { + errors.some((error) => { if (error.dataPath !== ".functions['foo'].events[4].http") return false; if (error.keyword !== 'pattern') return false; error.isExpected = true; @@ -269,7 +269,7 @@ describe('#normalizeAjvErrors', () => { 'and object with missing required property was used', () => expect( - errors.some(error => { + errors.some((error) => { if (error.dataPath !== ".functions['foo'].events[5].http") return false; if (error.keyword !== 'required') return false; error.isExpected = true; @@ -282,7 +282,7 @@ describe('#normalizeAjvErrors', () => { 'and for one variant error for deeper path was reported', () => expect( - errors.some(error => { + errors.some((error) => { if (error.dataPath !== '.provider.deploymentBucket.maxPreviousDeploymentArtifacts') { return false; } @@ -297,7 +297,7 @@ describe('#normalizeAjvErrors', () => { 'and for all variants errors relate to paths of same depth', () => expect( - errors.some(error => { + errors.some((error) => { if (error.dataPath !== '.custom.someCustom') { return false; } @@ -308,13 +308,13 @@ describe('#normalizeAjvErrors', () => { ).to.be.true ); it('should not report side errors', () => - expect(errors.filter(error => !error.isExpected)).to.deep.equal([])); + expect(errors.filter((error) => !error.isExpected)).to.deep.equal([])); }); describe('Message customization', () => { it('should report "additionalProperties" error with meaningful message', () => expect( - errors.find(error => { + errors.find((error) => { if (error.dataPath !== '.package') return false; if (error.keyword !== 'additionalProperties') return false; return true; @@ -322,7 +322,7 @@ describe('#normalizeAjvErrors', () => { ).to.include('unrecognized property ')); it('should report invalid function name error with meaningful message', () => expect( - errors.find(error => { + errors.find((error) => { if (error.dataPath !== '.functions') return false; if (error.keyword !== 'additionalProperties') return false; return true; @@ -330,7 +330,7 @@ describe('#normalizeAjvErrors', () => { ).to.include('must be alphanumeric')); it('should report unrecognized event error with a meaningful message', () => expect( - errors.find(error => { + errors.find((error) => { if (error.dataPath !== ".functions['foo'].events[0]") return false; if (error.keyword !== 'anyOf') return false; return true; diff --git a/test/unit/lib/classes/PluginManager.test.js b/test/unit/lib/classes/PluginManager.test.js index a278feb613b..34b5bc0c500 100644 --- a/test/unit/lib/classes/PluginManager.test.js +++ b/test/unit/lib/classes/PluginManager.test.js @@ -134,14 +134,14 @@ describe('PluginManager', () => { } functions() { - return new BbPromise(resolve => { + return new BbPromise((resolve) => { this.deployedFunctions += 1; return resolve(); }); } resources() { - return new BbPromise(resolve => { + return new BbPromise((resolve) => { this.deployedResources += 1; return resolve(); }); @@ -671,15 +671,15 @@ describe('PluginManager', () => { const servicePlugins = ['ServicePluginMock1', 'ServicePluginMock2']; pluginManager.loadAllPlugins(servicePlugins); - expect(pluginManager.plugins.some(plugin => plugin instanceof ServicePluginMock1)).to.equal( + expect(pluginManager.plugins.some((plugin) => plugin instanceof ServicePluginMock1)).to.equal( true ); - expect(pluginManager.plugins.some(plugin => plugin instanceof ServicePluginMock2)).to.equal( - true - ); - expect(pluginManager.plugins.some(plugin => plugin instanceof EnterprisePluginMock)).to.equal( + expect(pluginManager.plugins.some((plugin) => plugin instanceof ServicePluginMock2)).to.equal( true ); + expect( + pluginManager.plugins.some((plugin) => plugin instanceof EnterprisePluginMock) + ).to.equal(true); // note: this test will be refactored as the Create plugin will be moved // to another directory expect(pluginManager.plugins.length).to.be.above(2); @@ -691,10 +691,10 @@ describe('PluginManager', () => { pluginManager.loadAllPlugins(servicePlugins); const pluginIndexes = [ - pluginManager.plugins.findIndex(plugin => plugin instanceof Create), - pluginManager.plugins.findIndex(plugin => plugin instanceof ServicePluginMock1), - pluginManager.plugins.findIndex(plugin => plugin instanceof ServicePluginMock2), - pluginManager.plugins.findIndex(plugin => plugin instanceof EnterprisePluginMock), + pluginManager.plugins.findIndex((plugin) => plugin instanceof Create), + pluginManager.plugins.findIndex((plugin) => plugin instanceof ServicePluginMock1), + pluginManager.plugins.findIndex((plugin) => plugin instanceof ServicePluginMock2), + pluginManager.plugins.findIndex((plugin) => plugin instanceof EnterprisePluginMock), ]; expect(pluginIndexes).to.deep.equal(pluginIndexes.slice().sort((a, b) => a - b)); }); @@ -1219,9 +1219,7 @@ describe('PluginManager', () => { }); it('should accept a single event in place of an array', () => { - expect(pluginManager.getHooks('deploy:functions')) - .to.be.an('Array') - .with.length(1); + expect(pluginManager.getHooks('deploy:functions')).to.be.an('Array').with.length(1); }); }); @@ -1238,8 +1236,8 @@ describe('PluginManager', () => { const plugins = pluginManager.getPlugins(); expect(plugins.length).to.be.above(3); - expect(plugins.some(plugin => plugin instanceof ServicePluginMock1)).to.be.true; - expect(plugins.some(plugin => plugin instanceof ServicePluginMock2)).to.be.true; + expect(plugins.some((plugin) => plugin instanceof ServicePluginMock1)).to.be.true; + expect(plugins.some((plugin) => plugin instanceof ServicePluginMock2)).to.be.true; }); afterEach(() => { @@ -1321,7 +1319,7 @@ describe('PluginManager', () => { expect(pluginManager.cliOptions.bar).to.equal(100); }); - [0, '', false].forEach(defaultValue => { + [0, '', false].forEach((defaultValue) => { it(`assigns valid falsy default value '${defaultValue} to empty options`, () => { pluginManager.commands = { foo: { @@ -1718,9 +1716,7 @@ describe('PluginManager', () => { pluginManager.addPlugin(AliasPluginMock); const commands = pluginManager.getCommands(); - expect(commands) - .to.have.a.property('on') - .that.has.a.nested.property('commands.premise'); + expect(commands).to.have.a.property('on').that.has.a.nested.property('commands.premise'); expect(commands).to.have.a.property('premise'); }); }); @@ -1788,7 +1784,7 @@ describe('PluginManager', () => { }, }; }); - it('should give a suggestion for an unknown command', done => { + it('should give a suggestion for an unknown command', (done) => { try { pluginManager.getCommand(['creet']); done('Test failed. Expected an error to be thrown'); @@ -1802,7 +1798,7 @@ describe('PluginManager', () => { } }); - it('should not give a suggestion for valid top level command', done => { + it('should not give a suggestion for valid top level command', (done) => { try { pluginManager.getCommand(['deploy', 'function-misspelled']); done('Test failed. Expected an error to be thrown'); @@ -1978,8 +1974,8 @@ describe('PluginManager', () => { installPlugin(localPluginDir, SynchronousPluginMock); pluginManager.loadAllPlugins(['local-plugin']); - expect(pluginManager.plugins).to.satisfy(plugins => - plugins.some(plugin => plugin.constructor.name === 'SynchronousPluginMock') + expect(pluginManager.plugins).to.satisfy((plugins) => + plugins.some((plugin) => plugin.constructor.name === 'SynchronousPluginMock') ); }); @@ -1993,8 +1989,8 @@ describe('PluginManager', () => { }); // Had to use contructor.name because the class will be loaded via // require and the reference will not match with SynchronousPluginMock - expect(pluginManager.plugins).to.satisfy(plugins => - plugins.some(plugin => plugin.constructor.name === 'SynchronousPluginMock') + expect(pluginManager.plugins).to.satisfy((plugins) => + plugins.some((plugin) => plugin.constructor.name === 'SynchronousPluginMock') ); }); @@ -2009,8 +2005,8 @@ describe('PluginManager', () => { }); // Had to use contructor.name because the class will be loaded via // require and the reference will not match with SynchronousPluginMock - expect(pluginManager.plugins).to.satisfy(plugins => - plugins.some(plugin => plugin.constructor.name === 'SynchronousPluginMock') + expect(pluginManager.plugins).to.satisfy((plugins) => + plugins.some((plugin) => plugin.constructor.name === 'SynchronousPluginMock') ); }); @@ -2025,8 +2021,8 @@ describe('PluginManager', () => { }); // Had to use contructor.name because the class will be loaded via // require and the reference will not match with SynchronousPluginMock - expect(pluginManager.plugins).to.satisfy(plugins => - plugins.some(plugin => plugin.constructor.name === 'SynchronousPluginMock') + expect(pluginManager.plugins).to.satisfy((plugins) => + plugins.some((plugin) => plugin.constructor.name === 'SynchronousPluginMock') ); }); @@ -2041,7 +2037,7 @@ describe('PluginManager', () => { }); }); - describe('Plugin / CLI integration', function() { + describe('Plugin / CLI integration', function () { this.timeout(1000 * 60 * 10); let serverlessInstance; diff --git a/test/unit/lib/classes/PromiseTracker.test.js b/test/unit/lib/classes/PromiseTracker.test.js index 8e872c5fbc7..e82702db8a7 100644 --- a/test/unit/lib/classes/PromiseTracker.test.js +++ b/test/unit/lib/classes/PromiseTracker.test.js @@ -37,7 +37,7 @@ describe('PromiseTracker', () => { }); it('reports the correct number of added promise statuses', () => { let resolve; - const pending = new BbPromise(rslv => { + const pending = new BbPromise((rslv) => { resolve = rslv; }); const resolved = BbPromise.resolve(); @@ -73,7 +73,7 @@ describe('PromiseTracker', () => { }); it('reports and then clears tracked promises when stopped after reporting.', () => { let resolve; - const pending = new BbPromise(rslv => { + const pending = new BbPromise((rslv) => { resolve = rslv; }); const resolved = BbPromise.resolve(); diff --git a/test/unit/lib/classes/Utils.test.js b/test/unit/lib/classes/Utils.test.js index b6e50621a82..ce2b35ac793 100644 --- a/test/unit/lib/classes/Utils.test.js +++ b/test/unit/lib/classes/Utils.test.js @@ -85,7 +85,7 @@ describe('Utils', () => { serverless.utils.writeFileSync(tmpFilePath, { foo: 'bar' }); - return expect(serverless.yamlParser.parse(tmpFilePath)).to.be.fulfilled.then(obj => { + return expect(serverless.yamlParser.parse(tmpFilePath)).to.be.fulfilled.then((obj) => { expect(obj.foo).to.equal('bar'); }); }); @@ -95,7 +95,7 @@ describe('Utils', () => { serverless.utils.writeFileSync(tmpFilePath, { foo: 'bar' }); - return expect(serverless.yamlParser.parse(tmpFilePath)).to.be.fulfilled.then(obj => { + return expect(serverless.yamlParser.parse(tmpFilePath)).to.be.fulfilled.then((obj) => { expect(obj.foo).to.equal('bar'); }); }); @@ -186,7 +186,7 @@ describe('Utils', () => { serverless.utils.writeFileSync(tmpFilePath, { foo: 'bar' }); // note: use return when testing promises otherwise you'll have unhandled rejection errors - return expect(serverless.utils.readFile(tmpFilePath)).to.be.fulfilled.then(obj => { + return expect(serverless.utils.readFile(tmpFilePath)).to.be.fulfilled.then((obj) => { expect(obj.foo).to.equal('bar'); }); }); diff --git a/test/unit/lib/classes/Variables.test.js b/test/unit/lib/classes/Variables.test.js index 46cd9735fdf..bdd2ac64577 100644 --- a/test/unit/lib/classes/Variables.test.js +++ b/test/unit/lib/classes/Variables.test.js @@ -71,7 +71,7 @@ describe('Variables', () => { .returns(BbPromise.resolve()); const populateObjectStub = sinon .stub(serverless.variables, 'populateObjectImpl') - .callsFake(val => { + .callsFake((val) => { expect(val).to.equal(serverless.service); expect(val.provider.variableSyntax).to.be.undefined; expect(val.serverless).to.be.undefined; @@ -88,14 +88,14 @@ describe('Variables', () => { it('should clear caches and remaining state *before* [pre]populating service', () => { const prepopulateServiceStub = sinon .stub(serverless.variables, 'prepopulateService') - .callsFake(val => { + .callsFake((val) => { expect(serverless.variables.deep).to.eql([]); expect(serverless.variables.tracker.getAll()).to.eql([]); return BbPromise.resolve(val); }); const populateObjectStub = sinon .stub(serverless.variables, 'populateObjectImpl') - .callsFake(val => { + .callsFake((val) => { expect(serverless.variables.deep).to.eql([]); expect(serverless.variables.tracker.getAll()).to.eql([]); return BbPromise.resolve(val); @@ -115,7 +115,7 @@ describe('Variables', () => { it('should clear caches and remaining *after* [pre]populating service', () => { const prepopulateServiceStub = sinon .stub(serverless.variables, 'prepopulateService') - .callsFake(val => { + .callsFake((val) => { serverless.variables.deep.push('${foo:}'); const promise = BbPromise.resolve(val); serverless.variables.tracker.add('foo:', promise, '${foo:}'); @@ -124,7 +124,7 @@ describe('Variables', () => { }); const populateObjectStub = sinon .stub(serverless.variables, 'populateObjectImpl') - .callsFake(val => { + .callsFake((val) => { serverless.variables.deep.push('${bar:}'); const promise = BbPromise.resolve(val); serverless.variables.tracker.add('bar:', promise, '${bar:}'); @@ -155,12 +155,12 @@ describe('Variables', () => { { value: 'でsu', description: 'mixed japanese leading' }, { value: 'suごi', description: 'mixed japanese middle' }, { value: '①⑴⒈⒜Ⓐⓐⓟ ..▉가Ὠ', description: 'random unicode' }, - ].forEach(testCase => { + ].forEach((testCase) => { it(testCase.description, () => { serverless.variables.service.custom = { settings: `\${self:nonExistent, "${testCase.value}"}`, }; - return serverless.variables.populateService().should.be.fulfilled.then(result => { + return serverless.variables.populateService().should.be.fulfilled.then((result) => { expect(result.custom).to.be.deep.eql({ settings: testCase.value, }); @@ -173,7 +173,7 @@ describe('Variables', () => { serverless.variables.service.custom = { settings: '${opt:nonExistent, "fallback"}', }; - return serverless.variables.populateService().should.be.fulfilled.then(result => { + return serverless.variables.populateService().should.be.fulfilled.then((result) => { expect(result.custom).to.be.deep.eql({ settings: 'fallback', }); @@ -184,7 +184,7 @@ describe('Variables', () => { serverless.variables.service.custom = { settings: '${env:nonExistent, "fallback"}', }; - return serverless.variables.populateService().should.be.fulfilled.then(result => { + return serverless.variables.populateService().should.be.fulfilled.then((result) => { expect(result.custom).to.be.deep.eql({ settings: 'fallback', }); @@ -202,7 +202,7 @@ describe('Variables', () => { return serverless.variables .populateService() - .should.be.fulfilled.then(result => { + .should.be.fulfilled.then((result) => { expect(result.custom).to.be.deep.eql({ settings: 'fallback', }); @@ -227,7 +227,7 @@ describe('Variables', () => { return serverless.variables .populateService() - .should.be.fulfilled.then(result => { + .should.be.fulfilled.then((result) => { expect(result.custom).to.be.deep.eql({ settings: 'fallback', }); @@ -256,7 +256,7 @@ describe('Variables', () => { return serverless.variables .populateService() - .should.be.fulfilled.then(result => { + .should.be.fulfilled.then((result) => { expect(result.custom.settings1).to.not.equal(result.custom.settings2); }) .finally(() => { @@ -283,7 +283,7 @@ describe('Variables', () => { serverless.variables.service.custom = { settings: '${s3:bucket/key, "fallback"}', }; - return serverless.variables.populateService().should.be.fulfilled.then(result => { + return serverless.variables.populateService().should.be.fulfilled.then((result) => { expect(result.custom).to.be.deep.eql({ settings: 'fallback', }); @@ -294,7 +294,7 @@ describe('Variables', () => { serverless.variables.service.custom = { settings: '${cf:stack.value, "fallback"}', }; - return serverless.variables.populateService().should.be.fulfilled.then(result => { + return serverless.variables.populateService().should.be.fulfilled.then((result) => { expect(result.custom).to.be.deep.eql({ settings: 'fallback', }); @@ -305,7 +305,7 @@ describe('Variables', () => { serverless.variables.service.custom = { settings: '${ssm:/path/param, "fallback"}', }; - return serverless.variables.populateService().should.be.fulfilled.then(result => { + return serverless.variables.populateService().should.be.fulfilled.then((result) => { expect(result.custom).to.be.deep.eql({ settings: 'fallback', }); @@ -343,28 +343,28 @@ describe('Variables', () => { requestStub.restore(); }); const prepopulatedProperties = [ - { name: 'region', getter: provider => provider.getRegion() }, - { name: 'stage', getter: provider => provider.getStage() }, - { name: 'profile', getter: provider => provider.getProfile() }, + { name: 'region', getter: (provider) => provider.getRegion() }, + { name: 'stage', getter: (provider) => provider.getStage() }, + { name: 'profile', getter: (provider) => provider.getProfile() }, { name: 'credentials', - getter: provider => provider.serverless.service.provider.credentials, + getter: (provider) => provider.serverless.service.provider.credentials, }, { name: 'credentials.accessKeyId', - getter: provider => provider.serverless.service.provider.credentials.accessKeyId, + getter: (provider) => provider.serverless.service.provider.credentials.accessKeyId, }, { name: 'credentials.secretAccessKey', - getter: provider => provider.serverless.service.provider.credentials.secretAccessKey, + getter: (provider) => provider.serverless.service.provider.credentials.secretAccessKey, }, { name: 'credentials.sessionToken', - getter: provider => provider.serverless.service.provider.credentials.sessionToken, + getter: (provider) => provider.serverless.service.provider.credentials.sessionToken, }, ]; describe('basic population tests', () => { - prepopulatedProperties.forEach(property => { + prepopulatedProperties.forEach((property) => { it(`should populate variables in ${property.name} values`, () => { _.set( awsProvider.serverless.service.provider, @@ -386,8 +386,8 @@ describe('Variables', () => { { value: '${s3:bucket/key}', name: 'S3' }, { value: '${ssm:/path/param}', name: 'SSM' }, ]; - prepopulatedProperties.forEach(property => { - dependentConfigs.forEach(config => { + prepopulatedProperties.forEach((property) => { + dependentConfigs.forEach((config) => { it(`should reject ${config.name} variables in ${property.name} values`, () => { _.set(awsProvider.serverless.service.provider, property.name, config.value); return serverless.variables @@ -413,7 +413,7 @@ describe('Variables', () => { { region: '${self:foo, "foo"}', state: 'bar' }, { region: '${self:foo, "foo"}', state: '${self:bar, "bar"}' }, ]; - stateCombinations.forEach(combination => { + stateCombinations.forEach((combination) => { it('must leave the dependent services in their original state', () => { const dependentMethods = [ { name: 'getValueFromCf', original: serverless.variables.getValueFromCf }, @@ -423,7 +423,7 @@ describe('Variables', () => { awsProvider.serverless.service.provider.region = combination.region; awsProvider.serverless.service.provider.state = combination.state; return serverless.variables.populateService().should.be.fulfilled.then(() => { - dependentMethods.forEach(method => { + dependentMethods.forEach((method) => { expect(serverless.variables[method.name]).to.equal(method.original); }); }); @@ -484,7 +484,7 @@ describe('Variables', () => { return serverless.variables .populateObject(object) - .then(populatedObject => { + .then((populatedObject) => { expect(populatedObject).to.deep.equal(expectedPopulatedObject); }) .finally(() => serverless.variables.populateValue.restore()); @@ -501,7 +501,7 @@ describe('Variables', () => { expectedPopulatedObject['some.nested.key'] = 'hello'; const populateValueStub = sinon.stub(serverless.variables, 'populateValue').callsFake( // eslint-disable-next-line no-template-curly-in-string - val => { + (val) => { return val === '${opt:stage}' ? BbPromise.resolve('prod') : BbPromise.resolve(val); } ); @@ -536,7 +536,7 @@ describe('Variables', () => { me: expected, }; return expect( - serverless.variables.populateObject(service).then(result => { + serverless.variables.populateObject(service).then((result) => { expect(jc.stringify(result)).to.eql(jc.stringify(expected)); }) ).to.be.fulfilled; @@ -553,7 +553,7 @@ describe('Variables', () => { val2: 'my value 0', }; return expect( - serverless.variables.populateObject(service.custom).then(result => { + serverless.variables.populateObject(service.custom).then((result) => { expect(result).to.eql(expected); }) ).to.be.fulfilled; @@ -568,7 +568,7 @@ describe('Variables', () => { val1: 'string', }; return expect( - serverless.variables.populateObject(service.custom).then(result => { + serverless.variables.populateObject(service.custom).then((result) => { expect(result).to.eql(expected); }) ).to.be.fulfilled; @@ -583,7 +583,7 @@ describe('Variables', () => { val1: '*', }; return expect( - serverless.variables.populateObject(service.custom).then(result => { + serverless.variables.populateObject(service.custom).then((result) => { expect(result).to.eql(expected); }) ).to.be.fulfilled; @@ -598,7 +598,7 @@ describe('Variables', () => { val1: 'foo*', }; return expect( - serverless.variables.populateObject(service.custom).then(result => { + serverless.variables.populateObject(service.custom).then((result) => { expect(result).to.eql(expected); }) ).to.be.fulfilled; @@ -613,7 +613,7 @@ describe('Variables', () => { val1: 'my value', }; return expect( - serverless.variables.populateObject(service.custom).then(result => { + serverless.variables.populateObject(service.custom).then((result) => { expect(result).to.eql(expected); }) ).to.be.fulfilled; @@ -624,7 +624,7 @@ describe('Variables', () => { }; const expected = { val0: undefined }; return expect( - serverless.variables.populateObject(service.custom).then(result => { + serverless.variables.populateObject(service.custom).then((result) => { expect(result).to.eql(expected); }) ).to.be.fulfilled; @@ -639,7 +639,7 @@ describe('Variables', () => { val1: 'my value', }; return expect( - serverless.variables.populateObject(service.custom).then(result => { + serverless.variables.populateObject(service.custom).then((result) => { expect(result).to.eql(expected); }) ).to.be.fulfilled; @@ -654,7 +654,7 @@ describe('Variables', () => { val1: 'my value', }; return expect( - serverless.variables.populateObject(service.custom).then(result => { + serverless.variables.populateObject(service.custom).then((result) => { expect(result).to.eql(expected); }) ).to.be.fulfilled; @@ -671,7 +671,7 @@ describe('Variables', () => { val2: 'my value', }; return expect( - serverless.variables.populateObject(service.custom).then(result => { + serverless.variables.populateObject(service.custom).then((result) => { expect(result).to.eql(expected); }) ).to.be.fulfilled; @@ -688,7 +688,7 @@ describe('Variables', () => { val2: 'my value', }; return expect( - serverless.variables.populateObject(service.custom).then(result => { + serverless.variables.populateObject(service.custom).then((result) => { expect(result).to.eql(expected); }) ).to.be.fulfilled; @@ -705,7 +705,7 @@ describe('Variables', () => { val2: 'my value', }; return expect( - serverless.variables.populateObject(service.custom).then(result => { + serverless.variables.populateObject(service.custom).then((result) => { expect(result).to.eql(expected); }) ).to.be.fulfilled; @@ -722,7 +722,7 @@ describe('Variables', () => { val2: 'my value', }; return expect( - serverless.variables.populateObject(service.custom).then(result => { + serverless.variables.populateObject(service.custom).then((result) => { expect(result).to.eql(expected); }) ).to.be.fulfilled; @@ -741,7 +741,7 @@ describe('Variables', () => { val2: 'my value', }; return expect( - serverless.variables.populateObject(service.custom).then(result => { + serverless.variables.populateObject(service.custom).then((result) => { expect(result).to.eql(expected); }) ).to.be.fulfilled; @@ -1454,7 +1454,7 @@ module.exports = { getValueFromSourceStub.onCall(2).resolves('variableValue'); return serverless.variables .overwrite(['opt:stage', 'env:stage', 'self:provider.stage']) - .should.be.fulfilled.then(valueToPopulate => { + .should.be.fulfilled.then((valueToPopulate) => { expect(valueToPopulate).to.equal('variableValue'); expect(getValueFromSourceStub).to.have.been.calledThrice; }) @@ -1467,7 +1467,7 @@ module.exports = { getValueFromSourceStub.onCall(1).resolves('variableValue'); return serverless.variables .overwrite(['opt:stage', 'env:stage']) - .should.be.fulfilled.then(valueToPopulate => { + .should.be.fulfilled.then((valueToPopulate) => { expect(valueToPopulate).to.equal('variableValue'); expect(getValueFromSourceStub).to.have.been.calledTwice; }) @@ -1480,7 +1480,7 @@ module.exports = { getValueFromSourceStub.onCall(1).resolves([]); return serverless.variables .overwrite(['opt:stage', 'env:stage']) - .should.be.fulfilled.then(valueToPopulate => { + .should.be.fulfilled.then((valueToPopulate) => { expect(valueToPopulate).to.deep.equal([]); expect(getValueFromSourceStub).to.have.been.calledTwice; }) @@ -1516,7 +1516,7 @@ module.exports = { getValueFromSourceStub.onCall(2).resolves('variableValue2'); return serverless.variables .overwrite(['opt:stage', 'env:stage', 'self:provider.stage']) - .should.be.fulfilled.then(valueToPopulate => + .should.be.fulfilled.then((valueToPopulate) => expect(valueToPopulate).to.equal('variableValue') ) .finally(() => getValueFromSourceStub.restore()); @@ -1587,7 +1587,7 @@ module.exports = { it('should call getValueFromSls if referencing sls var', () => serverless.variables .getValueFromSource('sls:instanceId') - .should.be.fulfilled.then(valueToPopulate => { + .should.be.fulfilled.then((valueToPopulate) => { expect(valueToPopulate).to.equal(variableValue); expect(getValueFromSlsStub).to.have.been.called; expect(getValueFromSlsStub).to.have.been.calledWith('sls:instanceId'); @@ -1596,7 +1596,7 @@ module.exports = { it('should call getValueFromEnv if referencing env var', () => serverless.variables .getValueFromSource('env:TEST_VAR') - .should.be.fulfilled.then(valueToPopulate => { + .should.be.fulfilled.then((valueToPopulate) => { expect(valueToPopulate).to.equal(variableValue); expect(getValueFromEnvStub).to.have.been.called; expect(getValueFromEnvStub).to.have.been.calledWith('env:TEST_VAR'); @@ -1605,7 +1605,7 @@ module.exports = { it('should call getValueFromOptions if referencing an option', () => serverless.variables .getValueFromSource('opt:stage') - .should.be.fulfilled.then(valueToPopulate => { + .should.be.fulfilled.then((valueToPopulate) => { expect(valueToPopulate).to.equal(variableValue); expect(getValueFromOptionsStub).to.have.been.called; expect(getValueFromOptionsStub).to.have.been.calledWith('opt:stage'); @@ -1614,7 +1614,7 @@ module.exports = { it('should call getValueFromSelf if referencing from self', () => serverless.variables .getValueFromSource('self:provider') - .should.be.fulfilled.then(valueToPopulate => { + .should.be.fulfilled.then((valueToPopulate) => { expect(valueToPopulate).to.equal(variableValue); expect(getValueFromSelfStub).to.have.been.called; expect(getValueFromSelfStub).to.have.been.calledWith('self:provider'); @@ -1623,7 +1623,7 @@ module.exports = { it('should call getValueFromFile if referencing from another file', () => serverless.variables .getValueFromSource('file(./config.yml)') - .should.be.fulfilled.then(valueToPopulate => { + .should.be.fulfilled.then((valueToPopulate) => { expect(valueToPopulate).to.equal(variableValue); expect(getValueFromFileStub).to.have.been.called; expect(getValueFromFileStub).to.have.been.calledWith('file(./config.yml)'); @@ -1632,7 +1632,7 @@ module.exports = { it('should call getValueFromCf if referencing CloudFormation Outputs', () => serverless.variables .getValueFromSource('cf:test-stack.testOutput') - .should.be.fulfilled.then(valueToPopulate => { + .should.be.fulfilled.then((valueToPopulate) => { expect(valueToPopulate).to.equal(variableValue); expect(getValueFromCfStub).to.have.been.called; expect(getValueFromCfStub).to.have.been.calledWith('cf:test-stack.testOutput'); @@ -1641,7 +1641,7 @@ module.exports = { it('should call getValueFromS3 if referencing variable in S3', () => serverless.variables .getValueFromSource('s3:test-bucket/path/to/key') - .should.be.fulfilled.then(valueToPopulate => { + .should.be.fulfilled.then((valueToPopulate) => { expect(valueToPopulate).to.equal(variableValue); expect(getValueFromS3Stub).to.have.been.called; expect(getValueFromS3Stub).to.have.been.calledWith('s3:test-bucket/path/to/key'); @@ -1650,7 +1650,7 @@ module.exports = { it('should call getValueFromSsm if referencing variable in SSM', () => serverless.variables .getValueFromSource('ssm:/test/path/to/param') - .should.be.fulfilled.then(valueToPopulate => { + .should.be.fulfilled.then((valueToPopulate) => { expect(valueToPopulate).to.equal(variableValue); expect(getValueFromSsmStub).to.have.been.called; expect(getValueFromSsmStub).to.have.been.calledWith('ssm:/test/path/to/param'); @@ -1684,7 +1684,7 @@ module.exports = { variableString: 'ssm:/test/path/to/param', }, ]; - sources.forEach(source => { + sources.forEach((source) => { it(`should only call ${source.function} once, returning the cached value otherwise`, () => { const getValueFunctionStub = serverless.variables.variableResolvers[source.functionIndex].resolver; @@ -1709,7 +1709,7 @@ module.exports = { describe('#getValueFromSls()', () => { it('should get variable from Serverless Framework provided variables', () => { serverless.instanceId = 12345678; - return serverless.variables.getValueFromSls('sls:instanceId').then(valueToPopulate => { + return serverless.variables.getValueFromSls('sls:instanceId').then((valueToPopulate) => { expect(valueToPopulate).to.equal(12345678); }); }); @@ -1723,7 +1723,7 @@ module.exports = { it('should allow top-level references to the environment variables hive', () => { process.env.TEST_VAR = 'someValue'; - return serverless.variables.getValueFromEnv('env:').then(valueToPopulate => { + return serverless.variables.getValueFromEnv('env:').then((valueToPopulate) => { expect(valueToPopulate.TEST_VAR).to.be.equal('someValue'); }); }); @@ -1813,7 +1813,7 @@ module.exports = { const readFileSyncStub = sinon.stub(serverless.utils, 'readFileSync').returns(configYml); return serverless.variables .getValueFromFile('file(~/somedir/config.yml)') - .should.be.fulfilled.then(valueToPopulate => { + .should.be.fulfilled.then((valueToPopulate) => { expect(realpathSync).to.not.have.been.called; expect(fileExistsStub).to.have.been.calledWithMatch(expectedFileName); expect(readFileSyncStub).to.have.been.calledWithMatch(expectedFileName); @@ -1851,7 +1851,7 @@ module.exports = { const existsSync = sinon.spy(fse, 'existsSync'); return serverless.variables .getValueFromFile('file(./non-existing.yml)') - .should.be.fulfilled.then(valueToPopulate => { + .should.be.fulfilled.then((valueToPopulate) => { expect(realpathSync).to.not.have.been.called; expect(existsSync).to.have.been.calledOnce; expect(valueToPopulate).to.be.undefined; @@ -1870,7 +1870,7 @@ module.exports = { return serverless.variables.getValueFromFile('file(./someFile)').should.become('hello world'); }); - it('should populate symlinks', function() { + it('should populate symlinks', function () { const SUtils = new Utils(); const tmpDirPath = getTmpDirPath(); const realFilePath = path.join(tmpDirPath, 'someFile'); @@ -2593,13 +2593,13 @@ module.exports = { it('truthy string should throw an error', () => { return serverless.variables .getValueStrToBool('strToBool(anything)') - .catch(err => err.message) + .catch((err) => err.message) .should.become(errMessage); }); it('null (string) should throw an error', () => { return serverless.variables .getValueStrToBool('strToBool(null)') - .catch(err => err.message) + .catch((err) => err.message) .should.become(errMessage); }); it('strToBool(true) as an input to strToBool', () => { diff --git a/test/unit/lib/configSchema.test.js b/test/unit/lib/configSchema.test.js index 18139c652e1..38897e05516 100644 --- a/test/unit/lib/configSchema.test.js +++ b/test/unit/lib/configSchema.test.js @@ -131,7 +131,7 @@ describe('#configSchema', () => { if (someCase.logMessage) expect(stdoutData).to.include(someCase.logMessage); return; }, - err => { + (err) => { try { expect(err.message).to.include(someCase.errorMessage); } catch (error) { diff --git a/test/unit/lib/plugins/aws/common/lib/cleanupTempDir.test.js b/test/unit/lib/plugins/aws/common/lib/cleanupTempDir.test.js index e806c5e04da..c1ce7dfd94f 100644 --- a/test/unit/lib/plugins/aws/common/lib/cleanupTempDir.test.js +++ b/test/unit/lib/plugins/aws/common/lib/cleanupTempDir.test.js @@ -34,14 +34,14 @@ describe('#cleanupTempDir()', () => { }); }); - it('should resolve if servicePath is not present', done => { + it('should resolve if servicePath is not present', (done) => { delete serverless.config.servicePath; packageService.cleanupTempDir().then(() => { done(); }); }); - it('should resolve if the .serverless directory is not present', done => { + it('should resolve if the .serverless directory is not present', (done) => { packageService.cleanupTempDir().then(() => { done(); }); diff --git a/test/unit/lib/plugins/aws/configCredentials.test.js b/test/unit/lib/plugins/aws/configCredentials.test.js index c7495f1838a..eac88a4f6b6 100644 --- a/test/unit/lib/plugins/aws/configCredentials.test.js +++ b/test/unit/lib/plugins/aws/configCredentials.test.js @@ -29,7 +29,7 @@ describe('AwsConfigCredentials', () => { () => { throw new Error('Unexpected ~/.aws directory, related tests aborted'); }, - error => { + (error) => { if (error.code === 'ENOENT') return; throw error; } @@ -118,7 +118,7 @@ describe('AwsConfigCredentials', () => { expect(awsConfigCredentials.options.profile).to.equal('default'); })); - it('should resolve if the provider option is not "aws"', done => { + it('should resolve if the provider option is not "aws"', (done) => { awsConfigCredentials.options.provider = 'invalid-provider'; awsConfigCredentials.configureCredentials().then(() => done()); @@ -131,7 +131,7 @@ describe('AwsConfigCredentials', () => { () => { throw new Error('Unexpected'); }, - error => + (error) => expect(error.message).to.include('Please include --key and --secret options for AWS') ); }); diff --git a/test/unit/lib/plugins/aws/deploy/lib/checkForChanges.test.js b/test/unit/lib/plugins/aws/deploy/lib/checkForChanges.test.js index 1a2f15aab3a..586b3a24c89 100644 --- a/test/unit/lib/plugins/aws/deploy/lib/checkForChanges.test.js +++ b/test/unit/lib/plugins/aws/deploy/lib/checkForChanges.test.js @@ -125,7 +125,7 @@ describe('checkForChanges', () => { it('should resolve if no result is returned', () => { listObjectsV2Stub.resolves(); - return expect(awsDeploy.getMostRecentObjects()).to.be.fulfilled.then(result => { + return expect(awsDeploy.getMostRecentObjects()).to.be.fulfilled.then((result) => { expect(listObjectsV2Stub).to.have.been.calledWithExactly('S3', 'listObjectsV2', { Bucket: awsDeploy.bucketName, Prefix: 'serverless/my-service/dev', @@ -160,7 +160,7 @@ describe('checkForChanges', () => { listObjectsV2Stub.resolves(serviceObjects); - return expect(awsDeploy.getMostRecentObjects()).to.be.fulfilled.then(result => { + return expect(awsDeploy.getMostRecentObjects()).to.be.fulfilled.then((result) => { expect(listObjectsV2Stub).to.have.been.calledWithExactly('S3', 'listObjectsV2', { Bucket: awsDeploy.bucketName, Prefix: 'serverless/my-service/dev', @@ -181,7 +181,7 @@ describe('checkForChanges', () => { listObjectsV2Stub.resolves(serviceObjects); - return expect(awsDeploy.getMostRecentObjects()).to.be.fulfilled.then(result => { + return expect(awsDeploy.getMostRecentObjects()).to.be.fulfilled.then((result) => { expect(listObjectsV2Stub).to.have.been.calledWithExactly('S3', 'listObjectsV2', { Bucket: awsDeploy.bucketName, Prefix: 'serverless/my-service/dev', @@ -206,7 +206,7 @@ describe('checkForChanges', () => { }); it('should resolve if no input is provided', () => - expect(awsDeploy.getObjectMetadata()).to.be.fulfilled.then(result => { + expect(awsDeploy.getObjectMetadata()).to.be.fulfilled.then((result) => { expect(headObjectStub).to.not.have.been.called; expect(result).to.deep.equal([]); })); @@ -214,7 +214,7 @@ describe('checkForChanges', () => { it('should resolve if no objects are provided as input', () => { const input = []; - return expect(awsDeploy.getObjectMetadata(input)).to.be.fulfilled.then(result => { + return expect(awsDeploy.getObjectMetadata(input)).to.be.fulfilled.then((result) => { expect(headObjectStub).to.not.have.been.called; expect(result).to.deep.equal([]); }); @@ -290,11 +290,7 @@ describe('checkForChanges', () => { it('should resolve if objects are given, but no function last modified date', () => { globbySyncStub.returns(['my-service.zip']); - cryptoStub - .createHash() - .update() - .digest.onCall(0) - .returns('local-hash-cf-template'); + cryptoStub.createHash().update().digest.onCall(0).returns('local-hash-cf-template'); const input = [{ Metadata: { filesha256: 'remote-hash-cf-template' } }]; @@ -320,16 +316,8 @@ describe('checkForChanges', () => { it('should not set a flag if there are more remote hashes', () => { globbySyncStub.returns(['my-service.zip']); - cryptoStub - .createHash() - .update() - .digest.onCall(0) - .returns('local-hash-cf-template'); - cryptoStub - .createHash() - .update() - .digest.onCall(1) - .returns('local-hash-zip-file-1'); + cryptoStub.createHash().update().digest.onCall(0).returns('local-hash-cf-template'); + cryptoStub.createHash().update().digest.onCall(1).returns('local-hash-zip-file-1'); const input = [ { Metadata: { filesha256: 'remote-hash-cf-template' } }, @@ -363,16 +351,8 @@ describe('checkForChanges', () => { it('should not set a flag if remote and local hashes are different', () => { globbySyncStub.returns(['my-service.zip']); - cryptoStub - .createHash() - .update() - .digest.onCall(0) - .returns('local-hash-cf-template'); - cryptoStub - .createHash() - .update() - .digest.onCall(1) - .returns('local-hash-zip-file-1'); + cryptoStub.createHash().update().digest.onCall(0).returns('local-hash-cf-template'); + cryptoStub.createHash().update().digest.onCall(1).returns('local-hash-zip-file-1'); const input = [ { Metadata: { filesha256: 'remote-hash-cf-template' } }, @@ -401,22 +381,10 @@ describe('checkForChanges', () => { it('should not set a flag if remote and local hashes are the same but are duplicated', () => { globbySyncStub.returns(['func1.zip', 'func2.zip']); - cryptoStub - .createHash() - .update() - .digest.onCall(0) - .returns('remote-hash-cf-template'); + cryptoStub.createHash().update().digest.onCall(0).returns('remote-hash-cf-template'); // happens when package.individually is used - cryptoStub - .createHash() - .update() - .digest.onCall(1) - .returns('remote-hash-zip-file-1'); - cryptoStub - .createHash() - .update() - .digest.onCall(2) - .returns('remote-hash-zip-file-1'); + cryptoStub.createHash().update().digest.onCall(1).returns('remote-hash-zip-file-1'); + cryptoStub.createHash().update().digest.onCall(2).returns('remote-hash-zip-file-1'); const input = [ { Metadata: { filesha256: 'remote-hash-cf-template' } }, @@ -448,16 +416,8 @@ describe('checkForChanges', () => { it('should not set a flag if the hashes are equal, but the objects were modified after their functions', () => { globbySyncStub.returns(['my-service.zip']); - cryptoStub - .createHash() - .update() - .digest.onCall(0) - .returns('hash-cf-template'); - cryptoStub - .createHash() - .update() - .digest.onCall(1) - .returns('hash-zip-file-1'); + cryptoStub.createHash().update().digest.onCall(0).returns('hash-cf-template'); + cryptoStub.createHash().update().digest.onCall(1).returns('hash-zip-file-1'); const now = new Date(); const inThePast = new Date(new Date().getTime() - 100000); @@ -490,16 +450,8 @@ describe('checkForChanges', () => { it('should set a flag if the remote and local hashes are equal', () => { globbySyncStub.returns(['my-service.zip']); - cryptoStub - .createHash() - .update() - .digest.onCall(0) - .returns('hash-cf-template'); - cryptoStub - .createHash() - .update() - .digest.onCall(1) - .returns('hash-zip-file-1'); + cryptoStub.createHash().update().digest.onCall(0).returns('hash-cf-template'); + cryptoStub.createHash().update().digest.onCall(1).returns('hash-zip-file-1'); const input = [ { Metadata: { filesha256: 'hash-cf-template' } }, @@ -528,16 +480,8 @@ describe('checkForChanges', () => { it('should set a flag if the remote and local hashes are equal, and the edit times are ordered', () => { globbySyncStub.returns(['my-service.zip']); - cryptoStub - .createHash() - .update() - .digest.onCall(0) - .returns('hash-cf-template'); - cryptoStub - .createHash() - .update() - .digest.onCall(1) - .returns('hash-zip-file-1'); + cryptoStub.createHash().update().digest.onCall(0).returns('hash-cf-template'); + cryptoStub.createHash().update().digest.onCall(1).returns('hash-zip-file-1'); const longAgo = new Date(new Date().getTime() - 100000); const longerAgo = new Date(new Date().getTime() - 200000); @@ -571,22 +515,10 @@ describe('checkForChanges', () => { it('should set a flag if the remote and local hashes are duplicated and equal', () => { globbySyncStub.returns(['func1.zip', 'func2.zip']); - cryptoStub - .createHash() - .update() - .digest.onCall(0) - .returns('hash-cf-template'); + cryptoStub.createHash().update().digest.onCall(0).returns('hash-cf-template'); // happens when package.individually is used - cryptoStub - .createHash() - .update() - .digest.onCall(1) - .returns('hash-zip-file-1'); - cryptoStub - .createHash() - .update() - .digest.onCall(2) - .returns('hash-zip-file-1'); + cryptoStub.createHash().update().digest.onCall(1).returns('hash-zip-file-1'); + cryptoStub.createHash().update().digest.onCall(2).returns('hash-zip-file-1'); const input = [ { Metadata: { filesha256: 'hash-cf-template' } }, @@ -623,16 +555,8 @@ describe('checkForChanges', () => { }; globbySyncStub.returns([]); - cryptoStub - .createHash() - .update() - .digest.onCall(0) - .returns('hash-cf-template'); - cryptoStub - .createHash() - .update() - .digest.onCall(1) - .returns('local-my-own-hash'); + cryptoStub.createHash().update().digest.onCall(0).returns('hash-cf-template'); + cryptoStub.createHash().update().digest.onCall(1).returns('local-my-own-hash'); const input = [ { Metadata: { filesha256: 'hash-cf-template' } }, @@ -709,7 +633,7 @@ describe('checkForChanges', () => { sandbox.stub(awsDeploy, 'checkIfDeploymentIsNecessary').callsFake( () => - new Promise(resolve => { + new Promise((resolve) => { awsDeploy.serverless.service.provider.shouldNotDeploy = true; resolve(); }) @@ -920,7 +844,7 @@ describe('checkForChanges', () => { awsDeploy.serverless.service.setFunctionNames(); return expect(awsDeploy.getFunctionsEarliestLastModifiedDate()).to.have.been.fulfilled.then( - ans => { + (ans) => { expect(getFunctionStub).to.have.not.been.called; expect(ans).to.be.null; } @@ -950,7 +874,7 @@ describe('checkForChanges', () => { awsDeploy.serverless.service.setFunctionNames(); return expect(awsDeploy.getFunctionsEarliestLastModifiedDate()).to.have.been.fulfilled.then( - ans => { + (ans) => { expect(ans.valueOf()).to.equal(new Date(0).valueOf()); expect(getFunctionStub).to.have.been.calledTwice; } @@ -991,7 +915,7 @@ describe('checkForChanges', () => { awsDeploy.serverless.service.setFunctionNames(); return expect(awsDeploy.getFunctionsEarliestLastModifiedDate()).to.have.been.fulfilled.then( - ans => { + (ans) => { expect(ans.valueOf()).to.equal(longerAgo.valueOf()); expect(getFunctionStub).to.have.been.calledThrice; } diff --git a/test/unit/lib/plugins/aws/deploy/lib/cleanupS3Bucket.test.js b/test/unit/lib/plugins/aws/deploy/lib/cleanupS3Bucket.test.js index 3549ee3af30..533fac2187d 100644 --- a/test/unit/lib/plugins/aws/deploy/lib/cleanupS3Bucket.test.js +++ b/test/unit/lib/plugins/aws/deploy/lib/cleanupS3Bucket.test.js @@ -74,7 +74,7 @@ describe('cleanupS3Bucket', () => { const listObjectsStub = sinon.stub(awsDeploy.provider, 'request').resolves(serviceObjects); - return awsDeploy.getObjectsToRemove().then(objectsToRemove => { + return awsDeploy.getObjectsToRemove().then((objectsToRemove) => { expect(objectsToRemove).to.not.include({ Key: `${s3Key}${s3Key}/141321321541-2016-08-18T11:23:02/artifact.zip`, }); @@ -122,7 +122,7 @@ describe('cleanupS3Bucket', () => { const listObjectsStub = sinon.stub(awsDeploy.provider, 'request').resolves(serviceObjects); - return awsDeploy.getObjectsToRemove().then(objectsToRemove => { + return awsDeploy.getObjectsToRemove().then((objectsToRemove) => { expect(objectsToRemove.length).to.equal(0); expect(listObjectsStub.calledOnce).to.be.equal(true); expect(listObjectsStub).to.have.been.calledWithExactly('S3', 'listObjectsV2', { @@ -149,7 +149,7 @@ describe('cleanupS3Bucket', () => { const listObjectsStub = sinon.stub(awsDeploy.provider, 'request').resolves(serviceObjects); - return awsDeploy.getObjectsToRemove().then(objectsToRemove => { + return awsDeploy.getObjectsToRemove().then((objectsToRemove) => { expect(objectsToRemove).to.have.lengthOf(0); expect(listObjectsStub).to.have.been.calledOnce; expect(listObjectsStub).to.have.been.calledWithExactly('S3', 'listObjectsV2', { @@ -185,7 +185,7 @@ describe('cleanupS3Bucket', () => { const listObjectsStub = sinon.stub(awsDeploy.provider, 'request').resolves(serviceObjects); - return awsDeploy.getObjectsToRemove().then(objectsToRemove => { + return awsDeploy.getObjectsToRemove().then((objectsToRemove) => { expect(objectsToRemove).to.deep.include.members([ { Key: `${s3Key}/141321321541-2016-08-18T11:23:02/artifact.zip` }, { Key: `${s3Key}/141321321541-2016-08-18T11:23:02/cloudformation.json` }, diff --git a/test/unit/lib/plugins/aws/deploy/lib/createStack.test.js b/test/unit/lib/plugins/aws/deploy/lib/createStack.test.js index 10f3e86222b..41ffe18891d 100644 --- a/test/unit/lib/plugins/aws/deploy/lib/createStack.test.js +++ b/test/unit/lib/plugins/aws/deploy/lib/createStack.test.js @@ -150,7 +150,7 @@ describe('createStack', () => { const createStub = sandbox.stub(awsDeploy, 'create').resolves(); - return awsDeploy.createStack().catch(e => { + return awsDeploy.createStack().catch((e) => { expect(createStub.called).to.be.equal(false); expect(e.name).to.be.equal('ServerlessError'); expect(e.message).to.be.equal(errorMock.message); diff --git a/test/unit/lib/plugins/aws/deploy/lib/existsDeploymentBucket.test.js b/test/unit/lib/plugins/aws/deploy/lib/existsDeploymentBucket.test.js index 701619c7ec7..1a1a69be83c 100644 --- a/test/unit/lib/plugins/aws/deploy/lib/existsDeploymentBucket.test.js +++ b/test/unit/lib/plugins/aws/deploy/lib/existsDeploymentBucket.test.js @@ -44,7 +44,7 @@ describe('#existsDeploymentBucket()', () => { const errorObj = { message: 'Access Denied' }; sinon.stub(awsPlugin.provider, 'request').throws(errorObj); - return expect(awsPlugin.existsDeploymentBucket(bucketName)).to.be.rejected.then(err => { + return expect(awsPlugin.existsDeploymentBucket(bucketName)).to.be.rejected.then((err) => { expect(awsPluginStub.args[0][0]).to.equal('S3'); expect(awsPluginStub.args[0][1]).to.equal('getBucketLocation'); expect(awsPluginStub.args[0][2].Bucket).to.equal(bucketName); @@ -60,7 +60,7 @@ describe('#existsDeploymentBucket()', () => { LocationConstraint: 'us-west-1', }); - return expect(awsPlugin.existsDeploymentBucket(bucketName)).to.be.rejected.then(err => { + return expect(awsPlugin.existsDeploymentBucket(bucketName)).to.be.rejected.then((err) => { expect(awsPluginStub.args[0][0]).to.equal('S3'); expect(awsPluginStub.args[0][1]).to.equal('getBucketLocation'); expect(awsPluginStub.args[0][2].Bucket).to.equal(bucketName); @@ -71,7 +71,7 @@ describe('#existsDeploymentBucket()', () => { [ { region: 'eu-west-1', response: 'EU' }, { region: 'us-east-1', response: '' }, - ].forEach(value => { + ].forEach((value) => { it(`should handle inconsistent getBucketLocation responses for ${value.region} region`, () => { const bucketName = 'com.serverless.deploys'; diff --git a/test/unit/lib/plugins/aws/deploy/lib/uploadArtifacts.test.js b/test/unit/lib/plugins/aws/deploy/lib/uploadArtifacts.test.js index 84b3a436f45..6f836a3d22a 100644 --- a/test/unit/lib/plugins/aws/deploy/lib/uploadArtifacts.test.js +++ b/test/unit/lib/plugins/aws/deploy/lib/uploadArtifacts.test.js @@ -101,11 +101,7 @@ describe('uploadArtifacts', () => { }); it('should upload the CloudFormation file to the S3 bucket', () => { - cryptoStub - .createHash() - .update() - .digest.onCall(0) - .returns('local-hash-cf-template'); + cryptoStub.createHash().update().digest.onCall(0).returns('local-hash-cf-template'); return awsDeploy.uploadCloudFormationFile().then(() => { expect(normalizeCloudFormationTemplateStub).to.have.been.calledOnce; @@ -124,11 +120,7 @@ describe('uploadArtifacts', () => { }); it('should upload the CloudFormation file to a bucket with SSE bucket policy', () => { - cryptoStub - .createHash() - .update() - .digest.onCall(0) - .returns('local-hash-cf-template'); + cryptoStub.createHash().update().digest.onCall(0).returns('local-hash-cf-template'); awsDeploy.serverless.service.provider.deploymentBucketObject = { serverSideEncryption: 'AES256', }; @@ -170,11 +162,7 @@ describe('uploadArtifacts', () => { }); it('should upload the .zip file to the S3 bucket', () => { - cryptoStub - .createHash() - .update() - .digest.onCall(0) - .returns('local-hash-zip-file'); + cryptoStub.createHash().update().digest.onCall(0).returns('local-hash-zip-file'); const tmpDirPath = getTmpDirPath(); const artifactFilePath = path.join(tmpDirPath, 'artifact.zip'); @@ -197,11 +185,7 @@ describe('uploadArtifacts', () => { }); it('should upload the .zip file to a bucket with SSE bucket policy', () => { - cryptoStub - .createHash() - .update() - .digest.onCall(0) - .returns('local-hash-zip-file'); + cryptoStub.createHash().update().digest.onCall(0).returns('local-hash-zip-file'); const tmpDirPath = getTmpDirPath(); const artifactFilePath = path.join(tmpDirPath, 'artifact.zip'); @@ -368,11 +352,7 @@ describe('uploadArtifacts', () => { it('should upload the custom resources .zip file to the S3 bucket', () => { fse.ensureFileSync(customResourcesFilePath); - cryptoStub - .createHash() - .update() - .digest.onCall(0) - .returns('local-hash-zip-file'); + cryptoStub.createHash().update().digest.onCall(0).returns('local-hash-zip-file'); return expect(awsDeploy.uploadCustomResources()).to.eventually.be.fulfilled.then(() => { expect(uploadStub).to.have.been.calledOnce; diff --git a/test/unit/lib/plugins/aws/deploy/lib/validateTemplate.test.js b/test/unit/lib/plugins/aws/deploy/lib/validateTemplate.test.js index 62bca437061..130301c6823 100644 --- a/test/unit/lib/plugins/aws/deploy/lib/validateTemplate.test.js +++ b/test/unit/lib/plugins/aws/deploy/lib/validateTemplate.test.js @@ -65,7 +65,7 @@ describe('validateTemplate', () => { it('should throw an error if the CloudFormation template is invalid', () => { validateTemplateStub.rejects({ message: 'Some error while validating' }); - return expect(awsDeploy.validateTemplate()).to.be.rejected.then(error => { + return expect(awsDeploy.validateTemplate()).to.be.rejected.then((error) => { expect(awsDeploy.serverless.cli.log).to.have.been.called; expect(validateTemplateStub).to.have.been.calledOnce; expect(validateTemplateStub).to.have.been.calledWithExactly( diff --git a/test/unit/lib/plugins/aws/deployFunction.test.js b/test/unit/lib/plugins/aws/deployFunction.test.js index d2bb8844c01..55c293e4293 100644 --- a/test/unit/lib/plugins/aws/deployFunction.test.js +++ b/test/unit/lib/plugins/aws/deployFunction.test.js @@ -452,11 +452,7 @@ describe('AwsDeployFunction', () => { }); it('should deploy the function if the hashes are different', async () => { - cryptoStub - .createHash() - .update() - .digest.onCall(0) - .returns('local-hash-zip-file'); + cryptoStub.createHash().update().digest.onCall(0).returns('local-hash-zip-file'); await awsDeployFunction.deployFunction(); @@ -474,11 +470,7 @@ describe('AwsDeployFunction', () => { it('should deploy the function if the hashes are same but the "force" option is used', async () => { awsDeployFunction.options.force = true; - cryptoStub - .createHash() - .update() - .digest.onCall(0) - .returns('remote-hash-zip-file'); + cryptoStub.createHash().update().digest.onCall(0).returns('remote-hash-zip-file'); await awsDeployFunction.deployFunction(); const data = fs.readFileSync(artifactFilePath); @@ -495,11 +487,7 @@ describe('AwsDeployFunction', () => { }); it('should resolve if the hashes are the same', async () => { - cryptoStub - .createHash() - .update() - .digest.onCall(0) - .returns('remote-hash-zip-file'); + cryptoStub.createHash().update().digest.onCall(0).returns('remote-hash-zip-file'); await awsDeployFunction.deployFunction(); diff --git a/test/unit/lib/plugins/aws/invoke.test.js b/test/unit/lib/plugins/aws/invoke.test.js index 231a6ffdf13..ff51c700346 100644 --- a/test/unit/lib/plugins/aws/invoke.test.js +++ b/test/unit/lib/plugins/aws/invoke.test.js @@ -464,7 +464,7 @@ describe('test/unit/lib/plugins/aws/invoke.test.js', () => { cliArgs: ['invoke', '--function', 'callback', '--context', 'somecontext'], awsRequestStubMap: { Lambda: { - invoke: args => { + invoke: (args) => { lambdaInvokeStub.returns('payload'); return lambdaInvokeStub(args); }, @@ -489,7 +489,7 @@ describe('test/unit/lib/plugins/aws/invoke.test.js', () => { cliArgs: ['invoke', '--function', 'callback', '--raw', '--context', '{"ctx": "somecontext"}'], awsRequestStubMap: { Lambda: { - invoke: args => { + invoke: (args) => { lambdaInvokeStub.returns('payload'); return lambdaInvokeStub(args); }, @@ -524,7 +524,7 @@ describe('test/unit/lib/plugins/aws/invoke.test.js', () => { cliArgs: ['invoke', '--function', 'callback', '--contextPath', contextDataFile], awsRequestStubMap: { Lambda: { - invoke: args => { + invoke: (args) => { lambdaInvokeStub.returns('payload'); return lambdaInvokeStub(args); }, @@ -552,7 +552,7 @@ describe('test/unit/lib/plugins/aws/invoke.test.js', () => { cliArgs: ['invoke', '--function', 'callback', '--contextPath', contextDataFile], awsRequestStubMap: { Lambda: { - invoke: args => { + invoke: (args) => { lambdaInvokeStub.returns('payload'); return lambdaInvokeStub(args); }, diff --git a/test/unit/lib/plugins/aws/invokeLocal/index.test.js b/test/unit/lib/plugins/aws/invokeLocal/index.test.js index 6a30e56d05b..0992f11b392 100644 --- a/test/unit/lib/plugins/aws/invokeLocal/index.test.js +++ b/test/unit/lib/plugins/aws/invokeLocal/index.test.js @@ -442,7 +442,7 @@ describe('AwsInvokeLocal', () => { [ { path: 'handler.hello', expected: 'handler' }, { path: '.build/handler.hello', expected: '.build/handler' }, - ].forEach(item => { + ].forEach((item) => { it(`should call invokeLocalNodeJs for any node.js runtime version for ${item.path}`, async () => { awsInvokeLocal.options.functionObj.handler = item.path; @@ -887,7 +887,7 @@ describe('AwsInvokeLocal', () => { afterEach(afterEachCallback); describe('context.remainingTimeInMillis', () => { - it('should become lower over time', async function() { + it('should become lower over time', async function () { // skipping in CI for now due to handler loading issues // in the Windows machine on Travis CI if (process.env.CI) { @@ -939,7 +939,7 @@ describe('AwsInvokeLocal', () => { afterEach(afterEachCallback); describe('context.remainingTimeInMillis', () => { - it('should become lower over time', async function() { + it('should become lower over time', async function () { awsInvokeLocal.serverless.config.servicePath = tmpServicePath; try { @@ -958,7 +958,7 @@ describe('AwsInvokeLocal', () => { }); describe('calling a class method', () => { - it('should execute', async function() { + it('should execute', async function () { awsInvokeLocal.serverless.config.servicePath = tmpServicePath; try { @@ -980,7 +980,7 @@ describe('AwsInvokeLocal', () => { }); describe('context.deadlineMs', () => { - it('should return deadline', async function() { + it('should return deadline', async function () { awsInvokeLocal.serverless.config.servicePath = tmpServicePath; try { diff --git a/test/unit/lib/plugins/aws/lib/monitorStack.test.js b/test/unit/lib/plugins/aws/lib/monitorStack.test.js index 67b66bb615d..604f23f3134 100644 --- a/test/unit/lib/plugins/aws/lib/monitorStack.test.js +++ b/test/unit/lib/plugins/aws/lib/monitorStack.test.js @@ -71,7 +71,7 @@ describe('monitorStack', () => { describeStackEventsStub.onCall(0).resolves(updateStartEvent); describeStackEventsStub.onCall(1).resolves(updateFinishedEvent); - return awsPlugin.monitorStack('create', cfDataMock, { frequency: 10 }).then(stackStatus => { + return awsPlugin.monitorStack('create', cfDataMock, { frequency: 10 }).then((stackStatus) => { expect(describeStackEventsStub.callCount).to.be.equal(2); expect( describeStackEventsStub.calledWithExactly('CloudFormation', 'describeStackEvents', { @@ -116,7 +116,7 @@ describe('monitorStack', () => { describeStackEventsStub.onCall(0).resolves(updateStartEvent); describeStackEventsStub.onCall(1).resolves(updateFinishedEvent); - return awsPlugin.monitorStack('update', cfDataMock, { frequency: 10 }).then(stackStatus => { + return awsPlugin.monitorStack('update', cfDataMock, { frequency: 10 }).then((stackStatus) => { expect(describeStackEventsStub.callCount).to.be.equal(2); expect( describeStackEventsStub.calledWithExactly('CloudFormation', 'describeStackEvents', { @@ -161,7 +161,7 @@ describe('monitorStack', () => { describeStackEventsStub.onCall(0).resolves(updateStartEvent); describeStackEventsStub.onCall(1).resolves(updateFinishedEvent); - return awsPlugin.monitorStack('delete', cfDataMock, { frequency: 10 }).then(stackStatus => { + return awsPlugin.monitorStack('delete', cfDataMock, { frequency: 10 }).then((stackStatus) => { expect(describeStackEventsStub.callCount).to.be.equal(2); expect( describeStackEventsStub.calledWithExactly('CloudFormation', 'describeStackEvents', { @@ -219,7 +219,7 @@ describe('monitorStack', () => { describeStackEventsStub.onCall(1).resolves(nestedStackEvent); describeStackEventsStub.onCall(2).resolves(updateFinishedEvent); - return awsPlugin.monitorStack('create', cfDataMock, { frequency: 10 }).then(stackStatus => { + return awsPlugin.monitorStack('create', cfDataMock, { frequency: 10 }).then((stackStatus) => { expect(describeStackEventsStub.callCount).to.be.equal(3); expect( describeStackEventsStub.calledWithExactly('CloudFormation', 'describeStackEvents', { @@ -277,7 +277,7 @@ describe('monitorStack', () => { describeStackEventsStub.onCall(1).resolves(nestedStackEvent); describeStackEventsStub.onCall(2).resolves(updateFinishedEvent); - return awsPlugin.monitorStack('update', cfDataMock, { frequency: 10 }).then(stackStatus => { + return awsPlugin.monitorStack('update', cfDataMock, { frequency: 10 }).then((stackStatus) => { expect(describeStackEventsStub.callCount).to.be.equal(3); expect( describeStackEventsStub.calledWithExactly('CloudFormation', 'describeStackEvents', { @@ -335,7 +335,7 @@ describe('monitorStack', () => { describeStackEventsStub.onCall(1).resolves(nestedStackEvent); describeStackEventsStub.onCall(2).resolves(updateFinishedEvent); - return awsPlugin.monitorStack('delete', cfDataMock, { frequency: 10 }).then(stackStatus => { + return awsPlugin.monitorStack('delete', cfDataMock, { frequency: 10 }).then((stackStatus) => { expect(describeStackEventsStub.callCount).to.be.equal(3); expect( describeStackEventsStub.calledWithExactly('CloudFormation', 'describeStackEvents', { @@ -371,7 +371,7 @@ describe('monitorStack', () => { describeStackEventsStub.onCall(0).resolves(updateStartEvent); describeStackEventsStub.onCall(1).rejects(stackNotFoundError); - return awsPlugin.monitorStack('delete', cfDataMock, { frequency: 10 }).then(stackStatus => { + return awsPlugin.monitorStack('delete', cfDataMock, { frequency: 10 }).then((stackStatus) => { expect(describeStackEventsStub.callCount).to.be.equal(2); expect( describeStackEventsStub.calledWithExactly('CloudFormation', 'describeStackEvents', { @@ -443,7 +443,7 @@ describe('monitorStack', () => { describeStackEventsStub.onCall(2).resolves(updateRollbackEvent); describeStackEventsStub.onCall(3).resolves(updateRollbackComplete); - return awsPlugin.monitorStack('update', cfDataMock, { frequency: 10 }).catch(e => { + return awsPlugin.monitorStack('update', cfDataMock, { frequency: 10 }).catch((e) => { let errorMessage = 'An error occurred: '; errorMessage += 'mochaS3 - Bucket already exists.'; if (e.name !== 'ServerlessError') throw e; @@ -525,7 +525,7 @@ describe('monitorStack', () => { describeStackEventsStub.onCall(0).rejects(failedDescribeStackEvents); - return awsPlugin.monitorStack('update', cfDataMock, { frequency: 10 }).catch(e => { + return awsPlugin.monitorStack('update', cfDataMock, { frequency: 10 }).catch((e) => { expect(e.message).to.be.equal('Something went wrong.'); expect(describeStackEventsStub.callCount).to.be.equal(1); expect( @@ -593,7 +593,7 @@ describe('monitorStack', () => { describeStackEventsStub.onCall(2).resolves(updateRollbackEvent); describeStackEventsStub.onCall(3).resolves(updateRollbackFailedEvent); - return awsPlugin.monitorStack('update', cfDataMock, { frequency: 10 }).catch(e => { + return awsPlugin.monitorStack('update', cfDataMock, { frequency: 10 }).catch((e) => { let errorMessage = 'An error occurred: '; errorMessage += 'mochaS3 - Bucket already exists.'; expect(e.name).to.be.equal('ServerlessError'); @@ -669,7 +669,7 @@ describe('monitorStack', () => { describeStackEventsStub.onCall(2).resolves(deleteItemFailedEvent); describeStackEventsStub.onCall(3).resolves(deleteFailedEvent); - return awsPlugin.monitorStack('delete', cfDataMock, { frequency: 10 }).catch(e => { + return awsPlugin.monitorStack('delete', cfDataMock, { frequency: 10 }).catch((e) => { let errorMessage = 'An error occurred: '; errorMessage += 'mochaLambda - You are not authorized to perform this operation.'; expect(e.name).to.be.equal('ServerlessError'); @@ -749,7 +749,7 @@ describe('monitorStack', () => { describeStackEventsStub.onCall(2).resolves(deleteItemFailedEvent); describeStackEventsStub.onCall(3).resolves(deleteFailedEvent); - return awsPlugin.monitorStack('delete', cfDataMock, { frequency: 10 }).catch(e => { + return awsPlugin.monitorStack('delete', cfDataMock, { frequency: 10 }).catch((e) => { let errorMessage = 'An error occurred: '; errorMessage += 'mochaLambda - You are not authorized to perform this operation.'; expect(e.name).to.be.equal('ServerlessError'); @@ -941,7 +941,7 @@ describe('monitorStack', () => { describeStackEventsStub.onCall(1).resolves(updateRollbackEvent); describeStackEventsStub.onCall(2).resolves(updateRollbackCompleteEvent); - return awsPlugin.monitorStack('update', cfDataMock, { frequency: 10 }).catch(e => { + return awsPlugin.monitorStack('update', cfDataMock, { frequency: 10 }).catch((e) => { let errorMessage = 'An error occurred: '; errorMessage += 'mocha - Export is in use.'; expect(e.name).to.be.equal('ServerlessError'); diff --git a/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/apiKeys.test.js b/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/apiKeys.test.js index ee9b72b8bf2..0ffb156b95a 100644 --- a/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/apiKeys.test.js +++ b/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/apiKeys.test.js @@ -178,7 +178,7 @@ describe('#compileApiKeys()', () => { { name: 'jihgfedcba', value: undefined, description: undefined }, ], }; - awsCompileApigEvents.serverless.service.provider.apiGateway.apiKeys.forEach(plan => { + awsCompileApigEvents.serverless.service.provider.apiGateway.apiKeys.forEach((plan) => { const planName = Object.keys(plan)[0]; // free || paid const apiKeys = expectedApiKeys[planName]; apiKeys.forEach((apiKey, index) => { diff --git a/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/hack/updateStage.test.js b/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/hack/updateStage.test.js index de75b687d81..641a5857b73 100644 --- a/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/hack/updateStage.test.js +++ b/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/hack/updateStage.test.js @@ -676,7 +676,7 @@ describe('#updateStage()', () => { return checkLogLevel(null, defaultApiGatewayLogLevel); }); - ['INFO', 'ERROR'].forEach(logLevel => { + ['INFO', 'ERROR'].forEach((logLevel) => { it(`should update the stage with a custom APIGW log level if given ${logLevel}`, () => { return checkLogLevel(logLevel, logLevel); }); diff --git a/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/resources.test.js b/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/resources.test.js index a5f671f4610..44a677c64a1 100644 --- a/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/resources.test.js +++ b/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/resources.test.js @@ -171,7 +171,7 @@ describe('#compileResources()', () => { 'foo/{foo_id}': 'ApiGatewayResourceFooFooidVar', 'foo/{foo_id}/bar': 'ApiGatewayResourceFooFooidVarBar', }; - Object.keys(expectedResourceLogicalIds).forEach(path => { + Object.keys(expectedResourceLogicalIds).forEach((path) => { expect(awsCompileApigEvents.apiGatewayResources[path].resourceLogicalId).equal( expectedResourceLogicalIds[path] ); @@ -200,7 +200,7 @@ describe('#compileResources()', () => { 'foo/bar': 'ApiGatewayResourceFooBar', 'foo/{bar}': 'ApiGatewayResourceFooBarVar', }; - Object.keys(expectedResourceLogicalIds).forEach(path => { + Object.keys(expectedResourceLogicalIds).forEach((path) => { expect(awsCompileApigEvents.apiGatewayResources[path].resourceLogicalId).equal( expectedResourceLogicalIds[path] ); @@ -511,7 +511,7 @@ describe('#compileResources()', () => { Object.keys( awsCompileApigEvents.serverless.service.provider.compiledCloudFormationTemplate.Resources ).every( - k => ['ApiGatewayMethodundefinedGet', 'ApiGatewayMethodundefinedPost'].indexOf(k) === -1 + (k) => ['ApiGatewayMethodundefinedGet', 'ApiGatewayMethodundefinedPost'].indexOf(k) === -1 ) ).to.equal(true); }); diff --git a/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/usagePlanKeys.test.js b/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/usagePlanKeys.test.js index 5be4b3710cb..43ed57e6b1a 100644 --- a/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/usagePlanKeys.test.js +++ b/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/usagePlanKeys.test.js @@ -98,7 +98,7 @@ describe('#compileUsagePlanKeys()', () => { }; return awsCompileApigEvents.compileUsagePlanKeys().then(() => { - awsCompileApigEvents.serverless.service.provider.apiGateway.apiKeys.forEach(plan => { + awsCompileApigEvents.serverless.service.provider.apiGateway.apiKeys.forEach((plan) => { const planName = Object.keys(plan)[0]; // free || paid const apiKeys = plan[planName]; apiKeys.forEach((apiKey, index) => { diff --git a/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/validate.test.js b/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/validate.test.js index 60cc5ccbd72..d4525c5c72a 100644 --- a/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/validate.test.js +++ b/test/unit/lib/plugins/aws/package/compile/events/apiGateway/lib/validate.test.js @@ -31,9 +31,7 @@ describe('#validate()', () => { }, }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(0); + expect(validated.events).to.be.an('Array').with.length(0); }); it('should reject an invalid http event', () => { @@ -72,9 +70,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); }); it('should discard a starting slash from paths', () => { @@ -94,9 +90,7 @@ describe('#validate()', () => { }, }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(2); + expect(validated.events).to.be.an('Array').with.length(2); expect(validated.events[0].http).to.have.property('path', 'foo/bar'); expect(validated.events[1].http).to.have.property('path', 'foo/bar'); }); @@ -266,9 +260,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(2); + expect(validated.events).to.be.an('Array').with.length(2); expect(validated.events[0].http.authorizer.type).to.equal('AWS_IAM'); expect(validated.events[1].http.authorizer.type).to.equal('AWS_IAM'); }); @@ -301,9 +293,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(2); + expect(validated.events).to.be.an('Array').with.length(2); expect(validated.events[0].http.authorizer.name).to.equal('foo'); expect(validated.events[0].http.authorizer.arn).to.deep.equal({ 'Fn::GetAtt': ['FooLambdaFunction', 'Arn'], @@ -437,9 +427,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.cors).to.deep.equal({ headers: [ 'Content-Type', @@ -473,9 +461,7 @@ describe('#validate()', () => { }, }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.cors.headers).to.deep.equal(['X-Foo-Bar']); }); @@ -501,9 +487,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.cors).to.deep.equal({ headers: ['X-Foo-Bar'], methods: ['POST', 'OPTIONS'], @@ -611,9 +595,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.response.statusCodes).to.deep.equal({ 200: { pattern: '', @@ -652,9 +634,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.response.statusCodes).to.deep.equal({ 418: { pattern: '', @@ -681,9 +661,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.cors.methods).to.deep.equal(['POST', 'OPTIONS']); }); @@ -704,9 +682,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.authorizer.name).to.equal('authorizer'); expect(validated.events[0].http.authorizer.arn).to.deep.equal({ 'Fn::GetAtt': ['AuthorizerLambdaFunction', 'Arn'], @@ -729,9 +705,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.authorizer.name).to.equal('authorizer'); expect(validated.events[0].http.authorizer.arn).to.equal('xxx:dev-authorizer'); }); @@ -755,9 +729,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.authorizer.name).to.equal('authorizer'); expect(validated.events[0].http.authorizer.arn).to.deep.equal({ 'Fn::GetAtt': ['AuthorizerLambdaFunction', 'Arn'], @@ -782,9 +754,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.authorizer.name).to.equal('authorizer'); expect(validated.events[0].http.authorizer.arn).to.equal('xxx:dev-authorizer'); }); @@ -808,9 +778,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.authorizer.name).to.equal('custom-name'); expect(validated.events[0].http.authorizer.arn).to.equal('xxx:dev-authorizer'); }); @@ -847,9 +815,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.request.parameters).to.deep.equal({ 'method.request.querystring.foo': true, 'method.request.querystring.bar': false, @@ -892,9 +858,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.request.parameters).to.deep.equal({ 'method.request.querystring.foo': true, 'method.request.querystring.bar': false, @@ -936,9 +900,7 @@ describe('#validate()', () => { }, }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.integration).to.equal('AWS_PROXY'); }); @@ -986,9 +948,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(5); + expect(validated.events).to.be.an('Array').with.length(5); expect(validated.events[0].http.integration).to.equal('AWS'); expect(validated.events[1].http.integration).to.equal('AWS'); expect(validated.events[2].http.integration).to.equal('AWS_PROXY'); @@ -1015,9 +975,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.integration).to.equal('HTTP'); }); @@ -1054,9 +1012,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.request.parameters).to.deep.equal({ 'method.request.querystring.foo': true, 'method.request.querystring.bar': false, @@ -1104,9 +1060,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.integration).to.equal('HTTP_PROXY'); }); @@ -1143,9 +1097,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.request.parameters).to.deep.equal({ 'method.request.querystring.foo': true, 'method.request.querystring.bar': false, @@ -1282,9 +1234,7 @@ describe('#validate()', () => { sinon.stub(serverless.cli, 'log'); const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.response).to.equal(undefined); expect(validated.events[0].http.request.uri).to.equal('http://www.example.com'); expect(validated.events[0].http.request.parameters).to.deep.equal({ @@ -1309,9 +1259,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.integration).to.equal('MOCK'); }); @@ -1331,9 +1279,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.integration).to.equal('AWS'); expect(validated.events[0].http.async); }); @@ -1443,9 +1389,7 @@ describe('#validate()', () => { sinon.stub(serverless.cli, 'log'); const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.response).to.equal(undefined); expect(validated.events[0].http.request.parameters).to.deep.equal({ 'method.request.path.foo': true, @@ -1472,9 +1416,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.request.passThrough).to.equal('WHEN_NO_MATCH'); }); @@ -1494,9 +1436,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.request.passThrough).to.equal('NEVER'); }); @@ -1520,9 +1460,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.request.passThrough).to.equal(undefined); }); @@ -1547,9 +1485,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.integration).to.equal('HTTP_PROXY'); expect(validated.events[0].http.connectionType).to.equal('VPC_LINK'); }); @@ -1619,9 +1555,7 @@ describe('#validate()', () => { }; const validated = awsCompileApigEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(1); + expect(validated.events).to.be.an('Array').with.length(1); expect(validated.events[0].http.response.statusCodes).to.deep.equal({ 200: { pattern: '', diff --git a/test/unit/lib/plugins/aws/package/compile/events/cloudFront.test.js b/test/unit/lib/plugins/aws/package/compile/events/cloudFront.test.js index 02143bd5844..5a0d3623a53 100644 --- a/test/unit/lib/plugins/aws/package/compile/events/cloudFront.test.js +++ b/test/unit/lib/plugins/aws/package/compile/events/cloudFront.test.js @@ -1865,9 +1865,9 @@ describe('lib/plugins/aws/package/compile/events/cloudFront/index.new.test.js', }, }; - const getAssociatedCacheBehavior = pathPattern => + const getAssociatedCacheBehavior = (pathPattern) => cfResources.CloudFrontDistribution.Properties.DistributionConfig.CacheBehaviors.find( - cacheBehavior => cacheBehavior.PathPattern === pathPattern + (cacheBehavior) => cacheBehavior.PathPattern === pathPattern ); before(async () => { diff --git a/test/unit/lib/plugins/aws/package/compile/events/s3/index.test.js b/test/unit/lib/plugins/aws/package/compile/events/s3/index.test.js index 1ce05f29037..baf3621c934 100644 --- a/test/unit/lib/plugins/aws/package/compile/events/s3/index.test.js +++ b/test/unit/lib/plugins/aws/package/compile/events/s3/index.test.js @@ -859,7 +859,7 @@ describe('AwsCompileS3Events', () => { const lambdaPermissionsPolicies = cfTemplate.Resources.IamRoleCustomResourcesLambdaExecution.Properties.Policies[ '0' - ].PolicyDocument.Statement.filter(x => x.Action[0].includes('AddPermission')); + ].PolicyDocument.Statement.filter((x) => x.Action[0].includes('AddPermission')); expect(lambdaPermissionsPolicies).to.have.length(1); diff --git a/test/unit/lib/plugins/aws/package/compile/events/websockets/lib/validate.test.js b/test/unit/lib/plugins/aws/package/compile/events/websockets/lib/validate.test.js index 520b241ebd6..635b557240b 100644 --- a/test/unit/lib/plugins/aws/package/compile/events/websockets/lib/validate.test.js +++ b/test/unit/lib/plugins/aws/package/compile/events/websockets/lib/validate.test.js @@ -264,9 +264,7 @@ describe('#validate()', () => { }, }; const validated = awsCompileWebsocketsEvents.validate(); - expect(validated.events) - .to.be.an('Array') - .with.length(0); + expect(validated.events).to.be.an('Array').with.length(0); }); }); diff --git a/test/unit/lib/plugins/aws/package/compile/functions.test.js b/test/unit/lib/plugins/aws/package/compile/functions.test.js index c73cca9a33d..99218878559 100644 --- a/test/unit/lib/plugins/aws/package/compile/functions.test.js +++ b/test/unit/lib/plugins/aws/package/compile/functions.test.js @@ -1801,7 +1801,7 @@ describe('lib/plugins/aws/package/compile/functions/index.test.js', () => { const functionCfLogicalId = awsNaming.getLambdaLogicalId('foo'); const originalVersionCfConfig = Object.values(originalTemplate.Resources).find( - resource => + (resource) => resource.Type === 'AWS::Lambda::Version' && resource.Properties.FunctionName.Ref === functionCfLogicalId ).Properties; @@ -1816,7 +1816,7 @@ describe('lib/plugins/aws/package/compile/functions/index.test.js', () => { cliArgs: ['package'], }); const updatedVersionCfConfig = Object.values(updatedTemplate.Resources).find( - resource => + (resource) => resource.Type === 'AWS::Lambda::Version' && resource.Properties.FunctionName.Ref === functionCfLogicalId ).Properties; @@ -2199,7 +2199,7 @@ describe('lib/plugins/aws/package/compile/functions/index.test.js', () => { expect(imageDigest).to.match(/^sha256:[a-f0-9]{64}$/); const imageDigestSha = imageDigest.slice('sha256:'.length); const versionCfConfig = Object.values(cfResources).find( - resource => + (resource) => resource.Type === 'AWS::Lambda::Version' && resource.Properties.FunctionName.Ref === functionCfLogicalId ).Properties; @@ -2218,7 +2218,7 @@ describe('lib/plugins/aws/package/compile/functions/index.test.js', () => { expect(functionCfConfig).to.not.have.property('Runtime'); const versionCfConfig = Object.values(cfResources).find( - resource => + (resource) => resource.Type === 'AWS::Lambda::Version' && resource.Properties.FunctionName.Ref === functionCfLogicalId ).Properties; @@ -2242,14 +2242,14 @@ describe('lib/plugins/aws/package/compile/functions/index.test.js', () => { }, }, cliArgs: ['package'], - }).catch(error => { + }).catch((error) => { expect(error).to.have.property('code', 'LAMBDA_FILE_SYSTEM_CONFIG_MISSING_VPC'); }); }); }); describe('Version hash resolution', () => { - const testLambdaHashingVersion = lambdaHashingVersion => { + const testLambdaHashingVersion = (lambdaHashingVersion) => { const configExt = lambdaHashingVersion ? { provider: { lambdaHashingVersion } } : {}; it.skip('TODO: should create a different version if configuration changed', () => { diff --git a/test/unit/lib/plugins/aws/package/compile/layers.test.js b/test/unit/lib/plugins/aws/package/compile/layers.test.js index aa3e55f12d2..f71f262e0d4 100644 --- a/test/unit/lib/plugins/aws/package/compile/layers.test.js +++ b/test/unit/lib/plugins/aws/package/compile/layers.test.js @@ -362,7 +362,7 @@ describe('lib/plugins/aws/package/compile/layers/index.test.js', () => { describe('`layers[].retain` property', () => { it('should ensure expected deletion policy for layer resource', () => { const layerResourceNamePrefix = naming.getLambdaLayerLogicalId('layerRetain'); - const layerResourceName = Object.keys(cfResources).find(resourceName => + const layerResourceName = Object.keys(cfResources).find((resourceName) => resourceName.startsWith(layerResourceNamePrefix) ); expect(layerResourceName).to.not.equal(layerResourceNamePrefix); @@ -375,7 +375,7 @@ describe('lib/plugins/aws/package/compile/layers/index.test.js', () => { 'layerRetain', allowedAccount ); - const layerPermissionResourceName = Object.keys(cfResources).find(resourceName => + const layerPermissionResourceName = Object.keys(cfResources).find((resourceName) => resourceName.startsWith(layerPermissionResourceNamePrefix) ); expect(layerPermissionResourceName).to.not.equal(layerPermissionResourceNamePrefix); @@ -385,7 +385,7 @@ describe('lib/plugins/aws/package/compile/layers/index.test.js', () => { it('should ensure unique resource id per layer version', async () => { const layerResourceNamePrefix = naming.getLambdaLayerLogicalId('layerRetain'); - const firstLayerResourceName = Object.keys(cfResources).find(resourceName => + const firstLayerResourceName = Object.keys(cfResources).find((resourceName) => resourceName.startsWith(layerResourceNamePrefix) ); diff --git a/test/unit/lib/plugins/aws/provider.test.js b/test/unit/lib/plugins/aws/provider.test.js index d87299707df..e67c3ad446b 100644 --- a/test/unit/lib/plugins/aws/provider.test.js +++ b/test/unit/lib/plugins/aws/provider.test.js @@ -85,7 +85,7 @@ describe('AwsProvider', () => { describe('stage name validation', () => { const stages = ['myStage', 'my-stage', 'my_stage', "${opt:stage, 'prod'}"]; - stages.forEach(stage => { + stages.forEach((stage) => { it(`should not throw an error before variable population even if http event is present and stage is ${stage}`, () => { const config = { @@ -228,7 +228,7 @@ describe('AwsProvider', () => { putObject() { return { - send: cb => cb(null, { called: true }), + send: (cb) => cb(null, { called: true }), }; } } @@ -247,7 +247,7 @@ describe('AwsProvider', () => { }, }; - return awsProvider.request('S3', 'putObject', {}).then(data => { + return awsProvider.request('S3', 'putObject', {}).then((data) => { expect(data.called).to.equal(true); }); }); @@ -260,7 +260,7 @@ describe('AwsProvider', () => { put() { return { - send: cb => cb(null, { called: true }), + send: (cb) => cb(null, { called: true }), }; } } @@ -282,7 +282,7 @@ describe('AwsProvider', () => { }, }; - return awsProvider.request('DynamoDB.DocumentClient', 'put', {}).then(data => { + return awsProvider.request('DynamoDB.DocumentClient', 'put', {}).then((data) => { expect(data.called).to.equal(true); }); }); @@ -315,7 +315,7 @@ describe('AwsProvider', () => { }, }; - return awsProvider.request('APIGateway', 'getRestApis', {}).then(data => { + return awsProvider.request('APIGateway', 'getRestApis', {}).then((data) => { expect(data.called).to.equal(true); }); }); @@ -329,7 +329,7 @@ describe('AwsProvider', () => { describeStacks() { return { - send: cb => + send: (cb) => cb(null, { region: this.config.region, }), @@ -358,12 +358,12 @@ describe('AwsProvider', () => { { StackName: 'foo' }, { region: 'ap-northeast-1' } ) - .then(data => { + .then((data) => { expect(data).to.eql({ region: 'ap-northeast-1' }); }); }); - it('should retry if error code is 429', done => { + it('should retry if error code is 429', (done) => { const error = { statusCode: 429, retryable: true, @@ -388,7 +388,7 @@ describe('AwsProvider', () => { }; awsProvider .request('S3', 'error', {}) - .then(data => { + .then((data) => { expect(data).to.exist; expect(sendFake.send).to.have.been.calledTwice; done(); @@ -396,7 +396,7 @@ describe('AwsProvider', () => { .catch(done); }); - it('should retry if error code is 429 and retryable is set to false', done => { + it('should retry if error code is 429 and retryable is set to false', (done) => { const error = { statusCode: 429, retryable: false, @@ -421,7 +421,7 @@ describe('AwsProvider', () => { }; awsProvider .request('S3', 'error', {}) - .then(data => { + .then((data) => { expect(data).to.exist; expect(sendFake.send).to.have.been.calledTwice; done(); @@ -429,7 +429,7 @@ describe('AwsProvider', () => { .catch(done); }); - it('should not retry if error code is 403 and retryable is set to true', done => { + it('should not retry if error code is 403 and retryable is set to true', (done) => { const error = { statusCode: 403, retryable: true, @@ -461,7 +461,7 @@ describe('AwsProvider', () => { }); }); - it('should reject errors', done => { + it('should reject errors', (done) => { const error = { statusCode: 500, message: 'Some error message', @@ -488,7 +488,7 @@ describe('AwsProvider', () => { .catch(() => done()); }); - it('should use error message if it exists', done => { + it('should use error message if it exists', (done) => { const awsErrorResponse = { message: 'Something went wrong...', code: 'Forbidden', @@ -520,14 +520,14 @@ describe('AwsProvider', () => { awsProvider .request('S3', 'error', {}) .then(() => done('Should not succeed')) - .catch(err => { + .catch((err) => { expect(err.message).to.eql(awsErrorResponse.message); done(); }) .catch(done); }); - it('should default to error code if error message is non-existent', done => { + it('should default to error code if error message is non-existent', (done) => { const awsErrorResponse = { message: null, code: 'Forbidden', @@ -559,14 +559,14 @@ describe('AwsProvider', () => { awsProvider .request('S3', 'error', {}) .then(() => done('Should not succeed')) - .catch(err => { + .catch((err) => { expect(err.message).to.eql(awsErrorResponse.code); done(); }) .catch(done); }); - it('should return ref to docs for missing credentials', done => { + it('should return ref to docs for missing credentials', (done) => { const error = { statusCode: 403, message: 'Missing credentials in config', @@ -591,14 +591,14 @@ describe('AwsProvider', () => { awsProvider .request('S3', 'error', {}) .then(() => done('Should not succeed')) - .catch(err => { + .catch((err) => { expect(err.message).to.contain('in our docs here:'); done(); }) .catch(done); }); - it('should not retry for missing credentials', done => { + it('should not retry for missing credentials', (done) => { const error = { statusCode: 403, message: 'Missing credentials in config', @@ -622,7 +622,7 @@ describe('AwsProvider', () => { awsProvider .request('S3', 'error', {}) .then(() => done('Should not succeed')) - .catch(err => { + .catch((err) => { expect(sendFake.send).to.have.been.calledOnce; expect(err.message).to.contain('in our docs here:'); done(); @@ -639,7 +639,7 @@ describe('AwsProvider', () => { putObject() { return { - send: cb => cb(null, { called: true }), + send: (cb) => cb(null, { called: true }), }; } } @@ -678,7 +678,7 @@ describe('AwsProvider', () => { describeStacks() { return { - send: cb => cb(null, { called: true }), + send: (cb) => cb(null, { called: true }), }; } } @@ -699,7 +699,7 @@ describe('AwsProvider', () => { return awsProvider .request('CloudFormation', 'describeStacks', {}, { useCache: true }) - .then(data => { + .then((data) => { expect(data.called).to.equal(true); }); }); @@ -722,7 +722,7 @@ describe('AwsProvider', () => { awsProvider.sdk = { CloudFormation: FakeCF, }; - const executeRequestWithRegion = region => + const executeRequestWithRegion = (region) => awsProvider.request( 'CloudFormation', 'describeStacks', @@ -737,9 +737,9 @@ describe('AwsProvider', () => { requests.push(BbPromise.try(() => executeRequestWithRegion('ap-northeast-1'))); return BbPromise.all(requests) - .then(results => { + .then((results) => { expect(Object.keys(results).length).to.equal(2); - results.forEach(result => { + results.forEach((result) => { expect(result).to.deep.equal(expectedResult); }); return expect(sendStub.callCount).to.equal(2); @@ -789,9 +789,9 @@ describe('AwsProvider', () => { } return BbPromise.all(requests) - .then(results => { + .then((results) => { expect(Object.keys(results).length).to.equal(numTests); - results.forEach(result => { + results.forEach((result) => { expect(result).to.deep.equal(expectedResult); }); return BbPromise.join( @@ -849,7 +849,7 @@ describe('AwsProvider', () => { describeStacks() { return { - send: cb => cb(null, {}), + send: (cb) => cb(null, {}), }; } } @@ -1295,7 +1295,7 @@ describe('AwsProvider', () => { }, }); - return awsProvider.getServerlessDeploymentBucketName().then(bucketName => { + return awsProvider.getServerlessDeploymentBucketName().then((bucketName) => { expect(bucketName).to.equal('serverlessDeploymentBucketName'); expect(describeStackResourcesStub.calledOnce).to.be.equal(true); expect( @@ -1317,7 +1317,7 @@ describe('AwsProvider', () => { }, }); - return awsProvider.getServerlessDeploymentBucketName().then(bucketName => { + return awsProvider.getServerlessDeploymentBucketName().then((bucketName) => { expect(describeStackResourcesStub.called).to.be.equal(false); expect(bucketName).to.equal('custom-bucket'); awsProvider.request.restore(); @@ -1437,7 +1437,7 @@ describe('AwsProvider', () => { Arn: 'arn:aws:sts::123456789012:assumed-role/ROLE-NAME/VWXYZ', }); - return awsProvider.getAccountInfo().then(result => { + return awsProvider.getAccountInfo().then((result) => { expect(stsGetCallerIdentityStub.calledOnce).to.equal(true); expect(result.accountId).to.equal(accountId); expect(result.partition).to.equal(partition); @@ -1457,7 +1457,7 @@ describe('AwsProvider', () => { Arn: 'arn:aws:sts::123456789012:assumed-role/ROLE-NAME/VWXYZ', }); - return awsProvider.getAccountId().then(result => { + return awsProvider.getAccountId().then((result) => { expect(stsGetCallerIdentityStub.calledOnce).to.equal(true); expect(result).to.equal(accountId); awsProvider.request.restore(); diff --git a/test/unit/lib/plugins/aws/remove/lib/bucket.test.js b/test/unit/lib/plugins/aws/remove/lib/bucket.test.js index e40215a9f9c..8ad896b7939 100644 --- a/test/unit/lib/plugins/aws/remove/lib/bucket.test.js +++ b/test/unit/lib/plugins/aws/remove/lib/bucket.test.js @@ -100,7 +100,7 @@ describe('emptyS3Bucket', () => { }); }); - it('should resolve if objectsInBucket is empty', done => { + it('should resolve if objectsInBucket is empty', (done) => { awsRemove.objectsInBucket = []; awsRemove.deleteObjects().then(() => { diff --git a/test/unit/lib/plugins/aws/rollback.test.js b/test/unit/lib/plugins/aws/rollback.test.js index 461db672893..146d5bb72e4 100644 --- a/test/unit/lib/plugins/aws/rollback.test.js +++ b/test/unit/lib/plugins/aws/rollback.test.js @@ -14,7 +14,7 @@ describe('AwsRollback', () => { let serverless; let provider; - const createInstance = options => { + const createInstance = (options) => { serverless = new Serverless(); provider = new AwsProvider(serverless, options); serverless.setProvider('aws', provider); @@ -124,7 +124,7 @@ describe('AwsRollback', () => { .then(() => { assert.isNotOk(true, 'setStackToUpdate should not resolve'); }) - .catch(errorMessage => { + .catch((errorMessage) => { expect(errorMessage).to.include("Couldn't find any existing deployments"); expect(listObjectsStub.calledOnce).to.be.equal(true); expect( @@ -159,7 +159,7 @@ describe('AwsRollback', () => { .then(() => { assert.isNotOk(true, 'setStackToUpdate should not resolve'); }) - .catch(errorMessage => { + .catch((errorMessage) => { expect(errorMessage).to.include("Couldn't find a deployment for the timestamp"); expect(listObjectsStub.calledOnce).to.be.equal(true); expect( diff --git a/test/unit/lib/plugins/aws/rollbackFunction.test.js b/test/unit/lib/plugins/aws/rollbackFunction.test.js index 039dd05010a..101d67afaa7 100644 --- a/test/unit/lib/plugins/aws/rollbackFunction.test.js +++ b/test/unit/lib/plugins/aws/rollbackFunction.test.js @@ -103,7 +103,7 @@ describe('AwsRollbackFunction', () => { awsRollbackFunction.options.function = 'hello'; awsRollbackFunction.options['function-version'] = '4711'; - return awsRollbackFunction.getFunctionToBeRestored().then(result => { + return awsRollbackFunction.getFunctionToBeRestored().then((result) => { expect(getFunctionStub.calledOnce).to.equal(true); expect( getFunctionStub.calledWithExactly('Lambda', 'getFunction', { @@ -134,7 +134,7 @@ describe('AwsRollbackFunction', () => { awsRollbackFunction.options.function = 'hello'; awsRollbackFunction.options['function-version'] = '4711'; - return awsRollbackFunction.getFunctionToBeRestored().catch(error => { + return awsRollbackFunction.getFunctionToBeRestored().catch((error) => { expect(error.message.match(/Function "hello" with version "4711" not found/)); expect(getFunctionStub.calledOnce).to.equal(true); expect( @@ -165,7 +165,7 @@ describe('AwsRollbackFunction', () => { awsRollbackFunction.options.function = 'hello'; awsRollbackFunction.options['function-version'] = '4711'; - return awsRollbackFunction.getFunctionToBeRestored().catch(error => { + return awsRollbackFunction.getFunctionToBeRestored().catch((error) => { expect(error.message.match(/something went wrong/)); expect(getFunctionStub.calledOnce).to.equal(true); expect( diff --git a/test/unit/lib/plugins/aws/utils/credentials.test.js b/test/unit/lib/plugins/aws/utils/credentials.test.js index b7e56a763de..4d5af13824b 100644 --- a/test/unit/lib/plugins/aws/utils/credentials.test.js +++ b/test/unit/lib/plugins/aws/utils/credentials.test.js @@ -19,7 +19,7 @@ describe('#credentials', () => { () => { throw new Error('Unexpected ~/.aws directory, related tests aborted'); }, - error => { + (error) => { if (error.code === 'ENOENT') return; throw error; } @@ -58,14 +58,14 @@ describe('#credentials', () => { ].join('\n')}\n`; return new BbPromise((resolve, reject) => { - outputFile(credentialsFilePath, credentialsFileContent, error => { + outputFile(credentialsFilePath, credentialsFileContent, (error) => { if (error) reject(error); else resolve(); }); }).then(() => credentials .resolveFileProfiles() - .then(resolvedProfiles => expect(resolvedProfiles).to.deep.equal(profiles)) + .then((resolvedProfiles) => expect(resolvedProfiles).to.deep.equal(profiles)) ); }); @@ -102,7 +102,7 @@ describe('#credentials', () => { .then(() => credentials .resolveFileProfiles() - .then(resolvedProfiles => expect(resolvedProfiles).to.deep.equal(profiles)) + .then((resolvedProfiles) => expect(resolvedProfiles).to.deep.equal(profiles)) ); }); }); diff --git a/test/unit/lib/plugins/aws/utils/findReferences.test.js b/test/unit/lib/plugins/aws/utils/findReferences.test.js index 4f4373a35de..00d79d061cb 100644 --- a/test/unit/lib/plugins/aws/utils/findReferences.test.js +++ b/test/unit/lib/plugins/aws/utils/findReferences.test.js @@ -8,12 +8,8 @@ describe('#findReferences()', () => { const withoutArgs = findReferences(); const nullArgs = findReferences(null); - expect(withoutArgs) - .to.be.a('Array') - .to.have.lengthOf(0); - expect(nullArgs) - .to.be.a('Array') - .have.lengthOf(0); + expect(withoutArgs).to.be.a('Array').to.have.lengthOf(0); + expect(nullArgs).to.be.a('Array').have.lengthOf(0); }); it('should return paths', () => { @@ -48,10 +44,8 @@ describe('#findReferences()', () => { ]; const paths = findReferences(testObject, 'hit'); - expect(paths) - .to.be.a('Array') - .to.have.lengthOf(4); - expect(paths.every(path => expectedResult.includes(path))).to.equal(true); + expect(paths).to.be.a('Array').to.have.lengthOf(4); + expect(paths.every((path) => expectedResult.includes(path))).to.equal(true); }); it('should not fail with circular references', () => { @@ -87,9 +81,7 @@ describe('#findReferences()', () => { ]; const paths = findReferences(testObject, 'hit'); - expect(paths) - .to.be.a('Array') - .to.have.lengthOf(4); - expect(paths.every(path => expectedResult.includes(path))).to.equal(true); + expect(paths).to.be.a('Array').to.have.lengthOf(4); + expect(paths.every((path) => expectedResult.includes(path))).to.equal(true); }); }); diff --git a/test/unit/lib/plugins/aws/utils/resolveCfImportValue.test.js b/test/unit/lib/plugins/aws/utils/resolveCfImportValue.test.js index b0b9d828e43..0389c768286 100644 --- a/test/unit/lib/plugins/aws/utils/resolveCfImportValue.test.js +++ b/test/unit/lib/plugins/aws/utils/resolveCfImportValue.test.js @@ -21,7 +21,7 @@ describe('#resolveCfImportValue', () => { ], }), }; - return resolveCfImportValue(provider, 'exportName').then(result => { + return resolveCfImportValue(provider, 'exportName').then((result) => { expect(result).to.equal('exportValue'); }); }); diff --git a/test/unit/lib/plugins/aws/utils/resolveCfRefValue.test.js b/test/unit/lib/plugins/aws/utils/resolveCfRefValue.test.js index 6971e6d4e78..073f24c2764 100644 --- a/test/unit/lib/plugins/aws/utils/resolveCfRefValue.test.js +++ b/test/unit/lib/plugins/aws/utils/resolveCfRefValue.test.js @@ -24,7 +24,7 @@ describe('#resolveCfRefValue', () => { ], }), }; - return resolveCfRefValue(provider, 'myDB').then(result => { + return resolveCfRefValue(provider, 'myDB').then((result) => { expect(result).to.equal('stack-name-db-id'); }); }); diff --git a/test/unit/lib/plugins/config.test.js b/test/unit/lib/plugins/config.test.js index f1eadadb10e..ba41f4453cc 100644 --- a/test/unit/lib/plugins/config.test.js +++ b/test/unit/lib/plugins/config.test.js @@ -27,13 +27,13 @@ describe('Config', () => { runServerless({ config: { service: 'foo', provider: 'aws' }, cliArgs: ['config', 'credentials', '-k', 'foo', '-s', 'bar'], - }).then(unexpected, error => expect(error).to.be.instanceof(ServerlessError))); + }).then(unexpected, (error) => expect(error).to.be.instanceof(ServerlessError))); it('should throw an error if user passed unsupported "provider" option', () => runServerless({ config: { service: 'foo', provider: 'aws' }, cliArgs: ['config', 'credentials', '--provider', 'not-supported', '-k', 'foo', '-s', 'bar'], - }).then(unexpected, error => expect(error).to.be.instanceof(ServerlessError))); + }).then(unexpected, (error) => expect(error).to.be.instanceof(ServerlessError))); if (isTabCompletionSupported) { it('should support "config tabcompletion install" command', () => @@ -45,7 +45,7 @@ describe('Config', () => { Promise.all([ fs .readFileAsync(path.resolve(os.homedir(), '.bashrc'), 'utf8') - .then(bashRcContent => + .then((bashRcContent) => expect(bashRcContent).to.include(' ~/.config/tabtab/__tabtab.bash') ), fs.readFileAsync(path.resolve(os.homedir(), '.config/tabtab/serverless.bash'), 'utf8'), @@ -67,10 +67,10 @@ describe('Config', () => { Promise.all([ fs .readFileAsync(path.resolve(os.homedir(), '.config/tabtab/serverless.bash')) - .then(unexpected, error => expect(error.code).to.equal('ENOENT')), + .then(unexpected, (error) => expect(error.code).to.equal('ENOENT')), fs .readFileAsync(path.resolve(os.homedir(), '.config/tabtab/sls.bash')) - .then(unexpected, error => expect(error.code).to.equal('ENOENT')), + .then(unexpected, (error) => expect(error.code).to.equal('ENOENT')), ]) ) )); diff --git a/test/unit/lib/plugins/create/create.test.js b/test/unit/lib/plugins/create/create.test.js index cb8ddeab443..7b7c40ee955 100644 --- a/test/unit/lib/plugins/create/create.test.js +++ b/test/unit/lib/plugins/create/create.test.js @@ -74,7 +74,7 @@ describe('Create', () => { downloadStub.rejects(new Error('Wrong')); create.options['template-url'] = 'https://github.com/serverless/serverless'; - return create.create().catch(error => { + return create.create().catch((error) => { expect(error).to.match(/Wrong/); expect(downloadStub).to.have.been.calledOnce; // eslint-disable-line }); @@ -85,7 +85,7 @@ describe('Create', () => { create.options['template-url'] = 'https://github.com/serverless/serverless'; return create.create().then(() => { - const installationMessage = logSpy.args.filter(arg => + const installationMessage = logSpy.args.filter((arg) => arg[0].includes('installed "serverless"') ); @@ -100,7 +100,7 @@ describe('Create', () => { create.options.name = 'sls'; return create.create().then(() => { - const installationMessage = logSpy.args.filter(arg => + const installationMessage = logSpy.args.filter((arg) => arg[0].includes('installed "serverless" as "sls"') ); @@ -121,7 +121,7 @@ describe('Create', () => { create.options.name = 'my_service'; return create.create().then(() => - create.serverless.yamlParser.parse(path.join(tmpDir, 'serverless.yml')).then(obj => { + create.serverless.yamlParser.parse(path.join(tmpDir, 'serverless.yml')).then((obj) => { expect(obj.service).to.equal('my_service'); }) ); @@ -149,7 +149,7 @@ describe('Create', () => { create.options.template = 'aws-clojure-gradle'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); @@ -170,7 +170,7 @@ describe('Create', () => { create.options.template = 'aws-clojurescript-gradle'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); @@ -206,7 +206,7 @@ describe('Create', () => { create.options.template = 'aws-nodejs-typescript'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); expect(dirContent).to.include('.gitignore'); @@ -316,7 +316,7 @@ describe('Create', () => { create.options.template = 'aws-java-maven'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); @@ -341,7 +341,7 @@ describe('Create', () => { create.options.template = 'aws-kotlin-jvm-maven'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); @@ -366,7 +366,7 @@ describe('Create', () => { create.options.template = 'aws-kotlin-jvm-gradle'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); @@ -391,7 +391,7 @@ describe('Create', () => { create.options.template = 'aws-kotlin-jvm-gradle-kts'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); @@ -417,7 +417,7 @@ describe('Create', () => { create.options.template = 'aws-kotlin-nodejs-gradle'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); @@ -446,7 +446,7 @@ describe('Create', () => { create.options.template = 'aws-java-gradle'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); @@ -475,7 +475,7 @@ describe('Create', () => { create.options.template = 'aws-groovy-gradle'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); @@ -504,7 +504,7 @@ describe('Create', () => { create.options.template = 'aws-scala-sbt'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); @@ -522,7 +522,7 @@ describe('Create', () => { create.options.template = 'openwhisk-java-maven'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); expect(dirContent).to.include('pom.xml'); @@ -786,7 +786,7 @@ describe('Create', () => { create.options.template = 'knative-docker'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); expect(dirContent).to.include('package.json'); @@ -841,7 +841,7 @@ describe('Create', () => { create.options.template = 'spotinst-java8'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); @@ -860,7 +860,7 @@ describe('Create', () => { create.options.template = 'fn-nodejs'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); expect(dirContent).to.include('package.json'); @@ -877,7 +877,7 @@ describe('Create', () => { create.options.template = 'fn-go'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); expect(dirContent).to.include('package.json'); @@ -1145,7 +1145,7 @@ describe('Create', () => { create.options.template = 'aws-go'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); @@ -1162,7 +1162,7 @@ describe('Create', () => { create.options.template = 'aws-go-dep'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); @@ -1180,7 +1180,7 @@ describe('Create', () => { create.options.template = 'aws-go-mod'; return create.create().then(() => { - const dirContent = walkDirSync(tmpDir).map(elem => + const dirContent = walkDirSync(tmpDir).map((elem) => elem.replace(path.join(tmpDir, path.sep), '') ); diff --git a/test/unit/lib/plugins/deploy.test.js b/test/unit/lib/plugins/deploy.test.js index fef3fdc72be..fa162ef7ff7 100644 --- a/test/unit/lib/plugins/deploy.test.js +++ b/test/unit/lib/plugins/deploy.test.js @@ -29,9 +29,7 @@ describe('Deploy', () => { it('should have hooks', () => expect(deploy.hooks).to.be.not.empty); it('should work without options', () => { const noOptionDeploy = new Deploy(serverless); - expect(noOptionDeploy) - .to.have.property('options') - .to.be.eql({}); + expect(noOptionDeploy).to.have.property('options').to.be.eql({}); }); }); diff --git a/test/unit/lib/plugins/install.test.js b/test/unit/lib/plugins/install.test.js index 52f5f3c7e89..fc756913ee4 100644 --- a/test/unit/lib/plugins/install.test.js +++ b/test/unit/lib/plugins/install.test.js @@ -100,7 +100,7 @@ describe('Install', () => { downloadStub.resolves('remote-service'); return install.install().then(() => { - const installationMessage = logSpy.args.filter(arg => + const installationMessage = logSpy.args.filter((arg) => arg[0].includes('installed "remote-service"') ); @@ -115,7 +115,7 @@ describe('Install', () => { downloadStub.resolves('remote-service'); return install.install().then(() => { - const installationMessage = logSpy.args.filter(arg => + const installationMessage = logSpy.args.filter((arg) => arg[0].includes('installed "remote-service" as "remote"') ); diff --git a/test/unit/lib/plugins/interactiveCli/initializeService.test.js b/test/unit/lib/plugins/interactiveCli/initializeService.test.js index fcf3703807b..b798c54becf 100644 --- a/test/unit/lib/plugins/interactiveCli/initializeService.test.js +++ b/test/unit/lib/plugins/interactiveCli/initializeService.test.js @@ -74,7 +74,7 @@ describe('interactiveCli: initializeService', () => { lifecycleHookNamesBlacklist, }) .then(() => lstat(join(newProjectPath, 'serverless.yml'))) - .then(stats => expect(stats.isFile()).to.be.true); + .then((stats) => expect(stats.isFile()).to.be.true); }); }); @@ -92,7 +92,7 @@ describe('interactiveCli: initializeService', () => { () => { throw new Error('Unexpected'); }, - error => expect(error.code).to.equal('INVALID_ANSWER') + (error) => expect(error.code).to.equal('INVALID_ANSWER') ); }); @@ -110,7 +110,7 @@ describe('interactiveCli: initializeService', () => { () => { throw new Error('Unexpected'); }, - error => expect(error.code).to.equal('INVALID_ANSWER') + (error) => expect(error.code).to.equal('INVALID_ANSWER') ); }); }); diff --git a/test/unit/lib/plugins/interactiveCli/setupAws.test.js b/test/unit/lib/plugins/interactiveCli/setupAws.test.js index c0fa41371ed..d16f92e295d 100644 --- a/test/unit/lib/plugins/interactiveCli/setupAws.test.js +++ b/test/unit/lib/plugins/interactiveCli/setupAws.test.js @@ -21,7 +21,7 @@ const lifecycleHookNamesBlacklist = [ const openBrowserUrls = []; const modulesCacheStub = { - './lib/utils/openBrowser': url => + './lib/utils/openBrowser': (url) => BbPromise.try(() => { openBrowserUrls.push(url); }), @@ -84,7 +84,7 @@ describe('interactiveCli: setupAws', () => { () => { throw new Error('Unexpected ~/.aws directory, related tests aborted'); }, - error => { + (error) => { if (error.code === 'ENOENT') return; throw error; } @@ -130,7 +130,7 @@ describe('interactiveCli: setupAws', () => { expect(openBrowserUrls.length).to.equal(2); expect(openBrowserUrls[0].includes('signup')).to.be.true; expect(openBrowserUrls[1].includes('console.aws.amazon.com')).to.be.true; - return resolveFileProfiles().then(profiles => { + return resolveFileProfiles().then((profiles) => { expect(profiles).to.deep.equal(new Map([['default', { accessKeyId, secretAccessKey }]])); }); }); @@ -148,7 +148,7 @@ describe('interactiveCli: setupAws', () => { }).then(() => { expect(openBrowserUrls.length).to.equal(1); expect(openBrowserUrls[0].includes('console.aws.amazon.com')).to.be.true; - return resolveFileProfiles().then(profiles => { + return resolveFileProfiles().then((profiles) => { expect(profiles).to.deep.equal(new Map([['default', { accessKeyId, secretAccessKey }]])); }); }); @@ -167,7 +167,7 @@ describe('interactiveCli: setupAws', () => { () => { throw new Error('Unexpected'); }, - error => expect(error.code).to.equal('INVALID_ANSWER') + (error) => expect(error.code).to.equal('INVALID_ANSWER') ); }); @@ -184,7 +184,7 @@ describe('interactiveCli: setupAws', () => { () => { throw new Error('Unexpected'); }, - error => expect(error.code).to.equal('INVALID_ANSWER') + (error) => expect(error.code).to.equal('INVALID_ANSWER') ); }); }); diff --git a/test/unit/lib/plugins/interactiveCli/tabCompletion.test.js b/test/unit/lib/plugins/interactiveCli/tabCompletion.test.js index 0a85e805a5e..acb89ed4d63 100644 --- a/test/unit/lib/plugins/interactiveCli/tabCompletion.test.js +++ b/test/unit/lib/plugins/interactiveCli/tabCompletion.test.js @@ -88,7 +88,7 @@ describe('interactiveCli: tabCompletion', () => { Promise.all([ fs .readFileAsync(path.resolve(os.homedir(), '.bashrc'), 'utf8') - .then(bashRcContent => + .then((bashRcContent) => expect(bashRcContent).to.include(' ~/.config/tabtab/__tabtab.bash') ), fs.readFileAsync(path.resolve(os.homedir(), '.config/tabtab/serverless.bash'), 'utf8'), diff --git a/test/unit/lib/plugins/package/lib/packageService.test.js b/test/unit/lib/plugins/package/lib/packageService.test.js index fd3596c6d4f..de402681fb3 100644 --- a/test/unit/lib/plugins/package/lib/packageService.test.js +++ b/test/unit/lib/plugins/package/lib/packageService.test.js @@ -72,7 +72,7 @@ describe('#packageService()', () => { const localPath = './myplugins'; serverless.service.plugins = { localPath }; - return expect(packagePlugin.getExcludes()).to.be.fulfilled.then(exclude => + return expect(packagePlugin.getExcludes()).to.be.fulfilled.then((exclude) => expect(exclude).to.deep.equal( _.union(packagePlugin.defaultExcludes, [serverlessConfigFileName], [localPath]) ) @@ -86,7 +86,7 @@ describe('#packageService()', () => { const packageExcludes = ['dir', 'file.js']; serverless.service.package.exclude = packageExcludes; - return expect(packagePlugin.getExcludes()).to.be.fulfilled.then(exclude => + return expect(packagePlugin.getExcludes()).to.be.fulfilled.then((exclude) => expect(exclude).to.deep.equal( _.union( packagePlugin.defaultExcludes, @@ -107,7 +107,7 @@ describe('#packageService()', () => { const funcExcludes = ['lib', 'other.js']; - return expect(packagePlugin.getExcludes(funcExcludes)).to.be.fulfilled.then(exclude => + return expect(packagePlugin.getExcludes(funcExcludes)).to.be.fulfilled.then((exclude) => expect(exclude).to.deep.equal( _.union( packagePlugin.defaultExcludes, @@ -135,7 +135,7 @@ describe('#packageService()', () => { const packageFunctionStub = sinon .stub(packagePlugin, 'packageFunction') - .resolves(func => func.name); + .resolves((func) => func.name); return expect(packagePlugin.packageService()).to.be.fulfilled.then( () => expect(packageFunctionStub).to.be.calledTwice @@ -157,8 +157,8 @@ describe('#packageService()', () => { const packageFunctionStub = sinon .stub(packagePlugin, 'packageFunction') - .resolves(func => func.name); - const packageAllStub = sinon.stub(packagePlugin, 'packageAll').resolves(func => func.name); + .resolves((func) => func.name); + const packageAllStub = sinon.stub(packagePlugin, 'packageAll').resolves((func) => func.name); return expect(packagePlugin.packageService()).to.be.fulfilled.then(() => BbPromise.join( @@ -192,8 +192,8 @@ describe('#packageService()', () => { const packageFunctionStub = sinon .stub(packagePlugin, 'packageFunction') - .resolves(func => func.name); - const packageAllStub = sinon.stub(packagePlugin, 'packageAll').resolves(func => func.name); + .resolves((func) => func.name); + const packageAllStub = sinon.stub(packagePlugin, 'packageAll').resolves((func) => func.name); return expect(packagePlugin.packageService()).to.be.fulfilled.then(() => BbPromise.join( @@ -219,8 +219,8 @@ describe('#packageService()', () => { const packageFunctionStub = sinon .stub(packagePlugin, 'packageFunction') - .resolves(func => func.name); - const packageAllStub = sinon.stub(packagePlugin, 'packageAll').resolves(func => func.name); + .resolves((func) => func.name); + const packageAllStub = sinon.stub(packagePlugin, 'packageAll').resolves((func) => func.name); return expect(packagePlugin.packageService()).to.be.fulfilled.then(() => BbPromise.join( @@ -361,7 +361,7 @@ describe('#packageService()', () => { return expect( packagePlugin.resolveFilePathsFromPatterns(params) - ).to.be.fulfilled.then(actual => expect(actual).to.deep.equal([handlerFile])); + ).to.be.fulfilled.then((actual) => expect(actual).to.deep.equal([handlerFile])); }); it('should include file specified with `!` in exclude params', () => { @@ -373,7 +373,7 @@ describe('#packageService()', () => { return expect( packagePlugin.resolveFilePathsFromPatterns(params) - ).to.be.fulfilled.then(actual => + ).to.be.fulfilled.then((actual) => expect(actual.sort()).to.deep.equal([handlerFile, utilsFile].sort()) ); }); @@ -388,7 +388,7 @@ describe('#packageService()', () => { return expect( packagePlugin.resolveFilePathsFromPatterns(params) - ).to.be.fulfilled.then(actual => expect(actual.sort()).to.deep.equal(expected.sort())); + ).to.be.fulfilled.then((actual) => expect(actual.sort()).to.deep.equal(expected.sort())); }); }); }); diff --git a/test/unit/lib/plugins/package/lib/zipService.test.js b/test/unit/lib/plugins/package/lib/zipService.test.js index c483088cef7..bc5e3ae6e8b 100644 --- a/test/unit/lib/plugins/package/lib/zipService.test.js +++ b/test/unit/lib/plugins/package/lib/zipService.test.js @@ -83,9 +83,11 @@ describe('zipService', () => { fs.writeFileSync(filePath, buf); - return expect(packagePlugin.getFileContentAndStat(filePath)).to.be.fulfilled.then(result => { - expect(result.data).to.deep.equal(buf); - }); + return expect(packagePlugin.getFileContentAndStat(filePath)).to.be.fulfilled.then( + (result) => { + expect(result.data).to.deep.equal(buf); + } + ); }); }); @@ -103,7 +105,7 @@ describe('zipService', () => { fs.writeFileSync(filePath, buf); - return expect(packagePlugin.getFileContent(filePath)).to.be.fulfilled.then(result => { + return expect(packagePlugin.getFileContent(filePath)).to.be.fulfilled.then((result) => { expect(result).to.deep.equal(buf); }); }); @@ -114,7 +116,7 @@ describe('zipService', () => { packagePlugin.serverless.service.package.excludeDevDependencies = false; return expect(packagePlugin.excludeDevDependencies(params)).to.be.fulfilled.then( - updatedParams => { + (updatedParams) => { expect(updatedParams).to.deep.equal(params); } ); @@ -145,7 +147,7 @@ describe('zipService', () => { globbySyncStub.returns(filePaths); return expect(packagePlugin.excludeDevDependencies(params)).to.be.fulfilled.then( - updatedParams => { + (updatedParams) => { expect(globbySyncStub).to.have.been.calledOnce; expect(execAsyncStub).to.not.have.been.called; expect(readFileAsyncStub).to.not.have.been.called; @@ -172,7 +174,7 @@ describe('zipService', () => { readFileAsyncStub.resolves(depPaths); return expect(packagePlugin.excludeDevDependencies(params)).to.be.fulfilled.then( - updatedParams => { + (updatedParams) => { expect(globbySyncStub).to.have.been.calledOnce; expect(execAsyncStub).to.have.been.calledTwice; expect(readFileAsyncStub).to.have.been.calledTwice; @@ -202,7 +204,7 @@ describe('zipService', () => { globbySyncStub.throws(); return expect(packagePlugin.excludeDevDependencies(params)).to.be.fulfilled.then( - updatedParams => { + (updatedParams) => { expect(globbySyncStub).to.have.been.calledOnce; expect(execAsyncStub).to.not.have.been.called; expect(readFileAsyncStub).to.not.have.been.called; @@ -222,7 +224,7 @@ describe('zipService', () => { readFileAsyncStub.resolves(); return expect(packagePlugin.excludeDevDependencies(params)).to.be.fulfilled.then( - updatedParams => { + (updatedParams) => { expect(globbySyncStub).to.been.calledOnce; expect(execAsyncStub).to.have.been.calledTwice; expect(readFileAsyncStub).to.have.been.calledTwice; @@ -243,7 +245,7 @@ describe('zipService', () => { readFileAsyncStub.onCall(1).rejects(); return expect(packagePlugin.excludeDevDependencies(params)).to.be.fulfilled.then( - updatedParams => { + (updatedParams) => { expect(globbySyncStub).to.been.calledOnce; expect(execAsyncStub).to.have.been.calledTwice; expect(readFileAsyncStub).to.have.been.calledTwice; @@ -289,7 +291,7 @@ describe('zipService', () => { readFileAsyncStub.onCall(5).resolves('{}'); return expect(packagePlugin.excludeDevDependencies(params)).to.be.fulfilled.then( - updatedParams => { + (updatedParams) => { expect(globbySyncStub).to.have.been.calledOnce; expect(execAsyncStub.callCount).to.equal(6); expect(readFileAsyncStub).to.have.callCount(6); @@ -364,7 +366,7 @@ describe('zipService', () => { readFileAsyncStub.onCall(3).resolves('{}'); return expect(packagePlugin.excludeDevDependencies(params)).to.be.fulfilled.then( - updatedParams => { + (updatedParams) => { expect(globbySyncStub).to.have.been.calledOnce; expect(execAsyncStub).to.have.been.calledTwice; expect(readFileAsyncStub).to.have.callCount(4); @@ -433,7 +435,7 @@ describe('zipService', () => { readFileAsyncStub.onCall(7).resolves('{}'); return expect(packagePlugin.excludeDevDependencies(params)).to.be.fulfilled.then( - updatedParams => { + (updatedParams) => { expect(globbySyncStub).to.have.been.calledOnce; expect(execAsyncStub.callCount).to.equal(6); expect(readFileAsyncStub).to.have.callCount(8); @@ -500,7 +502,7 @@ describe('zipService', () => { readFileAsyncStub.onCall(2).resolves('{}'); return expect(packagePlugin.excludeDevDependencies(params)).to.be.fulfilled.then( - updatedParams => { + (updatedParams) => { expect(globbySyncStub).to.have.been.calledOnce; expect(execAsyncStub).to.have.been.calledTwice; expect(readFileAsyncStub).to.have.been.calledThrice; @@ -547,7 +549,7 @@ describe('zipService', () => { globbySyncStub.returns(filePaths); execAsyncStub.resolves(); - const mapper = depPath => path.join(`${servicePath}`, depPath); + const mapper = (depPath) => path.join(`${servicePath}`, depPath); const devDepPaths = devPaths.map(mapper).join('\n'); readFileAsyncStub.withArgs(sinon.match(/dev$/)).resolves(devDepPaths); @@ -565,7 +567,7 @@ describe('zipService', () => { .resolves('{"name": "meowmix", "bin": {"meow": "./bin/meow.js", "mix": "./bin/mix.js"}}'); return expect(packagePlugin.excludeDevDependencies(params)).to.be.fulfilled.then( - updatedParams => { + (updatedParams) => { expect(globbySyncStub).to.been.calledOnce; expect(execAsyncStub).to.have.been.calledTwice; @@ -616,7 +618,7 @@ describe('zipService', () => { '1st/2nd/node_modules/module-1', '1st/2nd/node_modules/module-2', ]; - const depPaths = deps.map(depPath => path.join(`${servicePath}`, depPath)); + const depPaths = deps.map((depPath) => path.join(`${servicePath}`, depPath)); readFileAsyncStub.withArgs(sinon.match(/dev$/)).resolves(depPaths.join('\n')); readFileAsyncStub.withArgs(sinon.match(/prod$/)).resolves([]); @@ -639,7 +641,7 @@ describe('zipService', () => { readFileAsyncStub.onCall(7).resolves(module2PackageJson); return expect(packagePlugin.excludeDevDependencies(params)).to.be.fulfilled.then( - updatedParams => { + (updatedParams) => { expect(globbySyncStub).to.have.been.calledOnce; expect(execAsyncStub.callCount).to.equal(6); expect(readFileAsyncStub).to.have.callCount(8); @@ -726,11 +728,11 @@ describe('zipService', () => { beforeEach(() => { zip = new JsZip(); - Object.keys(testDirectory).forEach(dirName => { + Object.keys(testDirectory).forEach((dirName) => { const dirPath = path.join(tmpDirPath, dirName); const files = testDirectory[dirName]; - Object.keys(files).forEach(fileName => { + Object.keys(files).forEach((fileName) => { const filePath = path.join(dirPath, fileName); const fileValue = files[fileName]; const file = _.isObject(fileValue) ? fileValue : { content: fileValue }; @@ -755,15 +757,15 @@ describe('zipService', () => { .to.eventually.be.equal( path.join(serverless.config.servicePath, '.serverless', params.zipFileName) ) - .then(artifact => { + .then((artifact) => { const data = fs.readFileSync(artifact); return expect(zip.loadAsync(data)).to.be.fulfilled; }) - .then(unzippedData => { + .then((unzippedData) => { const unzippedFileData = unzippedData.files; expect( - Object.keys(unzippedFileData).filter(file => !unzippedFileData[file].dir) + Object.keys(unzippedFileData).filter((file) => !unzippedFileData[file].dir) ).to.be.lengthOf(12); // root directory @@ -805,11 +807,11 @@ describe('zipService', () => { .to.eventually.be.equal( path.join(serverless.config.servicePath, '.serverless', params.zipFileName) ) - .then(artifact => { + .then((artifact) => { const data = fs.readFileSync(artifact); return expect(zip.loadAsync(data)).to.be.fulfilled; }) - .then(unzippedData => { + .then((unzippedData) => { const unzippedFileData = unzippedData.files; if (os.platform() !== 'win32') { @@ -835,15 +837,15 @@ describe('zipService', () => { .to.eventually.be.equal( path.join(serverless.config.servicePath, '.serverless', params.zipFileName) ) - .then(artifact => { + .then((artifact) => { const data = fs.readFileSync(artifact); return expect(zip.loadAsync(data)).to.be.fulfilled; }) - .then(unzippedData => { + .then((unzippedData) => { const unzippedFileData = unzippedData.files; expect( - Object.keys(unzippedFileData).filter(file => !unzippedFileData[file].dir) + Object.keys(unzippedFileData).filter((file) => !unzippedFileData[file].dir) ).to.be.lengthOf(7); // root directory @@ -880,15 +882,15 @@ describe('zipService', () => { .to.eventually.be.equal( path.join(serverless.config.servicePath, '.serverless', params.zipFileName) ) - .then(artifact => { + .then((artifact) => { const data = fs.readFileSync(artifact); return expect(zip.loadAsync(data)).to.be.fulfilled; }) - .then(unzippedData => { + .then((unzippedData) => { const unzippedFileData = unzippedData.files; expect( - Object.keys(unzippedFileData).filter(file => !unzippedFileData[file].dir) + Object.keys(unzippedFileData).filter((file) => !unzippedFileData[file].dir) ).to.be.lengthOf(10); // root directory @@ -926,15 +928,15 @@ describe('zipService', () => { .to.eventually.be.equal( path.join(serverless.config.servicePath, '.serverless', params.zipFileName) ) - .then(artifact => { + .then((artifact) => { const data = fs.readFileSync(artifact); return expect(zip.loadAsync(data)).to.be.fulfilled; }) - .then(unzippedData => { + .then((unzippedData) => { const unzippedFileData = unzippedData.files; expect( - Object.keys(unzippedFileData).filter(file => !unzippedFileData[file].dir) + Object.keys(unzippedFileData).filter((file) => !unzippedFileData[file].dir) ).to.be.lengthOf(10); // root directory @@ -973,11 +975,11 @@ describe('zipService', () => { .to.eventually.be.equal( path.join(serverless.config.servicePath, '.serverless', params.zipFileName) ) - .then(artifact => { + .then((artifact) => { const data = fs.readFileSync(artifact); return expect(zip.loadAsync(data)).to.be.fulfilled; }) - .then(unzippedData => { + .then((unzippedData) => { const unzippedFileData = unzippedData.files; expect(Object.keys(unzippedFileData).sort()).to.deep.equal([ 'bin/binary-444', @@ -996,11 +998,11 @@ describe('zipService', () => { .to.eventually.be.equal( path.join(serverless.config.servicePath, '.serverless', params.zipFileName) ) - .then(artifact => { + .then((artifact) => { const data = fs.readFileSync(artifact); return expect(zip.loadAsync(data)).to.be.fulfilled; }) - .then(unzippedData => { + .then((unzippedData) => { const unzippedFileData = unzippedData.files; expect(Object.keys(unzippedFileData).sort()).to.deep.equal([ 'bin/binary-444', diff --git a/test/unit/lib/plugins/plugin/lib/utils.test.js b/test/unit/lib/plugins/plugin/lib/utils.test.js index 4495a87c2af..677e7dd1f46 100644 --- a/test/unit/lib/plugins/plugin/lib/utils.test.js +++ b/test/unit/lib/plugins/plugin/lib/utils.test.js @@ -59,7 +59,7 @@ describe('PluginUtils', () => { }).to.throw(Error); }); - it('should resolve if the cwd is a Serverless service', done => { + it('should resolve if the cwd is a Serverless service', (done) => { pluginUtils.serverless.config.servicePath = true; pluginUtils.validate().then(() => done()); @@ -79,7 +79,7 @@ describe('PluginUtils', () => { fse.ensureFileSync(serverlessYmlFilePath); return expect(pluginUtils.getServerlessFilePath()).to.be.fulfilled.then( - serverlessFilePath => { + (serverlessFilePath) => { expect(serverlessFilePath).to.equal(serverlessYmlFilePath); } ); @@ -90,7 +90,7 @@ describe('PluginUtils', () => { fse.ensureFileSync(serverlessYamlFilePath); return expect(pluginUtils.getServerlessFilePath()).to.be.fulfilled.then( - serverlessFilePath => { + (serverlessFilePath) => { expect(serverlessFilePath).to.equal(serverlessYamlFilePath); } ); @@ -101,7 +101,7 @@ describe('PluginUtils', () => { fse.ensureFileSync(serverlessJsonFilePath); return expect(pluginUtils.getServerlessFilePath()).to.be.fulfilled.then( - serverlessFilePath => { + (serverlessFilePath) => { expect(serverlessFilePath).to.equal(serverlessJsonFilePath); } ); @@ -112,7 +112,7 @@ describe('PluginUtils', () => { fse.ensureFileSync(serverlessJsFilePath); return expect(pluginUtils.getServerlessFilePath()).to.be.fulfilled.then( - serverlessFilePath => { + (serverlessFilePath) => { expect(serverlessFilePath).to.equal(serverlessJsFilePath); } ); @@ -142,7 +142,7 @@ describe('PluginUtils', () => { it('should fetch and return the plugins from the plugins repository', () => { const endpoint = 'https://raw.githubusercontent.com/serverless/plugins/master/plugins.json'; - return pluginWithFetchStub.getPlugins().then(result => { + return pluginWithFetchStub.getPlugins().then((result) => { expect(fetchStub.calledOnce).to.equal(true); expect(fetchStub.args[0][0]).to.equal(endpoint); expect(result).to.deep.equal(plugins); @@ -177,7 +177,7 @@ describe('PluginUtils', () => { expectedMessage += `${chalk.yellow.underline('serverless-plugin-2')}`; expectedMessage += ' - Serverless Plugin 2\n'; expectedMessage = expectedMessage.slice(0, -2); - return expect(pluginUtils.display(plugins)).to.be.fulfilled.then(message => { + return expect(pluginUtils.display(plugins)).to.be.fulfilled.then((message) => { expect(consoleLogStub.calledTwice).to.equal(true); expect(message).to.equal(expectedMessage); }); @@ -186,7 +186,7 @@ describe('PluginUtils', () => { it('should print a message when no plugins are available to display', () => { const expectedMessage = 'There are no plugins available to display'; - return pluginUtils.display([]).then(message => { + return pluginUtils.display([]).then((message) => { expect(consoleLogStub.calledOnce).to.equal(true); expect(message).to.equal(expectedMessage); }); diff --git a/test/unit/lib/plugins/print.test.js b/test/unit/lib/plugins/print.test.js index e598f490323..1142c217588 100644 --- a/test/unit/lib/plugins/print.test.js +++ b/test/unit/lib/plugins/print.test.js @@ -330,7 +330,7 @@ describe('Print', () => { [ { value: 'hello_123@~:/+', description: 'ascii chars' }, { value: '①⑴⒈⒜Ⓐⓐⓟ ..▉가Ὠ', description: 'unicode chars' }, - ].forEach(testCase => { + ].forEach((testCase) => { it(testCase.description, () => { const conf = { custom: { diff --git a/test/unit/lib/plugins/slstats.test.js b/test/unit/lib/plugins/slstats.test.js index 3b6d1b07fa7..18cd9ab6669 100644 --- a/test/unit/lib/plugins/slstats.test.js +++ b/test/unit/lib/plugins/slstats.test.js @@ -73,7 +73,7 @@ describe('SlStats', () => { slStats.options = { enable: true }; - return slStats.toggleStats().catch(error => { + return slStats.toggleStats().catch((error) => { expect(setStub.calledOnce).to.equal(false); expect(error).to.match(/of statistics failed/); }); @@ -84,7 +84,7 @@ describe('SlStats', () => { setStub.throws('error while updating config file'); slStats.options = { disable: true }; - return slStats.toggleStats().catch(error => { + return slStats.toggleStats().catch((error) => { expect(setStub.calledOnce).to.equal(true); expect(error).to.match(/of statistics failed/); }); diff --git a/test/unit/lib/utils/analytics/index.test.js b/test/unit/lib/utils/analytics/index.test.js index 3278d34ec0f..b91344475e7 100644 --- a/test/unit/lib/utils/analytics/index.test.js +++ b/test/unit/lib/utils/analytics/index.test.js @@ -32,7 +32,7 @@ describe('analytics', () => { ({ report, sendPending } = proxyquire('../../../../../lib/utils/analytics/index.js', { '@serverless/utils/analytics-and-notfications-url': analyticsUrl, './areDisabled': false, - 'node-fetch': url => { + 'node-fetch': (url) => { usedUrl = url; ++pendingRequests; if (pendingRequests > concurrentRequestsMax) concurrentRequestsMax = pendingRequests; @@ -63,11 +63,11 @@ describe('analytics', () => { }); it('Should ignore missing cacheDirPath', () => - sendPending().then(sendPendingResult => { + sendPending().then((sendPendingResult) => { expect(sendPendingResult).to.be.null; return sendReport().then(() => { expect(usedUrl).to.equal(analyticsUrl); - return fse.readdir(cacheDirPath).then(dirFilenames => { + return fse.readdir(cacheDirPath).then((dirFilenames) => { expect(dirFilenames.filter(isFilename).length).to.equal(0); }); }); @@ -80,13 +80,13 @@ describe('analytics', () => { expect(usedUrl).to.equal(analyticsUrl); return fse.readdir(cacheDirPath); }) - .then(dirFilenames => { + .then((dirFilenames) => { expect(dirFilenames.filter(isFilename).length).to.equal(1); expectedState = 'success'; return sendPending(); }) .then(() => fse.readdir(cacheDirPath)) - .then(dirFilenames => { + .then((dirFilenames) => { expect(dirFilenames.filter(isFilename).length).to.equal(0); }); }); @@ -96,7 +96,7 @@ describe('analytics', () => { expect(pendingRequests).to.equal(0); let resolveServerlessExecutionSpan; const serverlessExecutionSpan = new BbPromise( - resolve => (resolveServerlessExecutionSpan = resolve) + (resolve) => (resolveServerlessExecutionSpan = resolve) ); return Promise.all([ sendReport(), @@ -110,7 +110,7 @@ describe('analytics', () => { .then(() => { return fse.readdir(cacheDirPath); }) - .then(dirFilenames => { + .then((dirFilenames) => { expect(dirFilenames.filter(isFilename).length).to.equal(7); expectedState = 'success'; expect(pendingRequests).to.equal(0); @@ -118,7 +118,7 @@ describe('analytics', () => { return sendPending({ serverlessExecutionSpan }); }) .then(() => fse.readdir(cacheDirPath)) - .then(dirFilenames => { + .then((dirFilenames) => { expect(dirFilenames.filter(isFilename).length).to.equal(0); expect(concurrentRequestsMax).to.equal(3); resolveServerlessExecutionSpan(); @@ -140,13 +140,13 @@ describe('analytics', () => { .then(() => { return fse.readdir(cacheDirPath); }) - .then(dirFilenames => { + .then((dirFilenames) => { expect(dirFilenames.filter(isFilename).length).to.equal(7); expectedState = 'success'; return sendPending(); }) .then(() => fse.readdir(cacheDirPath)) - .then(dirFilenames => { + .then((dirFilenames) => { expect(dirFilenames.filter(isFilename).length).to.equal(4); return fse.emptyDir(cacheDirPath); }); @@ -157,7 +157,7 @@ describe('analytics', () => { expect(pendingRequests).to.equal(0); let resolveServerlessExecutionSpan; const serverlessExecutionSpan = new BbPromise( - resolve => (resolveServerlessExecutionSpan = resolve) + (resolve) => (resolveServerlessExecutionSpan = resolve) ); return Promise.all([ cacheEvent(0), @@ -171,7 +171,7 @@ describe('analytics', () => { .then(() => { return fse.readdir(cacheDirPath); }) - .then(dirFilenames => { + .then((dirFilenames) => { expect(dirFilenames.filter(isFilename).length).to.equal(7); expectedState = 'success'; expect(pendingRequests).to.equal(0); @@ -179,7 +179,7 @@ describe('analytics', () => { return sendPending({ serverlessExecutionSpan }); }) .then(() => fse.readdir(cacheDirPath)) - .then(dirFilenames => { + .then((dirFilenames) => { expect(dirFilenames.filter(isFilename).length).to.equal(0); expect(concurrentRequestsMax).to.equal(2); resolveServerlessExecutionSpan(); @@ -193,7 +193,7 @@ describe('analytics', () => { .then(() => { return fse.readdir(cacheDirPath); }) - .then(dirFilenames => { + .then((dirFilenames) => { expect(dirFilenames.filter(isFilename).length).to.equal(0); }); }); diff --git a/test/unit/lib/utils/downloadTemplateFromRepo.test.js b/test/unit/lib/utils/downloadTemplateFromRepo.test.js index 1ac7102da5d..cb7fc5a2c9e 100644 --- a/test/unit/lib/utils/downloadTemplateFromRepo.test.js +++ b/test/unit/lib/utils/downloadTemplateFromRepo.test.js @@ -50,7 +50,7 @@ describe('downloadTemplateFromRepo', () => { const downloadTemplateFromRepoModule = proxyquire( '../../../../lib/utils/downloadTemplateFromRepo', { - 'node-fetch': url => { + 'node-fetch': (url) => { if (url.indexOf('mybitbucket.server.ltd') > -1) { return fetchStub(); } @@ -65,7 +65,7 @@ describe('downloadTemplateFromRepo', () => { parseRepoURL = downloadTemplateFromRepoModule.parseRepoURL; }); - afterEach(done => { + afterEach((done) => { // change back to the old cwd process.chdir(cwd); fse.remove(newServicePath).then(done); @@ -108,14 +108,14 @@ describe('downloadTemplateFromRepo', () => { const name = 'new-service-name'; spawnStub.resolves({ - then: callback => { + then: (callback) => { const slsYml = path.join(process.cwd(), 'new-service-name', 'serverless.yml'); writeFileSync(slsYml, 'service: sample-service'); callback(); }, }); - return expect(downloadTemplateFromRepo(url, name)).to.be.fulfilled.then(serviceName => { + return expect(downloadTemplateFromRepo(url, name)).to.be.fulfilled.then((serviceName) => { expect(spawnStub.calledOnce).to.equal(true); expect(downloadStub.calledOnce).to.equal(false); expect(spawnStub.args[0][0]).to.equal('git'); @@ -144,14 +144,14 @@ describe('downloadTemplateFromRepo', () => { const name = 'new-service-name'; spawnStub.resolves({ - then: callback => { + then: (callback) => { const slsYml = path.join(process.cwd(), 'new-service-name', 'serverless.yml'); writeFileSync(slsYml, 'service: sample-service'); callback(); }, }); - return expect(downloadTemplateFromRepo(url, name)).to.be.fulfilled.then(serviceName => { + return expect(downloadTemplateFromRepo(url, name)).to.be.fulfilled.then((serviceName) => { expect(spawnStub.calledOnce).to.equal(true); expect(downloadStub.calledOnce).to.equal(false); expect(spawnStub.args[0][0]).to.equal('git'); @@ -177,14 +177,14 @@ describe('downloadTemplateFromRepo', () => { const name = 'new-service-name'; downloadStub.resolves({ - then: callback => { + then: (callback) => { const slsYml = path.join(process.cwd(), 'new-service-name', 'serverless.yml'); writeFileSync(slsYml, 'service: service-name'); callback(); }, }); - return expect(downloadTemplateFromRepo(url, name)).to.be.fulfilled.then(serviceName => { + return expect(downloadTemplateFromRepo(url, name)).to.be.fulfilled.then((serviceName) => { expect(downloadStub.calledOnce).to.equal(true); expect(downloadStub.args[0][1]).to.contain(name); expect(downloadStub.args[0][0]).to.equal(`${url}/archive/master.zip`); @@ -210,7 +210,7 @@ describe('downloadTemplateFromRepo', () => { }) ); - return expect(downloadTemplateFromRepo(url, name)).to.be.fulfilled.then(serviceName => { + return expect(downloadTemplateFromRepo(url, name)).to.be.fulfilled.then((serviceName) => { expect(downloadStub.calledOnce).to.equal(true); const yml = readFileSync(path.join(newServicePath, 'serverless.yml')); expect(yml.service).to.equal(name); @@ -244,7 +244,7 @@ describe('downloadTemplateFromRepo', () => { it('should parse a valid GitHub URL', () => { return expect(parseRepoURL('https://github.com/serverless/serverless')).to.be.fulfilled.then( - output => { + (output) => { expect(output).to.deep.eq({ owner: 'serverless', repo: 'serverless', @@ -261,7 +261,7 @@ describe('downloadTemplateFromRepo', () => { it('should parse a valid GitHub URL with subdirectory', () => { return expect( parseRepoURL('https://github.com/serverless/serverless/tree/master/assets') - ).to.be.fulfilled.then(output => { + ).to.be.fulfilled.then((output) => { expect(output).to.deep.eq({ owner: 'serverless', repo: 'serverless', @@ -277,7 +277,7 @@ describe('downloadTemplateFromRepo', () => { it('should parse a valid GitHub Entreprise URL', () => { return expect( parseRepoURL('https://github.mydomain.com/serverless/serverless') - ).to.be.fulfilled.then(output => { + ).to.be.fulfilled.then((output) => { expect(output).to.deep.eq({ owner: 'serverless', repo: 'serverless', @@ -293,7 +293,7 @@ describe('downloadTemplateFromRepo', () => { it('should parse a valid GitHub Entreprise with subdirectory', () => { return expect( parseRepoURL('https://github.mydomain.com/serverless/serverless/tree/master/assets') - ).to.be.fulfilled.then(output => { + ).to.be.fulfilled.then((output) => { expect(output).to.deep.eq({ owner: 'serverless', repo: 'serverless', @@ -309,7 +309,7 @@ describe('downloadTemplateFromRepo', () => { it('should parse a valid GitHub Entreprise URL with authentication', () => { return expect( parseRepoURL('https://username:password@github.com/serverless/serverless/') - ).to.be.fulfilled.then(output => { + ).to.be.fulfilled.then((output) => { expect(output).to.deep.eq({ owner: 'serverless', repo: 'serverless', @@ -323,7 +323,7 @@ describe('downloadTemplateFromRepo', () => { }); it('should parse a valid BitBucket URL', () => { - return parseRepoURL('https://bitbucket.org/atlassian/localstack').then(output => { + return parseRepoURL('https://bitbucket.org/atlassian/localstack').then((output) => { expect(output).to.deep.eq({ owner: 'atlassian', repo: 'localstack', @@ -339,7 +339,7 @@ describe('downloadTemplateFromRepo', () => { it('should parse a valid BitBucket URL with subdirectory', () => { return parseRepoURL( 'https://bitbucket.org/atlassian/localstack/src/85870856fd6941ae75c0fa946a51cf756ff2f53a/localstack/dashboard/?at=mvn' - ).then(output => { + ).then((output) => { expect(output).to.deep.eq({ owner: 'atlassian', repo: 'localstack', @@ -355,7 +355,7 @@ describe('downloadTemplateFromRepo', () => { it('should parse a valid Bitbucket Server URL', () => { return parseRepoURL( 'https://user:pass@mybitbucket.server.ltd/rest/api/latest/projects/myproject/repos/myrepo/archive?at=refs%2Fheads%2Fdevelop' - ).then(output => { + ).then((output) => { expect(output).to.deep.eq({ owner: 'myproject', repo: 'myrepo', @@ -370,7 +370,7 @@ describe('downloadTemplateFromRepo', () => { }); it('should parse a valid GitLab URL ', () => { - return parseRepoURL('https://gitlab.com/serverless/serverless').then(output => { + return parseRepoURL('https://gitlab.com/serverless/serverless').then((output) => { expect(output).to.deep.eq({ owner: 'serverless', repo: 'serverless', @@ -386,7 +386,7 @@ describe('downloadTemplateFromRepo', () => { it('should parse a valid GitLab URL with subdirectory', () => { return parseRepoURL('https://gitlab.com/serverless/serverless/tree/dev/subdir').then( - output => { + (output) => { expect(output).to.deep.eq({ owner: 'serverless', repo: 'serverless', diff --git a/test/unit/lib/utils/fs/copyDirContentsSync.test.js b/test/unit/lib/utils/fs/copyDirContentsSync.test.js index 7ee29106eda..491b919829a 100644 --- a/test/unit/lib/utils/fs/copyDirContentsSync.test.js +++ b/test/unit/lib/utils/fs/copyDirContentsSync.test.js @@ -16,7 +16,7 @@ describe('#copyDirContentsSync()', () => { }; afterEach(afterCallback); - it('should recursively copy directory files including symbolic links', function() { + it('should recursively copy directory files including symbolic links', function () { const tmpSrcDirPath = path.join(process.cwd(), 'testSrc'); const tmpDestDirPath = path.join(process.cwd(), 'testDest'); @@ -44,7 +44,7 @@ describe('#copyDirContentsSync()', () => { expect(fileExistsSync(destFile3)).to.equal(true); }); - it('should recursively copy directory files excluding symbolic links', function() { + it('should recursively copy directory files excluding symbolic links', function () { const tmpSrcDirPath = path.join(process.cwd(), 'testSrc'); const tmpDestDirPath = path.join(process.cwd(), 'testDest'); diff --git a/test/unit/lib/utils/fs/createZipFile.test.js b/test/unit/lib/utils/fs/createZipFile.test.js index 51757ce7d07..0432557daaf 100644 --- a/test/unit/lib/utils/fs/createZipFile.test.js +++ b/test/unit/lib/utils/fs/createZipFile.test.js @@ -15,13 +15,10 @@ describe('#createZipFile()', () => { const toZipFilePath = createTmpFile('foo.json'); const zipFilePath = createTmpFile('package.zip'); - const srcDirPath = toZipFilePath - .split(path.sep) - .slice(0, -1) - .join(path.sep); + const srcDirPath = toZipFilePath.split(path.sep).slice(0, -1).join(path.sep); return createZipFile(srcDirPath, zipFilePath) .then(listZipFiles) - .then(files => expect(files).to.deep.equal(['foo.json'])); + .then((files) => expect(files).to.deep.equal(['foo.json'])); }); }); diff --git a/test/unit/lib/utils/fs/parse.test.js b/test/unit/lib/utils/fs/parse.test.js index 6476aaead49..e67e137b5e8 100644 --- a/test/unit/lib/utils/fs/parse.test.js +++ b/test/unit/lib/utils/fs/parse.test.js @@ -108,7 +108,7 @@ describe('#parse()', () => { expect(obj).to.equal('serverless'); }); - shortHandOptions.forEach(shortHandOption => { + shortHandOptions.forEach((shortHandOption) => { it(`should convert shorthand syntax "${shortHandOption.name}"`, () => { const tmpFilePath = 'anything.yml'; const fileContents = shortHandOption.yaml; diff --git a/test/unit/lib/utils/fs/readFile.test.js b/test/unit/lib/utils/fs/readFile.test.js index 87218236e98..428a9a5daf3 100644 --- a/test/unit/lib/utils/fs/readFile.test.js +++ b/test/unit/lib/utils/fs/readFile.test.js @@ -39,7 +39,7 @@ describe('#readFile()', () => { const tmpFilePath = getTmpFilePath('invalid.yml'); return writeFile(tmpFilePath, ': a') .then(() => readFile(tmpFilePath)) - .catch(e => { + .catch((e) => { expect(e.name).to.equal('YAMLException'); expect(e.message).to.match(new RegExp('.*invalid.yml')); }); diff --git a/test/unit/lib/utils/fs/walkDirSync.test.js b/test/unit/lib/utils/fs/walkDirSync.test.js index 83fd26dda03..e6bcbf2ec80 100644 --- a/test/unit/lib/utils/fs/walkDirSync.test.js +++ b/test/unit/lib/utils/fs/walkDirSync.test.js @@ -31,7 +31,7 @@ describe('#walkDirSync()', () => { expect(filePaths).to.include(tmpFilePath3); }); - it('should check noLinks option', function() { + it('should check noLinks option', function () { const tmpDirPath = getTmpDirPath(); const realFile = path.join(tmpDirPath, 'real'); diff --git a/test/unit/lib/utils/fs/writeFile.test.js b/test/unit/lib/utils/fs/writeFile.test.js index 831395b3259..433e0a1abd8 100644 --- a/test/unit/lib/utils/fs/writeFile.test.js +++ b/test/unit/lib/utils/fs/writeFile.test.js @@ -12,7 +12,7 @@ chai.use(require('chai-as-promised')); chai.use(require('sinon-chai')); const expect = require('chai').expect; -describe('#writeFile()', function() { +describe('#writeFile()', function () { let serverless; this.timeout(0); diff --git a/test/unit/lib/utils/fs/writeFileSync.test.js b/test/unit/lib/utils/fs/writeFileSync.test.js index 8f38294f4ca..65ba0e0a05b 100644 --- a/test/unit/lib/utils/fs/writeFileSync.test.js +++ b/test/unit/lib/utils/fs/writeFileSync.test.js @@ -28,7 +28,7 @@ describe('#writeFileSync()', () => { writeFileSync(tmpFilePath, { foo: 'bar' }); - return serverless.yamlParser.parse(tmpFilePath).then(obj => { + return serverless.yamlParser.parse(tmpFilePath).then((obj) => { expect(obj.foo).to.equal('bar'); }); }); @@ -38,7 +38,7 @@ describe('#writeFileSync()', () => { writeFileSync(tmpFilePath, { foo: 'bar' }); - return serverless.yamlParser.parse(tmpFilePath).then(obj => { + return serverless.yamlParser.parse(tmpFilePath).then((obj) => { expect(obj.foo).to.equal('bar'); }); }); @@ -57,7 +57,7 @@ describe('#writeFileSync()', () => { writeFileSync(tmpFilePath, bar, true); - return fse.readFile(tmpFilePath, 'utf8').then(contents => { + return fse.readFile(tmpFilePath, 'utf8').then((contents) => { expect(contents).to.equal(expected); }); }); diff --git a/test/unit/lib/utils/getEnsureArtifact.test.js b/test/unit/lib/utils/getEnsureArtifact.test.js index b0f4bb1c0cd..a735b9aec59 100644 --- a/test/unit/lib/utils/getEnsureArtifact.test.js +++ b/test/unit/lib/utils/getEnsureArtifact.test.js @@ -16,7 +16,7 @@ describe('#getEnsureArtifact', () => { let invokedCount = 0; before(() => { - ensureArtifact = getEnsureArtifact(testArtifactName, cachePath => { + ensureArtifact = getEnsureArtifact(testArtifactName, (cachePath) => { testArtifactPath = path.resolve(cachePath, testArtifactName); ++invokedCount; return fse.writeFile(testArtifactPath, ''); @@ -24,11 +24,11 @@ describe('#getEnsureArtifact', () => { }); it('Should not generate on ensure function initialization', () => - fse.pathExists(testArtifactPath).then(exists => expect(exists).to.be.false)); + fse.pathExists(testArtifactPath).then((exists) => expect(exists).to.be.false)); it('Should generate artifact if missing', () => ensureArtifact().then(() => - fse.pathExists(testArtifactPath).then(exists => expect(exists).to.be.true) + fse.pathExists(testArtifactPath).then((exists) => expect(exists).to.be.true) )); it('Should generate only on first access', () => @@ -40,7 +40,7 @@ describe('#getEnsureArtifact', () => { }); it('Should return cache path', () => - ensureArtifact().then(cachePath => + ensureArtifact().then((cachePath) => expect(cachePath).to.include(`.serverless${path.sep}artifacts`) )); }); diff --git a/test/unit/lib/utils/getServerlessConfigFile.test.js b/test/unit/lib/utils/getServerlessConfigFile.test.js index 514df69df42..75a5e86731d 100644 --- a/test/unit/lib/utils/getServerlessConfigFile.test.js +++ b/test/unit/lib/utils/getServerlessConfigFile.test.js @@ -32,7 +32,7 @@ describe('#getServerlessConfigFile()', () => { processedInput: { options: {} }, config: { servicePath: tmpDirPath }, }) - ).to.be.fulfilled.then(result => { + ).to.be.fulfilled.then((result) => { expect(result).to.equal(null); }); }); @@ -46,7 +46,7 @@ describe('#getServerlessConfigFile()', () => { processedInput: { options: {} }, config: { servicePath: tmpDirPath }, }) - ).to.be.fulfilled.then(result => { + ).to.be.fulfilled.then((result) => { expect(result).to.deep.equal({}); }); }); @@ -60,7 +60,7 @@ describe('#getServerlessConfigFile()', () => { processedInput: { options: {} }, config: { servicePath: tmpDirPath }, }) - ).to.be.fulfilled.then(result => { + ).to.be.fulfilled.then((result) => { expect(result).to.deep.equal({ service: 'my-yml-service' }); }); }); @@ -74,7 +74,7 @@ describe('#getServerlessConfigFile()', () => { processedInput: { options: {} }, config: { servicePath: tmpDirPath }, }) - ).to.be.fulfilled.then(result => { + ).to.be.fulfilled.then((result) => { expect(result).to.deep.equal({ service: 'my-yaml-service' }); }); }); @@ -88,7 +88,7 @@ describe('#getServerlessConfigFile()', () => { processedInput: { options: { config: 'foobar.yaml' } }, config: { servicePath: tmpDirPath }, }) - ).to.be.fulfilled.then(result => { + ).to.be.fulfilled.then((result) => { expect(result).to.deep.equal({ service: 'my-yaml-service' }); }); }); @@ -102,7 +102,7 @@ describe('#getServerlessConfigFile()', () => { processedInput: { options: {} }, config: { servicePath: tmpDirPath }, }) - ).to.be.fulfilled.then(result => { + ).to.be.fulfilled.then((result) => { expect(result).to.deep.equal({ service: 'my-json-service' }); }); }); @@ -116,7 +116,7 @@ describe('#getServerlessConfigFile()', () => { processedInput: { options: {} }, config: { servicePath: tmpDirPath }, }) - ).to.be.fulfilled.then(result => { + ).to.be.fulfilled.then((result) => { expect(result).to.deep.equal({ service: 'my-json-service' }); }); }); @@ -133,7 +133,7 @@ describe('#getServerlessConfigFile()', () => { processedInput: { options: {} }, config: { servicePath: tmpDirPath }, }) - ).to.be.fulfilled.then(result => { + ).to.be.fulfilled.then((result) => { expect(result).to.deep.equal({ service: 'my-json-service' }); }); }); @@ -162,11 +162,11 @@ describe('#getServerlessConfigFile()', () => { config: {}, }) ).to.be.fulfilled.then( - result => { + (result) => { process.chdir(cwd); expect(result).to.deep.equal({ service: 'my-yml-service' }); }, - error => { + (error) => { process.chdir(cwd); throw error; } @@ -185,7 +185,7 @@ describe('#getServerlessConfigFile()', () => { fixture: 'serverlessTs', cliArgs: ['package'], shouldStubSpawn: true, - }).catch(error => { + }).catch((error) => { if (error.code !== 'TS_NODE_NOT_FOUND') throw error; }); }); diff --git a/test/unit/lib/utils/logDeprecation.test.js b/test/unit/lib/utils/logDeprecation.test.js index 52b260fdea7..80ae859fed8 100644 --- a/test/unit/lib/utils/logDeprecation.test.js +++ b/test/unit/lib/utils/logDeprecation.test.js @@ -25,7 +25,7 @@ describe('#logDeprecation()', () => { it('Should log deprecation message if not disabled and first time', () => { let stdoutData = ''; overrideStdoutWrite( - data => (stdoutData += data), + (data) => (stdoutData += data), () => logDeprecation('CODE1', 'Start using deprecation log') ); expect(stdoutData).to.include('Start using deprecation log'); @@ -39,7 +39,7 @@ describe('#logDeprecation()', () => { logDeprecation = mockRequire.reRequire('../../../../lib/utils/logDeprecation'); let stdoutData = ''; overrideStdoutWrite( - data => (stdoutData += data), + (data) => (stdoutData += data), () => logDeprecation('CODE1', 'Start using deprecation log') ); expect(stdoutData).to.equal(''); @@ -56,7 +56,7 @@ describe('#logDeprecation()', () => { const serviceConfig = serverless.service; let stdoutData = ''; overrideStdoutWrite( - data => (stdoutData += data), + (data) => (stdoutData += data), () => logDeprecation('CODE1', 'Start using deprecation log', { serviceConfig }) ); expect(stdoutData).to.equal(''); @@ -68,7 +68,7 @@ describe('#logDeprecation()', () => { logDeprecation = mockRequire.reRequire('../../../../lib/utils/logDeprecation'); let stdoutData = ''; overrideStdoutWrite( - data => (stdoutData += data), + (data) => (stdoutData += data), () => logDeprecation('CODE1', 'Start using deprecation log') ); expect(stdoutData).to.equal(''); @@ -84,7 +84,7 @@ describe('#logDeprecation()', () => { const serviceConfig = serverless.service; let stdoutData = ''; overrideStdoutWrite( - data => (stdoutData += data), + (data) => (stdoutData += data), () => logDeprecation('CODE1', 'Start using deprecation log', { serviceConfig }) ); expect(stdoutData).to.equal(''); @@ -94,7 +94,7 @@ describe('#logDeprecation()', () => { it('Should not log deprecation twice', () => { let stdoutData = ''; overrideStdoutWrite( - data => (stdoutData += data), + (data) => (stdoutData += data), () => { logDeprecation('CODE1', 'Start using deprecation log'); expect(stdoutData).to.include('Start using deprecation log'); diff --git a/test/utils/apiGateway.js b/test/utils/apiGateway.js index 2861aa26982..361187f4f45 100644 --- a/test/utils/apiGateway.js +++ b/test/utils/apiGateway.js @@ -24,7 +24,7 @@ function getResources(restApiId) { restApiId, }; - return awsRequest('APIGateway', 'getResources', params).then(data => data.items); + return awsRequest('APIGateway', 'getResources', params).then((data) => data.items); } function findRestApis(name) { @@ -34,8 +34,8 @@ function findRestApis(name) { function recursiveFind(found, position) { if (position) params.position = position; - return awsRequest('APIGateway', 'getRestApis', params).then(result => { - const matches = result.items.filter(restApi => restApi.name.match(name)); + return awsRequest('APIGateway', 'getRestApis', params).then((result) => { + const matches = result.items.filter((restApi) => restApi.name.match(name)); if (matches.length) { _.merge(found, matches); } diff --git a/test/utils/awsCleanup.js b/test/utils/awsCleanup.js index b08a9f15883..d2a7d264121 100644 --- a/test/utils/awsCleanup.js +++ b/test/utils/awsCleanup.js @@ -13,7 +13,7 @@ async function findDeploymentBuckets(stacks) { const buckets = []; for (const stack of stacks) { const stackResources = await listStackResources(stack.StackId); - const bucket = stackResources.filter(resource => { + const bucket = stackResources.filter((resource) => { return resource.LogicalResourceId === 'ServerlessDeploymentBucket'; }); buckets.push(...bucket); @@ -44,9 +44,9 @@ async function cleanup() { ]); let bucketsToRemove = []; - const stacksToRemove = stacks.filter(stack => +new Date(stack.CreationTime) < yesterday); - const apisToRemove = apis.filter(api => +new Date(api.createdDate) < yesterday); - const userPoolsToRemove = userPools.filter(userPool => userPool.CreationDate < yesterday); + const stacksToRemove = stacks.filter((stack) => +new Date(stack.CreationTime) < yesterday); + const apisToRemove = apis.filter((api) => +new Date(api.createdDate) < yesterday); + const userPoolsToRemove = userPools.filter((userPool) => userPool.CreationDate < yesterday); if (stacksToRemove) { bucketsToRemove = await findDeploymentBuckets(stacksToRemove); @@ -59,7 +59,7 @@ async function cleanup() { if (bucketsToRemove.length) { logger.log('Removing Buckets...'); - const promises = bucketsToRemove.map(bucket => deleteBucket(bucket.PhysicalResourceId)); + const promises = bucketsToRemove.map((bucket) => deleteBucket(bucket.PhysicalResourceId)); try { await Promise.all(promises); } catch (error) { @@ -69,7 +69,7 @@ async function cleanup() { if (stacksToRemove.length) { logger.log('Removing Stacks...'); - const promises = stacksToRemove.map(stack => deleteStack(stack.StackName)); + const promises = stacksToRemove.map((stack) => deleteStack(stack.StackName)); try { await Promise.all(promises); } catch (error) { @@ -79,7 +79,7 @@ async function cleanup() { if (apisToRemove.length) { logger.log('Removing APIs...'); - const promises = apisToRemove.map(api => deleteRestApi(api.id)); + const promises = apisToRemove.map((api) => deleteRestApi(api.id)); try { await Promise.all(promises); } catch (error) { @@ -89,7 +89,7 @@ async function cleanup() { if (userPoolsToRemove.length) { logger.log('Removing User Pools...'); - const promises = userPoolsToRemove.map(userPool => deleteUserPoolById(userPool.Id)); + const promises = userPoolsToRemove.map((userPool) => deleteUserPoolById(userPool.Id)); try { await Promise.all(promises); } catch (error) { @@ -98,7 +98,7 @@ async function cleanup() { } } -cleanup().catch(error => { +cleanup().catch((error) => { // eslint-disable-next-line no-console console.error(error); process.exit(1); diff --git a/test/utils/cloudformation.js b/test/utils/cloudformation.js index 243b55d69ca..dc14d95c626 100644 --- a/test/utils/cloudformation.js +++ b/test/utils/cloudformation.js @@ -12,8 +12,8 @@ function findStacks(name, status) { function recursiveFind(found, token) { if (token) params.NextToken = token; - return awsRequest('CloudFormation', 'listStacks', params).then(result => { - const matches = result.StackSummaries.filter(stack => stack.StackName.match(name)); + return awsRequest('CloudFormation', 'listStacks', params).then((result) => { + const matches = result.StackSummaries.filter((stack) => stack.StackName.match(name)); if (matches.length) { found.push(...matches); } @@ -40,7 +40,7 @@ function listStackResources(stack) { function recursiveFind(resources, token) { if (token) params.NextToken = token; - return awsRequest('CloudFormation', 'listStackResources', params).then(result => { + return awsRequest('CloudFormation', 'listStackResources', params).then((result) => { resources.push(...result.StackResourceSummaries); if (result.NextToken) return recursiveFind(resources, result.NextToken); return resources; diff --git a/test/utils/cognito.js b/test/utils/cognito.js index 570112b6d14..e7b7f4f357d 100644 --- a/test/utils/cognito.js +++ b/test/utils/cognito.js @@ -18,7 +18,7 @@ function createUserPoolClient(name, userPoolId) { } function deleteUserPool(name) { - return findUserPoolByName(name).then(pool => + return findUserPoolByName(name).then((pool) => awsRequest('CognitoIdentityServiceProvider', 'deleteUserPool', { UserPoolId: pool.Id }) ); } @@ -37,8 +37,8 @@ function findUserPoolByName(name) { const pools = []; function recursiveFind(nextToken) { if (nextToken) params.NextToken = nextToken; - return awsRequest('CognitoIdentityServiceProvider', 'listUserPools', params).then(result => { - pools.push(...result.UserPools.filter(pool => pool.Name === name)); + return awsRequest('CognitoIdentityServiceProvider', 'listUserPools', params).then((result) => { + pools.push(...result.UserPools.filter((pool) => pool.Name === name)); if (result.NextToken) return recursiveFind(result.NextToken); switch (pools.length) { case 0: @@ -60,8 +60,8 @@ function findUserPools() { const pools = []; function recursiveFind(nextToken) { if (nextToken) params.NextToken = nextToken; - return awsRequest('CognitoIdentityServiceProvider', 'listUserPools', params).then(result => { - pools.push(...result.UserPools.filter(pool => pool.Name.includes(' CUP '))); + return awsRequest('CognitoIdentityServiceProvider', 'listUserPools', params).then((result) => { + pools.push(...result.UserPools.filter((pool) => pool.Name.includes(' CUP '))); if (result.NextToken) return recursiveFind(result.NextToken); return null; }); @@ -73,7 +73,7 @@ function findUserPools() { function describeUserPool(userPoolId) { return awsRequest('CognitoIdentityServiceProvider', 'describeUserPool', { UserPoolId: userPoolId, - }).then(result => { + }).then((result) => { awsLog.debug('cognito.describeUserPool %s %j', userPoolId, result); return result; }); diff --git a/test/utils/eventBridge.js b/test/utils/eventBridge.js index 9f1866c0350..3844d21d232 100644 --- a/test/utils/eventBridge.js +++ b/test/utils/eventBridge.js @@ -15,7 +15,7 @@ function describeEventBus(name) { } function putEvents(EventBusName, Entries) { - Entries.map(entry => (entry.EventBusName = EventBusName)); + Entries.map((entry) => (entry.EventBusName = EventBusName)); const params = { Entries, }; diff --git a/test/utils/fs.js b/test/utils/fs.js index 43633b65556..e162702e3e8 100644 --- a/test/utils/fs.js +++ b/test/utils/fs.js @@ -46,7 +46,7 @@ function writeYamlFile(filePath, content) { } function listZipFiles(filename) { - return new JSZip().loadAsync(fs.readFileSync(filename)).then(zip => Object.keys(zip.files)); + return new JSZip().loadAsync(fs.readFileSync(filename)).then((zip) => Object.keys(zip.files)); } module.exports = { diff --git a/test/utils/integration.js b/test/utils/integration.js index 44c6cdb9f94..5744df926a1 100644 --- a/test/utils/integration.js +++ b/test/utils/integration.js @@ -66,8 +66,8 @@ async function fetch(url, options) { .clone() .buffer() .then( - buffer => logFetch.debug('[%d] %s', requestId, String(buffer)), - error => logFetch.error('[%d] response resolution error: %o', requestId, error) + (buffer) => logFetch.debug('[%d] %s', requestId, String(buffer)), + (error) => logFetch.error('[%d] response resolution error: %o', requestId, error) ); return response; } diff --git a/test/utils/iot.js b/test/utils/iot.js index 63fd20914d7..d74db93b652 100644 --- a/test/utils/iot.js +++ b/test/utils/iot.js @@ -3,13 +3,13 @@ const awsRequest = require('@serverless/test/aws-request'); function resolveIotEndpoint() { - return awsRequest('Iot', 'describeEndpoint').then(data => { + return awsRequest('Iot', 'describeEndpoint').then((data) => { return data.endpointAddress; }); } function publishIotData(topic, message) { - return resolveIotEndpoint().then(endpoint => { + return resolveIotEndpoint().then((endpoint) => { const params = { topic, payload: Buffer.from(message), diff --git a/test/utils/kinesis.js b/test/utils/kinesis.js index 032aa076d0c..18100273a21 100644 --- a/test/utils/kinesis.js +++ b/test/utils/kinesis.js @@ -7,9 +7,9 @@ function waitForKinesisStream(streamName) { const params = { StreamName: streamName, }; - return new BbPromise(resolve => { + return new BbPromise((resolve) => { const interval = setInterval(() => { - awsRequest('Kinesis', 'describeStream', params).then(data => { + awsRequest('Kinesis', 'describeStream', params).then((data) => { const status = data.StreamDescription.StreamStatus; if (status === 'ACTIVE') { clearInterval(interval); diff --git a/test/utils/s3.js b/test/utils/s3.js index 93f676e1a3c..bb0e6a8d93b 100644 --- a/test/utils/s3.js +++ b/test/utils/s3.js @@ -24,11 +24,11 @@ function createAndRemoveInBucket(bucket, opts = {}) { } function emptyBucket(bucket) { - return awsRequest('S3', 'listObjects', { Bucket: bucket }).then(data => { + return awsRequest('S3', 'listObjects', { Bucket: bucket }).then((data) => { const items = data.Contents; const numItems = items.length; if (numItems) { - const keys = items.map(item => Object.assign({}, { Key: item.Key })); + const keys = items.map((item) => Object.assign({}, { Key: item.Key })); return awsRequest('S3', 'deleteObjects', { Bucket: bucket, Delete: { diff --git a/test/utils/sns.js b/test/utils/sns.js index d773fde73c8..18bcc8466b8 100644 --- a/test/utils/sns.js +++ b/test/utils/sns.js @@ -11,8 +11,8 @@ function createSnsTopic(topicName) { } function resolveTopicArn(topicName, nextToken = null) { - return awsRequest('SNS', 'listTopics', { NextToken: nextToken }).then(data => { - const targetTopic = data.Topics.find(topic => RegExp(topicName, 'g').test(topic.TopicArn)); + return awsRequest('SNS', 'listTopics', { NextToken: nextToken }).then((data) => { + const targetTopic = data.Topics.find((topic) => RegExp(topicName, 'g').test(topic.TopicArn)); if (targetTopic) return targetTopic.TopicArn; @@ -22,7 +22,7 @@ function resolveTopicArn(topicName, nextToken = null) { } function removeSnsTopic(topicName) { - return resolveTopicArn(topicName).then(topicArn => { + return resolveTopicArn(topicName).then((topicArn) => { const params = { TopicArn: topicArn, }; @@ -32,7 +32,7 @@ function removeSnsTopic(topicName) { } function publishSnsMessage(topicName, message, messageAttributes = null) { - return resolveTopicArn(topicName).then(topicArn => { + return resolveTopicArn(topicName).then((topicArn) => { const params = { Message: message, TopicArn: topicArn, diff --git a/test/utils/sqs.js b/test/utils/sqs.js index 4f07428b534..464a15df462 100644 --- a/test/utils/sqs.js +++ b/test/utils/sqs.js @@ -11,7 +11,7 @@ function createSqsQueue(queueName) { } function deleteSqsQueue(queueName) { - return awsRequest('SQS', 'getQueueUrl', { QueueName: queueName }).then(data => { + return awsRequest('SQS', 'getQueueUrl', { QueueName: queueName }).then((data) => { const params = { QueueUrl: data.QueueUrl, }; @@ -20,7 +20,7 @@ function deleteSqsQueue(queueName) { } function sendSqsMessage(queueName, message) { - return awsRequest('SQS', 'getQueueUrl', { QueueName: queueName }).then(data => { + return awsRequest('SQS', 'getQueueUrl', { QueueName: queueName }).then((data) => { const params = { QueueUrl: data.QueueUrl, MessageBody: message, diff --git a/test/utils/websocket.js b/test/utils/websocket.js index 37e25114fb3..3736a6ca173 100644 --- a/test/utils/websocket.js +++ b/test/utils/websocket.js @@ -33,7 +33,7 @@ function deleteStage(apiId, stageName) { } function getRoutes(apiId) { - return awsRequest('ApiGatewayV2', 'getRoutes', { ApiId: apiId }).then(data => data.Items); + return awsRequest('ApiGatewayV2', 'getRoutes', { ApiId: apiId }).then((data) => data.Items); } module.exports = {