diff --git a/browser.js b/browser.js index 3e67838..2d630cf 100644 --- a/browser.js +++ b/browser.js @@ -5,7 +5,7 @@ 'use strict'; -var Bootstrapper = require('./lib/bootstrapper'); +const Bootstrapper = require('./lib/bootstrapper'); /** * The browser version of `bootLoopBackApp`. @@ -26,18 +26,18 @@ var Bootstrapper = require('./lib/bootstrapper'); exports = module.exports = function bootBrowserApp(app, options, callback) { // Only using options.id to identify the browserified bundle to load for // this application. If no Id was provided, load the default bundle. - var moduleName = 'loopback-boot#instructions'; - var appId = options && typeof options === 'object' && options.appId; + let moduleName = 'loopback-boot#instructions'; + const appId = options && typeof options === 'object' && options.appId; if (appId) moduleName += '-' + appId; // The name of the module containing instructions // is hard-coded in lib/bundler - var instructions = require(moduleName); + const instructions = require(moduleName); - var bootstrapper = new Bootstrapper(options); + const bootstrapper = new Bootstrapper(options); bootstrapper.phases = ['starting', 'start', 'started']; - var context = { + const context = { app: app, instructions: instructions, }; diff --git a/index.js b/index.js index b67e6ef..0e7f59d 100644 --- a/index.js +++ b/index.js @@ -6,11 +6,11 @@ 'use strict'; // Strong globalize -var g = require('./lib/globalize'); +const g = require('./lib/globalize'); -var PluginBase = require('./lib/plugin-base'); -var Bootstrapper = require('./lib/bootstrapper'); -var addInstructionsToBrowserify = require('./lib/bundler'); +const PluginBase = require('./lib/plugin-base'); +const Bootstrapper = require('./lib/bootstrapper'); +const addInstructionsToBrowserify = require('./lib/bundler'); /** * Initialize an application from an options object or @@ -158,9 +158,9 @@ exports = module.exports = function bootLoopBackApp(app, options, callback) { // backwards compatibility with loopback's app.boot options.env = options.env || app.get('env'); - var bootstrapper = new Bootstrapper(options); + const bootstrapper = new Bootstrapper(options); - var context = { + const context = { bootstrapper: bootstrapper, app: app, }; @@ -169,9 +169,9 @@ exports = module.exports = function bootLoopBackApp(app, options, callback) { }; exports.compile = function(options, done) { - var bootstrapper = new Bootstrapper(options); + const bootstrapper = new Bootstrapper(options); bootstrapper.phases = ['load', 'compile']; - var context = {}; + const context = {}; return bootstrapper.run(context, done); }; @@ -199,10 +199,10 @@ exports.Bootstrapper = Bootstrapper; exports.PluginBase = PluginBase; exports.execute = function(app, instructions, done) { - var bootstrapper = new Bootstrapper( - {phases: ['starting', 'start', 'started']} + const bootstrapper = new Bootstrapper( + {phases: ['starting', 'start', 'started']}, ); - var context = { + const context = { app: app, instructions: instructions, }; diff --git a/lib/bootstrapper.js b/lib/bootstrapper.js index 5b3de6f..f6c2c02 100644 --- a/lib/bootstrapper.js +++ b/lib/bootstrapper.js @@ -5,21 +5,21 @@ 'use strict'; -var _ = require('lodash'); -var assert = require('assert'); -var async = require('async'); -var utils = require('./utils'); -var path = require('path'); -var pluginLoader = require('./plugin-loader'); -var debug = require('debug')('loopback:boot:bootstrapper'); -var Promise = require('bluebird'); -var arrayToObject = require('./utils').arrayToObject; +const _ = require('lodash'); +const assert = require('assert'); +const async = require('async'); +const utils = require('./utils'); +const path = require('path'); +const pluginLoader = require('./plugin-loader'); +const debug = require('debug')('loopback:boot:bootstrapper'); +const Promise = require('bluebird'); +const arrayToObject = require('./utils').arrayToObject; module.exports = Bootstrapper; function createPromiseCallback() { - var cb; - var promise = new Promise(function(resolve, reject) { + let cb; + const promise = new Promise(function(resolve, reject) { cb = function(err, data) { if (err) return reject(err); return resolve(data); @@ -29,22 +29,22 @@ function createPromiseCallback() { return cb; } -var builtinPlugins = [ +const builtinPlugins = [ 'application', 'datasource', 'model', 'mixin', 'middleware', 'component', 'boot-script', 'swagger', ]; -var builtinPhases = [ +const builtinPhases = [ 'load', 'compile', 'starting', 'start', 'started', ]; function loadAndRegisterPlugins(bootstrapper, options) { - var loader = pluginLoader(options); - var loaderContext = {}; + const loader = pluginLoader(options); + const loaderContext = {}; loader.load(loaderContext); loader.compile(loaderContext); - for (var i in loaderContext.instructions.pluginScripts) { + for (const i in loaderContext.instructions.pluginScripts) { bootstrapper.use('/boot/' + i, loaderContext.instructions.pluginScripts[i]); } } @@ -65,13 +65,13 @@ function Bootstrapper(options) { // For setting properties without modifying the original object options = Object.create(options); - var appRootDir = options.appRootDir = options.appRootDir || process.cwd(); - var env = options.env || process.env.NODE_ENV || 'development'; - var scriptExtensions = options.scriptExtensions ? + const appRootDir = options.appRootDir = options.appRootDir || process.cwd(); + const env = options.env || process.env.NODE_ENV || 'development'; + const scriptExtensions = options.scriptExtensions ? arrayToObject(options.scriptExtensions) : require.extensions; - var appConfigRootDir = options.appConfigRootDir || appRootDir; + const appConfigRootDir = options.appConfigRootDir || appRootDir; options.rootDir = appConfigRootDir; options.env = env; @@ -84,9 +84,9 @@ function Bootstrapper(options) { assert(Array.isArray(this.plugins), 'Invalid plugins: ' + this.builtinPlugins); - var self = this; + const self = this; self.builtinPlugins.forEach(function(p) { - var factory = require('./plugins/' + p); + const factory = require('./plugins/' + p); self.use('/boot/' + p, factory(options)); }); @@ -103,7 +103,7 @@ function Bootstrapper(options) { * @param {Function} handler */ Bootstrapper.prototype.use = function(path, handler) { - var plugin = { + const plugin = { path: path, handler: handler, }; @@ -135,7 +135,7 @@ Bootstrapper.prototype.getExtensions = function(path) { } return this.plugins.filter(function(p) { if (p.path.indexOf(path) === -1) return false; - var name = p.path.substring(path.length); + const name = p.path.substring(path.length); return name && name.indexOf('/') === -1; }); }; @@ -153,7 +153,7 @@ Bootstrapper.prototype.addPhases = function(phases) { function pluginIteratorFactory(context, phase) { return function executePluginPhase(plugin, done) { - var result; + let result; if (typeof plugin.handler[phase] !== 'function') { debug('Skipping %s.%s', plugin.handler.name, phase); return done(); @@ -190,24 +190,24 @@ Bootstrapper.prototype.run = function(context, done) { if (!done) { done = createPromiseCallback(); } - var options = this.options; - var appRootDir = options.appRootDir = options.appRootDir || process.cwd(); - var env = options.env || process.env.NODE_ENV || 'development'; + const options = this.options; + const appRootDir = options.appRootDir = options.appRootDir || process.cwd(); + const env = options.env || process.env.NODE_ENV || 'development'; - var appConfigRootDir = options.appConfigRootDir || appRootDir; + const appConfigRootDir = options.appConfigRootDir || appRootDir; options.rootDir = appConfigRootDir; options.env = env; context = context || {}; - var phases = context.phases || this.phases; + const phases = context.phases || this.phases; if (phases.includes('starting') || phases.includes('start')) { context.app.booting = true; } - var bootPlugins = this.getExtensions('/boot'); + const bootPlugins = this.getExtensions('/boot'); async.eachSeries(phases, function(phase, done) { debug('Phase %s', phase); async.eachSeries(bootPlugins, pluginIteratorFactory(context, phase), done); diff --git a/lib/bundler.js b/lib/bundler.js index 8932c6f..146c891 100644 --- a/lib/bundler.js +++ b/lib/bundler.js @@ -5,11 +5,11 @@ 'use strict'; -var fs = require('fs'); -var path = require('path'); -var commondir = require('commondir'); -var cloneDeep = require('lodash').cloneDeep; -var g = require('./globalize'); +const fs = require('fs'); +const path = require('path'); +const commondir = require('commondir'); +const cloneDeep = require('lodash').cloneDeep; +const g = require('./globalize'); /** * Add boot instructions to a browserify bundler. @@ -27,8 +27,8 @@ module.exports = function addInstructionsToBrowserify(context, bundler) { }; function addPlugins(bundler) { - var dir = path.join(__dirname, './plugins'); - var files = fs.readdirSync(dir); + const dir = path.join(__dirname, './plugins'); + const files = fs.readdirSync(dir); files.forEach(function(f) { bundler.require(path.join(dir, f), {expose: './plugins/' + path.basename(f, '.js')}); @@ -36,12 +36,12 @@ function addPlugins(bundler) { } function bundleOtherScripts(context, bundler) { - var list = context.instructions.bootScripts; + const list = context.instructions.bootScripts; addScriptsToBundle('boot', list, bundler); } function bundlePluginScripts(context, bundler) { - var list = context.instructions.pluginScripts; + const list = context.instructions.pluginScripts; addScriptsToBundle('plugins', list, bundler); } @@ -58,11 +58,11 @@ function bundleComponentScripts(context, bundler) { } function bundleSourceFiles(context, type, bundler) { - var files = context.instructions[type] + const files = context.instructions[type] .map(function(m) { return m.sourceFile; }) .filter(function(f) { return !!f; }); - var instructionToFileMapping = context.instructions[type] + const instructionToFileMapping = context.instructions[type] .map(function(m) { return files.indexOf(m.sourceFile); }); addScriptsToBundle(type, files, bundler); @@ -77,15 +77,16 @@ function bundleSourceFiles(context, type, bundler) { function addScriptsToBundle(name, list, bundler) { if (!list.length) return; - var root = commondir(list.map(path.dirname)); + const root = commondir(list.map(path.dirname)); - for (var ix in list) { - var filepath = list[ix]; + for (const ix in list) { + const filepath = list[ix]; // Build a short unique id that does not expose too much // information about the file system, but still preserves // useful information about where is the file coming from. - var fileid = 'loopback-boot#' + name + '#' + path.relative(root, filepath); + const fileid = + 'loopback-boot#' + name + '#' + path.relative(root, filepath); // Add the file to the bundle. bundler.require(filepath, {expose: fileid}); @@ -97,19 +98,19 @@ function addScriptsToBundle(name, list, bundler) { } function bundleInstructions(context, bundler) { - var instructions = cloneDeep(context.instructions); + const instructions = cloneDeep(context.instructions); - var hasMiddleware = instructions.middleware.phases.length || + const hasMiddleware = instructions.middleware.phases.length || instructions.middleware.middleware.length; if (hasMiddleware) { g.warn( 'Discarding {{middleware}} instructions,' + - ' {{loopback}} client does not support {{middleware}}.' + ' {{loopback}} client does not support {{middleware}}.', ); } delete instructions.middleware; - var instructionsString = JSON.stringify(instructions, null, 2); + const instructionsString = JSON.stringify(instructions, null, 2); /* The following code does not work due to a bug in browserify * https://github.com/substack/node-browserify/issues/771 @@ -119,7 +120,7 @@ function bundleInstructions(context, bundler) { b.require(instructionsStream, { expose: 'loopback-boot#instructions' }); */ - var instructionId = 'instructions'; + let instructionId = 'instructions'; // Create an unique instruction identifier using the application ID. // This is only useful when multiple loopback applications are being bundled // together. @@ -128,10 +129,10 @@ function bundleInstructions(context, bundler) { // Write the instructions to a file in our node_modules folder. // The location should not really matter as long as it is .gitignore-ed - var instructionsFile = path.resolve(__dirname, + const instructionsFile = path.resolve(__dirname, '..', 'generated-' + instructionId + '.json'); fs.writeFileSync(instructionsFile, instructionsString, 'utf-8'); - var moduleName = 'loopback-boot#' + instructionId; + const moduleName = 'loopback-boot#' + instructionId; bundler.require(instructionsFile, {expose: moduleName}); } diff --git a/lib/globalize.js b/lib/globalize.js index 64bdf32..3dabea9 100644 --- a/lib/globalize.js +++ b/lib/globalize.js @@ -5,7 +5,7 @@ 'use strict'; -var path = require('path'); -var SG = require('strong-globalize'); +const path = require('path'); +const SG = require('strong-globalize'); SG.SetRootDir(path.join(__dirname, '..'), {autonomousMsgLoading: 'all'}); module.exports = SG(); diff --git a/lib/plugin-base.js b/lib/plugin-base.js index 9138427..b17a3bc 100644 --- a/lib/plugin-base.js +++ b/lib/plugin-base.js @@ -5,13 +5,13 @@ 'use strict'; -var fs = require('fs'); -var path = require('path'); -var debug = require('debug')('loopback:boot:plugin'); -var assert = require('assert'); -var _ = require('lodash'); -var util = require('./utils'); -var g = require('./globalize'); +const fs = require('fs'); +const path = require('path'); +const debug = require('debug')('loopback:boot:plugin'); +const assert = require('assert'); +const _ = require('lodash'); +const util = require('./utils'); +const g = require('./globalize'); module.exports = PluginBase; @@ -26,11 +26,11 @@ PluginBase.prototype.getRootDir = function() { }; PluginBase.prototype.load = function(context) { - var rootDir = this.getRootDir() || this.options.rootDir; - var env = this.options.env; + const rootDir = this.getRootDir() || this.options.rootDir; + const env = this.options.env; assert(this.name, 'Plugin name must to be set'); debug('Root dir: %s, env: %s, artifact: %s', rootDir, env, this.artifact); - var config = {}; + let config = {}; if (this.options[this.name]) { // First check if options have the corresponding config object debug('Artifact: %s is using provided config obj instead' + @@ -67,7 +67,7 @@ PluginBase.prototype.merge = function(target, config, keyPrefix) { * @returns {Object} */ PluginBase.prototype.loadNamed = function(rootDir, env, name) { - var files = this.findConfigFiles(rootDir, env, name); + const files = this.findConfigFiles(rootDir, env, name); debug('Looking in dir %s for %s configs', rootDir, this.name); if (files.length) { debug('found %s %s files: %j', env, name, files); @@ -75,8 +75,8 @@ PluginBase.prototype.loadNamed = function(rootDir, env, name) { debug(' %s', f); }); } - var configs = this._loadConfigFiles(files); - var merged = this._mergeConfigurations(configs); + const configs = this._loadConfigFiles(files); + const merged = this._mergeConfigurations(configs); debug('merged %s %s configuration %j', env, name, merged); @@ -92,14 +92,14 @@ PluginBase.prototype.loadNamed = function(rootDir, env, name) { * @returns {Array.} Array of absolute file paths. */ PluginBase.prototype.findConfigFiles = function(rootDir, env, name, exts) { - var master = ifExists(name + '.json'); + const master = ifExists(name + '.json'); if (!master && (ifExistsWithAnyExt(name + '.local') || ifExistsWithAnyExt(name + '.' + env))) { g.warn('WARNING: Main config file "%s{{.json}}" is missing', name); } if (!master) return []; - var candidates = [ + const candidates = [ master, ifExistsWithAnyExt(name + '.local'), ifExistsWithAnyExt(name + '.' + env), @@ -110,14 +110,14 @@ PluginBase.prototype.findConfigFiles = function(rootDir, env, name, exts) { }); function ifExists(fileName) { - var filePath = path.resolve(rootDir, fileName); + const filePath = path.resolve(rootDir, fileName); return util.fileExistsSync(filePath) ? filePath : undefined; } function ifExistsWithAnyExt(fileName) { - var extensions = exts || ['js', 'json']; - var file; - for (var i = 0, n = extensions.length; i < n; i++) { + const extensions = exts || ['js', 'json']; + let file; + for (let i = 0, n = extensions.length; i < n; i++) { file = ifExists(fileName + '.' + extensions[i]); if (file) { return file; @@ -134,7 +134,7 @@ PluginBase.prototype.findConfigFiles = function(rootDir, env, name, exts) { */ PluginBase.prototype._loadConfigFiles = function(files) { return files.map(function(f) { - var config = require(f); + let config = require(f); config = _.cloneDeep(config); Object.defineProperty(config, '_filename', { enumerable: false, @@ -149,18 +149,18 @@ PluginBase.prototype._loadConfigFiles = function(files) { * @param {Array.} configObjects */ PluginBase.prototype._mergeConfigurations = function(configObjects) { - var result = configObjects.shift() || {}; + const result = configObjects.shift() || {}; while (configObjects.length) { - var next = configObjects.shift(); + const next = configObjects.shift(); this.merge(result, next, next._filename); } return result; }; PluginBase.prototype._mergeObjects = function(target, config, keyPrefix) { - for (var key in config) { - var fullKey = keyPrefix ? keyPrefix + '.' + key : key; - var err = this._mergeSingleItemOrProperty(target, config, key, fullKey); + for (const key in config) { + const fullKey = keyPrefix ? keyPrefix + '.' + key : key; + const err = this._mergeSingleItemOrProperty(target, config, key, fullKey); if (err) throw err; } return null; // no error @@ -170,12 +170,12 @@ PluginBase.prototype._mergeNamedItems = function(arr1, arr2, key) { assert(Array.isArray(arr1), 'invalid array: ' + arr1); assert(Array.isArray(arr2), 'invalid array: ' + arr2); key = key || 'name'; - var result = [].concat(arr1); - for (var i = 0, n = arr2.length; i < n; i++) { - var item = arr2[i]; - var found = false; + const result = [].concat(arr1); + for (let i = 0, n = arr2.length; i < n; i++) { + const item = arr2[i]; + let found = false; if (item[key]) { - for (var j = 0, k = result.length; j < k; j++) { + for (let j = 0, k = result.length; j < k; j++) { if (result[j][key] === item[key]) { this._mergeObjects(result[j], item); found = true; @@ -192,8 +192,8 @@ PluginBase.prototype._mergeNamedItems = function(arr1, arr2, key) { PluginBase.prototype._mergeSingleItemOrProperty = function(target, config, key, fullKey) { - var origValue = target[key]; - var newValue = config[key]; + const origValue = target[key]; + const newValue = config[key]; if (!hasCompatibleType(origValue, newValue)) { return 'Cannot merge values of incompatible types for the option `' + @@ -219,9 +219,9 @@ PluginBase.prototype._mergeArrays = function(target, config, keyPrefix) { } // Use for(;;) to iterate over undefined items, for(in) would skip them. - for (var ix = 0; ix < target.length; ix++) { - var fullKey = keyPrefix + '[' + ix + ']'; - var err = this._mergeSingleItemOrProperty(target, config, ix, fullKey); + for (let ix = 0; ix < target.length; ix++) { + const fullKey = keyPrefix + '[' + ix + ']'; + const err = this._mergeSingleItemOrProperty(target, config, ix, fullKey); if (err) return err; } @@ -244,10 +244,10 @@ function hasCompatibleType(origValue, newValue) { } PluginBase.prototype.compile = function(context) { - var instructions; + let instructions; if (typeof this.buildInstructions === 'function') { - var rootDir = this.options.rootDir; - var config = context.configurations[this.name] || {}; + const rootDir = this.options.rootDir; + const config = context.configurations[this.name] || {}; instructions = this.buildInstructions(context, rootDir, config); } else { instructions = context.configurations[this.name]; @@ -265,12 +265,12 @@ PluginBase.prototype.compile = function(context) { return undefined; }; -var DYNAMIC_CONFIG_PARAM = /\$\{(\w+)\}$/; +const DYNAMIC_CONFIG_PARAM = /\$\{(\w+)\}$/; function getConfigVariable(app, param, useEnvVars) { - var configVariable = param; - var match = configVariable.match(DYNAMIC_CONFIG_PARAM); + let configVariable = param; + const match = configVariable.match(DYNAMIC_CONFIG_PARAM); if (match) { - var varName = match[1]; + const varName = match[1]; if (useEnvVars && process.env[varName] !== undefined) { debug('Dynamic Configuration: Resolved via process.env: %s as %s', process.env[varName], param); @@ -278,7 +278,7 @@ function getConfigVariable(app, param, useEnvVars) { } else if (app.get(varName) !== undefined) { debug('Dynamic Configuration: Resolved via app.get(): %s as %s', app.get(varName), param); - var appValue = app.get(varName); + const appValue = app.get(varName); configVariable = appValue; } else { // previously it returns the original string such as "${restApiRoot}" @@ -296,8 +296,8 @@ function getConfigVariable(app, param, useEnvVars) { } PluginBase.prototype.getUpdatedConfigObject = function(context, config, opts) { - var app = context.app; - var useEnvVars = opts && opts.useEnvVars; + const app = context.app; + const useEnvVars = opts && opts.useEnvVars; function interpolateVariables(config) { // config is a string and contains a config variable ('${var}') @@ -317,9 +317,9 @@ PluginBase.prototype.getUpdatedConfigObject = function(context, config, opts) { return config; // recurse into object props - var interpolated = {}; + const interpolated = {}; Object.keys(config).forEach(function(configKey) { - var value = config[configKey]; + const value = config[configKey]; if (Array.isArray(value)) { interpolated[configKey] = value.map(interpolateVariables); } else if (typeof value === 'string') { diff --git a/lib/plugin-loader.js b/lib/plugin-loader.js index bc01d36..1fec706 100644 --- a/lib/plugin-loader.js +++ b/lib/plugin-loader.js @@ -5,13 +5,13 @@ 'use strict'; -var util = require('util'); -var utils = require('./utils'); -var path = require('path'); -var async = require('async'); -var debug = require('debug')('loopback:boot:plugin-loader'); -var PluginBase = require('./plugin-base'); -var _ = require('lodash'); +const util = require('util'); +const utils = require('./utils'); +const path = require('path'); +const async = require('async'); +const debug = require('debug')('loopback:boot:plugin-loader'); +const PluginBase = require('./plugin-base'); +const _ = require('lodash'); module.exports = function(options) { return new PluginScript(options); @@ -24,23 +24,23 @@ function PluginScript(options) { util.inherits(PluginScript, PluginBase); PluginScript.prototype.load = function(context) { - var options = this.options; - var appRootDir = options.rootDir; + const options = this.options; + const appRootDir = options.rootDir; // require directories - var pluginDirs = options.pluginDirs || []; // precedence + let pluginDirs = options.pluginDirs || []; // precedence pluginDirs = pluginDirs.concat(path.join(appRootDir, 'plugins')); utils.resolveRelativePaths(pluginDirs, appRootDir); - var pluginScripts = options.pluginScripts || []; + let pluginScripts = options.pluginScripts || []; utils.resolveRelativePaths(pluginScripts, appRootDir); pluginDirs.forEach(function(dir) { pluginScripts = pluginScripts.concat( - utils.findScripts(dir, options.scriptExtensions) + utils.findScripts(dir, options.scriptExtensions), ); - var envdir = dir + '/' + options.env; + const envdir = dir + '/' + options.env; pluginScripts = pluginScripts.concat( - utils.findScripts(envdir, options.scriptExtensions) + utils.findScripts(envdir, options.scriptExtensions), ); }); @@ -51,15 +51,15 @@ PluginScript.prototype.load = function(context) { }; PluginScript.prototype.compile = function(context) { - var pluginScripts = context.configurations.pluginScripts; + const pluginScripts = context.configurations.pluginScripts; context.instructions = context.instructions || {}; - var plugins = context.instructions.pluginScripts = {}; - var self = this; + const plugins = context.instructions.pluginScripts = {}; + const self = this; pluginScripts.forEach(function(ps) { debug('Loading %s', ps); - var factory = require(ps); - var handler = factory(self.options); - var name = handler.name || path.basename(ps, '.js'); + const factory = require(ps); + const handler = factory(self.options); + const name = handler.name || path.basename(ps, '.js'); debug('Loaded plugin name: %s', name); plugins[name] = handler; }); diff --git a/lib/plugins/application.js b/lib/plugins/application.js index 46f56bc..5779b2c 100644 --- a/lib/plugins/application.js +++ b/lib/plugins/application.js @@ -5,11 +5,11 @@ 'use strict'; -var util = require('util'); -var assert = require('assert'); -var semver = require('semver'); -var PluginBase = require('../plugin-base'); -var g = require('../globalize'); +const util = require('util'); +const assert = require('assert'); +const semver = require('semver'); +const PluginBase = require('../plugin-base'); +const g = require('../globalize'); module.exports = function(options) { return new Application(options); @@ -22,19 +22,19 @@ function Application(options) { util.inherits(Application, PluginBase); function assertLoopBackVersion(app) { - var RANGE = '2.x || 3.x'; + const RANGE = '2.x || 3.x'; - var loopback = app.loopback; + const loopback = app.loopback; // remove any pre-release tag from the version string, // because semver has special treatment of pre-release versions, // while loopback-boot treats pre-releases the same way as regular versions - var version = (loopback.version || '1.0.0').replace(/-.*$/, ''); + const version = (loopback.version || '1.0.0').replace(/-.*$/, ''); if (!semver.satisfies(version, RANGE)) { - var msg = g.f( + const msg = g.f( 'The `app` is powered by an incompatible loopback version %s. ' + 'Supported versions: %s', loopback.version || '(unknown)', - RANGE + RANGE, ); throw new Error(msg); } @@ -47,7 +47,7 @@ function setEnv(app, env) { function setHost(app, appConfig) { // jscs:disable requireCamelCaseOrUpperCaseIdentifiers - var host = + const host = process.env.npm_config_host || process.env.OPENSHIFT_SLS_IP || process.env.OPENSHIFT_NODEJS_IP || @@ -65,7 +65,7 @@ function setHost(app, appConfig) { function setPort(app, appConfig) { // jscs:disable requireCamelCaseOrUpperCaseIdentifiers - var port = find([ + const port = find([ process.env.npm_config_port, process.env.OPENSHIFT_SLS_PORT, process.env.OPENSHIFT_NODEJS_PORT, @@ -80,7 +80,7 @@ function setPort(app, appConfig) { }); if (port !== undefined) { - var portType = typeof port; + const portType = typeof port; assert(portType === 'string' || portType === 'number', 'app.port must be a string or number'); app.set('port', port); @@ -92,7 +92,7 @@ function find(array, predicate) { } function setApiRoot(app, appConfig) { - var restApiRoot = + const restApiRoot = appConfig.restApiRoot || app.get('restApiRoot') || '/api'; @@ -106,8 +106,8 @@ function setApiRoot(app, appConfig) { } function applyAppConfig(app, appConfig) { - for (var configKey in appConfig) { - var cur = app.get(configKey); + for (const configKey in appConfig) { + const cur = app.get(configKey); if (cur === undefined || cur === null) { app.set(configKey, appConfig[configKey]); } @@ -115,10 +115,10 @@ function applyAppConfig(app, appConfig) { } Application.prototype.starting = function(context) { - var app = context.app; + const app = context.app; assertLoopBackVersion(app); - var appConfig = context.instructions.application; + const appConfig = context.instructions.application; setEnv(app, context.instructions.env || this.options.env); setHost(app, appConfig); setPort(app, appConfig); @@ -127,7 +127,7 @@ Application.prototype.starting = function(context) { }; Application.prototype.started = function(context, done) { - var app = context.app; + const app = context.app; process.nextTick(function() { app.emit('booted'); done(); diff --git a/lib/plugins/boot-script.js b/lib/plugins/boot-script.js index a0eb80c..ce54926 100644 --- a/lib/plugins/boot-script.js +++ b/lib/plugins/boot-script.js @@ -5,14 +5,14 @@ 'use strict'; -var util = require('util'); -var utils = require('../utils'); -var path = require('path'); -var async = require('async'); -var debug = require('debug')('loopback:boot:script'); -var PluginBase = require('../plugin-base'); -var _ = require('lodash'); -var g = require('../globalize'); +const util = require('util'); +const utils = require('../utils'); +const path = require('path'); +const async = require('async'); +const debug = require('debug')('loopback:boot:script'); +const PluginBase = require('../plugin-base'); +const _ = require('lodash'); +const g = require('../globalize'); module.exports = function(options) { return new Script(options); @@ -25,23 +25,23 @@ function Script(options) { util.inherits(Script, PluginBase); Script.prototype.load = function(context) { - var options = this.options; - var appRootDir = options.rootDir; + const options = this.options; + const appRootDir = options.rootDir; // require directories - var bootDirs = options.bootDirs || []; // precedence + let bootDirs = options.bootDirs || []; // precedence bootDirs = bootDirs.concat(path.join(appRootDir, 'boot')); utils.resolveRelativePaths(bootDirs, appRootDir); - var bootScripts = options.bootScripts || []; + let bootScripts = options.bootScripts || []; utils.resolveRelativePaths(bootScripts, appRootDir); bootDirs.forEach(function(dir) { bootScripts = bootScripts.concat( - utils.findScripts(dir, options.scriptExtensions) + utils.findScripts(dir, options.scriptExtensions), ); - var envdir = dir + '/' + options.env; + const envdir = dir + '/' + options.env; bootScripts = bootScripts.concat( - utils.findScripts(envdir, options.scriptExtensions) + utils.findScripts(envdir, options.scriptExtensions), ); }); @@ -54,18 +54,18 @@ Script.prototype.load = function(context) { }; Script.prototype.start = function(context, done) { - var app = context.app; - var instructions = context.instructions[this.name]; + const app = context.app; + const instructions = context.instructions[this.name]; runScripts(app, instructions, done); }; function runScripts(app, list, callback) { list = list || []; - var functions = []; + const functions = []; list.forEach(function(filepath) { debug('Requiring script %s', filepath); try { - var exports = require(filepath); + let exports = require(filepath); if (exports.__esModule) exports = exports.default; if (typeof exports === 'function') { debug('Exported function detected %s', filepath); @@ -82,7 +82,7 @@ function runScripts(app, list, callback) { async.eachSeries(functions, function(f, done) { debug('Running script %s', f.path); - var cb = function(err) { + let cb = function(err) { debug('Async function %s %s', err ? 'failed' : 'finished', f.path); done(err); // Make sure done() isn't called twice, e.g. if a script returns a @@ -90,7 +90,7 @@ function runScripts(app, list, callback) { cb = function() {}; }; try { - var result = f.func(app, cb); + const result = f.func(app, cb); if (result && typeof result.then === 'function') { result.then(function() { cb(); }, cb); } else if (f.func.length < 2) { diff --git a/lib/plugins/component.js b/lib/plugins/component.js index 9d4c722..7a49795 100644 --- a/lib/plugins/component.js +++ b/lib/plugins/component.js @@ -5,13 +5,13 @@ 'use strict'; -var util = require('util'); -var debug = require('debug')('loopback:boot:component'); -var PluginBase = require('../plugin-base'); +const util = require('util'); +const debug = require('debug')('loopback:boot:component'); +const PluginBase = require('../plugin-base'); -var utils = require('../utils'); +const utils = require('../utils'); -var resolveAppScriptPath = utils.resolveAppScriptPath; +const resolveAppScriptPath = utils.resolveAppScriptPath; module.exports = function(options) { return new Component(options); @@ -40,11 +40,11 @@ Component.prototype.buildInstructions = function(context, rootDir, config) { }; Component.prototype.start = function(context) { - var app = context.app; - var self = this; + const app = context.app; + const self = this; context.instructions[this.name].forEach(function(data) { debug('Configuring component %j', data.sourceFile); - var configFn = require(data.sourceFile); + const configFn = require(data.sourceFile); data.config = self.getUpdatedConfigObject(context, data.config, {useEnvVars: true}); configFn(app, data.config); diff --git a/lib/plugins/datasource.js b/lib/plugins/datasource.js index 62ccdd1..bfcdede 100644 --- a/lib/plugins/datasource.js +++ b/lib/plugins/datasource.js @@ -5,10 +5,10 @@ 'use strict'; -var util = require('util'); -var utils = require('../utils'); -var PluginBase = require('../plugin-base'); -var debug = require('debug')('loopback:boot:datasource'); +const util = require('util'); +const utils = require('../utils'); +const PluginBase = require('../plugin-base'); +const debug = require('debug')('loopback:boot:datasource'); module.exports = function(options) { return new DataSource(options); @@ -25,9 +25,9 @@ DataSource.prototype.getRootDir = function() { }; DataSource.prototype.start = function(context) { - var app = context.app; - var self = this; - var lazyConnect = process.env.LB_LAZYCONNECT_DATASOURCES; + const app = context.app; + const self = this; + const lazyConnect = process.env.LB_LAZYCONNECT_DATASOURCES; utils.forEachKeyedObject(context.instructions[this.name], function(key, obj) { obj = self.getUpdatedConfigObject(context, obj, {useEnvVars: true}); debug('Registering data source %s %j', key, obj); diff --git a/lib/plugins/middleware.js b/lib/plugins/middleware.js index 25e4c52..858eb47 100644 --- a/lib/plugins/middleware.js +++ b/lib/plugins/middleware.js @@ -5,18 +5,18 @@ 'use strict'; -var util = require('util'); -var assert = require('assert'); -var path = require('path'); -var _ = require('lodash'); -var cloneDeepWith = _.cloneDeepWith; -var cloneDeep = _.cloneDeep; -var debug = require('debug')('loopback:boot:middleware'); -var PluginBase = require('../plugin-base'); -var utils = require('../utils'); -var g = require('../globalize'); +const util = require('util'); +const assert = require('assert'); +const path = require('path'); +const _ = require('lodash'); +const cloneDeepWith = _.cloneDeepWith; +const cloneDeep = _.cloneDeep; +const debug = require('debug')('loopback:boot:middleware'); +const PluginBase = require('../plugin-base'); +const utils = require('../utils'); +const g = require('../globalize'); -var resolveAppScriptPath = utils.resolveAppScriptPath; +const resolveAppScriptPath = utils.resolveAppScriptPath; module.exports = function(options) { return new Middleware(options); @@ -33,7 +33,7 @@ Middleware.prototype.getRootDir = function() { }; Middleware.prototype.merge = function(target, config, fileName) { - var err, phase; + let err, phase; for (phase in config) { if (phase in target) { err = this.mergePhaseConfig(target[phase], config[phase], phase); @@ -46,11 +46,11 @@ Middleware.prototype.merge = function(target, config, fileName) { }; Middleware.prototype.mergePhaseConfig = function(target, config, phase) { - var err, mw; + let err, mw; for (mw in config) { if (mw in target) { - var targetMiddleware = target[mw]; - var configMiddleware = config[mw]; + const targetMiddleware = target[mw]; + const configMiddleware = config[mw]; if (Array.isArray(targetMiddleware) && Array.isArray(configMiddleware)) { // Both are arrays, combine them target[mw] = this._mergeNamedItems(targetMiddleware, configMiddleware); @@ -83,18 +83,18 @@ Middleware.prototype.mergePhaseConfig = function(target, config, phase) { }; Middleware.prototype.buildInstructions = function(context, rootDir, config) { - var phasesNames = Object.keys(config); - var middlewareList = []; + const phasesNames = Object.keys(config); + const middlewareList = []; phasesNames.forEach(function(phase) { - var phaseConfig = config[phase]; + const phaseConfig = config[phase]; Object.keys(phaseConfig).forEach(function(middleware) { - var allConfigs = phaseConfig[middleware]; + let allConfigs = phaseConfig[middleware]; if (!Array.isArray(allConfigs)) allConfigs = [allConfigs]; allConfigs.forEach(function(config) { - var resolved = resolveMiddlewarePath(rootDir, middleware, config); + const resolved = resolveMiddlewarePath(rootDir, middleware, config); // resolved.sourceFile will be false-y if an optional middleware // is not resolvable. // if a non-optional middleware is not resolvable, it will throw @@ -105,16 +105,16 @@ Middleware.prototype.buildInstructions = function(context, rootDir, config) { resolved.optional); } - var middlewareConfig = cloneDeep(config); + const middlewareConfig = cloneDeep(config); middlewareConfig.phase = phase; if (middlewareConfig.params) { middlewareConfig.params = resolveMiddlewareParams( - rootDir, middlewareConfig.params + rootDir, middlewareConfig.params, ); } - var item = { + const item = { sourceFile: resolved.sourceFile, config: middlewareConfig, }; @@ -126,7 +126,7 @@ Middleware.prototype.buildInstructions = function(context, rootDir, config) { }); }); - var flattenedPhaseNames = phasesNames + const flattenedPhaseNames = phasesNames .map(function getBaseName(name) { return name.replace(/:[^:]+$/, ''); }) @@ -143,15 +143,15 @@ Middleware.prototype.buildInstructions = function(context, rootDir, config) { }; function resolveMiddlewarePath(rootDir, middleware, config) { - var resolved = { + const resolved = { optional: !!config.optional, }; - var segments = middleware.split('#'); - var pathName = segments[0]; - var fragment = segments[1]; - var middlewarePath = pathName; - var opts = { + const segments = middleware.split('#'); + let pathName = segments[0]; + const fragment = segments[1]; + const middlewarePath = pathName; + const opts = { strict: true, optional: !!config.optional, }; @@ -165,7 +165,7 @@ function resolveMiddlewarePath(rootDir, middleware, config) { pathName = path.resolve(rootDir, pathName); } - var resolveOpts = _.extend(opts, { + const resolveOpts = _.extend(opts, { // Workaround for strong-agent to allow probes to detect that // strong-express-middleware was loaded: exclude the path to the // module main file from the source file path. @@ -175,7 +175,7 @@ function resolveMiddlewarePath(rootDir, middleware, config) { // node_modules/strong-express-metrics/index.js fullResolve: false, }); - var sourceFile = resolveAppScriptPath(rootDir, middlewarePath, resolveOpts); + const sourceFile = resolveAppScriptPath(rootDir, middlewarePath, resolveOpts); if (!fragment) { resolved.sourceFile = sourceFile; @@ -184,7 +184,7 @@ function resolveMiddlewarePath(rootDir, middleware, config) { // Try to require the module and check if . is a valid // function - var m = require(sourceFile); + const m = require(sourceFile); if (typeof m[fragment] === 'function') { resolved.sourceFile = sourceFile; return resolved; @@ -194,7 +194,7 @@ function resolveMiddlewarePath(rootDir, middleware, config) { * module/server/middleware/fragment * module/middleware/fragment */ - var candidates = [ + const candidates = [ pathName + '/server/middleware/' + fragment, pathName + '/middleware/' + fragment, // TODO: [rfeng] Should we support the following flavors? @@ -202,7 +202,7 @@ function resolveMiddlewarePath(rootDir, middleware, config) { // pathName + '/' + fragment ]; - var err, ix; + let err, ix; for (ix in candidates) { try { resolved.sourceFile = resolveAppScriptPath(rootDir, candidates[ix], opts); @@ -217,7 +217,7 @@ function resolveMiddlewarePath(rootDir, middleware, config) { } // Match values starting with `$!./` or `$!../` -var MIDDLEWARE_PATH_PARAM_REGEX = /^\$!(\.\/|\.\.\/)/; +const MIDDLEWARE_PATH_PARAM_REGEX = /^\$!(\.\/|\.\.\/)/; function resolveMiddlewareParams(rootDir, params) { return cloneDeepWith(params, function resolvePathParam(value) { @@ -230,20 +230,20 @@ function resolveMiddlewareParams(rootDir, params) { } Middleware.prototype.start = function(context) { - var self = this; - var app = context.app; - var instructions = context.instructions.middleware; + const self = this; + const app = context.app; + const instructions = context.instructions.middleware; if (!instructions) { // the browserified client does not support middleware return; } // Phases can be empty - var phases = instructions.phases || []; + const phases = instructions.phases || []; assert(Array.isArray(phases), 'Middleware phases must be an array'); - var middleware = instructions.middleware; + const middleware = instructions.middleware; assert(Array.isArray(middleware), 'Middleware must be an array'); @@ -253,7 +253,7 @@ Middleware.prototype.start = function(context) { middleware.forEach(function(data) { debug('Configuring middleware %j%s', data.sourceFile, data.fragment ? ('#' + data.fragment) : ''); - var factory = require(data.sourceFile); + let factory = require(data.sourceFile); if (data.fragment) { factory = factory[data.fragment].bind(factory); } diff --git a/lib/plugins/mixin.js b/lib/plugins/mixin.js index f828899..f2c17b5 100644 --- a/lib/plugins/mixin.js +++ b/lib/plugins/mixin.js @@ -5,19 +5,19 @@ 'use strict'; -var util = require('util'); -var fs = require('fs'); -var path = require('path'); -var PluginBase = require('../plugin-base'); -var _ = require('lodash'); -var debug = require('debug')('loopback:boot:mixin'); -var utils = require('../utils'); -var g = require('../globalize'); +const util = require('util'); +const fs = require('fs'); +const path = require('path'); +const PluginBase = require('../plugin-base'); +const _ = require('lodash'); +const debug = require('debug')('loopback:boot:mixin'); +const utils = require('../utils'); +const g = require('../globalize'); -var tryResolveAppPath = utils.tryResolveAppPath; -var getExcludedExtensions = utils.getExcludedExtensions; -var findScripts = utils.findScripts; -var FILE_EXTENSION_JSON = utils.FILE_EXTENSION_JSON; +const tryResolveAppPath = utils.tryResolveAppPath; +const getExcludedExtensions = utils.getExcludedExtensions; +const findScripts = utils.findScripts; +const FILE_EXTENSION_JSON = utils.FILE_EXTENSION_JSON; module.exports = function(options) { return new Mixin(options); @@ -30,14 +30,14 @@ function Mixin(options) { util.inherits(Mixin, PluginBase); Mixin.prototype.buildInstructions = function(context, rootDir, config) { - var modelsMeta = context.configurations.mixins._meta || {}; - var modelInstructions = context.instructions.models; - var mixinSources = this.options.mixinSources || modelsMeta.mixins || + const modelsMeta = context.configurations.mixins._meta || {}; + const modelInstructions = context.instructions.models; + const mixinSources = this.options.mixinSources || modelsMeta.mixins || ['./mixins']; - var scriptExtensions = this.options.scriptExtensions || require.extensions; + const scriptExtensions = this.options.scriptExtensions || require.extensions; - var mixinInstructions = buildAllMixinInstructions( - rootDir, this.options, mixinSources, scriptExtensions, modelInstructions + const mixinInstructions = buildAllMixinInstructions( + rootDir, this.options, mixinSources, scriptExtensions, modelInstructions, ); return mixinInstructions; @@ -46,14 +46,14 @@ Mixin.prototype.buildInstructions = function(context, rootDir, config) { function buildAllMixinInstructions(appRootDir, options, mixinSources, scriptExtensions, modelInstructions) { // load mixins from `options.mixins` - var sourceFiles = options.mixins || []; - var mixinDirs = options.mixinDirs || []; - var instructionsFromMixins = loadMixins(sourceFiles, options.normalization); + let sourceFiles = options.mixins || []; + const mixinDirs = options.mixinDirs || []; + const instructionsFromMixins = loadMixins(sourceFiles, options.normalization); // load mixins from `options.mixinDirs` sourceFiles = findMixinDefinitions(appRootDir, mixinDirs, scriptExtensions); if (sourceFiles === undefined) return; - var instructionsFromMixinDirs = loadMixins(sourceFiles, + const instructionsFromMixinDirs = loadMixins(sourceFiles, options.normalization); /* If `mixinDirs` and `mixinSources` have any directories in common, @@ -64,31 +64,31 @@ function buildAllMixinInstructions(appRootDir, options, mixinSources, sourceFiles = findMixinDefinitions(appRootDir, mixinSources, scriptExtensions); if (sourceFiles === undefined) return; - var instructionsFromMixinSources = loadMixins(sourceFiles, + let instructionsFromMixinSources = loadMixins(sourceFiles, options.normalization); // Fetch unique list of mixin names, used in models - var modelMixins = fetchMixinNamesUsedInModelInstructions(modelInstructions); + let modelMixins = fetchMixinNamesUsedInModelInstructions(modelInstructions); modelMixins = _.uniq(modelMixins); // Filter-in only mixins, that are used in models instructionsFromMixinSources = filterMixinInstructionsUsingWhitelist( - instructionsFromMixinSources, modelMixins + instructionsFromMixinSources, modelMixins, ); - var mixins = _.assign( + const mixins = _.assign( instructionsFromMixins, instructionsFromMixinDirs, - instructionsFromMixinSources + instructionsFromMixinSources, ); return _.values(mixins); } function findMixinDefinitions(appRootDir, sourceDirs, scriptExtensions) { - var files = []; + let files = []; sourceDirs.forEach(function(dir) { - var path = tryResolveAppPath(appRootDir, dir); + const path = tryResolveAppPath(appRootDir, dir); if (!path) { debug('Skipping unknown module source dir %j', dir); return; @@ -99,15 +99,15 @@ function findMixinDefinitions(appRootDir, sourceDirs, scriptExtensions) { } function loadMixins(sourceFiles, normalization) { - var mixinInstructions = {}; + const mixinInstructions = {}; sourceFiles.forEach(function(filepath) { - var dir = path.dirname(filepath); - var ext = path.extname(filepath); - var name = path.basename(filepath, ext); - var metafile = path.join(dir, name + FILE_EXTENSION_JSON); + const dir = path.dirname(filepath); + const ext = path.extname(filepath); + let name = path.basename(filepath, ext); + const metafile = path.join(dir, name + FILE_EXTENSION_JSON); name = normalizeMixinName(name, normalization); - var meta = {}; + const meta = {}; meta.name = name; if (utils.fileExistsSync(metafile)) { // May overwrite name, not sourceFile @@ -129,10 +129,10 @@ function fetchMixinNamesUsedInModelInstructions(modelInstructions) { } function filterMixinInstructionsUsingWhitelist(instructions, includeMixins) { - var instructionKeys = Object.keys(instructions); + const instructionKeys = Object.keys(instructions); includeMixins = _.intersection(instructionKeys, includeMixins); - var filteredInstructions = {}; + const filteredInstructions = {}; instructionKeys.forEach(function(mixinName) { if (includeMixins.indexOf(mixinName) !== -1) { filteredInstructions[mixinName] = instructions[mixinName]; @@ -168,7 +168,7 @@ function normalizeMixinName(str, normalization) { return normalization(str); } - var err = new Error(g.f('Invalid normalization format - "%s"', + const err = new Error(g.f('Invalid normalization format - "%s"', normalization)); err.code = 'INVALID_NORMALIZATION_FORMAT'; throw err; @@ -176,18 +176,18 @@ function normalizeMixinName(str, normalization) { } Mixin.prototype.starting = function(context) { - var app = context.app; - var instructions = context.instructions.mixins; + const app = context.app; + const instructions = context.instructions.mixins; - var modelBuilder = (app.registry || app.loopback).modelBuilder; - var BaseClass = app.loopback.Model; - var mixins = instructions || []; + const modelBuilder = (app.registry || app.loopback).modelBuilder; + const BaseClass = app.loopback.Model; + const mixins = instructions || []; if (!modelBuilder.mixins || !mixins.length) return; mixins.forEach(function(obj) { debug('Requiring mixin %s', obj.sourceFile); - var mixin = require(obj.sourceFile); + const mixin = require(obj.sourceFile); if (typeof mixin === 'function' || mixin.prototype instanceof BaseClass) { debug('Defining mixin %s', obj.name); diff --git a/lib/plugins/model.js b/lib/plugins/model.js index f30b5a6..e8366e0 100644 --- a/lib/plugins/model.js +++ b/lib/plugins/model.js @@ -5,20 +5,20 @@ 'use strict'; -var assert = require('assert'); -var util = require('util'); -var PluginBase = require('../plugin-base'); -var path = require('path'); -var debug = require('debug')('loopback:boot:model'); -var _ = require('lodash'); -var toposort = require('toposort'); -var utils = require('../utils'); +const assert = require('assert'); +const util = require('util'); +const PluginBase = require('../plugin-base'); +const path = require('path'); +const debug = require('debug')('loopback:boot:model'); +const _ = require('lodash'); +const toposort = require('toposort'); +const utils = require('../utils'); -var tryReadDir = utils.tryReadDir; -var assertIsValidConfig = utils.assertIsValidConfig; -var tryResolveAppPath = utils.tryResolveAppPath; -var fixFileExtension = utils.fixFileExtension; -var g = require('../globalize'); +const tryReadDir = utils.tryReadDir; +const assertIsValidConfig = utils.assertIsValidConfig; +const tryResolveAppPath = utils.tryResolveAppPath; +const fixFileExtension = utils.fixFileExtension; +const g = require('../globalize'); module.exports = function(options) { return new Model(options); @@ -35,39 +35,42 @@ Model.prototype.getRootDir = function() { }; Model.prototype.load = function(context) { - var config = PluginBase.prototype.load.apply(this, arguments); + const config = PluginBase.prototype.load.apply(this, arguments); assertIsValidModelConfig(config); return config; }; Model.prototype.buildInstructions = function(context, rootDir, modelsConfig) { - var modelsMeta = modelsConfig._meta || {}; + const modelsMeta = modelsConfig._meta || {}; delete modelsConfig._meta; context.configurations.mixins._meta = modelsMeta; - var modelSources = this.options.modelSources || modelsMeta.sources || + const modelSources = this.options.modelSources || modelsMeta.sources || ['./models']; - var modelInstructions = buildAllModelInstructions( + const modelInstructions = buildAllModelInstructions( rootDir, modelsConfig, modelSources, this.options.modelDefinitions, - this.options.scriptExtensions + this.options.scriptExtensions, ); return modelInstructions; }; function buildAllModelInstructions(rootDir, modelsConfig, sources, modelDefinitions, scriptExtensions) { - var registry = verifyModelDefinitions(rootDir, modelDefinitions, + let registry = verifyModelDefinitions(rootDir, modelDefinitions, scriptExtensions); if (!registry) { registry = findModelDefinitions(rootDir, sources, scriptExtensions); } - var modelNamesToBuild = addAllBaseModels(registry, Object.keys(modelsConfig)); + const modelNamesToBuild = addAllBaseModels( + registry, + Object.keys(modelsConfig), + ); - var instructions = modelNamesToBuild + const instructions = modelNamesToBuild .map(function createModelInstructions(name) { - var config = modelsConfig[name]; - var definition = registry[name] || {}; + const config = modelsConfig[name]; + const definition = registry[name] || {}; debug('Using model "%s"\nConfiguration: %j\nDefinition %j', name, config, definition.definition); @@ -84,20 +87,20 @@ function buildAllModelInstructions(rootDir, modelsConfig, sources, } function addAllBaseModels(registry, modelNames) { - var result = []; - var visited = {}; + const result = []; + const visited = {}; while (modelNames.length) { - var name = modelNames.shift(); + const name = modelNames.shift(); if (visited[name]) continue; visited[name] = true; result.push(name); - var definition = registry[name] && registry[name].definition; + const definition = registry[name] && registry[name].definition; if (!definition) continue; - var base = getBaseModelName(definition); + const base = getBaseModelName(definition); // ignore built-in models like User if (!registry[base]) continue; @@ -118,14 +121,14 @@ function getBaseModelName(modelDefinition) { function sortByInheritance(instructions) { // create edges Base name -> Model name - var edges = instructions + const edges = instructions .map(function(inst) { return [getBaseModelName(inst.definition), inst.name]; }); - var sortedNames = toposort(edges); + const sortedNames = toposort(edges); - var instructionsByModelName = {}; + const instructionsByModelName = {}; instructions.forEach(function(inst) { instructionsByModelName[inst.name] = inst; }); @@ -146,14 +149,14 @@ function verifyModelDefinitions(rootDir, modelDefinitions, scriptExtensions) { return undefined; } - var registry = {}; + const registry = {}; modelDefinitions.forEach(function(definition, idx) { if (definition.sourceFile) { - var fullPath = path.resolve(rootDir, definition.sourceFile); + const fullPath = path.resolve(rootDir, definition.sourceFile); definition.sourceFile = fixFileExtension( fullPath, tryReadDir(path.dirname(fullPath)), - scriptExtensions + scriptExtensions, ); if (!definition.sourceFile) { @@ -168,7 +171,7 @@ function verifyModelDefinitions(rootDir, modelDefinitions, scriptExtensions) { path.relative(rootDir, definition.sourceFile) : '(no source file)'); - var modelName = definition.definition.name; + const modelName = definition.definition.name; if (!modelName) { debug('Skipping model definition without Model name ' + '(from options.modelDefinitions @ index %s)', @@ -182,26 +185,26 @@ function verifyModelDefinitions(rootDir, modelDefinitions, scriptExtensions) { } function findModelDefinitions(rootDir, sources, scriptExtensions) { - var registry = {}; + const registry = {}; sources.forEach(function(src) { - var srcDir = tryResolveAppPath(rootDir, src, {strict: false}); + const srcDir = tryResolveAppPath(rootDir, src, {strict: false}); if (!srcDir) { debug('Skipping unknown module source dir %j', src); return; } - var files = tryReadDir(srcDir); + const files = tryReadDir(srcDir); files .filter(function(f) { return f[0] !== '_' && path.extname(f) === '.json'; }) .forEach(function(f) { - var fullPath = path.resolve(srcDir, f); - var entry = loadModelDefinition(rootDir, fullPath, files, + const fullPath = path.resolve(srcDir, f); + const entry = loadModelDefinition(rootDir, fullPath, files, scriptExtensions); - var modelName = entry.definition.name; + const modelName = entry.definition.name; if (!modelName) { debug('Skipping model definition without Model name: %s', path.relative(srcDir, fullPath)); @@ -215,12 +218,12 @@ function findModelDefinitions(rootDir, sources, scriptExtensions) { } function loadModelDefinition(rootDir, jsonFile, allFiles, scriptExtensions) { - var definition = require(jsonFile); - var basename = path.basename(jsonFile, path.extname(jsonFile)); + const definition = require(jsonFile); + const basename = path.basename(jsonFile, path.extname(jsonFile)); definition.name = definition.name || _.upperFirst(_.camelCase(basename)); // find a matching file with a supported extension like `.js` or `.coffee` - var sourceFile = fixFileExtension(jsonFile, allFiles, scriptExtensions); + const sourceFile = fixFileExtension(jsonFile, allFiles, scriptExtensions); if (sourceFile === undefined) { debug('Model source code not found: %s', sourceFile); @@ -238,26 +241,26 @@ function loadModelDefinition(rootDir, jsonFile, allFiles, scriptExtensions) { function assertIsValidModelConfig(config) { assertIsValidConfig('model', config); - for (var name in config) { - var entry = config[name]; - var options = entry.options || {}; - var unsupported = entry.properties || + for (const name in config) { + const entry = config[name]; + const options = entry.options || {}; + const unsupported = entry.properties || entry.base || options.base || entry.plural || options.plural; if (unsupported) { throw new Error(g.f( 'The data in {{model-config.json}} ' + - 'is in the unsupported {{1.x}} format.' + 'is in the unsupported {{1.x}} format.', )); } } } // Regular expression to match built-in loopback models -var LOOPBACK_MODEL_REGEXP = new RegExp( +const LOOPBACK_MODEL_REGEXP = new RegExp( ['', 'node_modules', 'loopback', '[^\\/\\\\]+', 'models', '[^\\/\\\\]+\\.js$'] - .join('\\' + path.sep) + .join('\\' + path.sep), ); function isBuiltinLoopBackModel(app, data) { @@ -265,19 +268,19 @@ function isBuiltinLoopBackModel(app, data) { if (!app.loopback[data.name]) return false; // 2. Built-in models have a script file `loopback/{facet}/models/{name}.js` - var srcFile = data.sourceFile; + const srcFile = data.sourceFile; return srcFile && LOOPBACK_MODEL_REGEXP.test(srcFile); } Model.prototype.start = function(context) { - var app = context.app; - var instructions = context.instructions[this.name]; + const app = context.app; + const instructions = context.instructions[this.name]; - var registry = app.registry || app.loopback; + const registry = app.registry || app.loopback; instructions.forEach(function(data) { - var name = data.name; - var model; + const name = data.name; + let model; if (!data.definition) { model = registry.getModel(name); @@ -294,7 +297,7 @@ Model.prototype.start = function(context) { model = registry.createModel(data.definition); if (data.sourceFile) { debug('Loading customization script %s', data.sourceFile); - var code = require(data.sourceFile); + const code = require(data.sourceFile); if (typeof code === 'function') { debug('Customizing model %s', name); code(model); diff --git a/lib/plugins/swagger.js b/lib/plugins/swagger.js index 761ea01..5dfcce9 100644 --- a/lib/plugins/swagger.js +++ b/lib/plugins/swagger.js @@ -5,8 +5,8 @@ 'use strict'; -var util = require('util'); -var PluginBase = require('../plugin-base'); +const util = require('util'); +const PluginBase = require('../plugin-base'); module.exports = function(options) { return new Swagger(options); @@ -19,13 +19,13 @@ function Swagger(options) { util.inherits(Swagger, PluginBase); Swagger.prototype.start = function(context) { - var app = context.app; - var appConfig = context.instructions.application; + const app = context.app; + const appConfig = context.instructions.application; // disable token requirement for swagger, if available - var swagger = app.remotes().exports.swagger; + const swagger = app.remotes().exports.swagger; if (!swagger) return; - var requireTokenForSwagger = appConfig.swagger && + const requireTokenForSwagger = appConfig.swagger && appConfig.swagger.requireToken; swagger.requireToken = requireTokenForSwagger || false; }; diff --git a/lib/utils.js b/lib/utils.js index 7c6573e..ddbc8ac 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -5,13 +5,13 @@ 'use strict'; -var debug = require('debug')('loopback:boot'); -var path = require('path'); -var Module = require('module'); -var fs = require('fs'); -var assert = require('assert'); -var _ = require('lodash'); -var g = require('./globalize'); +const debug = require('debug')('loopback:boot'); +const path = require('path'); +const Module = require('module'); +const fs = require('fs'); +const assert = require('assert'); +const _ = require('lodash'); +const g = require('./globalize'); exports.arrayToObject = arrayToObject; exports.tryReadDir = tryReadDir; @@ -26,7 +26,7 @@ exports.tryResolveAppPath = tryResolveAppPath; exports.forEachKeyedObject = forEachKeyedObject; exports.mergePhaseNameLists = mergePhaseNameLists; -var FILE_EXTENSION_JSON = exports.FILE_EXTENSION_JSON = '.json'; +const FILE_EXTENSION_JSON = exports.FILE_EXTENSION_JSON = '.json'; /** * Find all javascript files (except for those prefixed with _) * and all directories. @@ -37,7 +37,7 @@ var FILE_EXTENSION_JSON = exports.FILE_EXTENSION_JSON = '.json'; function findScripts(dir, scriptExtensions) { assert(dir, 'cannot require directory contents without directory name'); - var files = tryReadDir(dir); + const files = tryReadDir(dir); scriptExtensions = scriptExtensions || require.extensions; // sort files in lowercase alpha for linux @@ -54,15 +54,15 @@ function findScripts(dir, scriptExtensions) { } }); - var results = []; + const results = []; files.forEach(function(filename) { // ignore index.js and files prefixed with underscore if (filename === 'index.js' || filename[0] === '_') { return; } - var filepath = path.resolve(path.join(dir, filename)); - var stats = fs.statSync(filepath); + const filepath = path.resolve(path.join(dir, filename)); + const stats = fs.statSync(filepath); // only require files supported by specified extensions if (stats.isFile()) { @@ -87,9 +87,13 @@ function tryReadDir() { } function resolveRelativePaths(relativePaths, appRootDir) { - var resolveOpts = {strict: false}; + const resolveOpts = {strict: false}; relativePaths.forEach(function(relativePath, k) { - var resolvedPath = tryResolveAppPath(appRootDir, relativePath, resolveOpts); + const resolvedPath = tryResolveAppPath( + appRootDir, + relativePath, + resolveOpts, + ); if (resolvedPath !== undefined) { relativePaths[k] = resolvedPath; } else { @@ -121,28 +125,28 @@ function arrayToObject(array) { function isPreferredExtension(filename, includeExtensions) { assert(!!includeExtensions, '"includeExtensions" argument is required'); - var ext = path.extname(filename); + const ext = path.extname(filename); return (ext in includeExtensions) && !(ext in getExcludedExtensions()); } function fixFileExtension(filepath, files, scriptExtensions) { - var results = []; - var otherFile; + const results = []; + let otherFile; /* Prefer coffee scripts over json */ if (scriptExtensions && isPreferredExtension(filepath, scriptExtensions)) { return filepath; } - var basename = path.basename(filepath, FILE_EXTENSION_JSON); - var sourceDir = path.dirname(filepath); + const basename = path.basename(filepath, FILE_EXTENSION_JSON); + const sourceDir = path.dirname(filepath); files.forEach(function(f) { otherFile = path.resolve(sourceDir, f); - var stats = fs.statSync(otherFile); + const stats = fs.statSync(otherFile); if (stats.isFile()) { - var otherFileExtension = path.extname(f); + const otherFileExtension = path.extname(f); if (!(otherFileExtension in getExcludedExtensions()) && path.basename(f, otherFileExtension) == basename) { @@ -156,9 +160,9 @@ function fixFileExtension(filepath, files, scriptExtensions) { } function resolveAppPath(rootDir, relativePath, resolveOptions) { - var resolvedPath = tryResolveAppPath(rootDir, relativePath, resolveOptions); + const resolvedPath = tryResolveAppPath(rootDir, relativePath, resolveOptions); if (resolvedPath === undefined && !resolveOptions.optional) { - var err = new Error(g.f('Cannot resolve path "%s"', relativePath)); + const err = new Error(g.f('Cannot resolve path "%s"', relativePath)); err.code = 'PATH_NOT_FOUND'; throw err; } @@ -166,19 +170,19 @@ function resolveAppPath(rootDir, relativePath, resolveOptions) { } function resolveAppScriptPath(rootDir, relativePath, resolveOptions) { - var resolvedPath = resolveAppPath(rootDir, relativePath, resolveOptions); + const resolvedPath = resolveAppPath(rootDir, relativePath, resolveOptions); if (!resolvedPath) { return false; } - var sourceDir = path.dirname(resolvedPath); - var files = tryReadDir(sourceDir); - var fixedFile = fixFileExtension(resolvedPath, files); + const sourceDir = path.dirname(resolvedPath); + const files = tryReadDir(sourceDir); + const fixedFile = fixFileExtension(resolvedPath, files); return (fixedFile === undefined ? resolvedPath : fixedFile); } function tryResolveAppPath(rootDir, relativePath, resolveOptions) { - var fullPath; - var start = relativePath.substring(0, 2); + let fullPath; + const start = relativePath.substring(0, 2); /* In order to retain backward compatibility, we need to support * two ways how to treat values that are not relative nor absolute @@ -189,7 +193,7 @@ function tryResolveAppPath(rootDir, relativePath, resolveOptions) { */ resolveOptions = resolveOptions || {strict: true}; - var isModuleRelative = false; + let isModuleRelative = false; if (relativePath[0] === '/') { fullPath = relativePath; } else if (start === './' || start === '..') { @@ -222,17 +226,17 @@ function tryResolveAppPath(rootDir, relativePath, resolveOptions) { // [ env.NODE_PATH values, $HOME/.node_modules, etc. ] // Module._nodeModulePaths(rootDir) returns a list of paths like // [ rootDir/node_modules, rootDir/../node_modules, etc. ] - var modulePaths = Module.globalPaths + const modulePaths = Module.globalPaths .concat(Module._nodeModulePaths(rootDir)); fullPath = modulePaths .map(function(candidateDir) { - var absPath = path.join(candidateDir, relativePath); + const absPath = path.join(candidateDir, relativePath); try { // NOTE(bajtos) We need to create a proper String object here, // otherwise we can't attach additional properties to it /* jshint -W053 */ - var filePath = new String(require.resolve(absPath)); + const filePath = new String(require.resolve(absPath)); filePath.unresolvedPath = absPath; return filePath; } catch (err) { @@ -310,8 +314,8 @@ function forEachKeyedObject(obj, fn) { function mergePhaseNameLists(currentNames, namesToMerge) { if (!namesToMerge.length) return currentNames.slice(); - var targetArray = currentNames.slice(); - var targetIx = targetArray.indexOf(namesToMerge[0]); + const targetArray = currentNames.slice(); + let targetIx = targetArray.indexOf(namesToMerge[0]); if (targetIx === -1) { // the first new item does not match any existing one @@ -321,21 +325,21 @@ function mergePhaseNameLists(currentNames, namesToMerge) { } // merge (zip) two arrays - for (var sourceIx = 1; sourceIx < namesToMerge.length; sourceIx++) { - var valueToAdd = namesToMerge[sourceIx]; - var previousValue = namesToMerge[sourceIx - 1]; - var existingIx = targetArray.indexOf(valueToAdd, targetIx); + for (let sourceIx = 1; sourceIx < namesToMerge.length; sourceIx++) { + const valueToAdd = namesToMerge[sourceIx]; + const previousValue = namesToMerge[sourceIx - 1]; + const existingIx = targetArray.indexOf(valueToAdd, targetIx); if (existingIx === -1) { // A new phase - try to add it after the last one, // unless it was already registered if (targetArray.indexOf(valueToAdd) !== -1) { - var errMsg = g.f('Ordering conflict: cannot add "%s' + + const errMsg = g.f('Ordering conflict: cannot add "%s' + '" after "%s", because the opposite order was ' + ' already specified', valueToAdd, previousValue); throw new Error(errMsg); } - var previousIx = targetArray.indexOf(previousValue); + const previousIx = targetArray.indexOf(previousValue); targetArray.splice(previousIx + 1, 0, valueToAdd); } else { // An existing phase - move the pointer diff --git a/package.json b/package.json index 1b78c6f..a9b60c8 100644 --- a/package.json +++ b/package.json @@ -40,8 +40,8 @@ "coffeeify": "^3.0.1", "coffeescript": "^2.3.1", "dirty-chai": "^2.0.1", - "eslint": "^5.2.0", - "eslint-config-loopback": "^11.0.0", + "eslint": "^6.6.0", + "eslint-config-loopback": "^13.1.0", "fs-extra": "^7.0.1", "loopback": "^3.0.0", "mocha": "^5.2.0", diff --git a/test/acceptance.test.js b/test/acceptance.test.js index 6bb7dcd..f39622f 100644 --- a/test/acceptance.test.js +++ b/test/acceptance.test.js @@ -5,18 +5,18 @@ 'use strict'; -var path = require('path'); -var loopback = require('loopback'); +const path = require('path'); +const loopback = require('loopback'); -var chai = require('chai'); -var dirtyChai = require('dirty-chai'); -var expect = chai.expect; +const chai = require('chai'); +const dirtyChai = require('dirty-chai'); +const expect = chai.expect; chai.use(dirtyChai); const bootLoopBackApp = require('..'); describe('bootLoopBackApp', function() { - var app; + let app; beforeEach(function() { app = loopback(); }); diff --git a/test/bootstrapper.test.js b/test/bootstrapper.test.js index d32ac72..d76d6f2 100644 --- a/test/bootstrapper.test.js +++ b/test/bootstrapper.test.js @@ -5,39 +5,39 @@ 'use strict'; -var path = require('path'); -var loopback = require('loopback'); +const path = require('path'); +const loopback = require('loopback'); -var chai = require('chai'); -var dirtyChai = require('dirty-chai'); -var expect = chai.expect; +const chai = require('chai'); +const dirtyChai = require('dirty-chai'); +const expect = chai.expect; chai.use(dirtyChai); -var Bootstrapper = require('../lib/bootstrapper'); +const Bootstrapper = require('../lib/bootstrapper'); describe('Bootstrapper', function() { - var app; + let app; beforeEach(function() { app = loopback(); process.bootFlags = []; }); it('should honor options.phases', function(done) { - var options = { + const options = { app: app, appRootDir: path.join(__dirname, './fixtures/simple-app'), phases: ['load'], }; - var bootstrapper = new Bootstrapper(options); + const bootstrapper = new Bootstrapper(options); - var context = { + const context = { app: app, }; bootstrapper.run(context, function(err) { if (err) return done(err); - var configs = context.configurations; + const configs = context.configurations; expect(configs.application, 'application').to.be.an('object'); expect(configs.bootScripts, 'bootScripts').to.be.an('array'); expect(configs.middleware, 'middleware').to.be.an('object'); @@ -50,22 +50,22 @@ describe('Bootstrapper', function() { }); it('should honor options.plugins', function(done) { - var options = { + const options = { app: app, appRootDir: path.join(__dirname, './fixtures/simple-app'), plugins: ['application', 'boot-script'], }; - var bootstrapper = new Bootstrapper(options); + const bootstrapper = new Bootstrapper(options); - var context = { + const context = { app: app, }; bootstrapper.run(context, function(err) { if (err) return done(err); - var configs = context.configurations; - var instructions = context.instructions; + const configs = context.configurations; + const instructions = context.instructions; expect(configs.application, 'application').to.be.an('object'); expect(configs.middleware, 'middleware').to.be.undefined(); expect(configs.models, 'models').to.be.undefined(); @@ -94,15 +94,15 @@ describe('Bootstrapper', function() { it('searches boot file extensions specified in options.scriptExtensions', function(done) { - var options = { + const options = { app: app, appRootDir: path.join(__dirname, './fixtures/simple-app'), scriptExtensions: ['.customjs', '.customjs2'], }; - var bootstrapper = new Bootstrapper(options); + const bootstrapper = new Bootstrapper(options); - var context = { + const context = { app: app, }; diff --git a/test/browser.multiapp.test.js b/test/browser.multiapp.test.js index 3cd18a5..e8608ff 100644 --- a/test/browser.multiapp.test.js +++ b/test/browser.multiapp.test.js @@ -5,18 +5,18 @@ 'use strict'; -var boot = require('../'); -var async = require('async'); -var exportBrowserifyToFile = require('./helpers/browserify').exportToSandbox; -var packageFilter = require('./helpers/browserify').packageFilter; -var fs = require('fs'); -var path = require('path'); -var expect = require('chai').expect; -var browserify = require('browserify'); -var sandbox = require('./helpers/sandbox'); -var vm = require('vm'); -var createBrowserLikeContext = require('./helpers/browser').createContext; -var printContextLogs = require('./helpers/browser').printContextLogs; +const boot = require('../'); +const async = require('async'); +const exportBrowserifyToFile = require('./helpers/browserify').exportToSandbox; +const packageFilter = require('./helpers/browserify').packageFilter; +const fs = require('fs'); +const path = require('path'); +const expect = require('chai').expect; +const browserify = require('browserify'); +const sandbox = require('./helpers/sandbox'); +const vm = require('vm'); +const createBrowserLikeContext = require('./helpers/browser').createContext; +const printContextLogs = require('./helpers/browser').printContextLogs; describe('browser support for multiple apps', function() { this.timeout(60000); // 60s to give browserify enough time to finish @@ -24,10 +24,10 @@ describe('browser support for multiple apps', function() { beforeEach(sandbox.reset); it('has API for bundling and booting multiple apps', function(done) { - var app1Dir = path.resolve(__dirname, './fixtures/browser-app'); - var app2Dir = path.resolve(__dirname, './fixtures/browser-app-2'); + const app1Dir = path.resolve(__dirname, './fixtures/browser-app'); + const app2Dir = path.resolve(__dirname, './fixtures/browser-app-2'); - var apps = [ + const apps = [ { appDir: app1Dir, appFile: './app.js', @@ -44,9 +44,9 @@ describe('browser support for multiple apps', function() { browserifyTestApps(apps, function(err, bundlePath) { if (err) return done(err); - var bundledApps = executeBundledApps(bundlePath, apps, function(err) { - var app1 = bundledApps.defaultApp; - var app2 = bundledApps.browserApp2; + const bundledApps = executeBundledApps(bundlePath, apps, function(err) { + const app1 = bundledApps.defaultApp; + const app2 = bundledApps.browserApp2; expect(app1.settings).to.have.property('custom-key', 'custom-value'); expect(Object.keys(app1.models)).to.include('Customer'); @@ -64,23 +64,23 @@ describe('browser support for multiple apps', function() { }); function browserifyTestApps(apps, next) { - var b = browserify({ + const b = browserify({ debug: true, basedir: path.resolve(__dirname, './fixtures'), packageFilter, }); - var bundles = []; - for (var i in apps) { - var appDir = apps[i].appDir; - var appFile = apps[i].appFile; - var moduleName = apps[i].moduleName; - var appId = apps[i].appId; + const bundles = []; + for (const i in apps) { + const appDir = apps[i].appDir; + let appFile = apps[i].appFile; + const moduleName = apps[i].moduleName; + const appId = apps[i].appId; appFile = path.join(appDir, appFile); b.require(appFile, {expose: moduleName}); - var opts = appDir; + let opts = appDir; if (appId) { opts = { appId: appId, @@ -97,21 +97,21 @@ function browserifyTestApps(apps, next) { } function executeBundledApps(bundlePath, apps, done) { - var code = fs.readFileSync(bundlePath); - var context = createBrowserLikeContext(); + const code = fs.readFileSync(bundlePath); + const context = createBrowserLikeContext(); vm.runInContext(code, context, bundlePath); - var ids = []; - var script = 'var apps = {};\n'; - for (var i in apps) { - var moduleName = apps[i].moduleName; - var id = apps[i].appId || 'defaultApp'; + const ids = []; + let script = 'var apps = {};\n'; + for (const i in apps) { + const moduleName = apps[i].moduleName; + const id = apps[i].appId || 'defaultApp'; ids.push(id); script += 'apps.' + id + ' = require("' + moduleName + '");\n'; } script += 'apps;\n'; - var appsInContext = vm.runInContext(script, context); + const appsInContext = vm.runInContext(script, context); async.each(ids, function(id, done) { appsInContext[id].once('booted', function() { done(); diff --git a/test/browser.test.js b/test/browser.test.js index e59ba08..f0de610 100644 --- a/test/browser.test.js +++ b/test/browser.test.js @@ -5,21 +5,21 @@ 'use strict'; -var boot = require('../'); -var exportBrowserifyToFile = require('./helpers/browserify').exportToSandbox; -var packageFilter = require('./helpers/browserify').packageFilter; -var fs = require('fs'); -var path = require('path'); -var expect = require('chai').expect; -var browserify = require('browserify'); -var sandbox = require('./helpers/sandbox'); -var vm = require('vm'); -var createBrowserLikeContext = require('./helpers/browser').createContext; -var printContextLogs = require('./helpers/browser').printContextLogs; +const boot = require('../'); +const exportBrowserifyToFile = require('./helpers/browserify').exportToSandbox; +const packageFilter = require('./helpers/browserify').packageFilter; +const fs = require('fs'); +const path = require('path'); +const expect = require('chai').expect; +const browserify = require('browserify'); +const sandbox = require('./helpers/sandbox'); +const vm = require('vm'); +const createBrowserLikeContext = require('./helpers/browser').createContext; +const printContextLogs = require('./helpers/browser').printContextLogs; -var compileStrategies = { +const compileStrategies = { default: function(appDir) { - var b = browserify({ + const b = browserify({ basedir: appDir, debug: true, packageFilter, @@ -29,7 +29,7 @@ var compileStrategies = { }, coffee: function(appDir) { - var b = browserify({ + const b = browserify({ basedir: appDir, extensions: ['.coffee'], debug: true, @@ -48,19 +48,19 @@ describe('browser support', function() { beforeEach(sandbox.reset); it('has API for bundling and executing boot instructions', function(done) { - var appDir = path.resolve(__dirname, './fixtures/browser-app'); + const appDir = path.resolve(__dirname, './fixtures/browser-app'); browserifyTestApp(appDir, function(err, bundlePath) { if (err) return done(err); - var app = executeBundledApp(bundlePath, function(err) { + const app = executeBundledApp(bundlePath, function(err) { if (err) return done(err); // configured in fixtures/browser-app/boot/configure.js expect(app.settings).to.have.property('custom-key', 'custom-value'); expect(Object.keys(app.models)).to.include('Customer'); expect(app.models.Customer.settings).to.have.property( '_customized', - 'Customer' + 'Customer', ); // configured in fixtures/browser-app/component-config.json @@ -72,17 +72,17 @@ describe('browser support', function() { }); it('loads mixins', function(done) { - var appDir = path.resolve(__dirname, './fixtures/browser-app'); - var options = { + const appDir = path.resolve(__dirname, './fixtures/browser-app'); + const options = { appRootDir: appDir, }; browserifyTestApp(options, function(err, bundlePath) { if (err) return done(err); - var app = executeBundledApp(bundlePath, function(err) { - var modelBuilder = app.registry.modelBuilder; - var registry = modelBuilder.mixins.mixins; + const app = executeBundledApp(bundlePath, function(err) { + const modelBuilder = app.registry.modelBuilder; + const registry = modelBuilder.mixins.mixins; expect(Object.keys(registry)).to.eql(['TimeStamps']); expect(app.models.Customer.timeStampsMixin).to.eql(true); @@ -95,18 +95,18 @@ describe('browser support', function() { // add coffee-script to require.extensions require('coffeescript/register'); - var appDir = path.resolve(__dirname, './fixtures/coffee-app'); + const appDir = path.resolve(__dirname, './fixtures/coffee-app'); browserifyTestApp(appDir, 'coffee', function(err, bundlePath) { if (err) return done(err); - var app = executeBundledApp(bundlePath, function(err) { + const app = executeBundledApp(bundlePath, function(err) { // configured in fixtures/browser-app/boot/configure.coffee expect(app.settings).to.have.property('custom-key', 'custom-value'); expect(Object.keys(app.models)).to.include('Customer'); expect(app.models.Customer.settings).to.have.property( '_customized', - 'Customer' + 'Customer', ); done(); }); @@ -122,8 +122,8 @@ function browserifyTestApp(options, strategy, next) { } if (!strategy) strategy = 'default'; - var appDir = typeof options === 'object' ? options.appRootDir : options; - var b = compileStrategies[strategy](appDir); + const appDir = typeof options === 'object' ? options.appRootDir : options; + const b = compileStrategies[strategy](appDir); boot.compileToBrowserify(options, b, function(err) { exportBrowserifyToFile(b, 'browser-app-bundle.js', next); @@ -131,10 +131,10 @@ function browserifyTestApp(options, strategy, next) { } function executeBundledApp(bundlePath, done) { - var code = fs.readFileSync(bundlePath); - var context = createBrowserLikeContext(); + const code = fs.readFileSync(bundlePath); + const context = createBrowserLikeContext(); vm.runInContext(code, context, bundlePath); - var app = vm.runInContext('require("browser-app")', context); + const app = vm.runInContext('require("browser-app")', context); app.once('booted', function(err) { printContextLogs(context); done(err, app); diff --git a/test/compiler.test.js b/test/compiler.test.js index 5af498a..bfd90d7 100644 --- a/test/compiler.test.js +++ b/test/compiler.test.js @@ -5,17 +5,17 @@ 'use strict'; -var boot = require('../'); -var fs = require('fs-extra'); -var path = require('path'); -var expect = require('chai').expect; -var sandbox = require('./helpers/sandbox'); -var appdir = require('./helpers/appdir'); +const boot = require('../'); +const fs = require('fs-extra'); +const path = require('path'); +const expect = require('chai').expect; +const sandbox = require('./helpers/sandbox'); +const appdir = require('./helpers/appdir'); // add coffee-script to require.extensions require('coffeescript/register'); -var SIMPLE_APP = path.join(__dirname, 'fixtures', 'simple-app'); +const SIMPLE_APP = path.join(__dirname, 'fixtures', 'simple-app'); describe('compiler', function() { beforeEach(sandbox.reset); @@ -48,7 +48,7 @@ describe('compiler', function() { } describe('from options', function() { - var options, instructions, appConfig; + let options, instructions, appConfig; beforeEach(function(done) { options = { @@ -115,12 +115,12 @@ describe('compiler', function() { }); describe('with custom model definitions', function(done) { - var dataSources = { + const dataSources = { 'the-db': {connector: 'memory'}, }; it('loads model without definition', function(done) { - var instruction = boot.compile( + const instruction = boot.compile( { appRootDir: appdir.PATH, models: { @@ -133,21 +133,21 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models[0].name).to.equal( - 'model-without-definition' + 'model-without-definition', ); expect(instructions.models[0].definition).to.equal(undefined); expect(instructions.models[0].sourceFile).to.equal(undefined); done(); - } + }, ); }); it('loads coffeescript models', function(done) { - var modelScript = appdir.writeFileSync( + const modelScript = appdir.writeFileSync( 'custom-models/coffee-model-with-definition.coffee', - '' + '', ); boot.compile( { @@ -169,23 +169,23 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models[0].name).to.equal( - 'coffee-model-with-definition' + 'coffee-model-with-definition', ); expect(instructions.models[0].definition).to.eql({ name: 'coffee-model-with-definition', }); expect(instructions.models[0].sourceFile).to.equal(modelScript); done(); - } + }, ); }); it('handles sourceFile path without extension (.js)', function(done) { - var modelScript = appdir.writeFileSync( + const modelScript = appdir.writeFileSync( 'custom-models/model-without-ext.coffee', - '' + '', ); boot.compile( { @@ -207,18 +207,18 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models[0].name).to.equal('model-without-ext'); expect(instructions.models[0].sourceFile).to.equal(modelScript); done(); - } + }, ); }); it('handles sourceFile path without extension (.coffee)', function(done) { - var modelScript = appdir.writeFileSync( + const modelScript = appdir.writeFileSync( 'custom-models/model-without-ext.coffee', - '' + '', ); boot.compile( { @@ -240,18 +240,18 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models[0].name).to.equal('model-without-ext'); expect(instructions.models[0].sourceFile).to.equal(modelScript); done(); - } + }, ); }); it('sets source file path if the file exist', function(done) { - var modelScript = appdir.writeFileSync( + const modelScript = appdir.writeFileSync( 'custom-models/model-with-definition.js', - '' + '', ); boot.compile( { @@ -273,14 +273,14 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models[0].name).to.equal( - 'model-with-definition' + 'model-with-definition', ); expect(instructions.models[0].definition).not.to.equal(undefined); expect(instructions.models[0].sourceFile).to.equal(modelScript); done(); - } + }, ); }); @@ -301,7 +301,7 @@ describe('compiler', function() { }, sourceFile: appdir.resolve( 'custom-models', - 'file-does-not-exist.js' + 'file-does-not-exist.js', ), }, ], @@ -309,14 +309,14 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models[0].name).to.equal( - 'model-with-definition-with-falsey-source-file' + 'model-with-definition-with-falsey-source-file', ); expect(instructions.models[0].definition).not.to.equal(undefined); expect(instructions.models[0].sourceFile).to.equal(undefined); done(); - } + }, ); }); @@ -342,14 +342,14 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models[0].name).to.equal( - 'model-with-definition-without-source-file-property' + 'model-with-definition-without-source-file-property', ); expect(instructions.models[0].definition).not.to.equal(undefined); expect(instructions.models[0].sourceFile).to.equal(undefined); done(); - } + }, ); }); @@ -378,12 +378,12 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models.map(getNameProperty)).to.eql([ 'some-model', ]); done(); - } + }, ); }); }); @@ -393,7 +393,7 @@ describe('compiler', function() { it('loads config files', function(done) { boot.compile(SIMPLE_APP, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.eql({ @@ -414,21 +414,21 @@ describe('compiler', function() { db: {local: 'applied'}, }); - var env = process.env.NODE_ENV || 'development'; + const env = process.env.NODE_ENV || 'development'; appdir.writeConfigFileSync('datasources.' + env + '.json', { db: {env: 'applied'}, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var db = instructions.dataSources.db; + const db = instructions.dataSources.db; expect(db).to.have.property('local', 'applied'); expect(db).to.have.property('env', 'applied'); - var expectedLoadOrder = ['local', 'env']; - var actualLoadOrder = Object.keys(db).filter(function(k) { + const expectedLoadOrder = ['local', 'env']; + const actualLoadOrder = Object.keys(db).filter(function(k) { return expectedLoadOrder.indexOf(k) !== -1; }); @@ -441,21 +441,21 @@ describe('compiler', function() { appdir.createConfigFilesSync(); appdir.writeFileSync( 'datasources.local.js', - 'module.exports = { db: { fromJs: true } };' + 'module.exports = { db: { fromJs: true } };', ); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var db = instructions.dataSources.db; + const db = instructions.dataSources.db; expect(db).to.have.property('fromJs', true); done(); }); }); it('merges new Object values', function(done) { - var objectValue = {key: 'value'}; + const objectValue = {key: 'value'}; appdir.createConfigFilesSync(); appdir.writeConfigFileSync('datasources.local.json', { db: {nested: objectValue}, @@ -463,9 +463,9 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var db = instructions.dataSources.db; + const db = instructions.dataSources.db; expect(db).to.have.property('nested'); expect(db.nested).to.eql(objectValue); done(); @@ -481,7 +481,7 @@ describe('compiler', function() { host: 'localhost', }, }, - } + }, ); appdir.writeConfigFileSync('datasources.local.json', { @@ -494,8 +494,8 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; - var email = instructions.dataSources.email; + const instructions = context.instructions; + const email = instructions.dataSources.email; expect(email.transport.host).to.equal('mail.example.com'); done(); }); @@ -515,7 +515,7 @@ describe('compiler', function() { }, ], }, - } + }, ); appdir.writeConfigFileSync('datasources.local.json', { rest: { @@ -531,9 +531,9 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var rest = instructions.dataSources.rest; + const rest = instructions.dataSources.rest; expect(rest.operations[0].template).to.eql({ method: 'POST', // the value from datasources.json url: 'http://api.example.com', // overriden in datasources.local.json @@ -543,7 +543,7 @@ describe('compiler', function() { }); it('merges Array properties', function(done) { - var arrayValue = ['value']; + const arrayValue = ['value']; appdir.createConfigFilesSync(); appdir.writeConfigFileSync('datasources.local.json', { db: {nested: arrayValue}, @@ -551,9 +551,9 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var db = instructions.dataSources.db; + const db = instructions.dataSources.db; expect(db).to.have.property('nested'); expect(db.nested).to.eql(arrayValue); done(); @@ -570,28 +570,28 @@ describe('compiler', function() { }); // Here we load main config and merge it with DEV overrides - var bootOptions = { + const bootOptions = { appRootDir: appdir.PATH, env: 'development', phases: ['load'], }; - var productionBootOptions = { + const productionBootOptions = { appRootDir: appdir.PATH, env: 'production', phases: ['load'], }; boot.compile(bootOptions, function(err, context) { - var config = context.configurations.middleware; + const config = context.configurations.middleware; expect( config['strong-error-handler'].params.debug, - 'debug in development' + 'debug in development', ).to.equal(true); boot.compile(productionBootOptions, function(err, context2) { - var config = context2.configurations.middleware; + const config = context2.configurations.middleware; expect( config['strong-error-handler'].params.debug, - 'debug in production' + 'debug in production', ).to.equal(false); done(); }); @@ -606,7 +606,7 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.have.property('name', 'foo'); @@ -624,7 +624,7 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.have.property('name', 'foo'); @@ -640,12 +640,12 @@ describe('compiler', function() { appdir.createConfigFilesSync(); appdir.writeFileSync( 'model-config.local.js', - "module.exports = { foo: { dataSource: 'db' } };" + "module.exports = { foo: { dataSource: 'db' } };", ); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.have.property('name', 'foo'); @@ -672,7 +672,7 @@ describe('compiler', function() { expectCompileToThrow( /array values of different length.*nest\.array/, - done + done, ); }); @@ -707,7 +707,7 @@ describe('compiler', function() { expectCompileToThrow( /array values of different length.*toplevel\[0\]\.nested/, - done + done, ); }); @@ -738,21 +738,21 @@ describe('compiler', function() { appdir.writeConfigFileSync('config.local.json', {cfgLocal: 'applied'}); - var env = process.env.NODE_ENV || 'development'; + const env = process.env.NODE_ENV || 'development'; appdir.writeConfigFileSync('config.' + env + '.json', { cfgEnv: 'applied', }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; - var appConfig = instructions.application; + const instructions = context.instructions; + const appConfig = instructions.application; expect(appConfig).to.have.property('cfgLocal', 'applied'); expect(appConfig).to.have.property('cfgEnv', 'applied'); - var expectedLoadOrder = ['cfgLocal', 'cfgEnv']; - var actualLoadOrder = Object.keys(appConfig).filter(function(k) { + const expectedLoadOrder = ['cfgLocal', 'cfgEnv']; + const actualLoadOrder = Object.keys(appConfig).filter(function(k) { return expectedLoadOrder.indexOf(k) !== -1; }); @@ -765,13 +765,13 @@ describe('compiler', function() { appdir.createConfigFilesSync(); appdir.writeFileSync( 'config.local.js', - 'module.exports = { fromJs: true };' + 'module.exports = { fromJs: true };', ); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; - var appConfig = instructions.application; + const instructions = context.instructions; + const appConfig = instructions.application; expect(appConfig).to.have.property('fromJs', true); done(); @@ -781,11 +781,11 @@ describe('compiler', function() { it('supports `appConfigRootDir` option', function(done) { appdir.createConfigFilesSync({port: 3000}); - var customDir = path.resolve(appdir.PATH, 'custom'); + const customDir = path.resolve(appdir.PATH, 'custom'); fs.mkdirsSync(customDir); fs.renameSync( path.resolve(appdir.PATH, 'config.json'), - path.resolve(customDir, 'config.json') + path.resolve(customDir, 'config.json'), ); boot.compile( @@ -795,22 +795,22 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.application).to.have.property('port'); done(); - } + }, ); }); it('supports `dsRootDir` option', function(done) { appdir.createConfigFilesSync(); - var customDir = path.resolve(appdir.PATH, 'custom'); + const customDir = path.resolve(appdir.PATH, 'custom'); fs.mkdirsSync(customDir); fs.renameSync( path.resolve(appdir.PATH, 'datasources.json'), - path.resolve(customDir, 'datasources.json') + path.resolve(customDir, 'datasources.json'), ); boot.compile( @@ -820,11 +820,11 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.dataSources).to.have.property('db'); done(); - } + }, ); }); @@ -841,24 +841,24 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.have.property('name', 'foo'); done(); - } + }, ); }); it('includes boot/*.js scripts', function(done) { appdir.createConfigFilesSync(); - var initJs = appdir.writeFileSync( + const initJs = appdir.writeFileSync( 'boot/init.js', - 'module.exports = function(app) { app.fnCalled = true; };' + 'module.exports = function(app) { app.fnCalled = true; };', ); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); }); @@ -866,9 +866,9 @@ describe('compiler', function() { it('supports `bootDirs` option', function(done) { appdir.createConfigFilesSync(); - var initJs = appdir.writeFileSync( + const initJs = appdir.writeFileSync( 'custom-boot/init.js', - 'module.exports = function(app) { app.fnCalled = true; };' + 'module.exports = function(app) { app.fnCalled = true; };', ); boot.compile( { @@ -877,18 +877,18 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); - } + }, ); }); it('should resolve relative path in `bootDirs`', function(done) { appdir.createConfigFilesSync(); - var initJs = appdir.writeFileSync( + const initJs = appdir.writeFileSync( 'custom-boot/init.js', - 'module.exports = function(app) { app.fnCalled = true; };' + 'module.exports = function(app) { app.fnCalled = true; };', ); boot.compile( { @@ -897,16 +897,16 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); - } + }, ); }); it('should resolve non-relative path in `bootDirs`', function(done) { appdir.createConfigFilesSync(); - var initJs = appdir.writeFileSync('custom-boot/init.js', ''); + const initJs = appdir.writeFileSync('custom-boot/init.js', ''); boot.compile( { appRootDir: appdir.PATH, @@ -914,10 +914,10 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); - } + }, ); }); @@ -931,17 +931,17 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.bootScripts).to.have.length(0); done(); - } + }, ); }); it('prefers coffeescript over json in `appRootDir/bootDir`', function(done) { appdir.createConfigFilesSync(); - var coffee = appdir.writeFileSync('./custom-boot/init.coffee', ''); + const coffee = appdir.writeFileSync('./custom-boot/init.coffee', ''); appdir.writeFileSync('./custom-boot/init.json', {}); boot.compile( @@ -951,17 +951,17 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.bootScripts).to.eql([coffee]); done(); - } + }, ); }); it('prefers coffeescript over json in `bootDir` non-relative path', function(done) { appdir.createConfigFilesSync(); - var coffee = appdir.writeFileSync('custom-boot/init.coffee', ''); + const coffee = appdir.writeFileSync('custom-boot/init.coffee', ''); appdir.writeFileSync('custom-boot/init.json', ''); boot.compile( @@ -971,18 +971,18 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.bootScripts).to.eql([coffee]); done(); - } + }, ); }); it('supports `bootScripts` option', function(done) { appdir.createConfigFilesSync(); - var initJs = appdir.writeFileSync( + const initJs = appdir.writeFileSync( 'custom-boot/init.js', - 'module.exports = function(app) { app.fnCalled = true; };' + 'module.exports = function(app) { app.fnCalled = true; };', ); boot.compile( { @@ -991,18 +991,18 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); - } + }, ); }); it('should remove duplicate scripts', function(done) { appdir.createConfigFilesSync(); - var initJs = appdir.writeFileSync( + const initJs = appdir.writeFileSync( 'custom-boot/init.js', - 'module.exports = function(app) { app.fnCalled = true; };' + 'module.exports = function(app) { app.fnCalled = true; };', ); boot.compile( { @@ -1012,18 +1012,18 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); - } + }, ); }); it('should resolve relative path in `bootScripts`', function(done) { appdir.createConfigFilesSync(); - var initJs = appdir.writeFileSync( + const initJs = appdir.writeFileSync( 'custom-boot/init.js', - 'module.exports = function(app) { app.fnCalled = true; };' + 'module.exports = function(app) { app.fnCalled = true; };', ); boot.compile( { @@ -1032,16 +1032,16 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); - } + }, ); }); it('should resolve non-relative path in `bootScripts`', function(done) { appdir.createConfigFilesSync(); - var initJs = appdir.writeFileSync('custom-boot/init.js', ''); + const initJs = appdir.writeFileSync('custom-boot/init.js', ''); boot.compile( { appRootDir: appdir.PATH, @@ -1049,16 +1049,16 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); - } + }, ); }); it('resolves missing extensions in `bootScripts`', function(done) { appdir.createConfigFilesSync(); - var initJs = appdir.writeFileSync('custom-boot/init.js', ''); + const initJs = appdir.writeFileSync('custom-boot/init.js', ''); boot.compile( { appRootDir: appdir.PATH, @@ -1066,17 +1066,17 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); - } + }, ); }); it('resolves missing extensions in `bootScripts` in module relative path', function(done) { appdir.createConfigFilesSync(); - var initJs = appdir.writeFileSync('node_modules/custom-boot/init.js', + const initJs = appdir.writeFileSync('node_modules/custom-boot/init.js', ''); boot.compile( @@ -1086,16 +1086,19 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); - } + }, ); }); it('resolves module relative path for `bootScripts`', function(done) { appdir.createConfigFilesSync(); - var initJs = appdir.writeFileSync('node_modules/custom-boot/init.js', ''); + const initJs = appdir.writeFileSync( + 'node_modules/custom-boot/init.js', + '', + ); boot.compile( { appRootDir: appdir.PATH, @@ -1103,16 +1106,16 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); - } + }, ); }); it('explores `bootScripts` in app relative path', function(done) { appdir.createConfigFilesSync(); - var appJs = appdir.writeFileSync('./custom-boot/init.js', ''); + const appJs = appdir.writeFileSync('./custom-boot/init.js', ''); appdir.writeFileSync('node_modules/custom-boot/init.js', ''); @@ -1123,10 +1126,10 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.bootScripts).to.eql([appJs]); done(); - } + }, ); }); @@ -1136,7 +1139,7 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.bootScripts).to.not.have.property('models'); done(); @@ -1150,7 +1153,7 @@ describe('compiler', function() { {}, { foo: {properties: {name: 'string'}}, - } + }, ); expectCompileToThrow(/unsupported 1\.x format/, done); @@ -1163,7 +1166,7 @@ describe('compiler', function() { {}, { Customer: {options: {base: 'User'}}, - } + }, ); expectCompileToThrow(/unsupported 1\.x format/, done); @@ -1175,14 +1178,14 @@ describe('compiler', function() { {}, { Car: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('models/car.json', {name: 'Car'}); appdir.writeFileSync('models/car.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.eql({ @@ -1205,14 +1208,14 @@ describe('compiler', function() { {}, { Car: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('models/car.json', {name: 'Car'}); appdir.writeFileSync('models/car.coffee', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.eql({ @@ -1235,7 +1238,7 @@ describe('compiler', function() { {}, { Car: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('custom-models/car.json', {name: 'Car'}); appdir.writeFileSync('custom-models/car.js', ''); @@ -1247,7 +1250,7 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.eql({ @@ -1261,7 +1264,7 @@ describe('compiler', function() { sourceFile: path.resolve(appdir.PATH, 'custom-models', 'car.js'), }); done(); - } + }, ); }); @@ -1274,14 +1277,14 @@ describe('compiler', function() { sources: ['./custom-models'], }, Car: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('custom-models/car.json', {name: 'Car'}); appdir.writeFileSync('custom-models/car.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.eql({ @@ -1304,7 +1307,7 @@ describe('compiler', function() { {}, { User: {dataSource: 'db'}, - } + }, ); boot.compile( @@ -1317,7 +1320,7 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.eql({ @@ -1329,7 +1332,7 @@ describe('compiler', function() { sourceFile: require.resolve('loopback/common/models/user.js'), }); done(); - } + }, ); }); @@ -1339,10 +1342,10 @@ describe('compiler', function() { {}, { Car: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('custom-models/car.json', {name: 'Car'}); - var appJS = appdir.writeFileSync('custom-models/car.js', ''); + const appJS = appdir.writeFileSync('custom-models/car.js', ''); boot.compile( { @@ -1351,12 +1354,12 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0].sourceFile).to.equal(appJS); done(); - } + }, ); }); @@ -1367,12 +1370,12 @@ describe('compiler', function() { {}, { Car: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('node_modules/custom-models/car.json', { name: 'Car', }); - var appJS = appdir.writeFileSync('node_modules/custom-models/car.js', + const appJS = appdir.writeFileSync('node_modules/custom-models/car.js', ''); boot.compile( @@ -1382,12 +1385,12 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0].sourceFile).to.equal(appJS); done(); - } + }, ); }); @@ -1401,14 +1404,14 @@ describe('compiler', function() { sources: ['./custom-models'], }, Car: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('custom-models/car.json', {name: 'Car'}); - var appJS = appdir.writeFileSync('custom-models/car.js', ''); + const appJS = appdir.writeFileSync('custom-models/car.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0].sourceFile).to.equal(appJS); @@ -1426,18 +1429,18 @@ describe('compiler', function() { sources: ['custom-models'], }, Car: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('node_modules/custom-models/car.json', { name: 'Car', }); - var appJS = appdir.writeFileSync('node_modules/custom-models/car.js', + const appJS = appdir.writeFileSync('node_modules/custom-models/car.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0].sourceFile).to.equal(appJS); @@ -1451,13 +1454,13 @@ describe('compiler', function() { {}, { Car: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('models/car.json', {name: 'Car'}); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models).to.eql([ { @@ -1481,16 +1484,16 @@ describe('compiler', function() { {}, { Car: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('models/car.json', {name: 'Car'}); appdir.writeConfigFileSync('models/bar.json', {name: 'Bar'}); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var models = instructions.models.map(getNameProperty); + const models = instructions.models.map(getNameProperty); expect(models).to.eql(['Car']); done(); }); @@ -1502,7 +1505,7 @@ describe('compiler', function() { {}, { Car: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('models/car.json', { name: 'Car', @@ -1514,9 +1517,9 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; - var models = instructions.models; - var modelNames = models.map(getNameProperty); + const instructions = context.instructions; + const models = instructions.models; + const modelNames = models.map(getNameProperty); expect(modelNames).to.eql(['Vehicle', 'Car']); expect(models[0].config).to.equal(undefined); @@ -1530,7 +1533,7 @@ describe('compiler', function() { {}, { Car: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('models/car.json', { name: 'Car', @@ -1539,9 +1542,9 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var modelNames = instructions.models.map(getNameProperty); + const modelNames = instructions.models.map(getNameProperty); expect(modelNames).to.eql(['Car']); done(); }); @@ -1555,7 +1558,7 @@ describe('compiler', function() { Vehicle: {dataSource: 'db'}, FlyingCar: {dataSource: 'db'}, Car: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('models/car.json', { name: 'Car', @@ -1571,9 +1574,9 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var modelNames = instructions.models.map(getNameProperty); + const modelNames = instructions.models.map(getNameProperty); expect(modelNames).to.eql(['Vehicle', 'Car', 'FlyingCar']); done(); }); @@ -1586,7 +1589,7 @@ describe('compiler', function() { { Vehicle: {dataSource: 'db'}, Car: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('models/car.json', { name: 'Car', @@ -1606,15 +1609,15 @@ describe('compiler', function() { {}, { Car: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('models/car.json', {}); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var modelNames = instructions.models.map(getNameProperty); + const modelNames = instructions.models.map(getNameProperty); expect(modelNames).to.eql(['Car']); done(); }); @@ -1627,15 +1630,15 @@ describe('compiler', function() { {}, { OrderItem: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('models/order-item.json', {}); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var modelNames = instructions.models.map(getNameProperty); + const modelNames = instructions.models.map(getNameProperty); expect(modelNames).to.eql(['OrderItem']); done(); }); @@ -1648,15 +1651,15 @@ describe('compiler', function() { {}, { OrderItem: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('models/order_item.json', {}); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var modelNames = instructions.models.map(getNameProperty); + const modelNames = instructions.models.map(getNameProperty); expect(modelNames).to.eql(['OrderItem']); done(); }); @@ -1669,15 +1672,15 @@ describe('compiler', function() { {}, { OrderItem: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('models/order item.json', {}); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var modelNames = instructions.models.map(getNameProperty); + const modelNames = instructions.models.map(getNameProperty); expect(modelNames).to.eql(['OrderItem']); done(); }); @@ -1690,15 +1693,15 @@ describe('compiler', function() { {}, { overrideCar: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('models/car.json', {name: 'overrideCar'}); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var modelNames = instructions.models.map(getNameProperty); + const modelNames = instructions.models.map(getNameProperty); expect(modelNames).to.eql(['overrideCar']); done(); }); @@ -1710,7 +1713,7 @@ describe('compiler', function() { {}, { OrderItem: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('models/order-item.json', { @@ -1725,11 +1728,11 @@ describe('compiler', function() { quantity: {type: 'number'}, }, }); - var appJS = appdir.writeFileSync('models/orderItem.js', ''); + const appJS = appdir.writeFileSync('models/orderItem.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models).to.eql([ { @@ -1756,7 +1759,7 @@ describe('compiler', function() { {}, { customOrder: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('models/order1.json', { @@ -1773,11 +1776,11 @@ describe('compiler', function() { quantity: {type: 'number'}, }, }); - var appJS = appdir.writeFileSync('models/order2.js', ''); + const appJS = appdir.writeFileSync('models/order2.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.models).to.eql([ { @@ -1803,12 +1806,12 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; instructions.application.modified = true; boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.application).to.not.have.property('modified'); done(); }); @@ -1818,7 +1821,7 @@ describe('compiler', function() { describe('for mixins', function() { describe(' - mixinDirs', function(done) { function verifyMixinIsFoundViaMixinDirs(sourceFile, mixinDirs, done) { - var appJS = appdir.writeFileSync(sourceFile, ''); + const appJS = appdir.writeFileSync(sourceFile, ''); boot.compile( { @@ -1827,10 +1830,10 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.mixins[0].sourceFile).to.eql(appJS); done(); - } + }, ); } @@ -1838,7 +1841,7 @@ describe('compiler', function() { verifyMixinIsFoundViaMixinDirs( 'custom-mixins/other.js', ['./custom-mixins'], - done + done, ); }); @@ -1846,7 +1849,7 @@ describe('compiler', function() { verifyMixinIsFoundViaMixinDirs( 'custom-mixins/other.js', ['./custom-mixins'], - done + done, ); }); @@ -1855,7 +1858,7 @@ describe('compiler', function() { verifyMixinIsFoundViaMixinDirs( 'node_modules/custom-mixins/other.js', ['custom-mixins'], - done + done, ); }); }); @@ -1867,7 +1870,7 @@ describe('compiler', function() { {}, { Car: {dataSource: 'db'}, - } + }, ); appdir.writeConfigFileSync('models/car.json', { name: 'Car', @@ -1878,9 +1881,9 @@ describe('compiler', function() { function verifyMixinIsFoundViaMixinSources( sourceFile, mixinSources, - done + done, ) { - var appJS = appdir.writeFileSync(sourceFile, ''); + const appJS = appdir.writeFileSync(sourceFile, ''); boot.compile( { @@ -1889,10 +1892,10 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.mixins[0].sourceFile).to.eql(appJS); done(); - } + }, ); } @@ -1900,7 +1903,7 @@ describe('compiler', function() { verifyMixinIsFoundViaMixinSources( 'mixins/time-stamps.js', ['./mixins'], - done + done, ); }); @@ -1908,7 +1911,7 @@ describe('compiler', function() { verifyMixinIsFoundViaMixinSources( 'custom-mixins/time-stamps.js', ['./custom-mixins'], - done + done, ); }); @@ -1917,7 +1920,7 @@ describe('compiler', function() { verifyMixinIsFoundViaMixinSources( 'node_modules/custom-mixins/time-stamps.js', ['custom-mixins'], - done + done, ); }); @@ -1932,13 +1935,16 @@ describe('compiler', function() { Car: { dataSource: 'db', }, - } + }, ); - var appJS = appdir.writeFileSync('custom-mixins/time-stamps.js', ''); + const appJS = appdir.writeFileSync( + 'custom-mixins/time-stamps.js', + '', + ); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.mixins[0].sourceFile).to.eql(appJS); done(); }); @@ -1946,22 +1952,22 @@ describe('compiler', function() { it('sets by default `mixinSources` to `mixins` directory', function(done) { - var appJS = appdir.writeFileSync('mixins/time-stamps.js', ''); + const appJS = appdir.writeFileSync('mixins/time-stamps.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.mixins[0].sourceFile).to.eql(appJS); done(); }); }); it('loads only mixins used by models', function(done) { - var appJS = appdir.writeFileSync('mixins/time-stamps.js', ''); + const appJS = appdir.writeFileSync('mixins/time-stamps.js', ''); appdir.writeFileSync('mixins/foo.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.mixins).to.have.length(1); expect(instructions.mixins[0].sourceFile).to.eql(appJS); done(); @@ -1970,7 +1976,7 @@ describe('compiler', function() { it('loads mixins from model using mixin name in JSON file', function(done) { - var appJS = appdir.writeFileSync('mixins/time-stamps.js', ''); + const appJS = appdir.writeFileSync('mixins/time-stamps.js', ''); appdir.writeConfigFileSync('mixins/time-stamps.json', { name: 'Timestamping', }); @@ -1982,7 +1988,7 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.mixins).to.have.length(1); expect(instructions.mixins[0].sourceFile).to.eql(appJS); done(); @@ -1991,10 +1997,10 @@ describe('compiler', function() { it('loads mixin only once for dirs common to mixinDirs & mixinSources', function(done) { - var appJS = appdir.writeFileSync('custom-mixins/time-stamps.js', + const appJS = appdir.writeFileSync('custom-mixins/time-stamps.js', ''); - var options = { + const options = { appRootDir: appdir.PATH, mixinDirs: ['./custom-mixins'], mixinSources: ['./custom-mixins'], @@ -2002,7 +2008,7 @@ describe('compiler', function() { boot.compile(options, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.mixins).to.have.length(1); expect(instructions.mixins[0].sourceFile).to.eql(appJS); done(); @@ -2012,9 +2018,12 @@ describe('compiler', function() { it('loads mixin from mixinSources, when it is also found in mixinDirs', function(done) { appdir.writeFileSync('mixinDir/time-stamps.js', ''); - var appJS = appdir.writeFileSync('mixinSource/time-stamps.js', ''); + const appJS = appdir.writeFileSync( + 'mixinSource/time-stamps.js', + '', + ); - var options = { + const options = { appRootDir: appdir.PATH, mixinDirs: ['./mixinDir'], mixinSources: ['./mixinSource'], @@ -2022,7 +2031,7 @@ describe('compiler', function() { boot.compile(options, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.mixins).to.have.length(1); expect(instructions.mixins[0].sourceFile).to.eql(appJS); done(); @@ -2031,16 +2040,16 @@ describe('compiler', function() { it('loads mixin from the most recent mixin definition', function(done) { appdir.writeFileSync('mixins1/time-stamps.js', ''); - var mixins2 = appdir.writeFileSync('mixins2/time-stamps.js', ''); + const mixins2 = appdir.writeFileSync('mixins2/time-stamps.js', ''); - var options = { + const options = { appRootDir: appdir.PATH, mixinSources: ['./mixins1', './mixins2'], }; boot.compile(options, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.mixins).to.have.length(1); expect(instructions.mixins[0].sourceFile).to.eql(mixins2); done(); @@ -2049,7 +2058,7 @@ describe('compiler', function() { }); describe('name normalization', function() { - var options; + let options; beforeEach(function() { options = {appRootDir: appdir.PATH, mixinDirs: ['./custom-mixins']}; @@ -2064,10 +2073,10 @@ describe('compiler', function() { options.normalization = 'classify'; boot.compile(options, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var mixins = instructions.mixins; - var mixinNames = mixins.map(getNameProperty); + const mixins = instructions.mixins; + const mixinNames = mixins.map(getNameProperty); expect(mixinNames).to.eql([ 'CamelCase', @@ -2084,10 +2093,10 @@ describe('compiler', function() { options.normalization = 'dasherize'; boot.compile(options, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var mixins = instructions.mixins; - var mixinNames = mixins.map(getNameProperty); + const mixins = instructions.mixins; + const mixinNames = mixins.map(getNameProperty); expect(mixinNames).to.eql([ 'camel-case', @@ -2101,16 +2110,16 @@ describe('compiler', function() { }); it('supports custom function', function(done) { - var normalize = function(name) { + const normalize = function(name) { return name.toUpperCase(); }; options.normalization = normalize; boot.compile(options, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var mixins = instructions.mixins; - var mixinNames = mixins.map(getNameProperty); + const mixins = instructions.mixins; + const mixinNames = mixins.map(getNameProperty); expect(mixinNames).to.eql([ 'CAMELCASE', @@ -2127,10 +2136,10 @@ describe('compiler', function() { options.normalization = 'none'; boot.compile(options, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var mixins = instructions.mixins; - var mixinNames = mixins.map(getNameProperty); + const mixins = instructions.mixins; + const mixinNames = mixins.map(getNameProperty); expect(mixinNames).to.eql([ 'camelCase', @@ -2147,10 +2156,10 @@ describe('compiler', function() { options.normalization = false; boot.compile(options, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var mixins = instructions.mixins; - var mixinNames = mixins.map(getNameProperty); + const mixins = instructions.mixins; + const mixinNames = mixins.map(getNameProperty); expect(mixinNames).to.eql([ 'camelCase', @@ -2166,10 +2175,10 @@ describe('compiler', function() { it('defaults to classify', function(done) { boot.compile(options, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var mixins = instructions.mixins; - var mixinNames = mixins.map(getNameProperty); + const mixins = instructions.mixins; + const mixinNames = mixins.map(getNameProperty); expect(mixinNames).to.eql([ 'CamelCase', @@ -2188,7 +2197,7 @@ describe('compiler', function() { expectCompileToThrow( /Invalid normalization format - "invalidFormat"/, options, - done + done, ); }); }); @@ -2197,13 +2206,13 @@ describe('compiler', function() { appdir.writeFileSync('mixins/foo.js', ''); appdir.writeConfigFileSync('mixins/foo.json', {name: 'fooBar'}); - var options = { + const options = { appRootDir: appdir.PATH, mixinDirs: ['./mixins'], }; boot.compile(options, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.mixins[0].name).to.eql('fooBar'); done(); @@ -2211,7 +2220,7 @@ describe('compiler', function() { }); it('extends definition from JSON with same file name', function(done) { - var appJS = appdir.writeFileSync('custom-mixins/foo-bar.js', ''); + const appJS = appdir.writeFileSync('custom-mixins/foo-bar.js', ''); appdir.writeConfigFileSync('custom-mixins/foo-bar.json', { description: 'JSON file name same as JS file name', @@ -2220,14 +2229,14 @@ describe('compiler', function() { description: 'JSON file name same as normalized name of mixin', }); - var options = { + const options = { appRootDir: appdir.PATH, mixinDirs: ['./custom-mixins'], normalization: 'classify', }; boot.compile(options, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.mixins).to.eql([ { @@ -2244,7 +2253,7 @@ describe('compiler', function() { describe('for middleware', function() { function testMiddlewareRegistration(middlewareId, sourceFile, done) { - var json = { + const json = { initial: {}, custom: {}, }; @@ -2257,7 +2266,7 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware).to.eql({ phases: ['initial', 'custom'], @@ -2275,11 +2284,11 @@ describe('compiler', function() { }); } - var sourceFileForUrlNotFound; + let sourceFileForUrlNotFound; beforeEach(function() { fs.copySync(SIMPLE_APP, appdir.PATH); sourceFileForUrlNotFound = require.resolve( - 'loopback/server/middleware/url-not-found' + 'loopback/server/middleware/url-not-found', ); }); @@ -2287,7 +2296,7 @@ describe('compiler', function() { testMiddlewareRegistration( 'loopback/server/middleware/url-not-found', sourceFileForUrlNotFound, - done + done, ); }); @@ -2295,12 +2304,12 @@ describe('compiler', function() { testMiddlewareRegistration( 'loopback#url-not-found', sourceFileForUrlNotFound, - done + done, ); }); it('supports `middlewareRootDir` option', function(done) { - var middlewareJson = { + const middlewareJson = { initial: {}, custom: { 'loopback/server/middleware/url-not-found': { @@ -2308,11 +2317,11 @@ describe('compiler', function() { }, }, }; - var customDir = path.resolve(appdir.PATH, 'custom'); + const customDir = path.resolve(appdir.PATH, 'custom'); fs.mkdirsSync(customDir); fs.writeJsonSync( path.resolve(customDir, 'middleware.json'), - middlewareJson + middlewareJson, ); boot.compile( { @@ -2320,7 +2329,7 @@ describe('compiler', function() { middlewareRootDir: customDir, }, function(err, context) { - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware).to.eql({ phases: ['initial', 'custom'], middleware: [ @@ -2334,7 +2343,7 @@ describe('compiler', function() { ], }); done(); - } + }, ); }); @@ -2396,7 +2405,7 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware).to.eql({ phases: ['routes'], @@ -2434,7 +2443,7 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expectFirstMiddlewareParams(instructions).to.eql({ key: 'custom value', @@ -2464,11 +2473,11 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware.middleware[0].config).to.have.property( 'enabled', - false + false, ); done(); }); @@ -2477,7 +2486,7 @@ describe('compiler', function() { function verifyMiddlewareConfig(done) { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware.middleware).to.eql([ { @@ -2604,7 +2613,7 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware.middleware).to.eql([ { @@ -2655,7 +2664,7 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware.middleware).to.eql([ { @@ -2695,7 +2704,7 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware.phases, 'phases').to.eql([ 'initial', @@ -2704,7 +2713,7 @@ describe('compiler', function() { expect(instructions.middleware.middleware, 'middleware').to.eql([ { sourceFile: require.resolve( - 'loopback/server/middleware/url-not-found' + 'loopback/server/middleware/url-not-found', ), config: { phase: 'custom:before', @@ -2733,7 +2742,7 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware.middleware).to.eql([ { @@ -2764,10 +2773,10 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware.middleware[0].sourceFile).to.equal( - require.resolve('loopback/server/middleware/url-not-found') + require.resolve('loopback/server/middleware/url-not-found'), ); done(); }); @@ -2782,14 +2791,14 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware.middleware[0].sourceFile).to.equal( - path.resolve(appdir.PATH, './middleware/index.js') + path.resolve(appdir.PATH, './middleware/index.js'), ); expect(instructions.middleware.middleware[0]).have.property( 'fragment', - 'myMiddleware' + 'myMiddleware', ); done(); }); @@ -2805,25 +2814,25 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware.middleware[0]).have.property( 'sourceFile', - pathWithoutIndex(require.resolve('loopback')) + pathWithoutIndex(require.resolve('loopback')), ); expect(instructions.middleware.middleware[0]).have.property( 'fragment', - 'errorHandler' + 'errorHandler', ); done(); }); }); it('resolves modules relative to appRootDir', function(done) { - var HANDLER_FILE = 'node_modules/handler/index.js'; + const HANDLER_FILE = 'node_modules/handler/index.js'; appdir.writeFileSync( HANDLER_FILE, - 'module.exports = function(req, res, next) { next(); }' + 'module.exports = function(req, res, next) { next(); }', ); appdir.writeConfigFileSync('middleware.json', { @@ -2834,18 +2843,18 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware.middleware[0]).have.property( 'sourceFile', - pathWithoutIndex(appdir.resolve(HANDLER_FILE)) + pathWithoutIndex(appdir.resolve(HANDLER_FILE)), ); done(); }); }); it('prefers appRootDir over node_modules for middleware', function(done) { - var appJS = appdir.writeFileSync('./my-middleware.js', ''); + const appJS = appdir.writeFileSync('./my-middleware.js', ''); appdir.writeFileSync('node_modules/my-middleware.js', ''); appdir.writeConfigFileSync('middleware.json', { routes: { @@ -2855,12 +2864,12 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware.middleware).to.have.length(1); expect(instructions.middleware.middleware[0]).have.property( 'sourceFile', - appJS + appJS, ); done(); }); @@ -2869,7 +2878,7 @@ describe('compiler', function() { it('does not treat module relative path as `appRootDir` relative', function(done) { appdir.writeFileSync('./my-middleware.js', ''); - var moduleJS = appdir.writeFileSync('node_modules/my-middleware.js', + const moduleJS = appdir.writeFileSync('node_modules/my-middleware.js', ''); appdir.writeConfigFileSync('middleware.json', { routes: { @@ -2879,19 +2888,19 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware.middleware).to.have.length(1); expect(instructions.middleware.middleware[0]).have.property( 'sourceFile', - moduleJS + moduleJS, ); done(); }); }); it('loads middleware from coffeescript in appRootdir', function(done) { - var coffee = appdir.writeFileSync('my-middleware.coffee', ''); + const coffee = appdir.writeFileSync('my-middleware.coffee', ''); appdir.writeConfigFileSync('middleware.json', { routes: { './my-middleware': {}, @@ -2900,20 +2909,20 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware.middleware[0]).have.property( 'sourceFile', - coffee + coffee, ); done(); }); }); it('loads coffeescript from middleware under node_modules', function(done) { - var file = appdir.writeFileSync( + const file = appdir.writeFileSync( 'node_modules/my-middleware/index.coffee', - '' + '', ); appdir.writeFileSync('node_modules/my-middleware/index.json', ''); appdir.writeConfigFileSync('middleware.json', { @@ -2924,12 +2933,12 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware.middleware).to.have.length(1); expect(instructions.middleware.middleware[0]).have.property( 'sourceFile', - pathWithoutIndex(file) + pathWithoutIndex(file), ); done(); }); @@ -2937,7 +2946,7 @@ describe('compiler', function() { it('prefers coffeescript over json for relative middleware path', function(done) { - var coffee = appdir.writeFileSync('my-middleware.coffee', ''); + const coffee = appdir.writeFileSync('my-middleware.coffee', ''); appdir.writeFileSync('my-middleware.json', ''); appdir.writeConfigFileSync('middleware.json', { routes: { @@ -2947,12 +2956,12 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware.middleware).to.have.length(1); expect(instructions.middleware.middleware[0]).have.property( 'sourceFile', - coffee + coffee, ); done(); }); @@ -2960,9 +2969,9 @@ describe('compiler', function() { it('prefers coffeescript over json for module relative middleware path', function(done) { - var coffee = appdir.writeFileSync( + const coffee = appdir.writeFileSync( 'node_modules/my-middleware.coffee', - '' + '', ); appdir.writeFileSync('node_modules/my-middleware.json', ''); appdir.writeConfigFileSync('middleware.json', { @@ -2973,25 +2982,25 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware.middleware).to.have.length(1); expect(instructions.middleware.middleware[0]).have.property( 'sourceFile', - coffee + coffee, ); done(); }); }); it('ignores sourcmap files when loading middleware', function(done) { - var middleware = appdir.writeFileSync( + const middleware = appdir.writeFileSync( 'my-middleware.js', - '// I am the middleware' + '// I am the middleware', ); - var sourcemap = appdir.writeFileSync( + const sourcemap = appdir.writeFileSync( 'my-middleware.js.map', - '// I am a sourcemap' + '// I am a sourcemap', ); appdir.writeConfigFileSync('middleware.json', { routes: { @@ -3001,20 +3010,20 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.middleware.middleware[0]).have.property( 'sourceFile', - middleware + middleware, ); done(); }); }); describe('config with relative paths in params', function() { - var RELATIVE_PATH_PARAMS = ['$!./here', '$!../there']; + const RELATIVE_PATH_PARAMS = ['$!./here', '$!../there']; - var absolutePathParams; + let absolutePathParams; beforeEach(function resolveRelativePathParams() { absolutePathParams = RELATIVE_PATH_PARAMS.map(function(p) { return appdir.resolve(p.slice(2)); @@ -3026,7 +3035,7 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expectFirstMiddlewareParams(instructions).to.eql(absolutePathParams); done(); @@ -3042,7 +3051,7 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expectFirstMiddlewareParams(instructions).to.eql({ path: absolutePathParams[0], @@ -3056,10 +3065,10 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expectFirstMiddlewareParams(instructions).to.eql( - absolutePathParams[0] + absolutePathParams[0], ); done(); }); @@ -3077,7 +3086,7 @@ describe('compiler', function() { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expectFirstMiddlewareParams(instructions).to.eql({ nestedObject: { @@ -3091,12 +3100,12 @@ describe('compiler', function() { it('does not convert values not starting with `./` or `../`', function(done) { - var PARAMS = ['$!.somerc', '$!/root', '$!hello!']; + const PARAMS = ['$!.somerc', '$!/root', '$!hello!']; givenMiddlewareEntrySync({params: PARAMS}); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expectFirstMiddlewareParams(instructions).to.eql(PARAMS); done(); @@ -3115,16 +3124,16 @@ describe('compiler', function() { debug: {local: 'applied'}, }); - var env = process.env.NODE_ENV || 'development'; + const env = process.env.NODE_ENV || 'development'; appdir.writeConfigFileSync('component-config.' + env + '.json', { debug: {env: 'applied'}, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; - var component = instructions.components[0]; + const component = instructions.components[0]; expect(component).to.eql({ sourceFile: require.resolve('debug'), config: { @@ -3138,16 +3147,16 @@ describe('compiler', function() { }); it('supports `componentRootDir` option', function(done) { - var componentJson = { + const componentJson = { debug: { option: 'value', }, }; - var customDir = path.resolve(appdir.PATH, 'custom'); + const customDir = path.resolve(appdir.PATH, 'custom'); fs.mkdirsSync(customDir); fs.writeJsonSync( path.resolve(customDir, 'component-config.json'), - componentJson + componentJson, ); boot.compile( @@ -3157,8 +3166,8 @@ describe('compiler', function() { }, function(err, context) { if (err) return done(err); - var instructions = context.instructions; - var component = instructions.components[0]; + const instructions = context.instructions; + const component = instructions.components[0]; expect(component).to.eql({ sourceFile: require.resolve('debug'), config: { @@ -3166,7 +3175,7 @@ describe('compiler', function() { }, }); done(); - } + }, ); }); @@ -3174,11 +3183,11 @@ describe('compiler', function() { appdir.writeConfigFileSync('./component-config.json', { './index': {}, }); - var appJS = appdir.writeConfigFileSync('index.js', ''); + const appJS = appdir.writeConfigFileSync('index.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.components[0]).have.property('sourceFile', appJS); done(); }); @@ -3188,14 +3197,14 @@ describe('compiler', function() { appdir.writeConfigFileSync('component-config.json', { mycomponent: {}, }); - var js = appdir.writeConfigFileSync( + const js = appdir.writeConfigFileSync( 'node_modules/mycomponent/index.js', - '' + '', ); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.components[0]).have.property('sourceFile', js); done(); }); @@ -3210,7 +3219,7 @@ describe('compiler', function() { expectCompileToThrow( 'Cannot resolve path "my-component/component.js"', - done + done, ); }); @@ -3220,17 +3229,17 @@ describe('compiler', function() { './component': {}, }); - var coffee = appdir.writeFileSync('component.coffee', ''); + const coffee = appdir.writeFileSync('component.coffee', ''); appdir.writeFileSync('component.json', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.components).to.have.length(1); expect(instructions.components[0]).have.property( 'sourceFile', - coffee + coffee, ); done(); }); @@ -3242,17 +3251,20 @@ describe('compiler', function() { component: {}, }); - var coffee = appdir.writeFileSync('node_modules/component.coffee', ''); + const coffee = appdir.writeFileSync( + 'node_modules/component.coffee', + '', + ); appdir.writeFileSync('node_modules/component.json', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); - var instructions = context.instructions; + const instructions = context.instructions; expect(instructions.components).to.have.length(1); expect(instructions.components[0]).have.property( 'sourceFile', - coffee + coffee, ); done(); }); @@ -3280,7 +3292,7 @@ function expectFirstMiddlewareParams(instructions) { function pathWithoutExtension(value) { return path.join( path.dirname(value), - path.basename(value, path.extname(value)) + path.basename(value, path.extname(value)), ); } diff --git a/test/executor.test.js b/test/executor.test.js index 529959a..fd6ad7c 100644 --- a/test/executor.test.js +++ b/test/executor.test.js @@ -5,27 +5,27 @@ 'use strict'; -var async = require('async'); -var boot = require('../'); -var path = require('path'); -var loopback = require('loopback'); -var assert = require('assert'); +const async = require('async'); +const boot = require('../'); +const path = require('path'); +const loopback = require('loopback'); +const assert = require('assert'); -var chai = require('chai'); -var dirtyChai = require('dirty-chai'); -var expect = chai.expect; +const chai = require('chai'); +const dirtyChai = require('dirty-chai'); +const expect = chai.expect; chai.use(dirtyChai); -var fs = require('fs-extra'); -var sandbox = require('./helpers/sandbox'); -var appdir = require('./helpers/appdir'); -var supertest = require('supertest'); -var os = require('os'); +const fs = require('fs-extra'); +const sandbox = require('./helpers/sandbox'); +const appdir = require('./helpers/appdir'); +const supertest = require('supertest'); +const os = require('os'); -var SIMPLE_APP = path.join(__dirname, 'fixtures', 'simple-app'); -var ENV_APP = path.join(__dirname, 'fixtures', 'env-app'); +const SIMPLE_APP = path.join(__dirname, 'fixtures', 'simple-app'); +const ENV_APP = path.join(__dirname, 'fixtures', 'env-app'); -var app; +let app; describe('executor', function() { beforeEach(sandbox.reset); @@ -43,7 +43,7 @@ describe('executor', function() { delete process.bootFlags; }); - var dummyInstructions = someInstructions({ + const dummyInstructions = someInstructions({ application: { port: 0, host: '127.0.0.1', @@ -134,7 +134,7 @@ describe('executor', function() { expect(app.models.Customer).to.exist(); expect(app.models.Customer.settings._customized).to.be.equal('Customer'); - var UserModel = app.registry.getModel('User'); + const UserModel = app.registry.getModel('User'); expect(UserModel.settings._customized).to.equal('Base'); done(); }); @@ -232,7 +232,7 @@ describe('executor', function() { }); it('throws on bad require() call inside boot script', function(done) { - var file = appdir.writeFileSync('boot/badScript.js', + const file = appdir.writeFileSync('boot/badScript.js', 'require("doesnt-exist"); module.exports = {};'); boot.execute(app, someInstructions({bootScripts: [file]}), @@ -261,7 +261,7 @@ describe('executor', function() { // loopback-datasource-juggler quirk: // Model.dataSources has modelBuilder as the default value, // therefore it's not enough to assert a false-y value - var actual = loopback.Email.dataSource instanceof loopback.DataSource ? + const actual = loopback.Email.dataSource instanceof loopback.DataSource ? 'attached' : 'not attached'; expect(actual).to.equal('not attached'); done(); @@ -269,10 +269,10 @@ describe('executor', function() { }); it('skips definition of already defined LoopBack models', function(done) { - var builtinModel = { + const builtinModel = { name: 'User', definition: fs.readJsonSync( - require.resolve('loopback/common/models/user.json') + require.resolve('loopback/common/models/user.json'), ), config: {dataSource: 'db'}, sourceFile: require.resolve('loopback/common/models/user.js'), @@ -412,7 +412,7 @@ describe('executor', function() { }); describe('for mixins', function() { - var options; + let options; beforeEach(function() { appdir.writeFileSync('custom-mixins/example.js', 'module.exports = ' + @@ -436,8 +436,8 @@ describe('executor', function() { options.mixinDirs = ['./custom-mixins']; boot(app, options, function(err) { if (err) return done(err); - var modelBuilder = app.registry.modelBuilder; - var registry = modelBuilder.mixins.mixins; + const modelBuilder = app.registry.modelBuilder; + const registry = modelBuilder.mixins.mixins; expect(Object.keys(registry)).to.eql(['Example', 'Timestamping']); done(); }); @@ -449,8 +449,8 @@ describe('executor', function() { boot(app, options, function(err) { if (err) return done(err); - var modelBuilder = app.registry.modelBuilder; - var registry = modelBuilder.mixins.mixins; + const modelBuilder = app.registry.modelBuilder; + const registry = modelBuilder.mixins.mixins; expect(Object.keys(registry)).to.eql(['Example', 'Timestamping']); done(); }); @@ -581,7 +581,7 @@ describe('executor', function() { }); it('should respect named pipes port values in ENV', function(done) { - var NAMED_PORT = '\\.\\pipe\\test'; + const NAMED_PORT = '\\.\\pipe\\test'; process.env.PORT = NAMED_PORT; boot.execute(app, someInstructions({application: {port: 3000}}), function(err) { @@ -627,8 +627,7 @@ describe('executor', function() { it('dynamic variable from `env var` should have' + ' precedence over app.get()', function(done) { process.env.restApiRoot = '/url-from-env-var'; - var bootInstructions; - bootInstructions = simpleMiddlewareConfig('routes', + const bootInstructions = simpleMiddlewareConfig('routes', {path: '${restApiRoot}'}); bootInstructions.application = {restApiRoot: '/url-from-config'}; boot.execute(app, someInstructions(bootInstructions), function(err) { @@ -665,7 +664,7 @@ describe('executor', function() { supertest(app).get('/').end(function(err, res) { if (err) return done(err); expect(res.body.paths).to.eql( - [app.get('restApiRoot')] + [app.get('restApiRoot')], ); done(); }); @@ -721,10 +720,10 @@ describe('executor', function() { }); it('should not parse invalid config variables', function(done) { - var invalidDataTypes = [undefined, function() { + const invalidDataTypes = [undefined, function() { }]; async.each(invalidDataTypes, function(invalidDataType, cb) { - var config = simpleMiddlewareConfig('routes', { + const config = simpleMiddlewareConfig('routes', { path: invalidDataType, }); boot.execute(app, config, function(err) { @@ -742,7 +741,7 @@ describe('executor', function() { }); it('should parse valid config variables', function(done) { - var config = simpleMiddlewareConfig('routes', { + const config = simpleMiddlewareConfig('routes', { props: ['a', '${vVar}', 1, true, function() { }, {x: 1, y: '${y}'}], }); @@ -759,11 +758,11 @@ describe('executor', function() { }); it('should preserve object prototypes', function(done) { - var config = simpleMiddlewareConfig( + const config = simpleMiddlewareConfig( 'routes', // IMPORTANT we need more than one item to trigger the original issue [/^\/foobar/, /^\/another/], - {} + {}, ); boot.execute(app, config, function(err) { if (err) return done(err); @@ -783,7 +782,7 @@ describe('executor', function() { it('should parse a simple config variable', function(done) { boot.execute(app, simpleComponentConfig( - {path: '${restApiRoot}'} + {path: '${restApiRoot}'}, ), function(err) { if (err) return done(err); @@ -796,12 +795,12 @@ describe('executor', function() { }); it('should parse config from `env-var` and `config`', function(done) { - var bootInstructions = simpleComponentConfig( + const bootInstructions = simpleComponentConfig( { path: '${restApiRoot}', fromConfig: '${DYNAMIC_CONFIG}', fromEnvVar: '${DYNAMIC_ENVVAR}', - } + }, ); // result should get value from config.json @@ -821,8 +820,8 @@ describe('executor', function() { }); it('`env-var` should have precedence over `config`', function(done) { - var key = 'DYNAMIC_VARIABLE'; - var bootInstructions = simpleComponentConfig({ + const key = 'DYNAMIC_VARIABLE'; + const bootInstructions = simpleComponentConfig({ path: '${restApiRoot}', isDynamic: '${' + key + '}', }); @@ -841,7 +840,7 @@ describe('executor', function() { it('should parse multiple config variables', function(done) { boot.execute(app, simpleComponentConfig( - {path: '${restApiRoot}', env: '${env}'} + {path: '${restApiRoot}', env: '${env}'}, ), function(err) { if (err) return done(err); @@ -856,14 +855,14 @@ describe('executor', function() { it('should parse config variables in an array', function(done) { boot.execute(app, simpleComponentConfig( - {paths: ['${restApiRoot}']} + {paths: ['${restApiRoot}']}, ), function(err) { if (err) return done(err); supertest(app).get('/component').end(function(err, res) { if (err) return done(err); expect(res.body.paths).to.eql( - [app.get('restApiRoot')] + [app.get('restApiRoot')], ); done(); }); @@ -872,7 +871,7 @@ describe('executor', function() { it('should parse config variables in an object', function(done) { boot.execute(app, simpleComponentConfig( - {info: {path: '${restApiRoot}'}} + {info: {path: '${restApiRoot}'}}, ), function(err) { if (err) return done(err); @@ -888,7 +887,7 @@ describe('executor', function() { it('should parse config variables in a nested object', function(done) { boot.execute(app, simpleComponentConfig( - {nested: {info: {path: '${restApiRoot}'}}} + {nested: {info: {path: '${restApiRoot}'}}}, ), function(err) { if (err) return done(err); @@ -904,7 +903,7 @@ describe('executor', function() { }); it('calls function exported by boot/init.js', function(done) { - var file = appdir.writeFileSync('boot/init.js', + const file = appdir.writeFileSync('boot/init.js', 'module.exports = function(app) { app.fnCalled = true; };'); delete app.fnCalled; @@ -917,7 +916,7 @@ describe('executor', function() { }); it('configures middleware', function(done) { - var pushNamePath = require.resolve('./helpers/push-name-middleware'); + const pushNamePath = require.resolve('./helpers/push-name-middleware'); boot.execute(app, someInstructions({ middleware: { @@ -961,7 +960,7 @@ describe('executor', function() { .get('/') .end(function(err, res) { if (err) return done(err); - var names = (res.headers.names || '').split(','); + const names = (res.headers.names || '').split(','); expect(names).to.eql(['initial', 'custom', 'routes']); done(); }); @@ -989,7 +988,7 @@ describe('executor', function() { .get('/') .end(function(err, res) { if (err) return done(err); - var EXPECTED_TEXT = '\n\n\n' + + const EXPECTED_TEXT = '\n\n\n' + ' \n simple-app\n' + '\n\n

simple-app

\n' + '\n'; @@ -1031,7 +1030,7 @@ describe('executor', function() { if (err) return done(err); expect(Object.keys(require.cache)).to.include( - appdir.resolve('components/test-component/index.js') + appdir.resolve('components/test-component/index.js'), ); expect(app.componentOptions).to.eql({option: 'value'}); @@ -1052,7 +1051,7 @@ describe('executor', function() { if (err) return done(err); expect(Object.keys(require.cache)).to.not.include( - appdir.resolve('components/test-component/index.js') + appdir.resolve('components/test-component/index.js'), ); done(); }); @@ -1075,14 +1074,14 @@ describe('executor', function() { if (err) return done(err); expect(Object.keys(require.cache)).to.not.include( - appdir.resolve('components/test-component/index.js') + appdir.resolve('components/test-component/index.js'), ); done(); }); }); it('configures middleware (that requires `this`)', function(done) { - var passportPath = require.resolve('./fixtures/passport'); + const passportPath = require.resolve('./fixtures/passport'); boot.execute(app, someInstructions({ middleware: { @@ -1122,7 +1121,7 @@ describe('executor', function() { }); describe('when booting with lazy connect', function() { - var SAMPLE_INSTRUCTION = someInstructions({ + const SAMPLE_INSTRUCTION = someInstructions({ dataSources: { lazyConnector: { connector: 'testLazyConnect', @@ -1130,7 +1129,7 @@ describe('executor', function() { }, }, }); - var connectTriggered = true; + let connectTriggered = true; beforeEach(function() { app.connector('testLazyConnect', { @@ -1184,14 +1183,14 @@ describe('executor', function() { }); it('should convert dynamic variable for datasource', function(done) { - var datasource = { + const datasource = { mydb: { connector: 'memory', host: '${DYNAMIC_HOST}', port: '${DYNAMIC_PORT}', }, }; - var bootInstructions = {dataSources: datasource}; + const bootInstructions = {dataSources: datasource}; process.env.DYNAMIC_PORT = '10007'; process.env.DYNAMIC_HOST = '123.321.123.132'; @@ -1204,20 +1203,20 @@ describe('executor', function() { }); it('should resolve dynamic config via app.get()', function(done) { - var datasource = { + const datasource = { mydb: { connector: 'memory', host: '${DYNAMIC_HOST}', }, }; - var bootInstructions = { + const bootInstructions = { application: {DYNAMIC_HOST: '127.0.0.4'}, dataSources: datasource, }; boot.execute(app, someInstructions(bootInstructions), function() { expect(app.get('DYNAMIC_HOST')).to.equal('127.0.0.4'); expect(app.datasources.mydb.settings.host).to.equal( - '127.0.0.4' + '127.0.0.4', ); done(); }); @@ -1225,13 +1224,13 @@ describe('executor', function() { it('should take ENV precedence over config.json', function(done) { process.env.DYNAMIC_HOST = '127.0.0.2'; - var datasource = { + const datasource = { mydb: { connector: 'memory', host: '${DYNAMIC_HOST}', }, }; - var bootInstructions = { + const bootInstructions = { application: {DYNAMIC_HOST: '127.0.0.3'}, dataSources: datasource, }; @@ -1243,13 +1242,13 @@ describe('executor', function() { }); it('empty dynamic conf should resolve as `undefined`', function(done) { - var datasource = { + const datasource = { mydb: { connector: 'memory', host: '${DYNAMIC_HOST}', }, }; - var bootInstructions = {dataSources: datasource}; + const bootInstructions = {dataSources: datasource}; boot.execute(app, someInstructions(bootInstructions), function() { expect(app.get('DYNAMIC_HOST')).to.be.undefined(); @@ -1266,7 +1265,7 @@ function simpleMiddlewareConfig(phase, paths, params) { paths = undefined; } - var config = { + const config = { phase: phase, params: params, }; @@ -1315,7 +1314,7 @@ assert.isFunc = function(obj, name) { }; function someInstructions(values) { - var result = { + const result = { application: values.application || {}, models: values.models || [], dataSources: values.dataSources || {db: {connector: 'memory'}}, @@ -1328,7 +1327,7 @@ function someInstructions(values) { result.env = values.env; if (values.files) { - for (var k in values.files) + for (const k in values.files) result.files[k] = values.files[k]; } diff --git a/test/fixtures/browser-app-2/app.js b/test/fixtures/browser-app-2/app.js index 5b9141b..d333560 100644 --- a/test/fixtures/browser-app-2/app.js +++ b/test/fixtures/browser-app-2/app.js @@ -5,10 +5,10 @@ 'use strict'; -var loopback = require('loopback'); -var boot = require('../../../'); +const loopback = require('loopback'); +const boot = require('../../../'); -var app = module.exports = loopback(); +const app = module.exports = loopback(); boot(app, { appId: 'browserApp2', appRootDir: __dirname, diff --git a/test/fixtures/browser-app/app.js b/test/fixtures/browser-app/app.js index 6f853b1..478b6cf 100644 --- a/test/fixtures/browser-app/app.js +++ b/test/fixtures/browser-app/app.js @@ -5,8 +5,8 @@ 'use strict'; -var loopback = require('loopback'); -var boot = require('../../../'); +const loopback = require('loopback'); +const boot = require('../../../'); -var app = module.exports = loopback(); +const app = module.exports = loopback(); boot(app, __dirname); diff --git a/test/fixtures/passport.js b/test/fixtures/passport.js index d4ca24e..34adabb 100644 --- a/test/fixtures/passport.js +++ b/test/fixtures/passport.js @@ -5,7 +5,7 @@ 'use strict'; -var framework = { +const framework = { initialize: function(passport) { return function(req, res, next) { req._passport = passport; @@ -15,7 +15,7 @@ var framework = { }, }; -var Passport = function() { +const Passport = function() { this._framework = framework; }; diff --git a/test/fixtures/simple-app/boot/promise-callback.js b/test/fixtures/simple-app/boot/promise-callback.js index 1fb7e80..55ef4d2 100644 --- a/test/fixtures/simple-app/boot/promise-callback.js +++ b/test/fixtures/simple-app/boot/promise-callback.js @@ -5,7 +5,7 @@ 'use strict'; -var Promise = require('bluebird'); +const Promise = require('bluebird'); module.exports = function(app, callback) { callback(); diff --git a/test/fixtures/simple-app/boot/promise.js b/test/fixtures/simple-app/boot/promise.js index 38c3825..81258f1 100644 --- a/test/fixtures/simple-app/boot/promise.js +++ b/test/fixtures/simple-app/boot/promise.js @@ -5,7 +5,7 @@ 'use strict'; -var Promise = require('bluebird'); +const Promise = require('bluebird'); process.bootFlags.push('promiseLoaded'); module.exports = function(app) { diff --git a/test/fixtures/simple-app/boot/reject.js b/test/fixtures/simple-app/boot/reject.js index 7978cc4..35d37c9 100644 --- a/test/fixtures/simple-app/boot/reject.js +++ b/test/fixtures/simple-app/boot/reject.js @@ -5,7 +5,7 @@ 'use strict'; -var Promise = require('bluebird'); +const Promise = require('bluebird'); module.exports = function(app) { if (process.rejectPromise) { diff --git a/test/helpers/appdir.js b/test/helpers/appdir.js index aca3b3b..53e6350 100644 --- a/test/helpers/appdir.js +++ b/test/helpers/appdir.js @@ -5,14 +5,14 @@ 'use strict'; -var path = require('path'); -var fs = require('fs-extra'); -var extend = require('util')._extend; -var sandbox = require('./sandbox'); +const path = require('path'); +const fs = require('fs-extra'); +const extend = require('util')._extend; +const sandbox = require('./sandbox'); -var appdir = exports; +const appdir = exports; -var PATH = appdir.PATH = null; +let PATH = appdir.PATH = null; appdir.init = function(cb) { // Node's module loader has a very aggressive caching, therefore @@ -20,7 +20,7 @@ appdir.init = function(cb) { // The code here is used to generate a random string require('crypto').randomBytes(5, function(err, buf) { if (err) return cb(err); - var randomStr = buf.toString('hex'); + const randomStr = buf.toString('hex'); PATH = appdir.PATH = sandbox.resolve(randomStr); cb(null, appdir.PATH); }); @@ -49,7 +49,7 @@ appdir.writeConfigFileSync = function(name, json) { }; appdir.writeFileSync = function(name, content) { - var filePath = this.resolve(name); + const filePath = this.resolve(name); fs.mkdirsSync(path.dirname(filePath)); fs.writeFileSync(filePath, content, 'utf-8'); return filePath; diff --git a/test/helpers/browser.js b/test/helpers/browser.js index 8680bc5..f01546f 100644 --- a/test/helpers/browser.js +++ b/test/helpers/browser.js @@ -5,10 +5,10 @@ 'use strict'; -var vm = require('vm'); +const vm = require('vm'); function createContext() { - var context = { + const context = { // required by browserify XMLHttpRequest: function() {}, clearTimeout: function() {}, @@ -33,7 +33,7 @@ function createContext() { DataView: DataView, crypto: { getRandomValues: function(typedArray) { - var randomBuffer = require('crypto').randomBytes(typedArray.length); + const randomBuffer = require('crypto').randomBytes(typedArray.length); // This implementation is not secure: we take random 8bit values // and assign them to 8/16/32bit values, leaving high-order bits // filled with zeroes. @@ -73,9 +73,9 @@ function createContext() { exports.createContext = createContext; function printContextLogs(context) { - var k, ix; // see https://github.com/eslint/eslint/issues/5744 + let k, ix; // see https://github.com/eslint/eslint/issues/5744 for (k in context.console._logs) { - var items = context.console._logs[k]; + const items = context.console._logs[k]; for (ix in items) { console[k].apply(console, items[ix]); } diff --git a/test/helpers/browserify.js b/test/helpers/browserify.js index ea332fe..bb28b95 100644 --- a/test/helpers/browserify.js +++ b/test/helpers/browserify.js @@ -5,12 +5,12 @@ 'use strict'; -var fs = require('fs'); -var sandbox = require('./sandbox'); +const fs = require('fs'); +const sandbox = require('./sandbox'); function exportToSandbox(b, fileName, callback) { - var bundlePath = sandbox.resolve(fileName); - var out = fs.createWriteStream(bundlePath); + const bundlePath = sandbox.resolve(fileName); + const out = fs.createWriteStream(bundlePath); b.bundle().pipe(out); out.on('error', function(err) { diff --git a/test/helpers/sandbox.js b/test/helpers/sandbox.js index 7c07737..dd5afe7 100644 --- a/test/helpers/sandbox.js +++ b/test/helpers/sandbox.js @@ -5,10 +5,10 @@ 'use strict'; -var fs = require('fs-extra'); -var path = require('path'); +const fs = require('fs-extra'); +const path = require('path'); -var sandbox = exports; +const sandbox = exports; sandbox.PATH = path.join(__dirname, '..', 'sandbox'); sandbox.reset = function() { @@ -17,7 +17,7 @@ sandbox.reset = function() { }; sandbox.resolve = function() { - var args = Array.prototype.slice.apply(arguments); + const args = Array.prototype.slice.apply(arguments); args.unshift(sandbox.PATH); return path.resolve.apply(path.resolve, args); }; diff --git a/test/utils.test.js b/test/utils.test.js index 1a60dcf..ee69a2b 100644 --- a/test/utils.test.js +++ b/test/utils.test.js @@ -5,10 +5,10 @@ 'use strict'; -var utils = require('../lib/utils'); -var expect = require('chai').expect; -var sandbox = require('./helpers/sandbox'); -var appdir = require('./helpers/appdir'); +const utils = require('../lib/utils'); +const expect = require('chai').expect; +const sandbox = require('./helpers/sandbox'); +const appdir = require('./helpers/appdir'); describe('utils', function() { beforeEach(sandbox.reset); @@ -17,13 +17,13 @@ describe('utils', function() { }); describe('fileExistsSync', function() { it('returns false when a file does not exist', function() { - var doesNotExist = sandbox.resolve('does-not-exist.json'); + const doesNotExist = sandbox.resolve('does-not-exist.json'); expect(utils.fileExistsSync(doesNotExist)) .to.equal(false); }); it('returns true when a file does exist', function() { - var doesExist = appdir.writeConfigFileSync('does-exist.json', { + const doesExist = appdir.writeConfigFileSync('does-exist.json', { exists: true, }); expect(utils.fileExistsSync(doesExist))